diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..915b5860428c3c2e84b6de4ae2e6afe7f2440119 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,40 @@ +*.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 +assets/benchmark-appendix.jpg filter=lfs diff=lfs merge=lfs -text +assets/benchmark-limitations.jpg filter=lfs diff=lfs merge=lfs -text +assets/benchmark.jpg filter=lfs diff=lfs merge=lfs -text +assets/dfly2.png filter=lfs diff=lfs merge=lfs -text +assets/pretrained-model-bpb.png filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..7b59d5490e4400af300259d34805c685def2b16b --- /dev/null +++ b/.gitignore @@ -0,0 +1,41 @@ +# Python +__pycache__/ +*.py[cod] +*$py.class +*.so +*.egg-info/ +dist/ +build/ +*.egg + +# Virtual environments +.venv/ +venv/ +env/ + +# IDE +.idea/ +.vscode/ +*.swp +*.swo + +# OS +.DS_Store +Thumbs.db + + +# Training outputs +output/ +saves/ + +# Generated by the multi-node launch scripts +env.txt +hostfile +pssh.hosts + +# Logs +*.log +logs/ + +# Cache +.cache/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2be6f88597077cc42c495586eaf4fb6c6587e33c --- /dev/null +++ b/LICENSE @@ -0,0 +1,245 @@ + Tencent Hy License, Version 1.0 + + This License is derived from the Apache License, Version 2.0 + (http://www.apache.org/licenses/LICENSE-2.0), with modifications, mainly + the additional commercial terms for large Model-as-a-Service ("MaaS") + businesses in Section 10. This License is not the Apache License, + Version 2.0, and is not endorsed by or affiliated with the Apache + Software Foundation. + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 10 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). For the avoidance + of doubt, the Work includes the model weights, parameters, + configuration files, inference and training code, and documentation + made available by Licensor under this License. + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. For the avoidance of doubt, + Derivative Works include any fine-tuned, quantized, distilled, merged, + pruned, or otherwise modified versions of the model weights. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. Notwithstanding the + foregoing, any license terms You provide for the Work or any + Derivative Works must not remove, limit, or conflict with Section 10, + and Section 10 shall continue to apply to every recipient of the + Work or any Derivative Works. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + 10. Additional Commercial Terms. + + 10.1 MaaS. "MaaS" means giving third parties remote access to model + inference or fine-tuning (e.g., via API), allowing them to + submit inputs or specify parameters or training data. This + excludes (i) end-user products with model capabilities confined + to specific features or workflows, without general-purpose + model access, or (ii) merely relaying requests to an + independently operated third-party model service. + + 10.2 Separate License Required. Notwithstanding Sections 2 and 3, + and except as provided in Section 10.3, if You operate a MaaS + business, You must obtain a separate written license to use the + Work or any Derivative Works from Licensor (including by email), + in either of the following cases: + + (a) if Your aggregate worldwide gross revenue exceeds + US$50 million (or the equivalent in other currencies) in + any consecutive 12-month period, whether or not such + revenue is derived from the Work or any Derivative Works, + before using (or continuing to use) the Work or any + Derivative Works; or + + (b) before using the Work or any Derivative Works in or for any + product or service provided by You that has more than + 100 million monthly active users in any calendar month. + + 10.3 Internal Use. Section 10.2 does not apply to Your use of the + Work or any Derivative Works solely for internal purposes, + provided that neither the Work, any Derivative Works, nor their + outputs are made available to third parties. + + 10.4 Contact. For licensing requests or questions, please contact + hy_partners@tencent.com. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Tencent Hy License to your work. + + To apply this License to a Derivative Work, attach the following + notice, with the fields enclosed by brackets "[]" replaced with your + own identifying information. (Don't include the brackets!) + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Tencent Hy License, Version 1.0 (the "License"), + which is based on the Apache License, Version 2.0, with additional + commercial terms. You may not use this file except in compliance + with the License. You may obtain a copy of the License in the + LICENSE file distributed with this work. + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e6fbd162713df9ece76c98bfdc317c8701834f3b --- /dev/null +++ b/README.md @@ -0,0 +1,349 @@ +--- +license: other +license_name: tencent-hy-license +license_link: https://huggingface.co/tencent/Hy4/blob/main/LICENSE +library_name: transformers +pipeline_tag: image-text-to-text +tags: +- hunyuan +- hy4 +- moe +- multimodal +- instruct +--- + +

+ 中文 | English +

+
+ +

+
+

