mrfakename commited on
Commit
4c0600d
·
verified ·
1 Parent(s): 2857791

Mirror inclusionAI/Ming-3.0-asr-tiny

Browse files
.gitattributes CHANGED
@@ -33,3 +33,12 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
37
+ figures/model.jpg filter=lfs diff=lfs merge=lfs -text
38
+ figures/开源asr.jpg filter=lfs diff=lfs merge=lfs -text
39
+ figures/自建asr.jpg filter=lfs diff=lfs merge=lfs -text
40
+ figures/开源asr.png filter=lfs diff=lfs merge=lfs -text
41
+ figures/自建asr.png filter=lfs diff=lfs merge=lfs -text
42
+ figures/contextasr.png filter=lfs diff=lfs merge=lfs -text
43
+ figures/asr.png filter=lfs diff=lfs merge=lfs -text
44
+ media/ming-3.0-asr-tiny-intro.en.mp4 filter=lfs diff=lfs merge=lfs -text
CITATION.cff ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ cff-version: 1.2.0
2
+ message: "If you use Ming-3.0-asr-tiny, please cite this model repository."
3
+ title: "Ming-3.0-asr-tiny: Context-Aware Speech Recognition"
4
+ type: software
5
+ authors:
6
+ - name: inclusionAI
7
+ license: MIT
8
+ url: "https://github.com/inclusionAI/Ming-3.0-asr"
9
+ repository-code: "https://github.com/inclusionAI/Ming-3.0-asr"
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 inclusionAI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
LICENSE-APACHE-2.0 ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ license: mit
4
+ pipeline_tag: automatic-speech-recognition
5
+ language:
6
+ - zh
7
+ - en
8
+ tags:
9
+ - audio
10
+ - speech-recognition
11
+ - contextual-asr
12
+ ---
13
+ > 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`.
14
+
15
+ <div align="center">
16
+ <img src="./figures/bailing-logo.png" width="60" alt="Bailing logo" />
17
+ <h1>Ming-3.0-asr-tiny</h1>
18
+ <p><i>Context-aware speech recognition for Chinese, English, and dialects.</i></p>
19
+ </div>
20
+
21
+ English · [简体中文](https://huggingface.co/inclusionAI/Ming-3.0-asr-tiny/blob/main/README.zh.md)
22
+
23
+ [GitHub code and cookbook](https://github.com/inclusionAI/Ming-3.0-asr) · [Quick Start](#quick-start) · [Evaluation](#evaluation)
24
+
25
+ **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.
26
+
27
+ ## Capabilities
28
+
29
+ - **Chinese and English ASR:** speech-to-text transcription through one model interface.
30
+ - **Dialect recognition:** evaluated on 15 regional dialect test sets, including Cantonese, Minnan, and Shanghainese.
31
+ - **Context ASR:** accepts relevant hotwords or dialogue context as part of the transcription prompt.
32
+ - **Challenging speech:** evaluated on noisy speech and five application domains.
33
+
34
+ ## Architecture
35
+
36
+ <p align="center"><img src="./figures/model.jpg" width="850" alt="Ming-3.0-asr-tiny architecture" /></p>
37
+
38
+ ## Quick Start
39
+
40
+ ### Download and install
41
+
42
+ 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:
43
+
44
+ ```bash
45
+ python -m pip install "huggingface_hub[cli]"
46
+ hf download inclusionAI/Ming-3.0-asr-tiny --local-dir Ming-3.0-asr-tiny
47
+ cd Ming-3.0-asr-tiny
48
+ python -m pip install -r requirements.txt
49
+ ```
50
+
51
+ ### Run the PyTorch / Transformers example
52
+
53
+ ```bash
54
+ python examples/transcribe.py \
55
+ --model . \
56
+ --audio /path/to/speech.wav
57
+ ```
58
+
59
+ 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`.
60
+
61
+ ### PyTorch / Transformers Python API
62
+
63
+ 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):
64
+
65
+ ```python
66
+ import soundfile as sf
67
+ import torch
68
+ from transformers import AutoModelForCausalLM, AutoProcessor
69
+ from asr_request import decode_transcript, prepare_asr_request
70
+
71
+ processor = AutoProcessor.from_pretrained(".", trust_remote_code=True)
72
+ model = AutoModelForCausalLM.from_pretrained(
73
+ ".", trust_remote_code=True, dtype=torch.bfloat16,
74
+ device_map="cuda:0", attn_implementation="sdpa",
75
+ ).eval()
76
+ waveform, rate = sf.read("speech.wav", dtype="float32", always_2d=True)
77
+ inputs = prepare_asr_request(
78
+ processor, (waveform.T, rate), return_tensors="pt",
79
+ ).to(model.device)
80
+ eos = model.config.text_config.eos_token_id
81
+ with torch.inference_mode():
82
+ output = model.generate(
83
+ **inputs, max_new_tokens=256, do_sample=False,
84
+ eos_token_id=eos, pad_token_id=eos, no_repeat_ngram_size=10,
85
+ )
86
+ print(decode_transcript(
87
+ processor.tokenizer, output[0, inputs.input_ids.shape[1]:].tolist(),
88
+ ))
89
+ ```
90
+
91
+ ### Context ASR
92
+
93
+ 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:
94
+
95
+ ```bash
96
+ python examples/transcribe.py --model . --audio /path/to/speech.wav \
97
+ --language-hint zh --context-chunks \
98
+ --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:蜥蜴,姜知垠,曹承佑,姜惠贞,八音盒.'
99
+ ```
100
+
101
+ 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=...)`.
102
+
103
+ ### SGLang serving
104
+
105
+ 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:
106
+
107
+ ```bash
108
+ curl --fail-with-body --max-time 600 \
109
+ http://127.0.0.1:8000/v1/audio/transcriptions \
110
+ -F 'file=@/path/to/speech.wav' -F 'model=ming-asr' \
111
+ -F 'response_format=json' -F 'temperature=0'
112
+ ```
113
+
114
+ The response contains a `text` field. The cookbook also covers dataset evaluation settings.
115
+
116
+ ## Evaluation
117
+
118
+ ### ASR Overview
119
+
120
+ <p align="center"><img src="./figures/asr.png" width="1000" alt="ASR performance overview" /></p>
121
+
122
+ [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)
123
+
124
+ ### Chinese and English ASR
125
+
126
+ <p align="center"><img src="./figures/开源asr.png" width="1000" alt="Chinese and English ASR evaluation" /></p>
127
+
128
+ ### Dialects and Domains
129
+
130
+ <p align="center"><img src="./figures/自建asr.png" width="1000" alt="Dialect and domain ASR evaluation" /></p>
131
+
132
+ ### Context ASR
133
+
134
+ <p align="center"><img src="./figures/contextasr.png" width="1000" alt="Context ASR evaluation" /></p>
135
+
136
+ ## Usage Notes
137
+
138
+ - Output is transcription text, without word-level timestamps or speaker diarization.
139
+ - The included example does not support streaming input; image and video inputs are unsupported.
140
+ - Long audio can be encoded in chunks with `--audio-chunk-frames`, subject to the model context limit.
141
+ - Hotwords are hints, not a guarantee that a term will appear in the transcript.
142
+
143
+ For local Transformers inference, run the bundled [PyTorch example](./examples/transcribe.py).
144
+
145
+ ## License
146
+
147
+ 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.
148
+
149
+ ## Citation
150
+
151
+ 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).
152
+
153
+ ```bibtex
154
+ @misc{ming_3_0_asr_tiny_2026,
155
+ author = {{inclusionAI}},
156
+ title = {Ming-3.0-asr-tiny: Context-Aware Speech Recognition},
157
+ year = {2026},
158
+ url = {https://github.com/inclusionAI/Ming-3.0-asr}
159
+ }
160
+ ```
README.zh.md ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+ <img src="./figures/bailing-logo.png" width="60" alt="百灵 Logo" />
3
+ <h1>Ming-3.0-asr-tiny</h1>
4
+ <p><i>听懂中英文、方言,也听懂上下文。</i></p>
5
+ </div>
6
+
7
+ [English](https://huggingface.co/inclusionAI/Ming-3.0-asr-tiny) · 简体中文
8
+
9
+ [GitHub 代码与教程](https://github.com/inclusionAI/Ming-3.0-asr) · [快速开始](#快速开始) · [评测](#评测)
10
+
11
+ **Ming-3.0-asr-tiny** 基于 Ling-tiny-v3 语言模型与音频编码器构建,支持单轮中英文语音转写、方言识别,并可利用热词或对话上文改善领域术语识别。本仓库提供完整权重、tokenizer、Transformers 自定义实现和可运行的推理示例。
12
+
13
+ ## 模型能力
14
+
15
+ - **中英文语音识别:** 使用统一接口将语音转写为文本。
16
+ - **方言识别:** 在包括粤语、闽南语、上海话在内的 15 组地区方言测试集上评测。
17
+ - **Context ASR:** 可在转写提示中加入相关热词或对话上文。
18
+ - **复杂场景:** 覆盖高噪语音及五类应用领域评测。
19
+
20
+ ## 模型架构
21
+
22
+ <p align="center"><img src="./figures/model.jpg" width="850" alt="Ming-3.0-asr-tiny 模型架构" /></p>
23
+
24
+ ## 快速开始
25
+
26
+ ### 下载与安装
27
+
28
+ 使用 Python 3.12 和兼容 CUDA 的 Linux GPU。下载完整模型后,安装模型依赖,包括 PyTorch 与 torchaudio:
29
+
30
+ ```bash
31
+ python -m pip install "huggingface_hub[cli]"
32
+ hf download inclusionAI/Ming-3.0-asr-tiny --local-dir Ming-3.0-asr-tiny
33
+ cd Ming-3.0-asr-tiny
34
+ python -m pip install -r requirements.txt
35
+ ```
36
+
37
+ ### 运行 PyTorch / Transformers 推理脚本
38
+
39
+ ```bash
40
+ python examples/transcribe.py \
41
+ --model . \
42
+ --audio /path/to/speech.wav
43
+ ```
44
+
45
+ 已知语种时可加 `--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`。
46
+
47
+ ### PyTorch / Transformers Python 示例
48
+
49
+ 在下载后的模型目录运行,并将 `speech.wav` 换成自己的音频文件。该代码与仓库内的[可执行示例](./examples/transcribe.py)使用同一推理路径:
50
+
51
+ ```python
52
+ import soundfile as sf
53
+ import torch
54
+ from transformers import AutoModelForCausalLM, AutoProcessor
55
+ from asr_request import decode_transcript, prepare_asr_request
56
+
57
+ processor = AutoProcessor.from_pretrained(".", trust_remote_code=True)
58
+ model = AutoModelForCausalLM.from_pretrained(
59
+ ".", trust_remote_code=True, dtype=torch.bfloat16,
60
+ device_map="cuda:0", attn_implementation="sdpa",
61
+ ).eval()
62
+ waveform, rate = sf.read("speech.wav", dtype="float32", always_2d=True)
63
+ inputs = prepare_asr_request(
64
+ processor, (waveform.T, rate), return_tensors="pt",
65
+ ).to(model.device)
66
+ eos = model.config.text_config.eos_token_id
67
+ with torch.inference_mode():
68
+ output = model.generate(
69
+ **inputs, max_new_tokens=256, do_sample=False,
70
+ eos_token_id=eos, pad_token_id=eos, no_repeat_ngram_size=10,
71
+ )
72
+ print(decode_transcript(
73
+ processor.tokenizer, output[0, inputs.input_ids.shape[1]:].tolist(),
74
+ ))
75
+ ```
76
+
77
+ ### Context ASR
78
+
79
+ 普通转写和 Context ASR 使用同一输入格式。将主题和热词连续拼接在基础指令之后,不插入换行。对于语种已知、长度不超过 60 秒的音频,`--context-chunks` 会在 30 秒以内选择 3000 mel 帧,超过 30 秒选择 6000 mel 帧:
80
+
81
+ ```bash
82
+ python examples/transcribe.py --model . --audio /path/to/speech.wav \
83
+ --language-hint zh --context-chunks \
84
+ --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:蜥蜴,姜知垠,曹承佑,姜惠贞,八音盒.'
85
+ ```
86
+
87
+ 英文音频将语言提示改为 `--language-hint en`。这里的主题与热词仅供演示,也可以在提示词中加入对话上文。Python 调用可通过 `prepare_asr_request(..., prompt=...)` 传入完整提示。
88
+
89
+ ### SGLang 加速服务
90
+
91
+ 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 文件:
92
+
93
+ ```bash
94
+ curl --fail-with-body --max-time 600 \
95
+ http://127.0.0.1:8000/v1/audio/transcriptions \
96
+ -F 'file=@/path/to/speech.wav' -F 'model=ming-asr' \
97
+ -F 'response_format=json' -F 'temperature=0'
98
+ ```
99
+
100
+ 响应中的 `text` 字段即为转写结果。数据集评测参数见 SGLang 指南。
101
+
102
+ ## 评测
103
+
104
+ ### ASR 整体表现
105
+
106
+ <p align="center"><img src="./figures/asr.png" width="1000" alt="ASR 整体表现" /></p>
107
+
108
+ [观看 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)
109
+
110
+ ### 中英文语音识别
111
+
112
+ <p align="center"><img src="./figures/开源asr.png" width="1000" alt="开源中英文 ASR 评测" /></p>
113
+
114
+ ### 方言与领域识别
115
+
116
+ <p align="center"><img src="./figures/自建asr.png" width="1000" alt="方言与领域 ASR 评测" /></p>
117
+
118
+ ### Context ASR
119
+
120
+ <p align="center"><img src="./figures/contextasr.png" width="1000" alt="Context ASR 评测" /></p>
121
+
122
+ ## 使用说明
123
+
124
+ - 输出为转写文本,不提供词级时间戳或说话人分离。
125
+ - 当前示例不支持流式输入;模型不接受图像或视频。
126
+ - 长音频可用 `--audio-chunk-frames` 分块编码,仍受模型上下文长度限制。
127
+ - 热词仅是识别提示,不保证输出一定包含指定词语。
128
+
129
+ 本地 Transformers 推理可使用仓库内置的 [PyTorch 示例](./examples/transcribe.py)。
130
+
131
+ ## 许可证
132
+
133
+ 模型权重及项目原创代码采用 [MIT 许可证](./LICENSE),与 [Ming 项目](https://github.com/inclusionAI/Ming)保持一致。模型包中标注 Apache-2.0 的源码保留原有声明和[许可证文本](./LICENSE-APACHE-2.0);`modeling_whisper_encoder.py` 保留基于 OpenAI Whisper 代码的 MIT 声明。
134
+
135
+ ## 引用
136
+
137
+ 如果在研究或产品中使用 Ming-3.0-asr-tiny,请引用 [GitHub 仓库](https://github.com/inclusionAI/Ming-3.0-asr)。[CITATION.cff](./CITATION.cff) 也提供机器可读的引用信息。
138
+
139
+ ```bibtex
140
+ @misc{ming_3_0_asr_tiny_2026,
141
+ author = {{inclusionAI}},
142
+ title = {Ming-3.0-asr-tiny: Context-Aware Speech Recognition},
143
+ year = {2026},
144
+ url = {https://github.com/inclusionAI/Ming-3.0-asr}
145
+ }
146
+ ```
WHISPER_LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2022 OpenAI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
asr_request.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the audio request used by Ming-3.0-asr-tiny."""
2
+
3
+
4
+ # The character between the backticks is a literal tab, not a backslash and "t".
5
+ ASR_INSTRUCTION = (
6
+ "Please recognize the language of this speech and transcribe it, "
7
+ "placing a `\t` between the identified language and the transcribe."
8
+ )
9
+
10
+
11
+ def prepare_asr_request(
12
+ processor, audio, *, prompt=None, language_hint=None,
13
+ audio_chunk_frames=None, return_tensors="pt",
14
+ ):
15
+ """Prepare audio and context through the processor's single ASR entry point."""
16
+ return processor.apply_transcription_request(
17
+ audio, prompt=prompt, language_hint=language_hint,
18
+ audio_chunk_frames=audio_chunk_frames, return_tensors=return_tensors,
19
+ )
20
+
21
+
22
+ def context_chunk_frames(duration_seconds):
23
+ """Use one encoder chunk for a ContextASR-Bench clip up to 60 seconds."""
24
+ if duration_seconds <= 0:
25
+ raise ValueError("duration_seconds must be positive")
26
+ if duration_seconds > 60:
27
+ raise ValueError("Context ASR chunk policy supports clips up to 60 seconds")
28
+ return 6000 if duration_seconds > 30 else 3000
29
+
30
+
31
+ def decode_transcript(tokenizer, token_ids):
32
+ """Remove the language envelope from generated text."""
33
+ text = tokenizer.decode(token_ids, skip_special_tokens=True).strip()
34
+ if "\t" in text:
35
+ return text.split("\t", 1)[1].strip()
36
+ for language in ("Chinese", "English", "Canton", "Japanese", "Korean"):
37
+ if text.startswith(language):
38
+ return text[len(language):].strip()
39
+ return text
audio_spec.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 SGLang Team
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+ """Model-owned Ming audio geometry; no scheduler, tokenizer, or model imports."""
14
+
15
+ from dataclasses import dataclass
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class MingAudioSpec:
20
+ """Immutable preprocessing and encoder/projector length contract.
21
+
22
+ ``chunk_frames`` is measured before the encoder's stride-two convolution.
23
+ Chunk output lengths must be rounded separately, including the final chunk.
24
+ """
25
+
26
+ n_mels: int = 128
27
+ sample_rate: int = 16000
28
+ n_fft: int = 400
29
+ hop_length: int = 160
30
+ chunk_frames: int = 3000
31
+ kernels: tuple[int, ...] = (3,)
32
+ strides: tuple[int, ...] = (2,)
33
+ paddings: tuple[int, ...] = (1,)
34
+
35
+ def __post_init__(self):
36
+ if self.n_mels not in (80, 128):
37
+ raise ValueError("Ming audio requires 80 or 128 mel bins")
38
+ if (self.sample_rate, self.n_fft, self.hop_length) != (16000, 400, 160):
39
+ raise ValueError("Ming checkpoints require the 16 kHz Whisper frontend")
40
+ if self.chunk_frames <= 0:
41
+ raise ValueError("chunk_frames must be positive")
42
+ if not (len(self.kernels) == len(self.strides) == len(self.paddings)):
43
+ raise ValueError(
44
+ "audio downsampler kernel/stride/padding lists must have the same length"
45
+ )
46
+ if any(k <= 0 for k in self.kernels) or any(s <= 0 for s in self.strides):
47
+ raise ValueError("audio downsampler kernels and strides must be positive")
48
+ if any(p < 0 for p in self.paddings):
49
+ raise ValueError("audio downsampler paddings must be nonnegative")
50
+
51
+ @classmethod
52
+ def from_config(cls, config):
53
+ def get(name, default=None):
54
+ return (
55
+ config.get(name, default)
56
+ if isinstance(config, dict)
57
+ else getattr(config, name, default)
58
+ )
59
+
60
+ encoder = get("whisper_encoder_config") or {}
61
+ kernels = tuple(
62
+ get("downsampler_kernel_size_list") or [get("ds_kernel_size", 3)]
63
+ )
64
+ strides = tuple(get("downsampler_stride_list") or [get("ds_stride", 2)])
65
+ paddings = get("downsampler_padding_list")
66
+ spec = cls(
67
+ n_mels=encoder.get("n_mels", get("n_mels", 128)),
68
+ chunk_frames=get("chunk_frames", 3000),
69
+ kernels=kernels,
70
+ strides=strides,
71
+ paddings=tuple(
72
+ paddings if paddings is not None else [k // 2 for k in kernels]
73
+ ),
74
+ )
75
+ context = encoder.get("n_ctx", get("n_audio_ctx", 3000))
76
+ if (spec.chunk_frames + 1) // 2 > context:
77
+ raise ValueError("audio chunk exceeds encoder positional context")
78
+ return spec
79
+
80
+ def embedding_length(self, mel_length):
81
+ """Length of one chunk; accepts an integer or an integer tensor."""
82
+ length = (mel_length + 1) // 2
83
+ for kernel, stride, padding in zip(self.kernels, self.strides, self.paddings):
84
+ length = (length + 2 * padding - kernel) // stride + 1
85
+ return length
86
+
87
+ def chunks(self, mel_length: int) -> tuple[int, ...]:
88
+ if mel_length <= 0:
89
+ raise ValueError("audio mel length must be positive")
90
+ full, remainder = divmod(mel_length, self.chunk_frames)
91
+ return (self.chunk_frames,) * full + ((remainder,) if remainder else ())
92
+
93
+ def token_count(self, mel_length: int) -> int:
94
+ lengths = [self.embedding_length(n) for n in self.chunks(mel_length)]
95
+ if any(n <= 0 for n in lengths):
96
+ raise ValueError("audio chunk is too short for the configured downsampler")
97
+ return sum(lengths)
98
+
99
+
100
+ @dataclass(frozen=True)
101
+ class MingAudioMetadata:
102
+ """Versioned model metadata transported opaquely by the generic engine."""
103
+
104
+ mel_lengths: tuple[int, ...]
105
+ token_lengths: tuple[int, ...]
106
+ version: int = 1
107
+
108
+ def __post_init__(self):
109
+ if self.version != 1:
110
+ raise ValueError(f"Unsupported Ming audio metadata version: {self.version}")
111
+ if not self.mel_lengths or len(self.mel_lengths) != len(self.token_lengths):
112
+ raise ValueError("Ming audio metadata must describe each clip")
113
+ if any(n <= 0 for n in (*self.mel_lengths, *self.token_lengths)):
114
+ raise ValueError("Ming audio lengths must be positive")
115
+
116
+ def to_dict(self):
117
+ return {
118
+ "version": self.version,
119
+ "mel_lengths": list(self.mel_lengths),
120
+ "token_lengths": list(self.token_lengths),
121
+ }
122
+
123
+ @classmethod
124
+ def from_dict(cls, value):
125
+ return cls(
126
+ tuple(value["mel_lengths"]), tuple(value["token_lengths"]), value["version"]
127
+ )
chat_format.py ADDED
@@ -0,0 +1,904 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AntGLM Chat-model data format.
2
+
3
+ 格式化 AntGLM 以及各种开源模型的符号系统:
4
+ - 确定 Chat 模型依赖的文件数据结构协议
5
+ - 确定单轮/多轮的统一结构
6
+ - 确定 Chat 符号系统的协议, 包括角色定义、分隔符等
7
+ - 方便做开源模型依赖的 prompt 转换
8
+ - 支持工具、代码、推理等支持
9
+
10
+ 参考 FastChat Conversation 对象的设计思路.
11
+ Reference: https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py
12
+ """
13
+
14
+ import copy
15
+ import dataclasses
16
+ import logging
17
+ import re
18
+ import uuid
19
+ from copy import deepcopy
20
+ from enum import IntEnum, auto
21
+ from typing import Dict, List, Optional, Tuple
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ class PromptStyle(IntEnum):
27
+ """Prompt styles."""
28
+
29
+ # 原始 antglm format 格式, 单轮指令没有结构, 多轮 `第1轮\n用户: xx\n机器人: xx\n`
30
+ ANTGLM_RAW = auto()
31
+ # Chat format 格式, 单轮多轮统一为 chat format 格式
32
+ ANTGLM_CHAT = auto()
33
+ # 单轮指令没有结构, 只有多轮为 chat format 格式
34
+ ANTGLM_ONLY_MULTITURN_CHAT = auto()
35
+ # OpenAI ChatML 格式, 包括千问
36
+ CHATML = auto()
37
+ # LLAMA2 格式
38
+ LLAMA2 = auto()
39
+ # ChatGLM 1/2 格式
40
+ CHATGLM = auto()
41
+ # ChatGLM3 格式
42
+ CHATGLM3 = auto()
43
+ # 百川格式
44
+ BAICHUAN2 = auto()
45
+
46
+
47
+ @dataclasses.dataclass
48
+ class Chat:
49
+ """Chat 数据符号结构, 格式化 AntGLM 以及各种开源模型的符号系统.
50
+
51
+ Examples:
52
+
53
+ ```python
54
+ >>> from antllm.data.chat_format import Chat
55
+
56
+ >>> ### 从 json 数据结构创建 chat 对象, 并且 format 结构使用 AntGLM 原始结构
57
+ >>> input_json = {
58
+ ... "messages": [
59
+ ... {"role": "HUMAN", "content": "讲一个笑话"},
60
+ ... {"role": "ASSISTANT", "content": "为什么猪不能上网?因为它们会被网上的“猪”骗!哈哈哈!"},
61
+ ... {"role": "HUMAN", "content": "不好笑,换个程序员的笑话"}
62
+ ... ],
63
+ ... }
64
+ >>> chat = Chat.from_json(input_json, name='antglm_raw')
65
+
66
+ >>> ### 根据 chat 对象创建大模型训练所需 pack 数据
67
+ >>> pack_data = chat.prompt_pack
68
+ >>> print(pack_data)
69
+
70
+ >>> ### 根据 chat 对象创建大模型训练所需 input, output 数据
71
+ >>> data = chat.prompt_inout
72
+ >>> print(data)
73
+
74
+ >>> ### 根据 chat 对象创建大模型预测用的 prompt
75
+ >>> prompt = chat.prompt_str
76
+ >>> print(prompt)
77
+
78
+ >>> ### 从大模型训练数据 {"input": "xx", "output": "xx"} 中创建 chat 对象
79
+ >>> data = {
80
+ ... 'input': (
81
+ ... '第1轮\n用户: 讲一个笑话\n机器人: 为什么猪不能上网?因为它们会被网上的“猪”骗!哈哈哈!\n'
82
+ ... '第2轮\n用户: 不好笑,换个程序员的笑话\n机器人:'
83
+ ... ),
84
+ ... 'output': ''
85
+ ... }
86
+ >>> chat = Chat.from_inout(data, name='antglm_raw')
87
+
88
+ >>> ### 从大模型 pack 训练数据创建 chat 对象列表
89
+ >>> pack_data = {
90
+ ... 'inputs': ['第1轮\n用户: 讲一个笑话\n机器人:', '第2轮\n用户: 不好笑,换个程序员的笑话\n机器人:', '第1轮\n用户: 写首诗\n机器人:'],
91
+ ... 'outputs': [
92
+ ... '为什么猪不能上网?因为它们会被网上的“猪”骗!哈哈哈!\n',
93
+ ... '为什么程序员总是喜欢使用黑色主题?因为他们喜欢“黑暗模式”(Dark Mode),这样他们就可以在晚上加班时更好地隐藏自己的错误!',
94
+ ... '']
95
+ ... }
96
+ >>> chats = Chat.from_pack(pack_data, name='antglm_raw')
97
+ >>> assert len(chats) == 2
98
+ >>> print(chats[0])
99
+ >>> print(chats[1])
100
+
101
+ >>> ### 显示总交互轮数 (以用户输出多少次为轮数个数)
102
+ >>> print(chat.turns_num)
103
+
104
+ >>> ### 根据 chat 对象创建 json 格式化输出
105
+ >>> data_json = chat.to_json()
106
+ >>> print(data_json)
107
+
108
+ >>> ### 增加轮次信息
109
+ >>> content = (
110
+ ... '为什么程序员总是喜欢使用黑色主题?'
111
+ ... '因为他们喜欢“黑暗模式”(Dark Mode),这样他们就可以在晚上加班时更好地隐藏自己的错误!'
112
+ ... )
113
+ >>> chat.append_message(chat.role_assistant, content)
114
+
115
+ >>> ### 将 chat 对象转成 OpenAI ChatCompletion 接口的入参
116
+ >>> openai_messages = chat.to_openai_api_messages()
117
+ >>> print(openai_messages)
118
+
119
+ >>> ### 复制一个 chat 对象
120
+ >>> chat_new = chat.copy()
121
+ ```
122
+ """
123
+
124
+ # 数据结构名称
125
+ id: str = None
126
+
127
+ # format 支持: antglm_raw, antglm_chat, chatglm1, chatglm2, llama2, qwen, baichuan2
128
+ name: Optional[str] = None
129
+
130
+ # Prompt 风格
131
+ prompt_style: Optional[PromptStyle] = None
132
+
133
+ # System Template 和 message
134
+ system_template: str = "<role>SYSTEM</role>{}"
135
+ system_message: str = ""
136
+
137
+ # 角色定义
138
+ role_human: str = "HUMAN"
139
+ role_assistant: str = "ASSISTANT"
140
+ role_observation: str = "OBSERVATION"
141
+ role_template: str = "<role>{}</role>"
142
+
143
+ # 每轮符号定义
144
+ turn_start: str = ""
145
+ human_end: str = ""
146
+ assistant_start: str = ""
147
+ assistant_end: str = ""
148
+ assistant_end_ids: Optional[List[int]] = None
149
+ general_role_end: str = ""
150
+
151
+ # agent 符号定义
152
+ tool_template = "<tool>{}</tool>"
153
+ code_template = "<code>{}</code>"
154
+ arithemetic_templte = "<arithemetic>{}</arithemetic>"
155
+
156
+ # All messages. Each item is (role, message).
157
+ messages: List[Tuple[str, str]] = ()
158
+
159
+ # messages 中用于 few-shot messages
160
+ offset: int = 0
161
+
162
+ # 其他 meta data
163
+ source: Optional[str] = None
164
+ lang: Optional[str] = None
165
+ topic: Optional[str] = None
166
+
167
+ # 原始 json 数据
168
+ origin_json: Optional[dict] = None
169
+
170
+ @property
171
+ def support_names(self) -> Dict[str, str]:
172
+ """支持的数据对象名称."""
173
+ return {
174
+ "antglm_raw": "原始 antglm format 格式, 单轮指令没有结构, 多轮 `第1轮\\n用户:xx\\n机器人xx\\n`",
175
+ "antglm_chat": "Chat format 格式, 单轮多轮统一为 chat format 格式",
176
+ "chatglm1": "chatglm1 format",
177
+ "chatglm2": "chatglm2 format",
178
+ "llama2": "llama2 format",
179
+ "qwen": "千问 format",
180
+ "baichuan2": "百川 2 format",
181
+ }
182
+
183
+ @classmethod
184
+ def from_json(
185
+ cls,
186
+ input: dict,
187
+ name: Optional[str] = None,
188
+ prompt_style: Optional[PromptStyle] = None,
189
+ ):
190
+ """从文件数据结构到数据对象的转换.
191
+
192
+ Params:
193
+ name: `Optional[str]`, 符号系统名称
194
+ - format 支持: antglm_raw, antglm_chat, chatglm1, chatglm2, llama2, qwen, baichuan2
195
+ - 如果指定了 format name, 使用该 name 符号系统, 否则使用 input 中 `name` 字段
196
+
197
+ prompt_style: `Optional[PromptStyle]`, 指定 prompt 风格, 默认使用和 name 一致的风格
198
+
199
+ input: `dict`, 文件中的 json dict 对象, 协议为:
200
+ - 既支持 `messages` 字段, 也支持 `turns` 字段
201
+ {
202
+ "id": "xxx",
203
+ "name": "antglm",
204
+ "source": "xxx",
205
+ "lang": "xx",
206
+ "topic": "xx",
207
+ "system_template": "",
208
+ "system_message": "xx",
209
+ "messages": [
210
+ {
211
+ "role": "HUMAN",
212
+ "content": "Hi"
213
+ },
214
+ {
215
+ "role": "ASSISTANT",
216
+ "content": "Hello"
217
+ },
218
+ {
219
+ "role": "OBSERVATION",
220
+ "content": "xxx"
221
+ },
222
+ {
223
+ "role": "ASSISTANT",
224
+ "content": "xxx"
225
+ }
226
+ ],
227
+ "turns": [
228
+ {"HUMAN": "xxx", "OBSERVATION": "xx", "ASSISTANT": "xx"}
229
+ ]
230
+ }
231
+
232
+ Returns:
233
+ `Chat` 对象
234
+ """
235
+ _id = input.get("id")
236
+ if name:
237
+ _name = name
238
+ else:
239
+ _name = input.get("name")
240
+ source = input.get("source")
241
+ lang = input.get("lang")
242
+ topic = input.get("topic")
243
+ kwargs = {}
244
+ if "system_template" in input:
245
+ kwargs["system_template"] = input["system_template"]
246
+ if "system_message" in input:
247
+ kwargs["system_message"] = input["system_message"]
248
+
249
+ # 转换成 Chat 对象
250
+ chat = cls(
251
+ id=_id,
252
+ name=_name,
253
+ prompt_style=prompt_style,
254
+ source=source,
255
+ lang=lang,
256
+ topic=topic,
257
+ origin_json=deepcopy(input),
258
+ **kwargs,
259
+ )
260
+ if "messages" in input:
261
+ for msg in input["messages"]:
262
+ if msg["role"] == "HUMAN":
263
+ role = chat.role_human
264
+ elif msg["role"] == "OBSERVATION":
265
+ role = chat.role_observation
266
+ elif msg["role"] == "ASSISTANT":
267
+ role = chat.role_assistant
268
+ else:
269
+ raise ValueError(f"不支持数据集中的 role: {msg['role']}")
270
+
271
+ chat.append_message(role, msg["content"])
272
+
273
+ elif "turns" in input:
274
+ for turn in input["turns"]:
275
+ if "HUMAN" in turn:
276
+ content = turn["HUMAN"]
277
+ chat.append_message(chat.role_human, content)
278
+ if "OBSERVATION" in turn:
279
+ content = turn["OBSERVATION"]
280
+ chat.append_message(chat.role_observation, content)
281
+ if "ASSISTANT" in turn:
282
+ content = turn["ASSISTANT"]
283
+ chat.append_message(chat.role_assistant, content)
284
+
285
+ return chat
286
+
287
+ @classmethod
288
+ def from_pack(
289
+ cls,
290
+ packs: Dict[str, List[str]],
291
+ name: str,
292
+ prompt_style: Optional[PromptStyle] = None,
293
+ ) -> list:
294
+ """根据 pack 数据创建 Chat 对象.
295
+
296
+ Params:
297
+ packs: `dict`, pack 样本数据
298
+ {
299
+ 'inputs': ['xx', 'xx'],
300
+ 'outputs': ['xx', 'xx'],
301
+ }
302
+
303
+ name: `str`, 符号系统名称
304
+ prompt_style: `Optional[PromptStyle]`, 指定 prompt 风格, 默认使用和 name 一致的风格
305
+ """
306
+ chat = cls(name=name, prompt_style=prompt_style)
307
+ packs = cls._format_packs(packs)
308
+
309
+ sys_pattern = re.compile(chat.system_template.format(r"(.*?)"), re.DOTALL)
310
+ turn_pattern = re.compile(chat.turn_start.format(r"(\d+)"), re.DOTALL)
311
+ human_pattern = re.compile(
312
+ chat.role_template.format(chat.role_human).strip(), re.DOTALL
313
+ )
314
+ observe_pattern = re.compile(
315
+ chat.role_template.format(chat.role_observation).strip(), re.DOTALL
316
+ )
317
+ assistant_pattern = re.compile(
318
+ chat.role_template.format(chat.role_assistant).strip(), re.DOTALL
319
+ )
320
+
321
+ chats = []
322
+ for input, output in zip(packs["input"], packs["output"]):
323
+ # system message
324
+ sys_match = sys_pattern.search(input)
325
+ if sys_match and sys_match.group(0):
326
+ # system 指令只在首轮, 新增 chat 对象
327
+ if len(chat.messages) > 0:
328
+ chats.append(chat)
329
+ chat = cls(name=name, prompt_style=prompt_style)
330
+
331
+ input = input[sys_match.end() :]
332
+ chat.system_message = sys_match.group(1)
333
+
334
+ # turn start
335
+ turn_match = turn_pattern.search(input)
336
+ if turn_match and turn_match.group(0):
337
+ # 当出现下一个轮次开始信息, 新增 chat 对象
338
+ if name in ["antglm", "antglm_raw", "chatglm2"]:
339
+ round_start = 1
340
+ else:
341
+ round_start = 0
342
+
343
+ if all(
344
+ [
345
+ len(turn_match.groups()) > 0,
346
+ int(turn_match.group(1)) == round_start,
347
+ len(chat.messages) > 0,
348
+ ]
349
+ ):
350
+ chats.append(chat)
351
+ chat = cls(name=name, prompt_style=prompt_style)
352
+
353
+ input = input[turn_match.end() :]
354
+
355
+ human_iter = human_pattern.finditer(input)
356
+ observe_iter = observe_pattern.finditer(input)
357
+ assistant_iter = assistant_pattern.finditer(input)
358
+ human_match = next(human_iter, None)
359
+ observe_match = next(observe_iter, None)
360
+ assistant_match = next(assistant_iter, None)
361
+
362
+ if not human_match and not observe_match:
363
+ # 无 role format
364
+ chat.append_message(chat.role_human, input)
365
+
366
+ while human_match or observe_match:
367
+ next_human_match = next(human_iter, None)
368
+ next_observe_match = next(observe_iter, None)
369
+ input = cls._append_human_observation(
370
+ chat,
371
+ input,
372
+ human_match=human_match,
373
+ next_human_match=next_human_match,
374
+ observe_match=observe_match,
375
+ next_observe_match=next_observe_match,
376
+ assistant_match=assistant_match,
377
+ )
378
+
379
+ human_match = next_human_match
380
+ observe_match = next_observe_match
381
+ next_human_match = next(human_iter, None)
382
+ next_observe_match = next(observe_iter, None)
383
+
384
+ if output:
385
+ chat.append_message(chat.role_assistant, output)
386
+
387
+ if chat.messages:
388
+ chats.append(chat)
389
+
390
+ return chats
391
+
392
+ @classmethod
393
+ def _append_human_observation(
394
+ cls,
395
+ chat,
396
+ input: str,
397
+ human_match: Optional[re.Match] = None,
398
+ next_human_match: Optional[re.Match] = None,
399
+ observe_match: Optional[re.Match] = None,
400
+ next_observe_match: Optional[re.Match] = None,
401
+ assistant_match: Optional[re.Match] = None,
402
+ ) -> str:
403
+ """给 chat 对象增加 human/observation message."""
404
+ if observe_match:
405
+ # observation 在 human 之后
406
+ if observe_match.span()[0] > observe_match.span()[0]:
407
+ human_str = input[observe_match.span()[1] : observe_match.span()[0]]
408
+ observe_str = input[observe_match.span()[1] : assistant_match.span()[0]]
409
+ chat.append_message(chat.role_human, human_str.strip())
410
+ input_end = observe_match.span()[1]
411
+ if observe_match.span()[0] < next_human_match.span()[0]:
412
+ chat.append_message(chat.role_observation, observe_str.strip())
413
+ input_end = assistant_match.span()[1]
414
+ else:
415
+ # observation 在 human 之前
416
+ human_str = input[observe_match.span()[1] : assistant_match.span()[0]]
417
+ observe_str = input[observe_match.span()[1] : observe_match.span()[0]]
418
+ chat.append_message(chat.role_observation, observe_str.strip())
419
+ input_end = observe_match.span()[1]
420
+ if observe_match.span()[0] < next_observe_match.span()[0]:
421
+ chat.append_message(chat.role_human, human_str.strip())
422
+ input_end = assistant_match.span()[1]
423
+ else:
424
+ if assistant_match:
425
+ human_str = input[human_match.span()[1] : assistant_match.span()[0]]
426
+ input_end = assistant_match.span()[1]
427
+ else:
428
+ human_str = input[human_match.span()[1] :]
429
+ input_end = len(input)
430
+ chat.append_message(chat.role_human, human_str.strip())
431
+
432
+ return input[input_end:]
433
+
434
+ @classmethod
435
+ def from_inout(
436
+ cls,
437
+ sample: Dict[str, str],
438
+ name: str,
439
+ prompt_style: Optional[PromptStyle] = None,
440
+ ):
441
+ """根据单样本创建一个 Chat 对象.
442
+
443
+ Params:
444
+ sample: `Dict[str, str]`, input/output 数据样本
445
+ {
446
+ "input": "xxx",
447
+ "output": "xxx",
448
+ }
449
+
450
+ name: `str`, 符号系统名称
451
+ prompt_style: `Optional[PromptStyle]`, 指定 prompt 风格, 默认使用和 name 一致的风格
452
+ """
453
+ chat = cls(name=name, prompt_style=prompt_style)
454
+ input = sample["input"]
455
+ output = sample["output"]
456
+
457
+ sys_pattern = re.compile(chat.system_template.format(r"(.*?)"), re.DOTALL)
458
+ turn_pattern = re.compile(chat.turn_start.format(r"(\d+)"), re.DOTALL)
459
+ human_pattern = re.compile(
460
+ chat.role_template.format(chat.role_human).strip(), re.DOTALL
461
+ )
462
+ observe_pattern = re.compile(
463
+ chat.role_template.format(chat.role_observation).strip(), re.DOTALL
464
+ )
465
+ assistant_pattern = re.compile(
466
+ chat.role_template.format(chat.role_assistant).strip(), re.DOTALL
467
+ )
468
+
469
+ # 去除轮次信息
470
+ input = turn_pattern.sub("", input)
471
+
472
+ # system message search
473
+ sys_match = sys_pattern.search(input)
474
+ if sys_match and sys_match.group(0):
475
+ input = input[sys_match.end() :]
476
+ chat.system_message = sys_match.group(1)
477
+
478
+ human_iter = human_pattern.finditer(input)
479
+ observe_iter = observe_pattern.finditer(input)
480
+ assistant_iter = assistant_pattern.finditer(input)
481
+ human_match = next(human_iter, None)
482
+ observe_match = next(observe_iter, None)
483
+ assistant_match = next(assistant_iter, None)
484
+ next_human_match = next(human_iter, None)
485
+ next_observe_match = next(observe_iter, None)
486
+
487
+ while any(
488
+ [
489
+ human_match,
490
+ observe_match,
491
+ assistant_match,
492
+ ]
493
+ ):
494
+ # human/observation 先后顺序可能不一样, 并且有可能有多个
495
+ # 判断 assitant 之前是否还有 human/observation
496
+ while any(
497
+ [
498
+ human_match and human_match.span()[0] < assistant_match.span()[0],
499
+ observe_match
500
+ and observe_match.span()[0] < assistant_match.span()[0],
501
+ next_human_match
502
+ and next_human_match.span()[0] < assistant_match.span()[0],
503
+ next_observe_match
504
+ and next_observe_match.span()[0] < assistant_match.span()[0],
505
+ ]
506
+ ):
507
+ if not input:
508
+ break
509
+
510
+ cls._append_human_observation(
511
+ chat,
512
+ input,
513
+ human_match=human_match,
514
+ next_human_match=next_human_match,
515
+ observe_match=observe_match,
516
+ next_observe_match=next_observe_match,
517
+ assistant_match=assistant_match,
518
+ )
519
+
520
+ human_match = next_human_match
521
+ observe_match = next_observe_match
522
+ next_human_match = next(human_iter, None)
523
+ next_observe_match = next(observe_iter, None)
524
+
525
+ # assistant message
526
+ if assistant_match and assistant_match.span():
527
+ if observe_match:
528
+ if (
529
+ observe_match.span()
530
+ and observe_match.span()[0] < human_match.span()[0]
531
+ ):
532
+ assistant_str = input[
533
+ assistant_match.span()[1] : observe_match.span()[0]
534
+ ]
535
+ elif human_match:
536
+ if human_match.span():
537
+ assistant_str = input[
538
+ assistant_match.span()[1] : human_match.span()[0]
539
+ ]
540
+ else:
541
+ assistant_str = input[assistant_match.span()[1] :]
542
+
543
+ if assistant_str:
544
+ chat.append_message(chat.role_assistant, assistant_str)
545
+
546
+ assistant_match = next(assistant_iter, None)
547
+
548
+ if output:
549
+ chat.append_message(chat.role_assistant, output)
550
+
551
+ return chat
552
+
553
+ def __hash__(self):
554
+ """数据对象的 hash 函数."""
555
+ return hash(self.id)
556
+
557
+ def __post_init__(self):
558
+ """对象初始化后的处理, 处理包括:
559
+ - 根据数据对象名称, 支持转成其他开源数据对象的基本信息
560
+ """
561
+ self.id = str(uuid.uuid4())
562
+ if not self.messages:
563
+ self.messages = []
564
+
565
+ if not self.name and not self.prompt_style:
566
+ logger.error(
567
+ "构造 Chat 对象至少包含以下一个入参: `name/prompt_style`.\n\n"
568
+ "`name` 支持以下 format 名称:"
569
+ )
570
+ logger.error(
571
+ "\n".join([f"{k}: {v}" for k, v in self.support_names.items()])
572
+ )
573
+ logger.error("\n`prompt_style` 参考 antllm.data.chat_format.PromptStyle")
574
+ raise ValueError
575
+
576
+ if self.name == "antglm":
577
+ # 默认 antglm 使用原始 antglm_raw - 第1轮\n用户: xx\n机器人: xx\n
578
+ self.name = "antglm_raw"
579
+
580
+ if not self.name and self.prompt_style == PromptStyle.ANTGLM_CHAT:
581
+ logger.info(
582
+ "Chat 对象入参没有 `name`, 默认使用 `ANTGLM_CHAT`, format:\n"
583
+ f"role_human: {self.role_human}\n"
584
+ f"role_assistant: {self.role_assistant}\n"
585
+ f"role_observation: {self.role_observation}\n"
586
+ f"role_template: {self.role_template}\n"
587
+ f"turn_start: {self.turn_start}\n"
588
+ f"human_end: {self.human_end}\n"
589
+ f"assistant_start: {self.assistant_start}\n"
590
+ f"assistant_end: {self.assistant_end}\n"
591
+ f"assistant_end_ids: {self.assistant_end_ids}\n"
592
+ f"general_role_end: {self.general_role_end}\n"
593
+ f"tool_template: {self.tool_template}\n"
594
+ f"code_template: {self.code_template}\n"
595
+ f"arithemetic_templte: {self.arithemetic_templte}\n"
596
+ f"\n入参 `name` 支持: ``"
597
+ )
598
+ return
599
+
600
+ if self.name == "antglm_raw" or self.prompt_style == PromptStyle.ANTGLM_RAW:
601
+ self.prompt_style = PromptStyle.ANTGLM_RAW
602
+ self.role_template = "{}"
603
+ self.role_human = "用户: "
604
+ self.role_assistant = "机器人: "
605
+ self.turn_start = "第{}轮\n"
606
+ self.general_role_end = "\n"
607
+
608
+ if (
609
+ self.name in ["chatglm1", "chatglm2"]
610
+ or self.prompt_style == PromptStyle.CHATGLM
611
+ ):
612
+ self.prompt_style = PromptStyle.CHATGLM
613
+ self.role_template = "{}"
614
+ self.role_human = "问:"
615
+ self.role_assistant = "答:"
616
+ self.turn_start = "[Round {}]\n"
617
+ if self.name == "chatglm1":
618
+ self.general_role_end = "\n"
619
+ else:
620
+ self.general_role_end = "\n\n"
621
+
622
+ elif self.name == "chatglm3" or self.prompt_style == PromptStyle.CHATGLM3:
623
+ self.prompt_style = PromptStyle.CHATGLM3
624
+ self.system_template = "<|system|>\n {}"
625
+ self.role_human = "<|user|>\n "
626
+ self.role_assistant = "<|assistant|>\n "
627
+ self.role_template = "{}"
628
+
629
+ elif self.name == "llama2" or self.prompt_style == PromptStyle.LLAMA2:
630
+ self.prompt_style = PromptStyle.LLAMA2
631
+ self.role_template = "{}"
632
+ self.system_template = "[INST] <<SYS>>\n{}\n<</SYS>>\n\n"
633
+ self.role_human = "[INST] "
634
+ self.role_assistant = "[/INST] "
635
+ self.human_end = " "
636
+ self.assistant_end = " </s><s>"
637
+
638
+ elif self.name == "qwen":
639
+ self.prompt_style = PromptStyle.CHATML
640
+ self.role_template = "{}"
641
+ self.system_template = "<|im_start|>system\n{}"
642
+ if not self.system_message:
643
+ self.system_message = "You are a helpful assistant."
644
+ self.role_human = "<|im_start|>user\n"
645
+ self.role_assistant = "<|im_start|>assistant\n"
646
+ self.general_role_end = "<|im_end|>\n"
647
+
648
+ elif self.name == "baichuan":
649
+ self.prompt_style = PromptStyle.BAICHUAN2
650
+ self.role_template = "{}"
651
+ self.system_template = "{}"
652
+ self.role_human = "<token_id-195>"
653
+ self.role_assistant = "<token_id-196>"
654
+
655
+ if not self.system_template:
656
+ self.system_template = "{}"
657
+
658
+ def readable_messages(self) -> str:
659
+ """将 messages 输出为人类可读的字符串, 方便分析数据."""
660
+ pass
661
+
662
+ @property
663
+ def prompt_str(self) -> str:
664
+ """将 Chat 对象转成 prompt str, 合并 human/assitant 输出为 format 字符串."""
665
+ return f"{self.prompt_inout['input']}{self.prompt_inout['output']}"
666
+
667
+ @classmethod
668
+ def _format_packs(cls, packs: Dict[str, List[str]]) -> Dict[str, List[str]]:
669
+ """格式化 pack 样本, 输出相同 pack inputs, outputs 个数."""
670
+ _packs = copy.deepcopy(packs)
671
+ if len(_packs["input"]) - 1 == len(_packs["output"]):
672
+ _packs["output"].append("")
673
+
674
+ if len(_packs["input"]) != len(_packs["output"]):
675
+ print(packs)
676
+ raise ValueError(
677
+ "输入 input 和 output 数量不匹配, "
678
+ f"input num: {len(packs['input'])}, "
679
+ f"output num: {len(packs['output'])}"
680
+ )
681
+
682
+ return _packs
683
+
684
+ @property
685
+ def prompt_inout(self) -> Dict[str, str]:
686
+ """将 Chat 对象转成 input prompt, output prompt 字符串.
687
+
688
+ Returns:
689
+ `Dict[str, str]`, 示例:
690
+ {
691
+ "input": "<role>SYSTEM</role>xxxx<role>HUMAN</role>你好<role>ASSISTANT</role>你好,有什么可以帮您?<role>ASSISTANT</role>", # noqa
692
+ "output": "你好,有什么可以帮您?"
693
+ }
694
+ """
695
+ packs = self._format_packs(self.prompt_pack)
696
+
697
+ # 兼容逻辑
698
+ if self.prompt_style == PromptStyle.ANTGLM_RAW:
699
+ packs["input"] = [f"{item} " for item in packs["input"]]
700
+
701
+ prompt_input = "".join(
702
+ [f"{x}{y}" for x, y in zip(packs["input"][:-1], packs["output"][:-1])]
703
+ )
704
+ prompt_input += packs["input"][-1]
705
+ prompt_output = packs["output"][-1]
706
+
707
+ # 兼容逻辑
708
+ if self.prompt_style == PromptStyle.ANTGLM_RAW:
709
+ prompt_input = prompt_input.strip()
710
+
711
+ return {
712
+ "input": prompt_input,
713
+ "output": prompt_output,
714
+ }
715
+
716
+ @property
717
+ def prompt_pack(self) -> Dict[str, List[str]]:
718
+ """将数据对象转成 pack input prompt, output prompt 字符串列表.:
719
+
720
+ Returns:
721
+ `Dict[str, List[str]]`, 示例:
722
+
723
+ {
724
+ "input": [
725
+ "<role>SYSTEM</role>xxxx<role>HUMAN</role>你好<role>ASSISTANT</role>",
726
+ "<role>HUMAN</role>讲个笑话<role>ASSISTANT</role>",
727
+ "<role>OBSERVATION</role>{\"weather\": \"晴\"}<role>ASSISTANT</role>"
728
+ ],
729
+ "output": [
730
+ "你好,有什么可以帮您?",
731
+ "笑话 1",
732
+ "今天天气 xxx"
733
+ ]
734
+ }
735
+
736
+ """
737
+ inputs = []
738
+ outputs = []
739
+
740
+ # 最开始 system 构造
741
+ system_prompt = ""
742
+ if self.system_message:
743
+ system_prompt = self.system_template.format(self.system_message)
744
+
745
+ if system_prompt:
746
+ ret = system_prompt + self.general_role_end
747
+ else:
748
+ ret = ""
749
+
750
+ # 有些 prompt style 单轮指令没有 format
751
+ if self.prompt_style in [
752
+ PromptStyle.ANTGLM_RAW,
753
+ PromptStyle.ANTGLM_ONLY_MULTITURN_CHAT,
754
+ ]:
755
+ if len(self.messages) <= 2:
756
+ output = ""
757
+ for role, message in self.messages:
758
+ if role == self.role_assistant:
759
+ output = message
760
+ else:
761
+ input = ret + message
762
+ return {
763
+ "input": [input],
764
+ "output": [output],
765
+ }
766
+
767
+ # 多轮对话
768
+ if self.name in ["antglm_raw", "chatglm2"]:
769
+ round_start = 1
770
+ else:
771
+ round_start = 0
772
+
773
+ for i, (role, message) in enumerate(self.messages):
774
+ # 轮次信息
775
+ if self.name in ["antglm_raw", "chatglm1", "chatglm2"]:
776
+ if i % 2 == 0:
777
+ ret += self.turn_start.format(i // 2 + round_start)
778
+
779
+ # 角色 + 内容
780
+ role_end = self.general_role_end
781
+ if role == self.role_assistant and self.assistant_end:
782
+ role_end = self.assistant_end
783
+ elif self.human_end:
784
+ role_end = self.human_end
785
+
786
+ ret += self.role_template.format(role) + message + role_end
787
+
788
+ if role == self.role_assistant:
789
+ # output 只保留实际 assistant 内容
790
+ if not message:
791
+ outputs.append("")
792
+ else:
793
+ outputs.append(message + role_end)
794
+ # input 需要连接 assistant role
795
+ inputs[-1] += ret[: -len(message + role_end)]
796
+ elif all(
797
+ [
798
+ role == self.role_observation,
799
+ len(self.messages) > 1,
800
+ self.messages[i - 1][0] != self.role_assistant,
801
+ ]
802
+ ):
803
+ # observation 之前不是 assistant, 需要将 observation 和上一个 input 连接一起
804
+ continue
805
+ else:
806
+ inputs.append(ret)
807
+ ret = ""
808
+
809
+ # 最后一轮不是机器人回复, 需要拼接机器人 role, 用于模型生成
810
+ if i == len(self.messages) - 1 and role != self.role_assistant:
811
+ inputs[-1] += self.role_template.format(self.role_assistant).strip()
812
+
813
+ # 兼容逻辑, 去除 inputs 最后空格符号
814
+ if self.prompt_style == PromptStyle.ANTGLM_RAW:
815
+ inputs = [item.strip() for item in inputs]
816
+
817
+ return {
818
+ "input": inputs,
819
+ "output": outputs,
820
+ }
821
+
822
+ @property
823
+ def turns_num(self) -> int:
824
+ """和机器人的交互轮数, 以用户输出多少次为轮数个数."""
825
+ return sum([1 if msg[0] == self.role_human else 0 for msg in self.messages])
826
+
827
+ def to_json(self) -> dict:
828
+ """输出 chat json dict 格式, 包含不同角色和机器人交互的每轮信息.
829
+
830
+ Returns
831
+ `List[dict]`, {
832
+ "id": "xx",
833
+ "messages": [
834
+ {"role": "HUMAN", "content": "xxx"}
835
+ ]
836
+ "turns": [
837
+ {"HUMAN": "xx", "OBSERVATION": "xx", "ASSISTANT": "xx"}
838
+ ]
839
+ }
840
+ """
841
+ turns = []
842
+ messages = []
843
+ turn = {}
844
+ for msg in self.messages:
845
+ if msg[0] == self.role_assistant:
846
+ messages.append({"role": "ASSISTANT", "content": msg[1]})
847
+ turn["ASSISTANT"] = msg[1]
848
+ turns.append(turn)
849
+ turn = {}
850
+
851
+ if msg[0] == self.role_human:
852
+ messages.append({"role": "HUMAN", "content": msg[1]})
853
+ turn["HUMAN"] = msg[1]
854
+
855
+ if msg[0] == self.role_observation:
856
+ messages.append({"role": "OBSERVATION", "content": msg[1]})
857
+ turn["OBSERVATION"] = msg[1]
858
+
859
+ if self.messages[-1][0] == self.role_human:
860
+ messages.append({"role": "ASSISTANT", "content": ""})
861
+ turn["ASSISTANT"] = ""
862
+ turns.append(turn)
863
+
864
+ result = self.origin_json or {}
865
+ result.update(
866
+ {
867
+ "id": self.id,
868
+ "name": self.name,
869
+ "source": self.source,
870
+ "lang": self.lang,
871
+ "topic": self.topic,
872
+ "system_template": self.system_template,
873
+ "system_message": self.system_message,
874
+ "turns": turns,
875
+ "messages": messages,
876
+ }
877
+ )
878
+
879
+ return result
880
+
881
+ def set_system_message(self, system_message: str):
882
+ """Set the system message."""
883
+ self.system_message = system_message
884
+
885
+ def append_message(self, role: str, message: str):
886
+ """Append a new message."""
887
+ if not message:
888
+ message = ""
889
+ self.messages.append([role, message])
890
+
891
+ def to_openai_api_messages(self) -> List[dict]:
892
+ """Convert the conversation to OpenAI chat completion format."""
893
+ ret = [{"role": "system", "content": self.system_message}]
894
+
895
+ for i, (_, msg) in enumerate(self.messages[self.offset :]):
896
+ if i % 2 == 0:
897
+ ret.append({"role": "user", "content": msg})
898
+ else:
899
+ if msg is not None:
900
+ ret.append({"role": "assistant", "content": msg})
901
+ return ret
902
+
903
+ def copy(self):
904
+ return copy.deepcopy(self)
chat_template.jinja ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#- Tiny checkpoint template: preserve audio/text rendering exactly. -#}
2
+ {%- for message in messages %}
3
+ {%- if message.content is iterable and message.content is not string %}
4
+ {%- for part in message.content %}
5
+ {%- 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) %}
6
+ {{- raise_exception('Ming-ASR-Tiny supports audio/text content only.') }}
7
+ {%- endif %}
8
+ {%- endfor %}
9
+ {%- endif %}
10
+ {%- endfor %}
11
+ {{- '<role>SYSTEM</role>' }}
12
+ {%- if messages and messages[0].role == 'system' and messages[0].content is string %}
13
+ {{- messages[0].content }}
14
+ {%- else %}
15
+ {{- '你是一个友好的AI助手。' }}
16
+ {%- endif %}
17
+
18
+ {{- '
19
+
20
+ detailed thinking ' }}
21
+ {{- 'on' if enable_thinking else 'off' }}
22
+ {{- '<|role_end|>' }}
23
+
24
+ {%- for message in messages %}
25
+ {%- set role_lower = message.role | lower %}
26
+
27
+ {%- if role_lower in ['user', 'human'] -%}
28
+ <role>HUMAN</role>
29
+ {%- set contents = message.content if message.content is iterable and message.content is not string else [message.content] %}
30
+ {%- for part in contents %}
31
+ {%- if part.type is defined %}
32
+ {%- if part.type == 'audio' or 'audio_url' in part -%}
33
+ <AUDIO>
34
+ {%- elif part.type == 'text' %}
35
+ {{- part.text }}
36
+ {%- endif %}
37
+ {%- else %}
38
+ {{- part }}
39
+ {%- endif %}
40
+ {%- endfor %}
41
+ {{- '<|role_end|>' }}
42
+
43
+ {%- elif role_lower in ['assistant'] -%}
44
+ <role>ASSISTANT</role>
45
+ {%- set contents = message.content if message.content is iterable and message.content is not string else [message.content] %}
46
+ {%- for part in contents %}
47
+ {%- if part.type is defined and part.type == 'text' %}
48
+ {{- part.text }}
49
+ {%- elif part is string %}
50
+ {{- part }}
51
+ {%- endif %}
52
+ {%- endfor %}
53
+ {{- '<|role_end|>' }}
54
+ {%- endif %}
55
+ {%- endfor %}
56
+
57
+ {{- '<role>ASSISTANT</role>' -}}
config.json ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "ming_v3_asr",
3
+ "architectures": [
4
+ "MingV3ASRForConditionalGeneration"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_ming_v3_asr.MingV3ASRConfig",
8
+ "AutoModelForCausalLM": "modeling_ming_v3_asr.MingV3ASRForConditionalGeneration",
9
+ "AutoProcessor": "processing_ming_v3_asr.MingV3ASRProcessor"
10
+ },
11
+ "tie_word_embeddings": false,
12
+ "audio_token_id": 157168,
13
+ "text_config": {
14
+ "vocab_size": 157184,
15
+ "hidden_size": 1536,
16
+ "intermediate_size": 4608,
17
+ "num_hidden_layers": 24,
18
+ "num_attention_heads": 16,
19
+ "num_key_value_heads": 16,
20
+ "hidden_act": "silu",
21
+ "use_qkv_bias": false,
22
+ "use_bias": false,
23
+ "rms_norm_eps": 1e-06,
24
+ "tie_word_embeddings": false,
25
+ "embedding_dropout": 0.0,
26
+ "attention_dropout": 0.0,
27
+ "output_dropout": 0.0,
28
+ "initializer_range": 0.02,
29
+ "max_position_embeddings": 8192,
30
+ "rope_theta": 10000,
31
+ "use_cache": true,
32
+ "max_window_layers": 20,
33
+ "rope_scaling": null,
34
+ "pad_token_id": 156892,
35
+ "eos_token_id": 156892,
36
+ "num_experts": 128,
37
+ "num_shared_experts": 1,
38
+ "num_experts_per_tok": 8,
39
+ "n_group": 8,
40
+ "topk_group": 4,
41
+ "moe_intermediate_size": 512,
42
+ "moe_shared_expert_intermediate_size": 512,
43
+ "first_k_dense_replace": 1,
44
+ "head_dim": 128,
45
+ "output_router_logits": false,
46
+ "use_qk_norm": true,
47
+ "num_nextn_predict_layers": 1,
48
+ "mtp_loss_scaling_factor": 0,
49
+ "moe_router_enable_expert_bias": true,
50
+ "routed_scaling_factor": 2.5,
51
+ "layer_group_size": 4,
52
+ "kv_lora_rank": 512,
53
+ "q_lora_rank": 256,
54
+ "qk_rope_head_dim": 64,
55
+ "v_head_dim": 128,
56
+ "qk_nope_head_dim": 128,
57
+ "rope_interleave": true,
58
+ "score_function": "sigmoid",
59
+ "scoring_func": "sigmoid",
60
+ "seq_aux": true,
61
+ "topk_method": "noaux_tc",
62
+ "router_dtype": "fp32",
63
+ "gated_attention_proj_granularity_type": "head_wise",
64
+ "no_kda_lora": true,
65
+ "kda_safe_gate": true,
66
+ "kda_lower_bound": -5.0,
67
+ "short_conv_kernel_size": 4
68
+ },
69
+ "audio_config": {
70
+ "n_mels": 128,
71
+ "n_audio_ctx": 3000,
72
+ "n_audio_state": 1280,
73
+ "n_audio_head": 20,
74
+ "n_audio_layer": 32,
75
+ "downsampler_kernel_size_list": [
76
+ 3
77
+ ],
78
+ "downsampler_stride_list": [
79
+ 2
80
+ ]
81
+ },
82
+ "asr_output_format": "plain",
83
+ "supported_modalities": [
84
+ "audio"
85
+ ],
86
+ "dtype": "bfloat16"
87
+ }
configuration_ming_v3_asr.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Antgroup and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Ming V3 ASR audio/text configuration."""
16
+
17
+ import os
18
+ from typing import Union
19
+
20
+ from transformers.configuration_utils import PretrainedConfig
21
+ from transformers.utils import logging
22
+
23
+ from .audio_spec import MingAudioSpec
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ class BailingMoeV3Config(PretrainedConfig):
29
+ model_type = "bailing_moe_v3"
30
+
31
+ def __init__(
32
+ self,
33
+ vocab_size=157184,
34
+ hidden_size=2048,
35
+ intermediate_size=5120,
36
+ num_hidden_layers=20,
37
+ num_attention_heads=16,
38
+ num_key_value_heads=4,
39
+ hidden_act="silu",
40
+ use_qkv_bias=False, # bailing only
41
+ use_bias=False, # bailing only
42
+ rms_norm_eps=1e-06,
43
+ tie_word_embeddings=False, # PretrainedConfig key, here change default value.
44
+ embedding_dropout=0.0,
45
+ attention_dropout=0.0,
46
+ output_dropout=0.0,
47
+ initializer_range=0.02,
48
+ max_position_embeddings=32768,
49
+ rope_theta=600000.0,
50
+ use_cache=True,
51
+ max_window_layers=20,
52
+ rope_scaling=None,
53
+ pad_token_id=156892,
54
+ eos_token_id=156892,
55
+ num_experts=256,
56
+ num_shared_experts=1,
57
+ num_experts_per_tok=8,
58
+ n_group=8,
59
+ topk_group=4,
60
+ moe_intermediate_size=512,
61
+ moe_shared_expert_intermediate_size=512,
62
+ expert_swiglu_limit_list=None,
63
+ share_expert_swiglu_limit_list=None,
64
+ first_k_dense_replace=1,
65
+ head_dim=128,
66
+ output_router_logits=False,
67
+ use_qk_norm=True,
68
+ num_nextn_predict_layers=0,
69
+ mtp_loss_scaling_factor=0,
70
+ moe_router_enable_expert_bias=True,
71
+ routed_scaling_factor=1.0,
72
+ layer_group_size=5,
73
+ kv_lora_rank=512,
74
+ q_lora_rank=None,
75
+ qk_rope_head_dim=64,
76
+ v_head_dim=128,
77
+ qk_nope_head_dim=128,
78
+ rope_interleave=True,
79
+ score_function="sigmoid",
80
+ scoring_func="sigmoid",
81
+ seq_aux=True,
82
+ topk_method="noaux_tc",
83
+ router_dtype="fp32",
84
+ gated_attention_proj_granularity_type=None,
85
+ no_kda_lora=False,
86
+ kda_safe_gate=False,
87
+ kda_lower_bound=None,
88
+ short_conv_kernel_size=4,
89
+ **kwargs,
90
+ ):
91
+ # Historical mixed checkpoints carry these non-audio metadata fields.
92
+ for key in (
93
+ "image_patch_token",
94
+ "video_patch_token",
95
+ "image_start_token",
96
+ "video_start_token",
97
+ "mrope_section",
98
+ ):
99
+ kwargs.pop(key, None)
100
+ self.num_hidden_layers = num_hidden_layers
101
+ self.vocab_size = vocab_size
102
+ self.hidden_size = hidden_size
103
+ self.intermediate_size = intermediate_size
104
+ self.num_attention_heads = num_attention_heads
105
+ self.num_key_value_heads = num_key_value_heads
106
+ self.hidden_act = hidden_act
107
+ self.use_qkv_bias = use_qkv_bias
108
+ self.use_bias = use_bias
109
+ self.rms_norm_eps = rms_norm_eps
110
+ self.embedding_dropout = embedding_dropout
111
+ self.attention_dropout = attention_dropout
112
+ self.output_dropout = output_dropout
113
+ self.num_nextn_predict_layers = num_nextn_predict_layers
114
+ self.mtp_loss_scaling_factor = mtp_loss_scaling_factor
115
+ self.initializer_range = initializer_range
116
+ self.max_position_embeddings = max_position_embeddings
117
+ self.rope_theta = rope_theta
118
+ self.use_cache = use_cache
119
+ self.max_window_layers = max_window_layers
120
+ self.head_dim = head_dim or self.hidden_size // self.num_attention_heads
121
+ self.rope_scaling = rope_scaling
122
+ self.use_qk_norm = use_qk_norm
123
+ self.moe_router_enable_expert_bias = moe_router_enable_expert_bias
124
+ self.routed_scaling_factor = routed_scaling_factor
125
+
126
+ # MoE configs
127
+ self.num_experts = num_experts
128
+ self.num_shared_experts = num_shared_experts
129
+ self.num_experts_per_tok = num_experts_per_tok
130
+ self.n_group = n_group
131
+ self.topk_group = topk_group
132
+ self.moe_intermediate_size = moe_intermediate_size
133
+ self.moe_shared_expert_intermediate_size = moe_shared_expert_intermediate_size
134
+ self.expert_swiglu_limit_list = (
135
+ None if expert_swiglu_limit_list is None else list(expert_swiglu_limit_list)
136
+ )
137
+ self.share_expert_swiglu_limit_list = (
138
+ None
139
+ if share_expert_swiglu_limit_list is None
140
+ else list(share_expert_swiglu_limit_list)
141
+ )
142
+ self.first_k_dense_replace = first_k_dense_replace
143
+ self.output_router_logits = output_router_logits
144
+
145
+ # Linear configs
146
+ self.layer_group_size = layer_group_size
147
+ if not isinstance(layer_group_size, int) or layer_group_size < 1:
148
+ raise ValueError("layer_group_size must be a positive integer")
149
+ # Match the trained decoder layout, including a trailing partial group.
150
+ # Transformers uses these types to allocate recurrent and KV cache layers.
151
+ layer_types = [
152
+ "full_attention"
153
+ if (index + 1) % layer_group_size == 0
154
+ or index >= num_hidden_layers // layer_group_size * layer_group_size
155
+ else "linear_attention"
156
+ for index in range(num_hidden_layers)
157
+ ]
158
+ serialized_layer_types = kwargs.pop("layer_types", None)
159
+ if (
160
+ serialized_layer_types is not None
161
+ and list(serialized_layer_types) != layer_types
162
+ ):
163
+ raise ValueError(
164
+ "layer_types does not match the configured Ming decoder layout"
165
+ )
166
+ self.layer_types = layer_types
167
+ # mla
168
+ self.kv_lora_rank = kv_lora_rank
169
+ self.q_lora_rank = q_lora_rank
170
+ self.qk_rope_head_dim = qk_rope_head_dim
171
+
172
+ self.score_function = score_function
173
+ self.scoring_func = scoring_func
174
+ self.seq_aux = seq_aux
175
+ self.topk_method = topk_method
176
+ self.v_head_dim = v_head_dim
177
+ self.qk_nope_head_dim = qk_nope_head_dim
178
+ self.qk_head_dim = qk_nope_head_dim + qk_rope_head_dim
179
+ self.rope_interleave = rope_interleave
180
+ self.router_dtype = router_dtype
181
+ self.gated_attention_proj_granularity_type = (
182
+ gated_attention_proj_granularity_type
183
+ )
184
+ self.no_kda_lora = no_kda_lora
185
+ self.kda_safe_gate = kda_safe_gate
186
+ self.kda_lower_bound = kda_lower_bound
187
+ self.short_conv_kernel_size = short_conv_kernel_size
188
+ super().__init__(
189
+ pad_token_id=pad_token_id,
190
+ eos_token_id=eos_token_id,
191
+ tie_word_embeddings=tie_word_embeddings,
192
+ **kwargs,
193
+ )
194
+
195
+
196
+ class MingV3ASREncoderConfig(PretrainedConfig):
197
+ model_type = "ming_v3_asr_audio"
198
+
199
+ def __init__(
200
+ self,
201
+ n_mels=128,
202
+ n_audio_ctx=3000,
203
+ n_audio_state=1280,
204
+ n_audio_head=20,
205
+ n_audio_layer=32,
206
+ downsampler_kernel_size_list=None,
207
+ downsampler_stride_list=None,
208
+ downsampler_padding_list=None,
209
+ chunk_frames=3000,
210
+ **kwargs,
211
+ ):
212
+ super().__init__(**kwargs)
213
+ self.n_mels = n_mels
214
+ self.n_audio_ctx = n_audio_ctx
215
+ self.n_audio_state = n_audio_state
216
+ self.n_audio_head = n_audio_head
217
+ self.n_audio_layer = n_audio_layer
218
+ self.downsampler_kernel_size_list = list(
219
+ [3]
220
+ if downsampler_kernel_size_list is None
221
+ else downsampler_kernel_size_list
222
+ )
223
+ self.downsampler_stride_list = list(
224
+ [2] if downsampler_stride_list is None else downsampler_stride_list
225
+ )
226
+ self.downsampler_padding_list = list(
227
+ [kernel // 2 for kernel in self.downsampler_kernel_size_list]
228
+ if downsampler_padding_list is None
229
+ else downsampler_padding_list
230
+ )
231
+ self.chunk_frames = chunk_frames
232
+ MingAudioSpec.from_config(self)
233
+
234
+ @classmethod
235
+ def from_pretrained(
236
+ cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs
237
+ ) -> "PretrainedConfig":
238
+ config_dict, kwargs = cls.get_config_dict(
239
+ pretrained_model_name_or_path, **kwargs
240
+ )
241
+ if "audio_config" in config_dict:
242
+ config_dict = config_dict["audio_config"]
243
+ return cls.from_dict(config_dict, **kwargs)
244
+
245
+
246
+ class MingV3ASRConfig(PretrainedConfig):
247
+ model_type = "ming_v3_asr"
248
+ sub_configs = {
249
+ "text_config": BailingMoeV3Config,
250
+ "audio_config": MingV3ASREncoderConfig,
251
+ }
252
+
253
+ def __init__(
254
+ self,
255
+ text_config=None,
256
+ audio_config=None,
257
+ audio_token_id=157168,
258
+ tie_word_embeddings=False,
259
+ mlp_depth=2,
260
+ **kwargs,
261
+ ):
262
+ for key in (
263
+ "vision_config",
264
+ "image_token_id",
265
+ "video_token_id",
266
+ "vision_start_token_id",
267
+ "vision_end_token_id",
268
+ "mrope_section",
269
+ ):
270
+ kwargs.pop(key, None)
271
+
272
+ if isinstance(text_config, dict):
273
+ text_config = BailingMoeV3Config(**text_config)
274
+ elif text_config is None:
275
+ text_config = BailingMoeV3Config()
276
+
277
+ if isinstance(audio_config, dict):
278
+ audio_config = MingV3ASREncoderConfig(**audio_config)
279
+ elif audio_config is None:
280
+ audio_config = MingV3ASREncoderConfig()
281
+
282
+ self.text_config = text_config
283
+ self.audio_config = audio_config
284
+ self.audio_token_id = audio_token_id
285
+
286
+ if not isinstance(mlp_depth, int) or mlp_depth < 2:
287
+ raise ValueError("Ming audio projector mlp_depth must be at least 2")
288
+ self.mlp_depth = mlp_depth
289
+
290
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
291
+
292
+ def get_text_config(self, decoder=False):
293
+ return self.text_config
examples/transcribe.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Transcribe local audio with the aligned Ming 3.0 ASR Tiny model."""
2
+ import argparse
3
+ import json
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ REPO_ROOT = Path(__file__).resolve().parents[1]
8
+ sys.path.insert(0, str(REPO_ROOT))
9
+ from asr_request import (
10
+ context_chunk_frames, decode_transcript, prepare_asr_request,
11
+ )
12
+
13
+
14
+ def main():
15
+ parser = argparse.ArgumentParser(description=__doc__)
16
+ parser.add_argument("--model", required=True, help="Complete checkpoint directory or model ID")
17
+ parser.add_argument("--audio", type=Path, required=True)
18
+ parser.add_argument("--device", default="cuda:0")
19
+ parser.add_argument("--attention", choices=("sdpa", "eager"), default="sdpa")
20
+ parser.add_argument("--max-new-tokens", type=int, default=256)
21
+ parser.add_argument("--prompt", default=None)
22
+ parser.add_argument("--language-hint", choices=("zh", "en"),
23
+ help="Optional known-language prefix; omit when language is unknown")
24
+ parser.add_argument("--audio-chunk-frames", type=int,
25
+ help="Mel frames per audio encoder chunk; 6000 supports up to 60-second chunks")
26
+ parser.add_argument("--context-chunks", action="store_true",
27
+ help="Context ASR: 3000 frames up to 30 s, else 6000")
28
+ parser.add_argument("--output", type=Path)
29
+ args = parser.parse_args()
30
+ if not args.audio.is_file():
31
+ parser.error(f"Audio file does not exist: {args.audio}")
32
+ if args.max_new_tokens < 1:
33
+ parser.error("--max-new-tokens must be positive")
34
+ if args.audio_chunk_frames is not None and args.audio_chunk_frames < 1:
35
+ parser.error("--audio-chunk-frames must be positive")
36
+ if args.context_chunks and args.audio_chunk_frames is not None:
37
+ parser.error("Use either --context-chunks or --audio-chunk-frames")
38
+
39
+ import soundfile as sf
40
+ import torch
41
+ from transformers import AutoModelForCausalLM, AutoProcessor
42
+
43
+ if not args.device.startswith("cuda") or not torch.cuda.is_available():
44
+ parser.error("The supported inference path requires a CUDA GPU")
45
+ processor = AutoProcessor.from_pretrained(args.model, trust_remote_code=True)
46
+ model = AutoModelForCausalLM.from_pretrained(
47
+ args.model, trust_remote_code=True, dtype=torch.bfloat16,
48
+ device_map=args.device, attn_implementation=args.attention,
49
+ ).eval()
50
+ waveform, rate = sf.read(args.audio, dtype="float32", always_2d=True)
51
+ audio_chunk_frames = (context_chunk_frames(len(waveform) / rate)
52
+ if args.context_chunks else args.audio_chunk_frames)
53
+ if audio_chunk_frames is not None:
54
+ model.config.audio_config.chunk_frames = audio_chunk_frames
55
+ inputs = prepare_asr_request(
56
+ processor, (waveform.T, rate), prompt=args.prompt,
57
+ language_hint=args.language_hint, audio_chunk_frames=audio_chunk_frames,
58
+ ).to(model.device)
59
+ eos = getattr(model.config, "text_config", model.config).eos_token_id
60
+ with torch.inference_mode():
61
+ output = model.generate(
62
+ **inputs, max_new_tokens=args.max_new_tokens, do_sample=False,
63
+ eos_token_id=eos, pad_token_id=eos, no_repeat_ngram_size=10,
64
+ )
65
+ generated = output[0, inputs.input_ids.shape[1]:]
66
+ transcript = decode_transcript(processor.tokenizer, generated.tolist())
67
+ print(transcript)
68
+ if args.output:
69
+ args.output.parent.mkdir(parents=True, exist_ok=True)
70
+ args.output.write_text(json.dumps({
71
+ "audio": str(args.audio), "model": args.model, "text": transcript,
72
+ "language_hint": args.language_hint,
73
+ "audio_chunk_frames": audio_chunk_frames,
74
+ "generated_token_ids": generated.tolist(), "max_new_tokens": args.max_new_tokens,
75
+ }, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
76
+
77
+
78
+ if __name__ == "__main__":
79
+ main()
feature_extraction_ming_v3_asr.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Ant Group. All rights reserved.
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0
5
+ # Unless required by applicable law or agreed to in writing, software
6
+ # distributed under the License is distributed on an "AS IS" BASIS,
7
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8
+ """Serializable Ming V3 ASR frontend, independent of the serving engine.
9
+
10
+ The numerical frontend is adapted from SGLang's ``bailing_audio_frontend.py``
11
+ (Apache-2.0), which implements the OpenAI Whisper Slaney-normalized mel bank.
12
+ """
13
+
14
+ import math
15
+ from functools import lru_cache
16
+ from numbers import Integral, Real
17
+
18
+ import numpy as np
19
+ import torch
20
+ from transformers.feature_extraction_sequence_utils import SequenceFeatureExtractor
21
+ from transformers.feature_extraction_utils import BatchFeature
22
+
23
+ from .audio_spec import MingAudioSpec
24
+
25
+
26
+ @lru_cache(maxsize=2)
27
+ def _mel_filters(n_mels):
28
+ frequencies = torch.linspace(0, 8000, 201, dtype=torch.float64)
29
+ linear_scale = 200.0 / 3.0
30
+ log_start = 1000.0 / linear_scale
31
+ log_step = math.log(6.4) / 27.0
32
+ mel_max = log_start + math.log(8.0) / log_step
33
+ mels = torch.linspace(0, mel_max, n_mels + 2, dtype=torch.float64)
34
+ centers = linear_scale * mels
35
+ logarithmic = mels >= log_start
36
+ centers[logarithmic] = 1000.0 * torch.exp(
37
+ log_step * (mels[logarithmic] - log_start)
38
+ )
39
+ widths = centers[1:] - centers[:-1]
40
+ ramps = centers[:, None] - frequencies[None, :]
41
+ lower = -ramps[:-2] / widths[:-1, None]
42
+ upper = ramps[2:] / widths[1:, None]
43
+ bank = torch.maximum(
44
+ torch.zeros((), dtype=torch.float64), torch.minimum(lower, upper)
45
+ )
46
+ # Match the canonical Whisper bank's intermediate FP32 rounding before
47
+ # Slaney normalization; casting only at the end changes the coefficients.
48
+ bank = bank.float()
49
+ bank *= (2.0 / (centers[2:] - centers[:-2]))[:, None]
50
+ return bank.float()
51
+
52
+
53
+ class MingV3ASRFeatureExtractor(SequenceFeatureExtractor):
54
+ """Extract padded ``[clips, mel_frames, mel_bins]`` features.
55
+
56
+ Inputs are mono ``[samples]`` or channel-first ``[channels, samples]``
57
+ waveforms, a flat list of waveforms, or ``(waveform, sampling_rate)`` pairs.
58
+ Waveform amplitudes are used as supplied, including integer inputs; callers
59
+ decoding PCM should supply normalized floating point samples. Stereo is
60
+ averaged and non-16-kHz inputs use torchaudio's sinc resampler.
61
+
62
+ Features preserve the serving frontend's BF16 rounding. NumPy output uses
63
+ float32 to represent those same values. Lengths always count raw mel frames,
64
+ never projected token positions. Clips are not truncated or padded to 30 s.
65
+ """
66
+
67
+ model_input_names = ["audio_feats", "audio_feats_lengths"]
68
+
69
+ def __init__(
70
+ self,
71
+ feature_size=128,
72
+ sampling_rate=16000,
73
+ padding_value=0.0,
74
+ audio_config=None,
75
+ **kwargs,
76
+ ):
77
+ if sampling_rate != 16000:
78
+ raise ValueError("Ming feature extraction requires sampling_rate=16000")
79
+ if padding_value != 0.0:
80
+ raise ValueError("Ming mel padding_value must be zero")
81
+ if audio_config is None:
82
+ audio_config = {
83
+ "n_mels": feature_size,
84
+ "downsampler_kernel_size_list": [3],
85
+ "downsampler_stride_list": [2],
86
+ }
87
+ elif hasattr(audio_config, "to_dict"):
88
+ audio_config = audio_config.to_dict()
89
+ spec = MingAudioSpec.from_config(audio_config)
90
+ self.audio_config = {
91
+ "n_mels": spec.n_mels,
92
+ "chunk_frames": spec.chunk_frames,
93
+ "downsampler_kernel_size_list": list(spec.kernels),
94
+ "downsampler_stride_list": list(spec.strides),
95
+ "downsampler_padding_list": list(spec.paddings),
96
+ }
97
+ super().__init__(
98
+ feature_size=spec.n_mels,
99
+ sampling_rate=sampling_rate,
100
+ padding_value=padding_value,
101
+ **kwargs,
102
+ )
103
+
104
+ @property
105
+ def spec(self):
106
+ return MingAudioSpec.from_config(self.audio_config)
107
+
108
+ @staticmethod
109
+ def _is_rate_pair(value):
110
+ return (
111
+ isinstance(value, tuple)
112
+ and len(value) == 2
113
+ and isinstance(value[1], Real)
114
+ and not isinstance(value[0], Real)
115
+ )
116
+
117
+ @classmethod
118
+ def as_clips(cls, audio):
119
+ """Normalize the public flat clip input without guessing batch axes."""
120
+ if audio is None:
121
+ return []
122
+ if isinstance(audio, (torch.Tensor, np.ndarray)) or cls._is_rate_pair(audio):
123
+ return [audio]
124
+ if isinstance(audio, (list, tuple)):
125
+ if not audio:
126
+ return []
127
+ if all(isinstance(value, Real) for value in audio):
128
+ return [audio]
129
+ return list(audio)
130
+ raise ValueError(
131
+ "audio must contain waveforms or (waveform, sampling_rate) pairs"
132
+ )
133
+
134
+ def _prepare_waveform(self, value, sampling_rate):
135
+ if self._is_rate_pair(value):
136
+ value, sampling_rate = value
137
+ if (
138
+ not isinstance(sampling_rate, Integral)
139
+ or isinstance(sampling_rate, bool)
140
+ or sampling_rate <= 0
141
+ ):
142
+ raise ValueError("sampling_rate must be a positive integer")
143
+ try:
144
+ waveform = torch.as_tensor(value)
145
+ except (TypeError, ValueError, RuntimeError) as error:
146
+ raise ValueError("audio must be a numeric waveform") from error
147
+ if waveform.ndim not in (1, 2):
148
+ raise ValueError("audio shape must be [samples] or [channels, samples]")
149
+ if waveform.numel() == 0:
150
+ raise ValueError("audio must not be empty")
151
+ if waveform.is_complex() or not torch.isfinite(waveform).all():
152
+ raise ValueError("audio must contain finite real samples")
153
+ waveform = waveform.detach().to(device="cpu", dtype=torch.float32)
154
+ if waveform.ndim == 2:
155
+ waveform = waveform.mean(dim=0)
156
+ if sampling_rate != self.sampling_rate:
157
+ import torchaudio
158
+
159
+ waveform = torchaudio.functional.resample(
160
+ waveform, sampling_rate, self.sampling_rate
161
+ )
162
+ if waveform.numel() <= self.spec.n_fft // 2:
163
+ raise ValueError(
164
+ "audio is too short for Whisper reflect padding (need more than 200 samples at 16 kHz)"
165
+ )
166
+ if not torch.isfinite(waveform).all():
167
+ raise ValueError(
168
+ "audio contains non-finite values after downmix/resampling"
169
+ )
170
+ return waveform.contiguous()
171
+
172
+ def _extract_mel(self, waveform):
173
+ spec = self.spec
174
+ spectrum = torch.stft(
175
+ waveform,
176
+ spec.n_fft,
177
+ spec.hop_length,
178
+ window=torch.hann_window(spec.n_fft),
179
+ return_complex=True,
180
+ )
181
+ power = spectrum[..., :-1].abs().square()
182
+ mel = _mel_filters(spec.n_mels) @ power
183
+ log_mel = mel.clamp(min=1e-10).log10()
184
+ log_mel = torch.maximum(log_mel, log_mel.max() - 8.0)
185
+ return ((log_mel + 4.0) / 4.0).transpose(0, 1).to(torch.bfloat16)
186
+
187
+ def __call__(
188
+ self,
189
+ audio,
190
+ sampling_rate=None,
191
+ return_tensors=None,
192
+ padding=True,
193
+ truncation=False,
194
+ max_length=None,
195
+ return_attention_mask=False,
196
+ **kwargs,
197
+ ):
198
+ if kwargs:
199
+ raise TypeError(
200
+ f"Unsupported Ming audio options: {', '.join(sorted(kwargs))}"
201
+ )
202
+ if return_tensors not in (None, "pt", "np"):
203
+ raise ValueError("Ming audio supports return_tensors='pt' or 'np'")
204
+ if truncation or max_length is not None:
205
+ raise ValueError(
206
+ "Ming audio does not truncate waveforms; limit audio before processing"
207
+ )
208
+ if padding not in (True, False, "longest", "do_not_pad"):
209
+ raise ValueError("Ming audio pads mel features to the longest clip")
210
+ clips = self.as_clips(audio)
211
+ if not clips:
212
+ raise ValueError("audio must contain at least one nonempty waveform")
213
+ sampling_rate = self.sampling_rate if sampling_rate is None else sampling_rate
214
+ features = [
215
+ self._extract_mel(self._prepare_waveform(clip, sampling_rate))
216
+ for clip in clips
217
+ ]
218
+ lengths = torch.tensor([len(feature) for feature in features], dtype=torch.long)
219
+ padded = torch.nn.utils.rnn.pad_sequence(features, batch_first=True)
220
+ data = {"audio_feats": padded, "audio_feats_lengths": lengths}
221
+ if return_attention_mask:
222
+ data["audio_attention_mask"] = (
223
+ torch.arange(padded.shape[1])[None, :] < lengths[:, None]
224
+ ).long()
225
+ if return_tensors != "pt":
226
+ data = {
227
+ key: value.float().numpy()
228
+ if value.dtype == torch.bfloat16
229
+ else value.numpy()
230
+ for key, value in data.items()
231
+ }
232
+ return BatchFeature(data=data)
233
+
234
+
235
+ MingV3ASRFeatureExtractor.register_for_auto_class()
figures/asr.png ADDED

Git LFS Details

  • SHA256: 624d98d65546e12b1763eb157690e51e388f3db6de05ec1980ea457f4122e56d
  • Pointer size: 132 Bytes
  • Size of remote file: 1.24 MB
figures/bailing-logo.png ADDED
figures/contextasr.png ADDED

Git LFS Details

  • SHA256: 6924bd1057aa68ef194912995c92d8ca998ef68b15ec55053f5b168da087cd32
  • Pointer size: 131 Bytes
  • Size of remote file: 923 kB
figures/model.jpg ADDED

Git LFS Details

  • SHA256: 55a45a2358cb39f250eea875c45070103edc78af6bad771ef8f7f904ab46975f
  • Pointer size: 131 Bytes
  • Size of remote file: 317 kB
figures/开源asr.png ADDED

Git LFS Details

  • SHA256: e05cf1897bd7eb80d64146613e18f3fb83e1e46f763443f42525ee3eddddd795
  • Pointer size: 132 Bytes
  • Size of remote file: 1.01 MB
figures/自建asr.png ADDED

Git LFS Details

  • SHA256: 31ade60fefc3a90aab51439be9d52518775710f262a5a7e5371e89ff56667a40
  • Pointer size: 132 Bytes
  • Size of remote file: 1.23 MB
generation_config.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eos_token_id": 156892,
3
+ "pad_token_id": 156892,
4
+ "do_sample": false
5
+ }
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3c3aeb85649b6f64a032d069a2321826191d36fe1413191bddd01835b1570d45
3
+ size 10709697720
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a274b5c624f396a3a2547cbc7cf28aeb33890b61141457b45ac1af85ac6e7c55
3
+ size 7023162728
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_ming_v3_asr.py ADDED
@@ -0,0 +1,2150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 Antgroup and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """Ming-ASR-Tiny audio/text model; legacy class names preserve checkpoint loading."""
21
+
22
+ import math
23
+ import warnings
24
+ from copy import deepcopy
25
+ from typing import Callable, List, Optional, Tuple, Union
26
+
27
+ import torch
28
+ import torch.nn.functional as F
29
+ from torch import nn
30
+ from transformers.activations import ACT2FN
31
+ from transformers.cache_utils import Cache, DynamicCache, LinearAttentionLayer
32
+ from transformers.modeling_attn_mask_utils import (
33
+ AttentionMaskConverter,
34
+ _prepare_4d_attention_mask,
35
+ _prepare_4d_causal_attention_mask,
36
+ _prepare_4d_causal_attention_mask_for_sdpa,
37
+ )
38
+ from transformers.modeling_outputs import MoeModelOutputWithPast
39
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
40
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
41
+ from transformers.pytorch_utils import (
42
+ ALL_LAYERNORM_LAYERS,
43
+ is_torch_greater_or_equal_than_1_13,
44
+ )
45
+ from transformers.utils import (
46
+ add_start_docstrings,
47
+ add_start_docstrings_to_model_forward,
48
+ logging,
49
+ )
50
+
51
+ try:
52
+ from transformers.utils.import_utils import is_torch_fx_available
53
+ except ImportError:
54
+
55
+ def is_torch_fx_available():
56
+ return False
57
+
58
+
59
+ from dataclasses import dataclass
60
+
61
+ from einops import rearrange, repeat
62
+ from transformers.generation.utils import GenerationMixin
63
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
64
+ from transformers.processing_utils import Unpack
65
+ from transformers.utils import ModelOutput, TransformersKwargs
66
+ from transformers.utils.deprecation import deprecate_kwarg
67
+
68
+ from .audio_spec import MingAudioSpec
69
+ from .configuration_ming_v3_asr import (
70
+ BailingMoeV3Config,
71
+ MingV3ASRConfig,
72
+ )
73
+ from .modeling_ming_v3_asr_encoder import (
74
+ build_audio_encoder,
75
+ build_audio_projector,
76
+ encode_audio_clips,
77
+ )
78
+ from .modeling_whisper_encoder import WhisperAudioEncoder # noqa: F401 - cache transitive dependency
79
+
80
+
81
+ def _reject_visual_inputs(kwargs):
82
+ for key in (
83
+ "pixel_values",
84
+ "pixel_values_videos",
85
+ "image_grid_thw",
86
+ "video_grid_thw",
87
+ "images",
88
+ "videos",
89
+ ):
90
+ if kwargs.pop(key, None) is not None:
91
+ raise ValueError(
92
+ "Ming supports audio and text only; image/video inputs are unsupported"
93
+ )
94
+
95
+
96
+ def _audio_clip_lengths(audio_feats, audio_feats_lengths):
97
+ """Validate the flattened, padded raw-mel contract before any encoding."""
98
+ if not isinstance(audio_feats, torch.Tensor) or audio_feats.ndim != 3:
99
+ raise ValueError("audio_feats must have shape [clips, frames, mel_bins]")
100
+ if audio_feats_lengths is None:
101
+ raise ValueError("audio_feats_lengths must provide raw mel lengths")
102
+ lengths = torch.as_tensor(audio_feats_lengths)
103
+ if (
104
+ lengths.ndim != 1
105
+ or lengths.numel() != audio_feats.shape[0]
106
+ or lengths.dtype
107
+ not in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8)
108
+ ):
109
+ raise ValueError("audio_feats_lengths must contain one integer length per clip")
110
+ if (
111
+ not lengths.numel()
112
+ or torch.any(lengths <= 0)
113
+ or torch.any(lengths > audio_feats.shape[1])
114
+ ):
115
+ raise ValueError(
116
+ "audio frame lengths must be positive and within the padded feature size"
117
+ )
118
+ return lengths.tolist()
119
+
120
+
121
+ def _audio_request_counts(audio_num_clips, batch_size, total_clips):
122
+ if audio_num_clips is None:
123
+ if batch_size != 1:
124
+ raise ValueError(
125
+ "audio_num_clips is required to associate clips with each request"
126
+ )
127
+ return [total_clips]
128
+ counts = torch.as_tensor(audio_num_clips)
129
+ if (
130
+ counts.ndim != 1
131
+ or counts.numel() != batch_size
132
+ or counts.dtype
133
+ not in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8)
134
+ or torch.any(counts < 0)
135
+ or int(counts.sum()) != total_clips
136
+ ):
137
+ raise ValueError(
138
+ "audio_num_clips must contain each request's nonnegative clip count"
139
+ )
140
+ return counts.tolist()
141
+
142
+
143
+ def _default_rope_parameters(config, device=None, seq_len=None):
144
+ """Unscaled RoPE, retained locally because Transformers 5 removed its registry entry."""
145
+ dimension = int(config.head_dim * getattr(config, "partial_rotary_factor", 1.0))
146
+ frequencies = (
147
+ torch.arange(0, dimension, 2, dtype=torch.float32, device=device) / dimension
148
+ )
149
+ return 1.0 / (config.rope_theta**frequencies), 1.0
150
+
151
+
152
+ def roll_tensor(tensor, shifts=-1, dims=-1, fill_value=0):
153
+ """Roll the tensor input along the given dimension(s).
154
+ Inserted elements are set to be 0.0.
155
+ """
156
+ rolled_tensor = torch.roll(tensor, shifts=shifts, dims=dims)
157
+ rolled_tensor.select(dims, shifts).fill_(fill_value)
158
+ return rolled_tensor, rolled_tensor.sum()
159
+
160
+
161
+ try:
162
+ from fla.modules import FusedRMSNormGated, ShortConvolution
163
+ from fla.ops.kda import chunk_kda, fused_recurrent_kda
164
+ from fla.utils import tensor_cache
165
+ except ImportError as error:
166
+ raise ImportError(
167
+ "Ming KDA requires fla-core and its dependencies; see requirements.txt."
168
+ ) from error
169
+
170
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
171
+ # It means that the function will not be traced through and simply appear as a node in the graph.
172
+ if is_torch_fx_available():
173
+ if not is_torch_greater_or_equal_than_1_13:
174
+ import torch.fx
175
+
176
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
177
+
178
+
179
+ logger = logging.get_logger(__name__)
180
+
181
+ _CONFIG_FOR_DOC = "MingV3ASRConfig"
182
+
183
+
184
+ def index_first_axis(x, indices):
185
+ other_shape = x.shape[1:]
186
+ second_dim = other_shape.numel()
187
+ return torch.gather(
188
+ rearrange(x, "b ... -> b (...)"),
189
+ 0,
190
+ repeat(indices, "z -> z d", d=second_dim),
191
+ ).reshape(-1, *other_shape)
192
+
193
+
194
+ def index_put_first_axis(x, indices, first_axis_dim):
195
+ y = torch.zeros(first_axis_dim, *x.shape[1:], device=x.device, dtype=x.dtype)
196
+ y[indices] = x
197
+ # y.scatter_(0, repeat(indices, 'z -> z d', d=x.shape[1]), x)
198
+ return y
199
+
200
+
201
+ def pad_input(
202
+ hidden_states: torch.Tensor,
203
+ indices: torch.LongTensor,
204
+ batch_size: int,
205
+ seq_len: int,
206
+ ) -> torch.Tensor:
207
+ output = index_put_first_axis(hidden_states, indices, batch_size * seq_len)
208
+ return rearrange(output, "(b s) ... -> b s ...", b=batch_size)
209
+
210
+
211
+ @tensor_cache
212
+ def _get_unpad_data(attention_mask):
213
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
214
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
215
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
216
+ cu_seqlens = F.pad(
217
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
218
+ )
219
+ return (
220
+ indices,
221
+ cu_seqlens,
222
+ max_seqlen_in_batch,
223
+ )
224
+
225
+
226
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
227
+ warnings.warn(
228
+ "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"
229
+ )
230
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
231
+
232
+
233
+ def _make_causal_mask(
234
+ input_ids_shape: torch.Size,
235
+ dtype: torch.dtype,
236
+ device: torch.device,
237
+ past_key_values_length: int = 0,
238
+ ):
239
+ warnings.warn(
240
+ "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"
241
+ )
242
+ return AttentionMaskConverter._make_causal_mask(
243
+ input_ids_shape=input_ids_shape,
244
+ dtype=dtype,
245
+ device=device,
246
+ past_key_values_length=past_key_values_length,
247
+ )
248
+
249
+
250
+ class BailingMoeV3RMSNorm(nn.Module):
251
+ def __init__(self, hidden_size, eps=1e-6):
252
+ """
253
+ BailingMoeV3RMSNorm is equivalent to T5LayerNorm
254
+ """
255
+ super().__init__()
256
+ self.weight = nn.Parameter(torch.ones(hidden_size))
257
+ self.variance_epsilon = eps
258
+
259
+ def forward(self, hidden_states):
260
+ input_dtype = hidden_states.dtype
261
+ hidden_states = hidden_states.to(torch.float32)
262
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
263
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
264
+ return self.weight * hidden_states.to(input_dtype)
265
+
266
+
267
+ class BailingMoeV3GroupRMSNorm(nn.Module):
268
+ def __init__(self, hidden_size, group_norm_size, eps=1e-6):
269
+ """
270
+ BailingMoeV3RMSNorm is equivalent to T5LayerNorm
271
+ """
272
+ super().__init__()
273
+ self.weight = nn.Parameter(torch.ones(hidden_size))
274
+ self.group_norm_size = group_norm_size
275
+ assert hidden_size % group_norm_size == 0, (
276
+ "hidden_size must be divisible by group_norm_size"
277
+ )
278
+ self.variance_epsilon = eps
279
+
280
+ def forward(self, hidden_states):
281
+ input_dtype = hidden_states.dtype
282
+ input_shape = hidden_states.size()
283
+ group_input_shape = input_shape[:-1] + (
284
+ self.group_norm_size,
285
+ input_shape[-1] // self.group_norm_size,
286
+ )
287
+ hidden_states = hidden_states.view(group_input_shape)
288
+ hidden_states = hidden_states.to(torch.float32)
289
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
290
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
291
+ return self.weight * hidden_states.to(input_dtype).view(input_shape)
292
+
293
+
294
+ ALL_LAYERNORM_LAYERS.append(BailingMoeV3RMSNorm)
295
+
296
+
297
+ class BailingMoeV3RotaryEmbedding(nn.Module):
298
+ """Sequential rotary positions shared by audio and text tokens."""
299
+
300
+ inv_freq: torch.Tensor
301
+
302
+ def __init__(self, config: BailingMoeV3Config, device=None):
303
+ super().__init__()
304
+ # BC: "rope_type" was originally "type"
305
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
306
+ self.rope_type = config.rope_scaling.get(
307
+ "rope_type", config.rope_scaling.get("type")
308
+ )
309
+ else:
310
+ self.rope_type = "default"
311
+ self.max_seq_len_cached = config.max_position_embeddings
312
+ self.original_max_seq_len = config.max_position_embeddings
313
+
314
+ self.config = deepcopy(config)
315
+ self.config.head_dim = config.qk_rope_head_dim
316
+ self.config.partial_rotary_factor = 1.0
317
+ self.rope_init_fn = (
318
+ _default_rope_parameters
319
+ if self.rope_type == "default"
320
+ else ROPE_INIT_FUNCTIONS[self.rope_type]
321
+ )
322
+
323
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
324
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
325
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
326
+
327
+ @torch.no_grad()
328
+ @dynamic_rope_update
329
+ def forward(self, x, position_ids):
330
+ if position_ids.ndim != 2:
331
+ raise ValueError(
332
+ "Audio/text position_ids must have shape [batch, sequence]"
333
+ )
334
+ inv_freq = (
335
+ self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
336
+ )
337
+ positions = position_ids[:, None, :].float()
338
+ device_type = x.device.type if x.device.type != "mps" else "cpu"
339
+ with torch.autocast(device_type=device_type, enabled=False):
340
+ freqs = (inv_freq @ positions).transpose(1, 2)
341
+ emb = torch.cat((freqs, freqs), dim=-1)
342
+ cos = emb.cos() * self.attention_scaling
343
+ sin = emb.sin() * self.attention_scaling
344
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
345
+
346
+
347
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
348
+ def rotate_half(x):
349
+ """Rotates half the hidden dims of the input."""
350
+ x1 = x[..., : x.shape[-1] // 2]
351
+ x2 = x[..., x.shape[-1] // 2 :]
352
+ return torch.cat((-x2, x1), dim=-1)
353
+
354
+
355
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
356
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
357
+ """Applies Rotary Position Embedding to the query and key tensors.
358
+ Args:
359
+ q (`torch.Tensor`): The query tensor.
360
+ k (`torch.Tensor`): The key tensor.
361
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
362
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
363
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
364
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
365
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
366
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
367
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
368
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
369
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
370
+ Returns:
371
+ `tuple(torch.Tensor)` comprising the query and key tensors rotated using the Rotary Position Embedding.
372
+ """
373
+ cos = cos.unsqueeze(unsqueeze_dim)
374
+ sin = sin.unsqueeze(unsqueeze_dim)
375
+
376
+ # Keep half or full tensor for later concatenation
377
+ rotary_dim = cos.shape[-1]
378
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
379
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
380
+
381
+ # Apply rotary embeddings on the first half or full tensor
382
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
383
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
384
+
385
+ # Concatenate back to full shape
386
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
387
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
388
+ return q_embed, k_embed
389
+
390
+
391
+ class BailingMoeV3MLP(nn.Module):
392
+ def __init__(
393
+ self,
394
+ config: BailingMoeV3Config,
395
+ intermediate_size: int,
396
+ swiglu_limit: Optional[float] = None,
397
+ ):
398
+ super().__init__()
399
+ self.config = config
400
+ self.hidden_size = config.hidden_size
401
+ self.intermediate_size = intermediate_size
402
+ self.swiglu_limit = swiglu_limit
403
+
404
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
405
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
406
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
407
+ self.act_fn = ACT2FN[config.hidden_act]
408
+
409
+ def forward(self, x):
410
+ gate = self.gate_proj(x)
411
+ up = self.up_proj(x)
412
+ if self.swiglu_limit is None and gate.dtype in (torch.float16, torch.bfloat16):
413
+ # Match fused SiLU/product: round once, after multiplication.
414
+ activated = (self.act_fn(gate.float()) * up.float()).to(gate.dtype)
415
+ return self.down_proj(activated)
416
+ gate = self.act_fn(gate)
417
+ if self.swiglu_limit is not None:
418
+ # The checkpoint clips after SiLU, before multiplication/down projection.
419
+ gate = gate.clamp(max=self.swiglu_limit)
420
+ up = up.clamp(min=-self.swiglu_limit, max=self.swiglu_limit)
421
+ return self.down_proj(gate * up)
422
+
423
+
424
+ class BailingMoeV3Gate(nn.Module):
425
+ def __init__(self, config):
426
+ super().__init__()
427
+ self.config = config
428
+ self.top_k = config.num_experts_per_tok
429
+ self.num_experts = config.num_experts
430
+
431
+ self.n_group = config.n_group
432
+ self.topk_group = config.topk_group
433
+
434
+ # topk selection algorithm
435
+ self.gating_dim = config.hidden_size
436
+ self.weight = nn.Parameter(torch.empty((self.num_experts, self.gating_dim)))
437
+ self.routed_scaling_factor = config.routed_scaling_factor
438
+
439
+ self.register_buffer("expert_bias", torch.zeros((self.num_experts)))
440
+ self.reset_parameters()
441
+
442
+ def reset_parameters(self) -> None:
443
+ import torch.nn.init as init
444
+
445
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
446
+
447
+ def group_limited_topk(
448
+ self,
449
+ scores: torch.Tensor,
450
+ ):
451
+ num_tokens, _ = scores.size()
452
+ # Organize the experts into groups
453
+ group_scores = (
454
+ scores.view(num_tokens, self.n_group, -1).topk(2, dim=-1)[0].sum(dim=-1)
455
+ )
456
+ group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
457
+ group_mask = torch.zeros_like(group_scores)
458
+ group_mask.scatter_(1, group_idx, 1)
459
+
460
+ # Mask the experts based on selection groups
461
+ score_mask = (
462
+ group_mask.unsqueeze(-1)
463
+ .expand(num_tokens, self.n_group, self.num_experts // self.n_group)
464
+ .reshape(num_tokens, -1)
465
+ )
466
+
467
+ masked_scores = scores.masked_fill(~score_mask.bool(), float("-inf"))
468
+ probs, top_indices = torch.topk(masked_scores, k=self.top_k, dim=-1)
469
+
470
+ return probs, top_indices
471
+
472
+ def forward(self, hidden_states):
473
+ # compute gating score
474
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
475
+ logits = F.linear(
476
+ hidden_states.type(torch.float32), self.weight.type(torch.float32)
477
+ )
478
+
479
+ scores = torch.sigmoid(logits.float()).type_as(logits)
480
+
481
+ scores_for_routing = scores + self.expert_bias
482
+ _, topk_idx = self.group_limited_topk(scores_for_routing)
483
+
484
+ scores = torch.gather(scores, dim=1, index=topk_idx).type_as(logits)
485
+
486
+ topk_weight = (
487
+ scores / (scores.sum(dim=-1, keepdim=True) + 1e-20)
488
+ if self.top_k > 1
489
+ else scores
490
+ )
491
+ topk_weight = topk_weight * self.routed_scaling_factor
492
+
493
+ return topk_idx, topk_weight, logits
494
+
495
+
496
+ class BailingMoeV3SparseMoeBlock(nn.Module):
497
+ """
498
+ A mixed expert module containing shared experts.
499
+ """
500
+
501
+ @staticmethod
502
+ def _get_swiglu_limit(limits, layer_idx):
503
+ if limits is None or not 0 <= layer_idx < len(limits):
504
+ return None
505
+ return limits[layer_idx] or None
506
+
507
+ def __init__(self, config: BailingMoeV3Config, layer_idx: int = 0):
508
+ super().__init__()
509
+ self.config = config
510
+ self.num_experts_per_tok = config.num_experts_per_tok
511
+ self.expert_swiglu_limit = self._get_swiglu_limit(
512
+ config.expert_swiglu_limit_list, layer_idx
513
+ )
514
+ self.share_expert_swiglu_limit = self._get_swiglu_limit(
515
+ config.share_expert_swiglu_limit_list, layer_idx
516
+ )
517
+ self._setup_experts()
518
+ self.gate = BailingMoeV3Gate(config)
519
+ if config.num_shared_experts is not None:
520
+ self.shared_experts = BailingMoeV3MLP(
521
+ config=config,
522
+ intermediate_size=config.moe_shared_expert_intermediate_size
523
+ * config.num_shared_experts,
524
+ swiglu_limit=self.share_expert_swiglu_limit,
525
+ )
526
+
527
+ def _setup_experts(self):
528
+ self.experts = nn.ModuleList(
529
+ [
530
+ BailingMoeV3MLP(
531
+ config=self.config,
532
+ intermediate_size=self.config.moe_intermediate_size,
533
+ swiglu_limit=self.expert_swiglu_limit,
534
+ )
535
+ for _ in range(self.config.num_experts)
536
+ ]
537
+ )
538
+
539
+ def forward(self, hidden_states):
540
+ identity = hidden_states
541
+ bsz, seq_len, h = hidden_states.shape
542
+ topk_idx, topk_weight, router_logits = self.gate(hidden_states)
543
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
544
+ flat_topk_idx = topk_idx.view(-1)
545
+ if self.training:
546
+ hidden_states = hidden_states.repeat_interleave(
547
+ self.num_experts_per_tok, dim=0
548
+ )
549
+ y = torch.empty_like(hidden_states)
550
+ for i, expert in enumerate(self.experts):
551
+ y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i])
552
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
553
+ y = y.to(hidden_states.dtype).view(bsz, seq_len, h)
554
+ else:
555
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(
556
+ bsz, seq_len, h
557
+ )
558
+ if self.config.num_shared_experts is not None:
559
+ y = y + self.shared_experts(identity)
560
+ return y, (
561
+ router_logits.view(bsz, seq_len, -1),
562
+ topk_idx.view(bsz, seq_len, -1),
563
+ )
564
+
565
+ @torch.no_grad()
566
+ def moe_infer(self, x, topk_ids, topk_weight):
567
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
568
+ cnts.scatter_(1, topk_ids, 1)
569
+ tokens_per_expert = cnts.sum(dim=0)
570
+ idxs = topk_ids.view(-1).argsort()
571
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
572
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
573
+ outputs = []
574
+ start_idx = 0
575
+ for i, num_tokens in enumerate(tokens_per_expert):
576
+ end_idx = start_idx + num_tokens
577
+ if num_tokens == 0:
578
+ continue
579
+ expert = self.experts[i]
580
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
581
+ expert_out = expert(tokens_for_this_expert)
582
+ outputs.append(expert_out.to(x.device))
583
+ start_idx = end_idx
584
+
585
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
586
+ new_x = torch.empty_like(outs)
587
+ new_x[idxs] = outs
588
+ final_out = (
589
+ new_x.view(*topk_ids.shape, -1)
590
+ .type(topk_weight.dtype)
591
+ .mul_(topk_weight.unsqueeze(dim=-1))
592
+ .sum(dim=1)
593
+ .type(new_x.dtype)
594
+ )
595
+ return final_out
596
+
597
+
598
+ # =============================================================================
599
+ # Text Model Components
600
+ # =============================================================================
601
+
602
+
603
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
604
+ def repeat_kv(
605
+ hidden_states: torch.Tensor, n_rep: int, head_first: bool = True
606
+ ) -> torch.Tensor:
607
+ """
608
+ 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,
609
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
610
+ """
611
+ if n_rep == 1:
612
+ return hidden_states
613
+ if head_first:
614
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
615
+ hidden_states = hidden_states[:, :, None, :, :].expand(
616
+ batch, num_key_value_heads, n_rep, slen, head_dim
617
+ )
618
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
619
+ else:
620
+ batch, slen, num_key_value_heads, head_dim = hidden_states.shape
621
+ hidden_states = hidden_states[:, :, :, None, :].expand(
622
+ batch, slen, num_key_value_heads, n_rep, head_dim
623
+ )
624
+ return hidden_states.reshape(batch, slen, num_key_value_heads * n_rep, head_dim)
625
+
626
+
627
+ def repeat_kv2(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
628
+ """
629
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
630
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
631
+ """
632
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
633
+ if n_rep == 1:
634
+ return hidden_states
635
+ hidden_states = hidden_states[:, :, None, :, :].expand(
636
+ batch, num_key_value_heads, n_rep, slen, head_dim
637
+ )
638
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
639
+
640
+
641
+ def eager_attention_forward(
642
+ module: nn.Module,
643
+ query: torch.Tensor,
644
+ key: torch.Tensor,
645
+ value: torch.Tensor,
646
+ attention_mask: Optional[torch.Tensor],
647
+ scaling: float,
648
+ dropout: float = 0.0,
649
+ **kwargs: Unpack[TransformersKwargs],
650
+ ):
651
+ key_states = repeat_kv2(key, module.num_key_value_groups)
652
+ value_states = repeat_kv2(value, module.num_key_value_groups)
653
+
654
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
655
+ if attention_mask is not None:
656
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
657
+ attn_weights = attn_weights + causal_mask
658
+
659
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(
660
+ query.dtype
661
+ )
662
+ attn_weights = nn.functional.dropout(
663
+ attn_weights, p=dropout, training=module.training
664
+ )
665
+ attn_output = torch.matmul(attn_weights, value_states)
666
+ attn_output = attn_output.transpose(1, 2).contiguous()
667
+
668
+ return attn_output, attn_weights
669
+
670
+
671
+ def apply_rotary_pos_emb_interleave(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
672
+ r"""
673
+ TODO let's just use the original freqcis computation to not have the view
674
+ transpose + reshape! This is not optimized!
675
+ Applies Rotary Position Embedding to the query and key tensors.
676
+
677
+ Args:
678
+ q (`torch.Tensor`): The query tensor.
679
+ k (`torch.Tensor`): The key tensor.
680
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
681
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
682
+ position_ids (`torch.Tensor`):
683
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
684
+ used to pass offsetted position ids when working with a KV-cache.
685
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
686
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
687
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
688
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
689
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
690
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
691
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
692
+ Returns:
693
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
694
+ """
695
+ cos = cos.unsqueeze(unsqueeze_dim)
696
+ sin = sin.unsqueeze(unsqueeze_dim)
697
+
698
+ b, h, s, d = q.shape
699
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
700
+
701
+ b, h, s, d = k.shape
702
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
703
+
704
+ q_embed = (q * cos) + (rotate_half(q) * sin)
705
+ k_embed = (k * cos) + (rotate_half(k) * sin)
706
+ return q_embed, k_embed
707
+
708
+
709
+ def yarn_get_mscale(scale=1, mscale=1):
710
+ if scale <= 1:
711
+ return 1.0
712
+ return 0.1 * mscale * math.log(scale) + 1.0
713
+
714
+
715
+ class BailingMoeV3MultiLatentAttention(nn.Module):
716
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
717
+
718
+ def __init__(self, config: BailingMoeV3Config, layer_idx: int):
719
+ super().__init__()
720
+ self.config = config
721
+ self.layer_idx = layer_idx
722
+ self.num_key_value_groups = (
723
+ config.num_attention_heads // config.num_key_value_heads
724
+ )
725
+ self.attention_dropout = config.attention_dropout
726
+ self.num_heads = config.num_attention_heads
727
+ self.rope_theta = config.rope_theta
728
+ self.q_lora_rank = config.q_lora_rank
729
+ self.qk_rope_head_dim = config.qk_rope_head_dim
730
+ self.kv_lora_rank = config.kv_lora_rank
731
+ self.v_head_dim = config.v_head_dim
732
+ self.qk_nope_head_dim = config.qk_nope_head_dim
733
+ self.qk_head_dim = config.qk_head_dim
734
+ self.gated_attention_proj_granularity_type = (
735
+ config.gated_attention_proj_granularity_type
736
+ )
737
+
738
+ self.is_causal = True
739
+ if self.q_lora_rank is None:
740
+ self.q_proj = nn.Linear(
741
+ config.hidden_size, self.num_heads * self.qk_head_dim, bias=False
742
+ )
743
+ else:
744
+ self.q_a_proj = nn.Linear(
745
+ config.hidden_size, config.q_lora_rank, bias=config.use_qkv_bias
746
+ )
747
+ self.q_a_layernorm = BailingMoeV3RMSNorm(config.q_lora_rank)
748
+ self.q_b_proj = nn.Linear(
749
+ config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False
750
+ )
751
+
752
+ self.kv_a_proj_with_mqa = nn.Linear(
753
+ config.hidden_size,
754
+ self.kv_lora_rank + self.qk_rope_head_dim,
755
+ bias=config.use_qkv_bias,
756
+ )
757
+ self.kv_a_layernorm = BailingMoeV3RMSNorm(self.kv_lora_rank)
758
+ self.kv_b_proj = nn.Linear(
759
+ self.kv_lora_rank,
760
+ self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
761
+ bias=False,
762
+ )
763
+ if self.gated_attention_proj_granularity_type is None:
764
+ self.g_proj = None
765
+ elif self.gated_attention_proj_granularity_type == "head_wise":
766
+ self.g_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False)
767
+ elif self.gated_attention_proj_granularity_type == "element_wise":
768
+ self.g_proj = nn.Linear(
769
+ config.hidden_size, self.num_heads * self.v_head_dim, bias=False
770
+ )
771
+
772
+ self.dense = nn.Linear(
773
+ self.num_heads * self.v_head_dim,
774
+ config.hidden_size,
775
+ bias=config.use_qkv_bias,
776
+ )
777
+
778
+ self.scaling = self.qk_head_dim ** (-0.5)
779
+ if self.config.rope_scaling is not None:
780
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
781
+ scaling_factor = self.config.rope_scaling.get("factor", 1.0)
782
+ if mscale_all_dim:
783
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
784
+ self.scaling = self.scaling * mscale * mscale
785
+
786
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
787
+ def forward(
788
+ self,
789
+ hidden_states: torch.Tensor,
790
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
791
+ attention_mask: Optional[torch.Tensor],
792
+ past_key_values: Optional[Cache] = None,
793
+ cache_position: Optional[torch.LongTensor] = None,
794
+ **kwargs: Unpack[FlashAttentionKwargs],
795
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
796
+
797
+ batch_size, seq_length = hidden_states.shape[:-1]
798
+ query_shape = (batch_size, seq_length, -1, self.qk_head_dim)
799
+ key_shape = (
800
+ batch_size,
801
+ seq_length,
802
+ -1,
803
+ self.qk_nope_head_dim + self.v_head_dim,
804
+ )
805
+
806
+ if self.q_lora_rank is None:
807
+ q_states = self.q_proj(hidden_states)
808
+ else:
809
+ q_states = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
810
+ q_states = q_states.view(query_shape).transpose(1, 2)
811
+ q_pass, q_rot = torch.split(
812
+ q_states, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
813
+ )
814
+
815
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
816
+ k_pass, k_rot = torch.split(
817
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
818
+ )
819
+
820
+ k_pass = (
821
+ self.kv_b_proj(self.kv_a_layernorm(k_pass)).view(key_shape).transpose(1, 2)
822
+ )
823
+ k_pass, value_states = torch.split(
824
+ k_pass, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
825
+ )
826
+
827
+ k_rot = k_rot.view(batch_size, 1, seq_length, self.qk_rope_head_dim)
828
+
829
+ cos, sin = position_embeddings
830
+ if (
831
+ self.config.rope_interleave
832
+ ): # support using interleaved weights for efficiency
833
+ q_rot, k_rot = apply_rotary_pos_emb_interleave(q_rot, k_rot, cos, sin)
834
+ else:
835
+ q_rot, k_rot = apply_rotary_pos_emb(q_rot, k_rot, cos, sin)
836
+ k_rot = k_rot.expand(*k_pass.shape[:-1], -1)
837
+
838
+ query_states = torch.cat((q_pass, q_rot), dim=-1)
839
+ key_states = torch.cat((k_pass, k_rot), dim=-1)
840
+
841
+ if past_key_values is not None:
842
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
843
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
844
+ key_states, value_states = past_key_values.update(
845
+ key_states, value_states, self.layer_idx, cache_kwargs
846
+ )
847
+
848
+ if (
849
+ self.config._attn_implementation == "flash_attention_2"
850
+ and self.qk_head_dim != self.v_head_dim
851
+ ):
852
+ value_states = F.pad(value_states, [0, self.qk_head_dim - self.v_head_dim])
853
+
854
+ if self.config._attn_implementation == "sdpa" and not kwargs.get(
855
+ "output_attentions", False
856
+ ):
857
+ attn_output = (
858
+ F.scaled_dot_product_attention(
859
+ query_states,
860
+ key_states,
861
+ value_states,
862
+ attn_mask=attention_mask,
863
+ dropout_p=self.attention_dropout if self.training else 0.0,
864
+ is_causal=attention_mask is None and seq_length > 1,
865
+ scale=self.scaling,
866
+ )
867
+ .transpose(1, 2)
868
+ .contiguous()
869
+ )
870
+ attn_weights = None
871
+ else:
872
+ attn_output, attn_weights = eager_attention_forward(
873
+ self,
874
+ query_states,
875
+ key_states,
876
+ value_states,
877
+ attention_mask,
878
+ dropout=0.0 if not self.training else self.attention_dropout,
879
+ scaling=self.scaling,
880
+ **kwargs,
881
+ )
882
+
883
+ if (
884
+ self.config._attn_implementation == "flash_attention_2"
885
+ and self.qk_head_dim != self.v_head_dim
886
+ ):
887
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
888
+
889
+ if self.g_proj is not None:
890
+ gate = self.g_proj(hidden_states)
891
+ gate = F.sigmoid(gate.float()).type_as(hidden_states)
892
+ if self.gated_attention_proj_granularity_type == "head_wise":
893
+ attn_output = attn_output * gate[:, :, :, None]
894
+ else:
895
+ attn_output = attn_output * gate.view(
896
+ batch_size, seq_length, self.num_heads, self.v_head_dim
897
+ )
898
+
899
+ attn_output = attn_output.reshape(batch_size, seq_length, -1).contiguous()
900
+ attn_output = self.dense(attn_output)
901
+ return attn_output, attn_weights, past_key_values
902
+
903
+
904
+ class BailingMoeV3KimiDeltaAttention(nn.Module):
905
+ def __init__(self, config: BailingMoeV3Config, layer_idx: int):
906
+ super().__init__()
907
+ self.config = config
908
+ self.mode = "chunk"
909
+
910
+ self.hidden_size = config.hidden_size
911
+ self.conv_size = config.short_conv_kernel_size
912
+ self.head_dim = config.head_dim
913
+ self.num_heads = config.num_attention_heads
914
+ self.head_k_dim = self.head_dim
915
+ self.num_k_heads = self.num_heads
916
+ self.no_kda_lora = config.no_kda_lora
917
+ self.safe_gate = config.kda_safe_gate
918
+ self.lower_bound = config.kda_lower_bound
919
+
920
+ self.layer_idx = layer_idx
921
+
922
+ assert self.mode in ["chunk", "fused_recurrent"], (
923
+ f"Not suppoerted mode `{self.mode}`."
924
+ )
925
+
926
+ projection_k_size = self.head_k_dim * self.num_k_heads
927
+ projection_size = self.head_dim * self.num_heads
928
+
929
+ self.q_proj = nn.Linear(self.hidden_size, projection_k_size, bias=False)
930
+ self.k_proj = nn.Linear(self.hidden_size, projection_k_size, bias=False)
931
+ self.v_proj = nn.Linear(self.hidden_size, projection_size, bias=False)
932
+
933
+ self.q_conv1d = ShortConvolution(
934
+ hidden_size=projection_k_size,
935
+ kernel_size=self.conv_size,
936
+ activation="silu",
937
+ )
938
+ self.k_conv1d = ShortConvolution(
939
+ hidden_size=projection_k_size,
940
+ kernel_size=self.conv_size,
941
+ activation="silu",
942
+ )
943
+ self.v_conv1d = ShortConvolution(
944
+ hidden_size=projection_size,
945
+ kernel_size=self.conv_size,
946
+ activation="silu",
947
+ )
948
+
949
+ self.A_log = torch.nn.Parameter(
950
+ torch.log(torch.empty(self.num_heads, dtype=torch.float32).uniform_(1, 16))
951
+ )
952
+
953
+ if self.no_kda_lora:
954
+ self.f_proj = nn.Linear(self.hidden_size, projection_size, bias=False)
955
+ else:
956
+ self.f_a_proj = nn.Linear(self.hidden_size, self.head_dim, bias=False)
957
+ self.f_b_proj = nn.Linear(self.head_dim, projection_size, bias=False)
958
+
959
+ self.dt_bias = nn.Parameter(torch.empty(projection_size, dtype=torch.float32))
960
+
961
+ self.b_proj = nn.Linear(self.hidden_size, self.num_heads, bias=False)
962
+
963
+ if self.no_kda_lora:
964
+ self.g_proj = nn.Linear(self.hidden_size, projection_size, bias=False)
965
+ else:
966
+ self.g_a_proj = nn.Linear(self.hidden_size, self.head_dim, bias=False)
967
+ self.g_b_proj = nn.Linear(self.head_dim, projection_size, bias=False)
968
+
969
+ self.o_norm = FusedRMSNormGated(
970
+ self.head_dim, eps=config.rms_norm_eps, activation="sigmoid"
971
+ )
972
+ self.o_proj = nn.Linear(projection_size, self.hidden_size, bias=False)
973
+
974
+ def forward(
975
+ self,
976
+ hidden_states: torch.Tensor,
977
+ attention_mask: torch.Tensor | None = None,
978
+ past_key_value=None,
979
+ **kwargs: Unpack[dict],
980
+ ) -> tuple[torch.Tensor, torch.Tensor | None, Cache | None]:
981
+ if attention_mask is not None:
982
+ if attention_mask.dim() != 2:
983
+ attention_mask = kwargs.get("padding_mask")
984
+
985
+ if attention_mask is not None and attention_mask.dim() != 2:
986
+ raise ValueError(
987
+ "attention_mask must be a 0-1 matrix of shape [batch_size, seq_len] "
988
+ "(0 = padding). 3D masks are not supported here.",
989
+ )
990
+ use_cache = past_key_value is not None
991
+ batch_size, q_len, _ = hidden_states.shape
992
+ mode = "fused_recurrent" if q_len <= 64 else self.mode
993
+ if self.training:
994
+ assert mode == "chunk", "Only chunk mode is supported in training."
995
+
996
+ cu_seqlens = kwargs.get("cu_seqlens")
997
+ indices = None
998
+ if attention_mask is not None:
999
+ attention_mask = attention_mask[:, -q_len:]
1000
+ if bool(attention_mask.bool().all()):
1001
+ attention_mask = None
1002
+ if attention_mask is not None:
1003
+ indices, cu_seqlens, _ = _get_unpad_data(attention_mask)
1004
+ hidden_states = index_first_axis(
1005
+ rearrange(hidden_states, "b s ... -> (b s) ..."), indices
1006
+ ).unsqueeze(0)
1007
+
1008
+ conv_state_q, conv_state_k, conv_state_v = None, None, None
1009
+ recurrent_state = None
1010
+
1011
+ if past_key_value is not None and isinstance(past_key_value, Cache):
1012
+ cache_layer = past_key_value.layers[self.layer_idx]
1013
+ if not isinstance(cache_layer, LinearAttentionLayer):
1014
+ raise TypeError(
1015
+ "Ming KDA requires a LinearAttentionLayer; construct DynamicCache(config=model.config)"
1016
+ )
1017
+ if cache_layer.is_recurrent_states_initialized:
1018
+ recurrent_state = cache_layer.recurrent_states.to(
1019
+ hidden_states.device
1020
+ ).contiguous()
1021
+ if cache_layer.is_conv_states_initialized:
1022
+ conv_state_q, conv_state_k, conv_state_v = cache_layer.conv_states.to(
1023
+ hidden_states.device
1024
+ ).unbind(1)
1025
+
1026
+ q, conv_state_q = self.q_conv1d(
1027
+ x=self.q_proj(hidden_states),
1028
+ cache=conv_state_q,
1029
+ output_final_state=use_cache,
1030
+ cu_seqlens=cu_seqlens,
1031
+ )
1032
+ k, conv_state_k = self.k_conv1d(
1033
+ x=self.k_proj(hidden_states),
1034
+ cache=conv_state_k,
1035
+ output_final_state=use_cache,
1036
+ cu_seqlens=cu_seqlens,
1037
+ )
1038
+ v, conv_state_v = self.v_conv1d(
1039
+ x=self.v_proj(hidden_states),
1040
+ cache=conv_state_v,
1041
+ output_final_state=use_cache,
1042
+ cu_seqlens=cu_seqlens,
1043
+ )
1044
+
1045
+ if self.no_kda_lora:
1046
+ g = self.f_proj(hidden_states)
1047
+ else:
1048
+ g = self.f_b_proj(self.f_a_proj(hidden_states))
1049
+
1050
+ beta = self.b_proj(hidden_states).float().sigmoid()
1051
+
1052
+ q, k = map(
1053
+ lambda x: rearrange(x, "... (h d) -> ... h d", d=self.head_k_dim), (q, k)
1054
+ )
1055
+ v = rearrange(v, "... (h d) -> ... h d", d=self.head_dim)
1056
+ g = rearrange(g, "... (h d) -> ... h d", d=self.head_dim)
1057
+
1058
+ if mode == "chunk":
1059
+ o, recurrent_state = chunk_kda(
1060
+ q=q,
1061
+ k=k,
1062
+ v=v,
1063
+ g=g,
1064
+ beta=beta,
1065
+ A_log=self.A_log,
1066
+ dt_bias=self.dt_bias,
1067
+ initial_state=recurrent_state,
1068
+ output_final_state=True,
1069
+ use_qk_l2norm_in_kernel=True,
1070
+ use_gate_in_kernel=True,
1071
+ safe_gate=self.safe_gate,
1072
+ lower_bound=self.lower_bound,
1073
+ cu_seqlens=cu_seqlens,
1074
+ )
1075
+ else:
1076
+ o, recurrent_state = fused_recurrent_kda(
1077
+ q=q,
1078
+ k=k,
1079
+ v=v,
1080
+ g=g,
1081
+ beta=beta,
1082
+ A_log=self.A_log,
1083
+ dt_bias=self.dt_bias,
1084
+ initial_state=recurrent_state,
1085
+ output_final_state=True,
1086
+ use_qk_l2norm_in_kernel=True,
1087
+ use_gate_in_kernel=True,
1088
+ lower_bound=self.lower_bound,
1089
+ cu_seqlens=cu_seqlens,
1090
+ )
1091
+
1092
+ if (
1093
+ use_cache
1094
+ and past_key_value is not None
1095
+ and isinstance(past_key_value, Cache)
1096
+ ):
1097
+ # A tensor stack keeps all three convolution states together during
1098
+ # standard cache beam reordering without pretending they are KV pairs.
1099
+ past_key_value.update_conv_state(
1100
+ torch.stack((conv_state_q, conv_state_k, conv_state_v), dim=1),
1101
+ self.layer_idx,
1102
+ )
1103
+ cache_layer = past_key_value.layers[self.layer_idx]
1104
+ if not cache_layer.is_recurrent_states_initialized:
1105
+ # KDA accumulates in FP32 even when convolution states are BF16.
1106
+ # Preserve that dtype instead of using the convolution buffer dtype.
1107
+ cache_layer.recurrent_states = torch.empty_like(recurrent_state)
1108
+ cache_layer.is_recurrent_states_initialized = True
1109
+ past_key_value.update_recurrent_state(recurrent_state, self.layer_idx)
1110
+
1111
+ if self.no_kda_lora:
1112
+ g = self.g_proj(hidden_states)
1113
+ else:
1114
+ g = self.g_b_proj(self.g_a_proj(hidden_states))
1115
+ g = rearrange(g, "... (h d) -> ... h d", d=self.head_dim)
1116
+ o = self.o_norm(o, g)
1117
+
1118
+ o = rearrange(o, "b t h d -> b t (h d)")
1119
+ o = self.o_proj(o)
1120
+ if attention_mask is not None:
1121
+ o = pad_input(o.squeeze(0), indices, batch_size, q_len)
1122
+
1123
+ return o, None, past_key_value
1124
+
1125
+
1126
+ class BailingMoeV3MTPLayer(nn.Module):
1127
+ def __init__(self, config: BailingMoeV3Config, layer_idx: int):
1128
+ super().__init__()
1129
+ self.layer_idx = layer_idx
1130
+ self.input_layernorm = BailingMoeV3RMSNorm(
1131
+ config.hidden_size, eps=config.rms_norm_eps
1132
+ )
1133
+ self.enorm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1134
+
1135
+ self.eh_proj = nn.Linear(config.hidden_size * 2, config.hidden_size, bias=False)
1136
+ self.post_attention_layernorm = BailingMoeV3RMSNorm(
1137
+ config.hidden_size, eps=config.rms_norm_eps
1138
+ )
1139
+ self.attention = BailingMoeV3MultiLatentAttention(
1140
+ config=config, layer_idx=layer_idx
1141
+ )
1142
+ self.mlp = BailingMoeV3SparseMoeBlock(config, layer_idx=layer_idx)
1143
+
1144
+ self.hnorm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1145
+ self.final_layernorm = BailingMoeV3RMSNorm(
1146
+ config.hidden_size, eps=config.rms_norm_eps
1147
+ )
1148
+
1149
+ def forward(
1150
+ self,
1151
+ input_embeds,
1152
+ hidden_states: torch.Tensor,
1153
+ attention_mask: Optional[torch.Tensor] = None,
1154
+ position_ids: Optional[torch.LongTensor] = None,
1155
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1156
+ output_attentions: Optional[bool] = False,
1157
+ output_router_logits: Optional[bool] = False,
1158
+ use_cache: Optional[bool] = False,
1159
+ position_embeddings: Optional[
1160
+ Tuple[torch.Tensor, torch.Tensor]
1161
+ ] = None, # necessary, but kept here for BC
1162
+ **kwargs,
1163
+ ) -> Tuple[
1164
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1165
+ ]:
1166
+ input_embeds = self.enorm(input_embeds)
1167
+ hidden_states = self.hnorm(hidden_states)
1168
+ hidden_states = self.eh_proj(torch.cat([input_embeds, hidden_states], dim=-1))
1169
+ residual = hidden_states
1170
+
1171
+ hidden_states = self.input_layernorm(hidden_states)
1172
+
1173
+ # Self Attention
1174
+ hidden_states, self_attn_weights, present_key_value = self.attention(
1175
+ hidden_states=hidden_states,
1176
+ attention_mask=attention_mask,
1177
+ position_ids=position_ids,
1178
+ past_key_value=past_key_value,
1179
+ output_attentions=output_attentions,
1180
+ position_embeddings=position_embeddings,
1181
+ use_cache=use_cache,
1182
+ )
1183
+ hidden_states = residual + hidden_states
1184
+
1185
+ # Fully Connected
1186
+ residual = hidden_states
1187
+ hidden_states = self.post_attention_layernorm(hidden_states)
1188
+ hidden_states = self.mlp(hidden_states)
1189
+ if isinstance(hidden_states, tuple):
1190
+ hidden_states, router_logits = hidden_states
1191
+ else:
1192
+ router_logits = None
1193
+ hidden_states = residual + hidden_states.to(residual.device)
1194
+ hidden_states = self.final_layernorm(hidden_states)
1195
+
1196
+ outputs = (hidden_states,)
1197
+
1198
+ if output_attentions:
1199
+ outputs += (self_attn_weights,)
1200
+
1201
+ if use_cache:
1202
+ outputs += (present_key_value,)
1203
+
1204
+ if output_router_logits:
1205
+ outputs += (router_logits,)
1206
+
1207
+ return outputs
1208
+
1209
+
1210
+ class BailingMoeV3DecoderLayer(nn.Module):
1211
+ def __init__(self, config: BailingMoeV3Config, layer_idx: int):
1212
+ super().__init__()
1213
+ self.hidden_size = config.hidden_size
1214
+ self.layer_idx = layer_idx
1215
+ self.attention_layer_type = (
1216
+ "attention"
1217
+ if (layer_idx + 1) % config.layer_group_size == 0
1218
+ or layer_idx
1219
+ >= config.num_hidden_layers
1220
+ // config.layer_group_size
1221
+ * config.layer_group_size
1222
+ else "linear_attention"
1223
+ )
1224
+
1225
+ if self.attention_layer_type == "attention":
1226
+ self.attention = BailingMoeV3MultiLatentAttention(
1227
+ config=config, layer_idx=layer_idx
1228
+ )
1229
+ else:
1230
+ self.attention = BailingMoeV3KimiDeltaAttention(
1231
+ config=config, layer_idx=layer_idx
1232
+ )
1233
+
1234
+ self.mlp = (
1235
+ BailingMoeV3SparseMoeBlock(config, layer_idx=layer_idx)
1236
+ if (
1237
+ config.num_experts is not None
1238
+ and layer_idx >= config.first_k_dense_replace
1239
+ )
1240
+ else BailingMoeV3MLP(
1241
+ config=config, intermediate_size=config.intermediate_size
1242
+ )
1243
+ )
1244
+ self.input_layernorm = BailingMoeV3RMSNorm(
1245
+ config.hidden_size, eps=config.rms_norm_eps
1246
+ )
1247
+ self.post_attention_layernorm = BailingMoeV3RMSNorm(
1248
+ config.hidden_size, eps=config.rms_norm_eps
1249
+ )
1250
+
1251
+ def forward(
1252
+ self,
1253
+ hidden_states: torch.Tensor,
1254
+ attention_mask: Optional[torch.Tensor] = None,
1255
+ position_ids: Optional[torch.LongTensor] = None,
1256
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1257
+ cache_position: Optional[torch.LongTensor] = None,
1258
+ output_attentions: Optional[bool] = False,
1259
+ output_router_logits: Optional[bool] = False,
1260
+ use_cache: Optional[bool] = False,
1261
+ position_embeddings: Optional[
1262
+ Tuple[torch.Tensor, torch.Tensor]
1263
+ ] = None, # necessary, but kept here for BC
1264
+ padding_mask: Optional[torch.Tensor] = None,
1265
+ **kwargs,
1266
+ ) -> Tuple[
1267
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1268
+ ]:
1269
+ """
1270
+ Args:
1271
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1272
+ attention_mask (`torch.FloatTensor`, *optional*):
1273
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1274
+ query_sequence_length, key_sequence_length)` if default attention is used.
1275
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1276
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1277
+ config.n_positions - 1]`.
1278
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*):
1279
+ cached past key and value projection states
1280
+ output_attentions (`bool`, *optional*):
1281
+ Whether to return the attentions tensors of all attention layers. See `attentions` under
1282
+ returned tensors for more detail.
1283
+ output_router_logits (`bool`, *optional*):
1284
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
1285
+ and should not be returned during inference.
1286
+ use_cache (`bool`, *optional*):
1287
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1288
+ (see `past_key_values`).
1289
+ """
1290
+ residual = hidden_states
1291
+
1292
+ hidden_states = self.input_layernorm(hidden_states)
1293
+
1294
+ # Self Attention
1295
+ if self.attention_layer_type == "attention":
1296
+ hidden_states, self_attn_weights, present_key_value = self.attention(
1297
+ hidden_states=hidden_states,
1298
+ attention_mask=attention_mask,
1299
+ position_ids=position_ids,
1300
+ past_key_values=past_key_value,
1301
+ output_attentions=output_attentions,
1302
+ use_cache=use_cache,
1303
+ cache_position=cache_position, #
1304
+ position_embeddings=position_embeddings, #
1305
+ **kwargs,
1306
+ )
1307
+ else:
1308
+ hidden_states, self_attn_weights, present_key_value = self.attention(
1309
+ hidden_states=hidden_states,
1310
+ attention_mask=padding_mask,
1311
+ past_key_value=past_key_value,
1312
+ position_ids=position_ids,
1313
+ use_cache=use_cache,
1314
+ output_attentions=output_attentions,
1315
+ )
1316
+
1317
+ hidden_states = residual + hidden_states
1318
+
1319
+ # Fully Connected
1320
+ residual = hidden_states
1321
+ hidden_states = self.post_attention_layernorm(hidden_states)
1322
+ hidden_states = self.mlp(hidden_states)
1323
+ if isinstance(hidden_states, tuple):
1324
+ hidden_states, router_logits = hidden_states
1325
+ else:
1326
+ router_logits = None
1327
+ hidden_states = residual + hidden_states.to(residual.device)
1328
+
1329
+ outputs = (hidden_states,)
1330
+
1331
+ if output_attentions:
1332
+ outputs += (self_attn_weights,)
1333
+
1334
+ if use_cache:
1335
+ outputs += (present_key_value,)
1336
+
1337
+ if output_router_logits:
1338
+ outputs += (router_logits,)
1339
+
1340
+ return outputs
1341
+
1342
+
1343
+ BAILINGMOEV3_START_DOCSTRING = r"""
1344
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1345
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1346
+ etc.)
1347
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1348
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1349
+ and behavior.
1350
+ Parameters:
1351
+ config ([`BailingMoeV3Config`]):
1352
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1353
+ load the weights associated with the model, only the configuration. Check out the
1354
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1355
+ """
1356
+
1357
+
1358
+ @dataclass
1359
+ class MingV3ASRModelOutputWithPast(ModelOutput):
1360
+ last_hidden_state: Optional[torch.FloatTensor] = None
1361
+ past_key_values: Optional[Cache] = None
1362
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
1363
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
1364
+ router_logits: Optional[tuple[torch.FloatTensor]] = None
1365
+
1366
+
1367
+ @dataclass
1368
+ class MingV3ASRCausalLMOutputWithPast(ModelOutput):
1369
+ loss: Optional[torch.FloatTensor] = None
1370
+ logits: Optional[torch.FloatTensor] = None
1371
+ past_key_values: Optional[Cache] = None
1372
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
1373
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
1374
+ router_logits: Optional[tuple[torch.FloatTensor]] = None
1375
+ aux_loss: Optional[torch.FloatTensor] = None
1376
+
1377
+
1378
+ @add_start_docstrings(
1379
+ "The bare BailingMoeV3 VL Model outputting raw hidden-states without any specific head on top.",
1380
+ BAILINGMOEV3_START_DOCSTRING,
1381
+ )
1382
+ class BailingMoeV3PreTrainedModel(PreTrainedModel):
1383
+ config_class = MingV3ASRConfig
1384
+ base_model_prefix = "model"
1385
+ # Routing corrections are saved in FP32. Rounding this small buffer can
1386
+ # change selected experts, even when the rest of the model uses BF16.
1387
+ _keep_in_fp32_modules_strict = ["expert_bias"]
1388
+ supports_gradient_checkpointing = True
1389
+ _no_split_modules = ["BailingMoeV3DecoderLayer"]
1390
+ _skip_keys_device_placement = "past_key_values"
1391
+ _supports_flash_attn_2 = False
1392
+ _supports_flash_attn = False
1393
+ _supports_sdpa = True
1394
+ _supports_cache_class = True
1395
+
1396
+ def _init_weights(self, module):
1397
+ if hasattr(self.config, "initializer_range"):
1398
+ std = self.config.initializer_range
1399
+ else:
1400
+ std = getattr(self.config.get_text_config(), "initializer_range", 0.02)
1401
+ if isinstance(module, BailingMoeV3RotaryEmbedding):
1402
+ # Nonpersistent buffers are absent from checkpoints. HF's meta-device
1403
+ # loader materializes them before initialization, so rebuild frequencies
1404
+ # here as well as in __init__ rather than retaining empty storage.
1405
+ inv_freq, module.attention_scaling = module.rope_init_fn(
1406
+ module.config, module.inv_freq.device
1407
+ )
1408
+ module.inv_freq.copy_(inv_freq)
1409
+ module.original_inv_freq.copy_(inv_freq)
1410
+ elif isinstance(module, BailingMoeV3KimiDeltaAttention):
1411
+ # Match FLA KDA's log-uniform time steps and inverse-softplus bias.
1412
+ # HF also calls this hook after materializing missing checkpoint
1413
+ # parameters; preserve a dt_bias that was actually loaded.
1414
+ if not getattr(module.dt_bias, "_is_hf_initialized", False):
1415
+ dt = torch.exp(
1416
+ torch.rand_like(module.dt_bias, dtype=torch.float32)
1417
+ * (math.log(0.1) - math.log(0.001))
1418
+ + math.log(0.001)
1419
+ ).clamp(min=1e-4)
1420
+ with torch.no_grad():
1421
+ module.dt_bias.copy_(dt + torch.log(-torch.expm1(-dt)))
1422
+ elif isinstance(module, nn.Linear):
1423
+ if not getattr(module.weight, "_is_hf_initialized", False):
1424
+ module.weight.data.normal_(mean=0.0, std=std)
1425
+ if module.bias is not None and not getattr(
1426
+ module.bias, "_is_hf_initialized", False
1427
+ ):
1428
+ module.bias.data.zero_()
1429
+ elif isinstance(module, nn.Embedding):
1430
+ if not getattr(module.weight, "_is_hf_initialized", False):
1431
+ module.weight.data.normal_(mean=0.0, std=std)
1432
+ if module.padding_idx is not None:
1433
+ module.weight.data[module.padding_idx].zero_()
1434
+
1435
+
1436
+ BAILINGMOEV3_INPUTS_DOCSTRING = r"""
1437
+ Args:
1438
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1439
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1440
+ it.
1441
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1442
+ [`PreTrainedTokenizer.__call__`] for details.
1443
+ [What are input IDs?](../glossary#input-ids)
1444
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1445
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1446
+ - 1 for tokens that are **not masked**,
1447
+ - 0 for tokens that are **masked**.
1448
+ [What are attention masks?](../glossary#attention-mask)
1449
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1450
+ [`PreTrainedTokenizer.__call__`] for details.
1451
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1452
+ `past_key_values`).
1453
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1454
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1455
+ information on the default strategy.
1456
+ - 1 indicates the head is **not masked**,
1457
+ - 0 indicates the head is **masked**.
1458
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1459
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1460
+ config.n_positions - 1]`.
1461
+ [What are position IDs?](../glossary#position-ids)
1462
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1463
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1464
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1465
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1466
+ Two formats are allowed:
1467
+ - a [`~cache_utils.Cache`] instance;
1468
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1469
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1470
+ cache format.
1471
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1472
+ legacy cache format will be returned.
1473
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1474
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1475
+ of shape `(batch_size, sequence_length)`.
1476
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1477
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1478
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1479
+ model's internal embedding lookup matrix.
1480
+ use_cache (`bool`, *optional*):
1481
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1482
+ `past_key_values`).
1483
+ output_attentions (`bool`, *optional*):
1484
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1485
+ tensors for more detail.
1486
+ output_hidden_states (`bool`, *optional*):
1487
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1488
+ more detail.
1489
+ return_dict (`bool`, *optional*):
1490
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1491
+ """
1492
+
1493
+
1494
+ @add_start_docstrings(
1495
+ "The bare BailingMoeV3 Model outputting raw hidden-states without any specific head on top.",
1496
+ BAILINGMOEV3_START_DOCSTRING,
1497
+ )
1498
+ class BailingMoeV3Model(BailingMoeV3PreTrainedModel):
1499
+ """
1500
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`BailingMoeV3DecoderLayer`]
1501
+ Args:
1502
+ config: BailingMoeV3Config
1503
+ """
1504
+
1505
+ def __init__(self, config: BailingMoeV3Config):
1506
+ super().__init__(config)
1507
+ self.padding_idx = config.pad_token_id
1508
+ self.vocab_size = config.vocab_size
1509
+ self.num_nextn_predict_layers = config.num_nextn_predict_layers
1510
+
1511
+ self.word_embeddings = nn.Embedding(
1512
+ config.vocab_size, config.hidden_size, self.padding_idx
1513
+ )
1514
+ layers = []
1515
+ for layer_idx in range(
1516
+ config.num_hidden_layers + config.num_nextn_predict_layers
1517
+ ):
1518
+ layer_cls = (
1519
+ BailingMoeV3DecoderLayer
1520
+ if layer_idx < config.num_hidden_layers
1521
+ else BailingMoeV3MTPLayer
1522
+ )
1523
+ layers.append(layer_cls(config, layer_idx))
1524
+ self.layers = nn.ModuleList(layers)
1525
+
1526
+ self._use_sdpa = config._attn_implementation == "sdpa"
1527
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1528
+ self.norm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1529
+ self.rotary_emb = BailingMoeV3RotaryEmbedding(config=config)
1530
+ self.gradient_checkpointing = False
1531
+ # Initialize weights and apply final processing
1532
+ self.post_init()
1533
+
1534
+ def get_input_embeddings(self):
1535
+ return self.word_embeddings
1536
+
1537
+ def set_input_embeddings(self, value):
1538
+ self.word_embeddings = value
1539
+
1540
+ @add_start_docstrings_to_model_forward(BAILINGMOEV3_INPUTS_DOCSTRING)
1541
+ def forward(
1542
+ self,
1543
+ input_ids: torch.LongTensor = None,
1544
+ attention_mask: Optional[torch.Tensor] = None,
1545
+ position_ids: Optional[torch.LongTensor] = None,
1546
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1547
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1548
+ cache_position: Optional[torch.LongTensor] = None,
1549
+ use_cache: Optional[bool] = None,
1550
+ output_attentions: Optional[bool] = None,
1551
+ output_hidden_states: Optional[bool] = None,
1552
+ output_router_logits: Optional[bool] = None,
1553
+ return_dict: Optional[bool] = None,
1554
+ **kwargs,
1555
+ ) -> Union[Tuple, MoeModelOutputWithPast]:
1556
+ output_attentions = (
1557
+ output_attentions
1558
+ if output_attentions is not None
1559
+ else self.config.output_attentions
1560
+ )
1561
+ output_hidden_states = (
1562
+ output_hidden_states
1563
+ if output_hidden_states is not None
1564
+ else self.config.output_hidden_states
1565
+ )
1566
+ output_router_logits = (
1567
+ output_router_logits
1568
+ if output_router_logits is not None
1569
+ else self.config.output_router_logits
1570
+ )
1571
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1572
+
1573
+ return_dict = (
1574
+ return_dict if return_dict is not None else self.config.use_return_dict
1575
+ )
1576
+
1577
+ # retrieve input_ids and inputs_embeds
1578
+ if input_ids is not None and inputs_embeds is not None:
1579
+ raise ValueError(
1580
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1581
+ )
1582
+ elif input_ids is not None:
1583
+ batch_size, seq_length = input_ids.shape[:2]
1584
+ elif inputs_embeds is not None:
1585
+ batch_size, seq_length = inputs_embeds.shape[:2]
1586
+ else:
1587
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1588
+
1589
+ if self.gradient_checkpointing and self.training:
1590
+ if use_cache:
1591
+ logger.warning_once(
1592
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
1593
+ )
1594
+ use_cache = False
1595
+
1596
+ if use_cache and past_key_values is None:
1597
+ past_key_values = DynamicCache(config=self.config)
1598
+
1599
+ if inputs_embeds is None:
1600
+ inputs_embeds = self.word_embeddings(input_ids)
1601
+
1602
+ if cache_position is None:
1603
+ past_seen_tokens = (
1604
+ past_key_values.get_seq_length() if past_key_values is not None else 0
1605
+ )
1606
+ cache_position = torch.arange(
1607
+ past_seen_tokens,
1608
+ past_seen_tokens + inputs_embeds.shape[1],
1609
+ device=inputs_embeds.device,
1610
+ )
1611
+
1612
+ if position_ids is None:
1613
+ position_ids = cache_position.unsqueeze(0)
1614
+ if position_ids.ndim != 2:
1615
+ raise ValueError(
1616
+ "Audio/text position_ids must have shape [batch, sequence]"
1617
+ )
1618
+
1619
+ past_seen_tokens = (
1620
+ past_key_values.get_seq_length() if past_key_values is not None else 0
1621
+ )
1622
+
1623
+ # Preserve padding independently of backend-specific causal mask transformations.
1624
+ padding_mask = (
1625
+ attention_mask
1626
+ if attention_mask is not None and attention_mask.ndim == 2
1627
+ else None
1628
+ )
1629
+
1630
+ if self._use_flash_attention_2:
1631
+ # 2d mask is passed through the layers
1632
+ attention_mask = (
1633
+ attention_mask
1634
+ if (attention_mask is not None and 0 in attention_mask)
1635
+ else None
1636
+ )
1637
+ elif self._use_sdpa and not output_attentions:
1638
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1639
+ attention_mask,
1640
+ (batch_size, seq_length),
1641
+ inputs_embeds,
1642
+ past_seen_tokens,
1643
+ )
1644
+ else:
1645
+ # 4d mask is passed through the layers
1646
+ attention_mask = _prepare_4d_causal_attention_mask(
1647
+ attention_mask,
1648
+ (batch_size, seq_length),
1649
+ inputs_embeds,
1650
+ past_seen_tokens,
1651
+ )
1652
+
1653
+ # embed positions
1654
+ hidden_states = inputs_embeds
1655
+
1656
+ # create position embeddings to be shared across the decoder layers
1657
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
1658
+
1659
+ # decoder layers
1660
+ all_hidden_states = () if output_hidden_states else None
1661
+ all_self_attns = () if output_attentions else None
1662
+ all_router_logits = () if output_router_logits else None
1663
+ next_decoder_cache = None
1664
+
1665
+ # Split main decoder layers and MTP layers
1666
+ main_layers = (
1667
+ self.layers[: -self.num_nextn_predict_layers]
1668
+ if self.num_nextn_predict_layers > 0
1669
+ else self.layers
1670
+ )
1671
+ mtp_layers = (
1672
+ self.layers[-self.num_nextn_predict_layers :]
1673
+ if self.num_nextn_predict_layers > 0
1674
+ else None
1675
+ )
1676
+
1677
+ for decoder_layer in main_layers:
1678
+ if output_hidden_states:
1679
+ all_hidden_states += (hidden_states,)
1680
+
1681
+ if self.gradient_checkpointing and self.training:
1682
+ layer_outputs = self._gradient_checkpointing_func(
1683
+ decoder_layer.__call__,
1684
+ hidden_states,
1685
+ attention_mask,
1686
+ position_ids,
1687
+ past_key_values,
1688
+ cache_position,
1689
+ output_attentions,
1690
+ output_router_logits,
1691
+ use_cache,
1692
+ position_embeddings,
1693
+ padding_mask,
1694
+ )
1695
+ else:
1696
+ layer_outputs = decoder_layer(
1697
+ hidden_states,
1698
+ attention_mask=attention_mask,
1699
+ position_ids=position_ids,
1700
+ past_key_value=past_key_values,
1701
+ cache_position=cache_position,
1702
+ output_attentions=output_attentions,
1703
+ output_router_logits=output_router_logits,
1704
+ use_cache=use_cache,
1705
+ position_embeddings=position_embeddings,
1706
+ padding_mask=padding_mask,
1707
+ )
1708
+ hidden_states = layer_outputs[0]
1709
+
1710
+ if use_cache:
1711
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1712
+
1713
+ if output_attentions:
1714
+ all_self_attns += (layer_outputs[1],)
1715
+
1716
+ if output_router_logits and layer_outputs[-1] is not None:
1717
+ all_router_logits += (layer_outputs[-1],)
1718
+
1719
+ hidden_states = self.norm(hidden_states)
1720
+ main_hidden_states = hidden_states
1721
+
1722
+ # add hidden states from the last decoder layer
1723
+ if output_hidden_states:
1724
+ all_hidden_states += (main_hidden_states,)
1725
+
1726
+ # MTP layers (training only)
1727
+ if mtp_layers and self.training:
1728
+ for decoder_layer in mtp_layers:
1729
+ input_ids, _ = roll_tensor(input_ids, shifts=-1, dims=-1)
1730
+ mtp_inputs_embeds = self.word_embeddings(input_ids)
1731
+
1732
+ if self.gradient_checkpointing and self.training:
1733
+ layer_outputs = self._gradient_checkpointing_func(
1734
+ decoder_layer.__call__,
1735
+ mtp_inputs_embeds,
1736
+ hidden_states,
1737
+ attention_mask,
1738
+ position_ids,
1739
+ past_key_values,
1740
+ output_attentions,
1741
+ output_router_logits,
1742
+ use_cache,
1743
+ position_embeddings,
1744
+ )
1745
+ else:
1746
+ layer_outputs = decoder_layer(
1747
+ mtp_inputs_embeds,
1748
+ hidden_states,
1749
+ attention_mask=attention_mask,
1750
+ position_ids=position_ids,
1751
+ past_key_value=past_key_values,
1752
+ output_attentions=output_attentions,
1753
+ output_router_logits=output_router_logits,
1754
+ use_cache=use_cache,
1755
+ position_embeddings=position_embeddings,
1756
+ )
1757
+ hidden_states = layer_outputs[0]
1758
+
1759
+ if output_hidden_states:
1760
+ all_hidden_states += (hidden_states,)
1761
+
1762
+ if use_cache:
1763
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1764
+
1765
+ if output_attentions:
1766
+ all_self_attns += (layer_outputs[1],)
1767
+
1768
+ if output_router_logits and layer_outputs[-1] is not None:
1769
+ all_router_logits += (layer_outputs[-1],)
1770
+
1771
+ next_cache = None
1772
+ if use_cache:
1773
+ next_cache = next_decoder_cache
1774
+ if not return_dict:
1775
+ return tuple(
1776
+ v
1777
+ for v in [
1778
+ main_hidden_states,
1779
+ next_cache,
1780
+ all_hidden_states,
1781
+ all_self_attns,
1782
+ all_router_logits,
1783
+ ]
1784
+ if v is not None
1785
+ )
1786
+ return MoeModelOutputWithPast(
1787
+ last_hidden_state=main_hidden_states,
1788
+ past_key_values=next_cache,
1789
+ hidden_states=all_hidden_states,
1790
+ attentions=all_self_attns,
1791
+ router_logits=all_router_logits,
1792
+ )
1793
+
1794
+
1795
+ # =============================================================================
1796
+ # Composite Audio Model
1797
+ # =============================================================================
1798
+
1799
+
1800
+ class MingV3ASRModel(BailingMoeV3Model):
1801
+ """Ming Audio V3 encoder and text decoder with stable checkpoint keys.
1802
+
1803
+ Inherits from BailingMoeV3Model so that LLM sub-modules (word_embeddings,
1804
+ layers, norm, rotary_emb) live directly on ``self``, matching the checkpoint
1805
+ key namespace (``model.layers.*`` etc.) produced by the conversion script.
1806
+ """
1807
+
1808
+ def __init__(self, config: MingV3ASRConfig):
1809
+ # Initialise LLM backbone with text_config
1810
+ # self.config remains text_config so BailingMoeV3Model.forward works correctly
1811
+ super().__init__(config.text_config)
1812
+ # Keep the composite audio configuration alongside the language config.
1813
+ self._audio_model_config = config
1814
+ # Audio encoder
1815
+ self.audio = build_audio_encoder(config.audio_config)
1816
+
1817
+ def get_audio_features(self, audio_feats, audio_feats_lengths, projector):
1818
+ """Return valid audio embeddings in clip order, with no batch padding."""
1819
+ lengths = _audio_clip_lengths(audio_feats, audio_feats_lengths)
1820
+ clips = [features[:length] for features, length in zip(audio_feats, lengths)]
1821
+ return encode_audio_clips(
1822
+ clips, self.audio, projector, self._audio_model_config.audio_config
1823
+ )
1824
+
1825
+ def get_audio_placeholder_mask(self, input_ids, inputs_embeds):
1826
+ if input_ids is None:
1827
+ marker = self.get_input_embeddings()(
1828
+ torch.tensor(
1829
+ self._audio_model_config.audio_token_id,
1830
+ dtype=torch.long,
1831
+ device=inputs_embeds.device,
1832
+ )
1833
+ )
1834
+ mask = (inputs_embeds == marker).all(-1)
1835
+ else:
1836
+ mask = input_ids == self._audio_model_config.audio_token_id
1837
+ return mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
1838
+
1839
+ def forward(
1840
+ self,
1841
+ input_ids: torch.LongTensor = None,
1842
+ attention_mask: Optional[torch.Tensor] = None,
1843
+ position_ids: Optional[torch.LongTensor] = None,
1844
+ past_key_values: Optional[Cache] = None,
1845
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1846
+ audio_feats: Optional[torch.FloatTensor] = None,
1847
+ audio_feats_lengths: Optional[torch.LongTensor] = None,
1848
+ audio_num_clips: Optional[torch.LongTensor] = None,
1849
+ mm_token_type_ids: Optional[torch.IntTensor] = None,
1850
+ projector_audio: Optional[nn.Module] = None,
1851
+ **kwargs,
1852
+ ) -> Union[Tuple, MingV3ASRModelOutputWithPast]:
1853
+ if (input_ids is None) ^ (inputs_embeds is not None):
1854
+ raise ValueError(
1855
+ "You must specify exactly one of input_ids or inputs_embeds"
1856
+ )
1857
+
1858
+ if inputs_embeds is None:
1859
+ inputs_embeds = self.get_input_embeddings()(input_ids)
1860
+
1861
+ _reject_visual_inputs(kwargs)
1862
+ if mm_token_type_ids is not None and not torch.all(
1863
+ (mm_token_type_ids == 0) | (mm_token_type_ids == 3)
1864
+ ):
1865
+ raise ValueError("Ming supports only text/audio token types")
1866
+
1867
+ # Process audio
1868
+ if audio_feats is not None:
1869
+ lengths = _audio_clip_lengths(audio_feats, audio_feats_lengths)
1870
+ counts = _audio_request_counts(
1871
+ audio_num_clips, inputs_embeds.shape[0], len(lengths)
1872
+ )
1873
+ spec = MingAudioSpec.from_config(self._audio_model_config.audio_config)
1874
+ token_counts = [spec.token_count(length) for length in lengths]
1875
+ audio_mask = self.get_audio_placeholder_mask(input_ids, inputs_embeds)
1876
+ clip_index = 0
1877
+ for index, count in enumerate(counts):
1878
+ expected = sum(token_counts[clip_index : clip_index + count])
1879
+ actual = int(audio_mask[index, :, 0].sum())
1880
+ if actual != expected:
1881
+ raise ValueError(
1882
+ f"Audio placeholder count for request {index} is {actual}, expected {expected}"
1883
+ )
1884
+ clip_index += count
1885
+ audio_embeds = self.get_audio_features(
1886
+ audio_feats, audio_feats_lengths, projector=projector_audio
1887
+ )
1888
+ audio_embeds_cvt = audio_embeds.to(
1889
+ inputs_embeds.device, inputs_embeds.dtype
1890
+ )
1891
+ inputs_embeds = inputs_embeds.masked_scatter(audio_mask, audio_embeds_cvt)
1892
+ elif audio_feats_lengths is not None or audio_num_clips is not None:
1893
+ raise ValueError("Audio lengths and clip counts require audio_feats")
1894
+ # Raw lengths are the model's mask contract; optional frontend masks do
1895
+ # not belong to the language decoder's attention arguments.
1896
+ kwargs.pop("audio_attention_mask", None)
1897
+
1898
+ if (
1899
+ position_ids is None
1900
+ and attention_mask is not None
1901
+ and attention_mask.ndim == 2
1902
+ ):
1903
+ position_ids = attention_mask.long().cumsum(-1) - 1
1904
+ position_ids.masked_fill_(attention_mask == 0, 0)
1905
+ position_ids = position_ids[:, -inputs_embeds.shape[1] :]
1906
+
1907
+ return_dict = kwargs.pop("return_dict", None)
1908
+ if return_dict is None:
1909
+ return_dict = self.config.use_return_dict
1910
+ outputs = super().forward(
1911
+ input_ids=None,
1912
+ position_ids=position_ids,
1913
+ attention_mask=attention_mask,
1914
+ past_key_values=past_key_values,
1915
+ inputs_embeds=inputs_embeds,
1916
+ return_dict=True,
1917
+ **kwargs,
1918
+ )
1919
+
1920
+ result = MingV3ASRModelOutputWithPast(
1921
+ last_hidden_state=outputs.last_hidden_state,
1922
+ past_key_values=outputs.past_key_values,
1923
+ hidden_states=outputs.hidden_states,
1924
+ attentions=outputs.attentions,
1925
+ router_logits=outputs.router_logits,
1926
+ )
1927
+ return result if return_dict else result.to_tuple()
1928
+
1929
+
1930
+ class MingV3ASRForConditionalGeneration(
1931
+ BailingMoeV3PreTrainedModel, GenerationMixin
1932
+ ):
1933
+ _tied_weights_keys = {"lm_head.weight": "model.word_embeddings.weight"}
1934
+ # Legacy mixed checkpoints may contain unused vision tensors. Only these
1935
+ # explicit namespaces are excluded; audio/LM loading diagnostics stay strict.
1936
+ _keys_to_ignore_on_load_unexpected = [r"^model\.visual\.", r"^linear_proj\."]
1937
+ accepts_loss_kwargs = False
1938
+
1939
+ def __init__(self, config: MingV3ASRConfig, **kwargs):
1940
+ super().__init__(config, **kwargs)
1941
+ self.model = MingV3ASRModel(config)
1942
+
1943
+ # Keep checkpoint-configured projector indices (Tiny: 0, 3).
1944
+ self.linear_proj_audio = build_audio_projector(
1945
+ config.audio_config, config.text_config.hidden_size, config.mlp_depth
1946
+ )
1947
+
1948
+ self.lm_head = nn.Linear(
1949
+ config.text_config.hidden_size, config.text_config.vocab_size, bias=False
1950
+ )
1951
+
1952
+ self.post_init()
1953
+
1954
+ def get_input_embeddings(self):
1955
+ return self.model.get_input_embeddings()
1956
+
1957
+ def set_input_embeddings(self, value):
1958
+ self.model.set_input_embeddings(value)
1959
+
1960
+ def get_output_embeddings(self):
1961
+ return self.lm_head
1962
+
1963
+ def set_output_embeddings(self, new_embeddings):
1964
+ self.lm_head = new_embeddings
1965
+
1966
+ def get_audio_features(self, audio_feats, audio_feats_lengths, **kwargs):
1967
+ return self.model.get_audio_features(
1968
+ audio_feats=audio_feats,
1969
+ audio_feats_lengths=audio_feats_lengths,
1970
+ projector=self.linear_proj_audio,
1971
+ **kwargs,
1972
+ )
1973
+
1974
+ def forward(
1975
+ self,
1976
+ input_ids: torch.LongTensor = None,
1977
+ attention_mask: Optional[torch.Tensor] = None,
1978
+ position_ids: Optional[torch.LongTensor] = None,
1979
+ past_key_values: Optional[Cache] = None,
1980
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1981
+ labels: Optional[torch.LongTensor] = None,
1982
+ audio_feats: Optional[torch.Tensor] = None,
1983
+ audio_feats_lengths: Optional[torch.LongTensor] = None,
1984
+ audio_num_clips: Optional[torch.LongTensor] = None,
1985
+ mm_token_type_ids: Optional[torch.IntTensor] = None,
1986
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1987
+ **kwargs,
1988
+ ) -> Union[Tuple, MingV3ASRCausalLMOutputWithPast]:
1989
+ return_dict = kwargs.pop("return_dict", None)
1990
+ if return_dict is None:
1991
+ return_dict = self.config.use_return_dict
1992
+ outputs = self.model(
1993
+ input_ids=input_ids,
1994
+ audio_feats=audio_feats,
1995
+ audio_feats_lengths=audio_feats_lengths,
1996
+ audio_num_clips=audio_num_clips,
1997
+ mm_token_type_ids=mm_token_type_ids,
1998
+ position_ids=position_ids,
1999
+ attention_mask=attention_mask,
2000
+ past_key_values=past_key_values,
2001
+ inputs_embeds=inputs_embeds,
2002
+ projector_audio=self.linear_proj_audio,
2003
+ return_dict=True,
2004
+ **kwargs,
2005
+ )
2006
+
2007
+ hidden_states = outputs[0]
2008
+
2009
+ # Only compute necessary logits
2010
+ slice_indices = (
2011
+ slice(-logits_to_keep, None)
2012
+ if isinstance(logits_to_keep, int)
2013
+ else logits_to_keep
2014
+ )
2015
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
2016
+
2017
+ loss = None
2018
+ if labels is not None:
2019
+ loss = self.loss_function(
2020
+ logits=logits,
2021
+ labels=labels,
2022
+ vocab_size=self.config.text_config.vocab_size,
2023
+ )
2024
+
2025
+ result = MingV3ASRCausalLMOutputWithPast(
2026
+ loss=loss,
2027
+ logits=logits,
2028
+ past_key_values=outputs.past_key_values,
2029
+ hidden_states=outputs.hidden_states,
2030
+ attentions=outputs.attentions,
2031
+ router_logits=outputs.router_logits,
2032
+ )
2033
+
2034
+ return result if return_dict else result.to_tuple()
2035
+
2036
+ def prepare_inputs_for_generation(
2037
+ self,
2038
+ input_ids,
2039
+ past_key_values=None,
2040
+ attention_mask=None,
2041
+ inputs_embeds=None,
2042
+ position_ids=None,
2043
+ use_cache=True,
2044
+ is_first_iteration=None,
2045
+ **kwargs,
2046
+ ):
2047
+ _reject_visual_inputs(kwargs)
2048
+ model_inputs = super().prepare_inputs_for_generation(
2049
+ input_ids,
2050
+ past_key_values=past_key_values,
2051
+ attention_mask=attention_mask,
2052
+ inputs_embeds=inputs_embeds,
2053
+ position_ids=position_ids,
2054
+ use_cache=use_cache,
2055
+ is_first_iteration=is_first_iteration,
2056
+ **kwargs,
2057
+ )
2058
+
2059
+ has_cached_tokens = False
2060
+ if use_cache:
2061
+ if is_first_iteration is not None:
2062
+ has_cached_tokens = not is_first_iteration
2063
+ elif kwargs.get("cache_position") is not None:
2064
+ has_cached_tokens = (
2065
+ bool(kwargs["cache_position"].numel())
2066
+ and int(kwargs["cache_position"][0]) > 0
2067
+ )
2068
+ elif past_key_values is not None:
2069
+ has_cached_tokens = past_key_values.get_seq_length() > 0
2070
+ if has_cached_tokens:
2071
+ for key in (
2072
+ "audio_feats",
2073
+ "audio_feats_lengths",
2074
+ "audio_num_clips",
2075
+ "audio_attention_mask",
2076
+ ):
2077
+ model_inputs[key] = None
2078
+
2079
+ return model_inputs
2080
+
2081
+ def _expand_inputs_for_generation(
2082
+ self,
2083
+ expand_size: int = 1,
2084
+ is_encoder_decoder: bool = False,
2085
+ input_ids: Optional[torch.LongTensor] = None,
2086
+ **model_kwargs,
2087
+ ) -> Tuple[torch.LongTensor, dict]:
2088
+ if expand_size == 1:
2089
+ return input_ids, model_kwargs
2090
+
2091
+ audio_keys = (
2092
+ "audio_feats",
2093
+ "audio_feats_lengths",
2094
+ "audio_num_clips",
2095
+ "audio_attention_mask",
2096
+ )
2097
+
2098
+ if model_kwargs.get("audio_feats") is not None:
2099
+ features = model_kwargs["audio_feats"]
2100
+ lengths = _audio_clip_lengths(
2101
+ features, model_kwargs.get("audio_feats_lengths")
2102
+ )
2103
+ batch_size = (
2104
+ input_ids.shape[0]
2105
+ if input_ids is not None
2106
+ else model_kwargs["inputs_embeds"].shape[0]
2107
+ )
2108
+ counts = _audio_request_counts(
2109
+ model_kwargs.get("audio_num_clips"), batch_size, len(lengths)
2110
+ )
2111
+ groups = torch.split(torch.arange(len(lengths)), counts)
2112
+ clip_order = torch.cat([group.repeat(expand_size) for group in groups])
2113
+ for key in ("audio_feats", "audio_feats_lengths", "audio_attention_mask"):
2114
+ if model_kwargs.get(key) is not None:
2115
+ value = torch.as_tensor(model_kwargs[key])
2116
+ model_kwargs[key] = value.index_select(
2117
+ 0, clip_order.to(value.device)
2118
+ )
2119
+ count_device = model_kwargs["audio_feats_lengths"].device
2120
+ model_kwargs["audio_num_clips"] = torch.tensor(
2121
+ counts, device=count_device
2122
+ ).repeat_interleave(expand_size)
2123
+
2124
+ def _expand_dict_for_generation(dict_to_expand):
2125
+ for key in dict_to_expand:
2126
+ if (
2127
+ dict_to_expand[key] is not None
2128
+ and isinstance(dict_to_expand[key], torch.Tensor)
2129
+ and key not in audio_keys
2130
+ ):
2131
+ dict_to_expand[key] = dict_to_expand[key].repeat_interleave(
2132
+ expand_size, dim=0
2133
+ )
2134
+ return dict_to_expand
2135
+
2136
+ if input_ids is not None:
2137
+ input_ids = input_ids.repeat_interleave(expand_size, dim=0)
2138
+
2139
+ model_kwargs = _expand_dict_for_generation(model_kwargs)
2140
+
2141
+ if is_encoder_decoder:
2142
+ if model_kwargs.get("encoder_outputs") is None:
2143
+ raise ValueError(
2144
+ "If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined."
2145
+ )
2146
+ model_kwargs["encoder_outputs"] = _expand_dict_for_generation(
2147
+ model_kwargs["encoder_outputs"]
2148
+ )
2149
+
2150
+ return input_ids, model_kwargs
modeling_ming_v3_asr_encoder.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Ant Group. All rights reserved.
2
+ # Licensed under the Apache License, Version 2.0.
3
+ """Standalone Ming V3 ASR audio tower and checkpoint-compatible projector.
4
+
5
+ Waveform preprocessing belongs to the feature extractor. This module consumes
6
+ raw mel clips, chunks by the trained context, and returns normalized embeddings.
7
+ Parameter names are deliberately stable for existing safetensors checkpoints.
8
+ """
9
+
10
+ import torch
11
+ from torch import nn
12
+ from torch.nn import functional as F
13
+
14
+ from .audio_spec import MingAudioSpec
15
+ from .modeling_whisper_encoder import WhisperAudioEncoder
16
+
17
+
18
+ class Transpose(nn.Module):
19
+ def forward(self, value):
20
+ return value.transpose(-1, -2)
21
+
22
+
23
+ def build_audio_encoder(config):
24
+ get = (
25
+ config.get
26
+ if isinstance(config, dict)
27
+ else lambda k, d=None: getattr(config, k, d)
28
+ )
29
+ settings = get("whisper_encoder_config")
30
+ if settings is None:
31
+ settings = dict(
32
+ n_mels=get("n_mels", 128),
33
+ n_ctx=get("n_audio_ctx", 3000),
34
+ n_state=get("n_audio_state", 1280),
35
+ n_head=get("n_audio_head", 20),
36
+ n_layer=get("n_audio_layer", 32),
37
+ )
38
+ return WhisperAudioEncoder(**settings)
39
+
40
+
41
+ def build_audio_projector(config, hidden_size, mlp_depth=2):
42
+ spec = MingAudioSpec.from_config(config)
43
+ get = (
44
+ config.get
45
+ if isinstance(config, dict)
46
+ else lambda k, d=None: getattr(config, k, d)
47
+ )
48
+ encoder = get("whisper_encoder_config") or {}
49
+ input_size = encoder.get("n_state", get("n_audio_state", 1280))
50
+ layers = []
51
+ for kernel, stride, padding in zip(spec.kernels, spec.strides, spec.paddings):
52
+ layers.extend(
53
+ [nn.Conv1d(input_size, hidden_size, kernel, stride, padding), nn.GELU()]
54
+ )
55
+ input_size = hidden_size
56
+ layers.extend([Transpose(), nn.Linear(hidden_size, hidden_size)])
57
+ for _ in range(2, mlp_depth):
58
+ layers.extend([nn.GELU(), nn.Linear(hidden_size, hidden_size)])
59
+ return nn.Sequential(*layers)
60
+
61
+
62
+ def encode_audio_clips(clips, encoder, projector, config):
63
+ """Encode each chunk with a fixed batch shape, preserving clip order.
64
+
65
+ Padding cannot be removed only after attention: both attention and stacked
66
+ biased convolutions would already have changed valid positions.
67
+ """
68
+ if not clips:
69
+ raise ValueError("Audio clips must not be empty")
70
+ spec = MingAudioSpec.from_config(config)
71
+ parameter = next(projector.parameters())
72
+ chunks = []
73
+ for clip in clips:
74
+ if clip.ndim != 2 or clip.shape[1] != spec.n_mels or not clip.shape[0]:
75
+ raise ValueError("Audio clips require positive [frames, mel_bins] shapes")
76
+ chunks.extend(
77
+ clip.to(device=parameter.device, dtype=parameter.dtype).split(
78
+ spec.chunk_frames
79
+ )
80
+ )
81
+ outputs = []
82
+ # Keep the BF16 GEMM batch shape independent of neighboring requests.
83
+ for chunk in chunks:
84
+ encoded = encoder(chunk.unsqueeze(0))
85
+ projected = projector(encoded.transpose(-1, -2))[0]
86
+ if projected.shape[0] != spec.embedding_length(chunk.shape[0]):
87
+ raise ValueError("Audio projector output violates the length contract")
88
+ outputs.append(projected)
89
+ return F.normalize(torch.cat(outputs), dim=-1)
modeling_whisper_encoder.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from OpenAI Whisper: https://github.com/openai/whisper
2
+ # MIT License
3
+ #
4
+ # Copyright (c) 2022 OpenAI
5
+ #
6
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ # of this software and associated documentation files (the "Software"), to deal
8
+ # in the Software without restriction, including without limitation the rights
9
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ # copies of the Software, and to permit persons to whom the Software is
11
+ # furnished to do so, subject to the following conditions:
12
+ #
13
+ # The above copyright notice and this permission notice shall be included in all
14
+ # copies or substantial portions of the Software.
15
+ #
16
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ # SOFTWARE.
23
+
24
+ """Local Whisper-compatible audio encoder used by Ming audio models."""
25
+
26
+ import math
27
+
28
+ import torch
29
+ import torch.nn.functional as F
30
+ from torch import Tensor, nn
31
+
32
+
33
+ class _WhisperLayerNorm(nn.LayerNorm):
34
+ def forward(self, x: Tensor) -> Tensor:
35
+ return F.layer_norm(
36
+ x.float(),
37
+ self.normalized_shape,
38
+ self.weight.float() if self.weight is not None else None,
39
+ self.bias.float() if self.bias is not None else None,
40
+ self.eps,
41
+ ).to(dtype=x.dtype)
42
+
43
+
44
+ class _WhisperLinear(nn.Linear):
45
+ def forward(self, x: Tensor) -> Tensor:
46
+ return F.linear(
47
+ x,
48
+ self.weight.to(dtype=x.dtype),
49
+ None if self.bias is None else self.bias.to(dtype=x.dtype),
50
+ )
51
+
52
+
53
+ class _WhisperConv1d(nn.Conv1d):
54
+ def _conv_forward(self, x: Tensor, weight: Tensor, bias: Tensor | None) -> Tensor:
55
+ return super()._conv_forward(
56
+ x,
57
+ weight.to(dtype=x.dtype),
58
+ None if bias is None else bias.to(dtype=x.dtype),
59
+ )
60
+
61
+
62
+ def _sinusoids(length: int, channels: int, max_timescale: int = 10000) -> Tensor:
63
+ assert channels % 2 == 0
64
+ log_timescale_increment = math.log(max_timescale) / (channels // 2 - 1)
65
+ inv_timescales = torch.exp(-log_timescale_increment * torch.arange(channels // 2))
66
+ scaled_time = torch.arange(length)[:, None] * inv_timescales[None, :]
67
+ return torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim=1)
68
+
69
+
70
+ class _WhisperMultiHeadAttention(nn.Module):
71
+ def __init__(self, n_state: int, n_head: int):
72
+ super().__init__()
73
+ self.n_head = n_head
74
+ self.query = _WhisperLinear(n_state, n_state)
75
+ self.key = _WhisperLinear(n_state, n_state, bias=False)
76
+ self.value = _WhisperLinear(n_state, n_state)
77
+ self.out = _WhisperLinear(n_state, n_state)
78
+
79
+ def forward(self, x: Tensor) -> Tensor:
80
+ batch_size, sequence_length, n_state = x.shape
81
+ head_dim = n_state // self.n_head
82
+ q = self.query(x).view(batch_size, sequence_length, self.n_head, head_dim)
83
+ k = self.key(x).view(batch_size, sequence_length, self.n_head, head_dim)
84
+ v = self.value(x).view(batch_size, sequence_length, self.n_head, head_dim)
85
+ q = q.permute(0, 2, 1, 3)
86
+ k = k.permute(0, 2, 1, 3)
87
+ v = v.permute(0, 2, 1, 3)
88
+ x = F.scaled_dot_product_attention(q, k, v)
89
+ x = x.permute(0, 2, 1, 3).flatten(start_dim=2)
90
+ return self.out(x)
91
+
92
+
93
+ class _WhisperResidualAttentionBlock(nn.Module):
94
+ def __init__(self, n_state: int, n_head: int):
95
+ super().__init__()
96
+ self.attn = _WhisperMultiHeadAttention(n_state, n_head)
97
+ self.attn_ln = _WhisperLayerNorm(n_state)
98
+ self.mlp = nn.Sequential(
99
+ _WhisperLinear(n_state, n_state * 4),
100
+ nn.GELU(),
101
+ _WhisperLinear(n_state * 4, n_state),
102
+ )
103
+ self.mlp_ln = _WhisperLayerNorm(n_state)
104
+
105
+ def forward(self, x: Tensor) -> Tensor:
106
+ x = x + self.attn(self.attn_ln(x))
107
+ return x + self.mlp(self.mlp_ln(x))
108
+
109
+
110
+ class WhisperAudioEncoder(nn.Module):
111
+ """Whisper encoder with Ming's variable-length ``[B, T, n_mels]`` input."""
112
+
113
+ def __init__(
114
+ self, n_mels: int, n_ctx: int, n_state: int, n_head: int, n_layer: int
115
+ ):
116
+ super().__init__()
117
+ self.conv1 = _WhisperConv1d(n_mels, n_state, kernel_size=3, padding=1)
118
+ self.conv2 = _WhisperConv1d(
119
+ n_state, n_state, kernel_size=3, stride=2, padding=1
120
+ )
121
+ self.register_buffer("positional_embedding", _sinusoids(n_ctx, n_state))
122
+ self.blocks = nn.ModuleList(
123
+ [_WhisperResidualAttentionBlock(n_state, n_head) for _ in range(n_layer)]
124
+ )
125
+ self.ln_post = _WhisperLayerNorm(n_state)
126
+ self.audio_emb_dim = n_state
127
+
128
+ def forward(self, x: Tensor) -> Tensor:
129
+ """Encode a batch of mel spectrograms shaped ``[batch, frames, mels]``."""
130
+ x = x.transpose(1, 2)
131
+ x = F.gelu(self.conv1(x))
132
+ x = F.gelu(self.conv2(x))
133
+ x = x.permute(0, 2, 1)
134
+ positional_embedding = self.positional_embedding[: x.shape[1], :]
135
+ assert x.shape[1:] == positional_embedding.shape, "incorrect audio shape"
136
+ x = (x + positional_embedding).to(dtype=x.dtype)
137
+
138
+ for block in self.blocks:
139
+ x = block(x)
140
+
141
+ return self.ln_post(x)
preprocessor_config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "feature_extractor_type": "MingV3ASRFeatureExtractor",
3
+ "processor_class": "MingV3ASRProcessor",
4
+ "feature_size": 128,
5
+ "sampling_rate": 16000,
6
+ "padding_value": 0.0,
7
+ "audio_config": {
8
+ "n_mels": 128,
9
+ "n_audio_ctx": 3000,
10
+ "n_audio_state": 1280,
11
+ "n_audio_head": 20,
12
+ "n_audio_layer": 32,
13
+ "downsampler_kernel_size_list": [
14
+ 3
15
+ ],
16
+ "downsampler_stride_list": [
17
+ 2
18
+ ],
19
+ "chunk_frames": 3000,
20
+ "downsampler_padding_list": [
21
+ 1
22
+ ]
23
+ },
24
+ "auto_map": {
25
+ "AutoFeatureExtractor": "feature_extraction_ming_v3_asr.MingV3ASRFeatureExtractor",
26
+ "AutoProcessor": "processing_ming_v3_asr.MingV3ASRProcessor"
27
+ }
28
+ }
processing_ming_v3_asr.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Ant Group. All rights reserved.
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0
5
+ # Unless required by applicable law or agreed to in writing, software
6
+ # distributed under the License is distributed on an "AS IS" BASIS,
7
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8
+ """Hugging Face processor for Ming V3 ASR transcription."""
9
+
10
+ import re
11
+
12
+ import numpy as np
13
+ import torch
14
+ from transformers.feature_extraction_utils import BatchFeature
15
+ from transformers.processing_utils import ProcessingKwargs, ProcessorMixin
16
+
17
+ from .audio_spec import MingAudioSpec # noqa: F401 - include transitive dependency in HF's local module cache
18
+ from .feature_extraction_ming_v3_asr import MingV3ASRFeatureExtractor
19
+
20
+ _AUDIO_FORMS = (
21
+ ("<audio>", "<audioPatch>", "</audio>"),
22
+ ("<|audio_start|>", "<|audio_pad|>", "<|audio_end|>"),
23
+ )
24
+ _PLACEHOLDER = "<AUDIO>"
25
+ _ASR_INSTRUCTION = (
26
+ "Please recognize the language of this speech and transcribe it, "
27
+ "placing a `\t` between the identified language and the transcribe."
28
+ )
29
+
30
+
31
+ class MingV3ASRProcessorKwargs(ProcessingKwargs, total=False):
32
+ _defaults = {
33
+ "text_kwargs": {
34
+ "padding": False,
35
+ "padding_side": "left",
36
+ "return_attention_mask": True,
37
+ "return_token_type_ids": False,
38
+ },
39
+ }
40
+
41
+
42
+ class MingV3ASRProcessor(ProcessorMixin):
43
+ """Expand audio tokens and combine an unchanged tokenizer with log-mel.
44
+
45
+ ``audio`` (or the compatible ``audios`` spelling) is a flat list of clips in
46
+ prompt-placeholder order. ``audio_num_clips`` records each text request's
47
+ clip count, including zero. Audio features and raw lengths are flattened
48
+ independently of the text batch. Image/video inputs are not supported.
49
+
50
+ Chat-template support is inherited from ``ProcessorMixin`` for tokenizer
51
+ compatibility. ASR inference uses ``apply_transcription_request`` instead.
52
+ """
53
+
54
+ feature_extractor_class = "AutoFeatureExtractor"
55
+ tokenizer_class = "AutoTokenizer"
56
+ valid_processor_kwargs = MingV3ASRProcessorKwargs
57
+
58
+ def __init__(
59
+ self,
60
+ feature_extractor: MingV3ASRFeatureExtractor,
61
+ tokenizer,
62
+ chat_template=None,
63
+ ):
64
+ template = tokenizer.chat_template if chat_template is None else chat_template
65
+ super().__init__(feature_extractor, tokenizer, chat_template=template)
66
+ vocabulary = tokenizer.get_vocab()
67
+ self.audio_start_token, self.audio_token, self.audio_end_token = next(
68
+ (
69
+ form
70
+ for form in _AUDIO_FORMS
71
+ if all(token in vocabulary for token in form)
72
+ ),
73
+ (None, None, None),
74
+ )
75
+ if self.audio_token is None:
76
+ raise ValueError("tokenizer lacks Ming audio start/patch/end tokens")
77
+ self.audio_token_id = tokenizer.convert_tokens_to_ids(self.audio_token)
78
+
79
+ @staticmethod
80
+ def _normalize_prompt(text):
81
+ for start, patch, end in _AUDIO_FORMS:
82
+ text = re.sub(
83
+ re.escape(start) + "(?:" + re.escape(patch) + ")+" + re.escape(end),
84
+ _PLACEHOLDER,
85
+ text,
86
+ )
87
+ return text
88
+
89
+ def __call__(
90
+ self, text=None, audio=None, *, images=None, videos=None, audios=None, **kwargs
91
+ ):
92
+ if images is not None or videos is not None:
93
+ raise ValueError("MingV3ASRProcessor supports audio and text only")
94
+ if audio is not None and audios is not None:
95
+ raise ValueError("Pass either audio or audios, not both")
96
+ clips = self.feature_extractor.as_clips(audio if audio is not None else audios)
97
+ if text is None:
98
+ if not clips:
99
+ raise ValueError("Provide text or audio")
100
+ text = " ".join([_PLACEHOLDER] * len(clips))
101
+ texts = [text] if isinstance(text, str) else text
102
+ if (
103
+ not isinstance(texts, (list, tuple))
104
+ or not texts
105
+ or not all(isinstance(t, str) for t in texts)
106
+ ):
107
+ raise ValueError("text must be a string or a nonempty list of strings")
108
+ texts = [self._normalize_prompt(t) for t in texts]
109
+ clip_counts = [t.count(_PLACEHOLDER) for t in texts]
110
+ if sum(clip_counts) != len(clips):
111
+ raise ValueError(
112
+ f"Audio placeholder count {sum(clip_counts)} does not match {len(clips)} clips"
113
+ )
114
+
115
+ options = self._merge_kwargs(
116
+ MingV3ASRProcessorKwargs,
117
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
118
+ **kwargs,
119
+ )
120
+ text_options = options["text_kwargs"]
121
+ audio_options = options["audio_kwargs"]
122
+ return_tensors = text_options.get("return_tensors")
123
+ audio_return_tensors = audio_options.get("return_tensors")
124
+ if (
125
+ return_tensors is not None
126
+ and audio_return_tensors is not None
127
+ and return_tensors != audio_return_tensors
128
+ ):
129
+ raise ValueError("text and audio return_tensors must match")
130
+ if return_tensors is None:
131
+ return_tensors = audio_return_tensors
132
+ if return_tensors is not None:
133
+ text_options["return_tensors"] = return_tensors
134
+ audio_options["return_tensors"] = return_tensors
135
+ if text_options.get("return_overflowing_tokens"):
136
+ raise ValueError("Audio token overflow windows are not supported")
137
+ # Top-level max_length/truncation refer to text; audio is always chunked.
138
+ # Explicit nested audio options retain extractor validation.
139
+ for key in ("max_length", "truncation", "padding"):
140
+ if key not in kwargs.get("audio_kwargs", {}):
141
+ audio_options.pop(key, None)
142
+ audio_inputs = self.feature_extractor(clips, **audio_options) if clips else {}
143
+ lengths = audio_inputs.get("audio_feats_lengths", [])
144
+ token_counts = [
145
+ self.feature_extractor.spec.token_count(int(length)) for length in lengths
146
+ ]
147
+
148
+ expected_counts = []
149
+ clip_index = 0
150
+ for index, count in enumerate(clip_counts):
151
+ expected_counts.append(sum(token_counts[clip_index : clip_index + count]))
152
+ for token_count in token_counts[clip_index : clip_index + count]:
153
+ replacement = (
154
+ self.audio_start_token
155
+ + self.audio_token * token_count
156
+ + self.audio_end_token
157
+ )
158
+ texts[index] = texts[index].replace(_PLACEHOLDER, replacement, 1)
159
+ clip_index += count
160
+ encoded = self.tokenizer(texts, **text_options)
161
+ for ids, expected in zip(encoded["input_ids"], expected_counts):
162
+ actual = sum(int(token) == self.audio_token_id for token in ids)
163
+ if actual != expected:
164
+ raise ValueError(
165
+ "Audio token count changed during tokenization; do not truncate audio placeholders"
166
+ )
167
+ if clips:
168
+ if return_tensors == "pt":
169
+ audio_inputs["audio_num_clips"] = torch.tensor(
170
+ clip_counts, dtype=torch.long
171
+ )
172
+ elif return_tensors == "np":
173
+ audio_inputs["audio_num_clips"] = np.asarray(
174
+ clip_counts, dtype=np.int64
175
+ )
176
+ else:
177
+ audio_inputs["audio_num_clips"] = clip_counts
178
+ return BatchFeature(data={**encoded, **audio_inputs})
179
+
180
+ def apply_transcription_request(
181
+ self, audio, *, prompt=None, language_hint=None,
182
+ audio_chunk_frames=None, return_tensors="pt",
183
+ ):
184
+ """Prepare one audio request in the released ASR input format.
185
+
186
+ ``prompt`` starts with the base ASR instruction and may append topic
187
+ and hotwords without a newline. A known language can be prefixed to
188
+ the generated answer with ``language_hint='zh'`` or ``'en'``.
189
+ """
190
+ if prompt is None:
191
+ prompt = _ASR_INSTRUCTION
192
+ if not isinstance(prompt, str) or not prompt.startswith(_ASR_INSTRUCTION):
193
+ raise ValueError("Prompt must start with the base ASR instruction")
194
+ if "\n" in prompt or "\r" in prompt:
195
+ raise ValueError("Prompt metadata must be contiguous, without newlines")
196
+ if _PLACEHOLDER in prompt:
197
+ raise ValueError("Prompt must not contain <AUDIO>; it is appended here")
198
+ if audio_chunk_frames is not None:
199
+ if (isinstance(audio_chunk_frames, bool)
200
+ or not isinstance(audio_chunk_frames, int)
201
+ or audio_chunk_frames < 1):
202
+ raise ValueError("audio_chunk_frames must be a positive integer")
203
+ extractor = self.feature_extractor
204
+ original_config = extractor.audio_config
205
+ extractor.audio_config = {**original_config, "chunk_frames": audio_chunk_frames}
206
+ try:
207
+ _ = extractor.spec
208
+ inputs = self(
209
+ text=prompt + _PLACEHOLDER, audio=audio,
210
+ return_tensors=return_tensors,
211
+ )
212
+ finally:
213
+ extractor.audio_config = original_config
214
+ else:
215
+ inputs = self(
216
+ text=prompt + _PLACEHOLDER, audio=audio,
217
+ return_tensors=return_tensors,
218
+ )
219
+ if language_hint is not None:
220
+ label = {"zh": "Chinese\t", "en": "English\t"}.get(language_hint)
221
+ if label is None:
222
+ raise ValueError("language_hint must be 'zh', 'en', or None")
223
+ if return_tensors != "pt":
224
+ raise ValueError("language_hint requires return_tensors='pt'")
225
+ label_ids = self.tokenizer(
226
+ label, add_special_tokens=False, return_tensors="pt",
227
+ )["input_ids"]
228
+ if inputs.input_ids.shape[0] != 1:
229
+ raise ValueError("language_hint requires exactly one audio request")
230
+ inputs["input_ids"] = torch.cat((inputs.input_ids, label_ids), dim=1)
231
+ if "attention_mask" in inputs:
232
+ inputs["attention_mask"] = torch.cat(
233
+ (inputs.attention_mask, torch.ones_like(label_ids)), dim=1,
234
+ )
235
+ return inputs
236
+
237
+ @property
238
+ def model_input_names(self):
239
+ return [
240
+ "input_ids",
241
+ "attention_mask",
242
+ "audio_feats",
243
+ "audio_feats_lengths",
244
+ "audio_num_clips",
245
+ ]
246
+
247
+
248
+ MingV3ASRProcessor.register_for_auto_class()
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python 3.12, Linux, CUDA 13.0 (NVIDIA L20Y).
2
+ # For another CUDA version, install matching PyTorch 2.11.0 wheels first.
3
+ torch==2.11.0
4
+ torchaudio==2.11.0
5
+ transformers==5.12.1
6
+ fla-core==0.5.2
7
+ accelerate==1.15.0
8
+ einops==0.8.2
9
+ safetensors==0.8.0
10
+ numpy==2.5.4
11
+ soundfile==0.14.0
special_tokens_map.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|arithmetic_end|>",
4
+ "<role>",
5
+ "<|number_end|>",
6
+ "<|arithmetic_start|>",
7
+ "</role>",
8
+ "<|number_start|>",
9
+ "<|role_end|>",
10
+ "<tool_call>",
11
+ "</tool_call>",
12
+ "<tool_response>",
13
+ "</tool_response>"
14
+ ],
15
+ "bos_token": {
16
+ "content": "<|startoftext|>",
17
+ "lstrip": false,
18
+ "normalized": false,
19
+ "rstrip": false,
20
+ "single_word": false
21
+ },
22
+ "cls_token": {
23
+ "content": "[CLS]",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false
28
+ },
29
+ "eos_token": {
30
+ "content": "<|role_end|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false
35
+ },
36
+ "gmask_token": {
37
+ "content": "[gMASK]",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": false,
41
+ "single_word": false
42
+ },
43
+ "pad_token": "<|role_end|>"
44
+ }
tokenization_bailing.py ADDED
@@ -0,0 +1,1155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # coding=utf-8
3
+ # Copyright (c) Ant Group. All rights reserved.
4
+
5
+ import itertools
6
+ from typing import Any, Dict, List, Optional, Union
7
+
8
+ import torch
9
+ from transformers import PreTrainedTokenizerFast
10
+ from transformers.tokenization_utils_base import AddedToken, BatchEncoding
11
+ from transformers.utils import TensorType, logging
12
+
13
+ logger = logging.get_logger(__name__)
14
+
15
+
16
+ def is_system(msg):
17
+ return msg["role"].lower() == "system"
18
+
19
+
20
+ def is_user(msg):
21
+ return msg["role"].lower() in ["human", "user"]
22
+
23
+
24
+ def is_assistant(msg):
25
+ return msg["role"].lower() == "assistant"
26
+
27
+
28
+ def _convert_to_conversation(query, system=None):
29
+ conversation = []
30
+ if system:
31
+ conversation.append({"role": "SYSTEM", "content": system})
32
+ if isinstance(query, str):
33
+ conversation.append({"role": "HUMAN", "content": query})
34
+ elif isinstance(query, List):
35
+ conversation.extend(query)
36
+ elif isinstance(query, Dict):
37
+ if "messages" in query:
38
+ conversation.extend(query["messages"])
39
+ if (
40
+ "system_message" in query
41
+ and len(conversation) > 0
42
+ and not is_system(conversation[0])
43
+ ):
44
+ conversation.insert(
45
+ 0, {"role": "SYSTEM", "content": query["system_message"]}
46
+ )
47
+ else:
48
+ conversation.append(query)
49
+ return conversation
50
+
51
+
52
+ class BailingTokenizer(PreTrainedTokenizerFast):
53
+ is_bailing_tokenizer = True
54
+ model_input_names = ["input_ids", "attention_mask"]
55
+ slow_tokenizer_class = None
56
+
57
+ # add gmask_token
58
+ SPECIAL_TOKENS_ATTRIBUTES = [
59
+ "bos_token",
60
+ "eos_token",
61
+ "unk_token",
62
+ "sep_token",
63
+ "pad_token",
64
+ "cls_token",
65
+ "mask_token",
66
+ "gmask_token",
67
+ "additional_special_tokens",
68
+ ]
69
+
70
+ def __init__(
71
+ self,
72
+ vocab_file=None,
73
+ merges_file=None,
74
+ tokenizer_file=None,
75
+ clean_up_tokenization_spaces=False,
76
+ bos_token="<|startoftext|>",
77
+ eos_token="<|endoftext|>",
78
+ cls_token="[CLS]",
79
+ pad_token="<|endoftext|>",
80
+ gmask_token="[gMASK]",
81
+ add_bos_token=False,
82
+ add_eos_token=False,
83
+ **kwargs,
84
+ ):
85
+ self._gmask_token = (
86
+ AddedToken(gmask_token, lstrip=False, rstrip=False, normalized=False)
87
+ if isinstance(gmask_token, str)
88
+ else gmask_token
89
+ )
90
+
91
+ self._sop_token = (
92
+ AddedToken(bos_token, lstrip=False, rstrip=False, normalized=False)
93
+ if isinstance(bos_token, str)
94
+ else bos_token
95
+ )
96
+
97
+ self._eop_token = (
98
+ AddedToken(eos_token, lstrip=False, rstrip=False, normalized=False)
99
+ if isinstance(eos_token, str)
100
+ else eos_token
101
+ )
102
+
103
+ super().__init__(
104
+ vocab_file=vocab_file,
105
+ merges_file=merges_file,
106
+ tokenizer_file=tokenizer_file,
107
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
108
+ bos_token=bos_token,
109
+ eos_token=eos_token,
110
+ cls_token=cls_token,
111
+ pad_token=pad_token,
112
+ gmask_token=gmask_token,
113
+ add_bos_token=add_bos_token,
114
+ add_eos_token=add_eos_token,
115
+ **kwargs,
116
+ )
117
+
118
+ if not hasattr(self, "add_bos_token"):
119
+ self.add_bos_token = add_bos_token
120
+
121
+ self.check_special_tokens()
122
+
123
+ def check_special_tokens(self):
124
+ """
125
+ eos_token, cls_token, mask_token
126
+ special tokens should init, check special token is not None
127
+ """
128
+ for name, special_token in zip(
129
+ ["eos", "bos", "cls", "gmask"],
130
+ [self.eos_token, self.bos_token, self.cls_token, self.gmask_token],
131
+ ):
132
+ assert special_token is not None, (
133
+ f"should init special token [{name}] in tokenizer_config.json"
134
+ )
135
+
136
+ @property
137
+ def gmask_token(self) -> Optional[str]:
138
+ if self._gmask_token is None:
139
+ if self.verbose:
140
+ logger.error("Using gmask_token, but it is not set yet.")
141
+ return None
142
+ return str(self._gmask_token)
143
+
144
+ @gmask_token.setter
145
+ def gmask_token(self, value):
146
+ if not isinstance(value, (str, AddedToken)) and value is not None:
147
+ raise ValueError("Cannot set a non-string value as the gmask token")
148
+ self._gmask_token = value
149
+
150
+ @property
151
+ def gmask_token_id(self) -> Optional[int]:
152
+ if self._gmask_token is None:
153
+ return None
154
+ return self.convert_tokens_to_ids(self.gmask_token)
155
+
156
+ @property
157
+ def sop_token(self) -> Optional[str]:
158
+ if self._sop_token is None:
159
+ if self.verbose:
160
+ logger.error("Using sop_token, but it is not set yet.")
161
+ return None
162
+ return str(self._sop_token)
163
+
164
+ @sop_token.setter
165
+ def sop_token(self, value):
166
+ if not isinstance(value, (str, AddedToken)) and value is not None:
167
+ raise ValueError("Cannot set a non-string value as the sop token")
168
+ self._sop_token = value
169
+
170
+ @property
171
+ def sop_token_id(self) -> Optional[int]:
172
+ if self._sop_token is None:
173
+ return None
174
+ return self.convert_tokens_to_ids(self.sop_token)
175
+
176
+ @property
177
+ def eop_token(self) -> Optional[str]:
178
+ if self._eop_token is None:
179
+ if self.verbose:
180
+ logger.error("Using eop_token, but it is not set yet.")
181
+ return None
182
+ return str(self._eop_token)
183
+
184
+ @eop_token.setter
185
+ def eop_token(self, value):
186
+ if not isinstance(value, (str, AddedToken)) and value is not None:
187
+ raise ValueError("Cannot set a non-string value as the eop token")
188
+ self._eop_token = value
189
+
190
+ @property
191
+ def eop_token_id(self) -> Optional[int]:
192
+ if self._eop_token is None:
193
+ return None
194
+ return self.convert_tokens_to_ids(self.eop_token)
195
+
196
+ @property
197
+ def vocab_size(self):
198
+ return len(self.get_vocab())
199
+
200
+ def _chat_from_json(self, chat, chat_format="antglm_chat", system=None):
201
+ msgs = chat if "messages" not in chat else chat["messages"]
202
+ _msgs = []
203
+ sys_msg = None
204
+ for msg in msgs:
205
+ if is_system(msg):
206
+ sys_msg = msg["content"]
207
+ else:
208
+ _msgs.append(msg)
209
+ chat = {"messages": _msgs}
210
+ system = system or sys_msg
211
+ if system:
212
+ chat["system_message"] = system
213
+ from .chat_format import Chat
214
+
215
+ return Chat.from_json(chat, name=chat_format)
216
+
217
+ def apply_chat_template(
218
+ self,
219
+ conversation: Union[List[Dict[str, str]], List[List[Dict[str, str]]]],
220
+ tools: Optional[List[Dict]] = None,
221
+ documents: Optional[List[Dict[str, str]]] = None,
222
+ chat_template: Optional[str] = None,
223
+ add_generation_prompt: bool = False,
224
+ system: str = None, # only used for legacy chatml
225
+ tokenize=False,
226
+ padding: bool = False,
227
+ truncation: bool = False,
228
+ max_length: Optional[int] = None,
229
+ return_tensors: Optional[Union[str, TensorType]] = None,
230
+ return_dict: bool = False,
231
+ return_assistant_tokens_mask: bool = False,
232
+ tokenizer_kwargs: Optional[Dict[str, Any]] = None,
233
+ **kwargs,
234
+ ):
235
+ if hasattr(self, "chat_template") and self.chat_template:
236
+ if isinstance(conversation, Dict) and "messages" in conversation:
237
+ conversation = conversation["messages"]
238
+ # use transformers built-in method
239
+ return super().apply_chat_template(
240
+ conversation=conversation,
241
+ tools=tools,
242
+ documents=documents,
243
+ chat_template=chat_template,
244
+ add_generation_prompt=add_generation_prompt,
245
+ tokenize=tokenize,
246
+ padding=padding,
247
+ truncation=truncation,
248
+ max_length=max_length,
249
+ return_tensors=return_tensors,
250
+ return_dict=return_dict,
251
+ return_assistant_tokens_mask=return_assistant_tokens_mask,
252
+ tokenizer_kwargs=tokenizer_kwargs,
253
+ **kwargs,
254
+ )
255
+
256
+ # 非chat_template方式后续将不再支持。
257
+ logger.warning("Please set chat_template in tokenizer_config.json!")
258
+
259
+ chat_format = kwargs.get("chat_format", "antglm_chat")
260
+
261
+ is_batched = False
262
+
263
+ if isinstance(conversation, List) and (
264
+ isinstance(conversation[0], (list, tuple)) or "messages" in conversation[0]
265
+ ):
266
+ conversations = conversation
267
+ is_batched = True
268
+
269
+ if not is_batched:
270
+ conversations = [conversation]
271
+
272
+ rendered = []
273
+ for chat in conversations:
274
+ rendered_chat = self._chat_from_json(
275
+ chat, chat_format=chat_format, system=system
276
+ ).prompt_str
277
+ rendered.append(rendered_chat)
278
+
279
+ if not is_batched:
280
+ rendered = rendered[0]
281
+
282
+ if tokenize:
283
+ out = self(
284
+ rendered,
285
+ padding=padding,
286
+ truncation=truncation,
287
+ max_length=max_length,
288
+ add_special_tokens=False,
289
+ return_tensors=return_tensors,
290
+ )
291
+ if return_dict:
292
+ return out
293
+ else:
294
+ return out["input_ids"]
295
+ else:
296
+ return rendered
297
+
298
+ def _build_position_ids(
299
+ self,
300
+ mask_pos: int,
301
+ bos_pos: int,
302
+ max_output_length: int,
303
+ rotary_type: Optional[str] = "none",
304
+ **kwargs,
305
+ ) -> List[List[int]]:
306
+ window_size = kwargs.get("window_size", 1024) - 1
307
+ block_position_ids = [0] * bos_pos
308
+
309
+ # 获得mask所在的位置,用于后面output positionid的构造
310
+ if "1d" in rotary_type:
311
+ position_ids = list(range(bos_pos)) + list(
312
+ range(mask_pos + 1, mask_pos + max_output_length + 2)
313
+ )
314
+ block_position_ids = block_position_ids + list(
315
+ range(1, max_output_length + 2)
316
+ )
317
+ elif "2d" in rotary_type:
318
+ # 后面input_ids要加一个bos_id
319
+ position_ids = list(range(bos_pos))
320
+ position_ids = position_ids + [mask_pos] * (1 + max_output_length)
321
+ block_position_ids = block_position_ids + list(
322
+ range(1, max_output_length + 2)
323
+ )
324
+ else:
325
+ # build position ids
326
+ position_ids = []
327
+ repeat_times = bos_pos // window_size
328
+ for _ in range(repeat_times):
329
+ position_ids += list(range(window_size))
330
+ position_ids += list(range(bos_pos - window_size * repeat_times))
331
+ # need consider additional bos_id after input_ids
332
+ mask_pos = position_ids[-1]
333
+ position_ids += [mask_pos] * (max_output_length + 1)
334
+
335
+ block_repeat_times = max_output_length // (window_size - 1)
336
+ additional_block_position_ids = []
337
+ for _ in range(block_repeat_times):
338
+ additional_block_position_ids += list(range(1, window_size))
339
+ additional_block_position_ids += list(
340
+ range(1, max_output_length + 2 - (window_size - 1) * block_repeat_times)
341
+ )
342
+ block_position_ids = block_position_ids + additional_block_position_ids
343
+
344
+ position_ids = [position_ids, block_position_ids]
345
+ return position_ids
346
+
347
+ def _build_inputs_for_generation(
348
+ self,
349
+ input_ids: List[int],
350
+ max_input_length=None,
351
+ left_truncate=True,
352
+ max_output_length=1024,
353
+ rotary_type="none",
354
+ unidirectional_attention: bool = True,
355
+ attention_dtype=None,
356
+ **kwargs,
357
+ ):
358
+ if max_input_length and len(input_ids) > max_input_length:
359
+ if left_truncate:
360
+ input_ids = input_ids[-max_input_length:]
361
+ else:
362
+ input_ids = input_ids[:max_input_length]
363
+
364
+ is_left_padding = input_ids[0] == self.eos_token_id
365
+ if not unidirectional_attention:
366
+ if input_ids[0] != self.cls_token_id:
367
+ input_ids = [self.cls_token_id] + input_ids
368
+
369
+ if self.gmask_token_id not in set(input_ids):
370
+ input_ids = input_ids + [self.gmask_token_id]
371
+
372
+ mask_pos = input_ids.index(self.gmask_token_id)
373
+ sep = len(input_ids)
374
+ else:
375
+ if self.add_bos_token:
376
+ input_ids = input_ids + [self.bos_token_id]
377
+ if self.eos_token_id in input_ids:
378
+ mask_pos = input_ids.index(self.eos_token_id) - 1
379
+ else:
380
+ mask_pos = len(input_ids) - 1
381
+ sep = len(input_ids) - 1
382
+ else:
383
+ sep = len(input_ids)
384
+ if self.eos_token_id in input_ids:
385
+ if is_left_padding:
386
+ ori_input_ids = input_ids
387
+ input_ids = input_ids[::-1]
388
+ mask_pos = input_ids.index(self.eos_token_id) - 1
389
+ mask_pos = max(0, mask_pos) # for empty sequence
390
+ if is_left_padding:
391
+ input_ids = ori_input_ids
392
+ mask_pos = sep - 1 - mask_pos # the first non-eos token
393
+
394
+ else:
395
+ mask_pos = len(input_ids) - 1
396
+
397
+ position_ids = self._build_position_ids(
398
+ mask_pos, sep, max_output_length, rotary_type, **kwargs
399
+ )
400
+
401
+ if is_left_padding:
402
+ position_ids[0] = [
403
+ max(0, i - mask_pos) for i in range(len(position_ids[0]))
404
+ ]
405
+
406
+ # 后面input_ids要加一个bos_id
407
+ total_length = sep + max_output_length
408
+ if self.add_bos_token:
409
+ total_length += 1
410
+
411
+ def build_mask_matrix(seq_length, sep, mask_pos, unidirectional_attention):
412
+ # 长序列使用bool类型节省显存
413
+ if unidirectional_attention:
414
+ attention_mask = torch.ones(
415
+ [seq_length, seq_length], dtype=attention_dtype
416
+ )
417
+ attention_mask = torch.tril(attention_mask)
418
+ if is_left_padding:
419
+ attention_mask[:, :mask_pos] = 0
420
+ else:
421
+ attention_mask[:, mask_pos + 1 : sep] = 0
422
+ else:
423
+ attention_mask = torch.zeros(
424
+ [seq_length, seq_length], dtype=attention_dtype
425
+ )
426
+ attention_mask[:, : mask_pos + 1] = 1
427
+ for i in range(sep, total_length):
428
+ attention_mask[i, sep : i + 1] = 1
429
+ return attention_mask
430
+
431
+ if self.add_bos_token:
432
+ attention_mask = build_mask_matrix(
433
+ total_length, sep + 1, mask_pos, unidirectional_attention
434
+ )
435
+ else:
436
+ attention_mask = build_mask_matrix(
437
+ total_length, sep, mask_pos, unidirectional_attention
438
+ )
439
+ attention_mask = torch.unsqueeze(attention_mask, dim=0)
440
+ attention_mask = torch.unsqueeze(attention_mask, dim=1)
441
+ if attention_dtype is None:
442
+ attention_mask = attention_mask.long()
443
+ inputs = {
444
+ "input_ids": torch.Tensor([input_ids]).long(),
445
+ "position_ids": torch.Tensor([position_ids]).long(),
446
+ "attention_mask": attention_mask,
447
+ }
448
+ return BatchEncoding(inputs)
449
+
450
+ def build_inputs_for_generation(
451
+ self,
452
+ input_ids: Union[List[int], List[List[int]], torch.Tensor],
453
+ max_input_length=None,
454
+ left_truncate=True,
455
+ max_output_length=1024,
456
+ rotary_type="1d",
457
+ unidirectional_attention=True,
458
+ attention_dtype=None,
459
+ **kwargs,
460
+ ):
461
+ if isinstance(input_ids, torch.Tensor):
462
+ input_ids = input_ids.tolist()
463
+
464
+ if isinstance(input_ids[0], list):
465
+ input_ids_list = []
466
+ position_ids_list = []
467
+ attention_mask_list = []
468
+ for _input_ids in input_ids:
469
+ inputs = self._build_inputs_for_generation(
470
+ _input_ids,
471
+ max_input_length=max_input_length,
472
+ left_truncate=left_truncate,
473
+ max_output_length=max_output_length,
474
+ rotary_type=rotary_type,
475
+ unidirectional_attention=unidirectional_attention,
476
+ attention_dtype=attention_dtype,
477
+ **kwargs,
478
+ )
479
+ input_ids_list.append(inputs["input_ids"])
480
+ position_ids_list.append(inputs["position_ids"])
481
+ attention_mask_list.append(inputs["attention_mask"])
482
+
483
+ max_ids_length = max([input.size(1) for input in input_ids_list])
484
+
485
+ for i in range(len(input_ids)):
486
+ cur_ids_length = input_ids_list[i].size(1)
487
+ if cur_ids_length < max_ids_length:
488
+ # pad input ids
489
+ pad_input_ids = input_ids_list[i].new_zeros(
490
+ (1, max_ids_length - cur_ids_length)
491
+ )
492
+ input_ids_list[i] = torch.cat(
493
+ [pad_input_ids, input_ids_list[i]], dim=-1
494
+ )
495
+
496
+ # pad postition ids with left pad
497
+ # 0, 1, 2, 3, 4 ... -> 0, ..., 0, 1, 2, 3, 4, ...
498
+ pad_position_ids = input_ids_list[i].new_zeros(
499
+ (1, 2, max_ids_length - cur_ids_length)
500
+ )
501
+ position_ids_list[i] = torch.cat(
502
+ [pad_position_ids, position_ids_list[i]], dim=-1
503
+ )
504
+
505
+ # pad generation attention mask with left and bottom pad
506
+ new_attention_mask = input_ids_list[i].new_zeros(
507
+ 1,
508
+ 1,
509
+ max_ids_length + max_output_length,
510
+ max_ids_length + max_output_length,
511
+ )
512
+ new_attention_mask[
513
+ :,
514
+ :,
515
+ max_ids_length - cur_ids_length :,
516
+ max_ids_length - cur_ids_length :,
517
+ ] = attention_mask_list[i]
518
+ attention_mask_list[i] = new_attention_mask.contiguous()
519
+
520
+ input_ids_list = torch.cat(input_ids_list, dim=0)
521
+ position_ids_list = torch.cat(position_ids_list, dim=0)
522
+ attention_mask_list = torch.cat(attention_mask_list, dim=0)
523
+
524
+ inputs = {
525
+ "input_ids": input_ids_list,
526
+ "position_ids": position_ids_list,
527
+ "attention_mask": attention_mask_list,
528
+ }
529
+
530
+ return BatchEncoding(inputs)
531
+ else:
532
+ return self._build_inputs_for_generation(
533
+ input_ids,
534
+ max_input_length=max_input_length,
535
+ left_truncate=left_truncate,
536
+ max_output_length=max_output_length,
537
+ rotary_type=rotary_type,
538
+ unidirectional_attention=unidirectional_attention,
539
+ **kwargs,
540
+ )
541
+
542
+ def _build_inputs_for_train(
543
+ self,
544
+ inputs: Union[str, List[str]],
545
+ outputs: Union[str, List[str]],
546
+ new_conversation_offset: List[int] = None,
547
+ max_length: int = 2048,
548
+ rotary_type: str = "1d",
549
+ left_truncate: bool = True,
550
+ unidirectional_attention: bool = True,
551
+ isolation_position_ids: bool = False,
552
+ padding: bool = True,
553
+ use_fa2: bool = True,
554
+ use_packed: bool = True,
555
+ use_baichuan_packed: bool = False,
556
+ skip_truncated_turn: bool = False,
557
+ return_attention_mask: bool = True,
558
+ ):
559
+ r"""
560
+ Build tensor input for model training. If inputs and outputs are list, will pack them.
561
+
562
+ Args:
563
+ inputs (str, List[str], List[Dict], List[List[Dict]]): the input prompts.
564
+ outputs (str, List[str]): the output responses.
565
+ max_length (int, Optional): the maximum length of the final input ids for training. Default: 2048
566
+ rotary_type (str, Optional): the rotary type of position embedding. Default: 1d
567
+ left_truncate (bool, Optional): whether truncate the inputs from left. Default: True
568
+ use_fa2 (bool, Optional): whether to build attention mask under flash attention 2.
569
+ new_conversation_offset (List[int], Optional): 第idx条样本是全新的对话,[0, 1]代表:inputs[0]和outputs[0]是一个对话,inputs[1]和outputs[1]是一个对话.
570
+ """
571
+ if use_packed and use_baichuan_packed and unidirectional_attention:
572
+ return self._build_baichuan_inputs_for_train(
573
+ inputs,
574
+ outputs,
575
+ new_conversation_offset,
576
+ max_length,
577
+ rotary_type,
578
+ left_truncate,
579
+ skip_truncated_turn,
580
+ use_fa2,
581
+ padding,
582
+ )
583
+ if isinstance(inputs, str):
584
+ inputs = [inputs]
585
+ if isinstance(outputs, str):
586
+ outputs = [outputs]
587
+
588
+ assert len(inputs) == len(outputs)
589
+
590
+ input_ids = [self(item)["input_ids"] for item in inputs]
591
+ output_ids = [self(item)["input_ids"] for item in outputs]
592
+
593
+ packed_input_ids = []
594
+ packed_output_ids = []
595
+ if new_conversation_offset is None:
596
+ new_conversation_offset = list(range(0, len(inputs)))
597
+ assert 0 in new_conversation_offset, (
598
+ f"没有0,请检查new_conversation_offset: {new_conversation_offset}"
599
+ )
600
+ current_len = 0
601
+
602
+ for idx, (input, output) in enumerate(zip(input_ids, output_ids)):
603
+ num_special_tokens = 0
604
+ if not unidirectional_attention:
605
+ if idx in new_conversation_offset:
606
+ # cls and gmask
607
+ num_special_tokens += 2
608
+ else:
609
+ # only gmask
610
+ num_special_tokens += 1
611
+ else:
612
+ # sop and eos
613
+ if self.add_bos_token:
614
+ num_special_tokens += 2
615
+ else:
616
+ num_special_tokens += 1
617
+
618
+ # truncate
619
+ if len(input) + len(output) + current_len > max_length - num_special_tokens:
620
+ if not use_packed or use_fa2 and unidirectional_attention:
621
+ attention_mask = torch.tensor(0)
622
+ elif use_fa2:
623
+ attention_mask = -1 * torch.ones([2, max_length])
624
+ else:
625
+ attention_mask = torch.tril(torch.ones([max_length, max_length]))
626
+ # 返回一个空的样本,该样本不参与训练
627
+ default_return = {
628
+ "input_ids": (torch.ones(max_length) * self.eos_token_id).long(),
629
+ "position_ids": torch.zeros(2, max_length).long(),
630
+ "attention_mask": (attention_mask.long()),
631
+ "labels": (torch.ones(max_length) * -100).long(),
632
+ }
633
+ # 如果不截断,直接返回
634
+ if skip_truncated_turn:
635
+ if current_len == 0:
636
+ return default_return
637
+ else:
638
+ break
639
+ left_len = max_length - num_special_tokens - current_len
640
+ # 如果截断,只截断prompt
641
+ if left_len - len(output) > 0:
642
+ if left_truncate:
643
+ input = input[-(left_len - len(output)) :]
644
+ else:
645
+ input = input[: left_len - len(output)]
646
+ else:
647
+ # response超过left_len,直接返回
648
+ if current_len == 0:
649
+ return default_return
650
+ else:
651
+ break
652
+ if unidirectional_attention:
653
+ packed_input_ids.append(list(input))
654
+ else:
655
+ if num_special_tokens == 4:
656
+ packed_input_ids.append(
657
+ [self.cls_token_id] + list(input) + [self.gmask_token_id]
658
+ )
659
+ else:
660
+ packed_input_ids.append(list(input) + [self.gmask_token_id])
661
+
662
+ packed_output_ids.append(list(output) + [self.eos_token_id])
663
+ current_len += len(input) + len(output) + num_special_tokens
664
+
665
+ assert current_len <= max_length
666
+
667
+ if use_packed:
668
+ # pack模式
669
+ def build_mask_matrix(seq_length, sep):
670
+ # https://github.com/pytorch/pytorch/issues/101932, fix triu/tril bf16 support
671
+ m = torch.ones((1, seq_length, seq_length))
672
+ mask = torch.arange(1, m.shape[-1] + 1).reshape(1, -1, 1).to(m.device)
673
+ ids = (
674
+ torch.arange(1, m.shape[-1] + 1)
675
+ .reshape(1, 1, -1)
676
+ .expand(1, m.shape[-1], -1)
677
+ .to(m.device)
678
+ )
679
+ m = (ids <= mask).type_as(m)
680
+
681
+ m[0, :, : int(sep)] = 1
682
+ m = m.squeeze(0)
683
+ return m
684
+
685
+ tokens = []
686
+ attention_mask_list = []
687
+ input_length_list = []
688
+ position_id_list = []
689
+ block_position_id_list = []
690
+ for input, output in zip(packed_input_ids, packed_output_ids):
691
+ if self.add_bos_token:
692
+ data = input + [self.sop_token_id] + output
693
+ mask_pos = len(input) - 1
694
+ else:
695
+ data = input + output
696
+ mask_pos = len(input) - 2
697
+ if return_attention_mask:
698
+ if unidirectional_attention:
699
+ attention_mask = build_mask_matrix(len(data), 0)
700
+ else:
701
+ attention_mask = build_mask_matrix(len(data), len(input))
702
+ attention_mask = attention_mask.squeeze((0, 1))
703
+
704
+ attention_mask_list.append(attention_mask)
705
+ input_length_list.append(len(input))
706
+ tokens += data
707
+
708
+ sop_pos = mask_pos + 1
709
+ position_ids, block_position_ids = self._build_position_ids(
710
+ mask_pos=mask_pos,
711
+ bos_pos=sop_pos,
712
+ max_output_length=len(output),
713
+ rotary_type=rotary_type,
714
+ )
715
+
716
+ position_id_list.append(position_ids)
717
+ block_position_id_list.append(block_position_ids)
718
+
719
+ labels = []
720
+ for i in range(len(packed_input_ids)):
721
+ if self.add_bos_token:
722
+ labels += (
723
+ [-100] * len(packed_input_ids[i])
724
+ + packed_output_ids[i]
725
+ + [-100]
726
+ )
727
+ else:
728
+ labels += (
729
+ [-100] * (len(packed_input_ids[i]) - 1)
730
+ + packed_output_ids[i]
731
+ + [-100]
732
+ )
733
+
734
+ total_len = 0
735
+ if use_fa2:
736
+ pack_attention_mask = -1 * torch.ones([2, current_len])
737
+ else:
738
+ pack_attention_mask = torch.tril(torch.ones([current_len, current_len]))
739
+
740
+ pack_position_ids = []
741
+ pack_block_position_ids = []
742
+ total_len = 0
743
+ max_index = 0
744
+ for i in range(len(position_id_list)):
745
+ if use_fa2:
746
+ pack_attention_mask[0][i] = total_len
747
+ pack_attention_mask[1][i] = total_len + input_length_list[i]
748
+ else:
749
+ pack_attention_mask[
750
+ total_len : total_len + attention_mask.shape[0],
751
+ total_len : total_len + attention_mask.shape[0],
752
+ ] = attention_mask
753
+ position_ids = [pid + max_index for pid in position_id_list[i]]
754
+ block_position_ids = block_position_id_list[i]
755
+ pack_position_ids.extend(position_ids)
756
+ pack_block_position_ids.extend(block_position_ids)
757
+ if not isolation_position_ids:
758
+ max_index = pack_position_ids[-1] + 1
759
+ total_len += len(position_id_list[i])
760
+ position_ids = [pack_position_ids, pack_block_position_ids]
761
+ else:
762
+ # 单输入模式
763
+ # 真多轮下,一条样本可能会有好几轮对话,此时需要获取第一条样本的结束位置
764
+ if len(new_conversation_offset) > 1:
765
+ end_idx = new_conversation_offset[1]
766
+ else:
767
+ end_idx = 1
768
+ input, output = (
769
+ list(itertools.chain(*packed_input_ids[:end_idx])),
770
+ list(itertools.chain(*packed_output_ids[:end_idx])),
771
+ )
772
+ if self.add_bos_token:
773
+ tokens = input + [self.sop_token_id] + output
774
+ else:
775
+ tokens = input + output
776
+
777
+ if self.add_bos_token:
778
+ labels = [-100] * len(input) + output + [-100]
779
+ position_ids = self._build_position_ids(
780
+ mask_pos=len(input) - 1,
781
+ bos_pos=len(input),
782
+ max_output_length=len(output),
783
+ rotary_type=rotary_type,
784
+ )
785
+ else:
786
+ labels = [-100] * (len(input) - 1) + output + [-100]
787
+ position_ids = self._build_position_ids(
788
+ mask_pos=len(input) - 2,
789
+ bos_pos=len(input) - 1,
790
+ max_output_length=len(output),
791
+ rotary_type=rotary_type,
792
+ )
793
+ attention_mask = len(input)
794
+ assert current_len == len(tokens)
795
+
796
+ # 最大长度补全
797
+ if max_length > 0 and len(tokens) < max_length and padding:
798
+ pad_length = max_length - len(tokens)
799
+ tokens += [self.pad_token_id] * pad_length
800
+ labels.extend([-100] * pad_length)
801
+ position_ids[0] += [0] * pad_length
802
+ position_ids[1] += [0] * pad_length
803
+
804
+ if use_packed:
805
+ if use_fa2:
806
+ new_attention_mask = -1 * torch.ones([2, max_length])
807
+ new_attention_mask[:, :current_len] = pack_attention_mask
808
+ else:
809
+ new_attention_mask = torch.tril(
810
+ torch.ones([max_length, max_length])
811
+ )
812
+ new_attention_mask[:current_len, :current_len] = pack_attention_mask
813
+ pack_attention_mask = new_attention_mask.contiguous()
814
+
815
+ assert len(tokens) == len(labels)
816
+
817
+ if max_length > 0 and padding:
818
+ assert len(tokens) == max_length
819
+
820
+ if use_fa2 and unidirectional_attention:
821
+ # pack_attention_mask = torch.zeros([1], dtype=torch.long)
822
+ pack_attention_mask = torch.tensor(0)
823
+
824
+ if use_packed:
825
+ if not use_fa2:
826
+ attention_mask = pack_attention_mask.unsqueeze(0).long()
827
+ else:
828
+ attention_mask = pack_attention_mask
829
+ else:
830
+ attention_mask = torch.tensor(attention_mask).long()
831
+ return {
832
+ "input_ids": torch.tensor(tokens).long(),
833
+ "position_ids": torch.tensor(position_ids).long(),
834
+ "attention_mask": attention_mask,
835
+ "labels": torch.tensor(labels).long(),
836
+ }
837
+
838
+ def _build_baichuan_inputs_for_train(
839
+ self,
840
+ inputs: Union[str, List[str]],
841
+ outputs: Union[str, List[str]],
842
+ new_conversation_offset: List[int] = None,
843
+ max_length: int = 2048,
844
+ rotary_type: str = "1d",
845
+ left_truncate: bool = True,
846
+ skip_truncated_turn: bool = True,
847
+ use_fa2: bool = True,
848
+ padding: bool = True,
849
+ ):
850
+ """
851
+ 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|>
852
+ 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
853
+ 只适用真多轮+pack数据训练单向模型,需要打开use_true_multiturn
854
+ """
855
+ if isinstance(inputs, str):
856
+ inputs = [inputs]
857
+ if isinstance(outputs, str):
858
+ outputs = [outputs]
859
+ assert len(inputs) == len(outputs)
860
+
861
+ input_ids = [self(item)["input_ids"] for item in inputs]
862
+ output_ids = [self(item)["input_ids"] for item in outputs]
863
+
864
+ packed_input_ids = []
865
+ packed_output_ids = []
866
+
867
+ if new_conversation_offset is None:
868
+ new_conversation_offset = list(range(0, len(inputs)))
869
+ assert 0 in new_conversation_offset, (
870
+ f"没有0,请检查new_conversation_offset: {new_conversation_offset}"
871
+ )
872
+ current_len = 0
873
+
874
+ for idx, (input, output) in enumerate(zip(input_ids, output_ids)):
875
+ num_special_tokens = 0
876
+ if idx != 0 and idx in new_conversation_offset:
877
+ # 在input_ids加入eos,只有第0条样本不加
878
+ num_special_tokens += 1
879
+
880
+ # truncate
881
+ if len(input) + len(output) + current_len > max_length - num_special_tokens:
882
+ if use_fa2:
883
+ attention_mask = torch.tensor(0)
884
+ else:
885
+ attention_mask = torch.tril(torch.ones([max_length, max_length]))
886
+ # 返回一个空的样本,该样本不参与训练
887
+ default_return = {
888
+ "input_ids": (torch.ones(max_length) * self.eos_token_id).long(),
889
+ "position_ids": torch.zeros(2, max_length).long(),
890
+ "attention_mask": (attention_mask.long()),
891
+ "labels": (torch.ones(max_length) * -100).long(),
892
+ }
893
+
894
+ # 如果不截断,直接返回
895
+ if skip_truncated_turn:
896
+ if current_len == 0:
897
+ return default_return
898
+ else:
899
+ break
900
+ left_len = max_length - num_special_tokens - current_len
901
+ # 如果截断,只截断prompt
902
+ if left_len - len(output) > 0:
903
+ if left_truncate:
904
+ input = input[-(left_len - len(output)) :]
905
+ else:
906
+ input = input[: left_len - len(output)]
907
+ else:
908
+ # response超过left_len,直接返回
909
+ if current_len == 0:
910
+ return default_return
911
+ else:
912
+ break
913
+ # 这里拼的是input_ids
914
+ if num_special_tokens == 1:
915
+ packed_input_ids.append([self.eos_token_id] + list(input))
916
+ else:
917
+ packed_input_ids.append(list(input))
918
+ packed_output_ids.append(list(output))
919
+ current_len += len(input) + len(output) + num_special_tokens
920
+ assert current_len <= max_length
921
+
922
+ def build_mask_matrix(seq_length, sep):
923
+ # https://github.com/pytorch/pytorch/issues/101932, fix triu/tril bf16 support
924
+ m = torch.ones((1, seq_length, seq_length))
925
+ mask = torch.arange(1, m.shape[-1] + 1).reshape(1, -1, 1).to(m.device)
926
+ ids = (
927
+ torch.arange(1, m.shape[-1] + 1)
928
+ .reshape(1, 1, -1)
929
+ .expand(1, m.shape[-1], -1)
930
+ .to(m.device)
931
+ )
932
+ m = (ids <= mask).type_as(m)
933
+
934
+ m[0, :, : int(sep)] = 1
935
+ m = m.squeeze(0)
936
+ return m
937
+
938
+ tokens = []
939
+ attention_mask_list = []
940
+ position_id_list = []
941
+ block_position_id_list = []
942
+ token_lens = []
943
+ for input, output in zip(packed_input_ids, packed_output_ids):
944
+ data = input + output
945
+ if not use_fa2:
946
+ attention_mask = build_mask_matrix(len(data), 0)
947
+ attention_mask_list.append(attention_mask)
948
+ tokens += data
949
+ token_lens.append(len(data))
950
+
951
+ position_ids, block_position_ids = self._build_position_ids(
952
+ mask_pos=len(input) - 2,
953
+ bos_pos=len(input) - 1,
954
+ max_output_length=len(output),
955
+ rotary_type=rotary_type,
956
+ )
957
+
958
+ position_id_list.append(position_ids)
959
+ block_position_id_list.append(block_position_ids)
960
+
961
+ labels = []
962
+ for i in range(len(packed_input_ids)):
963
+ labels += (
964
+ [-100] * (len(packed_input_ids[i]) - 1)
965
+ + packed_output_ids[i]
966
+ + [self.eos_token_id]
967
+ )
968
+
969
+ total_len = 0
970
+ if use_fa2:
971
+ pack_attention_mask = torch.Tensor([[0], [1]])
972
+ else:
973
+ pack_attention_mask = torch.tril(torch.ones([max_length, max_length]))
974
+
975
+ pack_position_ids = []
976
+ pack_block_position_ids = []
977
+ total_len = 0
978
+ max_index = 0
979
+ for i in range(len(token_lens)):
980
+ if not use_fa2:
981
+ attention_mask = attention_mask_list[i]
982
+ pack_attention_mask[
983
+ total_len : total_len + attention_mask.shape[0],
984
+ total_len : total_len + attention_mask.shape[0],
985
+ ] = attention_mask
986
+ position_ids = [pid + max_index for pid in position_id_list[i]]
987
+ block_position_ids = block_position_id_list[i]
988
+ pack_position_ids.extend(position_ids)
989
+ pack_block_position_ids.extend(block_position_ids)
990
+ max_index = pack_position_ids[-1] + 1
991
+ total_len += token_lens[i]
992
+ position_ids = [pack_position_ids, pack_block_position_ids]
993
+
994
+ if max_length > 0 and len(tokens) < max_length and padding:
995
+ pad_length = max_length - len(tokens)
996
+ tokens += [self.pad_token_id] * pad_length
997
+ labels.extend([-100] * pad_length)
998
+ position_ids[0] += [0] * pad_length
999
+ position_ids[1] += [0] * pad_length
1000
+
1001
+ assert len(tokens) == len(labels)
1002
+
1003
+ if not use_fa2:
1004
+ attention_mask = pack_attention_mask.unsqueeze(0).long()
1005
+ else:
1006
+ attention_mask = torch.tensor(0)
1007
+ return {
1008
+ "input_ids": torch.tensor(tokens).long(),
1009
+ "position_ids": torch.tensor(position_ids).long(),
1010
+ "attention_mask": attention_mask,
1011
+ "labels": torch.tensor(labels).long(),
1012
+ }
1013
+
1014
+ def build_inputs_for_train(
1015
+ self,
1016
+ data: Union[Dict, List[Dict]],
1017
+ new_conversation_offset: List[int] = None,
1018
+ chat_format="antglm_chat",
1019
+ is_chat_format=True, # 如果传入的是字符串,用于说明是否已经是
1020
+ use_true_multiturn=False,
1021
+ max_length: int = 2048,
1022
+ rotary_type: str = "1d",
1023
+ left_truncate: bool = True,
1024
+ unidirectional_attention: bool = True,
1025
+ isolation_position_ids: bool = False,
1026
+ padding: bool = True,
1027
+ use_fa2: bool = True,
1028
+ use_packed: bool = True,
1029
+ use_baichuan_packed: bool = False,
1030
+ skip_truncated_turn: bool = False,
1031
+ return_attention_mask: bool = True,
1032
+ ):
1033
+ r"""
1034
+ Build tensor input for model training. If inputs and outputs are list, will pack them.
1035
+
1036
+ Args:
1037
+ inputs (str, List[str], List[Dict], List[List[Dict]]): the input prompts.
1038
+ outputs (str, List[str]): the output responses.
1039
+ new_conversation_offset (List[int]): the offset index of the new conversation turn.
1040
+ is_chat_format (bool): whether the input is already chatml format
1041
+ max_length (int, Optional): the maximum length of the final input ids for training. Default: 2048
1042
+ rotary_type (str, Optional): the rotary type of position embedding. Default: 1d
1043
+ left_truncate (bool, Optional): whether truncate the inputs from left. Default: True
1044
+ use_fa2 (bool, Optional): whether to build attention mask under flash attention 2.
1045
+ """
1046
+ if isinstance(data, List):
1047
+ # chatml list
1048
+ _inputs = []
1049
+ _outputs = []
1050
+ new_conversation_offset = []
1051
+ for _input in data:
1052
+ if use_true_multiturn:
1053
+ chat = self._chat_from_json(_input, chat_format=chat_format)
1054
+ chat_data = chat.prompt_pack
1055
+ new_conversation_offset.append(len(_inputs))
1056
+ _inputs.extend(chat_data["input"])
1057
+ _outputs.extend(chat_data["output"])
1058
+ else:
1059
+ _conversation = _convert_to_conversation(_input)
1060
+ assert is_assistant(_conversation[-1])
1061
+
1062
+ _inputs.append(
1063
+ self.apply_chat_template(
1064
+ _conversation[:-1],
1065
+ tokenize=False,
1066
+ add_generation_prompt=True,
1067
+ )
1068
+ )
1069
+ _outputs.append(_conversation[-1]["content"])
1070
+
1071
+ return self._build_inputs_for_train(
1072
+ inputs=_inputs,
1073
+ outputs=_outputs,
1074
+ new_conversation_offset=new_conversation_offset,
1075
+ max_length=max_length,
1076
+ rotary_type=rotary_type,
1077
+ left_truncate=left_truncate,
1078
+ unidirectional_attention=unidirectional_attention,
1079
+ isolation_position_ids=isolation_position_ids,
1080
+ padding=padding,
1081
+ use_fa2=use_fa2,
1082
+ use_packed=use_packed,
1083
+ use_baichuan_packed=use_baichuan_packed,
1084
+ skip_truncated_turn=skip_truncated_turn,
1085
+ return_attention_mask=return_attention_mask,
1086
+ )
1087
+ elif isinstance(data, Dict):
1088
+ if "messages" in data:
1089
+ # chatml format
1090
+ if use_true_multiturn:
1091
+ chat = self._chat_from_json(data, chat_format=chat_format)
1092
+ chat_data = chat.prompt_pack
1093
+ else:
1094
+ _conversation = _convert_to_conversation(data)
1095
+ assert is_assistant(_conversation[-1])
1096
+
1097
+ chat_data = {
1098
+ "input": self.apply_chat_template(
1099
+ _conversation[:-1],
1100
+ tokenize=False,
1101
+ add_generation_prompt=True,
1102
+ ),
1103
+ "output": _conversation[-1]["content"],
1104
+ }
1105
+
1106
+ return self._build_inputs_for_train(
1107
+ inputs=chat_data["input"],
1108
+ outputs=chat_data["output"],
1109
+ max_length=max_length,
1110
+ rotary_type=rotary_type,
1111
+ left_truncate=left_truncate,
1112
+ unidirectional_attention=unidirectional_attention,
1113
+ isolation_position_ids=isolation_position_ids,
1114
+ padding=padding,
1115
+ use_fa2=use_fa2,
1116
+ use_packed=use_packed,
1117
+ use_baichuan_packed=use_baichuan_packed,
1118
+ skip_truncated_turn=skip_truncated_turn,
1119
+ return_attention_mask=return_attention_mask,
1120
+ )
1121
+ else:
1122
+ inputs = data["input"]
1123
+ outputs = data["output"]
1124
+
1125
+ if isinstance(inputs, str):
1126
+ inputs = [inputs]
1127
+ if isinstance(outputs, str):
1128
+ outputs = [outputs]
1129
+
1130
+ if not is_chat_format and chat_format:
1131
+ inputs = [
1132
+ self.apply_chat_template(
1133
+ [{"role": "HUMAN", "content": item}],
1134
+ tokenize=False,
1135
+ chat_format=chat_format,
1136
+ )
1137
+ for item in inputs
1138
+ ]
1139
+
1140
+ return self._build_inputs_for_train(
1141
+ inputs=inputs,
1142
+ outputs=outputs,
1143
+ new_conversation_offset=new_conversation_offset,
1144
+ max_length=max_length,
1145
+ rotary_type=rotary_type,
1146
+ left_truncate=left_truncate,
1147
+ unidirectional_attention=unidirectional_attention,
1148
+ isolation_position_ids=isolation_position_ids,
1149
+ padding=padding,
1150
+ use_fa2=use_fa2,
1151
+ use_packed=use_packed,
1152
+ use_baichuan_packed=use_baichuan_packed,
1153
+ skip_truncated_turn=skip_truncated_turn,
1154
+ return_attention_mask=return_attention_mask,
1155
+ )
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e4f5fe09e7484071da5fa93cfb82f7db15c0ebf9b6ee9821599c5a997563ee96
3
+ size 12210708
tokenizer_config.json ADDED
@@ -0,0 +1,2342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "added_tokens_decoder": {
5
+ "156891": {
6
+ "content": "<|startoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "156892": {
14
+ "content": "<|endoftext|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "156893": {
22
+ "content": "[CLS]",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "156894": {
30
+ "content": "[gMASK]",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "156895": {
38
+ "content": "<|role_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "156896": {
46
+ "content": "<tool_call>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "156897": {
54
+ "content": "</tool_call>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "156898": {
62
+ "content": "<tool_response>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "156899": {
70
+ "content": "</tool_response>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "156900": {
78
+ "content": "<|reserved_token_5|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "156901": {
86
+ "content": "<|reserved_token_6|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "156902": {
94
+ "content": "<|reserved_token_7|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "156903": {
102
+ "content": "<|reserved_token_8|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "156904": {
110
+ "content": "<|reserved_token_9|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "156905": {
118
+ "content": "<|reserved_token_10|>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": true
124
+ },
125
+ "156906": {
126
+ "content": "<|reserved_token_11|>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": true
132
+ },
133
+ "156907": {
134
+ "content": "<|reserved_token_12|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": true
140
+ },
141
+ "156908": {
142
+ "content": "<|reserved_token_13|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": true
148
+ },
149
+ "156909": {
150
+ "content": "<|reserved_token_14|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": true
156
+ },
157
+ "156910": {
158
+ "content": "<|reserved_token_15|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": true
164
+ },
165
+ "156911": {
166
+ "content": "<|reserved_token_16|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": true
172
+ },
173
+ "156912": {
174
+ "content": "<|reserved_token_17|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": true
180
+ },
181
+ "156913": {
182
+ "content": "<|reserved_token_18|>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": true
188
+ },
189
+ "156914": {
190
+ "content": "<|reserved_token_19|>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": true
196
+ },
197
+ "156915": {
198
+ "content": "<|reserved_token_20|>",
199
+ "lstrip": false,
200
+ "normalized": false,
201
+ "rstrip": false,
202
+ "single_word": false,
203
+ "special": true
204
+ },
205
+ "156916": {
206
+ "content": "<|reserved_token_21|>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": false,
210
+ "single_word": false,
211
+ "special": true
212
+ },
213
+ "156917": {
214
+ "content": "<|reserved_token_22|>",
215
+ "lstrip": false,
216
+ "normalized": false,
217
+ "rstrip": false,
218
+ "single_word": false,
219
+ "special": true
220
+ },
221
+ "156918": {
222
+ "content": "<|reserved_token_23|>",
223
+ "lstrip": false,
224
+ "normalized": false,
225
+ "rstrip": false,
226
+ "single_word": false,
227
+ "special": true
228
+ },
229
+ "156919": {
230
+ "content": "<|reserved_token_24|>",
231
+ "lstrip": false,
232
+ "normalized": false,
233
+ "rstrip": false,
234
+ "single_word": false,
235
+ "special": true
236
+ },
237
+ "156920": {
238
+ "content": "<|reserved_token_25|>",
239
+ "lstrip": false,
240
+ "normalized": false,
241
+ "rstrip": false,
242
+ "single_word": false,
243
+ "special": true
244
+ },
245
+ "156921": {
246
+ "content": "<|reserved_token_26|>",
247
+ "lstrip": false,
248
+ "normalized": false,
249
+ "rstrip": false,
250
+ "single_word": false,
251
+ "special": true
252
+ },
253
+ "156922": {
254
+ "content": "<|reserved_token_27|>",
255
+ "lstrip": false,
256
+ "normalized": false,
257
+ "rstrip": false,
258
+ "single_word": false,
259
+ "special": true
260
+ },
261
+ "156923": {
262
+ "content": "<|reserved_token_28|>",
263
+ "lstrip": false,
264
+ "normalized": false,
265
+ "rstrip": false,
266
+ "single_word": false,
267
+ "special": true
268
+ },
269
+ "156924": {
270
+ "content": "<|reserved_token_29|>",
271
+ "lstrip": false,
272
+ "normalized": false,
273
+ "rstrip": false,
274
+ "single_word": false,
275
+ "special": true
276
+ },
277
+ "156925": {
278
+ "content": "<|reserved_token_30|>",
279
+ "lstrip": false,
280
+ "normalized": false,
281
+ "rstrip": false,
282
+ "single_word": false,
283
+ "special": true
284
+ },
285
+ "156926": {
286
+ "content": "<|reserved_token_31|>",
287
+ "lstrip": false,
288
+ "normalized": false,
289
+ "rstrip": false,
290
+ "single_word": false,
291
+ "special": true
292
+ },
293
+ "156927": {
294
+ "content": "<|reserved_token_32|>",
295
+ "lstrip": false,
296
+ "normalized": false,
297
+ "rstrip": false,
298
+ "single_word": false,
299
+ "special": true
300
+ },
301
+ "156928": {
302
+ "content": "<|reserved_token_33|>",
303
+ "lstrip": false,
304
+ "normalized": false,
305
+ "rstrip": false,
306
+ "single_word": false,
307
+ "special": true
308
+ },
309
+ "156929": {
310
+ "content": "<|reserved_token_34|>",
311
+ "lstrip": false,
312
+ "normalized": false,
313
+ "rstrip": false,
314
+ "single_word": false,
315
+ "special": true
316
+ },
317
+ "156930": {
318
+ "content": "<|reserved_token_35|>",
319
+ "lstrip": false,
320
+ "normalized": false,
321
+ "rstrip": false,
322
+ "single_word": false,
323
+ "special": true
324
+ },
325
+ "156931": {
326
+ "content": "<|reserved_token_36|>",
327
+ "lstrip": false,
328
+ "normalized": false,
329
+ "rstrip": false,
330
+ "single_word": false,
331
+ "special": true
332
+ },
333
+ "156932": {
334
+ "content": "<|reserved_token_37|>",
335
+ "lstrip": false,
336
+ "normalized": false,
337
+ "rstrip": false,
338
+ "single_word": false,
339
+ "special": true
340
+ },
341
+ "156933": {
342
+ "content": "<|reserved_token_38|>",
343
+ "lstrip": false,
344
+ "normalized": false,
345
+ "rstrip": false,
346
+ "single_word": false,
347
+ "special": true
348
+ },
349
+ "156934": {
350
+ "content": "<|reserved_token_39|>",
351
+ "lstrip": false,
352
+ "normalized": false,
353
+ "rstrip": false,
354
+ "single_word": false,
355
+ "special": true
356
+ },
357
+ "156935": {
358
+ "content": "<|reserved_token_40|>",
359
+ "lstrip": false,
360
+ "normalized": false,
361
+ "rstrip": false,
362
+ "single_word": false,
363
+ "special": true
364
+ },
365
+ "156936": {
366
+ "content": "<|reserved_token_41|>",
367
+ "lstrip": false,
368
+ "normalized": false,
369
+ "rstrip": false,
370
+ "single_word": false,
371
+ "special": true
372
+ },
373
+ "156937": {
374
+ "content": "<|reserved_token_42|>",
375
+ "lstrip": false,
376
+ "normalized": false,
377
+ "rstrip": false,
378
+ "single_word": false,
379
+ "special": true
380
+ },
381
+ "156938": {
382
+ "content": "<|reserved_token_43|>",
383
+ "lstrip": false,
384
+ "normalized": false,
385
+ "rstrip": false,
386
+ "single_word": false,
387
+ "special": true
388
+ },
389
+ "156939": {
390
+ "content": "<|reserved_token_44|>",
391
+ "lstrip": false,
392
+ "normalized": false,
393
+ "rstrip": false,
394
+ "single_word": false,
395
+ "special": true
396
+ },
397
+ "156940": {
398
+ "content": "<|reserved_token_45|>",
399
+ "lstrip": false,
400
+ "normalized": false,
401
+ "rstrip": false,
402
+ "single_word": false,
403
+ "special": true
404
+ },
405
+ "156941": {
406
+ "content": "<|reserved_token_46|>",
407
+ "lstrip": false,
408
+ "normalized": false,
409
+ "rstrip": false,
410
+ "single_word": false,
411
+ "special": true
412
+ },
413
+ "156942": {
414
+ "content": "<|reserved_token_47|>",
415
+ "lstrip": false,
416
+ "normalized": false,
417
+ "rstrip": false,
418
+ "single_word": false,
419
+ "special": true
420
+ },
421
+ "156943": {
422
+ "content": "<|reserved_token_48|>",
423
+ "lstrip": false,
424
+ "normalized": false,
425
+ "rstrip": false,
426
+ "single_word": false,
427
+ "special": true
428
+ },
429
+ "156944": {
430
+ "content": "<|reserved_token_49|>",
431
+ "lstrip": false,
432
+ "normalized": false,
433
+ "rstrip": false,
434
+ "single_word": false,
435
+ "special": true
436
+ },
437
+ "156945": {
438
+ "content": "<|reserved_token_50|>",
439
+ "lstrip": false,
440
+ "normalized": false,
441
+ "rstrip": false,
442
+ "single_word": false,
443
+ "special": true
444
+ },
445
+ "156946": {
446
+ "content": "<|reserved_token_51|>",
447
+ "lstrip": false,
448
+ "normalized": false,
449
+ "rstrip": false,
450
+ "single_word": false,
451
+ "special": true
452
+ },
453
+ "156947": {
454
+ "content": "<|reserved_token_52|>",
455
+ "lstrip": false,
456
+ "normalized": false,
457
+ "rstrip": false,
458
+ "single_word": false,
459
+ "special": true
460
+ },
461
+ "156948": {
462
+ "content": "<|reserved_token_53|>",
463
+ "lstrip": false,
464
+ "normalized": false,
465
+ "rstrip": false,
466
+ "single_word": false,
467
+ "special": true
468
+ },
469
+ "156949": {
470
+ "content": "<|reserved_token_54|>",
471
+ "lstrip": false,
472
+ "normalized": false,
473
+ "rstrip": false,
474
+ "single_word": false,
475
+ "special": true
476
+ },
477
+ "156950": {
478
+ "content": "<|reserved_token_55|>",
479
+ "lstrip": false,
480
+ "normalized": false,
481
+ "rstrip": false,
482
+ "single_word": false,
483
+ "special": true
484
+ },
485
+ "156951": {
486
+ "content": "<|reserved_token_56|>",
487
+ "lstrip": false,
488
+ "normalized": false,
489
+ "rstrip": false,
490
+ "single_word": false,
491
+ "special": true
492
+ },
493
+ "156952": {
494
+ "content": "<|reserved_token_57|>",
495
+ "lstrip": false,
496
+ "normalized": false,
497
+ "rstrip": false,
498
+ "single_word": false,
499
+ "special": true
500
+ },
501
+ "156953": {
502
+ "content": "<|reserved_token_58|>",
503
+ "lstrip": false,
504
+ "normalized": false,
505
+ "rstrip": false,
506
+ "single_word": false,
507
+ "special": true
508
+ },
509
+ "156954": {
510
+ "content": "<|reserved_token_59|>",
511
+ "lstrip": false,
512
+ "normalized": false,
513
+ "rstrip": false,
514
+ "single_word": false,
515
+ "special": true
516
+ },
517
+ "156955": {
518
+ "content": "<|reserved_token_60|>",
519
+ "lstrip": false,
520
+ "normalized": false,
521
+ "rstrip": false,
522
+ "single_word": false,
523
+ "special": true
524
+ },
525
+ "156956": {
526
+ "content": "<|reserved_token_61|>",
527
+ "lstrip": false,
528
+ "normalized": false,
529
+ "rstrip": false,
530
+ "single_word": false,
531
+ "special": true
532
+ },
533
+ "156957": {
534
+ "content": "<|reserved_token_62|>",
535
+ "lstrip": false,
536
+ "normalized": false,
537
+ "rstrip": false,
538
+ "single_word": false,
539
+ "special": true
540
+ },
541
+ "156958": {
542
+ "content": "<|reserved_token_63|>",
543
+ "lstrip": false,
544
+ "normalized": false,
545
+ "rstrip": false,
546
+ "single_word": false,
547
+ "special": true
548
+ },
549
+ "156959": {
550
+ "content": "<|reserved_token_64|>",
551
+ "lstrip": false,
552
+ "normalized": false,
553
+ "rstrip": false,
554
+ "single_word": false,
555
+ "special": true
556
+ },
557
+ "156960": {
558
+ "content": "<|reserved_token_65|>",
559
+ "lstrip": false,
560
+ "normalized": false,
561
+ "rstrip": false,
562
+ "single_word": false,
563
+ "special": true
564
+ },
565
+ "156961": {
566
+ "content": "<|reserved_token_66|>",
567
+ "lstrip": false,
568
+ "normalized": false,
569
+ "rstrip": false,
570
+ "single_word": false,
571
+ "special": true
572
+ },
573
+ "156962": {
574
+ "content": "<|reserved_token_67|>",
575
+ "lstrip": false,
576
+ "normalized": false,
577
+ "rstrip": false,
578
+ "single_word": false,
579
+ "special": true
580
+ },
581
+ "156963": {
582
+ "content": "<|reserved_token_68|>",
583
+ "lstrip": false,
584
+ "normalized": false,
585
+ "rstrip": false,
586
+ "single_word": false,
587
+ "special": true
588
+ },
589
+ "156964": {
590
+ "content": "<|reserved_token_69|>",
591
+ "lstrip": false,
592
+ "normalized": false,
593
+ "rstrip": false,
594
+ "single_word": false,
595
+ "special": true
596
+ },
597
+ "156965": {
598
+ "content": "<|reserved_token_70|>",
599
+ "lstrip": false,
600
+ "normalized": false,
601
+ "rstrip": false,
602
+ "single_word": false,
603
+ "special": true
604
+ },
605
+ "156966": {
606
+ "content": "<|reserved_token_71|>",
607
+ "lstrip": false,
608
+ "normalized": false,
609
+ "rstrip": false,
610
+ "single_word": false,
611
+ "special": true
612
+ },
613
+ "156967": {
614
+ "content": "<|reserved_token_72|>",
615
+ "lstrip": false,
616
+ "normalized": false,
617
+ "rstrip": false,
618
+ "single_word": false,
619
+ "special": true
620
+ },
621
+ "156968": {
622
+ "content": "<|reserved_token_73|>",
623
+ "lstrip": false,
624
+ "normalized": false,
625
+ "rstrip": false,
626
+ "single_word": false,
627
+ "special": true
628
+ },
629
+ "156969": {
630
+ "content": "<|reserved_token_74|>",
631
+ "lstrip": false,
632
+ "normalized": false,
633
+ "rstrip": false,
634
+ "single_word": false,
635
+ "special": true
636
+ },
637
+ "156970": {
638
+ "content": "<|reserved_token_75|>",
639
+ "lstrip": false,
640
+ "normalized": false,
641
+ "rstrip": false,
642
+ "single_word": false,
643
+ "special": true
644
+ },
645
+ "156971": {
646
+ "content": "<|reserved_token_76|>",
647
+ "lstrip": false,
648
+ "normalized": false,
649
+ "rstrip": false,
650
+ "single_word": false,
651
+ "special": true
652
+ },
653
+ "156972": {
654
+ "content": "<|reserved_token_77|>",
655
+ "lstrip": false,
656
+ "normalized": false,
657
+ "rstrip": false,
658
+ "single_word": false,
659
+ "special": true
660
+ },
661
+ "156973": {
662
+ "content": "<|reserved_token_78|>",
663
+ "lstrip": false,
664
+ "normalized": false,
665
+ "rstrip": false,
666
+ "single_word": false,
667
+ "special": true
668
+ },
669
+ "156974": {
670
+ "content": "<|reserved_token_79|>",
671
+ "lstrip": false,
672
+ "normalized": false,
673
+ "rstrip": false,
674
+ "single_word": false,
675
+ "special": true
676
+ },
677
+ "156975": {
678
+ "content": "<|reserved_token_80|>",
679
+ "lstrip": false,
680
+ "normalized": false,
681
+ "rstrip": false,
682
+ "single_word": false,
683
+ "special": true
684
+ },
685
+ "156976": {
686
+ "content": "<|reserved_token_81|>",
687
+ "lstrip": false,
688
+ "normalized": false,
689
+ "rstrip": false,
690
+ "single_word": false,
691
+ "special": true
692
+ },
693
+ "156977": {
694
+ "content": "<|reserved_token_82|>",
695
+ "lstrip": false,
696
+ "normalized": false,
697
+ "rstrip": false,
698
+ "single_word": false,
699
+ "special": true
700
+ },
701
+ "156978": {
702
+ "content": "<|reserved_token_83|>",
703
+ "lstrip": false,
704
+ "normalized": false,
705
+ "rstrip": false,
706
+ "single_word": false,
707
+ "special": true
708
+ },
709
+ "156979": {
710
+ "content": "<|reserved_token_84|>",
711
+ "lstrip": false,
712
+ "normalized": false,
713
+ "rstrip": false,
714
+ "single_word": false,
715
+ "special": true
716
+ },
717
+ "156980": {
718
+ "content": "<|reserved_token_85|>",
719
+ "lstrip": false,
720
+ "normalized": false,
721
+ "rstrip": false,
722
+ "single_word": false,
723
+ "special": true
724
+ },
725
+ "156981": {
726
+ "content": "<|reserved_token_86|>",
727
+ "lstrip": false,
728
+ "normalized": false,
729
+ "rstrip": false,
730
+ "single_word": false,
731
+ "special": true
732
+ },
733
+ "156982": {
734
+ "content": "<|reserved_token_87|>",
735
+ "lstrip": false,
736
+ "normalized": false,
737
+ "rstrip": false,
738
+ "single_word": false,
739
+ "special": true
740
+ },
741
+ "156983": {
742
+ "content": "<|reserved_token_88|>",
743
+ "lstrip": false,
744
+ "normalized": false,
745
+ "rstrip": false,
746
+ "single_word": false,
747
+ "special": true
748
+ },
749
+ "156984": {
750
+ "content": "<|reserved_token_89|>",
751
+ "lstrip": false,
752
+ "normalized": false,
753
+ "rstrip": false,
754
+ "single_word": false,
755
+ "special": true
756
+ },
757
+ "156985": {
758
+ "content": "<|reserved_token_90|>",
759
+ "lstrip": false,
760
+ "normalized": false,
761
+ "rstrip": false,
762
+ "single_word": false,
763
+ "special": true
764
+ },
765
+ "156986": {
766
+ "content": "<|reserved_token_91|>",
767
+ "lstrip": false,
768
+ "normalized": false,
769
+ "rstrip": false,
770
+ "single_word": false,
771
+ "special": true
772
+ },
773
+ "156987": {
774
+ "content": "<|reserved_token_92|>",
775
+ "lstrip": false,
776
+ "normalized": false,
777
+ "rstrip": false,
778
+ "single_word": false,
779
+ "special": true
780
+ },
781
+ "156988": {
782
+ "content": "<|reserved_token_93|>",
783
+ "lstrip": false,
784
+ "normalized": false,
785
+ "rstrip": false,
786
+ "single_word": false,
787
+ "special": true
788
+ },
789
+ "156989": {
790
+ "content": "<|reserved_token_94|>",
791
+ "lstrip": false,
792
+ "normalized": false,
793
+ "rstrip": false,
794
+ "single_word": false,
795
+ "special": true
796
+ },
797
+ "156990": {
798
+ "content": "<|reserved_token_95|>",
799
+ "lstrip": false,
800
+ "normalized": false,
801
+ "rstrip": false,
802
+ "single_word": false,
803
+ "special": true
804
+ },
805
+ "156991": {
806
+ "content": "<|reserved_token_96|>",
807
+ "lstrip": false,
808
+ "normalized": false,
809
+ "rstrip": false,
810
+ "single_word": false,
811
+ "special": true
812
+ },
813
+ "156992": {
814
+ "content": "<|reserved_token_97|>",
815
+ "lstrip": false,
816
+ "normalized": false,
817
+ "rstrip": false,
818
+ "single_word": false,
819
+ "special": true
820
+ },
821
+ "156993": {
822
+ "content": "<|reserved_token_98|>",
823
+ "lstrip": false,
824
+ "normalized": false,
825
+ "rstrip": false,
826
+ "single_word": false,
827
+ "special": true
828
+ },
829
+ "156994": {
830
+ "content": "<|reserved_token_99|>",
831
+ "lstrip": false,
832
+ "normalized": false,
833
+ "rstrip": false,
834
+ "single_word": false,
835
+ "special": true
836
+ },
837
+ "156995": {
838
+ "content": "<|reserved_token_100|>",
839
+ "lstrip": false,
840
+ "normalized": false,
841
+ "rstrip": false,
842
+ "single_word": false,
843
+ "special": true
844
+ },
845
+ "156996": {
846
+ "content": "<|reserved_token_101|>",
847
+ "lstrip": false,
848
+ "normalized": false,
849
+ "rstrip": false,
850
+ "single_word": false,
851
+ "special": true
852
+ },
853
+ "156997": {
854
+ "content": "<|reserved_token_102|>",
855
+ "lstrip": false,
856
+ "normalized": false,
857
+ "rstrip": false,
858
+ "single_word": false,
859
+ "special": true
860
+ },
861
+ "156998": {
862
+ "content": "<|reserved_token_103|>",
863
+ "lstrip": false,
864
+ "normalized": false,
865
+ "rstrip": false,
866
+ "single_word": false,
867
+ "special": true
868
+ },
869
+ "156999": {
870
+ "content": "<|reserved_token_104|>",
871
+ "lstrip": false,
872
+ "normalized": false,
873
+ "rstrip": false,
874
+ "single_word": false,
875
+ "special": true
876
+ },
877
+ "157000": {
878
+ "content": "<|reserved_token_105|>",
879
+ "lstrip": false,
880
+ "normalized": false,
881
+ "rstrip": false,
882
+ "single_word": false,
883
+ "special": true
884
+ },
885
+ "157001": {
886
+ "content": "<|reserved_token_106|>",
887
+ "lstrip": false,
888
+ "normalized": false,
889
+ "rstrip": false,
890
+ "single_word": false,
891
+ "special": true
892
+ },
893
+ "157002": {
894
+ "content": "<|reserved_token_107|>",
895
+ "lstrip": false,
896
+ "normalized": false,
897
+ "rstrip": false,
898
+ "single_word": false,
899
+ "special": true
900
+ },
901
+ "157003": {
902
+ "content": "<|reserved_token_108|>",
903
+ "lstrip": false,
904
+ "normalized": false,
905
+ "rstrip": false,
906
+ "single_word": false,
907
+ "special": true
908
+ },
909
+ "157004": {
910
+ "content": "<|reserved_token_109|>",
911
+ "lstrip": false,
912
+ "normalized": false,
913
+ "rstrip": false,
914
+ "single_word": false,
915
+ "special": true
916
+ },
917
+ "157005": {
918
+ "content": "<|reserved_token_110|>",
919
+ "lstrip": false,
920
+ "normalized": false,
921
+ "rstrip": false,
922
+ "single_word": false,
923
+ "special": true
924
+ },
925
+ "157006": {
926
+ "content": "<|reserved_token_111|>",
927
+ "lstrip": false,
928
+ "normalized": false,
929
+ "rstrip": false,
930
+ "single_word": false,
931
+ "special": true
932
+ },
933
+ "157007": {
934
+ "content": "<|reserved_token_112|>",
935
+ "lstrip": false,
936
+ "normalized": false,
937
+ "rstrip": false,
938
+ "single_word": false,
939
+ "special": true
940
+ },
941
+ "157008": {
942
+ "content": "<|reserved_token_113|>",
943
+ "lstrip": false,
944
+ "normalized": false,
945
+ "rstrip": false,
946
+ "single_word": false,
947
+ "special": true
948
+ },
949
+ "157009": {
950
+ "content": "<|reserved_token_114|>",
951
+ "lstrip": false,
952
+ "normalized": false,
953
+ "rstrip": false,
954
+ "single_word": false,
955
+ "special": true
956
+ },
957
+ "157010": {
958
+ "content": "<|reserved_token_115|>",
959
+ "lstrip": false,
960
+ "normalized": false,
961
+ "rstrip": false,
962
+ "single_word": false,
963
+ "special": true
964
+ },
965
+ "157011": {
966
+ "content": "<|reserved_token_116|>",
967
+ "lstrip": false,
968
+ "normalized": false,
969
+ "rstrip": false,
970
+ "single_word": false,
971
+ "special": true
972
+ },
973
+ "157012": {
974
+ "content": "<|reserved_token_117|>",
975
+ "lstrip": false,
976
+ "normalized": false,
977
+ "rstrip": false,
978
+ "single_word": false,
979
+ "special": true
980
+ },
981
+ "157013": {
982
+ "content": "<|reserved_token_118|>",
983
+ "lstrip": false,
984
+ "normalized": false,
985
+ "rstrip": false,
986
+ "single_word": false,
987
+ "special": true
988
+ },
989
+ "157014": {
990
+ "content": "<|reserved_token_119|>",
991
+ "lstrip": false,
992
+ "normalized": false,
993
+ "rstrip": false,
994
+ "single_word": false,
995
+ "special": true
996
+ },
997
+ "157015": {
998
+ "content": "<|reserved_token_120|>",
999
+ "lstrip": false,
1000
+ "normalized": false,
1001
+ "rstrip": false,
1002
+ "single_word": false,
1003
+ "special": true
1004
+ },
1005
+ "157016": {
1006
+ "content": "<|reserved_token_121|>",
1007
+ "lstrip": false,
1008
+ "normalized": false,
1009
+ "rstrip": false,
1010
+ "single_word": false,
1011
+ "special": true
1012
+ },
1013
+ "157017": {
1014
+ "content": "<|reserved_token_122|>",
1015
+ "lstrip": false,
1016
+ "normalized": false,
1017
+ "rstrip": false,
1018
+ "single_word": false,
1019
+ "special": true
1020
+ },
1021
+ "157018": {
1022
+ "content": "<|reserved_token_123|>",
1023
+ "lstrip": false,
1024
+ "normalized": false,
1025
+ "rstrip": false,
1026
+ "single_word": false,
1027
+ "special": true
1028
+ },
1029
+ "157019": {
1030
+ "content": "<|reserved_token_124|>",
1031
+ "lstrip": false,
1032
+ "normalized": false,
1033
+ "rstrip": false,
1034
+ "single_word": false,
1035
+ "special": true
1036
+ },
1037
+ "157020": {
1038
+ "content": "<|reserved_token_125|>",
1039
+ "lstrip": false,
1040
+ "normalized": false,
1041
+ "rstrip": false,
1042
+ "single_word": false,
1043
+ "special": true
1044
+ },
1045
+ "157021": {
1046
+ "content": "<|reserved_token_126|>",
1047
+ "lstrip": false,
1048
+ "normalized": false,
1049
+ "rstrip": false,
1050
+ "single_word": false,
1051
+ "special": true
1052
+ },
1053
+ "157022": {
1054
+ "content": "<|reserved_token_127|>",
1055
+ "lstrip": false,
1056
+ "normalized": false,
1057
+ "rstrip": false,
1058
+ "single_word": false,
1059
+ "special": true
1060
+ },
1061
+ "157023": {
1062
+ "content": "<|reserved_token_128|>",
1063
+ "lstrip": false,
1064
+ "normalized": false,
1065
+ "rstrip": false,
1066
+ "single_word": false,
1067
+ "special": true
1068
+ },
1069
+ "157024": {
1070
+ "content": "<|reserved_token_129|>",
1071
+ "lstrip": false,
1072
+ "normalized": false,
1073
+ "rstrip": false,
1074
+ "single_word": false,
1075
+ "special": true
1076
+ },
1077
+ "157025": {
1078
+ "content": "<|reserved_token_130|>",
1079
+ "lstrip": false,
1080
+ "normalized": false,
1081
+ "rstrip": false,
1082
+ "single_word": false,
1083
+ "special": true
1084
+ },
1085
+ "157026": {
1086
+ "content": "<|reserved_token_131|>",
1087
+ "lstrip": false,
1088
+ "normalized": false,
1089
+ "rstrip": false,
1090
+ "single_word": false,
1091
+ "special": true
1092
+ },
1093
+ "157027": {
1094
+ "content": "<|reserved_token_132|>",
1095
+ "lstrip": false,
1096
+ "normalized": false,
1097
+ "rstrip": false,
1098
+ "single_word": false,
1099
+ "special": true
1100
+ },
1101
+ "157028": {
1102
+ "content": "<|reserved_token_133|>",
1103
+ "lstrip": false,
1104
+ "normalized": false,
1105
+ "rstrip": false,
1106
+ "single_word": false,
1107
+ "special": true
1108
+ },
1109
+ "157029": {
1110
+ "content": "<|reserved_token_134|>",
1111
+ "lstrip": false,
1112
+ "normalized": false,
1113
+ "rstrip": false,
1114
+ "single_word": false,
1115
+ "special": true
1116
+ },
1117
+ "157030": {
1118
+ "content": "<|reserved_token_135|>",
1119
+ "lstrip": false,
1120
+ "normalized": false,
1121
+ "rstrip": false,
1122
+ "single_word": false,
1123
+ "special": true
1124
+ },
1125
+ "157031": {
1126
+ "content": "<|reserved_token_136|>",
1127
+ "lstrip": false,
1128
+ "normalized": false,
1129
+ "rstrip": false,
1130
+ "single_word": false,
1131
+ "special": true
1132
+ },
1133
+ "157032": {
1134
+ "content": "<|reserved_token_137|>",
1135
+ "lstrip": false,
1136
+ "normalized": false,
1137
+ "rstrip": false,
1138
+ "single_word": false,
1139
+ "special": true
1140
+ },
1141
+ "157033": {
1142
+ "content": "<|reserved_token_138|>",
1143
+ "lstrip": false,
1144
+ "normalized": false,
1145
+ "rstrip": false,
1146
+ "single_word": false,
1147
+ "special": true
1148
+ },
1149
+ "157034": {
1150
+ "content": "<|reserved_token_139|>",
1151
+ "lstrip": false,
1152
+ "normalized": false,
1153
+ "rstrip": false,
1154
+ "single_word": false,
1155
+ "special": true
1156
+ },
1157
+ "157035": {
1158
+ "content": "<|reserved_token_140|>",
1159
+ "lstrip": false,
1160
+ "normalized": false,
1161
+ "rstrip": false,
1162
+ "single_word": false,
1163
+ "special": true
1164
+ },
1165
+ "157036": {
1166
+ "content": "<|reserved_token_141|>",
1167
+ "lstrip": false,
1168
+ "normalized": false,
1169
+ "rstrip": false,
1170
+ "single_word": false,
1171
+ "special": true
1172
+ },
1173
+ "157037": {
1174
+ "content": "<|reserved_token_142|>",
1175
+ "lstrip": false,
1176
+ "normalized": false,
1177
+ "rstrip": false,
1178
+ "single_word": false,
1179
+ "special": true
1180
+ },
1181
+ "157038": {
1182
+ "content": "<|reserved_token_143|>",
1183
+ "lstrip": false,
1184
+ "normalized": false,
1185
+ "rstrip": false,
1186
+ "single_word": false,
1187
+ "special": true
1188
+ },
1189
+ "157039": {
1190
+ "content": "<|reserved_token_144|>",
1191
+ "lstrip": false,
1192
+ "normalized": false,
1193
+ "rstrip": false,
1194
+ "single_word": false,
1195
+ "special": true
1196
+ },
1197
+ "157040": {
1198
+ "content": "<|reserved_token_145|>",
1199
+ "lstrip": false,
1200
+ "normalized": false,
1201
+ "rstrip": false,
1202
+ "single_word": false,
1203
+ "special": true
1204
+ },
1205
+ "157041": {
1206
+ "content": "<|reserved_token_146|>",
1207
+ "lstrip": false,
1208
+ "normalized": false,
1209
+ "rstrip": false,
1210
+ "single_word": false,
1211
+ "special": true
1212
+ },
1213
+ "157042": {
1214
+ "content": "<|reserved_token_147|>",
1215
+ "lstrip": false,
1216
+ "normalized": false,
1217
+ "rstrip": false,
1218
+ "single_word": false,
1219
+ "special": true
1220
+ },
1221
+ "157043": {
1222
+ "content": "<|reserved_token_148|>",
1223
+ "lstrip": false,
1224
+ "normalized": false,
1225
+ "rstrip": false,
1226
+ "single_word": false,
1227
+ "special": true
1228
+ },
1229
+ "157044": {
1230
+ "content": "<|reserved_token_149|>",
1231
+ "lstrip": false,
1232
+ "normalized": false,
1233
+ "rstrip": false,
1234
+ "single_word": false,
1235
+ "special": true
1236
+ },
1237
+ "157045": {
1238
+ "content": "<|reserved_token_150|>",
1239
+ "lstrip": false,
1240
+ "normalized": false,
1241
+ "rstrip": false,
1242
+ "single_word": false,
1243
+ "special": true
1244
+ },
1245
+ "157046": {
1246
+ "content": "<|reserved_token_151|>",
1247
+ "lstrip": false,
1248
+ "normalized": false,
1249
+ "rstrip": false,
1250
+ "single_word": false,
1251
+ "special": true
1252
+ },
1253
+ "157047": {
1254
+ "content": "<|reserved_token_152|>",
1255
+ "lstrip": false,
1256
+ "normalized": false,
1257
+ "rstrip": false,
1258
+ "single_word": false,
1259
+ "special": true
1260
+ },
1261
+ "157048": {
1262
+ "content": "<|reserved_token_153|>",
1263
+ "lstrip": false,
1264
+ "normalized": false,
1265
+ "rstrip": false,
1266
+ "single_word": false,
1267
+ "special": true
1268
+ },
1269
+ "157049": {
1270
+ "content": "<|reserved_token_154|>",
1271
+ "lstrip": false,
1272
+ "normalized": false,
1273
+ "rstrip": false,
1274
+ "single_word": false,
1275
+ "special": true
1276
+ },
1277
+ "157050": {
1278
+ "content": "<|reserved_token_155|>",
1279
+ "lstrip": false,
1280
+ "normalized": false,
1281
+ "rstrip": false,
1282
+ "single_word": false,
1283
+ "special": true
1284
+ },
1285
+ "157051": {
1286
+ "content": "<|reserved_token_156|>",
1287
+ "lstrip": false,
1288
+ "normalized": false,
1289
+ "rstrip": false,
1290
+ "single_word": false,
1291
+ "special": true
1292
+ },
1293
+ "157052": {
1294
+ "content": "<|reserved_token_157|>",
1295
+ "lstrip": false,
1296
+ "normalized": false,
1297
+ "rstrip": false,
1298
+ "single_word": false,
1299
+ "special": true
1300
+ },
1301
+ "157053": {
1302
+ "content": "<|reserved_token_158|>",
1303
+ "lstrip": false,
1304
+ "normalized": false,
1305
+ "rstrip": false,
1306
+ "single_word": false,
1307
+ "special": true
1308
+ },
1309
+ "157054": {
1310
+ "content": "<|reserved_token_159|>",
1311
+ "lstrip": false,
1312
+ "normalized": false,
1313
+ "rstrip": false,
1314
+ "single_word": false,
1315
+ "special": true
1316
+ },
1317
+ "157055": {
1318
+ "content": "<|reserved_token_160|>",
1319
+ "lstrip": false,
1320
+ "normalized": false,
1321
+ "rstrip": false,
1322
+ "single_word": false,
1323
+ "special": true
1324
+ },
1325
+ "157056": {
1326
+ "content": "<|reserved_token_161|>",
1327
+ "lstrip": false,
1328
+ "normalized": false,
1329
+ "rstrip": false,
1330
+ "single_word": false,
1331
+ "special": true
1332
+ },
1333
+ "157057": {
1334
+ "content": "<|reserved_token_162|>",
1335
+ "lstrip": false,
1336
+ "normalized": false,
1337
+ "rstrip": false,
1338
+ "single_word": false,
1339
+ "special": true
1340
+ },
1341
+ "157058": {
1342
+ "content": "<|reserved_token_163|>",
1343
+ "lstrip": false,
1344
+ "normalized": false,
1345
+ "rstrip": false,
1346
+ "single_word": false,
1347
+ "special": true
1348
+ },
1349
+ "157059": {
1350
+ "content": "<|reserved_token_164|>",
1351
+ "lstrip": false,
1352
+ "normalized": false,
1353
+ "rstrip": false,
1354
+ "single_word": false,
1355
+ "special": true
1356
+ },
1357
+ "157060": {
1358
+ "content": "<|reserved_token_165|>",
1359
+ "lstrip": false,
1360
+ "normalized": false,
1361
+ "rstrip": false,
1362
+ "single_word": false,
1363
+ "special": true
1364
+ },
1365
+ "157061": {
1366
+ "content": "<|reserved_token_166|>",
1367
+ "lstrip": false,
1368
+ "normalized": false,
1369
+ "rstrip": false,
1370
+ "single_word": false,
1371
+ "special": true
1372
+ },
1373
+ "157062": {
1374
+ "content": "<|reserved_token_167|>",
1375
+ "lstrip": false,
1376
+ "normalized": false,
1377
+ "rstrip": false,
1378
+ "single_word": false,
1379
+ "special": true
1380
+ },
1381
+ "157063": {
1382
+ "content": "<|reserved_token_168|>",
1383
+ "lstrip": false,
1384
+ "normalized": false,
1385
+ "rstrip": false,
1386
+ "single_word": false,
1387
+ "special": true
1388
+ },
1389
+ "157064": {
1390
+ "content": "<|reserved_token_169|>",
1391
+ "lstrip": false,
1392
+ "normalized": false,
1393
+ "rstrip": false,
1394
+ "single_word": false,
1395
+ "special": true
1396
+ },
1397
+ "157065": {
1398
+ "content": "<|reserved_token_170|>",
1399
+ "lstrip": false,
1400
+ "normalized": false,
1401
+ "rstrip": false,
1402
+ "single_word": false,
1403
+ "special": true
1404
+ },
1405
+ "157066": {
1406
+ "content": "<|reserved_token_171|>",
1407
+ "lstrip": false,
1408
+ "normalized": false,
1409
+ "rstrip": false,
1410
+ "single_word": false,
1411
+ "special": true
1412
+ },
1413
+ "157067": {
1414
+ "content": "<|reserved_token_172|>",
1415
+ "lstrip": false,
1416
+ "normalized": false,
1417
+ "rstrip": false,
1418
+ "single_word": false,
1419
+ "special": true
1420
+ },
1421
+ "157068": {
1422
+ "content": "<|reserved_token_173|>",
1423
+ "lstrip": false,
1424
+ "normalized": false,
1425
+ "rstrip": false,
1426
+ "single_word": false,
1427
+ "special": true
1428
+ },
1429
+ "157069": {
1430
+ "content": "<|reserved_token_174|>",
1431
+ "lstrip": false,
1432
+ "normalized": false,
1433
+ "rstrip": false,
1434
+ "single_word": false,
1435
+ "special": true
1436
+ },
1437
+ "157070": {
1438
+ "content": "<|reserved_token_175|>",
1439
+ "lstrip": false,
1440
+ "normalized": false,
1441
+ "rstrip": false,
1442
+ "single_word": false,
1443
+ "special": true
1444
+ },
1445
+ "157071": {
1446
+ "content": "<|reserved_token_176|>",
1447
+ "lstrip": false,
1448
+ "normalized": false,
1449
+ "rstrip": false,
1450
+ "single_word": false,
1451
+ "special": true
1452
+ },
1453
+ "157072": {
1454
+ "content": "<|reserved_token_177|>",
1455
+ "lstrip": false,
1456
+ "normalized": false,
1457
+ "rstrip": false,
1458
+ "single_word": false,
1459
+ "special": true
1460
+ },
1461
+ "157073": {
1462
+ "content": "<|reserved_token_178|>",
1463
+ "lstrip": false,
1464
+ "normalized": false,
1465
+ "rstrip": false,
1466
+ "single_word": false,
1467
+ "special": true
1468
+ },
1469
+ "157074": {
1470
+ "content": "<|reserved_token_179|>",
1471
+ "lstrip": false,
1472
+ "normalized": false,
1473
+ "rstrip": false,
1474
+ "single_word": false,
1475
+ "special": true
1476
+ },
1477
+ "157075": {
1478
+ "content": "<|reserved_token_180|>",
1479
+ "lstrip": false,
1480
+ "normalized": false,
1481
+ "rstrip": false,
1482
+ "single_word": false,
1483
+ "special": true
1484
+ },
1485
+ "157076": {
1486
+ "content": "<|reserved_token_181|>",
1487
+ "lstrip": false,
1488
+ "normalized": false,
1489
+ "rstrip": false,
1490
+ "single_word": false,
1491
+ "special": true
1492
+ },
1493
+ "157077": {
1494
+ "content": "<|reserved_token_182|>",
1495
+ "lstrip": false,
1496
+ "normalized": false,
1497
+ "rstrip": false,
1498
+ "single_word": false,
1499
+ "special": true
1500
+ },
1501
+ "157078": {
1502
+ "content": "<|reserved_token_183|>",
1503
+ "lstrip": false,
1504
+ "normalized": false,
1505
+ "rstrip": false,
1506
+ "single_word": false,
1507
+ "special": true
1508
+ },
1509
+ "157079": {
1510
+ "content": "<|reserved_token_184|>",
1511
+ "lstrip": false,
1512
+ "normalized": false,
1513
+ "rstrip": false,
1514
+ "single_word": false,
1515
+ "special": true
1516
+ },
1517
+ "157080": {
1518
+ "content": "<|reserved_token_185|>",
1519
+ "lstrip": false,
1520
+ "normalized": false,
1521
+ "rstrip": false,
1522
+ "single_word": false,
1523
+ "special": true
1524
+ },
1525
+ "157081": {
1526
+ "content": "<|reserved_token_186|>",
1527
+ "lstrip": false,
1528
+ "normalized": false,
1529
+ "rstrip": false,
1530
+ "single_word": false,
1531
+ "special": true
1532
+ },
1533
+ "157082": {
1534
+ "content": "<|reserved_token_187|>",
1535
+ "lstrip": false,
1536
+ "normalized": false,
1537
+ "rstrip": false,
1538
+ "single_word": false,
1539
+ "special": true
1540
+ },
1541
+ "157083": {
1542
+ "content": "<|reserved_token_188|>",
1543
+ "lstrip": false,
1544
+ "normalized": false,
1545
+ "rstrip": false,
1546
+ "single_word": false,
1547
+ "special": true
1548
+ },
1549
+ "157084": {
1550
+ "content": "<|reserved_token_189|>",
1551
+ "lstrip": false,
1552
+ "normalized": false,
1553
+ "rstrip": false,
1554
+ "single_word": false,
1555
+ "special": true
1556
+ },
1557
+ "157085": {
1558
+ "content": "<|reserved_token_190|>",
1559
+ "lstrip": false,
1560
+ "normalized": false,
1561
+ "rstrip": false,
1562
+ "single_word": false,
1563
+ "special": true
1564
+ },
1565
+ "157086": {
1566
+ "content": "<|reserved_token_191|>",
1567
+ "lstrip": false,
1568
+ "normalized": false,
1569
+ "rstrip": false,
1570
+ "single_word": false,
1571
+ "special": true
1572
+ },
1573
+ "157087": {
1574
+ "content": "<|reserved_token_192|>",
1575
+ "lstrip": false,
1576
+ "normalized": false,
1577
+ "rstrip": false,
1578
+ "single_word": false,
1579
+ "special": true
1580
+ },
1581
+ "157088": {
1582
+ "content": "<|reserved_token_193|>",
1583
+ "lstrip": false,
1584
+ "normalized": false,
1585
+ "rstrip": false,
1586
+ "single_word": false,
1587
+ "special": true
1588
+ },
1589
+ "157089": {
1590
+ "content": "<|reserved_token_194|>",
1591
+ "lstrip": false,
1592
+ "normalized": false,
1593
+ "rstrip": false,
1594
+ "single_word": false,
1595
+ "special": true
1596
+ },
1597
+ "157090": {
1598
+ "content": "<|reserved_token_195|>",
1599
+ "lstrip": false,
1600
+ "normalized": false,
1601
+ "rstrip": false,
1602
+ "single_word": false,
1603
+ "special": true
1604
+ },
1605
+ "157091": {
1606
+ "content": "<|reserved_token_196|>",
1607
+ "lstrip": false,
1608
+ "normalized": false,
1609
+ "rstrip": false,
1610
+ "single_word": false,
1611
+ "special": true
1612
+ },
1613
+ "157092": {
1614
+ "content": "<|reserved_token_197|>",
1615
+ "lstrip": false,
1616
+ "normalized": false,
1617
+ "rstrip": false,
1618
+ "single_word": false,
1619
+ "special": true
1620
+ },
1621
+ "157093": {
1622
+ "content": "<|reserved_token_198|>",
1623
+ "lstrip": false,
1624
+ "normalized": false,
1625
+ "rstrip": false,
1626
+ "single_word": false,
1627
+ "special": true
1628
+ },
1629
+ "157094": {
1630
+ "content": "<|reserved_token_199|>",
1631
+ "lstrip": false,
1632
+ "normalized": false,
1633
+ "rstrip": false,
1634
+ "single_word": false,
1635
+ "special": true
1636
+ },
1637
+ "157095": {
1638
+ "content": "<|reserved_token_200|>",
1639
+ "lstrip": false,
1640
+ "normalized": false,
1641
+ "rstrip": false,
1642
+ "single_word": false,
1643
+ "special": true
1644
+ },
1645
+ "157096": {
1646
+ "content": "<|reserved_token_201|>",
1647
+ "lstrip": false,
1648
+ "normalized": false,
1649
+ "rstrip": false,
1650
+ "single_word": false,
1651
+ "special": true
1652
+ },
1653
+ "157097": {
1654
+ "content": "<|reserved_token_202|>",
1655
+ "lstrip": false,
1656
+ "normalized": false,
1657
+ "rstrip": false,
1658
+ "single_word": false,
1659
+ "special": true
1660
+ },
1661
+ "157098": {
1662
+ "content": "<|reserved_token_203|>",
1663
+ "lstrip": false,
1664
+ "normalized": false,
1665
+ "rstrip": false,
1666
+ "single_word": false,
1667
+ "special": true
1668
+ },
1669
+ "157099": {
1670
+ "content": "<|reserved_token_204|>",
1671
+ "lstrip": false,
1672
+ "normalized": false,
1673
+ "rstrip": false,
1674
+ "single_word": false,
1675
+ "special": true
1676
+ },
1677
+ "157100": {
1678
+ "content": "<|reserved_token_205|>",
1679
+ "lstrip": false,
1680
+ "normalized": false,
1681
+ "rstrip": false,
1682
+ "single_word": false,
1683
+ "special": true
1684
+ },
1685
+ "157101": {
1686
+ "content": "<|reserved_token_206|>",
1687
+ "lstrip": false,
1688
+ "normalized": false,
1689
+ "rstrip": false,
1690
+ "single_word": false,
1691
+ "special": true
1692
+ },
1693
+ "157102": {
1694
+ "content": "<|reserved_token_207|>",
1695
+ "lstrip": false,
1696
+ "normalized": false,
1697
+ "rstrip": false,
1698
+ "single_word": false,
1699
+ "special": true
1700
+ },
1701
+ "157103": {
1702
+ "content": "<|reserved_token_208|>",
1703
+ "lstrip": false,
1704
+ "normalized": false,
1705
+ "rstrip": false,
1706
+ "single_word": false,
1707
+ "special": true
1708
+ },
1709
+ "157104": {
1710
+ "content": "<|reserved_token_209|>",
1711
+ "lstrip": false,
1712
+ "normalized": false,
1713
+ "rstrip": false,
1714
+ "single_word": false,
1715
+ "special": true
1716
+ },
1717
+ "157105": {
1718
+ "content": "<|reserved_token_210|>",
1719
+ "lstrip": false,
1720
+ "normalized": false,
1721
+ "rstrip": false,
1722
+ "single_word": false,
1723
+ "special": true
1724
+ },
1725
+ "157106": {
1726
+ "content": "<|reserved_token_211|>",
1727
+ "lstrip": false,
1728
+ "normalized": false,
1729
+ "rstrip": false,
1730
+ "single_word": false,
1731
+ "special": true
1732
+ },
1733
+ "157107": {
1734
+ "content": "<|reserved_token_212|>",
1735
+ "lstrip": false,
1736
+ "normalized": false,
1737
+ "rstrip": false,
1738
+ "single_word": false,
1739
+ "special": true
1740
+ },
1741
+ "157108": {
1742
+ "content": "<|reserved_token_213|>",
1743
+ "lstrip": false,
1744
+ "normalized": false,
1745
+ "rstrip": false,
1746
+ "single_word": false,
1747
+ "special": true
1748
+ },
1749
+ "157109": {
1750
+ "content": "<|reserved_token_214|>",
1751
+ "lstrip": false,
1752
+ "normalized": false,
1753
+ "rstrip": false,
1754
+ "single_word": false,
1755
+ "special": true
1756
+ },
1757
+ "157110": {
1758
+ "content": "<|reserved_token_215|>",
1759
+ "lstrip": false,
1760
+ "normalized": false,
1761
+ "rstrip": false,
1762
+ "single_word": false,
1763
+ "special": true
1764
+ },
1765
+ "157111": {
1766
+ "content": "<|reserved_token_216|>",
1767
+ "lstrip": false,
1768
+ "normalized": false,
1769
+ "rstrip": false,
1770
+ "single_word": false,
1771
+ "special": true
1772
+ },
1773
+ "157112": {
1774
+ "content": "<|reserved_token_217|>",
1775
+ "lstrip": false,
1776
+ "normalized": false,
1777
+ "rstrip": false,
1778
+ "single_word": false,
1779
+ "special": true
1780
+ },
1781
+ "157113": {
1782
+ "content": "<|reserved_token_218|>",
1783
+ "lstrip": false,
1784
+ "normalized": false,
1785
+ "rstrip": false,
1786
+ "single_word": false,
1787
+ "special": true
1788
+ },
1789
+ "157114": {
1790
+ "content": "<|reserved_token_219|>",
1791
+ "lstrip": false,
1792
+ "normalized": false,
1793
+ "rstrip": false,
1794
+ "single_word": false,
1795
+ "special": true
1796
+ },
1797
+ "157115": {
1798
+ "content": "<|reserved_token_220|>",
1799
+ "lstrip": false,
1800
+ "normalized": false,
1801
+ "rstrip": false,
1802
+ "single_word": false,
1803
+ "special": true
1804
+ },
1805
+ "157116": {
1806
+ "content": "<|reserved_token_221|>",
1807
+ "lstrip": false,
1808
+ "normalized": false,
1809
+ "rstrip": false,
1810
+ "single_word": false,
1811
+ "special": true
1812
+ },
1813
+ "157117": {
1814
+ "content": "<|reserved_token_222|>",
1815
+ "lstrip": false,
1816
+ "normalized": false,
1817
+ "rstrip": false,
1818
+ "single_word": false,
1819
+ "special": true
1820
+ },
1821
+ "157118": {
1822
+ "content": "<|reserved_token_223|>",
1823
+ "lstrip": false,
1824
+ "normalized": false,
1825
+ "rstrip": false,
1826
+ "single_word": false,
1827
+ "special": true
1828
+ },
1829
+ "157119": {
1830
+ "content": "<|reserved_token_224|>",
1831
+ "lstrip": false,
1832
+ "normalized": false,
1833
+ "rstrip": false,
1834
+ "single_word": false,
1835
+ "special": true
1836
+ },
1837
+ "157120": {
1838
+ "content": "<|reserved_token_225|>",
1839
+ "lstrip": false,
1840
+ "normalized": false,
1841
+ "rstrip": false,
1842
+ "single_word": false,
1843
+ "special": true
1844
+ },
1845
+ "157121": {
1846
+ "content": "<|reserved_token_226|>",
1847
+ "lstrip": false,
1848
+ "normalized": false,
1849
+ "rstrip": false,
1850
+ "single_word": false,
1851
+ "special": true
1852
+ },
1853
+ "157122": {
1854
+ "content": "<|reserved_token_227|>",
1855
+ "lstrip": false,
1856
+ "normalized": false,
1857
+ "rstrip": false,
1858
+ "single_word": false,
1859
+ "special": true
1860
+ },
1861
+ "157123": {
1862
+ "content": "<|reserved_token_228|>",
1863
+ "lstrip": false,
1864
+ "normalized": false,
1865
+ "rstrip": false,
1866
+ "single_word": false,
1867
+ "special": true
1868
+ },
1869
+ "157124": {
1870
+ "content": "<|reserved_token_229|>",
1871
+ "lstrip": false,
1872
+ "normalized": false,
1873
+ "rstrip": false,
1874
+ "single_word": false,
1875
+ "special": true
1876
+ },
1877
+ "157125": {
1878
+ "content": "<|reserved_token_230|>",
1879
+ "lstrip": false,
1880
+ "normalized": false,
1881
+ "rstrip": false,
1882
+ "single_word": false,
1883
+ "special": true
1884
+ },
1885
+ "157126": {
1886
+ "content": "<|reserved_token_231|>",
1887
+ "lstrip": false,
1888
+ "normalized": false,
1889
+ "rstrip": false,
1890
+ "single_word": false,
1891
+ "special": true
1892
+ },
1893
+ "157127": {
1894
+ "content": "<|reserved_token_232|>",
1895
+ "lstrip": false,
1896
+ "normalized": false,
1897
+ "rstrip": false,
1898
+ "single_word": false,
1899
+ "special": true
1900
+ },
1901
+ "157128": {
1902
+ "content": "<|reserved_token_233|>",
1903
+ "lstrip": false,
1904
+ "normalized": false,
1905
+ "rstrip": false,
1906
+ "single_word": false,
1907
+ "special": true
1908
+ },
1909
+ "157129": {
1910
+ "content": "<|reserved_token_234|>",
1911
+ "lstrip": false,
1912
+ "normalized": false,
1913
+ "rstrip": false,
1914
+ "single_word": false,
1915
+ "special": true
1916
+ },
1917
+ "157130": {
1918
+ "content": "<|reserved_token_235|>",
1919
+ "lstrip": false,
1920
+ "normalized": false,
1921
+ "rstrip": false,
1922
+ "single_word": false,
1923
+ "special": true
1924
+ },
1925
+ "157131": {
1926
+ "content": "<|reserved_token_236|>",
1927
+ "lstrip": false,
1928
+ "normalized": false,
1929
+ "rstrip": false,
1930
+ "single_word": false,
1931
+ "special": true
1932
+ },
1933
+ "157132": {
1934
+ "content": "<|reserved_token_237|>",
1935
+ "lstrip": false,
1936
+ "normalized": false,
1937
+ "rstrip": false,
1938
+ "single_word": false,
1939
+ "special": true
1940
+ },
1941
+ "157133": {
1942
+ "content": "<|reserved_token_238|>",
1943
+ "lstrip": false,
1944
+ "normalized": false,
1945
+ "rstrip": false,
1946
+ "single_word": false,
1947
+ "special": true
1948
+ },
1949
+ "157134": {
1950
+ "content": "<|reserved_token_239|>",
1951
+ "lstrip": false,
1952
+ "normalized": false,
1953
+ "rstrip": false,
1954
+ "single_word": false,
1955
+ "special": true
1956
+ },
1957
+ "157135": {
1958
+ "content": "<|reserved_token_240|>",
1959
+ "lstrip": false,
1960
+ "normalized": false,
1961
+ "rstrip": false,
1962
+ "single_word": false,
1963
+ "special": true
1964
+ },
1965
+ "157136": {
1966
+ "content": "<|reserved_token_241|>",
1967
+ "lstrip": false,
1968
+ "normalized": false,
1969
+ "rstrip": false,
1970
+ "single_word": false,
1971
+ "special": true
1972
+ },
1973
+ "157137": {
1974
+ "content": "<|reserved_token_242|>",
1975
+ "lstrip": false,
1976
+ "normalized": false,
1977
+ "rstrip": false,
1978
+ "single_word": false,
1979
+ "special": true
1980
+ },
1981
+ "157138": {
1982
+ "content": "<|reserved_token_243|>",
1983
+ "lstrip": false,
1984
+ "normalized": false,
1985
+ "rstrip": false,
1986
+ "single_word": false,
1987
+ "special": true
1988
+ },
1989
+ "157139": {
1990
+ "content": "<|reserved_token_244|>",
1991
+ "lstrip": false,
1992
+ "normalized": false,
1993
+ "rstrip": false,
1994
+ "single_word": false,
1995
+ "special": true
1996
+ },
1997
+ "157140": {
1998
+ "content": "<|reserved_token_245|>",
1999
+ "lstrip": false,
2000
+ "normalized": false,
2001
+ "rstrip": false,
2002
+ "single_word": false,
2003
+ "special": true
2004
+ },
2005
+ "157141": {
2006
+ "content": "<|reserved_token_246|>",
2007
+ "lstrip": false,
2008
+ "normalized": false,
2009
+ "rstrip": false,
2010
+ "single_word": false,
2011
+ "special": true
2012
+ },
2013
+ "157142": {
2014
+ "content": "<|reserved_token_247|>",
2015
+ "lstrip": false,
2016
+ "normalized": false,
2017
+ "rstrip": false,
2018
+ "single_word": false,
2019
+ "special": true
2020
+ },
2021
+ "157143": {
2022
+ "content": "<|reserved_token_248|>",
2023
+ "lstrip": false,
2024
+ "normalized": false,
2025
+ "rstrip": false,
2026
+ "single_word": false,
2027
+ "special": true
2028
+ },
2029
+ "157144": {
2030
+ "content": "<|reserved_token_249|>",
2031
+ "lstrip": false,
2032
+ "normalized": false,
2033
+ "rstrip": false,
2034
+ "single_word": false,
2035
+ "special": true
2036
+ },
2037
+ "157145": {
2038
+ "content": "<|reserved_token_250|>",
2039
+ "lstrip": false,
2040
+ "normalized": false,
2041
+ "rstrip": false,
2042
+ "single_word": false,
2043
+ "special": true
2044
+ },
2045
+ "157146": {
2046
+ "content": "<|reserved_token_251|>",
2047
+ "lstrip": false,
2048
+ "normalized": false,
2049
+ "rstrip": false,
2050
+ "single_word": false,
2051
+ "special": true
2052
+ },
2053
+ "157147": {
2054
+ "content": "<|reserved_token_252|>",
2055
+ "lstrip": false,
2056
+ "normalized": false,
2057
+ "rstrip": false,
2058
+ "single_word": false,
2059
+ "special": true
2060
+ },
2061
+ "157148": {
2062
+ "content": "<|reserved_token_253|>",
2063
+ "lstrip": false,
2064
+ "normalized": false,
2065
+ "rstrip": false,
2066
+ "single_word": false,
2067
+ "special": true
2068
+ },
2069
+ "157149": {
2070
+ "content": "<|reserved_token_254|>",
2071
+ "lstrip": false,
2072
+ "normalized": false,
2073
+ "rstrip": false,
2074
+ "single_word": false,
2075
+ "special": true
2076
+ },
2077
+ "157150": {
2078
+ "content": "<|reserved_token_255|>",
2079
+ "lstrip": false,
2080
+ "normalized": false,
2081
+ "rstrip": false,
2082
+ "single_word": false,
2083
+ "special": true
2084
+ },
2085
+ "157151": {
2086
+ "content": "<role>",
2087
+ "lstrip": false,
2088
+ "normalized": false,
2089
+ "rstrip": false,
2090
+ "single_word": false,
2091
+ "special": true
2092
+ },
2093
+ "157152": {
2094
+ "content": "</role>",
2095
+ "lstrip": false,
2096
+ "normalized": false,
2097
+ "rstrip": false,
2098
+ "single_word": false,
2099
+ "special": true
2100
+ },
2101
+ "157153": {
2102
+ "content": "<|arithmetic_end|>",
2103
+ "lstrip": false,
2104
+ "normalized": false,
2105
+ "rstrip": false,
2106
+ "single_word": false,
2107
+ "special": true
2108
+ },
2109
+ "157154": {
2110
+ "content": "<|number_end|>",
2111
+ "lstrip": false,
2112
+ "normalized": false,
2113
+ "rstrip": false,
2114
+ "single_word": false,
2115
+ "special": true
2116
+ },
2117
+ "157155": {
2118
+ "content": "<|arithmetic_start|>",
2119
+ "lstrip": false,
2120
+ "normalized": false,
2121
+ "rstrip": false,
2122
+ "single_word": false,
2123
+ "special": true
2124
+ },
2125
+ "157156": {
2126
+ "content": "<|number_start|>",
2127
+ "lstrip": false,
2128
+ "normalized": false,
2129
+ "rstrip": false,
2130
+ "single_word": false,
2131
+ "special": true
2132
+ },
2133
+ "157157": {
2134
+ "content": "<imagePatch>",
2135
+ "lstrip": false,
2136
+ "normalized": false,
2137
+ "rstrip": false,
2138
+ "single_word": false,
2139
+ "special": true
2140
+ },
2141
+ "157158": {
2142
+ "content": "<image>",
2143
+ "lstrip": false,
2144
+ "normalized": false,
2145
+ "rstrip": false,
2146
+ "single_word": false,
2147
+ "special": true
2148
+ },
2149
+ "157159": {
2150
+ "content": "</image>",
2151
+ "lstrip": false,
2152
+ "normalized": false,
2153
+ "rstrip": false,
2154
+ "single_word": false,
2155
+ "special": true
2156
+ },
2157
+ "157160": {
2158
+ "content": "<video>",
2159
+ "lstrip": false,
2160
+ "normalized": false,
2161
+ "rstrip": false,
2162
+ "single_word": false,
2163
+ "special": true
2164
+ },
2165
+ "157161": {
2166
+ "content": "</video>",
2167
+ "lstrip": false,
2168
+ "normalized": false,
2169
+ "rstrip": false,
2170
+ "single_word": false,
2171
+ "special": true
2172
+ },
2173
+ "157162": {
2174
+ "content": "<gen_imagePatch>",
2175
+ "lstrip": false,
2176
+ "normalized": false,
2177
+ "rstrip": false,
2178
+ "single_word": false,
2179
+ "special": true
2180
+ },
2181
+ "157163": {
2182
+ "content": "<gen_image>",
2183
+ "lstrip": false,
2184
+ "normalized": false,
2185
+ "rstrip": false,
2186
+ "single_word": false,
2187
+ "special": true
2188
+ },
2189
+ "157164": {
2190
+ "content": "</gen_image>",
2191
+ "lstrip": false,
2192
+ "normalized": false,
2193
+ "rstrip": false,
2194
+ "single_word": false,
2195
+ "special": true
2196
+ },
2197
+ "157165": {
2198
+ "content": "<imageHere>",
2199
+ "lstrip": false,
2200
+ "normalized": false,
2201
+ "rstrip": false,
2202
+ "single_word": false,
2203
+ "special": true
2204
+ },
2205
+ "157166": {
2206
+ "content": "<end_of_chunk>",
2207
+ "lstrip": false,
2208
+ "normalized": false,
2209
+ "rstrip": false,
2210
+ "single_word": false,
2211
+ "special": true
2212
+ },
2213
+ "157167": {
2214
+ "content": "<end_of_audio>",
2215
+ "lstrip": false,
2216
+ "normalized": false,
2217
+ "rstrip": false,
2218
+ "single_word": false,
2219
+ "special": true
2220
+ },
2221
+ "157168": {
2222
+ "content": "<audioPatch>",
2223
+ "lstrip": false,
2224
+ "normalized": false,
2225
+ "rstrip": false,
2226
+ "single_word": false,
2227
+ "special": true
2228
+ },
2229
+ "157169": {
2230
+ "content": "<audio>",
2231
+ "lstrip": false,
2232
+ "normalized": false,
2233
+ "rstrip": false,
2234
+ "single_word": false,
2235
+ "special": true
2236
+ },
2237
+ "157170": {
2238
+ "content": "</audio>",
2239
+ "lstrip": false,
2240
+ "normalized": false,
2241
+ "rstrip": false,
2242
+ "single_word": false,
2243
+ "special": true
2244
+ },
2245
+ "157171": {
2246
+ "content": "<gen_audioPatch>",
2247
+ "lstrip": false,
2248
+ "normalized": false,
2249
+ "rstrip": false,
2250
+ "single_word": false,
2251
+ "special": true
2252
+ },
2253
+ "157172": {
2254
+ "content": "<gen_audio>",
2255
+ "lstrip": false,
2256
+ "normalized": false,
2257
+ "rstrip": false,
2258
+ "single_word": false,
2259
+ "special": true
2260
+ },
2261
+ "157173": {
2262
+ "content": "</gen_audio>",
2263
+ "lstrip": false,
2264
+ "normalized": false,
2265
+ "rstrip": false,
2266
+ "single_word": false,
2267
+ "special": true
2268
+ },
2269
+ "157174": {
2270
+ "content": "<audioHere>",
2271
+ "lstrip": false,
2272
+ "normalized": false,
2273
+ "rstrip": false,
2274
+ "single_word": false,
2275
+ "special": true
2276
+ },
2277
+ "157175": {
2278
+ "content": "<framePatch>",
2279
+ "lstrip": false,
2280
+ "normalized": false,
2281
+ "rstrip": false,
2282
+ "single_word": false,
2283
+ "special": true
2284
+ },
2285
+ "157176": {
2286
+ "content": "<text>",
2287
+ "lstrip": false,
2288
+ "normalized": false,
2289
+ "rstrip": false,
2290
+ "single_word": false,
2291
+ "special": true
2292
+ },
2293
+ "157177": {
2294
+ "content": "<asr>",
2295
+ "lstrip": false,
2296
+ "normalized": false,
2297
+ "rstrip": false,
2298
+ "single_word": false,
2299
+ "special": true
2300
+ },
2301
+ "157178": {
2302
+ "content": "<tts>",
2303
+ "lstrip": false,
2304
+ "normalized": false,
2305
+ "rstrip": false,
2306
+ "single_word": false,
2307
+ "special": true
2308
+ }
2309
+ },
2310
+ "additional_special_tokens": [
2311
+ "<|arithmetic_end|>",
2312
+ "<role>",
2313
+ "<|number_end|>",
2314
+ "<|arithmetic_start|>",
2315
+ "</role>",
2316
+ "<|number_start|>",
2317
+ "<|role_end|>",
2318
+ "<tool_call>",
2319
+ "</tool_call>",
2320
+ "<tool_response>",
2321
+ "</tool_response>"
2322
+ ],
2323
+ "bos_token": "<|startoftext|>",
2324
+ "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>' -}}",
2325
+ "clean_up_tokenization_spaces": false,
2326
+ "cls_token": "[CLS]",
2327
+ "eos_token": "<|role_end|>",
2328
+ "extra_special_tokens": {},
2329
+ "fast_tokenizer": true,
2330
+ "gmask_token": "[gMASK]",
2331
+ "merges_file": null,
2332
+ "model_max_length": 1000000000000000019884624838656,
2333
+ "pad_token": "<|role_end|>",
2334
+ "auto_map": {
2335
+ "AutoTokenizer": [
2336
+ "tokenization_bailing.BailingTokenizer",
2337
+ null
2338
+ ]
2339
+ },
2340
+ "tokenizer_class": "BailingTokenizer",
2341
+ "trust_remote_code": true
2342
+ }