Automatic Speech Recognition
Transformers
Safetensors
Chinese
English
ming_v3_asr
text-generation
audio
speech-recognition
contextual-asr
custom_code
Run this model with HF Jobs
Run ml-resources/Ming-3.0-asr-tiny on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/ml-resources/Ming-3.0-asr-tiny. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/ml-resources/Ming-3.0-asr-tiny on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use ml-resources/Ming-3.0-asr-tiny with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use ml-resources/Ming-3.0-asr-tiny with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("automatic-speech-recognition", model="ml-resources/Ming-3.0-asr-tiny", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("ml-resources/Ming-3.0-asr-tiny", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Mirror inclusionAI/Ming-3.0-asr-tiny
Browse filesFiles changed (35)
- .gitattributes+9
- CITATION.cffAdded+9
- LICENSEAdded+21
- LICENSE-APACHE-2.0Added+201
- README.mdAdded+160
- README.zh.mdAdded+146
- WHISPER_LICENSEAdded+21
- asr_request.pyAdded+39
- audio_spec.pyAdded+127
- chat_format.pyAdded+904
- chat_template.jinjaAdded+57
- config.jsonAdded+87
- configuration_ming_v3_asr.pyAdded+293
- examples/transcribe.pyAdded+79
- feature_extraction_ming_v3_asr.pyAdded+235
- figures/asr.pngAdded
- figures/bailing-logo.pngAdded
- figures/contextasr.pngAdded
- figures/model.jpgAdded
- figures/开源asr.pngAdded
- figures/自建asr.pngAdded
- generation_config.jsonAdded+5
- model-00001-of-00002.safetensorsAdded+3
- model-00002-of-00002.safetensorsAdded+3
- model.safetensors.index.jsonAdded
- modeling_ming_v3_asr.pyAdded+2150
- modeling_ming_v3_asr_encoder.pyAdded+89
- modeling_whisper_encoder.pyAdded+141
- preprocessor_config.jsonAdded+28
- processing_ming_v3_asr.pyAdded+248
- requirements.txtAdded+11
- special_tokens_map.jsonAdded+44
- tokenization_bailing.pyAdded+1155
- tokenizer.jsonAdded+3
- tokenizer_config.jsonAdded+2342
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines33343536373839404142434432 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -textfigures/model.jpg filter=lfs diff=lfs merge=lfs -textfigures/开源asr.jpg filter=lfs diff=lfs merge=lfs -textfigures/自建asr.jpg filter=lfs diff=lfs merge=lfs -textfigures/开源asr.png filter=lfs diff=lfs merge=lfs -textfigures/自建asr.png filter=lfs diff=lfs merge=lfs -textfigures/contextasr.png filter=lfs diff=lfs merge=lfs -textfigures/asr.png filter=lfs diff=lfs merge=lfs -textmedia/ming-3.0-asr-tiny-intro.en.mp4 filter=lfs diff=lfs merge=lfs -text
123456789cff-version: 1.2.0message: "If you use Ming-3.0-asr-tiny, please cite this model repository."title: "Ming-3.0-asr-tiny: Context-Aware Speech Recognition"type: softwareauthors: - name: inclusionAIlicense: MITurl: "https://github.com/inclusionAI/Ming-3.0-asr"repository-code: "https://github.com/inclusionAI/Ming-3.0-asr"123456789101112131415161718192021MIT License
Copyright (c) 2026 inclusionAI
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, 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 THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
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 9 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).
"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.
"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.
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.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160---library_name: transformerslicense: mitpipeline_tag: automatic-speech-recognitionlanguage:- zh- entags:- audio- speech-recognition- contextual-asr---> Mirror of [inclusionAI/Ming-3.0-asr-tiny](https://huggingface.co/inclusionAI/Ming-3.0-asr-tiny). All credit to the original authors. Not an official release from them. License unchanged (mit); see `LICENSE`, `LICENSE-APACHE-2.0`, `WHISPER_LICENSE`.
<div align="center"> <img src="./figures/bailing-logo.png" width="60" alt="Bailing logo" /> <h1>Ming-3.0-asr-tiny</h1> <p><i>Context-aware speech recognition for Chinese, English, and dialects.</i></p></div>
English · [简体中文](https://huggingface.co/inclusionAI/Ming-3.0-asr-tiny/blob/main/README.zh.md)
[GitHub code and cookbook](https://github.com/inclusionAI/Ming-3.0-asr) · [Quick Start](#quick-start) · [Evaluation](#evaluation)
**Ming-3.0-asr-tiny** combines the Ling-tiny-v3 language backbone with an audio encoder. It transcribes single-turn Chinese and English speech, covers regional dialects, and can use hotwords or preceding dialogue to improve recognition of domain-specific terms. This repository includes the model weights, tokenizer, custom Transformers implementation, and runnable inference example.
## Capabilities
- **Chinese and English ASR:** speech-to-text transcription through one model interface.- **Dialect recognition:** evaluated on 15 regional dialect test sets, including Cantonese, Minnan, and Shanghainese.- **Context ASR:** accepts relevant hotwords or dialogue context as part of the transcription prompt.- **Challenging speech:** evaluated on noisy speech and five application domains.
## Architecture
<p align="center"><img src="./figures/model.jpg" width="850" alt="Ming-3.0-asr-tiny architecture" /></p>
## Quick Start
### Download and install
Use Python 3.12 on a Linux machine with a compatible CUDA GPU. Download the complete checkpoint and install its dependencies, including PyTorch and torchaudio:
```bashpython -m pip install "huggingface_hub[cli]"hf download inclusionAI/Ming-3.0-asr-tiny --local-dir Ming-3.0-asr-tinycd Ming-3.0-asr-tinypython -m pip install -r requirements.txt```
### Run the PyTorch / Transformers example
```bashpython examples/transcribe.py \ --model . \ --audio /path/to/speech.wav```
Add `--language-hint zh` or `--language-hint en` when the language is known. The example uses CUDA, BF16, SDPA, greedy decoding, and up to 256 new tokens; it loads the bundled model code with `trust_remote_code=True`. The dependency versions are listed in `requirements.txt`, including Transformers 5.12.1, fla-core 0.5.2, and PyTorch 2.11.0. For another CUDA version, first install matching PyTorch and torchaudio 2.11.0 wheels using the [official PyTorch instructions](https://pytorch.org/get-started/previous-versions/), then run `pip install -r requirements.txt`.
### PyTorch / Transformers Python API
Run this directly from the downloaded model directory with your own `speech.wav`. It is the same inference path as the bundled [executable example](./examples/transcribe.py):
```pythonimport soundfile as sfimport torchfrom transformers import AutoModelForCausalLM, AutoProcessorfrom asr_request import decode_transcript, prepare_asr_request
processor = AutoProcessor.from_pretrained(".", trust_remote_code=True)model = AutoModelForCausalLM.from_pretrained( ".", trust_remote_code=True, dtype=torch.bfloat16, device_map="cuda:0", attn_implementation="sdpa",).eval()waveform, rate = sf.read("speech.wav", dtype="float32", always_2d=True)inputs = prepare_asr_request( processor, (waveform.T, rate), return_tensors="pt",).to(model.device)eos = model.config.text_config.eos_token_idwith torch.inference_mode(): output = model.generate( **inputs, max_new_tokens=256, do_sample=False, eos_token_id=eos, pad_token_id=eos, no_repeat_ngram_size=10, )print(decode_transcript( processor.tokenizer, output[0, inputs.input_ids.shape[1]:].tolist(),))```
### Context ASR
Ordinary transcription and Context ASR use the same input format. Append the topic and hotwords directly to the base instruction, without a newline. For known-language clips up to 60 seconds, `--context-chunks` selects 3000 mel frames up to 30 seconds and 6000 beyond 30 seconds:
```bashpython examples/transcribe.py --model . --audio /path/to/speech.wav \ --language-hint zh --context-chunks \ --prompt $'Please recognize the language of this speech and transcribe it, placing a `\t` between the identified language and the transcribe.This is an audio about 电影蜥蜴.This audio may contains the following words or phrases:蜥蜴,姜知垠,曹承佑,姜惠贞,八音盒.'```
For English, use `--language-hint en`. The topic and hotwords above are illustrative. Dialogue context can also be included in the prompt text. For Python calls, pass the full prompt through `prepare_asr_request(..., prompt=...)`.
### SGLang serving
For GPU serving, see the [Ming SGLang adapter](https://github.com/inclusionAI/sglang_ling_v3/tree/ling_v3_audio_for_pr) and the [ASR serving guide](https://github.com/inclusionAI/Ming-3.0-asr/blob/main/cookbook/sglang/README.en.md), which includes pinned adapter patches, environment setup, a server launcher, and client examples. Once the server is running, transcribe a WAV file through its audio endpoint:
```bashcurl --fail-with-body --max-time 600 \ http://127.0.0.1:8000/v1/audio/transcriptions \ -F 'file=@/path/to/speech.wav' -F 'model=ming-asr' \ -F 'response_format=json' -F 'temperature=0'```
The response contains a `text` field. The cookbook also covers dataset evaluation settings.
## Evaluation
### ASR Overview
<p align="center"><img src="./figures/asr.png" width="1000" alt="ASR performance overview" /></p>
[Watch the Ming-3.0-asr-tiny release film](https://github.com/NiniAndy/Ming-3.0-asr-tiny-blog/releases/download/media-2026-10-19/ming-3.0-asr-final.mp4)
### Chinese and English ASR
<p align="center"><img src="./figures/开源asr.png" width="1000" alt="Chinese and English ASR evaluation" /></p>
### Dialects and Domains
<p align="center"><img src="./figures/自建asr.png" width="1000" alt="Dialect and domain ASR evaluation" /></p>
### Context ASR
<p align="center"><img src="./figures/contextasr.png" width="1000" alt="Context ASR evaluation" /></p>
## Usage Notes
- Output is transcription text, without word-level timestamps or speaker diarization.- The included example does not support streaming input; image and video inputs are unsupported.- Long audio can be encoded in chunks with `--audio-chunk-frames`, subject to the model context limit.- Hotwords are hints, not a guarantee that a term will appear in the transcript.
For local Transformers inference, run the bundled [PyTorch example](./examples/transcribe.py).
## License
The model weights and original project code are released under the [MIT License](./LICENSE), following the [Ming project](https://github.com/inclusionAI/Ming). Bundled Apache-2.0 source files retain their own headers and [license text](./LICENSE-APACHE-2.0). `modeling_whisper_encoder.py` retains the MIT notice for code adapted from OpenAI Whisper.
## Citation
If you use Ming-3.0-asr-tiny, cite the [GitHub repository](https://github.com/inclusionAI/Ming-3.0-asr). Citation metadata is also available in [CITATION.cff](./CITATION.cff).
```bibtex@misc{ming_3_0_asr_tiny_2026, author = {{inclusionAI}}, title = {Ming-3.0-asr-tiny: Context-Aware Speech Recognition}, year = {2026}, url = {https://github.com/inclusionAI/Ming-3.0-asr}}```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146<div align="center"> <img src="./figures/bailing-logo.png" width="60" alt="百灵 Logo" /> <h1>Ming-3.0-asr-tiny</h1> <p><i>听懂中英文、方言,也听懂上下文。</i></p></div>
[English](https://huggingface.co/inclusionAI/Ming-3.0-asr-tiny) · 简体中文
[GitHub 代码与教程](https://github.com/inclusionAI/Ming-3.0-asr) · [快速开始](#快速开始) · [评测](#评测)
**Ming-3.0-asr-tiny** 基于 Ling-tiny-v3 语言模型与音频编码器构建,支持单轮中英文语音转写、方言识别,并可利用热词或对话上文改善领域术语识别。本仓库提供完整权重、tokenizer、Transformers 自定义实现和可运行的推理示例。
## 模型能力
- **中英文语音识别:** 使用统一接口将语音转写为文本。- **方言识别:** 在包括粤语、闽南语、上海话在内的 15 组地区方言测试集上评测。- **Context ASR:** 可在转写提示中加入相关热词或对话上文。- **复杂场景:** 覆盖高噪语音及五类应用领域评测。
## 模型架构
<p align="center"><img src="./figures/model.jpg" width="850" alt="Ming-3.0-asr-tiny 模型架构" /></p>
## 快速开始
### 下载与安装
使用 Python 3.12 和兼容 CUDA 的 Linux GPU。下载完整模型后,安装模型依赖,包括 PyTorch 与 torchaudio:
```bashpython -m pip install "huggingface_hub[cli]"hf download inclusionAI/Ming-3.0-asr-tiny --local-dir Ming-3.0-asr-tinycd Ming-3.0-asr-tinypython -m pip install -r requirements.txt```
### 运行 PyTorch / Transformers 推理脚本
```bashpython examples/transcribe.py \ --model . \ --audio /path/to/speech.wav```
已知语种时可加 `--language-hint zh` 或 `--language-hint en`。示例使用 CUDA、BF16、SDPA、greedy decoding,最多生成 256 个新 token,并通过 `trust_remote_code=True` 加载仓库内的自定义实现。依赖版本见 `requirements.txt`,其中包括 Transformers 5.12.1、fla-core 0.5.2 和 PyTorch 2.11.0。若需其他 CUDA 版本,先按 [PyTorch 官方说明](https://pytorch.org/get-started/previous-versions/)安装匹配的 PyTorch 与 torchaudio 2.11.0 wheel,再运行 `pip install -r requirements.txt`。
### PyTorch / Transformers Python 示例
在下载后的模型目录运行,并将 `speech.wav` 换成自己的音频文件。该代码与仓库内的[可执行示例](./examples/transcribe.py)使用同一推理路径:
```pythonimport soundfile as sfimport torchfrom transformers import AutoModelForCausalLM, AutoProcessorfrom asr_request import decode_transcript, prepare_asr_request
processor = AutoProcessor.from_pretrained(".", trust_remote_code=True)model = AutoModelForCausalLM.from_pretrained( ".", trust_remote_code=True, dtype=torch.bfloat16, device_map="cuda:0", attn_implementation="sdpa",).eval()waveform, rate = sf.read("speech.wav", dtype="float32", always_2d=True)inputs = prepare_asr_request( processor, (waveform.T, rate), return_tensors="pt",).to(model.device)eos = model.config.text_config.eos_token_idwith torch.inference_mode(): output = model.generate( **inputs, max_new_tokens=256, do_sample=False, eos_token_id=eos, pad_token_id=eos, no_repeat_ngram_size=10, )print(decode_transcript( processor.tokenizer, output[0, inputs.input_ids.shape[1]:].tolist(),))```
### Context ASR
普通转写和 Context ASR 使用同一输入格式。将主题和热词连续拼接在基础指令之后,不插入换行。对于语种已知、长度不超过 60 秒的音频,`--context-chunks` 会在 30 秒以内选择 3000 mel 帧,超过 30 秒选择 6000 mel 帧:
```bashpython examples/transcribe.py --model . --audio /path/to/speech.wav \ --language-hint zh --context-chunks \ --prompt $'Please recognize the language of this speech and transcribe it, placing a `\t` between the identified language and the transcribe.This is an audio about 电影蜥蜴.This audio may contains the following words or phrases:蜥蜴,姜知垠,曹承佑,姜惠贞,八音盒.'```
英文音频将语言提示改为 `--language-hint en`。这里的主题与热词仅供演示,也可以在提示词中加入对话上文。Python 调用可通过 `prepare_asr_request(..., prompt=...)` 传入完整提示。
### SGLang 加速服务
GPU 服务请参阅 [Ming SGLang 适配仓库](https://github.com/inclusionAI/sglang_ling_v3/tree/ling_v3_audio_for_pr)和 [ASR 服务指南](https://github.com/inclusionAI/Ming-3.0-asr/blob/main/cookbook/sglang/README.en.md),其中包含固定版本适配补丁、环境配置、启动脚本和客户端示例。服务启动后,可通过音频接口转写 WAV 文件:
```bashcurl --fail-with-body --max-time 600 \ http://127.0.0.1:8000/v1/audio/transcriptions \ -F 'file=@/path/to/speech.wav' -F 'model=ming-asr' \ -F 'response_format=json' -F 'temperature=0'```
响应中的 `text` 字段即为转写结果。数据集评测参数见 SGLang 指南。
## 评测
### ASR 整体表现
<p align="center"><img src="./figures/asr.png" width="1000" alt="ASR 整体表现" /></p>
[观看 Ming-3.0-asr-tiny 发版视频](https://github.com/NiniAndy/Ming-3.0-asr-tiny-blog/releases/download/media-2026-10-19/ming-3.0-asr-final.mp4)
### 中英文语音识别
<p align="center"><img src="./figures/开源asr.png" width="1000" alt="开源中英文 ASR 评测" /></p>
### 方言与领域识别
<p align="center"><img src="./figures/自建asr.png" width="1000" alt="方言与领域 ASR 评测" /></p>
### Context ASR
<p align="center"><img src="./figures/contextasr.png" width="1000" alt="Context ASR 评测" /></p>
## 使用说明
- 输出为转写文本,不提供词级时间戳或说话人分离。- 当前示例不支持流式输入;模型不接受图像或视频。- 长音频可用 `--audio-chunk-frames` 分块编码,仍受模型上下文长度限制。- 热词仅是识别提示,不保证输出一定包含指定词语。
本地 Transformers 推理可使用仓库内置的 [PyTorch 示例](./examples/transcribe.py)。
## 许可证
模型权重及项目原创代码采用 [MIT 许可证](./LICENSE),与 [Ming 项目](https://github.com/inclusionAI/Ming)保持一致。模型包中标注 Apache-2.0 的源码保留原有声明和[许可证文本](./LICENSE-APACHE-2.0);`modeling_whisper_encoder.py` 保留基于 OpenAI Whisper 代码的 MIT 声明。
## 引用
如果在研究或产品中使用 Ming-3.0-asr-tiny,请引用 [GitHub 仓库](https://github.com/inclusionAI/Ming-3.0-asr)。[CITATION.cff](./CITATION.cff) 也提供机器可读的引用信息。
```bibtex@misc{ming_3_0_asr_tiny_2026, author = {{inclusionAI}}, title = {Ming-3.0-asr-tiny: Context-Aware Speech Recognition}, year = {2026}, url = {https://github.com/inclusionAI/Ming-3.0-asr}}```123456789101112131415161718192021MIT License
Copyright (c) 2022 OpenAI
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, 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 THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839"""Build the audio request used by Ming-3.0-asr-tiny."""
# The character between the backticks is a literal tab, not a backslash and "t".ASR_INSTRUCTION = ( "Please recognize the language of this speech and transcribe it, " "placing a `\t` between the identified language and the transcribe.")
def prepare_asr_request( processor, audio, *, prompt=None, language_hint=None, audio_chunk_frames=None, return_tensors="pt",): """Prepare audio and context through the processor's single ASR entry point.""" return processor.apply_transcription_request( audio, prompt=prompt, language_hint=language_hint, audio_chunk_frames=audio_chunk_frames, return_tensors=return_tensors, )
def context_chunk_frames(duration_seconds): """Use one encoder chunk for a ContextASR-Bench clip up to 60 seconds.""" if duration_seconds <= 0: raise ValueError("duration_seconds must be positive") if duration_seconds > 60: raise ValueError("Context ASR chunk policy supports clips up to 60 seconds") return 6000 if duration_seconds > 30 else 3000
def decode_transcript(tokenizer, token_ids): """Remove the language envelope from generated text.""" text = tokenizer.decode(token_ids, skip_special_tokens=True).strip() if "\t" in text: return text.split("\t", 1)[1].strip() for language in ("Chinese", "English", "Canton", "Japanese", "Korean"): if text.startswith(language): return text[len(language):].strip() return text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127# Copyright 2026 SGLang Team# Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## 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."""Model-owned Ming audio geometry; no scheduler, tokenizer, or model imports."""
from dataclasses import dataclass
@dataclass(frozen=True)class MingAudioSpec: """Immutable preprocessing and encoder/projector length contract.
``chunk_frames`` is measured before the encoder's stride-two convolution. Chunk output lengths must be rounded separately, including the final chunk. """
n_mels: int = 128 sample_rate: int = 16000 n_fft: int = 400 hop_length: int = 160 chunk_frames: int = 3000 kernels: tuple[int, ...] = (3,) strides: tuple[int, ...] = (2,) paddings: tuple[int, ...] = (1,)
def __post_init__(self): if self.n_mels not in (80, 128): raise ValueError("Ming audio requires 80 or 128 mel bins") if (self.sample_rate, self.n_fft, self.hop_length) != (16000, 400, 160): raise ValueError("Ming checkpoints require the 16 kHz Whisper frontend") if self.chunk_frames <= 0: raise ValueError("chunk_frames must be positive") if not (len(self.kernels) == len(self.strides) == len(self.paddings)): raise ValueError( "audio downsampler kernel/stride/padding lists must have the same length" ) if any(k <= 0 for k in self.kernels) or any(s <= 0 for s in self.strides): raise ValueError("audio downsampler kernels and strides must be positive") if any(p < 0 for p in self.paddings): raise ValueError("audio downsampler paddings must be nonnegative")
@classmethod def from_config(cls, config): def get(name, default=None): return ( config.get(name, default) if isinstance(config, dict) else getattr(config, name, default) )
encoder = get("whisper_encoder_config") or {} kernels = tuple( get("downsampler_kernel_size_list") or [get("ds_kernel_size", 3)] ) strides = tuple(get("downsampler_stride_list") or [get("ds_stride", 2)]) paddings = get("downsampler_padding_list") spec = cls( n_mels=encoder.get("n_mels", get("n_mels", 128)), chunk_frames=get("chunk_frames", 3000), kernels=kernels, strides=strides, paddings=tuple( paddings if paddings is not None else [k // 2 for k in kernels] ), ) context = encoder.get("n_ctx", get("n_audio_ctx", 3000)) if (spec.chunk_frames + 1) // 2 > context: raise ValueError("audio chunk exceeds encoder positional context") return spec
def embedding_length(self, mel_length): """Length of one chunk; accepts an integer or an integer tensor.""" length = (mel_length + 1) // 2 for kernel, stride, padding in zip(self.kernels, self.strides, self.paddings): length = (length + 2 * padding - kernel) // stride + 1 return length
def chunks(self, mel_length: int) -> tuple[int, ...]: if mel_length <= 0: raise ValueError("audio mel length must be positive") full, remainder = divmod(mel_length, self.chunk_frames) return (self.chunk_frames,) * full + ((remainder,) if remainder else ())
def token_count(self, mel_length: int) -> int: lengths = [self.embedding_length(n) for n in self.chunks(mel_length)] if any(n <= 0 for n in lengths): raise ValueError("audio chunk is too short for the configured downsampler") return sum(lengths)
@dataclass(frozen=True)class MingAudioMetadata: """Versioned model metadata transported opaquely by the generic engine."""
mel_lengths: tuple[int, ...] token_lengths: tuple[int, ...] version: int = 1
def __post_init__(self): if self.version != 1: raise ValueError(f"Unsupported Ming audio metadata version: {self.version}") if not self.mel_lengths or len(self.mel_lengths) != len(self.token_lengths): raise ValueError("Ming audio metadata must describe each clip") if any(n <= 0 for n in (*self.mel_lengths, *self.token_lengths)): raise ValueError("Ming audio lengths must be positive")
def to_dict(self): return { "version": self.version, "mel_lengths": list(self.mel_lengths), "token_lengths": list(self.token_lengths), }
@classmethod def from_dict(cls, value): return cls( tuple(value["mel_lengths"]), tuple(value["token_lengths"]), value["version"] )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904"""AntGLM Chat-model data format.
格式化 AntGLM 以及各种开源模型的符号系统: - 确定 Chat 模型依赖的文件数据结构协议 - 确定单轮/多轮的统一结构 - 确定 Chat 符号系统的协议, 包括角色定义、分隔符等 - 方便做开源模型依赖的 prompt 转换 - 支持工具、代码、推理等支持
参考 FastChat Conversation 对象的设计思路.Reference: https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py"""
import copyimport dataclassesimport loggingimport reimport uuidfrom copy import deepcopyfrom enum import IntEnum, autofrom typing import Dict, List, Optional, Tuple
logger = logging.getLogger(__name__)
class PromptStyle(IntEnum): """Prompt styles."""
# 原始 antglm format 格式, 单轮指令没有结构, 多轮 `第1轮\n用户: xx\n机器人: xx\n` ANTGLM_RAW = auto() # Chat format 格式, 单轮多轮统一为 chat format 格式 ANTGLM_CHAT = auto() # 单轮指令没有结构, 只有多轮为 chat format 格式 ANTGLM_ONLY_MULTITURN_CHAT = auto() # OpenAI ChatML 格式, 包括千问 CHATML = auto() # LLAMA2 格式 LLAMA2 = auto() # ChatGLM 1/2 格式 CHATGLM = auto() # ChatGLM3 格式 CHATGLM3 = auto() # 百川格式 BAICHUAN2 = auto()
@dataclasses.dataclassclass Chat: """Chat 数据符号结构, 格式化 AntGLM 以及各种开源模型的符号系统.
Examples:
```python >>> from antllm.data.chat_format import Chat
>>> ### 从 json 数据结构创建 chat 对象, 并且 format 结构使用 AntGLM 原始结构 >>> input_json = { ... "messages": [ ... {"role": "HUMAN", "content": "讲一个笑话"}, ... {"role": "ASSISTANT", "content": "为什么猪不能上网?因为它们会被网上的“猪”骗!哈哈哈!"}, ... {"role": "HUMAN", "content": "不好笑,换个程序员的笑话"} ... ], ... } >>> chat = Chat.from_json(input_json, name='antglm_raw')
>>> ### 根据 chat 对象创建大模型训练所需 pack 数据 >>> pack_data = chat.prompt_pack >>> print(pack_data)
>>> ### 根据 chat 对象创建大模型训练所需 input, output 数据 >>> data = chat.prompt_inout >>> print(data)
>>> ### 根据 chat 对象创建大模型预测用的 prompt >>> prompt = chat.prompt_str >>> print(prompt)
>>> ### 从大模型训练数据 {"input": "xx", "output": "xx"} 中创建 chat 对象 >>> data = { ... 'input': ( ... '第1轮\n用户: 讲一个笑话\n机器人: 为什么猪不能上网?因为它们会被网上的“猪”骗!哈哈哈!\n' ... '第2轮\n用户: 不好笑,换个程序员的笑话\n机器人:' ... ), ... 'output': '' ... } >>> chat = Chat.from_inout(data, name='antglm_raw')
>>> ### 从大模型 pack 训练数据创建 chat 对象列表 >>> pack_data = { ... 'inputs': ['第1轮\n用户: 讲一个笑话\n机器人:', '第2轮\n用户: 不好笑,换个程序员的笑话\n机器人:', '第1轮\n用户: 写首诗\n机器人:'], ... 'outputs': [ ... '为什么猪不能上网?因为它们会被网上的“猪”骗!哈哈哈!\n', ... '为什么程序员总是喜欢使用黑色主题?因为他们喜欢“黑暗模式”(Dark Mode),这样他们就可以在晚上加班时更好地隐藏自己的错误!', ... ''] ... } >>> chats = Chat.from_pack(pack_data, name='antglm_raw') >>> assert len(chats) == 2 >>> print(chats[0]) >>> print(chats[1])
>>> ### 显示总交互轮数 (以用户输出多少次为轮数个数) >>> print(chat.turns_num)
>>> ### 根据 chat 对象创建 json 格式化输出 >>> data_json = chat.to_json() >>> print(data_json)
>>> ### 增加轮次信息 >>> content = ( ... '为什么程序员总是喜欢使用黑色主题?' ... '因为他们喜欢“黑暗模式”(Dark Mode),这样他们就可以在晚上加班时更好地隐藏自己的错误!' ... ) >>> chat.append_message(chat.role_assistant, content)
>>> ### 将 chat 对象转成 OpenAI ChatCompletion 接口的入参 >>> openai_messages = chat.to_openai_api_messages() >>> print(openai_messages)
>>> ### 复制一个 chat 对象 >>> chat_new = chat.copy() ``` """
# 数据结构名称 id: str = None
# format 支持: antglm_raw, antglm_chat, chatglm1, chatglm2, llama2, qwen, baichuan2 name: Optional[str] = None
# Prompt 风格 prompt_style: Optional[PromptStyle] = None
# System Template 和 message system_template: str = "<role>SYSTEM</role>{}" system_message: str = ""
# 角色定义 role_human: str = "HUMAN" role_assistant: str = "ASSISTANT" role_observation: str = "OBSERVATION" role_template: str = "<role>{}</role>"
# 每轮符号定义 turn_start: str = "" human_end: str = "" assistant_start: str = "" assistant_end: str = "" assistant_end_ids: Optional[List[int]] = None general_role_end: str = ""
# agent 符号定义 tool_template = "<tool>{}</tool>" code_template = "<code>{}</code>" arithemetic_templte = "<arithemetic>{}</arithemetic>"
# All messages. Each item is (role, message). messages: List[Tuple[str, str]] = ()
# messages 中用于 few-shot messages offset: int = 0
# 其他 meta data source: Optional[str] = None lang: Optional[str] = None topic: Optional[str] = None
# 原始 json 数据 origin_json: Optional[dict] = None
@property def support_names(self) -> Dict[str, str]: """支持的数据对象名称.""" return { "antglm_raw": "原始 antglm format 格式, 单轮指令没有结构, 多轮 `第1轮\\n用户:xx\\n机器人xx\\n`", "antglm_chat": "Chat format 格式, 单轮多轮统一为 chat format 格式", "chatglm1": "chatglm1 format", "chatglm2": "chatglm2 format", "llama2": "llama2 format", "qwen": "千问 format", "baichuan2": "百川 2 format", }
@classmethod def from_json( cls, input: dict, name: Optional[str] = None, prompt_style: Optional[PromptStyle] = None, ): """从文件数据结构到数据对象的转换.
Params: name: `Optional[str]`, 符号系统名称 - format 支持: antglm_raw, antglm_chat, chatglm1, chatglm2, llama2, qwen, baichuan2 - 如果指定了 format name, 使用该 name 符号系统, 否则使用 input 中 `name` 字段
prompt_style: `Optional[PromptStyle]`, 指定 prompt 风格, 默认使用和 name 一致的风格
input: `dict`, 文件中的 json dict 对象, 协议为: - 既支持 `messages` 字段, 也支持 `turns` 字段 { "id": "xxx", "name": "antglm", "source": "xxx", "lang": "xx", "topic": "xx", "system_template": "", "system_message": "xx", "messages": [ { "role": "HUMAN", "content": "Hi" }, { "role": "ASSISTANT", "content": "Hello" }, { "role": "OBSERVATION", "content": "xxx" }, { "role": "ASSISTANT", "content": "xxx" } ], "turns": [ {"HUMAN": "xxx", "OBSERVATION": "xx", "ASSISTANT": "xx"} ] }
Returns: `Chat` 对象 """ _id = input.get("id") if name: _name = name else: _name = input.get("name") source = input.get("source") lang = input.get("lang") topic = input.get("topic") kwargs = {} if "system_template" in input: kwargs["system_template"] = input["system_template"] if "system_message" in input: kwargs["system_message"] = input["system_message"]
# 转换成 Chat 对象 chat = cls( id=_id, name=_name, prompt_style=prompt_style, source=source, lang=lang, topic=topic, origin_json=deepcopy(input), **kwargs, ) if "messages" in input: for msg in input["messages"]: if msg["role"] == "HUMAN": role = chat.role_human elif msg["role"] == "OBSERVATION": role = chat.role_observation elif msg["role"] == "ASSISTANT": role = chat.role_assistant else: raise ValueError(f"不支持数据集中的 role: {msg['role']}")
chat.append_message(role, msg["content"])
elif "turns" in input: for turn in input["turns"]: if "HUMAN" in turn: content = turn["HUMAN"] chat.append_message(chat.role_human, content) if "OBSERVATION" in turn: content = turn["OBSERVATION"] chat.append_message(chat.role_observation, content) if "ASSISTANT" in turn: content = turn["ASSISTANT"] chat.append_message(chat.role_assistant, content)
return chat
@classmethod def from_pack( cls, packs: Dict[str, List[str]], name: str, prompt_style: Optional[PromptStyle] = None, ) -> list: """根据 pack 数据创建 Chat 对象.
Params: packs: `dict`, pack 样本数据 { 'inputs': ['xx', 'xx'], 'outputs': ['xx', 'xx'], }
name: `str`, 符号系统名称 prompt_style: `Optional[PromptStyle]`, 指定 prompt 风格, 默认使用和 name 一致的风格 """ chat = cls(name=name, prompt_style=prompt_style) packs = cls._format_packs(packs)
sys_pattern = re.compile(chat.system_template.format(r"(.*?)"), re.DOTALL) turn_pattern = re.compile(chat.turn_start.format(r"(\d+)"), re.DOTALL) human_pattern = re.compile( chat.role_template.format(chat.role_human).strip(), re.DOTALL ) observe_pattern = re.compile( chat.role_template.format(chat.role_observation).strip(), re.DOTALL ) assistant_pattern = re.compile( chat.role_template.format(chat.role_assistant).strip(), re.DOTALL )
chats = [] for input, output in zip(packs["input"], packs["output"]): # system message sys_match = sys_pattern.search(input) if sys_match and sys_match.group(0): # system 指令只在首轮, 新增 chat 对象 if len(chat.messages) > 0: chats.append(chat) chat = cls(name=name, prompt_style=prompt_style)
input = input[sys_match.end() :] chat.system_message = sys_match.group(1)
# turn start turn_match = turn_pattern.search(input) if turn_match and turn_match.group(0): # 当出现下一个轮次开始信息, 新增 chat 对象 if name in ["antglm", "antglm_raw", "chatglm2"]: round_start = 1 else: round_start = 0
if all( [ len(turn_match.groups()) > 0, int(turn_match.group(1)) == round_start, len(chat.messages) > 0, ] ): chats.append(chat) chat = cls(name=name, prompt_style=prompt_style)
input = input[turn_match.end() :]
human_iter = human_pattern.finditer(input) observe_iter = observe_pattern.finditer(input) assistant_iter = assistant_pattern.finditer(input) human_match = next(human_iter, None) observe_match = next(observe_iter, None) assistant_match = next(assistant_iter, None)
if not human_match and not observe_match: # 无 role format chat.append_message(chat.role_human, input)
while human_match or observe_match: next_human_match = next(human_iter, None) next_observe_match = next(observe_iter, None) input = cls._append_human_observation( chat, input, human_match=human_match, next_human_match=next_human_match, observe_match=observe_match, next_observe_match=next_observe_match, assistant_match=assistant_match, )
human_match = next_human_match observe_match = next_observe_match next_human_match = next(human_iter, None) next_observe_match = next(observe_iter, None)
if output: chat.append_message(chat.role_assistant, output)
if chat.messages: chats.append(chat)
return chats
@classmethod def _append_human_observation( cls, chat, input: str, human_match: Optional[re.Match] = None, next_human_match: Optional[re.Match] = None, observe_match: Optional[re.Match] = None, next_observe_match: Optional[re.Match] = None, assistant_match: Optional[re.Match] = None, ) -> str: """给 chat 对象增加 human/observation message.""" if observe_match: # observation 在 human 之后 if observe_match.span()[0] > observe_match.span()[0]: human_str = input[observe_match.span()[1] : observe_match.span()[0]] observe_str = input[observe_match.span()[1] : assistant_match.span()[0]] chat.append_message(chat.role_human, human_str.strip()) input_end = observe_match.span()[1] if observe_match.span()[0] < next_human_match.span()[0]: chat.append_message(chat.role_observation, observe_str.strip()) input_end = assistant_match.span()[1] else: # observation 在 human 之前 human_str = input[observe_match.span()[1] : assistant_match.span()[0]] observe_str = input[observe_match.span()[1] : observe_match.span()[0]] chat.append_message(chat.role_observation, observe_str.strip()) input_end = observe_match.span()[1] if observe_match.span()[0] < next_observe_match.span()[0]: chat.append_message(chat.role_human, human_str.strip()) input_end = assistant_match.span()[1] else: if assistant_match: human_str = input[human_match.span()[1] : assistant_match.span()[0]] input_end = assistant_match.span()[1] else: human_str = input[human_match.span()[1] :] input_end = len(input) chat.append_message(chat.role_human, human_str.strip())
return input[input_end:]
@classmethod def from_inout( cls, sample: Dict[str, str], name: str, prompt_style: Optional[PromptStyle] = None, ): """根据单样本创建一个 Chat 对象.
Params: sample: `Dict[str, str]`, input/output 数据样本 { "input": "xxx", "output": "xxx", }
name: `str`, 符号系统名称 prompt_style: `Optional[PromptStyle]`, 指定 prompt 风格, 默认使用和 name 一致的风格 """ chat = cls(name=name, prompt_style=prompt_style) input = sample["input"] output = sample["output"]
sys_pattern = re.compile(chat.system_template.format(r"(.*?)"), re.DOTALL) turn_pattern = re.compile(chat.turn_start.format(r"(\d+)"), re.DOTALL) human_pattern = re.compile( chat.role_template.format(chat.role_human).strip(), re.DOTALL ) observe_pattern = re.compile( chat.role_template.format(chat.role_observation).strip(), re.DOTALL ) assistant_pattern = re.compile( chat.role_template.format(chat.role_assistant).strip(), re.DOTALL )
# 去除轮次信息 input = turn_pattern.sub("", input)
# system message search sys_match = sys_pattern.search(input) if sys_match and sys_match.group(0): input = input[sys_match.end() :] chat.system_message = sys_match.group(1)
human_iter = human_pattern.finditer(input) observe_iter = observe_pattern.finditer(input) assistant_iter = assistant_pattern.finditer(input) human_match = next(human_iter, None) observe_match = next(observe_iter, None) assistant_match = next(assistant_iter, None) next_human_match = next(human_iter, None) next_observe_match = next(observe_iter, None)
while any( [ human_match, observe_match, assistant_match, ] ): # human/observation 先后顺序可能不一样, 并且有可能有多个 # 判断 assitant 之前是否还有 human/observation while any( [ human_match and human_match.span()[0] < assistant_match.span()[0], observe_match and observe_match.span()[0] < assistant_match.span()[0], next_human_match and next_human_match.span()[0] < assistant_match.span()[0], next_observe_match and next_observe_match.span()[0] < assistant_match.span()[0], ] ): if not input: break
cls._append_human_observation( chat, input, human_match=human_match, next_human_match=next_human_match, observe_match=observe_match, next_observe_match=next_observe_match, assistant_match=assistant_match, )
human_match = next_human_match observe_match = next_observe_match next_human_match = next(human_iter, None) next_observe_match = next(observe_iter, None)
# assistant message if assistant_match and assistant_match.span(): if observe_match: if ( observe_match.span() and observe_match.span()[0] < human_match.span()[0] ): assistant_str = input[ assistant_match.span()[1] : observe_match.span()[0] ] elif human_match: if human_match.span(): assistant_str = input[ assistant_match.span()[1] : human_match.span()[0] ] else: assistant_str = input[assistant_match.span()[1] :]
if assistant_str: chat.append_message(chat.role_assistant, assistant_str)
assistant_match = next(assistant_iter, None)
if output: chat.append_message(chat.role_assistant, output)
return chat
def __hash__(self): """数据对象的 hash 函数.""" return hash(self.id)
def __post_init__(self): """对象初始化后的处理, 处理包括: - 根据数据对象名称, 支持转成其他开源数据对象的基本信息 """ self.id = str(uuid.uuid4()) if not self.messages: self.messages = []
if not self.name and not self.prompt_style: logger.error( "构造 Chat 对象至少包含以下一个入参: `name/prompt_style`.\n\n" "`name` 支持以下 format 名称:" ) logger.error( "\n".join([f"{k}: {v}" for k, v in self.support_names.items()]) ) logger.error("\n`prompt_style` 参考 antllm.data.chat_format.PromptStyle") raise ValueError
if self.name == "antglm": # 默认 antglm 使用原始 antglm_raw - 第1轮\n用户: xx\n机器人: xx\n self.name = "antglm_raw"
if not self.name and self.prompt_style == PromptStyle.ANTGLM_CHAT: logger.info( "Chat 对象入参没有 `name`, 默认使用 `ANTGLM_CHAT`, format:\n" f"role_human: {self.role_human}\n" f"role_assistant: {self.role_assistant}\n" f"role_observation: {self.role_observation}\n" f"role_template: {self.role_template}\n" f"turn_start: {self.turn_start}\n" f"human_end: {self.human_end}\n" f"assistant_start: {self.assistant_start}\n" f"assistant_end: {self.assistant_end}\n" f"assistant_end_ids: {self.assistant_end_ids}\n" f"general_role_end: {self.general_role_end}\n" f"tool_template: {self.tool_template}\n" f"code_template: {self.code_template}\n" f"arithemetic_templte: {self.arithemetic_templte}\n" f"\n入参 `name` 支持: ``" ) return
if self.name == "antglm_raw" or self.prompt_style == PromptStyle.ANTGLM_RAW: self.prompt_style = PromptStyle.ANTGLM_RAW self.role_template = "{}" self.role_human = "用户: " self.role_assistant = "机器人: " self.turn_start = "第{}轮\n" self.general_role_end = "\n"
if ( self.name in ["chatglm1", "chatglm2"] or self.prompt_style == PromptStyle.CHATGLM ): self.prompt_style = PromptStyle.CHATGLM self.role_template = "{}" self.role_human = "问:" self.role_assistant = "答:" self.turn_start = "[Round {}]\n" if self.name == "chatglm1": self.general_role_end = "\n" else: self.general_role_end = "\n\n"
elif self.name == "chatglm3" or self.prompt_style == PromptStyle.CHATGLM3: self.prompt_style = PromptStyle.CHATGLM3 self.system_template = "<|system|>\n {}" self.role_human = "<|user|>\n " self.role_assistant = "<|assistant|>\n " self.role_template = "{}"
elif self.name == "llama2" or self.prompt_style == PromptStyle.LLAMA2: self.prompt_style = PromptStyle.LLAMA2 self.role_template = "{}" self.system_template = "[INST] <<SYS>>\n{}\n<</SYS>>\n\n" self.role_human = "[INST] " self.role_assistant = "[/INST] " self.human_end = " " self.assistant_end = " </s><s>"
elif self.name == "qwen": self.prompt_style = PromptStyle.CHATML self.role_template = "{}" self.system_template = "<|im_start|>system\n{}" if not self.system_message: self.system_message = "You are a helpful assistant." self.role_human = "<|im_start|>user\n" self.role_assistant = "<|im_start|>assistant\n" self.general_role_end = "<|im_end|>\n"
elif self.name == "baichuan": self.prompt_style = PromptStyle.BAICHUAN2 self.role_template = "{}" self.system_template = "{}" self.role_human = "<token_id-195>" self.role_assistant = "<token_id-196>"
if not self.system_template: self.system_template = "{}"
def readable_messages(self) -> str: """将 messages 输出为人类可读的字符串, 方便分析数据.""" pass
@property def prompt_str(self) -> str: """将 Chat 对象转成 prompt str, 合并 human/assitant 输出为 format 字符串.""" return f"{self.prompt_inout['input']}{self.prompt_inout['output']}"
@classmethod def _format_packs(cls, packs: Dict[str, List[str]]) -> Dict[str, List[str]]: """格式化 pack 样本, 输出相同 pack inputs, outputs 个数.""" _packs = copy.deepcopy(packs) if len(_packs["input"]) - 1 == len(_packs["output"]): _packs["output"].append("")
if len(_packs["input"]) != len(_packs["output"]): print(packs) raise ValueError( "输入 input 和 output 数量不匹配, " f"input num: {len(packs['input'])}, " f"output num: {len(packs['output'])}" )
return _packs
@property def prompt_inout(self) -> Dict[str, str]: """将 Chat 对象转成 input prompt, output prompt 字符串.
Returns: `Dict[str, str]`, 示例: { "input": "<role>SYSTEM</role>xxxx<role>HUMAN</role>你好<role>ASSISTANT</role>你好,有什么可以帮您?<role>ASSISTANT</role>", # noqa "output": "你好,有什么可以帮您?" } """ packs = self._format_packs(self.prompt_pack)
# 兼容逻辑 if self.prompt_style == PromptStyle.ANTGLM_RAW: packs["input"] = [f"{item} " for item in packs["input"]]
prompt_input = "".join( [f"{x}{y}" for x, y in zip(packs["input"][:-1], packs["output"][:-1])] ) prompt_input += packs["input"][-1] prompt_output = packs["output"][-1]
# 兼容逻辑 if self.prompt_style == PromptStyle.ANTGLM_RAW: prompt_input = prompt_input.strip()
return { "input": prompt_input, "output": prompt_output, }
@property def prompt_pack(self) -> Dict[str, List[str]]: """将数据对象转成 pack input prompt, output prompt 字符串列表.:
Returns: `Dict[str, List[str]]`, 示例:
{ "input": [ "<role>SYSTEM</role>xxxx<role>HUMAN</role>你好<role>ASSISTANT</role>", "<role>HUMAN</role>讲个笑话<role>ASSISTANT</role>", "<role>OBSERVATION</role>{\"weather\": \"晴\"}<role>ASSISTANT</role>" ], "output": [ "你好,有什么可以帮您?", "笑话 1", "今天天气 xxx" ] }
""" inputs = [] outputs = []
# 最开始 system 构造 system_prompt = "" if self.system_message: system_prompt = self.system_template.format(self.system_message)
if system_prompt: ret = system_prompt + self.general_role_end else: ret = ""
# 有些 prompt style 单轮指令没有 format if self.prompt_style in [ PromptStyle.ANTGLM_RAW, PromptStyle.ANTGLM_ONLY_MULTITURN_CHAT, ]: if len(self.messages) <= 2: output = "" for role, message in self.messages: if role == self.role_assistant: output = message else: input = ret + message return { "input": [input], "output": [output], }
# 多轮对话 if self.name in ["antglm_raw", "chatglm2"]: round_start = 1 else: round_start = 0
for i, (role, message) in enumerate(self.messages): # 轮次信息 if self.name in ["antglm_raw", "chatglm1", "chatglm2"]: if i % 2 == 0: ret += self.turn_start.format(i // 2 + round_start)
# 角色 + 内容 role_end = self.general_role_end if role == self.role_assistant and self.assistant_end: role_end = self.assistant_end elif self.human_end: role_end = self.human_end
ret += self.role_template.format(role) + message + role_end
if role == self.role_assistant: # output 只保留实际 assistant 内容 if not message: outputs.append("") else: outputs.append(message + role_end) # input 需要连接 assistant role inputs[-1] += ret[: -len(message + role_end)] elif all( [ role == self.role_observation, len(self.messages) > 1, self.messages[i - 1][0] != self.role_assistant, ] ): # observation 之前不是 assistant, 需要将 observation 和上一个 input 连接一起 continue else: inputs.append(ret) ret = ""
# 最后一轮不是机器人回复, 需要拼接机器人 role, 用于模型生成 if i == len(self.messages) - 1 and role != self.role_assistant: inputs[-1] += self.role_template.format(self.role_assistant).strip()
# 兼容逻辑, 去除 inputs 最后空格符号 if self.prompt_style == PromptStyle.ANTGLM_RAW: inputs = [item.strip() for item in inputs]
return { "input": inputs, "output": outputs, }
@property def turns_num(self) -> int: """和机器人的交互轮数, 以用户输出多少次为轮数个数.""" return sum([1 if msg[0] == self.role_human else 0 for msg in self.messages])
def to_json(self) -> dict: """输出 chat json dict 格式, 包含不同角色和机器人交互的每轮信息.
Returns `List[dict]`, { "id": "xx", "messages": [ {"role": "HUMAN", "content": "xxx"} ] "turns": [ {"HUMAN": "xx", "OBSERVATION": "xx", "ASSISTANT": "xx"} ] } """ turns = [] messages = [] turn = {} for msg in self.messages: if msg[0] == self.role_assistant: messages.append({"role": "ASSISTANT", "content": msg[1]}) turn["ASSISTANT"] = msg[1] turns.append(turn) turn = {}
if msg[0] == self.role_human: messages.append({"role": "HUMAN", "content": msg[1]}) turn["HUMAN"] = msg[1]
if msg[0] == self.role_observation: messages.append({"role": "OBSERVATION", "content": msg[1]}) turn["OBSERVATION"] = msg[1]
if self.messages[-1][0] == self.role_human: messages.append({"role": "ASSISTANT", "content": ""}) turn["ASSISTANT"] = "" turns.append(turn)
result = self.origin_json or {} result.update( { "id": self.id, "name": self.name, "source": self.source, "lang": self.lang, "topic": self.topic, "system_template": self.system_template, "system_message": self.system_message, "turns": turns, "messages": messages, } )
return result
def set_system_message(self, system_message: str): """Set the system message.""" self.system_message = system_message
def append_message(self, role: str, message: str): """Append a new message.""" if not message: message = "" self.messages.append([role, message])
def to_openai_api_messages(self) -> List[dict]: """Convert the conversation to OpenAI chat completion format.""" ret = [{"role": "system", "content": self.system_message}]
for i, (_, msg) in enumerate(self.messages[self.offset :]): if i % 2 == 0: ret.append({"role": "user", "content": msg}) else: if msg is not None: ret.append({"role": "assistant", "content": msg}) return ret
def copy(self): return copy.deepcopy(self)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657{#- Tiny checkpoint template: preserve audio/text rendering exactly. -#}{%- for message in messages %} {%- if message.content is iterable and message.content is not string %} {%- for part in message.content %} {%- if part is mapping and (part.type in ['image', 'image_url', 'video', 'video_url'] or 'image' in part or 'image_url' in part or 'video' in part or 'video_url' in part) %} {{- raise_exception('Ming-ASR-Tiny supports audio/text content only.') }} {%- endif %} {%- endfor %} {%- endif %}{%- endfor %}{{- '<role>SYSTEM</role>' }}{%- if messages and messages[0].role == 'system' and messages[0].content is string %} {{- messages[0].content }}{%- else %} {{- '你是一个友好的AI助手。' }}{%- endif %}
{{- '
detailed thinking ' }}{{- 'on' if enable_thinking else 'off' }}{{- '<|role_end|>' }}
{%- for message in messages %} {%- set role_lower = message.role | lower %}
{%- if role_lower in ['user', 'human'] -%} <role>HUMAN</role> {%- set contents = message.content if message.content is iterable and message.content is not string else [message.content] %} {%- for part in contents %} {%- if part.type is defined %} {%- if part.type == 'audio' or 'audio_url' in part -%} <AUDIO> {%- elif part.type == 'text' %} {{- part.text }} {%- endif %} {%- else %} {{- part }} {%- endif %} {%- endfor %} {{- '<|role_end|>' }}
{%- elif role_lower in ['assistant'] -%} <role>ASSISTANT</role> {%- set contents = message.content if message.content is iterable and message.content is not string else [message.content] %} {%- for part in contents %} {%- if part.type is defined and part.type == 'text' %} {{- part.text }} {%- elif part is string %} {{- part }} {%- endif %} {%- endfor %} {{- '<|role_end|>' }} {%- endif %}{%- endfor %}
{{- '<role>ASSISTANT</role>' -}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687{ "model_type": "ming_v3_asr", "architectures": [ "MingV3ASRForConditionalGeneration" ], "auto_map": { "AutoConfig": "configuration_ming_v3_asr.MingV3ASRConfig", "AutoModelForCausalLM": "modeling_ming_v3_asr.MingV3ASRForConditionalGeneration", "AutoProcessor": "processing_ming_v3_asr.MingV3ASRProcessor" }, "tie_word_embeddings": false, "audio_token_id": 157168, "text_config": { "vocab_size": 157184, "hidden_size": 1536, "intermediate_size": 4608, "num_hidden_layers": 24, "num_attention_heads": 16, "num_key_value_heads": 16, "hidden_act": "silu", "use_qkv_bias": false, "use_bias": false, "rms_norm_eps": 1e-06, "tie_word_embeddings": false, "embedding_dropout": 0.0, "attention_dropout": 0.0, "output_dropout": 0.0, "initializer_range": 0.02, "max_position_embeddings": 8192, "rope_theta": 10000, "use_cache": true, "max_window_layers": 20, "rope_scaling": null, "pad_token_id": 156892, "eos_token_id": 156892, "num_experts": 128, "num_shared_experts": 1, "num_experts_per_tok": 8, "n_group": 8, "topk_group": 4, "moe_intermediate_size": 512, "moe_shared_expert_intermediate_size": 512, "first_k_dense_replace": 1, "head_dim": 128, "output_router_logits": false, "use_qk_norm": true, "num_nextn_predict_layers": 1, "mtp_loss_scaling_factor": 0, "moe_router_enable_expert_bias": true, "routed_scaling_factor": 2.5, "layer_group_size": 4, "kv_lora_rank": 512, "q_lora_rank": 256, "qk_rope_head_dim": 64, "v_head_dim": 128, "qk_nope_head_dim": 128, "rope_interleave": true, "score_function": "sigmoid", "scoring_func": "sigmoid", "seq_aux": true, "topk_method": "noaux_tc", "router_dtype": "fp32", "gated_attention_proj_granularity_type": "head_wise", "no_kda_lora": true, "kda_safe_gate": true, "kda_lower_bound": -5.0, "short_conv_kernel_size": 4 }, "audio_config": { "n_mels": 128, "n_audio_ctx": 3000, "n_audio_state": 1280, "n_audio_head": 20, "n_audio_layer": 32, "downsampler_kernel_size_list": [ 3 ], "downsampler_stride_list": [ 2 ] }, "asr_output_format": "plain", "supported_modalities": [ "audio" ], "dtype": "bfloat16"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293# Copyright 2025 Antgroup and The HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## 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.
"""Ming V3 ASR audio/text configuration."""
import osfrom typing import Union
from transformers.configuration_utils import PretrainedConfigfrom transformers.utils import logging
from .audio_spec import MingAudioSpec
logger = logging.get_logger(__name__)
class BailingMoeV3Config(PretrainedConfig): model_type = "bailing_moe_v3"
def __init__( self, vocab_size=157184, hidden_size=2048, intermediate_size=5120, num_hidden_layers=20, num_attention_heads=16, num_key_value_heads=4, hidden_act="silu", use_qkv_bias=False, # bailing only use_bias=False, # bailing only rms_norm_eps=1e-06, tie_word_embeddings=False, # PretrainedConfig key, here change default value. embedding_dropout=0.0, attention_dropout=0.0, output_dropout=0.0, initializer_range=0.02, max_position_embeddings=32768, rope_theta=600000.0, use_cache=True, max_window_layers=20, rope_scaling=None, pad_token_id=156892, eos_token_id=156892, num_experts=256, num_shared_experts=1, num_experts_per_tok=8, n_group=8, topk_group=4, moe_intermediate_size=512, moe_shared_expert_intermediate_size=512, expert_swiglu_limit_list=None, share_expert_swiglu_limit_list=None, first_k_dense_replace=1, head_dim=128, output_router_logits=False, use_qk_norm=True, num_nextn_predict_layers=0, mtp_loss_scaling_factor=0, moe_router_enable_expert_bias=True, routed_scaling_factor=1.0, layer_group_size=5, kv_lora_rank=512, q_lora_rank=None, qk_rope_head_dim=64, v_head_dim=128, qk_nope_head_dim=128, rope_interleave=True, score_function="sigmoid", scoring_func="sigmoid", seq_aux=True, topk_method="noaux_tc", router_dtype="fp32", gated_attention_proj_granularity_type=None, no_kda_lora=False, kda_safe_gate=False, kda_lower_bound=None, short_conv_kernel_size=4, **kwargs, ): # Historical mixed checkpoints carry these non-audio metadata fields. for key in ( "image_patch_token", "video_patch_token", "image_start_token", "video_start_token", "mrope_section", ): kwargs.pop(key, None) self.num_hidden_layers = num_hidden_layers self.vocab_size = vocab_size self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.hidden_act = hidden_act self.use_qkv_bias = use_qkv_bias self.use_bias = use_bias self.rms_norm_eps = rms_norm_eps self.embedding_dropout = embedding_dropout self.attention_dropout = attention_dropout self.output_dropout = output_dropout self.num_nextn_predict_layers = num_nextn_predict_layers self.mtp_loss_scaling_factor = mtp_loss_scaling_factor self.initializer_range = initializer_range self.max_position_embeddings = max_position_embeddings self.rope_theta = rope_theta self.use_cache = use_cache self.max_window_layers = max_window_layers self.head_dim = head_dim or self.hidden_size // self.num_attention_heads self.rope_scaling = rope_scaling self.use_qk_norm = use_qk_norm self.moe_router_enable_expert_bias = moe_router_enable_expert_bias self.routed_scaling_factor = routed_scaling_factor
# MoE configs self.num_experts = num_experts self.num_shared_experts = num_shared_experts self.num_experts_per_tok = num_experts_per_tok self.n_group = n_group self.topk_group = topk_group self.moe_intermediate_size = moe_intermediate_size self.moe_shared_expert_intermediate_size = moe_shared_expert_intermediate_size self.expert_swiglu_limit_list = ( None if expert_swiglu_limit_list is None else list(expert_swiglu_limit_list) ) self.share_expert_swiglu_limit_list = ( None if share_expert_swiglu_limit_list is None else list(share_expert_swiglu_limit_list) ) self.first_k_dense_replace = first_k_dense_replace self.output_router_logits = output_router_logits
# Linear configs self.layer_group_size = layer_group_size if not isinstance(layer_group_size, int) or layer_group_size < 1: raise ValueError("layer_group_size must be a positive integer") # Match the trained decoder layout, including a trailing partial group. # Transformers uses these types to allocate recurrent and KV cache layers. layer_types = [ "full_attention" if (index + 1) % layer_group_size == 0 or index >= num_hidden_layers // layer_group_size * layer_group_size else "linear_attention" for index in range(num_hidden_layers) ] serialized_layer_types = kwargs.pop("layer_types", None) if ( serialized_layer_types is not None and list(serialized_layer_types) != layer_types ): raise ValueError( "layer_types does not match the configured Ming decoder layout" ) self.layer_types = layer_types # mla self.kv_lora_rank = kv_lora_rank self.q_lora_rank = q_lora_rank self.qk_rope_head_dim = qk_rope_head_dim
self.score_function = score_function self.scoring_func = scoring_func self.seq_aux = seq_aux self.topk_method = topk_method self.v_head_dim = v_head_dim self.qk_nope_head_dim = qk_nope_head_dim self.qk_head_dim = qk_nope_head_dim + qk_rope_head_dim self.rope_interleave = rope_interleave self.router_dtype = router_dtype self.gated_attention_proj_granularity_type = ( gated_attention_proj_granularity_type ) self.no_kda_lora = no_kda_lora self.kda_safe_gate = kda_safe_gate self.kda_lower_bound = kda_lower_bound self.short_conv_kernel_size = short_conv_kernel_size super().__init__( pad_token_id=pad_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs, )
class MingV3ASREncoderConfig(PretrainedConfig): model_type = "ming_v3_asr_audio"
def __init__( self, n_mels=128, n_audio_ctx=3000, n_audio_state=1280, n_audio_head=20, n_audio_layer=32, downsampler_kernel_size_list=None, downsampler_stride_list=None, downsampler_padding_list=None, chunk_frames=3000, **kwargs, ): super().__init__(**kwargs) self.n_mels = n_mels self.n_audio_ctx = n_audio_ctx self.n_audio_state = n_audio_state self.n_audio_head = n_audio_head self.n_audio_layer = n_audio_layer self.downsampler_kernel_size_list = list( [3] if downsampler_kernel_size_list is None else downsampler_kernel_size_list ) self.downsampler_stride_list = list( [2] if downsampler_stride_list is None else downsampler_stride_list ) self.downsampler_padding_list = list( [kernel // 2 for kernel in self.downsampler_kernel_size_list] if downsampler_padding_list is None else downsampler_padding_list ) self.chunk_frames = chunk_frames MingAudioSpec.from_config(self)
@classmethod def from_pretrained( cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs ) -> "PretrainedConfig": config_dict, kwargs = cls.get_config_dict( pretrained_model_name_or_path, **kwargs ) if "audio_config" in config_dict: config_dict = config_dict["audio_config"] return cls.from_dict(config_dict, **kwargs)
class MingV3ASRConfig(PretrainedConfig): model_type = "ming_v3_asr" sub_configs = { "text_config": BailingMoeV3Config, "audio_config": MingV3ASREncoderConfig, }
def __init__( self, text_config=None, audio_config=None, audio_token_id=157168, tie_word_embeddings=False, mlp_depth=2, **kwargs, ): for key in ( "vision_config", "image_token_id", "video_token_id", "vision_start_token_id", "vision_end_token_id", "mrope_section", ): kwargs.pop(key, None)
if isinstance(text_config, dict): text_config = BailingMoeV3Config(**text_config) elif text_config is None: text_config = BailingMoeV3Config()
if isinstance(audio_config, dict): audio_config = MingV3ASREncoderConfig(**audio_config) elif audio_config is None: audio_config = MingV3ASREncoderConfig()
self.text_config = text_config self.audio_config = audio_config self.audio_token_id = audio_token_id
if not isinstance(mlp_depth, int) or mlp_depth < 2: raise ValueError("Ming audio projector mlp_depth must be at least 2") self.mlp_depth = mlp_depth
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
def get_text_config(self, decoder=False): return self.text_config12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879"""Transcribe local audio with the aligned Ming 3.0 ASR Tiny model."""import argparseimport jsonimport sysfrom pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(REPO_ROOT))from asr_request import ( context_chunk_frames, decode_transcript, prepare_asr_request,)
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--model", required=True, help="Complete checkpoint directory or model ID") parser.add_argument("--audio", type=Path, required=True) parser.add_argument("--device", default="cuda:0") parser.add_argument("--attention", choices=("sdpa", "eager"), default="sdpa") parser.add_argument("--max-new-tokens", type=int, default=256) parser.add_argument("--prompt", default=None) parser.add_argument("--language-hint", choices=("zh", "en"), help="Optional known-language prefix; omit when language is unknown") parser.add_argument("--audio-chunk-frames", type=int, help="Mel frames per audio encoder chunk; 6000 supports up to 60-second chunks") parser.add_argument("--context-chunks", action="store_true", help="Context ASR: 3000 frames up to 30 s, else 6000") parser.add_argument("--output", type=Path) args = parser.parse_args() if not args.audio.is_file(): parser.error(f"Audio file does not exist: {args.audio}") if args.max_new_tokens < 1: parser.error("--max-new-tokens must be positive") if args.audio_chunk_frames is not None and args.audio_chunk_frames < 1: parser.error("--audio-chunk-frames must be positive") if args.context_chunks and args.audio_chunk_frames is not None: parser.error("Use either --context-chunks or --audio-chunk-frames")
import soundfile as sf import torch from transformers import AutoModelForCausalLM, AutoProcessor
if not args.device.startswith("cuda") or not torch.cuda.is_available(): parser.error("The supported inference path requires a CUDA GPU") processor = AutoProcessor.from_pretrained(args.model, trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained( args.model, trust_remote_code=True, dtype=torch.bfloat16, device_map=args.device, attn_implementation=args.attention, ).eval() waveform, rate = sf.read(args.audio, dtype="float32", always_2d=True) audio_chunk_frames = (context_chunk_frames(len(waveform) / rate) if args.context_chunks else args.audio_chunk_frames) if audio_chunk_frames is not None: model.config.audio_config.chunk_frames = audio_chunk_frames inputs = prepare_asr_request( processor, (waveform.T, rate), prompt=args.prompt, language_hint=args.language_hint, audio_chunk_frames=audio_chunk_frames, ).to(model.device) eos = getattr(model.config, "text_config", model.config).eos_token_id with torch.inference_mode(): output = model.generate( **inputs, max_new_tokens=args.max_new_tokens, do_sample=False, eos_token_id=eos, pad_token_id=eos, no_repeat_ngram_size=10, ) generated = output[0, inputs.input_ids.shape[1]:] transcript = decode_transcript(processor.tokenizer, generated.tolist()) print(transcript) if args.output: args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps({ "audio": str(args.audio), "model": args.model, "text": transcript, "language_hint": args.language_hint, "audio_chunk_frames": audio_chunk_frames, "generated_token_ids": generated.tolist(), "max_new_tokens": args.max_new_tokens, }, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235# Copyright 2026 Ant Group. All rights reserved.# Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0# 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."""Serializable Ming V3 ASR frontend, independent of the serving engine.
The numerical frontend is adapted from SGLang's ``bailing_audio_frontend.py``(Apache-2.0), which implements the OpenAI Whisper Slaney-normalized mel bank."""
import mathfrom functools import lru_cachefrom numbers import Integral, Real
import numpy as npimport torchfrom transformers.feature_extraction_sequence_utils import SequenceFeatureExtractorfrom transformers.feature_extraction_utils import BatchFeature
from .audio_spec import MingAudioSpec
@lru_cache(maxsize=2)def _mel_filters(n_mels): frequencies = torch.linspace(0, 8000, 201, dtype=torch.float64) linear_scale = 200.0 / 3.0 log_start = 1000.0 / linear_scale log_step = math.log(6.4) / 27.0 mel_max = log_start + math.log(8.0) / log_step mels = torch.linspace(0, mel_max, n_mels + 2, dtype=torch.float64) centers = linear_scale * mels logarithmic = mels >= log_start centers[logarithmic] = 1000.0 * torch.exp( log_step * (mels[logarithmic] - log_start) ) widths = centers[1:] - centers[:-1] ramps = centers[:, None] - frequencies[None, :] lower = -ramps[:-2] / widths[:-1, None] upper = ramps[2:] / widths[1:, None] bank = torch.maximum( torch.zeros((), dtype=torch.float64), torch.minimum(lower, upper) ) # Match the canonical Whisper bank's intermediate FP32 rounding before # Slaney normalization; casting only at the end changes the coefficients. bank = bank.float() bank *= (2.0 / (centers[2:] - centers[:-2]))[:, None] return bank.float()
class MingV3ASRFeatureExtractor(SequenceFeatureExtractor): """Extract padded ``[clips, mel_frames, mel_bins]`` features.
Inputs are mono ``[samples]`` or channel-first ``[channels, samples]`` waveforms, a flat list of waveforms, or ``(waveform, sampling_rate)`` pairs. Waveform amplitudes are used as supplied, including integer inputs; callers decoding PCM should supply normalized floating point samples. Stereo is averaged and non-16-kHz inputs use torchaudio's sinc resampler.
Features preserve the serving frontend's BF16 rounding. NumPy output uses float32 to represent those same values. Lengths always count raw mel frames, never projected token positions. Clips are not truncated or padded to 30 s. """
model_input_names = ["audio_feats", "audio_feats_lengths"]
def __init__( self, feature_size=128, sampling_rate=16000, padding_value=0.0, audio_config=None, **kwargs, ): if sampling_rate != 16000: raise ValueError("Ming feature extraction requires sampling_rate=16000") if padding_value != 0.0: raise ValueError("Ming mel padding_value must be zero") if audio_config is None: audio_config = { "n_mels": feature_size, "downsampler_kernel_size_list": [3], "downsampler_stride_list": [2], } elif hasattr(audio_config, "to_dict"): audio_config = audio_config.to_dict() spec = MingAudioSpec.from_config(audio_config) self.audio_config = { "n_mels": spec.n_mels, "chunk_frames": spec.chunk_frames, "downsampler_kernel_size_list": list(spec.kernels), "downsampler_stride_list": list(spec.strides), "downsampler_padding_list": list(spec.paddings), } super().__init__( feature_size=spec.n_mels, sampling_rate=sampling_rate, padding_value=padding_value, **kwargs, )
@property def spec(self): return MingAudioSpec.from_config(self.audio_config)
@staticmethod def _is_rate_pair(value): return ( isinstance(value, tuple) and len(value) == 2 and isinstance(value[1], Real) and not isinstance(value[0], Real) )
@classmethod def as_clips(cls, audio): """Normalize the public flat clip input without guessing batch axes.""" if audio is None: return [] if isinstance(audio, (torch.Tensor, np.ndarray)) or cls._is_rate_pair(audio): return [audio] if isinstance(audio, (list, tuple)): if not audio: return [] if all(isinstance(value, Real) for value in audio): return [audio] return list(audio) raise ValueError( "audio must contain waveforms or (waveform, sampling_rate) pairs" )
def _prepare_waveform(self, value, sampling_rate): if self._is_rate_pair(value): value, sampling_rate = value if ( not isinstance(sampling_rate, Integral) or isinstance(sampling_rate, bool) or sampling_rate <= 0 ): raise ValueError("sampling_rate must be a positive integer") try: waveform = torch.as_tensor(value) except (TypeError, ValueError, RuntimeError) as error: raise ValueError("audio must be a numeric waveform") from error if waveform.ndim not in (1, 2): raise ValueError("audio shape must be [samples] or [channels, samples]") if waveform.numel() == 0: raise ValueError("audio must not be empty") if waveform.is_complex() or not torch.isfinite(waveform).all(): raise ValueError("audio must contain finite real samples") waveform = waveform.detach().to(device="cpu", dtype=torch.float32) if waveform.ndim == 2: waveform = waveform.mean(dim=0) if sampling_rate != self.sampling_rate: import torchaudio
waveform = torchaudio.functional.resample( waveform, sampling_rate, self.sampling_rate ) if waveform.numel() <= self.spec.n_fft // 2: raise ValueError( "audio is too short for Whisper reflect padding (need more than 200 samples at 16 kHz)" ) if not torch.isfinite(waveform).all(): raise ValueError( "audio contains non-finite values after downmix/resampling" ) return waveform.contiguous()
def _extract_mel(self, waveform): spec = self.spec spectrum = torch.stft( waveform, spec.n_fft, spec.hop_length, window=torch.hann_window(spec.n_fft), return_complex=True, ) power = spectrum[..., :-1].abs().square() mel = _mel_filters(spec.n_mels) @ power log_mel = mel.clamp(min=1e-10).log10() log_mel = torch.maximum(log_mel, log_mel.max() - 8.0) return ((log_mel + 4.0) / 4.0).transpose(0, 1).to(torch.bfloat16)
def __call__( self, audio, sampling_rate=None, return_tensors=None, padding=True, truncation=False, max_length=None, return_attention_mask=False, **kwargs, ): if kwargs: raise TypeError( f"Unsupported Ming audio options: {', '.join(sorted(kwargs))}" ) if return_tensors not in (None, "pt", "np"): raise ValueError("Ming audio supports return_tensors='pt' or 'np'") if truncation or max_length is not None: raise ValueError( "Ming audio does not truncate waveforms; limit audio before processing" ) if padding not in (True, False, "longest", "do_not_pad"): raise ValueError("Ming audio pads mel features to the longest clip") clips = self.as_clips(audio) if not clips: raise ValueError("audio must contain at least one nonempty waveform") sampling_rate = self.sampling_rate if sampling_rate is None else sampling_rate features = [ self._extract_mel(self._prepare_waveform(clip, sampling_rate)) for clip in clips ] lengths = torch.tensor([len(feature) for feature in features], dtype=torch.long) padded = torch.nn.utils.rnn.pad_sequence(features, batch_first=True) data = {"audio_feats": padded, "audio_feats_lengths": lengths} if return_attention_mask: data["audio_attention_mask"] = ( torch.arange(padded.shape[1])[None, :] < lengths[:, None] ).long() if return_tensors != "pt": data = { key: value.float().numpy() if value.dtype == torch.bfloat16 else value.numpy() for key, value in data.items() } return BatchFeature(data=data)
MingV3ASRFeatureExtractor.register_for_auto_class()12345{ "eos_token_id": 156892, "pad_token_id": 156892, "do_sample": false}123version https://git-lfs.github.com/spec/v1oid sha256:3c3aeb85649b6f64a032d069a2321826191d36fe1413191bddd01835b1570d45size 10709697720123version https://git-lfs.github.com/spec/v1oid sha256:a274b5c624f396a3a2547cbc7cf28aeb33890b61141457b45ac1af85ac6e7c55size 702316272812345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150# coding=utf-8# Copyright 2025 Antgroup and The HuggingFace Inc. team. All rights reserved.## This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX# and OPT implementations in this library. It has been modified from its# original forms to accommodate minor architectural differences compared# to GPT-NeoX and OPT used by the Meta AI team that trained the model.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## 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."""Ming-ASR-Tiny audio/text model; legacy class names preserve checkpoint loading."""
import mathimport warningsfrom copy import deepcopyfrom typing import Callable, List, Optional, Tuple, Union
import torchimport torch.nn.functional as Ffrom torch import nnfrom transformers.activations import ACT2FNfrom transformers.cache_utils import Cache, DynamicCache, LinearAttentionLayerfrom transformers.modeling_attn_mask_utils import ( AttentionMaskConverter, _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa,)from transformers.modeling_outputs import MoeModelOutputWithPastfrom transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_updatefrom transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModelfrom transformers.pytorch_utils import ( ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13,)from transformers.utils import ( add_start_docstrings, add_start_docstrings_to_model_forward, logging,)
try: from transformers.utils.import_utils import is_torch_fx_availableexcept ImportError:
def is_torch_fx_available(): return False
from dataclasses import dataclass
from einops import rearrange, repeatfrom transformers.generation.utils import GenerationMixinfrom transformers.modeling_flash_attention_utils import FlashAttentionKwargsfrom transformers.processing_utils import Unpackfrom transformers.utils import ModelOutput, TransformersKwargsfrom transformers.utils.deprecation import deprecate_kwarg
from .audio_spec import MingAudioSpecfrom .configuration_ming_v3_asr import ( BailingMoeV3Config, MingV3ASRConfig,)from .modeling_ming_v3_asr_encoder import ( build_audio_encoder, build_audio_projector, encode_audio_clips,)from .modeling_whisper_encoder import WhisperAudioEncoder # noqa: F401 - cache transitive dependency
def _reject_visual_inputs(kwargs): for key in ( "pixel_values", "pixel_values_videos", "image_grid_thw", "video_grid_thw", "images", "videos", ): if kwargs.pop(key, None) is not None: raise ValueError( "Ming supports audio and text only; image/video inputs are unsupported" )
def _audio_clip_lengths(audio_feats, audio_feats_lengths): """Validate the flattened, padded raw-mel contract before any encoding.""" if not isinstance(audio_feats, torch.Tensor) or audio_feats.ndim != 3: raise ValueError("audio_feats must have shape [clips, frames, mel_bins]") if audio_feats_lengths is None: raise ValueError("audio_feats_lengths must provide raw mel lengths") lengths = torch.as_tensor(audio_feats_lengths) if ( lengths.ndim != 1 or lengths.numel() != audio_feats.shape[0] or lengths.dtype not in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8) ): raise ValueError("audio_feats_lengths must contain one integer length per clip") if ( not lengths.numel() or torch.any(lengths <= 0) or torch.any(lengths > audio_feats.shape[1]) ): raise ValueError( "audio frame lengths must be positive and within the padded feature size" ) return lengths.tolist()
def _audio_request_counts(audio_num_clips, batch_size, total_clips): if audio_num_clips is None: if batch_size != 1: raise ValueError( "audio_num_clips is required to associate clips with each request" ) return [total_clips] counts = torch.as_tensor(audio_num_clips) if ( counts.ndim != 1 or counts.numel() != batch_size or counts.dtype not in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8) or torch.any(counts < 0) or int(counts.sum()) != total_clips ): raise ValueError( "audio_num_clips must contain each request's nonnegative clip count" ) return counts.tolist()
def _default_rope_parameters(config, device=None, seq_len=None): """Unscaled RoPE, retained locally because Transformers 5 removed its registry entry.""" dimension = int(config.head_dim * getattr(config, "partial_rotary_factor", 1.0)) frequencies = ( torch.arange(0, dimension, 2, dtype=torch.float32, device=device) / dimension ) return 1.0 / (config.rope_theta**frequencies), 1.0
def roll_tensor(tensor, shifts=-1, dims=-1, fill_value=0): """Roll the tensor input along the given dimension(s). Inserted elements are set to be 0.0. """ rolled_tensor = torch.roll(tensor, shifts=shifts, dims=dims) rolled_tensor.select(dims, shifts).fill_(fill_value) return rolled_tensor, rolled_tensor.sum()
try: from fla.modules import FusedRMSNormGated, ShortConvolution from fla.ops.kda import chunk_kda, fused_recurrent_kda from fla.utils import tensor_cacheexcept ImportError as error: raise ImportError( "Ming KDA requires fla-core and its dependencies; see requirements.txt." ) from error
# This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.# It means that the function will not be traced through and simply appear as a node in the graph.if is_torch_fx_available(): if not is_torch_greater_or_equal_than_1_13: import torch.fx
_prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
logger = logging.get_logger(__name__)
_CONFIG_FOR_DOC = "MingV3ASRConfig"
def index_first_axis(x, indices): other_shape = x.shape[1:] second_dim = other_shape.numel() return torch.gather( rearrange(x, "b ... -> b (...)"), 0, repeat(indices, "z -> z d", d=second_dim), ).reshape(-1, *other_shape)
def index_put_first_axis(x, indices, first_axis_dim): y = torch.zeros(first_axis_dim, *x.shape[1:], device=x.device, dtype=x.dtype) y[indices] = x # y.scatter_(0, repeat(indices, 'z -> z d', d=x.shape[1]), x) return y
def pad_input( hidden_states: torch.Tensor, indices: torch.LongTensor, batch_size: int, seq_len: int,) -> torch.Tensor: output = index_put_first_axis(hidden_states, indices, batch_size * seq_len) return rearrange(output, "(b s) ... -> b s ...", b=batch_size)
@tensor_cachedef _get_unpad_data(attention_mask): seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32) indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten() max_seqlen_in_batch = seqlens_in_batch.max().item() cu_seqlens = F.pad( torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0) ) return ( indices, cu_seqlens, max_seqlen_in_batch, )
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): warnings.warn( "Calling `transformers.models.BailingMoeV3.modeling_BailingMoeV3._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask" ) return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
def _make_causal_mask( input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0,): warnings.warn( "Calling `transformers.models.BailingMoeV3.modeling_BailingMoeV3._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.BailingMoeV3.modeling_BailingMoeV3.AttentionMaskConverter._make_causal_mask" ) return AttentionMaskConverter._make_causal_mask( input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length, )
class BailingMoeV3RMSNorm(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ BailingMoeV3RMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps
def forward(self, hidden_states): input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) return self.weight * hidden_states.to(input_dtype)
class BailingMoeV3GroupRMSNorm(nn.Module): def __init__(self, hidden_size, group_norm_size, eps=1e-6): """ BailingMoeV3RMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.group_norm_size = group_norm_size assert hidden_size % group_norm_size == 0, ( "hidden_size must be divisible by group_norm_size" ) self.variance_epsilon = eps
def forward(self, hidden_states): input_dtype = hidden_states.dtype input_shape = hidden_states.size() group_input_shape = input_shape[:-1] + ( self.group_norm_size, input_shape[-1] // self.group_norm_size, ) hidden_states = hidden_states.view(group_input_shape) hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) return self.weight * hidden_states.to(input_dtype).view(input_shape)
ALL_LAYERNORM_LAYERS.append(BailingMoeV3RMSNorm)
class BailingMoeV3RotaryEmbedding(nn.Module): """Sequential rotary positions shared by audio and text tokens."""
inv_freq: torch.Tensor
def __init__(self, config: BailingMoeV3Config, device=None): super().__init__() # BC: "rope_type" was originally "type" if hasattr(config, "rope_scaling") and config.rope_scaling is not None: self.rope_type = config.rope_scaling.get( "rope_type", config.rope_scaling.get("type") ) else: self.rope_type = "default" self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings
self.config = deepcopy(config) self.config.head_dim = config.qk_rope_head_dim self.config.partial_rotary_factor = 1.0 self.rope_init_fn = ( _default_rope_parameters if self.rope_type == "default" else ROPE_INIT_FUNCTIONS[self.rope_type] )
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device) self.register_buffer("inv_freq", inv_freq, persistent=False) self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
@torch.no_grad() @dynamic_rope_update def forward(self, x, position_ids): if position_ids.ndim != 2: raise ValueError( "Audio/text position_ids must have shape [batch, sequence]" ) inv_freq = ( self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1) ) positions = position_ids[:, None, :].float() device_type = x.device.type if x.device.type != "mps" else "cpu" with torch.autocast(device_type=device_type, enabled=False): freqs = (inv_freq @ positions).transpose(1, 2) emb = torch.cat((freqs, freqs), dim=-1) cos = emb.cos() * self.attention_scaling sin = emb.sin() * self.attention_scaling return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
# Copied from transformers.models.llama.modeling_llama.rotate_halfdef rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1)
# Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_embdef apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1): """Applies Rotary Position Embedding to the query and key tensors. Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. Returns: `tuple(torch.Tensor)` comprising the query and key tensors rotated using the Rotary Position Embedding. """ cos = cos.unsqueeze(unsqueeze_dim) sin = sin.unsqueeze(unsqueeze_dim)
# Keep half or full tensor for later concatenation rotary_dim = cos.shape[-1] q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:] k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
# Apply rotary embeddings on the first half or full tensor q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin) k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
# Concatenate back to full shape q_embed = torch.cat([q_embed, q_pass], dim=-1) k_embed = torch.cat([k_embed, k_pass], dim=-1) return q_embed, k_embed
class BailingMoeV3MLP(nn.Module): def __init__( self, config: BailingMoeV3Config, intermediate_size: int, swiglu_limit: Optional[float] = None, ): super().__init__() self.config = config self.hidden_size = config.hidden_size self.intermediate_size = intermediate_size self.swiglu_limit = swiglu_limit
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False) self.act_fn = ACT2FN[config.hidden_act]
def forward(self, x): gate = self.gate_proj(x) up = self.up_proj(x) if self.swiglu_limit is None and gate.dtype in (torch.float16, torch.bfloat16): # Match fused SiLU/product: round once, after multiplication. activated = (self.act_fn(gate.float()) * up.float()).to(gate.dtype) return self.down_proj(activated) gate = self.act_fn(gate) if self.swiglu_limit is not None: # The checkpoint clips after SiLU, before multiplication/down projection. gate = gate.clamp(max=self.swiglu_limit) up = up.clamp(min=-self.swiglu_limit, max=self.swiglu_limit) return self.down_proj(gate * up)
class BailingMoeV3Gate(nn.Module): def __init__(self, config): super().__init__() self.config = config self.top_k = config.num_experts_per_tok self.num_experts = config.num_experts
self.n_group = config.n_group self.topk_group = config.topk_group
# topk selection algorithm self.gating_dim = config.hidden_size self.weight = nn.Parameter(torch.empty((self.num_experts, self.gating_dim))) self.routed_scaling_factor = config.routed_scaling_factor
self.register_buffer("expert_bias", torch.zeros((self.num_experts))) self.reset_parameters()
def reset_parameters(self) -> None: import torch.nn.init as init
init.kaiming_uniform_(self.weight, a=math.sqrt(5))
def group_limited_topk( self, scores: torch.Tensor, ): num_tokens, _ = scores.size() # Organize the experts into groups group_scores = ( scores.view(num_tokens, self.n_group, -1).topk(2, dim=-1)[0].sum(dim=-1) ) group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1] group_mask = torch.zeros_like(group_scores) group_mask.scatter_(1, group_idx, 1)
# Mask the experts based on selection groups score_mask = ( group_mask.unsqueeze(-1) .expand(num_tokens, self.n_group, self.num_experts // self.n_group) .reshape(num_tokens, -1) )
masked_scores = scores.masked_fill(~score_mask.bool(), float("-inf")) probs, top_indices = torch.topk(masked_scores, k=self.top_k, dim=-1)
return probs, top_indices
def forward(self, hidden_states): # compute gating score hidden_states = hidden_states.view(-1, hidden_states.shape[-1]) logits = F.linear( hidden_states.type(torch.float32), self.weight.type(torch.float32) )
scores = torch.sigmoid(logits.float()).type_as(logits)
scores_for_routing = scores + self.expert_bias _, topk_idx = self.group_limited_topk(scores_for_routing)
scores = torch.gather(scores, dim=1, index=topk_idx).type_as(logits)
topk_weight = ( scores / (scores.sum(dim=-1, keepdim=True) + 1e-20) if self.top_k > 1 else scores ) topk_weight = topk_weight * self.routed_scaling_factor
return topk_idx, topk_weight, logits
class BailingMoeV3SparseMoeBlock(nn.Module): """ A mixed expert module containing shared experts. """
@staticmethod def _get_swiglu_limit(limits, layer_idx): if limits is None or not 0 <= layer_idx < len(limits): return None return limits[layer_idx] or None
def __init__(self, config: BailingMoeV3Config, layer_idx: int = 0): super().__init__() self.config = config self.num_experts_per_tok = config.num_experts_per_tok self.expert_swiglu_limit = self._get_swiglu_limit( config.expert_swiglu_limit_list, layer_idx ) self.share_expert_swiglu_limit = self._get_swiglu_limit( config.share_expert_swiglu_limit_list, layer_idx ) self._setup_experts() self.gate = BailingMoeV3Gate(config) if config.num_shared_experts is not None: self.shared_experts = BailingMoeV3MLP( config=config, intermediate_size=config.moe_shared_expert_intermediate_size * config.num_shared_experts, swiglu_limit=self.share_expert_swiglu_limit, )
def _setup_experts(self): self.experts = nn.ModuleList( [ BailingMoeV3MLP( config=self.config, intermediate_size=self.config.moe_intermediate_size, swiglu_limit=self.expert_swiglu_limit, ) for _ in range(self.config.num_experts) ] )
def forward(self, hidden_states): identity = hidden_states bsz, seq_len, h = hidden_states.shape topk_idx, topk_weight, router_logits = self.gate(hidden_states) hidden_states = hidden_states.view(-1, hidden_states.shape[-1]) flat_topk_idx = topk_idx.view(-1) if self.training: hidden_states = hidden_states.repeat_interleave( self.num_experts_per_tok, dim=0 ) y = torch.empty_like(hidden_states) for i, expert in enumerate(self.experts): y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i]) y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1) y = y.to(hidden_states.dtype).view(bsz, seq_len, h) else: y = self.moe_infer(hidden_states, topk_idx, topk_weight).view( bsz, seq_len, h ) if self.config.num_shared_experts is not None: y = y + self.shared_experts(identity) return y, ( router_logits.view(bsz, seq_len, -1), topk_idx.view(bsz, seq_len, -1), )
@torch.no_grad() def moe_infer(self, x, topk_ids, topk_weight): cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts))) cnts.scatter_(1, topk_ids, 1) tokens_per_expert = cnts.sum(dim=0) idxs = topk_ids.view(-1).argsort() sorted_tokens = x[idxs // topk_ids.shape[1]] tokens_per_expert = tokens_per_expert.cpu().numpy() outputs = [] start_idx = 0 for i, num_tokens in enumerate(tokens_per_expert): end_idx = start_idx + num_tokens if num_tokens == 0: continue expert = self.experts[i] tokens_for_this_expert = sorted_tokens[start_idx:end_idx] expert_out = expert(tokens_for_this_expert) outputs.append(expert_out.to(x.device)) start_idx = end_idx
outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0) new_x = torch.empty_like(outs) new_x[idxs] = outs final_out = ( new_x.view(*topk_ids.shape, -1) .type(topk_weight.dtype) .mul_(topk_weight.unsqueeze(dim=-1)) .sum(dim=1) .type(new_x.dtype) ) return final_out
# =============================================================================# Text Model Components# =============================================================================
# Copied from transformers.models.llama.modeling_llama.repeat_kvdef repeat_kv( hidden_states: torch.Tensor, n_rep: int, head_first: bool = True) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). If head_first is True, the hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ if n_rep == 1: return hidden_states if head_first: batch, num_key_value_heads, slen, head_dim = hidden_states.shape hidden_states = hidden_states[:, :, None, :, :].expand( batch, num_key_value_heads, n_rep, slen, head_dim ) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) else: batch, slen, num_key_value_heads, head_dim = hidden_states.shape hidden_states = hidden_states[:, :, :, None, :].expand( batch, slen, num_key_value_heads, n_rep, head_dim ) return hidden_states.reshape(batch, slen, num_key_value_heads * n_rep, head_dim)
def repeat_kv2(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand( batch, num_key_value_heads, n_rep, slen, head_dim ) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
def eager_attention_forward( module: nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: Optional[torch.Tensor], scaling: float, dropout: float = 0.0, **kwargs: Unpack[TransformersKwargs],): key_states = repeat_kv2(key, module.num_key_value_groups) value_states = repeat_kv2(value, module.num_key_value_groups)
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling if attention_mask is not None: causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] attn_weights = attn_weights + causal_mask
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to( query.dtype ) attn_weights = nn.functional.dropout( attn_weights, p=dropout, training=module.training ) attn_output = torch.matmul(attn_weights, value_states) attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
def apply_rotary_pos_emb_interleave(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): r""" TODO let's just use the original freqcis computation to not have the view transpose + reshape! This is not optimized! Applies Rotary Position Embedding to the query and key tensors.
Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. position_ids (`torch.Tensor`): The position indices of the tokens corresponding to the query and key tensors. For example, this can be used to pass offsetted position ids when working with a KV-cache. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ cos = cos.unsqueeze(unsqueeze_dim) sin = sin.unsqueeze(unsqueeze_dim)
b, h, s, d = q.shape q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
b, h, s, d = k.shape k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed
def yarn_get_mscale(scale=1, mscale=1): if scale <= 1: return 1.0 return 0.1 * mscale * math.log(scale) + 1.0
class BailingMoeV3MultiLatentAttention(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: BailingMoeV3Config, layer_idx: int): super().__init__() self.config = config self.layer_idx = layer_idx self.num_key_value_groups = ( config.num_attention_heads // config.num_key_value_heads ) self.attention_dropout = config.attention_dropout self.num_heads = config.num_attention_heads self.rope_theta = config.rope_theta self.q_lora_rank = config.q_lora_rank self.qk_rope_head_dim = config.qk_rope_head_dim self.kv_lora_rank = config.kv_lora_rank self.v_head_dim = config.v_head_dim self.qk_nope_head_dim = config.qk_nope_head_dim self.qk_head_dim = config.qk_head_dim self.gated_attention_proj_granularity_type = ( config.gated_attention_proj_granularity_type )
self.is_causal = True if self.q_lora_rank is None: self.q_proj = nn.Linear( config.hidden_size, self.num_heads * self.qk_head_dim, bias=False ) else: self.q_a_proj = nn.Linear( config.hidden_size, config.q_lora_rank, bias=config.use_qkv_bias ) self.q_a_layernorm = BailingMoeV3RMSNorm(config.q_lora_rank) self.q_b_proj = nn.Linear( config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False )
self.kv_a_proj_with_mqa = nn.Linear( config.hidden_size, self.kv_lora_rank + self.qk_rope_head_dim, bias=config.use_qkv_bias, ) self.kv_a_layernorm = BailingMoeV3RMSNorm(self.kv_lora_rank) self.kv_b_proj = nn.Linear( self.kv_lora_rank, self.num_heads * (self.qk_nope_head_dim + self.v_head_dim), bias=False, ) if self.gated_attention_proj_granularity_type is None: self.g_proj = None elif self.gated_attention_proj_granularity_type == "head_wise": self.g_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False) elif self.gated_attention_proj_granularity_type == "element_wise": self.g_proj = nn.Linear( config.hidden_size, self.num_heads * self.v_head_dim, bias=False )
self.dense = nn.Linear( self.num_heads * self.v_head_dim, config.hidden_size, bias=config.use_qkv_bias, )
self.scaling = self.qk_head_dim ** (-0.5) if self.config.rope_scaling is not None: mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0) scaling_factor = self.config.rope_scaling.get("factor", 1.0) if mscale_all_dim: mscale = yarn_get_mscale(scaling_factor, mscale_all_dim) self.scaling = self.scaling * mscale * mscale
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58") def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: Optional[torch.Tensor], past_key_values: Optional[Cache] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
batch_size, seq_length = hidden_states.shape[:-1] query_shape = (batch_size, seq_length, -1, self.qk_head_dim) key_shape = ( batch_size, seq_length, -1, self.qk_nope_head_dim + self.v_head_dim, )
if self.q_lora_rank is None: q_states = self.q_proj(hidden_states) else: q_states = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states))) q_states = q_states.view(query_shape).transpose(1, 2) q_pass, q_rot = torch.split( q_states, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1 )
compressed_kv = self.kv_a_proj_with_mqa(hidden_states) k_pass, k_rot = torch.split( compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1 )
k_pass = ( self.kv_b_proj(self.kv_a_layernorm(k_pass)).view(key_shape).transpose(1, 2) ) k_pass, value_states = torch.split( k_pass, [self.qk_nope_head_dim, self.v_head_dim], dim=-1 )
k_rot = k_rot.view(batch_size, 1, seq_length, self.qk_rope_head_dim)
cos, sin = position_embeddings if ( self.config.rope_interleave ): # support using interleaved weights for efficiency q_rot, k_rot = apply_rotary_pos_emb_interleave(q_rot, k_rot, cos, sin) else: q_rot, k_rot = apply_rotary_pos_emb(q_rot, k_rot, cos, sin) k_rot = k_rot.expand(*k_pass.shape[:-1], -1)
query_states = torch.cat((q_pass, q_rot), dim=-1) key_states = torch.cat((k_pass, k_rot), dim=-1)
if past_key_values is not None: # sin and cos are specific to RoPE models; cache_position needed for the static cache cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} key_states, value_states = past_key_values.update( key_states, value_states, self.layer_idx, cache_kwargs )
if ( self.config._attn_implementation == "flash_attention_2" and self.qk_head_dim != self.v_head_dim ): value_states = F.pad(value_states, [0, self.qk_head_dim - self.v_head_dim])
if self.config._attn_implementation == "sdpa" and not kwargs.get( "output_attentions", False ): attn_output = ( F.scaled_dot_product_attention( query_states, key_states, value_states, attn_mask=attention_mask, dropout_p=self.attention_dropout if self.training else 0.0, is_causal=attention_mask is None and seq_length > 1, scale=self.scaling, ) .transpose(1, 2) .contiguous() ) attn_weights = None else: attn_output, attn_weights = eager_attention_forward( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, **kwargs, )
if ( self.config._attn_implementation == "flash_attention_2" and self.qk_head_dim != self.v_head_dim ): attn_output = attn_output[:, :, :, : self.v_head_dim]
if self.g_proj is not None: gate = self.g_proj(hidden_states) gate = F.sigmoid(gate.float()).type_as(hidden_states) if self.gated_attention_proj_granularity_type == "head_wise": attn_output = attn_output * gate[:, :, :, None] else: attn_output = attn_output * gate.view( batch_size, seq_length, self.num_heads, self.v_head_dim )
attn_output = attn_output.reshape(batch_size, seq_length, -1).contiguous() attn_output = self.dense(attn_output) return attn_output, attn_weights, past_key_values
class BailingMoeV3KimiDeltaAttention(nn.Module): def __init__(self, config: BailingMoeV3Config, layer_idx: int): super().__init__() self.config = config self.mode = "chunk"
self.hidden_size = config.hidden_size self.conv_size = config.short_conv_kernel_size self.head_dim = config.head_dim self.num_heads = config.num_attention_heads self.head_k_dim = self.head_dim self.num_k_heads = self.num_heads self.no_kda_lora = config.no_kda_lora self.safe_gate = config.kda_safe_gate self.lower_bound = config.kda_lower_bound
self.layer_idx = layer_idx
assert self.mode in ["chunk", "fused_recurrent"], ( f"Not suppoerted mode `{self.mode}`." )
projection_k_size = self.head_k_dim * self.num_k_heads projection_size = self.head_dim * self.num_heads
self.q_proj = nn.Linear(self.hidden_size, projection_k_size, bias=False) self.k_proj = nn.Linear(self.hidden_size, projection_k_size, bias=False) self.v_proj = nn.Linear(self.hidden_size, projection_size, bias=False)
self.q_conv1d = ShortConvolution( hidden_size=projection_k_size, kernel_size=self.conv_size, activation="silu", ) self.k_conv1d = ShortConvolution( hidden_size=projection_k_size, kernel_size=self.conv_size, activation="silu", ) self.v_conv1d = ShortConvolution( hidden_size=projection_size, kernel_size=self.conv_size, activation="silu", )
self.A_log = torch.nn.Parameter( torch.log(torch.empty(self.num_heads, dtype=torch.float32).uniform_(1, 16)) )
if self.no_kda_lora: self.f_proj = nn.Linear(self.hidden_size, projection_size, bias=False) else: self.f_a_proj = nn.Linear(self.hidden_size, self.head_dim, bias=False) self.f_b_proj = nn.Linear(self.head_dim, projection_size, bias=False)
self.dt_bias = nn.Parameter(torch.empty(projection_size, dtype=torch.float32))
self.b_proj = nn.Linear(self.hidden_size, self.num_heads, bias=False)
if self.no_kda_lora: self.g_proj = nn.Linear(self.hidden_size, projection_size, bias=False) else: self.g_a_proj = nn.Linear(self.hidden_size, self.head_dim, bias=False) self.g_b_proj = nn.Linear(self.head_dim, projection_size, bias=False)
self.o_norm = FusedRMSNormGated( self.head_dim, eps=config.rms_norm_eps, activation="sigmoid" ) self.o_proj = nn.Linear(projection_size, self.hidden_size, bias=False)
def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None = None, past_key_value=None, **kwargs: Unpack[dict], ) -> tuple[torch.Tensor, torch.Tensor | None, Cache | None]: if attention_mask is not None: if attention_mask.dim() != 2: attention_mask = kwargs.get("padding_mask")
if attention_mask is not None and attention_mask.dim() != 2: raise ValueError( "attention_mask must be a 0-1 matrix of shape [batch_size, seq_len] " "(0 = padding). 3D masks are not supported here.", ) use_cache = past_key_value is not None batch_size, q_len, _ = hidden_states.shape mode = "fused_recurrent" if q_len <= 64 else self.mode if self.training: assert mode == "chunk", "Only chunk mode is supported in training."
cu_seqlens = kwargs.get("cu_seqlens") indices = None if attention_mask is not None: attention_mask = attention_mask[:, -q_len:] if bool(attention_mask.bool().all()): attention_mask = None if attention_mask is not None: indices, cu_seqlens, _ = _get_unpad_data(attention_mask) hidden_states = index_first_axis( rearrange(hidden_states, "b s ... -> (b s) ..."), indices ).unsqueeze(0)
conv_state_q, conv_state_k, conv_state_v = None, None, None recurrent_state = None
if past_key_value is not None and isinstance(past_key_value, Cache): cache_layer = past_key_value.layers[self.layer_idx] if not isinstance(cache_layer, LinearAttentionLayer): raise TypeError( "Ming KDA requires a LinearAttentionLayer; construct DynamicCache(config=model.config)" ) if cache_layer.is_recurrent_states_initialized: recurrent_state = cache_layer.recurrent_states.to( hidden_states.device ).contiguous() if cache_layer.is_conv_states_initialized: conv_state_q, conv_state_k, conv_state_v = cache_layer.conv_states.to( hidden_states.device ).unbind(1)
q, conv_state_q = self.q_conv1d( x=self.q_proj(hidden_states), cache=conv_state_q, output_final_state=use_cache, cu_seqlens=cu_seqlens, ) k, conv_state_k = self.k_conv1d( x=self.k_proj(hidden_states), cache=conv_state_k, output_final_state=use_cache, cu_seqlens=cu_seqlens, ) v, conv_state_v = self.v_conv1d( x=self.v_proj(hidden_states), cache=conv_state_v, output_final_state=use_cache, cu_seqlens=cu_seqlens, )
if self.no_kda_lora: g = self.f_proj(hidden_states) else: g = self.f_b_proj(self.f_a_proj(hidden_states))
beta = self.b_proj(hidden_states).float().sigmoid()
q, k = map( lambda x: rearrange(x, "... (h d) -> ... h d", d=self.head_k_dim), (q, k) ) v = rearrange(v, "... (h d) -> ... h d", d=self.head_dim) g = rearrange(g, "... (h d) -> ... h d", d=self.head_dim)
if mode == "chunk": o, recurrent_state = chunk_kda( q=q, k=k, v=v, g=g, beta=beta, A_log=self.A_log, dt_bias=self.dt_bias, initial_state=recurrent_state, output_final_state=True, use_qk_l2norm_in_kernel=True, use_gate_in_kernel=True, safe_gate=self.safe_gate, lower_bound=self.lower_bound, cu_seqlens=cu_seqlens, ) else: o, recurrent_state = fused_recurrent_kda( q=q, k=k, v=v, g=g, beta=beta, A_log=self.A_log, dt_bias=self.dt_bias, initial_state=recurrent_state, output_final_state=True, use_qk_l2norm_in_kernel=True, use_gate_in_kernel=True, lower_bound=self.lower_bound, cu_seqlens=cu_seqlens, )
if ( use_cache and past_key_value is not None and isinstance(past_key_value, Cache) ): # A tensor stack keeps all three convolution states together during # standard cache beam reordering without pretending they are KV pairs. past_key_value.update_conv_state( torch.stack((conv_state_q, conv_state_k, conv_state_v), dim=1), self.layer_idx, ) cache_layer = past_key_value.layers[self.layer_idx] if not cache_layer.is_recurrent_states_initialized: # KDA accumulates in FP32 even when convolution states are BF16. # Preserve that dtype instead of using the convolution buffer dtype. cache_layer.recurrent_states = torch.empty_like(recurrent_state) cache_layer.is_recurrent_states_initialized = True past_key_value.update_recurrent_state(recurrent_state, self.layer_idx)
if self.no_kda_lora: g = self.g_proj(hidden_states) else: g = self.g_b_proj(self.g_a_proj(hidden_states)) g = rearrange(g, "... (h d) -> ... h d", d=self.head_dim) o = self.o_norm(o, g)
o = rearrange(o, "b t h d -> b t (h d)") o = self.o_proj(o) if attention_mask is not None: o = pad_input(o.squeeze(0), indices, batch_size, q_len)
return o, None, past_key_value
class BailingMoeV3MTPLayer(nn.Module): def __init__(self, config: BailingMoeV3Config, layer_idx: int): super().__init__() self.layer_idx = layer_idx self.input_layernorm = BailingMoeV3RMSNorm( config.hidden_size, eps=config.rms_norm_eps ) self.enorm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.eh_proj = nn.Linear(config.hidden_size * 2, config.hidden_size, bias=False) self.post_attention_layernorm = BailingMoeV3RMSNorm( config.hidden_size, eps=config.rms_norm_eps ) self.attention = BailingMoeV3MultiLatentAttention( config=config, layer_idx=layer_idx ) self.mlp = BailingMoeV3SparseMoeBlock(config, layer_idx=layer_idx)
self.hnorm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.final_layernorm = BailingMoeV3RMSNorm( config.hidden_size, eps=config.rms_norm_eps )
def forward( self, input_embeds, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, output_attentions: Optional[bool] = False, output_router_logits: Optional[bool] = False, use_cache: Optional[bool] = False, position_embeddings: Optional[ Tuple[torch.Tensor, torch.Tensor] ] = None, # necessary, but kept here for BC **kwargs, ) -> Tuple[ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]] ]: input_embeds = self.enorm(input_embeds) hidden_states = self.hnorm(hidden_states) hidden_states = self.eh_proj(torch.cat([input_embeds, hidden_states], dim=-1)) residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
# Self Attention hidden_states, self_attn_weights, present_key_value = self.attention( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_value, output_attentions=output_attentions, position_embeddings=position_embeddings, use_cache=use_cache, ) hidden_states = residual + hidden_states
# Fully Connected residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) if isinstance(hidden_states, tuple): hidden_states, router_logits = hidden_states else: router_logits = None hidden_states = residual + hidden_states.to(residual.device) hidden_states = self.final_layernorm(hidden_states)
outputs = (hidden_states,)
if output_attentions: outputs += (self_attn_weights,)
if use_cache: outputs += (present_key_value,)
if output_router_logits: outputs += (router_logits,)
return outputs
class BailingMoeV3DecoderLayer(nn.Module): def __init__(self, config: BailingMoeV3Config, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.layer_idx = layer_idx self.attention_layer_type = ( "attention" if (layer_idx + 1) % config.layer_group_size == 0 or layer_idx >= config.num_hidden_layers // config.layer_group_size * config.layer_group_size else "linear_attention" )
if self.attention_layer_type == "attention": self.attention = BailingMoeV3MultiLatentAttention( config=config, layer_idx=layer_idx ) else: self.attention = BailingMoeV3KimiDeltaAttention( config=config, layer_idx=layer_idx )
self.mlp = ( BailingMoeV3SparseMoeBlock(config, layer_idx=layer_idx) if ( config.num_experts is not None and layer_idx >= config.first_k_dense_replace ) else BailingMoeV3MLP( config=config, intermediate_size=config.intermediate_size ) ) self.input_layernorm = BailingMoeV3RMSNorm( config.hidden_size, eps=config.rms_norm_eps ) self.post_attention_layernorm = BailingMoeV3RMSNorm( config.hidden_size, eps=config.rms_norm_eps )
def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, cache_position: Optional[torch.LongTensor] = None, output_attentions: Optional[bool] = False, output_router_logits: Optional[bool] = False, use_cache: Optional[bool] = False, position_embeddings: Optional[ Tuple[torch.Tensor, torch.Tensor] ] = None, # necessary, but kept here for BC padding_mask: Optional[torch.Tensor] = None, **kwargs, ) -> Tuple[ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]] ]: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`, *optional*): attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1, query_sequence_length, key_sequence_length)` if default attention is used. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`. past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states output_attentions (`bool`, *optional*): Whether to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_router_logits (`bool`, *optional*): Whether or not to return the logits of all the routers. They are useful for computing the router loss, and should not be returned during inference. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). """ residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
# Self Attention if self.attention_layer_type == "attention": hidden_states, self_attn_weights, present_key_value = self.attention( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_value, output_attentions=output_attentions, use_cache=use_cache, cache_position=cache_position, # position_embeddings=position_embeddings, # **kwargs, ) else: hidden_states, self_attn_weights, present_key_value = self.attention( hidden_states=hidden_states, attention_mask=padding_mask, past_key_value=past_key_value, position_ids=position_ids, use_cache=use_cache, output_attentions=output_attentions, )
hidden_states = residual + hidden_states
# Fully Connected residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) if isinstance(hidden_states, tuple): hidden_states, router_logits = hidden_states else: router_logits = None hidden_states = residual + hidden_states.to(residual.device)
outputs = (hidden_states,)
if output_attentions: outputs += (self_attn_weights,)
if use_cache: outputs += (present_key_value,)
if output_router_logits: outputs += (router_logits,)
return outputs
BAILINGMOEV3_START_DOCSTRING = r""" This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`BailingMoeV3Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights."""
@dataclassclass MingV3ASRModelOutputWithPast(ModelOutput): last_hidden_state: Optional[torch.FloatTensor] = None past_key_values: Optional[Cache] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None router_logits: Optional[tuple[torch.FloatTensor]] = None
@dataclassclass MingV3ASRCausalLMOutputWithPast(ModelOutput): loss: Optional[torch.FloatTensor] = None logits: Optional[torch.FloatTensor] = None past_key_values: Optional[Cache] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None router_logits: Optional[tuple[torch.FloatTensor]] = None aux_loss: Optional[torch.FloatTensor] = None
@add_start_docstrings( "The bare BailingMoeV3 VL Model outputting raw hidden-states without any specific head on top.", BAILINGMOEV3_START_DOCSTRING,)class BailingMoeV3PreTrainedModel(PreTrainedModel): config_class = MingV3ASRConfig base_model_prefix = "model" # Routing corrections are saved in FP32. Rounding this small buffer can # change selected experts, even when the rest of the model uses BF16. _keep_in_fp32_modules_strict = ["expert_bias"] supports_gradient_checkpointing = True _no_split_modules = ["BailingMoeV3DecoderLayer"] _skip_keys_device_placement = "past_key_values" _supports_flash_attn_2 = False _supports_flash_attn = False _supports_sdpa = True _supports_cache_class = True
def _init_weights(self, module): if hasattr(self.config, "initializer_range"): std = self.config.initializer_range else: std = getattr(self.config.get_text_config(), "initializer_range", 0.02) if isinstance(module, BailingMoeV3RotaryEmbedding): # Nonpersistent buffers are absent from checkpoints. HF's meta-device # loader materializes them before initialization, so rebuild frequencies # here as well as in __init__ rather than retaining empty storage. inv_freq, module.attention_scaling = module.rope_init_fn( module.config, module.inv_freq.device ) module.inv_freq.copy_(inv_freq) module.original_inv_freq.copy_(inv_freq) elif isinstance(module, BailingMoeV3KimiDeltaAttention): # Match FLA KDA's log-uniform time steps and inverse-softplus bias. # HF also calls this hook after materializing missing checkpoint # parameters; preserve a dt_bias that was actually loaded. if not getattr(module.dt_bias, "_is_hf_initialized", False): dt = torch.exp( torch.rand_like(module.dt_bias, dtype=torch.float32) * (math.log(0.1) - math.log(0.001)) + math.log(0.001) ).clamp(min=1e-4) with torch.no_grad(): module.dt_bias.copy_(dt + torch.log(-torch.expm1(-dt))) elif isinstance(module, nn.Linear): if not getattr(module.weight, "_is_hf_initialized", False): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None and not getattr( module.bias, "_is_hf_initialized", False ): module.bias.data.zero_() elif isinstance(module, nn.Embedding): if not getattr(module.weight, "_is_hf_initialized", False): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_()
BAILINGMOEV3_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. If `past_key_values` is used, optionally only the last `input_ids` have to be input (see `past_key_values`). If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy. - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids) past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*): Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`. Two formats are allowed: - a [`~cache_utils.Cache`] instance; - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy cache format. The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the legacy cache format will be returned. If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids` of shape `(batch_size, sequence_length)`. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple."""
@add_start_docstrings( "The bare BailingMoeV3 Model outputting raw hidden-states without any specific head on top.", BAILINGMOEV3_START_DOCSTRING,)class BailingMoeV3Model(BailingMoeV3PreTrainedModel): """ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`BailingMoeV3DecoderLayer`] Args: config: BailingMoeV3Config """
def __init__(self, config: BailingMoeV3Config): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.num_nextn_predict_layers = config.num_nextn_predict_layers
self.word_embeddings = nn.Embedding( config.vocab_size, config.hidden_size, self.padding_idx ) layers = [] for layer_idx in range( config.num_hidden_layers + config.num_nextn_predict_layers ): layer_cls = ( BailingMoeV3DecoderLayer if layer_idx < config.num_hidden_layers else BailingMoeV3MTPLayer ) layers.append(layer_cls(config, layer_idx)) self.layers = nn.ModuleList(layers)
self._use_sdpa = config._attn_implementation == "sdpa" self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2" self.norm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.rotary_emb = BailingMoeV3RotaryEmbedding(config=config) self.gradient_checkpointing = False # Initialize weights and apply final processing self.post_init()
def get_input_embeddings(self): return self.word_embeddings
def set_input_embeddings(self, value): self.word_embeddings = value
@add_start_docstrings_to_model_forward(BAILINGMOEV3_INPUTS_DOCSTRING) def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, cache_position: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, output_router_logits: Optional[bool] = None, return_dict: Optional[bool] = None, **kwargs, ) -> Union[Tuple, MoeModelOutputWithPast]: output_attentions = ( output_attentions if output_attentions is not None else self.config.output_attentions ) output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) output_router_logits = ( output_router_logits if output_router_logits is not None else self.config.output_router_logits ) use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = ( return_dict if return_dict is not None else self.config.use_return_dict )
# retrieve input_ids and inputs_embeds if input_ids is not None and inputs_embeds is not None: raise ValueError( "You cannot specify both input_ids and inputs_embeds at the same time" ) elif input_ids is not None: batch_size, seq_length = input_ids.shape[:2] elif inputs_embeds is not None: batch_size, seq_length = inputs_embeds.shape[:2] else: raise ValueError("You have to specify either input_ids or inputs_embeds")
if self.gradient_checkpointing and self.training: if use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`." ) use_cache = False
if use_cache and past_key_values is None: past_key_values = DynamicCache(config=self.config)
if inputs_embeds is None: inputs_embeds = self.word_embeddings(input_ids)
if cache_position is None: past_seen_tokens = ( past_key_values.get_seq_length() if past_key_values is not None else 0 ) cache_position = torch.arange( past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device, )
if position_ids is None: position_ids = cache_position.unsqueeze(0) if position_ids.ndim != 2: raise ValueError( "Audio/text position_ids must have shape [batch, sequence]" )
past_seen_tokens = ( past_key_values.get_seq_length() if past_key_values is not None else 0 )
# Preserve padding independently of backend-specific causal mask transformations. padding_mask = ( attention_mask if attention_mask is not None and attention_mask.ndim == 2 else None )
if self._use_flash_attention_2: # 2d mask is passed through the layers attention_mask = ( attention_mask if (attention_mask is not None and 0 in attention_mask) else None ) elif self._use_sdpa and not output_attentions: attention_mask = _prepare_4d_causal_attention_mask_for_sdpa( attention_mask, (batch_size, seq_length), inputs_embeds, past_seen_tokens, ) else: # 4d mask is passed through the layers attention_mask = _prepare_4d_causal_attention_mask( attention_mask, (batch_size, seq_length), inputs_embeds, past_seen_tokens, )
# embed positions hidden_states = inputs_embeds
# create position embeddings to be shared across the decoder layers position_embeddings = self.rotary_emb(hidden_states, position_ids)
# decoder layers all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None all_router_logits = () if output_router_logits else None next_decoder_cache = None
# Split main decoder layers and MTP layers main_layers = ( self.layers[: -self.num_nextn_predict_layers] if self.num_nextn_predict_layers > 0 else self.layers ) mtp_layers = ( self.layers[-self.num_nextn_predict_layers :] if self.num_nextn_predict_layers > 0 else None )
for decoder_layer in main_layers: if output_hidden_states: all_hidden_states += (hidden_states,)
if self.gradient_checkpointing and self.training: layer_outputs = self._gradient_checkpointing_func( decoder_layer.__call__, hidden_states, attention_mask, position_ids, past_key_values, cache_position, output_attentions, output_router_logits, use_cache, position_embeddings, padding_mask, ) else: layer_outputs = decoder_layer( hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_values, cache_position=cache_position, output_attentions=output_attentions, output_router_logits=output_router_logits, use_cache=use_cache, position_embeddings=position_embeddings, padding_mask=padding_mask, ) hidden_states = layer_outputs[0]
if use_cache: next_decoder_cache = layer_outputs[2 if output_attentions else 1]
if output_attentions: all_self_attns += (layer_outputs[1],)
if output_router_logits and layer_outputs[-1] is not None: all_router_logits += (layer_outputs[-1],)
hidden_states = self.norm(hidden_states) main_hidden_states = hidden_states
# add hidden states from the last decoder layer if output_hidden_states: all_hidden_states += (main_hidden_states,)
# MTP layers (training only) if mtp_layers and self.training: for decoder_layer in mtp_layers: input_ids, _ = roll_tensor(input_ids, shifts=-1, dims=-1) mtp_inputs_embeds = self.word_embeddings(input_ids)
if self.gradient_checkpointing and self.training: layer_outputs = self._gradient_checkpointing_func( decoder_layer.__call__, mtp_inputs_embeds, hidden_states, attention_mask, position_ids, past_key_values, output_attentions, output_router_logits, use_cache, position_embeddings, ) else: layer_outputs = decoder_layer( mtp_inputs_embeds, hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_values, output_attentions=output_attentions, output_router_logits=output_router_logits, use_cache=use_cache, position_embeddings=position_embeddings, ) hidden_states = layer_outputs[0]
if output_hidden_states: all_hidden_states += (hidden_states,)
if use_cache: next_decoder_cache = layer_outputs[2 if output_attentions else 1]
if output_attentions: all_self_attns += (layer_outputs[1],)
if output_router_logits and layer_outputs[-1] is not None: all_router_logits += (layer_outputs[-1],)
next_cache = None if use_cache: next_cache = next_decoder_cache if not return_dict: return tuple( v for v in [ main_hidden_states, next_cache, all_hidden_states, all_self_attns, all_router_logits, ] if v is not None ) return MoeModelOutputWithPast( last_hidden_state=main_hidden_states, past_key_values=next_cache, hidden_states=all_hidden_states, attentions=all_self_attns, router_logits=all_router_logits, )
# =============================================================================# Composite Audio Model# =============================================================================
class MingV3ASRModel(BailingMoeV3Model): """Ming Audio V3 encoder and text decoder with stable checkpoint keys.
Inherits from BailingMoeV3Model so that LLM sub-modules (word_embeddings, layers, norm, rotary_emb) live directly on ``self``, matching the checkpoint key namespace (``model.layers.*`` etc.) produced by the conversion script. """
def __init__(self, config: MingV3ASRConfig): # Initialise LLM backbone with text_config # self.config remains text_config so BailingMoeV3Model.forward works correctly super().__init__(config.text_config) # Keep the composite audio configuration alongside the language config. self._audio_model_config = config # Audio encoder self.audio = build_audio_encoder(config.audio_config)
def get_audio_features(self, audio_feats, audio_feats_lengths, projector): """Return valid audio embeddings in clip order, with no batch padding.""" lengths = _audio_clip_lengths(audio_feats, audio_feats_lengths) clips = [features[:length] for features, length in zip(audio_feats, lengths)] return encode_audio_clips( clips, self.audio, projector, self._audio_model_config.audio_config )
def get_audio_placeholder_mask(self, input_ids, inputs_embeds): if input_ids is None: marker = self.get_input_embeddings()( torch.tensor( self._audio_model_config.audio_token_id, dtype=torch.long, device=inputs_embeds.device, ) ) mask = (inputs_embeds == marker).all(-1) else: mask = input_ids == self._audio_model_config.audio_token_id return mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, audio_feats: Optional[torch.FloatTensor] = None, audio_feats_lengths: Optional[torch.LongTensor] = None, audio_num_clips: Optional[torch.LongTensor] = None, mm_token_type_ids: Optional[torch.IntTensor] = None, projector_audio: Optional[nn.Module] = None, **kwargs, ) -> Union[Tuple, MingV3ASRModelOutputWithPast]: if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError( "You must specify exactly one of input_ids or inputs_embeds" )
if inputs_embeds is None: inputs_embeds = self.get_input_embeddings()(input_ids)
_reject_visual_inputs(kwargs) if mm_token_type_ids is not None and not torch.all( (mm_token_type_ids == 0) | (mm_token_type_ids == 3) ): raise ValueError("Ming supports only text/audio token types")
# Process audio if audio_feats is not None: lengths = _audio_clip_lengths(audio_feats, audio_feats_lengths) counts = _audio_request_counts( audio_num_clips, inputs_embeds.shape[0], len(lengths) ) spec = MingAudioSpec.from_config(self._audio_model_config.audio_config) token_counts = [spec.token_count(length) for length in lengths] audio_mask = self.get_audio_placeholder_mask(input_ids, inputs_embeds) clip_index = 0 for index, count in enumerate(counts): expected = sum(token_counts[clip_index : clip_index + count]) actual = int(audio_mask[index, :, 0].sum()) if actual != expected: raise ValueError( f"Audio placeholder count for request {index} is {actual}, expected {expected}" ) clip_index += count audio_embeds = self.get_audio_features( audio_feats, audio_feats_lengths, projector=projector_audio ) audio_embeds_cvt = audio_embeds.to( inputs_embeds.device, inputs_embeds.dtype ) inputs_embeds = inputs_embeds.masked_scatter(audio_mask, audio_embeds_cvt) elif audio_feats_lengths is not None or audio_num_clips is not None: raise ValueError("Audio lengths and clip counts require audio_feats") # Raw lengths are the model's mask contract; optional frontend masks do # not belong to the language decoder's attention arguments. kwargs.pop("audio_attention_mask", None)
if ( position_ids is None and attention_mask is not None and attention_mask.ndim == 2 ): position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 0) position_ids = position_ids[:, -inputs_embeds.shape[1] :]
return_dict = kwargs.pop("return_dict", None) if return_dict is None: return_dict = self.config.use_return_dict outputs = super().forward( input_ids=None, position_ids=position_ids, attention_mask=attention_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, return_dict=True, **kwargs, )
result = MingV3ASRModelOutputWithPast( last_hidden_state=outputs.last_hidden_state, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, router_logits=outputs.router_logits, ) return result if return_dict else result.to_tuple()
class MingV3ASRForConditionalGeneration( BailingMoeV3PreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.word_embeddings.weight"} # Legacy mixed checkpoints may contain unused vision tensors. Only these # explicit namespaces are excluded; audio/LM loading diagnostics stay strict. _keys_to_ignore_on_load_unexpected = [r"^model\.visual\.", r"^linear_proj\."] accepts_loss_kwargs = False
def __init__(self, config: MingV3ASRConfig, **kwargs): super().__init__(config, **kwargs) self.model = MingV3ASRModel(config)
# Keep checkpoint-configured projector indices (Tiny: 0, 3). self.linear_proj_audio = build_audio_projector( config.audio_config, config.text_config.hidden_size, config.mlp_depth )
self.lm_head = nn.Linear( config.text_config.hidden_size, config.text_config.vocab_size, bias=False )
self.post_init()
def get_input_embeddings(self): return self.model.get_input_embeddings()
def set_input_embeddings(self, value): self.model.set_input_embeddings(value)
def get_output_embeddings(self): return self.lm_head
def set_output_embeddings(self, new_embeddings): self.lm_head = new_embeddings
def get_audio_features(self, audio_feats, audio_feats_lengths, **kwargs): return self.model.get_audio_features( audio_feats=audio_feats, audio_feats_lengths=audio_feats_lengths, projector=self.linear_proj_audio, **kwargs, )
def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, audio_feats: Optional[torch.Tensor] = None, audio_feats_lengths: Optional[torch.LongTensor] = None, audio_num_clips: Optional[torch.LongTensor] = None, mm_token_type_ids: Optional[torch.IntTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs, ) -> Union[Tuple, MingV3ASRCausalLMOutputWithPast]: return_dict = kwargs.pop("return_dict", None) if return_dict is None: return_dict = self.config.use_return_dict outputs = self.model( input_ids=input_ids, audio_feats=audio_feats, audio_feats_lengths=audio_feats_lengths, audio_num_clips=audio_num_clips, mm_token_type_ids=mm_token_type_ids, position_ids=position_ids, attention_mask=attention_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, projector_audio=self.linear_proj_audio, return_dict=True, **kwargs, )
hidden_states = outputs[0]
# Only compute necessary logits slice_indices = ( slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep ) logits = self.lm_head(hidden_states[:, slice_indices, :])
loss = None if labels is not None: loss = self.loss_function( logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, )
result = MingV3ASRCausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, router_logits=outputs.router_logits, )
return result if return_dict else result.to_tuple()
def prepare_inputs_for_generation( self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, position_ids=None, use_cache=True, is_first_iteration=None, **kwargs, ): _reject_visual_inputs(kwargs) model_inputs = super().prepare_inputs_for_generation( input_ids, past_key_values=past_key_values, attention_mask=attention_mask, inputs_embeds=inputs_embeds, position_ids=position_ids, use_cache=use_cache, is_first_iteration=is_first_iteration, **kwargs, )
has_cached_tokens = False if use_cache: if is_first_iteration is not None: has_cached_tokens = not is_first_iteration elif kwargs.get("cache_position") is not None: has_cached_tokens = ( bool(kwargs["cache_position"].numel()) and int(kwargs["cache_position"][0]) > 0 ) elif past_key_values is not None: has_cached_tokens = past_key_values.get_seq_length() > 0 if has_cached_tokens: for key in ( "audio_feats", "audio_feats_lengths", "audio_num_clips", "audio_attention_mask", ): model_inputs[key] = None
return model_inputs
def _expand_inputs_for_generation( self, expand_size: int = 1, is_encoder_decoder: bool = False, input_ids: Optional[torch.LongTensor] = None, **model_kwargs, ) -> Tuple[torch.LongTensor, dict]: if expand_size == 1: return input_ids, model_kwargs
audio_keys = ( "audio_feats", "audio_feats_lengths", "audio_num_clips", "audio_attention_mask", )
if model_kwargs.get("audio_feats") is not None: features = model_kwargs["audio_feats"] lengths = _audio_clip_lengths( features, model_kwargs.get("audio_feats_lengths") ) batch_size = ( input_ids.shape[0] if input_ids is not None else model_kwargs["inputs_embeds"].shape[0] ) counts = _audio_request_counts( model_kwargs.get("audio_num_clips"), batch_size, len(lengths) ) groups = torch.split(torch.arange(len(lengths)), counts) clip_order = torch.cat([group.repeat(expand_size) for group in groups]) for key in ("audio_feats", "audio_feats_lengths", "audio_attention_mask"): if model_kwargs.get(key) is not None: value = torch.as_tensor(model_kwargs[key]) model_kwargs[key] = value.index_select( 0, clip_order.to(value.device) ) count_device = model_kwargs["audio_feats_lengths"].device model_kwargs["audio_num_clips"] = torch.tensor( counts, device=count_device ).repeat_interleave(expand_size)
def _expand_dict_for_generation(dict_to_expand): for key in dict_to_expand: if ( dict_to_expand[key] is not None and isinstance(dict_to_expand[key], torch.Tensor) and key not in audio_keys ): dict_to_expand[key] = dict_to_expand[key].repeat_interleave( expand_size, dim=0 ) return dict_to_expand
if input_ids is not None: input_ids = input_ids.repeat_interleave(expand_size, dim=0)
model_kwargs = _expand_dict_for_generation(model_kwargs)
if is_encoder_decoder: if model_kwargs.get("encoder_outputs") is None: raise ValueError( "If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined." ) model_kwargs["encoder_outputs"] = _expand_dict_for_generation( model_kwargs["encoder_outputs"] )
return input_ids, model_kwargs1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889# Copyright 2026 Ant Group. All rights reserved.# Licensed under the Apache License, Version 2.0."""Standalone Ming V3 ASR audio tower and checkpoint-compatible projector.
Waveform preprocessing belongs to the feature extractor. This module consumesraw mel clips, chunks by the trained context, and returns normalized embeddings.Parameter names are deliberately stable for existing safetensors checkpoints."""
import torchfrom torch import nnfrom torch.nn import functional as F
from .audio_spec import MingAudioSpecfrom .modeling_whisper_encoder import WhisperAudioEncoder
class Transpose(nn.Module): def forward(self, value): return value.transpose(-1, -2)
def build_audio_encoder(config): get = ( config.get if isinstance(config, dict) else lambda k, d=None: getattr(config, k, d) ) settings = get("whisper_encoder_config") if settings is None: settings = dict( n_mels=get("n_mels", 128), n_ctx=get("n_audio_ctx", 3000), n_state=get("n_audio_state", 1280), n_head=get("n_audio_head", 20), n_layer=get("n_audio_layer", 32), ) return WhisperAudioEncoder(**settings)
def build_audio_projector(config, hidden_size, mlp_depth=2): spec = MingAudioSpec.from_config(config) get = ( config.get if isinstance(config, dict) else lambda k, d=None: getattr(config, k, d) ) encoder = get("whisper_encoder_config") or {} input_size = encoder.get("n_state", get("n_audio_state", 1280)) layers = [] for kernel, stride, padding in zip(spec.kernels, spec.strides, spec.paddings): layers.extend( [nn.Conv1d(input_size, hidden_size, kernel, stride, padding), nn.GELU()] ) input_size = hidden_size layers.extend([Transpose(), nn.Linear(hidden_size, hidden_size)]) for _ in range(2, mlp_depth): layers.extend([nn.GELU(), nn.Linear(hidden_size, hidden_size)]) return nn.Sequential(*layers)
def encode_audio_clips(clips, encoder, projector, config): """Encode each chunk with a fixed batch shape, preserving clip order.
Padding cannot be removed only after attention: both attention and stacked biased convolutions would already have changed valid positions. """ if not clips: raise ValueError("Audio clips must not be empty") spec = MingAudioSpec.from_config(config) parameter = next(projector.parameters()) chunks = [] for clip in clips: if clip.ndim != 2 or clip.shape[1] != spec.n_mels or not clip.shape[0]: raise ValueError("Audio clips require positive [frames, mel_bins] shapes") chunks.extend( clip.to(device=parameter.device, dtype=parameter.dtype).split( spec.chunk_frames ) ) outputs = [] # Keep the BF16 GEMM batch shape independent of neighboring requests. for chunk in chunks: encoded = encoder(chunk.unsqueeze(0)) projected = projector(encoded.transpose(-1, -2))[0] if projected.shape[0] != spec.embedding_length(chunk.shape[0]): raise ValueError("Audio projector output violates the length contract") outputs.append(projected) return F.normalize(torch.cat(outputs), dim=-1)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141# Adapted from OpenAI Whisper: https://github.com/openai/whisper# MIT License## Copyright (c) 2022 OpenAI## Permission is hereby granted, free of charge, to any person obtaining a copy# of this software and associated documentation files (the "Software"), to deal# in the Software without restriction, including without limitation the rights# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell# copies of the Software, and to permit persons to whom the Software is# furnished to do so, subject to the following conditions:## The above copyright notice and this permission notice shall be included in all# copies or substantial portions of the Software.## THE SOFTWARE IS PROVIDED "AS IS", 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 THE# AUTHORS 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.
"""Local Whisper-compatible audio encoder used by Ming audio models."""
import math
import torchimport torch.nn.functional as Ffrom torch import Tensor, nn
class _WhisperLayerNorm(nn.LayerNorm): def forward(self, x: Tensor) -> Tensor: return F.layer_norm( x.float(), self.normalized_shape, self.weight.float() if self.weight is not None else None, self.bias.float() if self.bias is not None else None, self.eps, ).to(dtype=x.dtype)
class _WhisperLinear(nn.Linear): def forward(self, x: Tensor) -> Tensor: return F.linear( x, self.weight.to(dtype=x.dtype), None if self.bias is None else self.bias.to(dtype=x.dtype), )
class _WhisperConv1d(nn.Conv1d): def _conv_forward(self, x: Tensor, weight: Tensor, bias: Tensor | None) -> Tensor: return super()._conv_forward( x, weight.to(dtype=x.dtype), None if bias is None else bias.to(dtype=x.dtype), )
def _sinusoids(length: int, channels: int, max_timescale: int = 10000) -> Tensor: assert channels % 2 == 0 log_timescale_increment = math.log(max_timescale) / (channels // 2 - 1) inv_timescales = torch.exp(-log_timescale_increment * torch.arange(channels // 2)) scaled_time = torch.arange(length)[:, None] * inv_timescales[None, :] return torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim=1)
class _WhisperMultiHeadAttention(nn.Module): def __init__(self, n_state: int, n_head: int): super().__init__() self.n_head = n_head self.query = _WhisperLinear(n_state, n_state) self.key = _WhisperLinear(n_state, n_state, bias=False) self.value = _WhisperLinear(n_state, n_state) self.out = _WhisperLinear(n_state, n_state)
def forward(self, x: Tensor) -> Tensor: batch_size, sequence_length, n_state = x.shape head_dim = n_state // self.n_head q = self.query(x).view(batch_size, sequence_length, self.n_head, head_dim) k = self.key(x).view(batch_size, sequence_length, self.n_head, head_dim) v = self.value(x).view(batch_size, sequence_length, self.n_head, head_dim) q = q.permute(0, 2, 1, 3) k = k.permute(0, 2, 1, 3) v = v.permute(0, 2, 1, 3) x = F.scaled_dot_product_attention(q, k, v) x = x.permute(0, 2, 1, 3).flatten(start_dim=2) return self.out(x)
class _WhisperResidualAttentionBlock(nn.Module): def __init__(self, n_state: int, n_head: int): super().__init__() self.attn = _WhisperMultiHeadAttention(n_state, n_head) self.attn_ln = _WhisperLayerNorm(n_state) self.mlp = nn.Sequential( _WhisperLinear(n_state, n_state * 4), nn.GELU(), _WhisperLinear(n_state * 4, n_state), ) self.mlp_ln = _WhisperLayerNorm(n_state)
def forward(self, x: Tensor) -> Tensor: x = x + self.attn(self.attn_ln(x)) return x + self.mlp(self.mlp_ln(x))
class WhisperAudioEncoder(nn.Module): """Whisper encoder with Ming's variable-length ``[B, T, n_mels]`` input."""
def __init__( self, n_mels: int, n_ctx: int, n_state: int, n_head: int, n_layer: int ): super().__init__() self.conv1 = _WhisperConv1d(n_mels, n_state, kernel_size=3, padding=1) self.conv2 = _WhisperConv1d( n_state, n_state, kernel_size=3, stride=2, padding=1 ) self.register_buffer("positional_embedding", _sinusoids(n_ctx, n_state)) self.blocks = nn.ModuleList( [_WhisperResidualAttentionBlock(n_state, n_head) for _ in range(n_layer)] ) self.ln_post = _WhisperLayerNorm(n_state) self.audio_emb_dim = n_state
def forward(self, x: Tensor) -> Tensor: """Encode a batch of mel spectrograms shaped ``[batch, frames, mels]``.""" x = x.transpose(1, 2) x = F.gelu(self.conv1(x)) x = F.gelu(self.conv2(x)) x = x.permute(0, 2, 1) positional_embedding = self.positional_embedding[: x.shape[1], :] assert x.shape[1:] == positional_embedding.shape, "incorrect audio shape" x = (x + positional_embedding).to(dtype=x.dtype)
for block in self.blocks: x = block(x)
return self.ln_post(x)12345678910111213141516171819202122232425262728{ "feature_extractor_type": "MingV3ASRFeatureExtractor", "processor_class": "MingV3ASRProcessor", "feature_size": 128, "sampling_rate": 16000, "padding_value": 0.0, "audio_config": { "n_mels": 128, "n_audio_ctx": 3000, "n_audio_state": 1280, "n_audio_head": 20, "n_audio_layer": 32, "downsampler_kernel_size_list": [ 3 ], "downsampler_stride_list": [ 2 ], "chunk_frames": 3000, "downsampler_padding_list": [ 1 ] }, "auto_map": { "AutoFeatureExtractor": "feature_extraction_ming_v3_asr.MingV3ASRFeatureExtractor", "AutoProcessor": "processing_ming_v3_asr.MingV3ASRProcessor" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248# Copyright 2026 Ant Group. All rights reserved.# Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0# 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."""Hugging Face processor for Ming V3 ASR transcription."""
import re
import numpy as npimport torchfrom transformers.feature_extraction_utils import BatchFeaturefrom transformers.processing_utils import ProcessingKwargs, ProcessorMixin
from .audio_spec import MingAudioSpec # noqa: F401 - include transitive dependency in HF's local module cachefrom .feature_extraction_ming_v3_asr import MingV3ASRFeatureExtractor
_AUDIO_FORMS = ( ("<audio>", "<audioPatch>", "</audio>"), ("<|audio_start|>", "<|audio_pad|>", "<|audio_end|>"),)_PLACEHOLDER = "<AUDIO>"_ASR_INSTRUCTION = ( "Please recognize the language of this speech and transcribe it, " "placing a `\t` between the identified language and the transcribe.")
class MingV3ASRProcessorKwargs(ProcessingKwargs, total=False): _defaults = { "text_kwargs": { "padding": False, "padding_side": "left", "return_attention_mask": True, "return_token_type_ids": False, }, }
class MingV3ASRProcessor(ProcessorMixin): """Expand audio tokens and combine an unchanged tokenizer with log-mel.
``audio`` (or the compatible ``audios`` spelling) is a flat list of clips in prompt-placeholder order. ``audio_num_clips`` records each text request's clip count, including zero. Audio features and raw lengths are flattened independently of the text batch. Image/video inputs are not supported.
Chat-template support is inherited from ``ProcessorMixin`` for tokenizer compatibility. ASR inference uses ``apply_transcription_request`` instead. """
feature_extractor_class = "AutoFeatureExtractor" tokenizer_class = "AutoTokenizer" valid_processor_kwargs = MingV3ASRProcessorKwargs
def __init__( self, feature_extractor: MingV3ASRFeatureExtractor, tokenizer, chat_template=None, ): template = tokenizer.chat_template if chat_template is None else chat_template super().__init__(feature_extractor, tokenizer, chat_template=template) vocabulary = tokenizer.get_vocab() self.audio_start_token, self.audio_token, self.audio_end_token = next( ( form for form in _AUDIO_FORMS if all(token in vocabulary for token in form) ), (None, None, None), ) if self.audio_token is None: raise ValueError("tokenizer lacks Ming audio start/patch/end tokens") self.audio_token_id = tokenizer.convert_tokens_to_ids(self.audio_token)
@staticmethod def _normalize_prompt(text): for start, patch, end in _AUDIO_FORMS: text = re.sub( re.escape(start) + "(?:" + re.escape(patch) + ")+" + re.escape(end), _PLACEHOLDER, text, ) return text
def __call__( self, text=None, audio=None, *, images=None, videos=None, audios=None, **kwargs ): if images is not None or videos is not None: raise ValueError("MingV3ASRProcessor supports audio and text only") if audio is not None and audios is not None: raise ValueError("Pass either audio or audios, not both") clips = self.feature_extractor.as_clips(audio if audio is not None else audios) if text is None: if not clips: raise ValueError("Provide text or audio") text = " ".join([_PLACEHOLDER] * len(clips)) texts = [text] if isinstance(text, str) else text if ( not isinstance(texts, (list, tuple)) or not texts or not all(isinstance(t, str) for t in texts) ): raise ValueError("text must be a string or a nonempty list of strings") texts = [self._normalize_prompt(t) for t in texts] clip_counts = [t.count(_PLACEHOLDER) for t in texts] if sum(clip_counts) != len(clips): raise ValueError( f"Audio placeholder count {sum(clip_counts)} does not match {len(clips)} clips" )
options = self._merge_kwargs( MingV3ASRProcessorKwargs, tokenizer_init_kwargs=self.tokenizer.init_kwargs, **kwargs, ) text_options = options["text_kwargs"] audio_options = options["audio_kwargs"] return_tensors = text_options.get("return_tensors") audio_return_tensors = audio_options.get("return_tensors") if ( return_tensors is not None and audio_return_tensors is not None and return_tensors != audio_return_tensors ): raise ValueError("text and audio return_tensors must match") if return_tensors is None: return_tensors = audio_return_tensors if return_tensors is not None: text_options["return_tensors"] = return_tensors audio_options["return_tensors"] = return_tensors if text_options.get("return_overflowing_tokens"): raise ValueError("Audio token overflow windows are not supported") # Top-level max_length/truncation refer to text; audio is always chunked. # Explicit nested audio options retain extractor validation. for key in ("max_length", "truncation", "padding"): if key not in kwargs.get("audio_kwargs", {}): audio_options.pop(key, None) audio_inputs = self.feature_extractor(clips, **audio_options) if clips else {} lengths = audio_inputs.get("audio_feats_lengths", []) token_counts = [ self.feature_extractor.spec.token_count(int(length)) for length in lengths ]
expected_counts = [] clip_index = 0 for index, count in enumerate(clip_counts): expected_counts.append(sum(token_counts[clip_index : clip_index + count])) for token_count in token_counts[clip_index : clip_index + count]: replacement = ( self.audio_start_token + self.audio_token * token_count + self.audio_end_token ) texts[index] = texts[index].replace(_PLACEHOLDER, replacement, 1) clip_index += count encoded = self.tokenizer(texts, **text_options) for ids, expected in zip(encoded["input_ids"], expected_counts): actual = sum(int(token) == self.audio_token_id for token in ids) if actual != expected: raise ValueError( "Audio token count changed during tokenization; do not truncate audio placeholders" ) if clips: if return_tensors == "pt": audio_inputs["audio_num_clips"] = torch.tensor( clip_counts, dtype=torch.long ) elif return_tensors == "np": audio_inputs["audio_num_clips"] = np.asarray( clip_counts, dtype=np.int64 ) else: audio_inputs["audio_num_clips"] = clip_counts return BatchFeature(data={**encoded, **audio_inputs})
def apply_transcription_request( self, audio, *, prompt=None, language_hint=None, audio_chunk_frames=None, return_tensors="pt", ): """Prepare one audio request in the released ASR input format.
``prompt`` starts with the base ASR instruction and may append topic and hotwords without a newline. A known language can be prefixed to the generated answer with ``language_hint='zh'`` or ``'en'``. """ if prompt is None: prompt = _ASR_INSTRUCTION if not isinstance(prompt, str) or not prompt.startswith(_ASR_INSTRUCTION): raise ValueError("Prompt must start with the base ASR instruction") if "\n" in prompt or "\r" in prompt: raise ValueError("Prompt metadata must be contiguous, without newlines") if _PLACEHOLDER in prompt: raise ValueError("Prompt must not contain <AUDIO>; it is appended here") if audio_chunk_frames is not None: if (isinstance(audio_chunk_frames, bool) or not isinstance(audio_chunk_frames, int) or audio_chunk_frames < 1): raise ValueError("audio_chunk_frames must be a positive integer") extractor = self.feature_extractor original_config = extractor.audio_config extractor.audio_config = {**original_config, "chunk_frames": audio_chunk_frames} try: _ = extractor.spec inputs = self( text=prompt + _PLACEHOLDER, audio=audio, return_tensors=return_tensors, ) finally: extractor.audio_config = original_config else: inputs = self( text=prompt + _PLACEHOLDER, audio=audio, return_tensors=return_tensors, ) if language_hint is not None: label = {"zh": "Chinese\t", "en": "English\t"}.get(language_hint) if label is None: raise ValueError("language_hint must be 'zh', 'en', or None") if return_tensors != "pt": raise ValueError("language_hint requires return_tensors='pt'") label_ids = self.tokenizer( label, add_special_tokens=False, return_tensors="pt", )["input_ids"] if inputs.input_ids.shape[0] != 1: raise ValueError("language_hint requires exactly one audio request") inputs["input_ids"] = torch.cat((inputs.input_ids, label_ids), dim=1) if "attention_mask" in inputs: inputs["attention_mask"] = torch.cat( (inputs.attention_mask, torch.ones_like(label_ids)), dim=1, ) return inputs
@property def model_input_names(self): return [ "input_ids", "attention_mask", "audio_feats", "audio_feats_lengths", "audio_num_clips", ]
MingV3ASRProcessor.register_for_auto_class()1234567891011# Python 3.12, Linux, CUDA 13.0 (NVIDIA L20Y).# For another CUDA version, install matching PyTorch 2.11.0 wheels first.torch==2.11.0torchaudio==2.11.0transformers==5.12.1fla-core==0.5.2accelerate==1.15.0einops==0.8.2safetensors==0.8.0numpy==2.5.4soundfile==0.14.01234567891011121314151617181920212223242526272829303132333435363738394041424344{ "additional_special_tokens": [ "<|arithmetic_end|>", "<role>", "<|number_end|>", "<|arithmetic_start|>", "</role>", "<|number_start|>", "<|role_end|>", "<tool_call>", "</tool_call>", "<tool_response>", "</tool_response>" ], "bos_token": { "content": "<|startoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "cls_token": { "content": "[CLS]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "eos_token": { "content": "<|role_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "gmask_token": { "content": "[gMASK]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "pad_token": "<|role_end|>"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155#!/usr/bin/env python3# coding=utf-8# Copyright (c) Ant Group. All rights reserved.
import itertoolsfrom typing import Any, Dict, List, Optional, Union
import torchfrom transformers import PreTrainedTokenizerFastfrom transformers.tokenization_utils_base import AddedToken, BatchEncodingfrom transformers.utils import TensorType, logging
logger = logging.get_logger(__name__)
def is_system(msg): return msg["role"].lower() == "system"
def is_user(msg): return msg["role"].lower() in ["human", "user"]
def is_assistant(msg): return msg["role"].lower() == "assistant"
def _convert_to_conversation(query, system=None): conversation = [] if system: conversation.append({"role": "SYSTEM", "content": system}) if isinstance(query, str): conversation.append({"role": "HUMAN", "content": query}) elif isinstance(query, List): conversation.extend(query) elif isinstance(query, Dict): if "messages" in query: conversation.extend(query["messages"]) if ( "system_message" in query and len(conversation) > 0 and not is_system(conversation[0]) ): conversation.insert( 0, {"role": "SYSTEM", "content": query["system_message"]} ) else: conversation.append(query) return conversation
class BailingTokenizer(PreTrainedTokenizerFast): is_bailing_tokenizer = True model_input_names = ["input_ids", "attention_mask"] slow_tokenizer_class = None
# add gmask_token SPECIAL_TOKENS_ATTRIBUTES = [ "bos_token", "eos_token", "unk_token", "sep_token", "pad_token", "cls_token", "mask_token", "gmask_token", "additional_special_tokens", ]
def __init__( self, vocab_file=None, merges_file=None, tokenizer_file=None, clean_up_tokenization_spaces=False, bos_token="<|startoftext|>", eos_token="<|endoftext|>", cls_token="[CLS]", pad_token="<|endoftext|>", gmask_token="[gMASK]", add_bos_token=False, add_eos_token=False, **kwargs, ): self._gmask_token = ( AddedToken(gmask_token, lstrip=False, rstrip=False, normalized=False) if isinstance(gmask_token, str) else gmask_token )
self._sop_token = ( AddedToken(bos_token, lstrip=False, rstrip=False, normalized=False) if isinstance(bos_token, str) else bos_token )
self._eop_token = ( AddedToken(eos_token, lstrip=False, rstrip=False, normalized=False) if isinstance(eos_token, str) else eos_token )
super().__init__( vocab_file=vocab_file, merges_file=merges_file, tokenizer_file=tokenizer_file, clean_up_tokenization_spaces=clean_up_tokenization_spaces, bos_token=bos_token, eos_token=eos_token, cls_token=cls_token, pad_token=pad_token, gmask_token=gmask_token, add_bos_token=add_bos_token, add_eos_token=add_eos_token, **kwargs, )
if not hasattr(self, "add_bos_token"): self.add_bos_token = add_bos_token
self.check_special_tokens()
def check_special_tokens(self): """ eos_token, cls_token, mask_token special tokens should init, check special token is not None """ for name, special_token in zip( ["eos", "bos", "cls", "gmask"], [self.eos_token, self.bos_token, self.cls_token, self.gmask_token], ): assert special_token is not None, ( f"should init special token [{name}] in tokenizer_config.json" )
@property def gmask_token(self) -> Optional[str]: if self._gmask_token is None: if self.verbose: logger.error("Using gmask_token, but it is not set yet.") return None return str(self._gmask_token)
@gmask_token.setter def gmask_token(self, value): if not isinstance(value, (str, AddedToken)) and value is not None: raise ValueError("Cannot set a non-string value as the gmask token") self._gmask_token = value
@property def gmask_token_id(self) -> Optional[int]: if self._gmask_token is None: return None return self.convert_tokens_to_ids(self.gmask_token)
@property def sop_token(self) -> Optional[str]: if self._sop_token is None: if self.verbose: logger.error("Using sop_token, but it is not set yet.") return None return str(self._sop_token)
@sop_token.setter def sop_token(self, value): if not isinstance(value, (str, AddedToken)) and value is not None: raise ValueError("Cannot set a non-string value as the sop token") self._sop_token = value
@property def sop_token_id(self) -> Optional[int]: if self._sop_token is None: return None return self.convert_tokens_to_ids(self.sop_token)
@property def eop_token(self) -> Optional[str]: if self._eop_token is None: if self.verbose: logger.error("Using eop_token, but it is not set yet.") return None return str(self._eop_token)
@eop_token.setter def eop_token(self, value): if not isinstance(value, (str, AddedToken)) and value is not None: raise ValueError("Cannot set a non-string value as the eop token") self._eop_token = value
@property def eop_token_id(self) -> Optional[int]: if self._eop_token is None: return None return self.convert_tokens_to_ids(self.eop_token)
@property def vocab_size(self): return len(self.get_vocab())
def _chat_from_json(self, chat, chat_format="antglm_chat", system=None): msgs = chat if "messages" not in chat else chat["messages"] _msgs = [] sys_msg = None for msg in msgs: if is_system(msg): sys_msg = msg["content"] else: _msgs.append(msg) chat = {"messages": _msgs} system = system or sys_msg if system: chat["system_message"] = system from .chat_format import Chat
return Chat.from_json(chat, name=chat_format)
def apply_chat_template( self, conversation: Union[List[Dict[str, str]], List[List[Dict[str, str]]]], tools: Optional[List[Dict]] = None, documents: Optional[List[Dict[str, str]]] = None, chat_template: Optional[str] = None, add_generation_prompt: bool = False, system: str = None, # only used for legacy chatml tokenize=False, padding: bool = False, truncation: bool = False, max_length: Optional[int] = None, return_tensors: Optional[Union[str, TensorType]] = None, return_dict: bool = False, return_assistant_tokens_mask: bool = False, tokenizer_kwargs: Optional[Dict[str, Any]] = None, **kwargs, ): if hasattr(self, "chat_template") and self.chat_template: if isinstance(conversation, Dict) and "messages" in conversation: conversation = conversation["messages"] # use transformers built-in method return super().apply_chat_template( conversation=conversation, tools=tools, documents=documents, chat_template=chat_template, add_generation_prompt=add_generation_prompt, tokenize=tokenize, padding=padding, truncation=truncation, max_length=max_length, return_tensors=return_tensors, return_dict=return_dict, return_assistant_tokens_mask=return_assistant_tokens_mask, tokenizer_kwargs=tokenizer_kwargs, **kwargs, )
# 非chat_template方式后续将不再支持。 logger.warning("Please set chat_template in tokenizer_config.json!")
chat_format = kwargs.get("chat_format", "antglm_chat")
is_batched = False
if isinstance(conversation, List) and ( isinstance(conversation[0], (list, tuple)) or "messages" in conversation[0] ): conversations = conversation is_batched = True
if not is_batched: conversations = [conversation]
rendered = [] for chat in conversations: rendered_chat = self._chat_from_json( chat, chat_format=chat_format, system=system ).prompt_str rendered.append(rendered_chat)
if not is_batched: rendered = rendered[0]
if tokenize: out = self( rendered, padding=padding, truncation=truncation, max_length=max_length, add_special_tokens=False, return_tensors=return_tensors, ) if return_dict: return out else: return out["input_ids"] else: return rendered
def _build_position_ids( self, mask_pos: int, bos_pos: int, max_output_length: int, rotary_type: Optional[str] = "none", **kwargs, ) -> List[List[int]]: window_size = kwargs.get("window_size", 1024) - 1 block_position_ids = [0] * bos_pos
# 获得mask所在的位置,用于后面output positionid的构造 if "1d" in rotary_type: position_ids = list(range(bos_pos)) + list( range(mask_pos + 1, mask_pos + max_output_length + 2) ) block_position_ids = block_position_ids + list( range(1, max_output_length + 2) ) elif "2d" in rotary_type: # 后面input_ids要加一个bos_id position_ids = list(range(bos_pos)) position_ids = position_ids + [mask_pos] * (1 + max_output_length) block_position_ids = block_position_ids + list( range(1, max_output_length + 2) ) else: # build position ids position_ids = [] repeat_times = bos_pos // window_size for _ in range(repeat_times): position_ids += list(range(window_size)) position_ids += list(range(bos_pos - window_size * repeat_times)) # need consider additional bos_id after input_ids mask_pos = position_ids[-1] position_ids += [mask_pos] * (max_output_length + 1)
block_repeat_times = max_output_length // (window_size - 1) additional_block_position_ids = [] for _ in range(block_repeat_times): additional_block_position_ids += list(range(1, window_size)) additional_block_position_ids += list( range(1, max_output_length + 2 - (window_size - 1) * block_repeat_times) ) block_position_ids = block_position_ids + additional_block_position_ids
position_ids = [position_ids, block_position_ids] return position_ids
def _build_inputs_for_generation( self, input_ids: List[int], max_input_length=None, left_truncate=True, max_output_length=1024, rotary_type="none", unidirectional_attention: bool = True, attention_dtype=None, **kwargs, ): if max_input_length and len(input_ids) > max_input_length: if left_truncate: input_ids = input_ids[-max_input_length:] else: input_ids = input_ids[:max_input_length]
is_left_padding = input_ids[0] == self.eos_token_id if not unidirectional_attention: if input_ids[0] != self.cls_token_id: input_ids = [self.cls_token_id] + input_ids
if self.gmask_token_id not in set(input_ids): input_ids = input_ids + [self.gmask_token_id]
mask_pos = input_ids.index(self.gmask_token_id) sep = len(input_ids) else: if self.add_bos_token: input_ids = input_ids + [self.bos_token_id] if self.eos_token_id in input_ids: mask_pos = input_ids.index(self.eos_token_id) - 1 else: mask_pos = len(input_ids) - 1 sep = len(input_ids) - 1 else: sep = len(input_ids) if self.eos_token_id in input_ids: if is_left_padding: ori_input_ids = input_ids input_ids = input_ids[::-1] mask_pos = input_ids.index(self.eos_token_id) - 1 mask_pos = max(0, mask_pos) # for empty sequence if is_left_padding: input_ids = ori_input_ids mask_pos = sep - 1 - mask_pos # the first non-eos token
else: mask_pos = len(input_ids) - 1
position_ids = self._build_position_ids( mask_pos, sep, max_output_length, rotary_type, **kwargs )
if is_left_padding: position_ids[0] = [ max(0, i - mask_pos) for i in range(len(position_ids[0])) ]
# 后面input_ids要加一个bos_id total_length = sep + max_output_length if self.add_bos_token: total_length += 1
def build_mask_matrix(seq_length, sep, mask_pos, unidirectional_attention): # 长序列使用bool类型节省显存 if unidirectional_attention: attention_mask = torch.ones( [seq_length, seq_length], dtype=attention_dtype ) attention_mask = torch.tril(attention_mask) if is_left_padding: attention_mask[:, :mask_pos] = 0 else: attention_mask[:, mask_pos + 1 : sep] = 0 else: attention_mask = torch.zeros( [seq_length, seq_length], dtype=attention_dtype ) attention_mask[:, : mask_pos + 1] = 1 for i in range(sep, total_length): attention_mask[i, sep : i + 1] = 1 return attention_mask
if self.add_bos_token: attention_mask = build_mask_matrix( total_length, sep + 1, mask_pos, unidirectional_attention ) else: attention_mask = build_mask_matrix( total_length, sep, mask_pos, unidirectional_attention ) attention_mask = torch.unsqueeze(attention_mask, dim=0) attention_mask = torch.unsqueeze(attention_mask, dim=1) if attention_dtype is None: attention_mask = attention_mask.long() inputs = { "input_ids": torch.Tensor([input_ids]).long(), "position_ids": torch.Tensor([position_ids]).long(), "attention_mask": attention_mask, } return BatchEncoding(inputs)
def build_inputs_for_generation( self, input_ids: Union[List[int], List[List[int]], torch.Tensor], max_input_length=None, left_truncate=True, max_output_length=1024, rotary_type="1d", unidirectional_attention=True, attention_dtype=None, **kwargs, ): if isinstance(input_ids, torch.Tensor): input_ids = input_ids.tolist()
if isinstance(input_ids[0], list): input_ids_list = [] position_ids_list = [] attention_mask_list = [] for _input_ids in input_ids: inputs = self._build_inputs_for_generation( _input_ids, max_input_length=max_input_length, left_truncate=left_truncate, max_output_length=max_output_length, rotary_type=rotary_type, unidirectional_attention=unidirectional_attention, attention_dtype=attention_dtype, **kwargs, ) input_ids_list.append(inputs["input_ids"]) position_ids_list.append(inputs["position_ids"]) attention_mask_list.append(inputs["attention_mask"])
max_ids_length = max([input.size(1) for input in input_ids_list])
for i in range(len(input_ids)): cur_ids_length = input_ids_list[i].size(1) if cur_ids_length < max_ids_length: # pad input ids pad_input_ids = input_ids_list[i].new_zeros( (1, max_ids_length - cur_ids_length) ) input_ids_list[i] = torch.cat( [pad_input_ids, input_ids_list[i]], dim=-1 )
# pad postition ids with left pad # 0, 1, 2, 3, 4 ... -> 0, ..., 0, 1, 2, 3, 4, ... pad_position_ids = input_ids_list[i].new_zeros( (1, 2, max_ids_length - cur_ids_length) ) position_ids_list[i] = torch.cat( [pad_position_ids, position_ids_list[i]], dim=-1 )
# pad generation attention mask with left and bottom pad new_attention_mask = input_ids_list[i].new_zeros( 1, 1, max_ids_length + max_output_length, max_ids_length + max_output_length, ) new_attention_mask[ :, :, max_ids_length - cur_ids_length :, max_ids_length - cur_ids_length :, ] = attention_mask_list[i] attention_mask_list[i] = new_attention_mask.contiguous()
input_ids_list = torch.cat(input_ids_list, dim=0) position_ids_list = torch.cat(position_ids_list, dim=0) attention_mask_list = torch.cat(attention_mask_list, dim=0)
inputs = { "input_ids": input_ids_list, "position_ids": position_ids_list, "attention_mask": attention_mask_list, }
return BatchEncoding(inputs) else: return self._build_inputs_for_generation( input_ids, max_input_length=max_input_length, left_truncate=left_truncate, max_output_length=max_output_length, rotary_type=rotary_type, unidirectional_attention=unidirectional_attention, **kwargs, )
def _build_inputs_for_train( self, inputs: Union[str, List[str]], outputs: Union[str, List[str]], new_conversation_offset: List[int] = None, max_length: int = 2048, rotary_type: str = "1d", left_truncate: bool = True, unidirectional_attention: bool = True, isolation_position_ids: bool = False, padding: bool = True, use_fa2: bool = True, use_packed: bool = True, use_baichuan_packed: bool = False, skip_truncated_turn: bool = False, return_attention_mask: bool = True, ): r""" Build tensor input for model training. If inputs and outputs are list, will pack them.
Args: inputs (str, List[str], List[Dict], List[List[Dict]]): the input prompts. outputs (str, List[str]): the output responses. max_length (int, Optional): the maximum length of the final input ids for training. Default: 2048 rotary_type (str, Optional): the rotary type of position embedding. Default: 1d left_truncate (bool, Optional): whether truncate the inputs from left. Default: True use_fa2 (bool, Optional): whether to build attention mask under flash attention 2. new_conversation_offset (List[int], Optional): 第idx条样本是全新的对话,[0, 1]代表:inputs[0]和outputs[0]是一个对话,inputs[1]和outputs[1]是一个对话. """ if use_packed and use_baichuan_packed and unidirectional_attention: return self._build_baichuan_inputs_for_train( inputs, outputs, new_conversation_offset, max_length, rotary_type, left_truncate, skip_truncated_turn, use_fa2, padding, ) if isinstance(inputs, str): inputs = [inputs] if isinstance(outputs, str): outputs = [outputs]
assert len(inputs) == len(outputs)
input_ids = [self(item)["input_ids"] for item in inputs] output_ids = [self(item)["input_ids"] for item in outputs]
packed_input_ids = [] packed_output_ids = [] if new_conversation_offset is None: new_conversation_offset = list(range(0, len(inputs))) assert 0 in new_conversation_offset, ( f"没有0,请检查new_conversation_offset: {new_conversation_offset}" ) current_len = 0
for idx, (input, output) in enumerate(zip(input_ids, output_ids)): num_special_tokens = 0 if not unidirectional_attention: if idx in new_conversation_offset: # cls and gmask num_special_tokens += 2 else: # only gmask num_special_tokens += 1 else: # sop and eos if self.add_bos_token: num_special_tokens += 2 else: num_special_tokens += 1
# truncate if len(input) + len(output) + current_len > max_length - num_special_tokens: if not use_packed or use_fa2 and unidirectional_attention: attention_mask = torch.tensor(0) elif use_fa2: attention_mask = -1 * torch.ones([2, max_length]) else: attention_mask = torch.tril(torch.ones([max_length, max_length])) # 返回一个空的样本,该样本不参与训练 default_return = { "input_ids": (torch.ones(max_length) * self.eos_token_id).long(), "position_ids": torch.zeros(2, max_length).long(), "attention_mask": (attention_mask.long()), "labels": (torch.ones(max_length) * -100).long(), } # 如果不截断,直接返回 if skip_truncated_turn: if current_len == 0: return default_return else: break left_len = max_length - num_special_tokens - current_len # 如果截断,只截断prompt if left_len - len(output) > 0: if left_truncate: input = input[-(left_len - len(output)) :] else: input = input[: left_len - len(output)] else: # response超过left_len,直接返回 if current_len == 0: return default_return else: break if unidirectional_attention: packed_input_ids.append(list(input)) else: if num_special_tokens == 4: packed_input_ids.append( [self.cls_token_id] + list(input) + [self.gmask_token_id] ) else: packed_input_ids.append(list(input) + [self.gmask_token_id])
packed_output_ids.append(list(output) + [self.eos_token_id]) current_len += len(input) + len(output) + num_special_tokens
assert current_len <= max_length
if use_packed: # pack模式 def build_mask_matrix(seq_length, sep): # https://github.com/pytorch/pytorch/issues/101932, fix triu/tril bf16 support m = torch.ones((1, seq_length, seq_length)) mask = torch.arange(1, m.shape[-1] + 1).reshape(1, -1, 1).to(m.device) ids = ( torch.arange(1, m.shape[-1] + 1) .reshape(1, 1, -1) .expand(1, m.shape[-1], -1) .to(m.device) ) m = (ids <= mask).type_as(m)
m[0, :, : int(sep)] = 1 m = m.squeeze(0) return m
tokens = [] attention_mask_list = [] input_length_list = [] position_id_list = [] block_position_id_list = [] for input, output in zip(packed_input_ids, packed_output_ids): if self.add_bos_token: data = input + [self.sop_token_id] + output mask_pos = len(input) - 1 else: data = input + output mask_pos = len(input) - 2 if return_attention_mask: if unidirectional_attention: attention_mask = build_mask_matrix(len(data), 0) else: attention_mask = build_mask_matrix(len(data), len(input)) attention_mask = attention_mask.squeeze((0, 1))
attention_mask_list.append(attention_mask) input_length_list.append(len(input)) tokens += data
sop_pos = mask_pos + 1 position_ids, block_position_ids = self._build_position_ids( mask_pos=mask_pos, bos_pos=sop_pos, max_output_length=len(output), rotary_type=rotary_type, )
position_id_list.append(position_ids) block_position_id_list.append(block_position_ids)
labels = [] for i in range(len(packed_input_ids)): if self.add_bos_token: labels += ( [-100] * len(packed_input_ids[i]) + packed_output_ids[i] + [-100] ) else: labels += ( [-100] * (len(packed_input_ids[i]) - 1) + packed_output_ids[i] + [-100] )
total_len = 0 if use_fa2: pack_attention_mask = -1 * torch.ones([2, current_len]) else: pack_attention_mask = torch.tril(torch.ones([current_len, current_len]))
pack_position_ids = [] pack_block_position_ids = [] total_len = 0 max_index = 0 for i in range(len(position_id_list)): if use_fa2: pack_attention_mask[0][i] = total_len pack_attention_mask[1][i] = total_len + input_length_list[i] else: pack_attention_mask[ total_len : total_len + attention_mask.shape[0], total_len : total_len + attention_mask.shape[0], ] = attention_mask position_ids = [pid + max_index for pid in position_id_list[i]] block_position_ids = block_position_id_list[i] pack_position_ids.extend(position_ids) pack_block_position_ids.extend(block_position_ids) if not isolation_position_ids: max_index = pack_position_ids[-1] + 1 total_len += len(position_id_list[i]) position_ids = [pack_position_ids, pack_block_position_ids] else: # 单输入模式 # 真多轮下,一条样本可能会有好几轮对话,此时需要获取第一条样本的结束位置 if len(new_conversation_offset) > 1: end_idx = new_conversation_offset[1] else: end_idx = 1 input, output = ( list(itertools.chain(*packed_input_ids[:end_idx])), list(itertools.chain(*packed_output_ids[:end_idx])), ) if self.add_bos_token: tokens = input + [self.sop_token_id] + output else: tokens = input + output
if self.add_bos_token: labels = [-100] * len(input) + output + [-100] position_ids = self._build_position_ids( mask_pos=len(input) - 1, bos_pos=len(input), max_output_length=len(output), rotary_type=rotary_type, ) else: labels = [-100] * (len(input) - 1) + output + [-100] position_ids = self._build_position_ids( mask_pos=len(input) - 2, bos_pos=len(input) - 1, max_output_length=len(output), rotary_type=rotary_type, ) attention_mask = len(input) assert current_len == len(tokens)
# 最大长度补全 if max_length > 0 and len(tokens) < max_length and padding: pad_length = max_length - len(tokens) tokens += [self.pad_token_id] * pad_length labels.extend([-100] * pad_length) position_ids[0] += [0] * pad_length position_ids[1] += [0] * pad_length
if use_packed: if use_fa2: new_attention_mask = -1 * torch.ones([2, max_length]) new_attention_mask[:, :current_len] = pack_attention_mask else: new_attention_mask = torch.tril( torch.ones([max_length, max_length]) ) new_attention_mask[:current_len, :current_len] = pack_attention_mask pack_attention_mask = new_attention_mask.contiguous()
assert len(tokens) == len(labels)
if max_length > 0 and padding: assert len(tokens) == max_length
if use_fa2 and unidirectional_attention: # pack_attention_mask = torch.zeros([1], dtype=torch.long) pack_attention_mask = torch.tensor(0)
if use_packed: if not use_fa2: attention_mask = pack_attention_mask.unsqueeze(0).long() else: attention_mask = pack_attention_mask else: attention_mask = torch.tensor(attention_mask).long() return { "input_ids": torch.tensor(tokens).long(), "position_ids": torch.tensor(position_ids).long(), "attention_mask": attention_mask, "labels": torch.tensor(labels).long(), }
def _build_baichuan_inputs_for_train( self, inputs: Union[str, List[str]], outputs: Union[str, List[str]], new_conversation_offset: List[int] = None, max_length: int = 2048, rotary_type: str = "1d", left_truncate: bool = True, skip_truncated_turn: bool = True, use_fa2: bool = True, padding: bool = True, ): """ input: <role> HUMAN </role> u1 <role> ASSISTANT </role> a11 a12 <role> HUMAN </role> u2 <role> ASSISTANT </role> a21 a22 <|endoftext|> <role> HUMAN </role> u1 <role> ASSISTANT </role> a11 a12 <role> HUMAN </role> u2 <role> ASSISTANT </role> a21 a22 <|endoftext|> output: x x x x x x a11 a12 <|endoftext|> x x x x x x a21 a22 <|endoftext|> x x x x x x x a11 a12 <|endoftext|> x x x x x x a21 a22 <|endoftext|> x 只适用真多轮+pack数据训练单向模型,需要打开use_true_multiturn """ if isinstance(inputs, str): inputs = [inputs] if isinstance(outputs, str): outputs = [outputs] assert len(inputs) == len(outputs)
input_ids = [self(item)["input_ids"] for item in inputs] output_ids = [self(item)["input_ids"] for item in outputs]
packed_input_ids = [] packed_output_ids = []
if new_conversation_offset is None: new_conversation_offset = list(range(0, len(inputs))) assert 0 in new_conversation_offset, ( f"没有0,请检查new_conversation_offset: {new_conversation_offset}" ) current_len = 0
for idx, (input, output) in enumerate(zip(input_ids, output_ids)): num_special_tokens = 0 if idx != 0 and idx in new_conversation_offset: # 在input_ids加入eos,只有第0条样本不加 num_special_tokens += 1
# truncate if len(input) + len(output) + current_len > max_length - num_special_tokens: if use_fa2: attention_mask = torch.tensor(0) else: attention_mask = torch.tril(torch.ones([max_length, max_length])) # 返回一个空的样本,该样本不参与训练 default_return = { "input_ids": (torch.ones(max_length) * self.eos_token_id).long(), "position_ids": torch.zeros(2, max_length).long(), "attention_mask": (attention_mask.long()), "labels": (torch.ones(max_length) * -100).long(), }
# 如果不截断,直接返回 if skip_truncated_turn: if current_len == 0: return default_return else: break left_len = max_length - num_special_tokens - current_len # 如果截断,只截断prompt if left_len - len(output) > 0: if left_truncate: input = input[-(left_len - len(output)) :] else: input = input[: left_len - len(output)] else: # response超过left_len,直接返回 if current_len == 0: return default_return else: break # 这里拼的是input_ids if num_special_tokens == 1: packed_input_ids.append([self.eos_token_id] + list(input)) else: packed_input_ids.append(list(input)) packed_output_ids.append(list(output)) current_len += len(input) + len(output) + num_special_tokens assert current_len <= max_length
def build_mask_matrix(seq_length, sep): # https://github.com/pytorch/pytorch/issues/101932, fix triu/tril bf16 support m = torch.ones((1, seq_length, seq_length)) mask = torch.arange(1, m.shape[-1] + 1).reshape(1, -1, 1).to(m.device) ids = ( torch.arange(1, m.shape[-1] + 1) .reshape(1, 1, -1) .expand(1, m.shape[-1], -1) .to(m.device) ) m = (ids <= mask).type_as(m)
m[0, :, : int(sep)] = 1 m = m.squeeze(0) return m
tokens = [] attention_mask_list = [] position_id_list = [] block_position_id_list = [] token_lens = [] for input, output in zip(packed_input_ids, packed_output_ids): data = input + output if not use_fa2: attention_mask = build_mask_matrix(len(data), 0) attention_mask_list.append(attention_mask) tokens += data token_lens.append(len(data))
position_ids, block_position_ids = self._build_position_ids( mask_pos=len(input) - 2, bos_pos=len(input) - 1, max_output_length=len(output), rotary_type=rotary_type, )
position_id_list.append(position_ids) block_position_id_list.append(block_position_ids)
labels = [] for i in range(len(packed_input_ids)): labels += ( [-100] * (len(packed_input_ids[i]) - 1) + packed_output_ids[i] + [self.eos_token_id] )
total_len = 0 if use_fa2: pack_attention_mask = torch.Tensor([[0], [1]]) else: pack_attention_mask = torch.tril(torch.ones([max_length, max_length]))
pack_position_ids = [] pack_block_position_ids = [] total_len = 0 max_index = 0 for i in range(len(token_lens)): if not use_fa2: attention_mask = attention_mask_list[i] pack_attention_mask[ total_len : total_len + attention_mask.shape[0], total_len : total_len + attention_mask.shape[0], ] = attention_mask position_ids = [pid + max_index for pid in position_id_list[i]] block_position_ids = block_position_id_list[i] pack_position_ids.extend(position_ids) pack_block_position_ids.extend(block_position_ids) max_index = pack_position_ids[-1] + 1 total_len += token_lens[i] position_ids = [pack_position_ids, pack_block_position_ids]
if max_length > 0 and len(tokens) < max_length and padding: pad_length = max_length - len(tokens) tokens += [self.pad_token_id] * pad_length labels.extend([-100] * pad_length) position_ids[0] += [0] * pad_length position_ids[1] += [0] * pad_length
assert len(tokens) == len(labels)
if not use_fa2: attention_mask = pack_attention_mask.unsqueeze(0).long() else: attention_mask = torch.tensor(0) return { "input_ids": torch.tensor(tokens).long(), "position_ids": torch.tensor(position_ids).long(), "attention_mask": attention_mask, "labels": torch.tensor(labels).long(), }
def build_inputs_for_train( self, data: Union[Dict, List[Dict]], new_conversation_offset: List[int] = None, chat_format="antglm_chat", is_chat_format=True, # 如果传入的是字符串,用于说明是否已经是 use_true_multiturn=False, max_length: int = 2048, rotary_type: str = "1d", left_truncate: bool = True, unidirectional_attention: bool = True, isolation_position_ids: bool = False, padding: bool = True, use_fa2: bool = True, use_packed: bool = True, use_baichuan_packed: bool = False, skip_truncated_turn: bool = False, return_attention_mask: bool = True, ): r""" Build tensor input for model training. If inputs and outputs are list, will pack them.
Args: inputs (str, List[str], List[Dict], List[List[Dict]]): the input prompts. outputs (str, List[str]): the output responses. new_conversation_offset (List[int]): the offset index of the new conversation turn. is_chat_format (bool): whether the input is already chatml format max_length (int, Optional): the maximum length of the final input ids for training. Default: 2048 rotary_type (str, Optional): the rotary type of position embedding. Default: 1d left_truncate (bool, Optional): whether truncate the inputs from left. Default: True use_fa2 (bool, Optional): whether to build attention mask under flash attention 2. """ if isinstance(data, List): # chatml list _inputs = [] _outputs = [] new_conversation_offset = [] for _input in data: if use_true_multiturn: chat = self._chat_from_json(_input, chat_format=chat_format) chat_data = chat.prompt_pack new_conversation_offset.append(len(_inputs)) _inputs.extend(chat_data["input"]) _outputs.extend(chat_data["output"]) else: _conversation = _convert_to_conversation(_input) assert is_assistant(_conversation[-1])
_inputs.append( self.apply_chat_template( _conversation[:-1], tokenize=False, add_generation_prompt=True, ) ) _outputs.append(_conversation[-1]["content"])
return self._build_inputs_for_train( inputs=_inputs, outputs=_outputs, new_conversation_offset=new_conversation_offset, max_length=max_length, rotary_type=rotary_type, left_truncate=left_truncate, unidirectional_attention=unidirectional_attention, isolation_position_ids=isolation_position_ids, padding=padding, use_fa2=use_fa2, use_packed=use_packed, use_baichuan_packed=use_baichuan_packed, skip_truncated_turn=skip_truncated_turn, return_attention_mask=return_attention_mask, ) elif isinstance(data, Dict): if "messages" in data: # chatml format if use_true_multiturn: chat = self._chat_from_json(data, chat_format=chat_format) chat_data = chat.prompt_pack else: _conversation = _convert_to_conversation(data) assert is_assistant(_conversation[-1])
chat_data = { "input": self.apply_chat_template( _conversation[:-1], tokenize=False, add_generation_prompt=True, ), "output": _conversation[-1]["content"], }
return self._build_inputs_for_train( inputs=chat_data["input"], outputs=chat_data["output"], max_length=max_length, rotary_type=rotary_type, left_truncate=left_truncate, unidirectional_attention=unidirectional_attention, isolation_position_ids=isolation_position_ids, padding=padding, use_fa2=use_fa2, use_packed=use_packed, use_baichuan_packed=use_baichuan_packed, skip_truncated_turn=skip_truncated_turn, return_attention_mask=return_attention_mask, ) else: inputs = data["input"] outputs = data["output"]
if isinstance(inputs, str): inputs = [inputs] if isinstance(outputs, str): outputs = [outputs]
if not is_chat_format and chat_format: inputs = [ self.apply_chat_template( [{"role": "HUMAN", "content": item}], tokenize=False, chat_format=chat_format, ) for item in inputs ]
return self._build_inputs_for_train( inputs=inputs, outputs=outputs, new_conversation_offset=new_conversation_offset, max_length=max_length, rotary_type=rotary_type, left_truncate=left_truncate, unidirectional_attention=unidirectional_attention, isolation_position_ids=isolation_position_ids, padding=padding, use_fa2=use_fa2, use_packed=use_packed, use_baichuan_packed=use_baichuan_packed, skip_truncated_turn=skip_truncated_turn, return_attention_mask=return_attention_mask, )123version https://git-lfs.github.com/spec/v1oid sha256:e4f5fe09e7484071da5fa93cfb82f7db15c0ebf9b6ee9821599c5a997563ee96size 1221070812345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342{ "add_bos_token": false, "add_eos_token": false, "added_tokens_decoder": { "156891": { "content": "<|startoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156892": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156893": { "content": "[CLS]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156894": { "content": "[gMASK]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156895": { "content": "<|role_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156896": { "content": "<tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156897": { "content": "</tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156898": { "content": "<tool_response>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156899": { "content": "</tool_response>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156900": { "content": "<|reserved_token_5|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156901": { "content": "<|reserved_token_6|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156902": { "content": "<|reserved_token_7|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156903": { "content": "<|reserved_token_8|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156904": { "content": "<|reserved_token_9|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156905": { "content": "<|reserved_token_10|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156906": { "content": "<|reserved_token_11|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156907": { "content": "<|reserved_token_12|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156908": { "content": "<|reserved_token_13|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156909": { "content": "<|reserved_token_14|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156910": { "content": "<|reserved_token_15|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156911": { "content": "<|reserved_token_16|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156912": { "content": "<|reserved_token_17|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156913": { "content": "<|reserved_token_18|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156914": { "content": "<|reserved_token_19|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156915": { "content": "<|reserved_token_20|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156916": { "content": "<|reserved_token_21|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156917": { "content": "<|reserved_token_22|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156918": { "content": "<|reserved_token_23|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156919": { "content": "<|reserved_token_24|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156920": { "content": "<|reserved_token_25|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156921": { "content": "<|reserved_token_26|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156922": { "content": "<|reserved_token_27|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156923": { "content": "<|reserved_token_28|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156924": { "content": "<|reserved_token_29|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156925": { "content": "<|reserved_token_30|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156926": { "content": "<|reserved_token_31|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156927": { "content": "<|reserved_token_32|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156928": { "content": "<|reserved_token_33|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156929": { "content": "<|reserved_token_34|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156930": { "content": "<|reserved_token_35|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156931": { "content": "<|reserved_token_36|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156932": { "content": "<|reserved_token_37|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156933": { "content": "<|reserved_token_38|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156934": { "content": "<|reserved_token_39|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156935": { "content": "<|reserved_token_40|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156936": { "content": "<|reserved_token_41|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156937": { "content": "<|reserved_token_42|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156938": { "content": "<|reserved_token_43|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156939": { "content": "<|reserved_token_44|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156940": { "content": "<|reserved_token_45|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156941": { "content": "<|reserved_token_46|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156942": { "content": "<|reserved_token_47|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156943": { "content": "<|reserved_token_48|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156944": { "content": "<|reserved_token_49|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156945": { "content": "<|reserved_token_50|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156946": { "content": "<|reserved_token_51|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156947": { "content": "<|reserved_token_52|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156948": { "content": "<|reserved_token_53|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156949": { "content": "<|reserved_token_54|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156950": { "content": "<|reserved_token_55|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156951": { "content": "<|reserved_token_56|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156952": { "content": "<|reserved_token_57|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156953": { "content": "<|reserved_token_58|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156954": { "content": "<|reserved_token_59|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156955": { "content": "<|reserved_token_60|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156956": { "content": "<|reserved_token_61|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156957": { "content": "<|reserved_token_62|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156958": { "content": "<|reserved_token_63|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156959": { "content": "<|reserved_token_64|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156960": { "content": "<|reserved_token_65|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156961": { "content": "<|reserved_token_66|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156962": { "content": "<|reserved_token_67|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156963": { "content": "<|reserved_token_68|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156964": { "content": "<|reserved_token_69|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156965": { "content": "<|reserved_token_70|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156966": { "content": "<|reserved_token_71|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156967": { "content": "<|reserved_token_72|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156968": { "content": "<|reserved_token_73|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156969": { "content": "<|reserved_token_74|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156970": { "content": "<|reserved_token_75|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156971": { "content": "<|reserved_token_76|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156972": { "content": "<|reserved_token_77|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156973": { "content": "<|reserved_token_78|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156974": { "content": "<|reserved_token_79|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156975": { "content": "<|reserved_token_80|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156976": { "content": "<|reserved_token_81|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156977": { "content": "<|reserved_token_82|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156978": { "content": "<|reserved_token_83|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156979": { "content": "<|reserved_token_84|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156980": { "content": "<|reserved_token_85|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156981": { "content": "<|reserved_token_86|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156982": { "content": "<|reserved_token_87|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156983": { "content": "<|reserved_token_88|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156984": { "content": "<|reserved_token_89|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156985": { "content": "<|reserved_token_90|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156986": { "content": "<|reserved_token_91|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156987": { "content": "<|reserved_token_92|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156988": { "content": "<|reserved_token_93|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156989": { "content": "<|reserved_token_94|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156990": { "content": "<|reserved_token_95|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156991": { "content": "<|reserved_token_96|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156992": { "content": "<|reserved_token_97|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156993": { "content": "<|reserved_token_98|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156994": { "content": "<|reserved_token_99|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156995": { "content": "<|reserved_token_100|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156996": { "content": "<|reserved_token_101|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156997": { "content": "<|reserved_token_102|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156998": { "content": "<|reserved_token_103|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "156999": { "content": "<|reserved_token_104|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157000": { "content": "<|reserved_token_105|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157001": { "content": "<|reserved_token_106|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157002": { "content": "<|reserved_token_107|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157003": { "content": "<|reserved_token_108|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157004": { "content": "<|reserved_token_109|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157005": { "content": "<|reserved_token_110|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157006": { "content": "<|reserved_token_111|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157007": { "content": "<|reserved_token_112|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157008": { "content": "<|reserved_token_113|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157009": { "content": "<|reserved_token_114|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157010": { "content": "<|reserved_token_115|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157011": { "content": "<|reserved_token_116|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157012": { "content": "<|reserved_token_117|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157013": { "content": "<|reserved_token_118|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157014": { "content": "<|reserved_token_119|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157015": { "content": "<|reserved_token_120|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157016": { "content": "<|reserved_token_121|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157017": { "content": "<|reserved_token_122|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157018": { "content": "<|reserved_token_123|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157019": { "content": "<|reserved_token_124|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157020": { "content": "<|reserved_token_125|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157021": { "content": "<|reserved_token_126|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157022": { "content": "<|reserved_token_127|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157023": { "content": "<|reserved_token_128|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157024": { "content": "<|reserved_token_129|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157025": { "content": "<|reserved_token_130|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157026": { "content": "<|reserved_token_131|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157027": { "content": "<|reserved_token_132|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157028": { "content": "<|reserved_token_133|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157029": { "content": "<|reserved_token_134|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157030": { "content": "<|reserved_token_135|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157031": { "content": "<|reserved_token_136|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157032": { "content": "<|reserved_token_137|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157033": { "content": "<|reserved_token_138|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157034": { "content": "<|reserved_token_139|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157035": { "content": "<|reserved_token_140|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157036": { "content": "<|reserved_token_141|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157037": { "content": "<|reserved_token_142|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157038": { "content": "<|reserved_token_143|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157039": { "content": "<|reserved_token_144|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157040": { "content": "<|reserved_token_145|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157041": { "content": "<|reserved_token_146|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157042": { "content": "<|reserved_token_147|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157043": { "content": "<|reserved_token_148|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157044": { "content": "<|reserved_token_149|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157045": { "content": "<|reserved_token_150|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157046": { "content": "<|reserved_token_151|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157047": { "content": "<|reserved_token_152|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157048": { "content": "<|reserved_token_153|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157049": { "content": "<|reserved_token_154|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157050": { "content": "<|reserved_token_155|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157051": { "content": "<|reserved_token_156|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157052": { "content": "<|reserved_token_157|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157053": { "content": "<|reserved_token_158|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157054": { "content": "<|reserved_token_159|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157055": { "content": "<|reserved_token_160|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157056": { "content": "<|reserved_token_161|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157057": { "content": "<|reserved_token_162|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157058": { "content": "<|reserved_token_163|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157059": { "content": "<|reserved_token_164|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157060": { "content": "<|reserved_token_165|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157061": { "content": "<|reserved_token_166|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157062": { "content": "<|reserved_token_167|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157063": { "content": "<|reserved_token_168|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157064": { "content": "<|reserved_token_169|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157065": { "content": "<|reserved_token_170|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157066": { "content": "<|reserved_token_171|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157067": { "content": "<|reserved_token_172|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157068": { "content": "<|reserved_token_173|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157069": { "content": "<|reserved_token_174|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157070": { "content": "<|reserved_token_175|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157071": { "content": "<|reserved_token_176|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157072": { "content": "<|reserved_token_177|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157073": { "content": "<|reserved_token_178|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157074": { "content": "<|reserved_token_179|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157075": { "content": "<|reserved_token_180|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157076": { "content": "<|reserved_token_181|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157077": { "content": "<|reserved_token_182|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157078": { "content": "<|reserved_token_183|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157079": { "content": "<|reserved_token_184|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157080": { "content": "<|reserved_token_185|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157081": { "content": "<|reserved_token_186|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157082": { "content": "<|reserved_token_187|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157083": { "content": "<|reserved_token_188|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157084": { "content": "<|reserved_token_189|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157085": { "content": "<|reserved_token_190|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157086": { "content": "<|reserved_token_191|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157087": { "content": "<|reserved_token_192|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157088": { "content": "<|reserved_token_193|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157089": { "content": "<|reserved_token_194|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157090": { "content": "<|reserved_token_195|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157091": { "content": "<|reserved_token_196|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157092": { "content": "<|reserved_token_197|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157093": { "content": "<|reserved_token_198|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157094": { "content": "<|reserved_token_199|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157095": { "content": "<|reserved_token_200|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157096": { "content": "<|reserved_token_201|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157097": { "content": "<|reserved_token_202|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157098": { "content": "<|reserved_token_203|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157099": { "content": "<|reserved_token_204|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157100": { "content": "<|reserved_token_205|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157101": { "content": "<|reserved_token_206|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157102": { "content": "<|reserved_token_207|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157103": { "content": "<|reserved_token_208|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157104": { "content": "<|reserved_token_209|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157105": { "content": "<|reserved_token_210|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157106": { "content": "<|reserved_token_211|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157107": { "content": "<|reserved_token_212|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157108": { "content": "<|reserved_token_213|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157109": { "content": "<|reserved_token_214|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157110": { "content": "<|reserved_token_215|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157111": { "content": "<|reserved_token_216|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157112": { "content": "<|reserved_token_217|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157113": { "content": "<|reserved_token_218|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157114": { "content": "<|reserved_token_219|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157115": { "content": "<|reserved_token_220|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157116": { "content": "<|reserved_token_221|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157117": { "content": "<|reserved_token_222|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157118": { "content": "<|reserved_token_223|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157119": { "content": "<|reserved_token_224|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157120": { "content": "<|reserved_token_225|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157121": { "content": "<|reserved_token_226|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157122": { "content": "<|reserved_token_227|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157123": { "content": "<|reserved_token_228|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157124": { "content": "<|reserved_token_229|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157125": { "content": "<|reserved_token_230|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157126": { "content": "<|reserved_token_231|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157127": { "content": "<|reserved_token_232|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157128": { "content": "<|reserved_token_233|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157129": { "content": "<|reserved_token_234|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157130": { "content": "<|reserved_token_235|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157131": { "content": "<|reserved_token_236|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157132": { "content": "<|reserved_token_237|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157133": { "content": "<|reserved_token_238|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157134": { "content": "<|reserved_token_239|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157135": { "content": "<|reserved_token_240|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157136": { "content": "<|reserved_token_241|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157137": { "content": "<|reserved_token_242|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157138": { "content": "<|reserved_token_243|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157139": { "content": "<|reserved_token_244|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157140": { "content": "<|reserved_token_245|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157141": { "content": "<|reserved_token_246|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157142": { "content": "<|reserved_token_247|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157143": { "content": "<|reserved_token_248|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157144": { "content": "<|reserved_token_249|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157145": { "content": "<|reserved_token_250|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157146": { "content": "<|reserved_token_251|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157147": { "content": "<|reserved_token_252|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157148": { "content": "<|reserved_token_253|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157149": { "content": "<|reserved_token_254|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157150": { "content": "<|reserved_token_255|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157151": { "content": "<role>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157152": { "content": "</role>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157153": { "content": "<|arithmetic_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157154": { "content": "<|number_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157155": { "content": "<|arithmetic_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157156": { "content": "<|number_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157157": { "content": "<imagePatch>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157158": { "content": "<image>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157159": { "content": "</image>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157160": { "content": "<video>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157161": { "content": "</video>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157162": { "content": "<gen_imagePatch>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157163": { "content": "<gen_image>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157164": { "content": "</gen_image>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157165": { "content": "<imageHere>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157166": { "content": "<end_of_chunk>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157167": { "content": "<end_of_audio>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157168": { "content": "<audioPatch>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157169": { "content": "<audio>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157170": { "content": "</audio>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157171": { "content": "<gen_audioPatch>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157172": { "content": "<gen_audio>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157173": { "content": "</gen_audio>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157174": { "content": "<audioHere>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157175": { "content": "<framePatch>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157176": { "content": "<text>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157177": { "content": "<asr>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "157178": { "content": "<tts>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true } }, "additional_special_tokens": [ "<|arithmetic_end|>", "<role>", "<|number_end|>", "<|arithmetic_start|>", "</role>", "<|number_start|>", "<|role_end|>", "<tool_call>", "</tool_call>", "<tool_response>", "</tool_response>" ], "bos_token": "<|startoftext|>", "chat_template": "{{- '<role>SYSTEM</role>' }}\n{%- if messages and messages[0].role == 'system' and messages[0].content is string %}\n {{- messages[0].content }}\n{%- else %}\n {{- '你是一个友好的AI助手。' }}\n{%- endif %}\n\n{{- '\n\ndetailed thinking ' }}\n{{- 'on' if enable_thinking else 'off' }}\n{{- '<|role_end|>' }}\n\n{%- for message in messages %}\n {%- set role_lower = message.role | lower %}\n \n {%- if role_lower in ['user', 'human'] -%}\n <role>HUMAN</role>\n {%- set contents = message.content if message.content is iterable and message.content is not string else [message.content] %}\n {%- for part in contents %}\n {%- if part.type is defined %}\n {%- if part.type == 'image' or 'image_url' in part -%}\n <IMAGE>\n {%- elif part.type == 'video' or 'video_url' in part -%}\n <VIDEO>\n {%- elif part.type == 'audio' or 'audio_url' in part -%}\n <AUDIO>\n {%- elif part.type == 'text' %}\n {{- part.text }}\n {%- endif %}\n {%- else %}\n {{- part }}\n {%- endif %}\n {%- endfor %}\n {{- '<|role_end|>' }}\n \n {%- elif role_lower in ['assistant'] -%}\n <role>ASSISTANT</role>\n {%- set contents = message.content if message.content is iterable and message.content is not string else [message.content] %}\n {%- for part in contents %}\n {%- if part.type is defined and part.type == 'text' %}\n {{- part.text }}\n {%- elif part is string %}\n {{- part }}\n {%- endif %}\n {%- endfor %}\n {{- '<|role_end|>' }}\n {%- endif %}\n{%- endfor %}\n\n{{- '<role>ASSISTANT</role>' -}}", "clean_up_tokenization_spaces": false, "cls_token": "[CLS]", "eos_token": "<|role_end|>", "extra_special_tokens": {}, "fast_tokenizer": true, "gmask_token": "[gMASK]", "merges_file": null, "model_max_length": 1000000000000000019884624838656, "pad_token": "<|role_end|>", "auto_map": { "AutoTokenizer": [ "tokenization_bailing.BailingTokenizer", null ] }, "tokenizer_class": "BailingTokenizer", "trust_remote_code": true}.gitattributes+9
CITATION.cffAdded+9
LICENSEAdded+21
LICENSE-APACHE-2.0Added+201
README.mdAdded+160
README.zh.mdAdded+146
WHISPER_LICENSEAdded+21
asr_request.pyAdded+39
audio_spec.pyAdded+127
chat_format.pyAdded+904
chat_template.jinjaAdded+57
config.jsonAdded+87
configuration_ming_v3_asr.pyAdded+293
examples/transcribe.pyAdded+79
feature_extraction_ming_v3_asr.pyAdded+235
figures/asr.pngAdded

Large File Pointer Details
- SHA256: 624d98d65546e12b1763eb157690e51e388f3db6de05ec1980ea457f4122e56d
- Pointer size: 132 Bytes
- Size of remote file: 1.24 MB
figures/bailing-logo.pngAdded

figures/contextasr.pngAdded

Large File Pointer Details
- SHA256: 6924bd1057aa68ef194912995c92d8ca998ef68b15ec55053f5b168da087cd32
- Pointer size: 131 Bytes
- Size of remote file: 923 kB
figures/model.jpgAdded

Large File Pointer Details
- SHA256: 55a45a2358cb39f250eea875c45070103edc78af6bad771ef8f7f904ab46975f
- Pointer size: 131 Bytes
- Size of remote file: 317 kB
figures/开源asr.pngAdded

Large File Pointer Details
- SHA256: e05cf1897bd7eb80d64146613e18f3fb83e1e46f763443f42525ee3eddddd795
- Pointer size: 132 Bytes
- Size of remote file: 1.01 MB
figures/自建asr.pngAdded

Large File Pointer Details
- SHA256: 31ade60fefc3a90aab51439be9d52518775710f262a5a7e5371e89ff56667a40
- Pointer size: 132 Bytes
- Size of remote file: 1.23 MB
generation_config.jsonAdded+5
model-00001-of-00002.safetensorsAdded+3
model-00002-of-00002.safetensorsAdded+3
model.safetensors.index.jsonAdded
modeling_ming_v3_asr.pyAdded+2150
modeling_ming_v3_asr_encoder.pyAdded+89
modeling_whisper_encoder.pyAdded+141
preprocessor_config.jsonAdded+28
processing_ming_v3_asr.pyAdded+248
requirements.txtAdded+11
special_tokens_map.jsonAdded+44
tokenization_bailing.pyAdded+1155
tokenizer.jsonAdded+3
tokenizer_config.jsonAdded+2342