+ +
+ + +[![License](https://img.shields.io/badge/License-Tencent%20Hy%20License-blue)](#license) +   +[![HuggingFace](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Tencent%20Hy-ffc107?color=ffc107&logoColor=white)](https://huggingface.co/tencent/Hy4) +   +[![ModelScope](https://img.shields.io/badge/ModelScope-Tencent%20Hy-624aff)](https://modelscope.cn/models/Tencent-Hunyuan/Hy4) +   +[![GitCode](https://img.shields.io/badge/GitCode-Tencent%20Hy-red?logoColor=white)](https://ai.gitcode.com/tencent_hunyuan/Hy4) + +
+ +

+ 🖥️ Official Website  |   + 💬 GitHub  |   + 📱 GGUF

+ +--- + +## Table of Contents + +- [Model Introduction](#model-introduction) +- [Pretrained model capability](#pretrained-model-capability) +- [Key Improvements](#key-improvements) +- [Capabilities and Use Cases](#capabilities-and-use-cases) + - [Vision and computer use](#vision-and-computer-use) + - [Frontend and game development](#frontend-and-game-development) + - [Finance and office workflows](#finance-and-office-workflows) + - [Scientific research and AI R&D](#scientific-research-and-ai-rd) + - [Long-horizon personal assistant](#long-horizon-personal-assistant) +- [Known Limitations](#known-limitations) +- [Appendix: benchmark results](#appendix-benchmark-results) +- [News](#news) +- [Model Links](#model-links) +- [Quickstart](#quickstart) +- [Deployment](#deployment) + - [DFly2 for Speculative Decoding](#dfly2-for-speculative-decoding) + - [Quantization](#quantization) + - [Inference Frameworks](#inference-frameworks) + - [vLLM](#vllm) + - [SGLang](#sglang) +- [Finetuning](#finetuning) +- [System Card](#system-card) +- [License](#license) +- [Contact Us](#contact-us) + +--- + +## Model Introduction + +**Hy4** is a new-generation Mixture-of-Experts (MoE) flagship model developed by the Tencent Hy Team, supporting text, image, and video understanding. The language backbone comprises 770B total parameters, of which 49B are activated per token. It consists of 78 layers, with a standard dense FFN in the first layer and MoE FFNs in the remaining 77 layers. Each MoE layer contains 256 routed experts and 1 shared expert; every token activates the top-8 routed experts along with the shared expert. In addition to the backbone, a 5-layer DFly2 drafter (3.3B parameters) is built in for speculative decoding. + +On the architecture side, inspired by DeepSeek and GLM, the attention module employs Gated [DeepSeek Sparse Attention](https://arxiv.org/abs/2512.02556) (Gated DSA) with [IndexCache](https://arxiv.org/abs/2603.12201) for cross-layer sparse index reuse. The residual pathway uses [iHC (identity Hyper-Connections)](https://zhuanlan.zhihu.com/p/2010852389670908320) to expand inter-layer information flow. A ViT supports dynamic image resolutions, with an adapter converting image and video frame features into visual tokens for the language model to process alongside text tokens. [DFly2](#dfly2-for-speculative-decoding), a parallel drafter, reuses Hy4's KV cache and sparse indices to support long-context speculative decoding at a low, constant cost. + +### Model Specifications + +| Property | Value | +|:---|:---| +| **Overview** | | +| Architecture | Mixture-of-Experts (MoE) | +| Total Parameters (excluding ViT, adapter, and DFly2) | 770B | +| Activated Parameters per Token | Text 49B + Vision 1.23B | +| ViT Parameters | 1.23B | +| DFly2 Parameters | 3.3B | +| Context Length | 1M (1,048,576 tokens) | +| **Language Backbone** | | +| Backbone Layers | 78 — 1 dense layer and 77 MoE layers | +| Hidden Size | 6,144 | +| Vocabulary Size | 120,832 | +| Residual Connections | iHC (identity Hyper-Connections) with 4 residual streams | +| **Attention** | | +| Attention Architecture | Gated DeepSeek Sparse Attention (Gated DSA) with IndexCache | +| Attention Formulation | Multi-head Latent Attention (MLA) | +| Attention Heads | 64 | +| MLA q_lora_rank | 2,048 | +| MLA kv_lora_rank | 512 | +| Indexer Heads / Head Dimension | 32 / 128 | +| Sparse Context Selection | Top-2,048 tokens selected by the indexer | +| **Feed-Forward Networks** | | +| Dense FFN Intermediate Size | 18,432 | +| Routed Experts per MoE Layer | 256 | +| Shared Experts per MoE Layer | 1 | +| Activated Routed Experts per Token | 8 | +| Expert Intermediate Size | 2,048 | +| **Vision Encoder** | | +| Vision Encoder Layers | 40 | +| Vision Encoder Hidden Size | 1,536 | +| Vision Encoder Intermediate Size | 6,144 | +| Vision Encoder Attention Heads | 16 | +| Vision Patch Size | 16 × 16 | +| Vision Position Embedding Size | 128 × 128 | +| Visual Feature Merging | 2 x 2 | + +## Pretrained model capability + +Bits-per-byte (BPB) on internal code & agent validation, lower is better: + +

+ Bits-per-byte on internal code and agent validation versus active parameters; lower is better +

+ +Few-shot pretrain benchmark evaluation: + +| Category | Benchmark | #Shots | Hy4 Base | Hy4 flash Base | Hy3 preview Base | DeepSeek-V4-flash-Base | DeepSeek-V4-Pro-Base | +| --- | --- | :---: | ---: | ---: | ---: | ---: | ---: | +| **Knowledge** | MMLU† | 5 | **91.6** | 88.7 | 87.5 | 89.7 | 91.1 | +| | MMLU-Pro† | 5 | **73.9** | 71.1 | 65.8 | 68.6 | 73.4 | +| | MMLU-Redux† | 5 | **90.6** | 87.6 | 87.0 | 88.8 | 90.2 | +| | SuperGPQA† | 5 | **62.7** | 57.8 | 52.3 | 52.5 | 54.8 | +| | C-Eval† | 5 | **95.0** | 92.0 | 90.1 | 91.9 | 93.4 | +| | CMMLU† | 5 | **93.1** | 91.6 | 89.6 | 89.8 | 90.7 | +| | SimpleQA | 5 | **57.2** | 37.5 | 26.4 | 31.3 | 52.1 | +| | Chinese-SimpleQA† | 5 | **83.9** | 74.6 | 69.6 | 71.9 | 76.6 | +| | AGIEval (English)† | 3 | **79.3** | 75.4 | 76.0 | 76.3 | 78.2 | +| | AGIEval (Chinese)† | 3 | **91.2** | 90.6 | 87.8 | 88.5 | 89.8 | +| **Reasoning** | HellaSwag (3,000-item subset) | 10 | **87.1** | 85.2 | 85.7 | 85.1 | 86.8 | +| | PIQA | 4 | **85.3** | 84.4 | 84.6 | 83.8 | 84.9 | +| | ARC-Challenge | 0 | **97.3** | 95.0 | 96.0 | **97.3** | 97.0 | +| | Social IQa | 0 | **82.7** | 80.1 | 80.5 | 72.5 | 73.1 | +| | KOR-Bench | 3 | **57.6** | 54.7 | 54.6 | 53.4 | 55.4 | +| | C³ | 0 | **82.4** | 77.3 | 75.9 | 74.1 | 78.3 | +| **Math** | U-MATH | 5 | **71.6** | 69.8 | 60.9 | 57.4 | 64.8 | +| | OCW Courses | 5 | 66.7 | 64.0 | 62.6 | 63.3 | **68.2** | +| **Code** | MBPP-plus | 3 | 74.0 | 73.7 | 77.4 | 76.8 | **79.1** | +| **Multilingual** | Belebele (5-language subset)† | 5 | 95.0 | 93.8 | 94.2 | 94.4 | **95.2** | +| | INCLUDE† | 5 | **88.1** | 82.8 | 84.3 | 84.0 | 84.3 | +| **Multimodal** | MMMU-Pro (Standard, 10 opts) | 4 | **59.6** | 52.0 | — | — | — | +| | SimpleVQA | 4 | **54.5** | 48.5 | — | — | — | +| | CVBench | 4 | **86.7** | 83.4 | — | — | — | +| | RealWorldQA | 4 | **72.3** | 71.1 | — | — | — | +| | TextVQA | 4 | **78.2** | 73.4 | — | — | — | +| | CountBenchQA | 4 | **90.6** | 86.6 | — | — | — | + +† Macro-averaged accuracy for the marked text benchmarks. Other text rows use the accuracy metric reported by our evaluation suite. Bold marks the highest available numerical score in each row; it does not indicate statistical significance. + +Multimodal results are reported only for Hy4 Base and Hy4 flash Base. + +ARC-Challenge and HellaSwag use 299-item and 3,000-item subsets, respectively. INCLUDE uses a 5,000-example Lite subset covering 44 languages. Belebele covers German, Korean, Vietnamese, Spanish, and Russian (4,475 examples in total). + +**Disclaimer: Because our base model was exposed to a large amount of synthetic instruction data during mid-training, it occasionally fails to follow the expected answer format in few-shot evaluations, which may distort the scores.** + +## Key Improvements + +Compared with Hy4 preview, Hy4 substantially scales up both pre-training and post-training. It adds vision capabilities and delivers major gains in instruction following, long-context understanding, long-horizon tasks, and deep research. + +

+ Hy4 benchmark highlights compared with Hy4 preview and other models +

+ +## Capabilities and Use Cases + +### Vision and computer use + +By combining perception, reasoning, and tool use, Hy4 can understand fine-grained image details and interpret complex charts. It supports computer-use workflows across command-line interfaces (CLI) and graphical user interfaces (GUI). Targeted training on specialized software such as Blender and CAD, as well as long-horizon workflows spanning multiple applications, improves task planning and execution. + +### Frontend and game development + +For frontend work, we optimized Hy4 for complex UI interactions, business logic, state management, and full-stack integration, so that generated interfaces are not only visually polished but also functionally complete. + +For game development, we partnered with professional developers at Tencent Interactive Entertainment Group (IEG) to curate high-quality training data and build evaluations. We focused on feature implementation, gameplay logic, state tracking, and asset pipelines. We also extensively adapted Hy4 for major engines such as Unreal Engine, Unity, and Godot, and expanded its capabilities to multiplayer game development. Compared with Hy4 preview, Hy4 improves by 19.1% on GameDev and 9.8% on GameLogic. + +### Finance and office workflows + +To ground Hy4 in real-world financial work, we built thousands of realistic workspaces and tens of thousands of tasks spanning fund research, equity analysis, quantitative strategies, asset allocation, corporate finance, and tax accounting. Working with Tencent Financial Technology (FiT), we evaluated Hy4 with 213 finance professionals, including 153 experts from leading financial institutions. More than 70% of these experts have over five years of industry experience. Across 579 real-world financial tasks, Hy4 ranks first among open-weight models: + +| Model | Average Score (out of 4) | +|:---|:---:| +| **Hy4** | **3.04** | +| DeepSeek-V4.1-Flash-1017 | 2.97 | +| Kimi K3.1 Pro | 2.68 | +| GLM-5.3 | 2.68 | + +On IRAB, an internal benchmark from financial AI agent company RabyteTech, Hy4 also scores 12.03 percentage points higher than Hy4 preview. To make Hy4 more reliable for financial and office workflows, we made targeted upgrades to search, focusing on time-sensitive retrieval, multi-source synthesis, and factual consistency verification. In internal evaluations, Hy4 cut the hallucination rate from 15.76% (on Hy4 preview) to 5.45%, and reduced speculative errors from 23.1% to 5.6%. We also improved Hy4’s ability to co-edit Word, Excel, and PowerPoint files with people in real time. In blind evaluations, Hy4 shows clear gains over Hy4 preview in document formatting, reliability, and overall usability. + +### Scientific research and AI R&D + +Hy4 combines deep reasoning, scientific computing, and long-horizon execution for research workflows. On TenureTrail, our internal benchmark of 123 research tasks across seven disciplines, Hy4 ranks first among open-weight models. It shows strong capabilities in mathematical construction, physical modeling, earth sciences, systems engineering, and socioeconomic decision-making. Paired with our [Hyra 2.0](https://hy.tencent.ai/research/hyra2) harness, Hy4 optimized our internal pre-training infrastructure for smaller models with the same architecture, and autonomously trained a variant that outperforms the official Jev baseline on multiple benchmarks. + +### Long-horizon personal assistant + +Given relevant work context, Hy4 can synthesize information from chat history, emails, documents, calendars, and meeting notes. It can track project history and updates, surface action items, prepare meeting briefs, flag upcoming deadlines, and help prioritize tasks. + +## Known Limitations + +Although Hy4 is one of the strongest open-weight models available today, a notable gap remains between it and top proprietary models, particularly on challenging internal benchmarks for research-level mathematics, long-horizon coding, model self-improvement, and advanced visual question answering. + +

+ Challenging benchmarks illustrating remaining gaps between Hy4 and leading proprietary models +

+ +## Appendix: benchmark results + +

+ Full Hy4 benchmark results, comparison models, and evaluation notes +

+ +## News + +* We open-source **Hy4**, **Hy4-FP8**, and the pre-trained **Hy4 base** model weights on [Hugging Face](https://huggingface.co/tencent/Hy4), [ModelScope](https://modelscope.cn/models/Tencent-Hunyuan/Hy4), and [GitCode](https://ai.gitcode.com/tencent_hunyuan/Hy4). + +## Model Links + +| Model Name | Description | Hugging Face | ModelScope | GitCode | +|:---|:---|:---:|:---:|:---:| +| Hy4 | Instruct model | [Model](https://huggingface.co/tencent/Hy4) | [Model](https://modelscope.cn/models/Tencent-Hunyuan/Hy4) | [Model](https://ai.gitcode.com/tencent_hunyuan/Hy4) | +| Hy4-FP8 | FP8 quantized instruct model | [Model](https://huggingface.co/tencent/Hy4-FP8) | [Model](https://modelscope.cn/models/Tencent-Hunyuan/Hy4-FP8) | [Model](https://ai.gitcode.com/tencent_hunyuan/Hy4-FP8) | +| Hy4 base | Pre-trained base model | [Model](https://huggingface.co/tencent/Hy4-base) | [Model](https://modelscope.cn/models/Tencent-Hunyuan/Hy4-base) | [Model](https://ai.gitcode.com/tencent_hunyuan/Hy4-base) | + +Hy4 base is a pre-trained base model, not an instruction-tuned chat model. The chat and reasoning examples below apply to Hy4 and Hy4-FP8. + +## Quickstart + +Deploy Hy4 with [vLLM](#vllm) or [SGLang](#sglang) first, then call the OpenAI-compatible API: + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://127.0.0.1:8000/v1", api_key="EMPTY") + +response = client.chat.completions.create( + model="hy4", + messages=[ + {"role": "user", "content": "Hello! Can you briefly introduce yourself?"}, + ], + temperature=0.9, + top_p=1.0, +) +print(response.choices[0].message.content) +``` + +> **Recommended parameters**: `temperature=0.9`, `top_p=1.0`. +> +> **Reasoning mode**: `reasoning_effort` accepts `"no_think"` and `"high"`. It defaults to `"high"` (deep chain-of-thought), which suits complex tasks such as math, coding, and reasoning. For direct responses, pass `extra_body={"chat_template_kwargs": {"reasoning_effort": "no_think"}}`. + +See the [Deployment](#deployment) section below for how to start the API server. + +## Deployment + +### DFly2 for Speculative Decoding + +DFly2 is Hy4's speculative-decoding drafter, trained with [AngelSpec](https://github.com/Tencent/AngelSpec) and built directly on Hy4's **Top-k Sparse KV**: each draft layer shares the KV cache (**KV Share**) and the indexer-selected top-2048 positions (**Index Share**) with its corresponding Hy4 DSA layer. This yields three advantages: + +- **Constant cost**: each draft token attends to at most ~2K keys, regardless of context length. +- **Zero extra KV memory**: no separate KV cache is maintained for the drafter. +- **PD-disaggregation ready**: not involved in prefill; the prefill-to-decode transfer adds only one last-layer hidden state. + +

+ DFly2 architecture: each draft layer reuses the KV cache and indexer-selected top-k positions of a Hy4 DSA layer +

+ +### Quantization + +We provide [AngelSlim](https://github.com/tencent/AngelSlim), a more accessible, comprehensive, and efficient toolkit for large model compression. AngelSlim supports a comprehensive suite of compression tools for large-scale multimodal models, including common quantization algorithms, low-bit quantization, and speculative sampling. + +For this model, we have provided a [GGUF](https://huggingface.co/AngelSlim/Hy4-GGUF) compressed version for end-to-end testing purposes. + +### Inference Frameworks + +For production serving, we recommend using [vLLM](https://github.com/vllm-project/vllm) or [SGLang](https://docs.sglang.io/). Please refer to the recipes: +- [Hy4 vLLM Recipe](https://recipes.vllm.ai/tencent/Hy4) +- [Hy4 SGLang Cookbook](https://docs.sglang.io/cookbook/autoregressive/Tencent/Hy4) + +#### vLLM + +Use official prebuilt image `vllm/vllm-openai:hy4`: + +```bash +docker run --gpus all \ + --privileged --ipc=host -p 8000:8000 \ + -v ~/.cache/huggingface:/root/.cache/huggingface \ + -e VLLM_USE_RUST_FRONTEND=1 \ + vllm/vllm-openai:hy4 tencent/Hy4-FP8 \ + --dtype bfloat16 \ + --limit-mm-per-prompt '{"image":1,"video":0}' \ + --tensor-parallel-size 8 \ + --enable-auto-tool-choice \ + --reasoning-parser hy_v4 \ + --tool-call-parser hy_v4 \ + --speculative-config '{"num_speculative_tokens":5,"method":"dfly"}' \ + --attention-backend FLASHMLA_SPARSE \ + --port 8000 \ + --served-model-name hy4 +``` + + +#### SGLang + +Use the official prebuilt image `lmsysorg/sglang:hy4` (multi-arch, x86 and Arm): + +```bash +docker pull lmsysorg/sglang:hy4 + +docker run --gpus all --ipc=host -p 8000:8000 lmsysorg/sglang:hy4 \ + sglang serve \ + --model-path tencent/Hy4-FP8 \ + --tp 8 \ + --speculative-algorithm DFLY \ + --port 8000 \ + --served-model-name hy4 + +``` + +## Finetuning + +Hy4 provides a complete model finetuning pipeline. For detailed documentation, please refer to: [Finetuning Guide](https://huggingface.co/tencent/Hy4/blob/main/finetune/README.md). + +## System Card + +Please refer to the [Hy4 System Card](https://hy.tencent.ai/Hy4_system_card.pdf). + +## License + +Hy4 is released under the **Tencent Hy License**. See [LICENSE](https://huggingface.co/tencent/Hy4/blob/main/LICENSE) for details. + +## Contact Us + +If you have any questions or suggestions, feel free to reach out to our R&D and product teams via email: + +📧 **hunyuan_opensource@tencent.com** + +--- + +

+ Hy4 is developed by the Tencent Hy Team. +

diff --git a/README_CN.md b/README_CN.md new file mode 100644 index 0000000000000000000000000000000000000000..66d0dd968ec9ac59f449d1efc939689929f90805 --- /dev/null +++ b/README_CN.md @@ -0,0 +1,334 @@ +

+ English | 中文 +

+
+ +

+
+

+ +
+ + +[![License](https://img.shields.io/badge/License-Tencent%20Hy%20License-blue)](#许可证) +   +[![HuggingFace](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Tencent%20Hy-ffc107?color=ffc107&logoColor=white)](https://huggingface.co/tencent/Hy4) +   +[![ModelScope](https://img.shields.io/badge/ModelScope-Tencent%20Hy-624aff)](https://modelscope.cn/models/Tencent-Hunyuan/Hy4) +   +[![GitCode](https://img.shields.io/badge/GitCode-Tencent%20Hy-red?logoColor=white)](https://ai.gitcode.com/tencent_hunyuan/Hy4) + +
+ +

+ 🖥️ 官方网站  |   + 💬 GitHub  |   + 📱 GGUF

+ +--- + +## 目录 + +- [模型介绍](#模型介绍) +- [预训练模型能力](#预训练模型能力) +- [主要改进](#主要改进) +- [能力与应用场景](#能力与应用场景) + - [视觉与电脑任务](#视觉与电脑任务) + - [前端与游戏开发](#前端与游戏开发) + - [金融与办公场景](#金融与办公场景) + - [科研与模型研发](#科研与模型研发) + - [长期个人助理](#长期个人助理) +- [已知局限](#已知局限) +- [Benchmark 附录](#benchmark-附录) +- [新闻](#新闻) +- [模型链接](#模型链接) +- [快速开始](#快速开始) +- [推理和部署](#推理和部署) + - [DFly2 投机解码](#dfly2-投机解码) + - [量化工具](#量化工具) + - [推理框架](#推理框架) + - [vLLM](#vllm) + - [SGLang](#sglang) +- [模型微调](#模型微调) +- [System Card](#system-card) +- [许可证](#许可证) +- [联系我们](#联系我们) + +--- + +## 模型介绍 + +**Hy4** 是由腾讯混元团队研发的新一代混合专家(MoE)旗舰模型,支持文本、图像和视频理解。语言模型主干总参数量 770B,每个 token 激活 49B,共包含 78 层,第一层采用标准 FFN,其余 77 层均为 MoE 结构,每层包含 256 个路由专家与 1 个共享专家,每个 token 激活 top-8 路由专家及共享专家。主干之外内置 5 层 DFly2 草稿模型(参数量 3.3B)以支持投机解码。 + +在架构层面,受到 DeepSeek 和 GLM 的启发,注意力侧采用 Gated [DeepSeek Sparse Attention](https://arxiv.org/abs/2512.02556)(Gated DSA),并引入 [IndexCache](https://arxiv.org/abs/2603.12201) 跨层复用稀疏索引,残差侧采用 [iHC (identity Hyper-Connections)](https://zhuanlan.zhihu.com/p/2010852389670908320) 扩展层间信息通路。视觉侧采用支持动态分辨率的 ViT,通过适配器将图像和视频帧的特征转换为视觉 token,与文本 token 一同输入语言模型。并行草稿模型 [DFly2](#dfly2-投机解码) 直接复用 Hy4 的 KV cache 与稀疏索引,以固定的低开销支持长上下文投机解码。 + +### 模型规格 + +| 规格项 | 取值 | +|:---|:---| +| **模型概览** | | +| Architecture | Mixture-of-Experts (MoE) | +| Total Parameters (excluding ViT, adapter, and DFly2) | 770B | +| Activated Parameters per Token | Text 49B + Vision 1.23B | +| ViT Parameters | 1.23B | +| DFly2 Parameters | 3.3B | +| Context Length | 1M (1,048,576 tokens) | +| **语言模型主干** | | +| Backbone Layers | 78 — 1 dense layer and 77 MoE layers | +| Hidden Size | 6,144 | +| Vocabulary Size | 120,832 | +| Residual Connections | iHC (identity Hyper-Connections) with 4 residual streams | +| **注意力** | | +| Attention Architecture | Gated DeepSeek Sparse Attention (Gated DSA) with IndexCache | +| Attention Formulation | Multi-head Latent Attention (MLA) | +| Attention Heads | 64 | +| MLA q_lora_rank | 2,048 | +| MLA kv_lora_rank | 512 | +| Indexer Heads / Head Dimension | 32 / 128 | +| Sparse Context Selection | Top-2,048 tokens selected by the indexer | +| **前馈网络** | | +| Dense FFN Intermediate Size | 18,432 | +| Routed Experts per MoE Layer | 256 | +| Shared Experts per MoE Layer | 1 | +| Activated Routed Experts per Token | 8 | +| Expert Intermediate Size | 2,048 | +| **视觉编码器** | | +| Vision Encoder Layers | 40 | +| Vision Encoder Hidden Size | 1,536 | +| Vision Encoder Intermediate Size | 6,144 | +| Vision Encoder Attention Heads | 16 | +| Vision Patch Size | 16 × 16 | +| Vision Position Embedding Size | 128 × 128 | +| Visual Feature Merging | 2 x 2 | + +## 预训练模型能力 + +内部代码与 Agent 验证集上的 BPB(Bits-per-byte,每字节比特数),数值越低越好: + +

+ 内部代码与 Agent 验证集上的 BPB 与激活参数量对比,BPB 越低越好 +

+ +预训练模型的 few-shot 基准评测结果: + +| 类别 | 评测基准 | #Shots | Hy4 Base | Hy4 flash Base | Hy3 preview Base | DeepSeek-V4-flash-Base | DeepSeek-V4-Pro-Base | +| --- | --- | :---: | ---: | ---: | ---: | ---: | ---: | +| **知识** | MMLU† | 5 | **91.6** | 88.7 | 87.5 | 89.7 | 91.1 | +| | MMLU-Pro† | 5 | **73.9** | 71.1 | 65.8 | 68.6 | 73.4 | +| | MMLU-Redux† | 5 | **90.6** | 87.6 | 87.0 | 88.8 | 90.2 | +| | SuperGPQA† | 5 | **62.7** | 57.8 | 52.3 | 52.5 | 54.8 | +| | C-Eval† | 5 | **95.0** | 92.0 | 90.1 | 91.9 | 93.4 | +| | CMMLU† | 5 | **93.1** | 91.6 | 89.6 | 89.8 | 90.7 | +| | SimpleQA | 5 | **57.2** | 37.5 | 26.4 | 31.3 | 52.1 | +| | Chinese-SimpleQA† | 5 | **83.9** | 74.6 | 69.6 | 71.9 | 76.6 | +| | AGIEval (English)† | 3 | **79.3** | 75.4 | 76.0 | 76.3 | 78.2 | +| | AGIEval (Chinese)† | 3 | **91.2** | 90.6 | 87.8 | 88.5 | 89.8 | +| **推理** | HellaSwag (3,000-item subset) | 10 | **87.1** | 85.2 | 85.7 | 85.1 | 86.8 | +| | PIQA | 4 | **85.3** | 84.4 | 84.6 | 83.8 | 84.9 | +| | ARC-Challenge | 0 | **97.3** | 95.0 | 96.0 | **97.3** | 97.0 | +| | Social IQa | 0 | **82.7** | 80.1 | 80.5 | 72.5 | 73.1 | +| | KOR-Bench | 3 | **57.6** | 54.7 | 54.6 | 53.4 | 55.4 | +| | C³ | 0 | **82.4** | 77.3 | 75.9 | 74.1 | 78.3 | +| **数学** | U-MATH | 5 | **71.6** | 69.8 | 60.9 | 57.4 | 64.8 | +| | OCW Courses | 5 | 66.7 | 64.0 | 62.6 | 63.3 | **68.2** | +| **代码** | MBPP-plus | 3 | 74.0 | 73.7 | 77.4 | 76.8 | **79.1** | +| **多语言** | Belebele (5-language subset)† | 5 | 95.0 | 93.8 | 94.2 | 94.4 | **95.2** | +| | INCLUDE† | 5 | **88.1** | 82.8 | 84.3 | 84.0 | 84.3 | +| **多模态** | MMMU-Pro (Standard, 10 opts) | 4 | **59.6** | 52.0 | — | — | — | +| | SimpleVQA | 4 | **54.5** | 48.5 | — | — | — | +| | CVBench | 4 | **86.7** | 83.4 | — | — | — | +| | RealWorldQA | 4 | **72.3** | 71.1 | — | — | — | +| | TextVQA | 4 | **78.2** | 73.4 | — | — | — | +| | CountBenchQA | 4 | **90.6** | 86.6 | — | — | — | + +† 标注的文本评测采用宏平均准确率,其余文本评测采用本评测框架报告的准确率。每行最高分以粗体标示;加粗不代表差异具有统计显著性。 + +多模态结果仅列出 Hy4 Base 和 Hy4 flash Base。 + +ARC-Challenge 和 HellaSwag 分别使用包含 299 道和 3,000 道题目的子集。INCLUDE 使用覆盖 44 种语言、包含 5,000 个样本的 Lite 子集。Belebele 覆盖德语、韩语、越南语、西班牙语和俄语,共 4,475 个样本。 + +**免责声明:我们的基座模型在中期训练中使用了大量合成指令数据,因此在 few-shot 评测中偶尔无法遵循预期的答案格式,可能导致得分失真。** + +## 主要改进 + +相比 Hy4 preview,Hy4 显著扩展了预训练和后训练规模,引入视觉理解能力,并大幅提升了指令遵循、长文理解、长程任务和深度研究等综合能力。 + +

+ Hy4 与 Hy4 preview 及其他模型的主要评测结果 +

+ +## 能力与应用场景 + +### 视觉与电脑任务 + +Hy4 结合视觉感知、推理与工具调用,支持细粒度图像理解、复杂图表分析,以及结合命令行与图形界面的电脑操作任务。针对 Blender、CAD 等专业软件和跨应用长程任务开展的专项训练,提升了任务规划与执行能力。 + +### 前端与游戏开发 + +我们针对复杂交互、业务逻辑、状态管理和前后端联动进行了优化,让生成的界面不仅好看,而且功能完整可用。通过与腾讯 IEG 专业游戏开发者合作,Hy4 在功能实现、玩法逻辑、状态理解和资产处理方面持续进步,深度适配 Unreal Engine、Unity、Godot 等主流引擎,并开始扩展至多人联机游戏开发。相比 Hy4 preview,Hy4 在 **GameDev 和 GameLogic 评测中分别提升 19.1% 和 9.8%**。 + +### 金融与办公场景 + +我们基于真实金融场景构建了数千个工作空间和上万个高质量任务,覆盖基金研究、证券分析、量化策略、资产配置、公司金融、财税会计等专业流程。联合腾讯金融科技 FiT 开展的众测邀请了 **213 位金融专家**,其中 **153 位来自外部头部金融机构**,约七成拥有五年以上工作经验。基于 **579 个真实金融任务**的众测显示,Hy4 综合表现位居开源模型第一: + +| 模型 | 平均分(满分 4 分) | +|:---|:---:| +| **Hy4** | **3.04** | +| DeepSeek-V4.1-Flash-1017 | 2.97 | +| Kimi K3.1 Pro | 2.68 | +| GLM-5.3 | 2.68 | + +在金融智能体公司讯兔科技的内部评测 IRAB 中,Hy4 较 Hy4 preview 提升 **12.03 个百分点**。针对时效检索、多源信息整合与事实一致性校验的搜索优化,也提升了金融和办公场景的可靠性:在自建测试中,幻觉率从 **15.76% 降至 5.45%**,猜测导致的错误率从 **23.1% 降至 5.6%**。Hy4 还支持与用户实时协作编辑 Word、Excel、PPT 等办公文件,盲评显示其文档美观度、稳定性与可用性均有明显提升。 + +### 科研与模型研发 + +Hy4 将复杂推理、科学编程与长程任务执行相结合,进一步提升端到端推进科研工作的能力。在涵盖 **7 大学科、123 项研究任务**的 TenureTrail 内部评测中,Hy4 位居开源模型第一。结合 [Hyra 2.0](https://hunyuan.tencent.com/research/hyra2) 脚手架,Hy4 优化了内部同架构小模型的预训练基础设施,并自动训练出在多项评测中优于官方基线的 Jev 模型。 + +### 长期个人助理 + +在提供相关工作上下文后,Hy4 可以综合聊天记录、邮件、文档、日程和会议记录等信息,梳理各项目的历史与最新进展,识别待办任务、准备会议、提醒截止事项,并协助安排优先级。 + +## 已知局限 + +尽管 Hy4 已经是目前最强的开源模型之一,其与顶尖闭源模型仍然存在较大差距,尤其在我们内部构建的前沿数学、长程开发、模型迭代、视觉问答等领域的高难度测试集上。 + +

+ 高难度评测中 Hy4 与顶尖闭源模型仍存在的差距 +

+ +## Benchmark 附录 + +

+ Hy4 完整评测结果、对比模型与测试说明 +

+ +## 新闻 + +* 我们在 [Hugging Face](https://huggingface.co/tencent/Hy4)、[ModelScope](https://modelscope.cn/models/Tencent-Hunyuan/Hy4) 和 [GitCode](https://ai.gitcode.com/tencent_hunyuan/Hy4) 开源 **Hy4**、**Hy4-FP8** 和预训练模型 **Hy4 base** 的权重。 + +## 模型链接 + +| 模型名 | 简介 | Hugging Face | ModelScope | GitCode | +|:---|:---|:---:|:---:|:---:| +| Hy4 | Instruct 模型 | [Model](https://huggingface.co/tencent/Hy4) | [Model](https://modelscope.cn/models/Tencent-Hunyuan/Hy4) | [Model](https://ai.gitcode.com/tencent_hunyuan/Hy4) | +| Hy4-FP8 | FP8 量化 Instruct 模型 | [Model](https://huggingface.co/tencent/Hy4-FP8) | [Model](https://modelscope.cn/models/Tencent-Hunyuan/Hy4-FP8) | [Model](https://ai.gitcode.com/tencent_hunyuan/Hy4-FP8) | +| Hy4 base | 预训练模型 | [Model](https://huggingface.co/tencent/Hy4-base) | [Model](https://modelscope.cn/models/Tencent-Hunyuan/Hy4-base) | [Model](https://ai.gitcode.com/tencent_hunyuan/Hy4-base) | + +Hy4 base 为预训练底座,非指令微调聊天模型;下方对话与推理模式示例适用于 Hy4 和 Hy4-FP8。 + +## 快速开始 + +建议先通过 [vLLM](#vllm) 或 [SGLang](#sglang) 部署服务,然后通过 OpenAI 兼容 API 调用: + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://127.0.0.1:8000/v1", api_key="EMPTY") + +response = client.chat.completions.create( + model="hy4", + messages=[ + {"role": "user", "content": "你好!请简单介绍一下你自己。"}, + ], + temperature=0.9, + top_p=1.0, +) +print(response.choices[0].message.content) +``` + +> **推荐参数**:`temperature=0.9`,`top_p=1.0`。 +> +> **推理模式**:`reasoning_effort` 可选 `"no_think"`、`"high"`,默认为 `"high"`(深度思维链),适合数学、编程、推理等复杂任务。日常对话如需直接回复,可传入 `extra_body={"chat_template_kwargs": {"reasoning_effort": "no_think"}}`。 + +具体部署方式请参考下方[推理和部署](#推理和部署)章节。 + +## 推理和部署 + +### DFly2 投机解码 + +DFly2 是基于 [AngelSpec](https://github.com/Tencent/AngelSpec) 框架训练的 Hy4 投机解码草稿模型,直接复用主模型的 **Top-k Sparse KV**:每个 draft 层与 Hy4 对应的 DSA 层共享 KV cache(**KV Share**)及 indexer 选出的 top-2048 个位置(**Index Share**)。由此带来三点优势: + +- **计算开销固定**:每个草稿 token 至多关注约 2K 个 key,注意力复杂度与上下文长度无关。 +- **零额外 KV 显存**:无需维护草稿模型独立的 KV cache。 +- **适配 PD 分离**:不参与 prefill,P→D 仅额外传输一个末层隐状态。 + +

+ DFly2 结构图:每个 draft 层复用 Hy4 对应 DSA 层的 KV cache 与 indexer 选出的 top-k 位置 +

+ +### 量化工具 + +我们提供了 [AngelSlim](https://github.com/tencent/AngelSlim)——一套易用、全面、高效的大模型压缩工具包,涵盖常用量化算法、低比特量化和投机采样等能力。 + +对于本模型我们提供了[GGUF](https://huggingface.co/AngelSlim/Hy4-GGUF) 压缩版本以供端测使用。 + +### 推理框架 + +对于生产环境部署,我们建议使用 [vLLM](https://github.com/vllm-project/vllm) 或 [SGLang](https://docs.sglang.io/)。请参考部署方案: +- [Hy4 vLLM Recipe](https://recipes.vllm.ai/tencent/Hy4) +- [Hy4 SGLang Cookbook](https://docs.sglang.io/cookbook/autoregressive/Tencent/Hy4) + + +#### vLLM + +使用社区官方镜像 `vllm/vllm-openai:hy4` 部署: + +```bash +docker run --gpus all \ + --privileged --ipc=host -p 8000:8000 \ + -v ~/.cache/huggingface:/root/.cache/huggingface \ + -e VLLM_USE_RUST_FRONTEND=1 \ + vllm/vllm-openai:hy4 tencent/Hy4-FP8 \ + --dtype bfloat16 \ + --limit-mm-per-prompt '{"image":1,"video":0}' \ + --tensor-parallel-size 8 \ + --enable-auto-tool-choice \ + --reasoning-parser hy_v4 \ + --tool-call-parser hy_v4 \ + --speculative-config '{"num_speculative_tokens":5,"method":"dfly"}' \ + --attention-backend FLASHMLA_SPARSE \ + --port 8000 \ + --served-model-name hy4 +``` + + +#### SGLang + +使用社区官方镜像 `lmsysorg/sglang:hy4` 部署(支持 x86 和 Arm): + +```bash +docker pull lmsysorg/sglang:hy4 + +docker run --gpus all --ipc=host -p 8000:8000 lmsysorg/sglang:hy4 \ + sglang serve \ + --model-path tencent/Hy4-FP8 \ + --tp 8 \ + --speculative-algorithm DFLY \ + --port 8000 \ + --served-model-name hy4 +``` + + +## 模型微调 + +Hy4 提供了完整的模型微调流程,详细的微调文档请参考:[模型微调指南](https://huggingface.co/tencent/Hy4/blob/main/finetune/README_CN.md)。 + +## System Card + +请参阅 [Hy4 System Card](https://hy.tencent.ai/Hy4_system_card.pdf)。 + +## 许可证 + +Hy4 基于 **Tencent Hy License** 发布。详情请参阅 [LICENSE](https://huggingface.co/tencent/Hy4/blob/main/LICENSE)。 + +## 联系我们 + +如有问题或建议,欢迎通过邮件联系我们的研发和产品团队: + +📧 **hunyuan_opensource@tencent.com** + +--- + +

+ Hy4 由腾讯混元团队研发。 +

diff --git a/assets/benchmark-appendix.jpg b/assets/benchmark-appendix.jpg new file mode 100644 index 0000000000000000000000000000000000000000..00811b750b61e8c4a6d233781fda0f97e70fcd2e --- /dev/null +++ b/assets/benchmark-appendix.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ce08997cd3c67a54db99d03bd1405c8079f3ab4b8abeddb342a5679834436c2 +size 2235286 diff --git a/assets/benchmark-limitations.jpg b/assets/benchmark-limitations.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d2cec7f59183ccf0628462a192e6f51457d6af56 --- /dev/null +++ b/assets/benchmark-limitations.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cd8641fdc4ed365e6acf11755eff02415c6f903983e74583bb6209e517ef3da2 +size 424434 diff --git a/assets/benchmark.jpg b/assets/benchmark.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6acf194d6bfda7eee570a09712bd1e70b1551f2d --- /dev/null +++ b/assets/benchmark.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5752db9d37eac7b7d8331ba90c0588fa0044355cb8f0acda142185c6966ecdef +size 1257136 diff --git a/assets/dfly2.png b/assets/dfly2.png new file mode 100644 index 0000000000000000000000000000000000000000..dbd9a8b1f7a13ae4330b4411e1a3ad444f026431 --- /dev/null +++ b/assets/dfly2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1a38561973c67c7834cbacf44df02d7d6ea9e569e50514b6bd58ac28a6e94ae9 +size 906016 diff --git a/assets/logo-en.png b/assets/logo-en.png new file mode 100644 index 0000000000000000000000000000000000000000..836258358f0904150d09dc896f300715368937d4 Binary files /dev/null and b/assets/logo-en.png differ diff --git a/assets/logo-zh.png b/assets/logo-zh.png new file mode 100644 index 0000000000000000000000000000000000000000..ff8436092e09b52a2ea06f237713fe64141f475c Binary files /dev/null and b/assets/logo-zh.png differ diff --git a/assets/pretrained-model-bpb.png b/assets/pretrained-model-bpb.png new file mode 100644 index 0000000000000000000000000000000000000000..77f64fd36d735b9a12ee723b8dd96b9d75e9cbc9 --- /dev/null +++ b/assets/pretrained-model-bpb.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1ad7aada7fcac0f34a88b629789bb6dce512b403b310faa5f7201dfc013b9640 +size 399524 diff --git a/chat_template.jinja b/chat_template.jinja new file mode 100644 index 0000000000000000000000000000000000000000..974eeefaa83ee5c1feee3ccd0fdb8328007e2b6d --- /dev/null +++ b/chat_template.jinja @@ -0,0 +1,355 @@ +{#- ----------‑‑‑ special token variables ‑‑‑---------- -#} +{%- set HYTK = ':opensource' %} +{%- set hy_start_token = '<|hy_start{}|>'.format(HYTK) %} +{%- set hy_middle_token = '<|hy_middle{}|>'.format(HYTK) %} +{%- set hy_end_token = '<|hy_end{}|>'.format(HYTK) %} +{%- set image_start_token = '<|hy_image▁start{}|>'.format(HYTK) %} +{%- set image_pad_token = '<|hy_image▁pad{}|>'.format(HYTK) %} +{%- set image_end_token = '<|hy_image▁end{}|>'.format(HYTK) %} +{%- set video_start_token = '<|hy_video▁start{}|>'.format(HYTK) %} +{%- set video_pad_token = '<|hy_video▁pad{}|>'.format(HYTK) %} +{%- set video_end_token = '<|hy_video▁end{}|>'.format(HYTK) %} +{%- set think_begin_token = ''.format(HYTK) %} +{%- set think_end_token = ''.format(HYTK) %} +{%- set toolcalls_begin_token = ''.format(HYTK) %} +{%- set toolcalls_end_token = ''.format(HYTK) %} +{%- set toolcall_begin_token = ''.format(HYTK) %} +{%- set toolcall_end_token = ''.format(HYTK) %} +{%- set argkey_begin_token = ''.format(HYTK) %} +{%- set argkey_end_token = ''.format(HYTK) %} +{%- set argvalue_begin_token = ''.format(HYTK) %} +{%- set argvalue_end_token = ''.format(HYTK) %} +{%- set toolresponse_begin_token = ''.format(HYTK) %} +{%- set toolresponse_end_token = ''.format(HYTK) %} +{%- set reasoning_mode_token = '<|reasoning_mode{}|>'.format(HYTK) %} + +{#- ----------‑‑‑ hyperparameters variables ‑‑‑---------- -#} +{%- if not add_generation_prompt is defined %} + {%- set add_generation_prompt = false %} +{%- endif %} +{%- if not preserved_thinking is defined %} + {%- if not tools %} + {%- set preserved_thinking = false %} + {%- else %} + {%- set preserved_thinking = true %} + {%- endif %} +{%- endif %} + +{%- if not reasoning_effort is defined %} + {%- set reasoning_effort = 'high' %} +{%- elif reasoning_effort not in ['no_think', 'high'] %} + {%- if reasoning_effort is none %} + {{- raise_exception('reasoning_effort error : None, should be no_think/high') }} + {%- else %} + {{- raise_exception('reasoning_effort error : ' + reasoning_effort + ', should be no_think/high') }} + {%- endif %} +{%- endif %} + +{%- if fallback_strategy is defined and fallback_strategy == 'reasoning_toolcall_retry' %} + {%- set reasoning_effort = 'high' %} + {%- set add_generation_prompt = false %} +{%- endif %} +{%- if not raw_last_assistant is defined %} + {%- set raw_last_assistant = false %} +{%- endif %} +{%- if not add_vision_id is defined %} + {%- set add_vision_id = false %} +{%- endif %} +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} + +{%- macro tool_to_json(tool) -%} + {%- set ns_tool = namespace(first=true) -%} + {{- '{' -}} + {%- for k, v in tool.items() -%} + {%- if k != 'defer_loading' and k != 'strict' -%} + {%- if not ns_tool.first -%}{{- ', ' -}}{%- endif -%} + {%- set ns_tool.first = false -%} + {{- '"' ~ k ~ '": ' ~ (v | tojson(ensure_ascii=False)) -}} + {%- endif -%} + {%- endfor -%} + {{- '}' -}} +{%- endmacro -%} + +{%- macro render_content(content, do_vision_count=true, is_system_content=false) -%} + {%- if content is string -%} + {{- content -}} + {%- elif content is iterable and content is not mapping -%} + {%- for item in content -%} + {%- if item is mapping and item.type == 'text' -%} + {{- item.text -}} + {%- elif item is mapping and ('image' in item or 'image_url' in item or item.type in ['image', 'image_url']) -%} + {%- if is_system_content -%} + {{- raise_exception('System message cannot contain images.') -}} + {%- endif -%} + {%- if do_vision_count -%} + {%- set image_count.value = image_count.value + 1 -%} + {%- endif -%} + {%- if add_vision_id -%} + {{- 'Picture ' ~ image_count.value ~ ': ' -}} + {%- endif -%} + {{- image_start_token ~ image_pad_token ~ image_end_token -}} + {%- elif item is mapping and ('video' in item or 'video_url' in item or item.type in ['video', 'video_url']) -%} + {%- if is_system_content -%} + {{- raise_exception('System message cannot contain videos.') -}} + {%- endif -%} + {%- if do_vision_count -%} + {%- set video_count.value = video_count.value + 1 -%} + {%- endif -%} + {%- if add_vision_id -%} + {{- 'Video ' ~ video_count.value ~ ': ' -}} + {%- endif -%} + {{- video_start_token ~ video_pad_token ~ video_end_token -}} + {%- elif item is string -%} + {{- item -}} + {%- else -%} + {{- item | string -}} + {%- endif -%} + {%- endfor -%} + {%- elif content is none -%} + {{- '' -}} + {%- else -%} + {{- content | string -}} + {%- endif -%} +{%- endmacro -%} + +{%- macro render_tools_prompt() -%} + {{- '# Tools\n\nYou may call one or more functions to assist with the user query.' -}} + {{- '\n\nYou are provided with function signatures within XML tags:' -}} + {{- '\n\n' -}} + {%- set tool_ns = namespace(first=true) -%} + {%- for tool in tools -%} + {%- set t = tool['function'] if tool is mapping and 'function' in tool else tool -%} + {%- if t.defer_loading is not defined or not t.defer_loading -%} + {%- if not tool_ns.first -%}{{- '\n' -}}{%- endif -%} + {%- set tool_ns.first = false -%} + {{- tool_to_json(t) -}} + {%- endif -%} + {%- endfor -%} + {{- '\n\n\n' -}} + {{- 'For function call returns, you should first print ' ~ toolcalls_begin_token -}} + {{- '\nFor each function call, you should return object like:\n' -}} + {{- toolcall_begin_token ~ '{function-name}' -}} + {{- argkey_begin_token ~ '{arg-key-1}' ~ argkey_end_token -}} + {{- argvalue_begin_token ~ '{arg-value-1}' ~ argvalue_end_token -}} + {{- argkey_begin_token ~ '{arg-key-2}' ~ argkey_end_token -}} + {{- argvalue_begin_token ~ '{arg-value-2}' ~ argvalue_end_token -}} + {{- '...' -}} + {{- toolcall_end_token -}} + {{- '\nAt the end of function call returns, you should print ' ~ toolcalls_end_token -}} +{%- endmacro -%} + +{#- adjacent tool_search_output parts share one block, so a tool search result has the same shape as the tools prompt -#} +{%- macro render_tool_response(message) -%} + {%- set content = message['content'] -%} + {{- toolresponse_begin_token -}} + {%- if content is string -%} + {{- content -}} + {%- elif content is iterable and content is not mapping -%} + {%- set tools_ns = namespace(open=false) -%} + {%- for item in content -%} + {%- set is_search_output = item is mapping and item.type is defined and item.type == 'tool_search_output' -%} + {%- if is_search_output and not tools_ns.open -%} + {{- '\n' -}} + {%- set tools_ns.open = true -%} + {%- elif not is_search_output and tools_ns.open -%} + {{- '' -}} + {%- set tools_ns.open = false -%} + {%- endif -%} + {%- if is_search_output -%} + {%- if item.tools is defined and item.tools is iterable -%} + {%- for tool in item.tools -%} + {%- set t = tool['function'] if tool is mapping and 'function' in tool else tool -%} + {{- tool_to_json(t) ~ '\n' -}} + {%- endfor -%} + {%- endif -%} + {%- elif item is mapping and item.output is defined -%} + {{- render_content(item.output) -}} + {%- else -%} + {{- render_content([item]) -}} + {%- endif -%} + {%- endfor -%} + {%- if tools_ns.open -%} + {{- '' -}} + {%- endif -%} + {%- else -%} + {{- render_content(content) -}} + {%- endif -%} + {{- toolresponse_end_token -}} +{%- endmacro -%} + +{#- consecutive tool messages are clustered into a single tool message whose content is the list of the original tool messages; the result is written to merged_ns.messages (a macro cannot return a list) -#} +{%- set merged_ns = namespace(messages=[]) %} +{%- macro merge_tool_responses(messages) -%} + {%- set merge_ns = namespace(result=[], cluster=[]) -%} + {%- for message in messages -%} + {%- if message['role'] == 'tool' -%} + {%- set merge_ns.cluster = merge_ns.cluster + [message] -%} + {%- else -%} + {%- if merge_ns.cluster -%} + {%- set merge_ns.result = merge_ns.result + [{'role': 'tool', 'content': merge_ns.cluster}] -%} + {%- set merge_ns.cluster = [] -%} + {%- endif -%} + {%- set merge_ns.result = merge_ns.result + [message] -%} + {%- endif -%} + {%- endfor -%} + {%- if merge_ns.cluster -%} + {%- set merge_ns.result = merge_ns.result + [{'role': 'tool', 'content': merge_ns.cluster}] -%} + {%- endif -%} + {%- set merged_ns.messages = merge_ns.result -%} +{%- endmacro -%} + +{#- render one tool cluster, reordered to follow the tool_call order of the preceding assistant turn; any missing / ambiguous id falls back to the original tool message order for the whole cluster -#} +{%- macro render_tool_responses(tool_messages, tool_call_ids) -%} + {%- set order_ns = namespace(ordered=[], matched=true) -%} + {%- if tool_call_ids and tool_call_ids | length == tool_messages | length -%} + {%- for tool_call_id in tool_call_ids -%} + {%- set hit_ns = namespace(count=0, message=none) -%} + {%- for tool_message in tool_messages -%} + {%- set message_id = tool_message['tool_call_id'] if tool_message['tool_call_id'] is defined else tool_message['id'] -%} + {%- if message_id is defined and message_id == tool_call_id -%} + {%- set hit_ns.count = hit_ns.count + 1 -%} + {%- set hit_ns.message = tool_message -%} + {%- endif -%} + {%- endfor -%} + {%- if hit_ns.count == 1 -%} + {%- set order_ns.ordered = order_ns.ordered + [hit_ns.message] -%} + {%- else -%} + {%- set order_ns.matched = false -%} + {%- endif -%} + {%- endfor -%} + {%- else -%} + {%- set order_ns.matched = false -%} + {%- endif -%} + {%- for tool_message in (order_ns.ordered if order_ns.matched else tool_messages) -%} + {{- render_tool_response(tool_message) -}} + {%- endfor -%} +{%- endmacro -%} + +{%- set _ = merge_tool_responses(messages) %} +{%- set normed_messages = merged_ns.messages %} + +{%- set ns = namespace(last_user_index=-1, has_leading_system=false) %} +{%- if normed_messages and normed_messages[0].role == 'system' %} + {%- set ns.has_leading_system = true %} +{%- endif %} +{%- for message in normed_messages %} + {%- if message['role'] == 'user' %} + {%- set ns.last_user_index = loop.index0 %} + {%- endif %} +{%- endfor %} + +{#- no leading system: synthesize one for tools and/or reasoning_mode -#} +{%- if not ns.has_leading_system %} + {{- hy_start_token ~ 'system' ~ hy_middle_token -}} + {%- if tools %} + {{- render_tools_prompt() -}} + {%- endif %} + {{- reasoning_mode_token ~ 'reasoning_effort:' ~ reasoning_effort -}} + {{- hy_end_token -}} +{%- endif %} + +{%- set last_ns = namespace(last_is_assistant=false) %} +{%- set prev_ns = namespace(tool_call_ids=[]) %} +{%- for message in normed_messages %} + {%- if message['role'] == 'system' %} + {{- hy_start_token ~ 'system' ~ hy_middle_token -}} + {#- tools / reasoning_mode only attach to the leading system (messages[0]) -#} + {%- if loop.first %} + {%- if tools %} + {{- render_tools_prompt() -}} + {%- endif %} + {%- set content = render_content(message['content']) -%} + {%- if tools and content -%} + {{- '\n\n' -}} + {%- endif -%} + {{- content -}} + {{- reasoning_mode_token ~ 'reasoning_effort:' ~ reasoning_effort -}} + {%- else %} + {{- render_content(message['content']) -}} + {%- endif %} + {{- hy_end_token -}} + {%- elif message['role'] == 'user' %} + {{- hy_start_token ~ 'user' ~ hy_middle_token -}} + {{- render_content(message['content']) -}} + {{- hy_end_token -}} + {%- elif message['role'] == 'assistant' %} + {%- set content_body = render_content(message['content']) -%} + {#- 'reasoning' takes precedence, fall back to 'reasoning_content' when it is empty -#} + {%- set reasoning_text = '' %} + {%- if message['reasoning'] is defined and message['reasoning'] is string and message['reasoning'] %} + {%- set reasoning_text = message['reasoning'] %} + {%- elif message['reasoning_content'] is defined and message['reasoning_content'] is string and message['reasoning_content'] %} + {%- set reasoning_text = message['reasoning_content'] %} + {%- endif %} + {#- no_think overrides preserved_thinking: history is always emitted with empty think tags -#} + {%- if reasoning_effort != 'no_think' and (preserved_thinking or loop.index0 > ns.last_user_index) and reasoning_text %} + {%- set content = think_begin_token ~ reasoning_text ~ think_end_token ~ content_body %} + {%- else %} + {%- set content = think_begin_token ~ think_end_token ~ content_body %} + {%- endif %} + {{- hy_start_token ~ 'assistant' ~ hy_middle_token -}} + {%- if message['tool_calls'] is defined and message['tool_calls'] %} + {#- remember the tool_call ids of this turn to order the following tool responses; an incomplete id set means "do not reorder" -#} + {%- set ids_ns = namespace(ids=[], complete=true) %} + {%- for tool in message['tool_calls'] %} + {%- set tool_call_id = tool['id'] if tool['id'] is defined and tool['id'] else tool['tool_call_id'] %} + {%- if tool_call_id is defined and tool_call_id %} + {%- set ids_ns.ids = ids_ns.ids + [tool_call_id] %} + {%- else %} + {%- set ids_ns.complete = false %} + {%- endif %} + {%- endfor %} + {%- set prev_ns.tool_call_ids = ids_ns.ids if ids_ns.complete else [] %} + {{- content -}} + {{- toolcalls_begin_token -}} + {%- for tool in message['tool_calls'] -%} + {%- set func = tool['function'] if tool is mapping and 'function' in tool else tool -%} + {%- set arguments = func['arguments'] -%} + {{- toolcall_begin_token ~ func['name'] -}} + {%- for key, value in arguments.items() -%} + {{- argkey_begin_token ~ key ~ argkey_end_token -}} + {%- if value is not string -%} + {%- set value = value | tojson(ensure_ascii=False) -%} + {%- endif -%} + {{- argvalue_begin_token ~ value ~ argvalue_end_token -}} + {%- endfor -%} + {{- toolcall_end_token -}} + {%- endfor -%} + {{- toolcalls_end_token -}} + {%- else %} + {%- if loop.last and raw_last_assistant %} + {{- content_body -}} + {%- else %} + {{- content -}} + {%- endif %} + {%- endif %} + {#- continuation / prefill: last assistant is still open, do not close with hy_end -#} + {%- if not (loop.last and raw_last_assistant) and not (loop.last and fallback_strategy is defined and fallback_strategy == 'reasoning_toolcall_retry') %} + {{- hy_end_token -}} + {%- endif %} + {%- elif message['role'] == 'tool' %} + {{- hy_start_token ~ 'tool' ~ hy_middle_token -}} + {{- render_tool_responses(message['content'], prev_ns.tool_call_ids) -}} + {{- hy_end_token -}} + {%- else %} + {{- hy_start_token ~ message['role'] ~ hy_middle_token -}} + {{- render_content(message['content']) -}} + {{- hy_end_token -}} + {%- endif %} + {%- if message['role'] != 'assistant' or not (message['tool_calls'] is defined and message['tool_calls']) %} + {%- set prev_ns.tool_call_ids = [] %} + {%- endif %} + {%- if loop.last and message['role'] == 'assistant' %} + {%- set last_ns.last_is_assistant = true %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {%- if not last_ns.last_is_assistant %} + {%- if reasoning_effort == 'no_think' %} + {{- hy_start_token ~ 'assistant' ~ hy_middle_token ~ think_begin_token ~ think_end_token -}} + {%- else %} + {{- hy_start_token ~ 'assistant' ~ hy_middle_token ~ think_begin_token -}} + {%- endif %} + {%- endif %} +{%- endif %} diff --git a/config.json b/config.json new file mode 100644 index 0000000000000000000000000000000000000000..a046c544421fca6a7eacb0e606ffbd8b972db6cb --- /dev/null +++ b/config.json @@ -0,0 +1,512 @@ +{ + "architectures": [ + "HYV4VLForConditionalGeneration" + ], + "attention_bias": false, + "attention_dropout": 0.0, + "bitwise_backward_align": false, + "bos_token_id": 120000, + "enable_ihc": true, + "enable_lm_head_fp32": true, + "eos_token_id": 120025, + "first_k_dense_replace": 1, + "gated_mla": true, + "gating_type": "elementwise", + "hc_eps": 1e-06, + "hc_magnitude": 2.0, + "hc_mult": 4, + "head_dim": 64, + "hidden_act": "silu", + "hidden_size": 6144, + "image_end_token_id": 120119, + "image_newline_token_id": 120121, + "image_start_token_id": 120118, + "image_token_id": 120120, + "index_head_dim": 128, + "index_n_heads": 32, + "index_topk": 2048, + "indexer_types": [ + "full", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full" + ], + "initializer_range": 0.006, + "intermediate_size": 18432, + "kv_lora_rank": 512, + "learnable_sink": true, + "learnable_sink_init": 0.0, + "max_position_embeddings": 1048576, + "model_type": "hy_v4_vl", + "moe_intermediate_size": 2048, + "n_group": 1, + "n_routed_experts": 256, + "n_shared_experts": 1, + "norm_topk_prob": true, + "num_attention_heads": 64, + "num_experts_per_tok": 8, + "num_hidden_layers": 78, + "num_key_value_heads": 8, + "num_nextn_predict_layers": 0, + "pad_token_id": 120002, + "q_lora_rank": 2048, + "qk_head_dim": 256, + "qk_nope_head_dim": 192, + "qk_norm": true, + "qk_rope_head_dim": 64, + "rms_norm_eps": 1e-05, + "rope_parameters": { + "mrope_interleaved": true, + "mrope_section": [ + 12, + 10, + 10 + ], + "rope_theta": 10000000, + "rope_type": "default" + }, + "routed_scaling_factor": 2.827, + "swiglu_limit": 10.0, + "text_config": { + "architectures": [ + "HYV4VLForConditionalGeneration" + ], + "attention_bias": false, + "attention_dropout": 0.0, + "bitwise_backward_align": false, + "bos_token_id": 120000, + "enable_ihc": true, + "enable_lm_head_fp32": true, + "eos_token_id": 120025, + "first_k_dense_replace": 1, + "gated_mla": true, + "gating_type": "elementwise", + "hc_eps": 1e-06, + "hc_magnitude": 2.0, + "hc_mult": 4, + "head_dim": 64, + "hidden_act": "silu", + "hidden_size": 6144, + "image_newline_token_id": 120121, + "index_head_dim": 128, + "index_n_heads": 32, + "index_topk": 2048, + "indexer_types": [ + "full", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full", + "shared", + "shared", + "shared", + "full" + ], + "initializer_range": 0.006, + "intermediate_size": 18432, + "kv_lora_rank": 512, + "layer_types": [ + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "deepseek_sparse_attention" + ], + "learnable_sink": true, + "learnable_sink_init": 0.0, + "max_position_embeddings": 1048576, + "mlp_layer_types": [ + "dense", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse" + ], + "model_type": "hy_v4", + "moe_intermediate_size": 2048, + "n_group": 1, + "n_routed_experts": 256, + "n_shared_experts": 1, + "norm_topk_prob": true, + "num_attention_heads": 64, + "num_experts_per_tok": 8, + "num_hidden_layers": 78, + "num_key_value_heads": 8, + "num_nextn_predict_layers": 0, + "pad_token_id": 120002, + "q_lora_rank": 2048, + "qk_head_dim": 256, + "qk_nope_head_dim": 192, + "qk_norm": true, + "qk_rope_head_dim": 64, + "rms_norm_eps": 1e-05, + "rope_parameters": { + "mrope_interleaved": true, + "mrope_section": [ + 12, + 10, + 10 + ], + "rope_theta": 10000000, + "rope_type": "default" + }, + "routed_scaling_factor": 2.827, + "swiglu_limit": 10.0, + "tie_word_embeddings": false, + "topk_group": 1, + "use_cache": true, + "v_head_dim": 256, + "video_token_id": 120124, + "vocab_size": 120832 + }, + "tie_word_embeddings": false, + "topk_group": 1, + "transformers_version": "5.24.0", + "v_head_dim": 256, + "video_end_token_id": 120123, + "video_start_token_id": 120122, + "video_token_id": 120124, + "vision_config": { + "add_patchemb_bias": true, + "anyres_vit_max_image_size": 2048, + "attention_dropout": 0.0, + "cat_extra_token": 0, + "hidden_act": "gelu", + "hidden_dropout": 0.0, + "hidden_size": 1536, + "img_max_token_num": 4096, + "intermediate_size": 6144, + "interpolate_mode": "bilinear", + "learnable_mlp_pooling_size": 0, + "max_image_size": 2048, + "max_vit_seq_len": 16384, + "min_image_size": 512, + "model_type": "hy_v4_vl", + "num_attention_heads": 16, + "num_channels": 3, + "num_hidden_layers": 40, + "num_key_value_heads": 16, + "out_hidden_size": 6144, + "patch_size": 16, + "perceive_post_norm": false, + "perceive_pre_norm": true, + "projector_type": "rmsnorm_mlp_adapter", + "remove_prenorm": true, + "resize_resolution": 2048, + "rms_norm_eps": 1e-05, + "rope_2d_percent": 1.0, + "rope_2d_theta": 10000.0, + "spatial_merge_size": 2, + "spatial_patch_size": 1, + "temporal_patch_size": 1, + "text_hidden_size": 6144, + "video_max_image_size": 768, + "video_min_image_size": 256, + "video_spatial_compression": false, + "video_temporal_compression": false, + "vision_full_attention": false + }, + "vocab_size": 120832, + "dtype": "bfloat16", + "dfly_enable_ihc": false, + "dfly_mtp_fusion": "slot0", + "dfly_target_index_topk": 2048, + "dfly_context_local_window": null, + "dfly_enable_hidden_correction": true, + "dfly_num_hidden_layers": 5, + "dfly_mlp_type": "dense", + "dfly_mask_token_id": 120009, + "dfly_target_index_layer": [61, 65, 69, 73, 77], + "dfly_target_kv_layers": [61, 65, 69, 73, 77], + "dfly_attn_causal": true, + "dfly_block_size": 7 +} diff --git a/finetune/README.md b/finetune/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bb9556c81361f9242488ffb3b9637f583e6ff3e8 --- /dev/null +++ b/finetune/README.md @@ -0,0 +1,590 @@ +

+ 中文 | English +

+ +# Model Fine-tuning + +Hy4 provides processes related to model fine-tuning. This section details how to process training data for model fine-tuning purposes. + +## Training Data Format and Processing + +**Hy4 supports two thinking modes, controlled by the `reasoning_effort` parameter (only `no_think` and `high` are accepted; any other value raises an error). The available options are**: + +| `reasoning_effort` | Mode | Description | +|---|---|---| +| `no_think` | Fast thinking | No reasoning process; the model directly outputs the answer. | +| `high` | Deep thinking | Thorough reasoning with a detailed thinking process. | + +The training data should be formatted as a list of messages shown below. By default, the system prompt for both training and inference is empty; customize it as needed. + +For `high` mode, the assistant's reasoning process can be provided in the `reasoning_content` field (the `chat_template` also accepts a `reasoning` field, which takes precedence); in `no_think` mode the template always emits empty `` tags, so no reasoning field is needed. + +```jsonl +# Fast thinking pattern (no_think) — no reasoning field +{"reasoning_effort": "no_think", "messages": [{"content": "You are a helpful assistant.\nThe current time is 2026-01-01 13:26:12 Thursday", "role": "system"}, {"content": "1+1=?", "role": "user"}, {"role": "assistant", "content": "1+1=2"}]} + +# Deep thinking pattern (high) — with reasoning content +{"reasoning_effort": "high", "messages": [{"content": "You are a helpful assistant.\nThe current time is 2026-01-01 13:26:12 Thursday", "role": "system"}, {"content": "1+1=?", "role": "user"}, {"role": "assistant", "content": "1+1=2", "reasoning_content": "The user is asking for the result of 1 + 1. In basic decimal arithmetic, 1 + 1 equals 2."}]} +``` + +> **`reasoning_effort` default values:** +> - **During training**: If `reasoning_effort` is not specified in the training data, the training script defaults to `no_think` (fast thinking). This is because samples without a reasoning field are treated as non-thinking-mode data by the training script. +> - **During inference**: If `reasoning_effort` is not passed when calling `apply_chat_template`, the `chat_template` defaults to `high` (deep thinking). + +Example of using `apply_chat_template` to tokenize: + +```python +from transformers import AutoTokenizer +tokenizer = AutoTokenizer.from_pretrained("./models", use_fast=False, trust_remote_code=True) + +messages = [ + {"content": "You are a helpful assistant.", "role": "system"}, + {"content": "1+1=?", "role": "user"}, + {"role": "assistant", "content": "1+1=2"} +] +ids = tokenizer.apply_chat_template(messages, tokenize=True, reasoning_effort="no_think") +``` + +### Multimodal Data Format (Image / Video) + +Hy4 supports mixed training with images, videos, and pure text. The data format is JSONL, with one sample per line. + +#### Image Data + +Use the `` tag in the user message to mark the image position, and provide the image path list in the `images` field: + +```json +{"messages": [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Please describe this image in detail."}, {"role": "assistant", "content": "The image shows a beautiful sunset over the ocean."}], "images": ["test_images/sunset.jpg"]} +``` + +Multiple images are supported — use multiple `` tags and provide the corresponding paths in the `images` list (in order): + +```json +{"messages": [{"role": "user", "content": "Compare the first image with the second one."}], "images": ["img1.jpg", "img2.jpg"]} +``` + +#### Video Data + +Use the `