diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..495a7175bb7b0b48bd0ac67d86f3e0c900127a71 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,36 @@ +*.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 -text +saved_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 -text +model.safetensors.index.json filter=lfs diff=lfs merge=lfs -text diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5c475cf292f954769b0eb124d8610245c461fbb3 --- /dev/null +++ b/LICENSE @@ -0,0 +1,52 @@ +Kimi 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 works +from it; and to permit persons to whom the Software is furnished to do so, in +each case subject to the following conditions: + +1. The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. Licensee's use of the +Software must comply with applicable laws and regulations. + +2. "Model as a Service" means giving a third party access to language model +inference or fine-tuning (e.g., via API) in a manner that allows such third +party to exercise meaningful control over the inputs, parameters, or training +data. This does not include (a) end-user products with model capabilities solely +embedded within specific features or harnesses, or (b) mere relaying of requests +to 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 million +US dollars (or the equivalent in other currencies) in total over any consecutive +12 months, the Licensee must enter into a separate agreement with Moonshot AI +before 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 the +Licensee's commercial products or services that have more than 100 million +monthly active users, or more than 20 million US dollars (or equivalent in other +currencies) in monthly revenue, "Kimi K3.1-Pro" must be prominently displayed on the +user interface of such product or service. + +4. The requirements set forth in Sections 2 and 3 do not apply to: (a) internal +use of the Software, defined as any use that does not make the Software, its +outputs, or its underlying capabilities available to third parties; or (b) any +use of the Software accessed through Moonshot AI's official products or +certified 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 NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +AND NONINFRINGEMENT. IN NO EVENT SHALL MOONSHOT AI OR ITS AFFILIATES OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +For any questions regarding this license, please contact . \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b3fafebfedc31e08b85fabb3fb4bc310e350dae8 --- /dev/null +++ b/README.md @@ -0,0 +1,705 @@ +--- +tags: +- compressed-tensors +- conversational +license: other +license_name: "kimi-k3.1-pro" +library_name: transformers +pipeline_tag: image-text-to-text +--- + +
+ + Kimi K3.1 Pro + +
+
+ Chat + Homepage +
+
+ Hugging Face + X + Discord + ModelScope +
+
+ License +
+ +

+πŸ“°  Tech Blog |     πŸš€  API Quickstart +

+ + + +## 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 + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArchitectureMixture-of-Experts (MoE)
Total Parameters2.8T
Activated Parameters104B
Number of Layers93
Number of Dense Layers1
Attention-Layer Composition69 KDA + 24 Gated DSA*
Attention Hidden Dimension7168
Number of Attention Heads96
DSA Index Head Dimension128
DSA Index Number of Heads32
DSA Index Top-K2048
Latent MoE Dimension3584
MoE Hidden Dimension (per Expert)3072
Number of Experts896
Selected Experts per Token16
Number of Shared Experts2
Vocabulary Size160K
Context Length1048576
Attention MechanismKDA & Gated DSA
Activation FunctionSiTU-GLU
Vision EncoderMoonViT-V2
Parameters of Vision Encoder401M
QuantizationMXFP4 weights / MXFP8 activations
(quantization-aware training)
ModalityText, Image
+
+ +

* 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.

+ +## 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. + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
BenchmarkKimi K3.1 Pro
(max)
Claude Fable 5.1
(max, w/ fallback)
GPT-6 Astra
(max, w/ fallback)
Claude Opus 5.5
(max, w/ fallback)
DeepSeek-V4.1-Flash-1017
(max)
GLM-5.3
(max)
Coding
Terminal-Bench 4.065.757.958.266.442.341.8
Terminal-Bench-Science 0.138.140.068.163.315.78.1
SWE Marathon v1.151.745.642.546.340.042.5
BenchCAD w/o tools72.860.6β€”73.041.2β€”
BenchCAD w/ tools92.792.695.996.281.6β€”
Program Bench31.553.550.065.029.119.0
DeepSWE v1.175.567.474.174.277.066.9
PostTrain Bench v1.236.544.641.943.830.534.5
Kimi Code Bench 2.0 (Internal)77.1β€”β€”β€”76.161.7
Kimi Code Bench 3.0 Long-horizon (Internal)61.258.866.558.551.545.5
Agentic
HLE-Full w/ tools70.065.657.267.758.862.5
BrowseComp92.1β€”91.590.8β€”β€”
BioMysteryBench80.681.678.981.980.079.6
CharXiv (RQ) w/ python93.492.792.893.885.6β€”
MMMU-Pro w/ python90.088.487.889.882.5β€”
GDP.pdf w/ python85.783.885.583.973.0β€”
ChartoGraphy w/ python90.288.491.089.083.0β€”
BabyVision w/ python95.495.196.697.792.5β€”
ZeroBench_main w/ python (pass@5)63.059.058.061.051.0β€”
Agents' Last Exam (ALL)43.2β€”41.842.637.726.2
Agents' Last Exam (CLI)44.2β€”44.240.736.029.4
Automation Bench-AA73.359.468.569.566.662.2
GDPval-AA v2.1 (Elo-score)184617541573186617461650
AA-Briefcase v1.1 (Elo-score)167816721569180315701507
APEX-Agents69.468.664.773.569.856.6
OfficeQA Pro v264.454.554.462.240.431.1
OfficeQA Pro67.468.666.2β€”62.458.6
Frontier Finance58.660.845.056.754.557.5
Harvey Legal Agent23.719.1β€”β€”21.0β€”
HANDBOOK.md44.638.8β€”41.528.920.8
OSWorld V2.179.680.775.881.869.3β€”
Business Operation (Internal)37.830.732.3β€”8.918.6
DECK-Arena (Internal, Elo-score)1456β€”1423125312311119
Design Bench (Internal, Elo-score)957β€”1076927863718
Kimi Hallu Bench Hard w/ tools (Internal, lower is better)8.323.35.515.023.322.6
Reasoning & Knowledge & Multimodal
GDP.pdf34.627.634.230.617.211.2
HLE-Full51.157.653.659.842.643.0*
HLE-Diamond39.455.165.860.921.625.1*
GPQA-Diamond94.293.796.193.992.291.7
CharXiv (RQ)89.088.890.092.177.0β€”
MMMU-Pro84.186.386.987.780.6β€”
ZeroBench_main (avg@5 / pass@5)29.8 / 39.023.0 / 35.043.2 / 52.035.0 / 43.011.8 / 23.0β€”
PerceptionBench68.363.077.672.147.7β€”
Kimi Hallu Bench w/o tools (Internal, lower is better)5.411.44.26.813.114.8
Cyber Security
ExploitBench74.783.010091.0β€”54.4
ExploitGym20.730.442.434.5β€”15.0
xdev-bench-hard (Internal)81.0β€”β€”β€”85.757.1
+
+ +
+Evaluation Footnotes + +#### 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. + +
+ +## 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 Usage +The thinking effort of Kimi K3.1 Pro is configured with the top-level `reasoning_effort` request field, which supports `"low"`, `"high"`, and `"max"` (default `"max"`). + +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`: + +```python +import 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). \ No newline at end of file diff --git a/assets/kimi-logo.png b/assets/kimi-logo.png new file mode 100644 index 0000000000000000000000000000000000000000..870b8be6e07cc2c46f7173e800fbaff8af0af5d1 Binary files /dev/null and b/assets/kimi-logo.png differ diff --git a/config.json b/config.json new file mode 100644 index 0000000000000000000000000000000000000000..f0fead8a6a9b5408e9df4479e67dcb2acd0a7bb8 --- /dev/null +++ b/config.json @@ -0,0 +1,330 @@ +{ + "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 + } +} \ No newline at end of file diff --git a/configuration_kimi_k3.py b/configuration_kimi_k3.py new file mode 100644 index 0000000000000000000000000000000000000000..03c69116f0a839286af100df529969b4a9dca90d --- /dev/null +++ b/configuration_kimi_k3.py @@ -0,0 +1,277 @@ +from 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) diff --git a/encoding_k3.py b/encoding_k3.py new file mode 100644 index 0000000000000000000000000000000000000000..e476b04e74f9305741aa16395371f98165e4ac44 --- /dev/null +++ b/encoding_k3.py @@ -0,0 +1,735 @@ +"""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/tool +text and attribute values are encoded as ordinary text. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from 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 ```` 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 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 segments diff --git a/generation_config.json b/generation_config.json new file mode 100644 index 0000000000000000000000000000000000000000..3908a4a5477122aa4b09386acab760fb7887c0fc --- /dev/null +++ b/generation_config.json @@ -0,0 +1,4 @@ +{ + "max_length": 1048576, + "eos_token_id": 163586 +} \ No newline at end of file diff --git a/kimi_k3_processor.py b/kimi_k3_processor.py new file mode 100644 index 0000000000000000000000000000000000000000..033a5773885c144509788e89a445217b76d6c046 --- /dev/null +++ b/kimi_k3_processor.py @@ -0,0 +1,187 @@ +"""Kimi-K3 processor: wraps vision processor + tokenizer into a single interface. + +Chat rendering (including XTML tool-result ordering) is handled by the +tokenizer's Python encoder; this processor adds multimodal media preprocessing. +""" + +from transformers.feature_extraction_utils import BatchFeature +from transformers.processing_utils import ProcessorMixin +from 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'] diff --git a/kimi_k3_vision_processing.py b/kimi_k3_vision_processing.py new file mode 100644 index 0000000000000000000000000000000000000000..58154424ff951289570c8fb5578e7372bfbfaa8b --- /dev/null +++ b/kimi_k3_vision_processing.py @@ -0,0 +1,179 @@ +"""Image processor class for Kimi-K3. +""" + +import json +from typing import Any, Dict, Optional, Union + +import numpy as np +import torch +from PIL import Image +from 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" diff --git a/media_utils.py b/media_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e8b2ae127e254e364e6b568b1093a7e12ac576e0 --- /dev/null +++ b/media_utils.py @@ -0,0 +1,376 @@ +import base64 +import functools +import io +import math +from dataclasses import dataclass +from typing import Literal, TypedDict + +import numpy as np +from PIL import Image + + +class ImageInput(TypedDict): + type: Literal['image'] + image: Image.Image + + +MediaInput = ImageInput + + +@dataclass +class 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)}") diff --git a/model-00001-of-000096.safetensors b/model-00001-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..915195d127790b770b422d378aacd7a169efc1c8 --- /dev/null +++ b/model-00001-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7f60e41909fb16712100c311ca4402cc4e66ecc9dff9dad4ebc06f05106c58a1 +size 2341216112 diff --git a/model-00002-of-000096.safetensors b/model-00002-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..caa0d8c8d58f4885fceffad1525d519654045cdc --- /dev/null +++ b/model-00002-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3896d0f0d987abeb75f90ff0c047b9fb7faf3ff39a6e31cbd49a1358f48b7ffa +size 16990911504 diff --git a/model-00003-of-000096.safetensors b/model-00003-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..5923adb6829cbb211981bc9f4bebbc9f697c9041 --- /dev/null +++ b/model-00003-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8db356979d0b5e4fdf16f13d56edee900261cc59d81395e498a52847518abf4c +size 16990911504 diff --git a/model-00004-of-000096.safetensors b/model-00004-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..a41d13831d06bcd178f2a7f1d9722ef9617bea24 --- /dev/null +++ b/model-00004-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01ca3a36220afc36a9f2891045c8c9d0e64fc2cd08fffe1b3851e24bd2a93a40 +size 16582379656 diff --git a/model-00005-of-000096.safetensors b/model-00005-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..c60b14427e24bc2fd55039958f5e40af20339a9c --- /dev/null +++ b/model-00005-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:596fc235fe92c9656cbbd63eb719cd46f68b19e22d792224ef307c156f699682 +size 16990911504 diff --git a/model-00006-of-000096.safetensors b/model-00006-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..dc351ad3768d64ea5469a18c09aef85ce96c2ad9 --- /dev/null +++ b/model-00006-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a9f6a9d6682b2f5177553b9986bdc0774fe84a2181b76a6b7d7482de0ecf049b +size 16990911504 diff --git a/model-00007-of-000096.safetensors b/model-00007-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..2c5ce848549d840763a2496b6d7054beec612b91 --- /dev/null +++ b/model-00007-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea268a3cb5978f50079ffd111d78d785bdd313fb9c7dafda8df0d841daeba4ab +size 16990911504 diff --git a/model-00008-of-000096.safetensors b/model-00008-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..9443003eb1f601c00fd7dfc421b52fd85048b21f --- /dev/null +++ b/model-00008-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e514e45c4a17a187657fbcd1d4f9eb6a0c33bcdbbe54049da391ed54ce57f60f +size 16582379656 diff --git a/model-00009-of-000096.safetensors b/model-00009-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..1184a9828cec3602a3ede39983324ba7c4f03c03 --- /dev/null +++ b/model-00009-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c5f9adff3d853bcf1e14c27bca0f1a74de985e7afb3149acd00eb2de3732ca12 +size 16990911504 diff --git a/model-00010-of-000096.safetensors b/model-00010-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..115714b3ac00457c1ea49a7b66ef0f50dfa3586b --- /dev/null +++ b/model-00010-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee9b1762da09dad17d6f8a22732645b070149266c40c3ae1e8ee90f48fec6742 +size 16990911504 diff --git a/model-00011-of-000096.safetensors b/model-00011-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..070ecd98ebd8909658becb909eca90e074c6c770 --- /dev/null +++ b/model-00011-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0bb52ff6b774c289888854203726e0cd955fc650dda2f5cf9e4f825037f4af72 +size 16990916912 diff --git a/model-00012-of-000096.safetensors b/model-00012-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..cfe4508ee88689cb10b81b87b9e636919b9085c5 --- /dev/null +++ b/model-00012-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c2c9be2d6b722d75bec065e545826a88a8839b8100766442e7f476143e7ba44 +size 16582385056 diff --git a/model-00013-of-000096.safetensors b/model-00013-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..8d38532f7b4c026408c3e0897cd5a8102da6efeb --- /dev/null +++ b/model-00013-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bbf5db5833f4607cd201156229aa7f05183f70f2ffd2cf0ca8a6d781ee7f139c +size 16990916912 diff --git a/model-00014-of-000096.safetensors b/model-00014-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..30178ca8d49cf142c5b01c28de50c1ac50775dd0 --- /dev/null +++ b/model-00014-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f412b94c799903bc4b3694e662e6ef342bcc3712a3108a63b157bef16ec59df +size 16990916912 diff --git a/model-00015-of-000096.safetensors b/model-00015-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..c92dde5fbfb37d079a90230c9d6d9219771310fe --- /dev/null +++ b/model-00015-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:28e678ecfc2286eb86aa6dfe20df03bd7c8873b34d96f0b230d1aab64365a889 +size 16990916912 diff --git a/model-00016-of-000096.safetensors b/model-00016-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..1bb42c54a307e652c1e0780379ef1e0f65ae3d4a --- /dev/null +++ b/model-00016-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:896fd658f4cddad15eaca16ed54471ad265ad73d48d291bb4bb792767dc4d617 +size 16582385056 diff --git a/model-00017-of-000096.safetensors b/model-00017-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..4a64c300f9188ae18c508d92a45ee04d0f39e402 --- /dev/null +++ b/model-00017-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4b82b33835679910ad9f87ec4662e38f8dc111421fb2a56f538cec5be6c55b74 +size 16990916912 diff --git a/model-00018-of-000096.safetensors b/model-00018-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..085264e1b06aae235e67623f5102f928f73be736 --- /dev/null +++ b/model-00018-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db91d8251d9bc0f47e31fc18955e8428a6a1fa25460a5e54578e4b261660e3ef +size 16990916912 diff --git a/model-00019-of-000096.safetensors b/model-00019-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..86b85b296e3ffde3537e487d9b0cd1777606cf0a --- /dev/null +++ b/model-00019-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:281ef055e54eff0c8ffacdf886e983ff27de43d002abf9aa97b663e9a3ae9ee7 +size 16990916912 diff --git a/model-00020-of-000096.safetensors b/model-00020-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..042e36606bf80943365de095ec2d7378dc34fb91 --- /dev/null +++ b/model-00020-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:783cbb7d6056c0ad3f32b8f1c10c20e6b2d7e5356e0cfd6ce6123f43d3648e60 +size 16582385056 diff --git a/model-00021-of-000096.safetensors b/model-00021-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..d766e547f49fa209dce1d22ff00f424329d2952a --- /dev/null +++ b/model-00021-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9774e732cae20192427c8777f79bd9a9fb7c9ef3bc71c2784a2f72e891e1b51e +size 16990916912 diff --git a/model-00022-of-000096.safetensors b/model-00022-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..3b7bc10aeb41c46fbb50fc9485f0978d39729697 --- /dev/null +++ b/model-00022-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e3f0905780d988b0fcb974479731e751f8bed319e22224f5f9d0ec76b1b755e +size 16990916912 diff --git a/model-00023-of-000096.safetensors b/model-00023-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..ddbad2bbc43a2b3cd0584d75087da6c389e95e30 --- /dev/null +++ b/model-00023-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69940e5bde762834f2731401194a8fb2c2784274890bd6d23e0c0aca91383451 +size 16990916912 diff --git a/model-00024-of-000096.safetensors b/model-00024-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..16b53ad8349b30543a3a26653538d290495e725c --- /dev/null +++ b/model-00024-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f48efe6ad27d75b51564a3de48ab312ee7c06969db35d7b2b764d9515c00b0a7 +size 16582385056 diff --git a/model-00025-of-000096.safetensors b/model-00025-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..9311d479c792aea2706e8c989cdf04878fa95f61 --- /dev/null +++ b/model-00025-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:833a0f761b2944cde386def5bdb7dabbfdf30f2927dd26304d0f7723b4ff018c +size 16990916912 diff --git a/model-00026-of-000096.safetensors b/model-00026-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..78a74dafba3936aa6eb975507f88bbdb3d74f1b9 --- /dev/null +++ b/model-00026-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:02bff688e36ec90942dcb3ece1bfc7f102fd3c78bffdabba79fd4ec4bedb9230 +size 16990916912 diff --git a/model-00027-of-000096.safetensors b/model-00027-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..36d5494da4144c9ed69fa381dad3415972755630 --- /dev/null +++ b/model-00027-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4fe3e6f06b9c341d06eee45c0add2c7f8aff48a4c48bdcd97130c48c91b93202 +size 16990916912 diff --git a/model-00028-of-000096.safetensors b/model-00028-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..0b121db6f8353eb22b63996de8bb0da0c542b7d8 --- /dev/null +++ b/model-00028-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:832b28d66ea0c9bca4b42c8b206463b3f8fa8cafd13d4118911604351c27dc22 +size 16582385056 diff --git a/model-00029-of-000096.safetensors b/model-00029-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..e99a3394f229e3b5f99a53a30d554ddf5182838b --- /dev/null +++ b/model-00029-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bf8f4f4f10a3cbf72d95851232c17d20c58d44f024a8c4e421b344cb0f871659 +size 16990916912 diff --git a/model-00030-of-000096.safetensors b/model-00030-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..4a0ecad424cd669f89cd38e5670850c86f604316 --- /dev/null +++ b/model-00030-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a974612d9f6300e9a86eb882e2c6dbad2446d491e15289b576acd015f1f69928 +size 16990916912 diff --git a/model-00031-of-000096.safetensors b/model-00031-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..a1f2bbeac6d11e85052e359e4a23252ee8c45ea0 --- /dev/null +++ b/model-00031-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa227f8eddaf25975915e8a161446fb042e1db7bb176aafd29d4953f01a4e2dd +size 16990916912 diff --git a/model-00032-of-000096.safetensors b/model-00032-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..6805b7592bcbb3cd4c96700305171d796b0ab0d0 --- /dev/null +++ b/model-00032-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4520a3321b8fd7e3f7da7c29afc084802af2f1498f8c96e5103fe4476b204957 +size 16582385056 diff --git a/model-00033-of-000096.safetensors b/model-00033-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..7fcd4b2b93051b993f7e3c42896cf71040f0e23d --- /dev/null +++ b/model-00033-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:32a8f004afb58539f28fe5333fef3e1604c60f2113bbe2e173c99502a0f0cd89 +size 16990916912 diff --git a/model-00034-of-000096.safetensors b/model-00034-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..bc129bad74be639939d9c870031d5cf1d027ceb9 --- /dev/null +++ b/model-00034-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4310c7808e7bf72506168fc1e521852ee95da94c6ee2f6ee6b8fa6b800c559c8 +size 16990916912 diff --git a/model-00035-of-000096.safetensors b/model-00035-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..0f1bf76673d52da95a941ad1f3c92accb5718228 --- /dev/null +++ b/model-00035-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ba50bc47a6b48c057208b7e2ea5aaccb6e8ce27041402e469cbb18661858ce2 +size 16990916912 diff --git a/model-00036-of-000096.safetensors b/model-00036-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..29809a6aa3e9d8cccd825931d67ed87aab7f4304 --- /dev/null +++ b/model-00036-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5a64e3f0e0988dda1e568fcbf37d4f0a03493e536daff572a8d8378442ef26ec +size 16582385056 diff --git a/model-00037-of-000096.safetensors b/model-00037-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..54ae643e07c436b92e12ab48abc242a5aa92168d --- /dev/null +++ b/model-00037-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43ab18d28759e45ba316e03423b2c0d447ebc7f8ffea7972c4634a7630349262 +size 16990916912 diff --git a/model-00038-of-000096.safetensors b/model-00038-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..2f7d2974f295133fe852453fe8c940acba59c7ef --- /dev/null +++ b/model-00038-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a518377eff993b5b0b0337296072bb32a3ed249776b0c1459aaef20f9749fcf1 +size 16990916912 diff --git a/model-00039-of-000096.safetensors b/model-00039-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..14d87edc2c5da1e32f9d603413d1d3adb35dbab2 --- /dev/null +++ b/model-00039-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0c693043cdf7910af15e649039a7bfd8e924b923f7224cc1222e0d56edd36358 +size 16990916912 diff --git a/model-00040-of-000096.safetensors b/model-00040-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..cb8280c441b7c8a8333b3e3456231f7192340be2 --- /dev/null +++ b/model-00040-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c5e62f355ede896136b7c425fc1c81e6ac0047ed61c50f121f360ed9959e74bb +size 16582385056 diff --git a/model-00041-of-000096.safetensors b/model-00041-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..c53616c758a78d6f55cba1c9b2263190a930dd4c --- /dev/null +++ b/model-00041-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5467de4bf7800406a595c87836ffedf5035f1246ec7ec09baeea481135221e6e +size 16990916912 diff --git a/model-00042-of-000096.safetensors b/model-00042-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..cdb22828214d903f0f4561c681144efdb70a192c --- /dev/null +++ b/model-00042-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f96acc33583215194c99f25af1bcbeef8256b5ad99eb825c049030812917a5a7 +size 16990916912 diff --git a/model-00043-of-000096.safetensors b/model-00043-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..7e4ac14652488fe973b76ba88baceaaf2fe12a52 --- /dev/null +++ b/model-00043-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c6b75c7c909f2cf34ebb1c094052ebc771575b79a2a6f2c3e1cf064c387603d5 +size 16990916912 diff --git a/model-00044-of-000096.safetensors b/model-00044-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..6d4f5d9753e36b0ed5e9b920ff7e72835ce681a6 --- /dev/null +++ b/model-00044-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f403f8bcca8b30839407515134c16b0e6d0605ad5a1b45cb586206f36271c14c +size 16582385056 diff --git a/model-00045-of-000096.safetensors b/model-00045-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..9d5c6b5f81021f1b9867fd8c671096650be7f107 --- /dev/null +++ b/model-00045-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f9be878defe6cd66660d7299a98aece70f224b17444dd513475a9d438d4db452 +size 16990916912 diff --git a/model-00046-of-000096.safetensors b/model-00046-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..12fad3a260d5ea8338de8f579ca0d0684a195fec --- /dev/null +++ b/model-00046-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a242c8b90256e28453138e1693f5f8aca76303ca2416a7370d3314ffbb010069 +size 16990916912 diff --git a/model-00047-of-000096.safetensors b/model-00047-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..d534feafd028e087ab39c81693f9dd29456a0abc --- /dev/null +++ b/model-00047-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6efb69aea07a4d81f4c7173051b0dfe65f6b936e905787663d4234329594b54c +size 16990916912 diff --git a/model-00048-of-000096.safetensors b/model-00048-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..b9301091db028eda67269cb9a93e69a511d4b03e --- /dev/null +++ b/model-00048-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a70396c45aa464926b8cc99a415fee1c5fb07b0df070541e9d9eca994a4922ea +size 16582385056 diff --git a/model-00049-of-000096.safetensors b/model-00049-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..32b8059b1ea0e93e5b1870af9a56b1d7c3efdbd7 --- /dev/null +++ b/model-00049-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0fff54860869ed29793a7c7398e914f70babdddf5c9994c1b57012245169d896 +size 16990916912 diff --git a/model-00050-of-000096.safetensors b/model-00050-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..f6d17de1952d2346d5bee4e0df21745baa646b43 --- /dev/null +++ b/model-00050-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:19181ab15f63e6debe603b5bb7b40cc7cbe7367ccfc0adecc13cdb9837b3784f +size 16990916912 diff --git a/model-00051-of-000096.safetensors b/model-00051-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..e1d66dc6d6faed241f1659b69d9c1607c0dcbcad --- /dev/null +++ b/model-00051-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e2ec567c0ae313944b0cd4058f8139630600138013cc109c61c9739b856ed7e3 +size 16990916912 diff --git a/model-00052-of-000096.safetensors b/model-00052-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..3380f786ca5c3ab46bfb58a1fd127be743d112d3 --- /dev/null +++ b/model-00052-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82fc278ee0ecb69f0a5954121f1446509d403f4c172e6346c4e16449893fb001 +size 16582385056 diff --git a/model-00053-of-000096.safetensors b/model-00053-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..f71a3c1c7f4820aa0f8053f21013243bc4aea369 --- /dev/null +++ b/model-00053-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c0d0e9c42b7533504908ee4d5d2f3cd7bfa4b692872413ebca1196376fd49cb +size 16990916912 diff --git a/model-00054-of-000096.safetensors b/model-00054-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..d20b48d834c8e00e308915ef0a41e2d2fd464df9 --- /dev/null +++ b/model-00054-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:19891780a0207b6697ea10a093a36ccc488b1ed409975c69c9a0f06c155d2841 +size 16990916912 diff --git a/model-00055-of-000096.safetensors b/model-00055-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..504adb88b60b680d1c82ec4426da80aac96e4bc6 --- /dev/null +++ b/model-00055-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6bf65a7ee82eb936ccda65e3ba5615b02ad821ad49123195443a8fab99cc395a +size 16990916912 diff --git a/model-00056-of-000096.safetensors b/model-00056-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..1b0d3ef65c746da5336c42859176e19c50f26c14 --- /dev/null +++ b/model-00056-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64b4d82603dc6d65dc3cbed3189edf0b78e3470092dde3f600c3f23694c4a775 +size 16582385056 diff --git a/model-00057-of-000096.safetensors b/model-00057-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..625f11c281d889631071f3eff4f48c986912c55b --- /dev/null +++ b/model-00057-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9e41e4f36fa0008bca9b73f1d3b6411347a3dd69cc4e0a51f7f808f132dfc8bb +size 16990916912 diff --git a/model-00058-of-000096.safetensors b/model-00058-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..5150961b026abcf54e8b7b1fb4f383320dfcdfe0 --- /dev/null +++ b/model-00058-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e202865cdb609ab0c5ab61d49daaca7c3f5c70f278bbf9fb589d878fa6e5ffca +size 16990916912 diff --git a/model-00059-of-000096.safetensors b/model-00059-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..d66401859aeceffb68f5c328400ca1abeed72f36 --- /dev/null +++ b/model-00059-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:66d4329257b993f12bb42d16239c147821d21c02a9e0025811310c05bc78ee69 +size 16990916912 diff --git a/model-00060-of-000096.safetensors b/model-00060-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..e7167e94dffaa990262931c5e9ccf8c18bc40626 --- /dev/null +++ b/model-00060-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:72705dacad50ab2cd28298bf4272087f5c828d32a1ce6d87989fdb98dfb2cdbd +size 16582385056 diff --git a/model-00061-of-000096.safetensors b/model-00061-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..f51092297600011fa72f546eac54824f170905be --- /dev/null +++ b/model-00061-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a3f6edaeed6f49019b2942c5caec31700f663e25d1de024b15e65849caa68242 +size 16990916912 diff --git a/model-00062-of-000096.safetensors b/model-00062-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..ef0c7068cb89e76699c188b43043b7c671c02163 --- /dev/null +++ b/model-00062-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5eae04b19e582871edcba0a8cb9f2a50a443e1e85132c009b7c61f1d3d6f464c +size 16990916912 diff --git a/model-00063-of-000096.safetensors b/model-00063-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..dfb6f16d35b5b6bce45a25e47a38125d3dcf7bc1 --- /dev/null +++ b/model-00063-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c51d0b570a95c0e4287f80d0d6592e887c24fc3b6f3382e8071176e5322d735 +size 16990916912 diff --git a/model-00064-of-000096.safetensors b/model-00064-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..b2727bf07e72b280dd72f60def289ab5d65a43aa --- /dev/null +++ b/model-00064-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:63df5a5ae8e5b3317b8e7d0c52775409728713873b8007ae2b11587e44a23528 +size 16582385056 diff --git a/model-00065-of-000096.safetensors b/model-00065-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..97ea6efa8413f67f9eb4eaedf13d1de89d4700d1 --- /dev/null +++ b/model-00065-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d29eb4cca4358b93880b397c8a1494134132c28cb6c3a827faa35e58cc7e08c +size 16990916912 diff --git a/model-00066-of-000096.safetensors b/model-00066-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..ff7042c2850599b2644f44d0dd7aad1700e35fd3 --- /dev/null +++ b/model-00066-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:629020d4d37304b6fdd5a136fc4c5115bc456fa41f1b78e6c6d90cce0eb23fe9 +size 16990916912 diff --git a/model-00067-of-000096.safetensors b/model-00067-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..ba6e547cd74a39e6ef6f0d908b2719fe5941fc6d --- /dev/null +++ b/model-00067-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ae2677403c72c3f652f3d19e14c11bb30bb746fbb41a366f60bceb609e73f25e +size 16990916912 diff --git a/model-00068-of-000096.safetensors b/model-00068-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..8d3e10635e648c7a3f770bccf377a0446a32a933 --- /dev/null +++ b/model-00068-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9ec02c5185a53562df29cf834664969e18f87dd7967b627f95b44580d3e489a1 +size 16582385056 diff --git a/model-00069-of-000096.safetensors b/model-00069-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..ccf4c39c94d5589ab09af95bc6baf45d86f126ff --- /dev/null +++ b/model-00069-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7cdce5d9fc6dfd773eb1c29194a3c4c1948361a225a9c2f35f35d1bb9504ff8b +size 16990916912 diff --git a/model-00070-of-000096.safetensors b/model-00070-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..21ad4c1035059768d9f72b95b711456c68fc0e2e --- /dev/null +++ b/model-00070-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7dd0afce2993bdfaeebe951b416e2994e413da054e7706850a800eef3d61aedf +size 16990916912 diff --git a/model-00071-of-000096.safetensors b/model-00071-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..f5d91c5bc448b479b700ea4aa4ecc2fe2685d2bf --- /dev/null +++ b/model-00071-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a6f30324f53f3644233dd6a43f3e96b9facdab22c84af0a5ebf76c6a4e62adc +size 16990916912 diff --git a/model-00072-of-000096.safetensors b/model-00072-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..5131d1019f2b2d84ed5ef8b52f78b27f8d71ff8d --- /dev/null +++ b/model-00072-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0289cad8c61fb91965a29292b1391de5c663a262e59a5716d1e207af57c26fe4 +size 16582385056 diff --git a/model-00073-of-000096.safetensors b/model-00073-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..acc702479988bc4fd0951c53c02bb9679a9f4bdc --- /dev/null +++ b/model-00073-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:562795ffd08c35c9a7e1e1da1457b933f5e52a9934cc0238a3ce47a5df81a0a1 +size 16990916912 diff --git a/model-00074-of-000096.safetensors b/model-00074-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..399255a915893f5a8c40c277983ef796175143e7 --- /dev/null +++ b/model-00074-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:da51f95cad8edd2321b799ff4f0e888211ea86eb32b4c8ef12a8501af3223687 +size 16990916912 diff --git a/model-00075-of-000096.safetensors b/model-00075-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..59a529b8875e249dc8b363d161d102ca7085f5d4 --- /dev/null +++ b/model-00075-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5cb481011c961484cdff4b0847ea4969ee6692f714d83c0ec8fb1e8eff64069b +size 16990916912 diff --git a/model-00076-of-000096.safetensors b/model-00076-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..591cf7b19879027f63f90fe28034fbb630cb1716 --- /dev/null +++ b/model-00076-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c3c1fa5945498c4e7a6c95ccc88a0e40286d020faae8d9dfe1f8aebf14bdcc7 +size 16582385056 diff --git a/model-00077-of-000096.safetensors b/model-00077-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..cb836035d27b9a10270cb5d4157c80a5e4bb5142 --- /dev/null +++ b/model-00077-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:31c1560d0dbd53f551e54895789bac84203990ce5d6e390385b85c63debd159a +size 16990916912 diff --git a/model-00078-of-000096.safetensors b/model-00078-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..493d896abd1d46e9ab1c4d545cbfbe47b4243102 --- /dev/null +++ b/model-00078-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:30d527befe028d04c27c437818fb234977a9fac39475b710291bb0cb35e0fb58 +size 16990916912 diff --git a/model-00079-of-000096.safetensors b/model-00079-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..0f40a8a954a8cac9d8f8eaf7f1c4d0fcc0fec0aa --- /dev/null +++ b/model-00079-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7362738c78d986de925b876e4d3090168102a58c287e50f917e427609d9b910f +size 16990916912 diff --git a/model-00080-of-000096.safetensors b/model-00080-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..1790a4f5b6a6bfb99bcdc5370b3f3bfd4983a661 --- /dev/null +++ b/model-00080-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e72acc23724a2d1a053cda24c20e31c583a5ae5ae895d5ff615097184abf417 +size 16582385056 diff --git a/model-00081-of-000096.safetensors b/model-00081-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..022e8fa3c31f78742ba502625aac83353dd5439b --- /dev/null +++ b/model-00081-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7e6db01ab5c5df86d40ab57c5283d744b8223b1ba4d936d7743addd072cae23d +size 16990916912 diff --git a/model-00082-of-000096.safetensors b/model-00082-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..e237fd93b591fc1d6ab01200d5cec9579894e476 --- /dev/null +++ b/model-00082-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cd92e1e29b094b9e763813d7afc34bafe1246619098c23823b6dff448f239211 +size 16990916912 diff --git a/model-00083-of-000096.safetensors b/model-00083-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..24001fbdf5176e71fba22be8ed090de8578ea60d --- /dev/null +++ b/model-00083-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:837cd4a41384987924a17b7afe3033cb38073f14ed9e22cc90d17e2be5950fb3 +size 16990916912 diff --git a/model-00084-of-000096.safetensors b/model-00084-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..cc5c81b929cd297af2a61acf25ffa09c6540db90 --- /dev/null +++ b/model-00084-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b023f4665c819bc1af02222a5fcd1a825d096e25c26d34f47a20a33e9299e205 +size 16582385056 diff --git a/model-00085-of-000096.safetensors b/model-00085-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..a576ff354b9c6a3c0ebd18273433dd3753d938b6 --- /dev/null +++ b/model-00085-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1ddd479ac40f7e78a2c118d9c456c8e3f22e716f483b294ae45071f6a19f0a74 +size 16990916912 diff --git a/model-00086-of-000096.safetensors b/model-00086-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..0ff923a00a1eef1c02513314e4288d8effec7f5c --- /dev/null +++ b/model-00086-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e39c007056d09ffbd7040df96981831254bac17f7120a7bb28ce1e5cb0350b7b +size 16990916912 diff --git a/model-00087-of-000096.safetensors b/model-00087-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..6ac531d79b0d74d85c1060511d07ed9c4efcf733 --- /dev/null +++ b/model-00087-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64b8ea577c64d7686f054b7286901df6874c5eb73d2157980c3f50b0408a86fc +size 16990916912 diff --git a/model-00088-of-000096.safetensors b/model-00088-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..c094dc6735be79789b31e00d820700f1718e6db8 --- /dev/null +++ b/model-00088-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c460a0083000f4239934d744a8c8cfb7ba77c2fc557fa73ae711ec72a0be7293 +size 16582385056 diff --git a/model-00089-of-000096.safetensors b/model-00089-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..7e5233eeebea135b58fbf11f98585ac194ea33a4 --- /dev/null +++ b/model-00089-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e8978e7faf4137773f58ccd25b4f8f8f72e316984f9a297bb34a25d6a413bd0b +size 16990916912 diff --git a/model-00090-of-000096.safetensors b/model-00090-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..0cc33003d77562c4abb814df14af7db56640a1dd --- /dev/null +++ b/model-00090-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cec0b73dcd7921ad1a1274757df6da0cca06f62307533ab1189992475925ca87 +size 16990916912 diff --git a/model-00091-of-000096.safetensors b/model-00091-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..ea775ccb3e4693f8076a6bcfb38824046a8ef74e --- /dev/null +++ b/model-00091-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ac71f812fcf256077f457f12b1f92aabdc8dfd1e6be46fa42ffb6140d79cf019 +size 16990916912 diff --git a/model-00092-of-000096.safetensors b/model-00092-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..e37c2635bfc32b559ac8d2249a001017089b12fd --- /dev/null +++ b/model-00092-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c526679aff4000da35704ebdc5e5356e8035520bf0b4ef7a5f0b543aed9a2481 +size 16582385056 diff --git a/model-00093-of-000096.safetensors b/model-00093-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..dedd5522452eacf2ce60c6bcc4400821c450211a --- /dev/null +++ b/model-00093-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:84e7d061fe22d29110c72d8f892681d4dbcc8a4fa4295844c98543f5707233a6 +size 16582385056 diff --git a/model-00094-of-000096.safetensors b/model-00094-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..a67302cad5858f6c341271e06f8c4f91336344e9 --- /dev/null +++ b/model-00094-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f60884ddcd7dc3d2c95640cf14626ae17702fa489d2612849433d7290c4358ff +size 4697664072 diff --git a/model-00095-of-000096.safetensors b/model-00095-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..b94638ece80201bd6df7fc116a1093867ba3ecfb --- /dev/null +++ b/model-00095-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db95f23534af1cb3b09d321d632b87f2103865fda2e96734c83379d80c114cfe +size 92289328 diff --git a/model-00096-of-000096.safetensors b/model-00096-of-000096.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..1efdad31fc1a0dac902585d53b0254be0356a32d --- /dev/null +++ b/model-00096-of-000096.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1912e9c59d01fe3962cab478be9c7546482b35ce2c19bea63dc990ee0fdcd4c2 +size 802448352 diff --git a/model.safetensors.index.json b/model.safetensors.index.json new file mode 100644 index 0000000000000000000000000000000000000000..b37dae58fa94b20d484867b00e5035d8693bad1e --- /dev/null +++ b/model.safetensors.index.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6500b553254ae3955e19bbf93d8cf3eee17101df4430493b33ce44d8ea1e2925 +size 59776878 diff --git a/preprocessor_config.json b/preprocessor_config.json new file mode 100644 index 0000000000000000000000000000000000000000..8be28c13c93fb8982f81928d3f4fe80568102286 --- /dev/null +++ b/preprocessor_config.json @@ -0,0 +1,38 @@ +{ + "media_proc_cfg": { + "in_patch_limit": 65536, + "patch_size": 14, + "image_mean": [ + 0.5, + 0.5, + 0.5 + ], + "image_std": [ + 0.5, + 0.5, + 0.5 + ], + "merge_kernel_size": 2, + "fixed_output_tokens": null, + "patch_limit_on_one_side": 512, + "in_patch_limit_each_frame": 16384, + "in_patch_limit_video": 655360, + "sample_fps": 8.0, + "max_num_frames_each_video": null, + "temporal_merge_kernel_size": 4, + "timestamp_mode": "hh:mm:ss.fff", + "transparent_bg_config": { + "pattern": "chessboard", + "chessboard_square_size": 8, + "chessboard_square_on_top_left": true, + "chessboard_white_value": 255, + "chessboard_gray_value": 180 + }, + "transparent_bg_fill_stage": "after_resize", + "config_type": "media_proc.processors.moonvit.MoonViTMediaProcessorConfig" + }, + "auto_map": { + "AutoProcessor": "kimi_k3_processor.KimiK3Processor", + "AutoImageProcessor": "kimi_k3_vision_processing.KimiK3VisionProcessor" + } +} \ No newline at end of file diff --git a/tiktoken.model b/tiktoken.model new file mode 100644 index 0000000000000000000000000000000000000000..b4149a6e17a01b6442187f39890f89bc2fe8d309 --- /dev/null +++ b/tiktoken.model @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b6c497a7469b33ced9c38afb1ad6e47f03f5e5dc05f15930799210ec050c5103 +size 2795286 diff --git a/tokenization_kimi.py b/tokenization_kimi.py new file mode 100644 index 0000000000000000000000000000000000000000..7ae891c2e0ef050bbeb2da55e9bc0401c4c508db --- /dev/null +++ b/tokenization_kimi.py @@ -0,0 +1,412 @@ +import os +from logging import getLogger +from pathlib import Path +from shutil import copyfile +from typing import Dict, Iterator, List, Optional, Tuple, Union, cast + +import tiktoken +from tiktoken.load import load_tiktoken_bpe +from tokenizers import AddedToken +from transformers.convert_slow_tokenizer import bytes_to_unicode +from transformers.tokenization_utils import PreTrainedTokenizer + +try: + from .encoding_k3 import build_chat_segments, is_batched_conversation +except ImportError: # pragma: no cover - supports direct file execution/import. + from encoding_k3 import build_chat_segments, is_batched_conversation + +logger = getLogger(__name__) +VOCAB_FILES_NAMES = {"vocab_file": "tiktoken.model"} + + +class TikTokenTokenizer(PreTrainedTokenizer): + """ + Tokenizing and encoding/decoding text using the Tiktoken tokenizer. See megatron/tokenizer/tiktoken_tokenizer.py. + + This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to + this superclass for more information regarding those methods. + + Args: + vocab_file (`str`): + The path to the Tiktoken model file. + bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<|begin_of_text|>",`): + The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token. + eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<|end_of_text|>"`): + The end of sequence token. + unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<|reserved_special_token_249|>"`): + The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this + token instead. The second to last item in special_tokens. + pad_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<|reserved_special_token_250|>"`): + The token used for padding, for example when batching sequences of different lengths. + additional_special_tokens (list of `str`, *optional*): + A tuple or a list of additional tokens, which will be marked as `special`, meaning that they will be + skipped when decoding if `skip_special_tokens` is set to `True`. + """ + + vocab_files_names = VOCAB_FILES_NAMES + + model_input_names = ["input_ids", "attention_mask"] + + special_tokens: Dict[str, int] + + num_reserved_special_tokens = 256 + + pat_str = "|".join([ + r"""[\p{Han}]+""", + r"""[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]*[\p{Ll}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?""", + r"""[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]+[\p{Ll}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?""", + r"""\p{N}{1,3}""", + r""" ?[^\s\p{L}\p{N}]+[\r\n]*""", + r"""\s*[\r\n]+""", + r"""\s+(?!\S)""", + r"""\s+""", + ]) + + def __init__( + self, + vocab_file, + bos_token: Union[str, AddedToken] = "[BOS]", + eos_token: Union[str, AddedToken] = "[EOS]", + unk_token: Union[str, AddedToken, None] = None, + pad_token: Union[str, AddedToken, None] = None, + additional_special_tokens: List[str] = None, + added_tokens_decoder: Optional[dict] = None, + **kwargs, + ): + assert os.path.isfile(vocab_file), vocab_file + + if additional_special_tokens is None: + additional_special_tokens = [ + "<|im_end|>", + "<|im_user|>", + "<|im_assistant|>", + "<|start_header_id|>", + "<|end_header_id|>", + "[EOT]", + "<|im_system|>", + "<|im_middle|>", + ] + + if added_tokens_decoder: + special_tokens_mapping = { + i: added_tokens_decoder[i].content + for i in added_tokens_decoder + } + else: + special_tokens_mapping = {} + + self.vocab_file = vocab_file + mergeable_ranks = load_tiktoken_bpe(vocab_file) + num_base_tokens = len(mergeable_ranks) + self.special_tokens = { + special_tokens_mapping.get(i, f"<|reserved_token_{i}|>"): i + for i in range(num_base_tokens, num_base_tokens + + self.num_reserved_special_tokens) + } + + self.model = tiktoken.Encoding( + name=Path(vocab_file).name, + pat_str=self.pat_str, + mergeable_ranks=mergeable_ranks, + special_tokens=self.special_tokens, + ) + logger.info(f"Reloaded tiktoken model from {vocab_file}") + + self.n_words: int = self.model.n_vocab + # BOS / EOS token IDs + self.bos_id: int = self.special_tokens[str(bos_token)] + self.eos_id: int = self.special_tokens[str(eos_token)] + logger.info( + f"#words: {self.n_words} - BOS ID: {self.bos_id} - EOS ID: {self.eos_id}" + ) + + self.pad_id: int = self.special_tokens[str(pad_token)] + self.unk_id: int = self.special_tokens[str(unk_token)] + + self.byte_encoder = bytes_to_unicode() + self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} + + self.decoder = {} + for i in range(self.n_words): + # Taken from https://gist.github.com/xenova/a452a6474428de0182b17605a98631ee + decoding = ''.join([ + self.byte_encoder[ord(char)] for char in + self.model.decode_single_token_bytes(i).decode('latin-1') + ]) + self.decoder[i] = decoding + + self.encoder = {} + for i in range(self.n_words): + if i in self.decoder: + self.encoder[self.decoder[i]] = i + + super().__init__( + bos_token=bos_token, + eos_token=eos_token, + unk_token=unk_token, + pad_token=pad_token, + additional_special_tokens=additional_special_tokens, + added_tokens_decoder=added_tokens_decoder, + **kwargs, + ) + self.all_special_ids_set = set(self.all_special_ids) + + def _encode_text_piece(self, + text: str, + allow_special_tokens: bool = True) -> List[int]: + # The tiktoken tokenizer can handle <=400k chars without + # pyo3_runtime.PanicException. + TIKTOKEN_MAX_ENCODE_CHARS = 400_000 + + # https://github.com/openai/tiktoken/issues/195 + # Here we iterate over subsequences and split if we exceed the limit + # of max consecutive non-whitespace or whitespace characters. + MAX_NO_WHITESPACES_CHARS = 25_000 + + t: List[int] = [] + for i in range(0, len(text), TIKTOKEN_MAX_ENCODE_CHARS): + for substr in self._split_whitespaces_or_nonwhitespaces( + text[i:i + TIKTOKEN_MAX_ENCODE_CHARS], + MAX_NO_WHITESPACES_CHARS, + ): + if allow_special_tokens: + t.extend( + # structural markers: encode <|...|> as their special token IDs + self.model.encode( + substr, + allowed_special="all", + )) + else: + t.extend( + # user/tool text: encode any <|...|> as ordinary BPE tokens (never as control tokens) + self.model.encode( + substr, + disallowed_special=(), + )) + + return t + + def encode(self, + text: str, + allow_special_tokens: bool = True, + **kwargs) -> List[int]: + """ + Encodes a string into a list of token IDs. + + Args: + text (str): The input string to be encoded. + + Returns: + list[int]: A list of token IDs. + """ + # If there are other args, we should call super().encode because there are a lot of code + # to handle those args. supper().encode finally will call _tokenize and _convert_token_to_id. + # NOTE: our encode method is not compatible with the super().encode method, + # e.g. split_special_tokens' default is True in our encode method. + if len(kwargs) > 0: + logger.warning(f"Calling super().encode with {kwargs}") + return super().encode(text, **kwargs) + + assert type(text) is str + return self._encode_text_piece( + text, allow_special_tokens=allow_special_tokens) + + def decode(self, token_ids: Union[int, List[int]], **kwargs) -> str: + """ + Decodes a list of token IDs into a string. + + Args: + token_ids (List[int]): The list of token IDs to be decoded. + + Returns: + str: The decoded string. + """ + # If there are other args, we should call super().decode because there are a lot of code + # to handle those args. supper().encode finally will call convert_tokens_to_string and _convert_id_to_token. + if len(kwargs) > 0: + return super().decode(token_ids, **kwargs) + + if type(token_ids) is int: + token_ids = [token_ids] + + return self.model.decode(cast(List[int], token_ids)) + + @staticmethod + def _split_whitespaces_or_nonwhitespaces( + s: str, max_consecutive_slice_len: int) -> Iterator[str]: + """ + Splits the string `s` so that each substring contains no more than `max_consecutive_slice_len` + consecutive whitespaces or consecutive non-whitespaces. + """ + current_slice_len = 0 + current_slice_is_space = s[0].isspace() if len(s) > 0 else False + slice_start = 0 + + for i in range(len(s)): + is_now_space = s[i].isspace() + + if current_slice_is_space ^ is_now_space: + current_slice_len = 1 + current_slice_is_space = is_now_space + else: + current_slice_len += 1 + if current_slice_len > max_consecutive_slice_len: + yield s[slice_start:i] + slice_start = i + current_slice_len = 1 + yield s[slice_start:] + + def _encode_chat_segments(self, segments) -> List[int]: + token_ids: List[int] = [] + for segment in segments: + token_ids.extend( + self._encode_text_piece( + segment.text, + allow_special_tokens=segment.allow_special, + )) + return token_ids + + @staticmethod + def _truncate(ids: List[int], + truncation: bool = False, + max_length: Optional[int] = None) -> List[int]: + if truncation and max_length is not None: + return ids[:max_length] + return ids + + def _format_chat_token_output(self, + encoded_inputs: List[List[int]], + *, + is_batched: bool, + padding=False, + truncation: bool = False, + max_length: Optional[int] = None, + return_tensors=None, + return_dict: bool = False): + encoded_inputs = [ + self._truncate(ids, truncation=truncation, max_length=max_length) + for ids in encoded_inputs + ] + + needs_batch_encoding = (is_batched or padding + or return_tensors is not None or return_dict) + if not needs_batch_encoding: + return encoded_inputs[0] + + features = [{ + "input_ids": ids, + "attention_mask": [1] * len(ids) + } for ids in encoded_inputs] + batch = self.pad(features, + padding=padding, + max_length=max_length if padding else None, + return_attention_mask=True, + return_tensors=return_tensors) + + if return_dict: + return batch + if is_batched: + return batch["input_ids"] + return batch["input_ids"][0] if return_tensors is None else batch[ + "input_ids"] + + """ ----- Below are the abstract methods required by PreTrainedTokenizer ----- """ + + @property + def vocab_size(self) -> int: + return self.n_words + + def get_vocab(self) -> Dict[str, int]: + return self.encoder + + def _tokenize(self, text: str, **kwargs) -> List[str]: + return [self.decoder[t] for t in self.encode(text)] + + def _convert_token_to_id(self, token: str) -> int: + return self.encoder.get(token, self.unk_id) + + def _convert_id_to_token(self, index: int) -> str: + return self.decoder.get(index) + + @staticmethod + def clean_up_tokenization(out_string: str) -> str: + return out_string + + def convert_tokens_to_string(self, tokens: List[str]) -> str: + text = ''.join(tokens) + text = bytearray([self.byte_decoder[c] + for c in text]).decode('utf-8', 'replace') + return text + + def save_vocabulary(self, + save_directory: str, + filename_prefix: Optional[str] = None) -> Tuple[str]: + if not os.path.isdir(save_directory): + raise ValueError( + f"vocabulary path ({save_directory}) should be a directory") + out_vocab_file = os.path.join( + save_directory, + (filename_prefix + "-" if filename_prefix else "") + + VOCAB_FILES_NAMES["vocab_file"]) + + if os.path.abspath(self.vocab_file) != os.path.abspath( + out_vocab_file) and os.path.isfile(self.vocab_file): + copyfile(self.vocab_file, out_vocab_file) + + return (out_vocab_file, ) + + def apply_chat_template(self, + conversation, + tools: Optional[list[dict]] = None, + tokenize: bool = False, + add_generation_prompt: bool = True, + thinking: bool = True, + padding=False, + truncation: bool = False, + max_length: Optional[int] = None, + return_tensors=None, + return_dict: bool = False, + **kwargs): + # Tokenizer-level rendering reorders tool result messages to match + # assistant tool_calls, normalizes per-call arguments and response + # schema, then encodes the resulting XTML structure segment-by-segment. + is_batched = is_batched_conversation(conversation) + conversations = conversation if is_batched else [conversation] + image_prompts = kwargs.pop("image_prompts", None) + if is_batched and image_prompts is not None: + raise ValueError("image_prompts is only supported for one chat.") + + # by default set thinking effort to max + kwargs.setdefault("thinking_effort", "max") + + segment_batches = [ + build_chat_segments( + messages, + tools=tools, + add_generation_prompt=add_generation_prompt, + thinking=thinking, + image_prompts=image_prompts, + **kwargs, + ) for messages in conversations + ] + + if not tokenize: + rendered = [ + "".join(segment.text for segment in segments) + for segments in segment_batches + ] + return rendered if is_batched else rendered[0] + + encoded_inputs = [ + self._encode_chat_segments(segments) + for segments in segment_batches + ] + return self._format_chat_token_output( + encoded_inputs, + is_batched=is_batched, + padding=padding, + truncation=truncation, + max_length=max_length, + return_tensors=return_tensors, + return_dict=return_dict, + ) diff --git a/tokenizer_config.json b/tokenizer_config.json new file mode 100644 index 0000000000000000000000000000000000000000..8b4d8c452d716709fe22591bb3fd19c3f5d5f269 --- /dev/null +++ b/tokenizer_config.json @@ -0,0 +1,156 @@ +{ + "added_tokens_decoder": { + "163584": { + "content": "[BOS]", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "163585": { + "content": "[EOS]", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "163586": { + "content": "<|end_of_msg|>", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "163587": { + "content": "<|open|>", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "163588": { + "content": "<|close|>", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "163589": { + "content": "<|sep|>", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "163590": { + "content": "[start_header_id]", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "163591": { + "content": "[end_header_id]", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "163593": { + "content": "[EOT]", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "163602": { + "content": "<|media_begin|>", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "163603": { + "content": "<|media_content|>", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "163604": { + "content": "<|media_end|>", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "163605": { + "content": "<|media_pad|>", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "163649": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "163838": { + "content": "[UNK]", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "163839": { + "content": "[PAD]", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + } + }, + "additional_special_tokens": [ + "<|end_of_msg|>", + "[start_header_id]", + "[end_header_id]", + "[EOT]", + "<|media_begin|>", + "<|media_content|>", + "<|media_end|>", + "<|media_pad|>", + "" + ], + "bos_token": "[BOS]", + "clean_up_tokenization_spaces": false, + "eos_token": "[EOS]", + "model_max_length": 1000000000000000019884624838656, + "pad_token": "[PAD]", + "unk_token": "[UNK]", + "tokenizer_class": "TikTokenTokenizer", + "auto_map": { + "AutoTokenizer": [ + "tokenization_kimi.TikTokenTokenizer", + null + ] + } +} \ No newline at end of file