Text-to-Speech
Transformers
ONNX
Safetensors
English
Chinese
bailing_moe_v3_audio
feature-extraction
audio
speech
automatic-speech-recognition
audio-understanding
audio-reasoning
speech-to-text
conversational
mixture-of-experts
custom_code
Run this model with HF Jobs
Run ml-resources/Ming-3.0-audio-tiny on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/ml-resources/Ming-3.0-audio-tiny. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/ml-resources/Ming-3.0-audio-tiny on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use ml-resources/Ming-3.0-audio-tiny with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use ml-resources/Ming-3.0-audio-tiny with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-to-speech", model="ml-resources/Ming-3.0-audio-tiny", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("ml-resources/Ming-3.0-audio-tiny", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Mirror inclusionAI/Ming-3.0-audio-tiny
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+17-35
- README.mdAdded+222
- assets/benchmark-asr.pngAdded
- assets/benchmark-audio-intelligence.pngAdded
- assets/benchmark-text.pngAdded
- assets/github-invertocat-black-17.svgAdded
- assets/ming-3.0-audio-logo.pngAdded
- chat_template.jinjaAdded+165
- config.jsonAdded+106
- configuration_bailing_moe_v3.pyAdded+130
- configuration_bailing_moe_v3_audio.pyAdded+226
- generation_config.jsonAdded+7
- model-00001-of-00002.safetensorsAdded+3
- model-00002-of-00002.safetensorsAdded+3
- model.safetensors.index.jsonAdded
- modeling_bailing_moe_v3.pyAdded+1687
- modeling_bailing_moe_v3_audio.pyAdded+334
- processing_bailing_moe_v3_audio.pyAdded+120
- processor_config.jsonAdded+6
- special_tokens_map.jsonAdded+57
- talker/AudioVAE/__init__.pyAdded
- talker/AudioVAE/__pycache__/__init__.cpython-312.pycAdded
- talker/AudioVAE/__pycache__/configuration_audio_vae.cpython-312.pycAdded
- talker/AudioVAE/__pycache__/istft.cpython-312.pycAdded
- talker/AudioVAE/__pycache__/modeling_audio_vae.cpython-312.pycAdded
- talker/AudioVAE/__pycache__/vae_modules.cpython-312.pycAdded
- talker/AudioVAE/configuration_audio_vae.pyAdded+19
- talker/AudioVAE/istft.pyAdded+181
- talker/AudioVAE/modeling_audio_vae.pyAdded+80
- talker/AudioVAE/vae_modules.pyAdded+204
- talker/__init__.pyAdded+5
- talker/campplus.onnxAdded+3
- talker/config.jsonAdded+35
- talker/configuration_bailing_talker.pyAdded+20
- talker/data/lid.176.LICENSE.mdAdded+10
- talker/data/lid.176.ftzAdded+3
- talker/front/__init__.pyAdded
- talker/front/__pycache__/__init__.cpython-312.pycAdded
- talker/front/__pycache__/number_en.cpython-312.pycAdded
- talker/front/__pycache__/text_segment_cut.cpython-312.pycAdded
- talker/front/__pycache__/toolkit.cpython-312.pycAdded
- talker/front/number_en.pyAdded+343
- talker/front/text_segment_cut.pyAdded+388
- talker/front/toolkit.pyAdded+240
- talker/inference.pyAdded+443
- talker/llm/added_tokens.jsonAdded+75
- talker/llm/config.jsonAdded+27
- talker/llm/generation_config.jsonAdded+14
- talker/llm/merges.txtAdded
- talker/llm/special_tokens_map.jsonAdded+137
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text1234567891011121314151617model-00001-of-00002.safetensors filter=lfs diff=lfs merge=lfs -textmodel-00002-of-00002.safetensors filter=lfs diff=lfs merge=lfs -texttalker/campplus.onnx filter=lfs diff=lfs merge=lfs -texttalker/data/lid.176.ftz filter=lfs diff=lfs merge=lfs -texttalker/llm/tokenizer.json filter=lfs diff=lfs merge=lfs -texttalker/model.safetensors filter=lfs diff=lfs merge=lfs -texttalker/talker_tn/en_tn_tagger.fst filter=lfs diff=lfs merge=lfs -texttalker/talker_tn/en_tn_verbalizer.fst filter=lfs diff=lfs merge=lfs -texttalker/talker_tn/zh_tn_tagger.fst filter=lfs diff=lfs merge=lfs -texttalker/vae/model.safetensors filter=lfs diff=lfs merge=lfs -textvoice_presets/voice_audio/lingguang.wav filter=lfs diff=lfs merge=lfs -textvoice_presets/voice_audio/US_James.wav filter=lfs diff=lfs merge=lfs -textvoice_presets/voice_audio/灵楷.wav filter=lfs diff=lfs merge=lfs -textassets/benchmark-asr.png filter=lfs diff=lfs merge=lfs -textassets/benchmark-audio-intelligence.png filter=lfs diff=lfs merge=lfs -textassets/benchmark-text.png filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222---language:- en- zhlicense: mitlibrary_name: transformerstags:- audio- speech- automatic-speech-recognition- audio-understanding- audio-reasoning- speech-to-text- text-to-speech- conversational- mixture-of-experts- custom_codemodel_name: Ming-3.0-audio-tiny---> Mirror of [inclusionAI/Ming-3.0-audio-tiny](https://huggingface.co/inclusionAI/Ming-3.0-audio-tiny). All credit to the original authors. Not an official release from them. License unchanged (mit).
<div align="center"> <img src="assets/ming-3.0-audio-logo.png" width="110" alt="Ming logo"> <h1>Ming-3.0-audio-tiny</h1> <p><strong>Hear clearly. Understand deeply. Act intelligently.</strong></p></div>
Ming-3.0-audio-tiny is a compact native audio-language model from inclusionAI. It accepts audio together with text instructions and supports speech recognition, spoken question answering, audio understanding, audio reasoning, and optional synthesized-speech responses.
<div align="center"><table align="center" border="0" cellpadding="0" cellspacing="0" style="border:none; display:inline-table; width:auto; margin:0 auto;"> <tr> <td valign="middle" style="border:none; padding:0;"><a href="https://github.com/inclusionAI/Ming-3.0-audio-flash" style="display:inline-block; white-space:nowrap; line-height:17px; background-image:linear-gradient(currentColor,currentColor); background-repeat:no-repeat; background-position:0 calc(100% - 0.5px); background-size:100% 1px; text-decoration:none;"><img src="assets/github-invertocat-black-17.svg" width="17" height="17" alt="" style="display:inline-block; vertical-align:middle; position:relative; top:-1.5px; margin:0 3px 0 0;">GitHub</a></td> <td valign="middle" style="border:none; padding:0 8px;">·</td> <td valign="middle" style="border:none; padding:0;"><a href="https://huggingface.co/inclusionAI/Ming-3.0-audio-flash">🤗 Flash</a></td> <td valign="middle" style="border:none; padding:0 8px;">·</td> <td valign="middle" style="border:none; padding:0;"><a href="https://huggingface.co/inclusionAI/Ming-3.0-audio-tiny">🤗 Tiny</a></td> <td valign="middle" style="border:none; padding:0 8px;">·</td> <td valign="middle" style="border:none; padding:0;"><a href="https://github.com/inclusionAI/Ming-3.0-audio-flash/tree/main/examples">💻 Examples</a></td> </tr></table></div>
## Model Summary
| Property | Description || --- | --- || Developer | inclusionAI || Model type | Compact native audio-language Mixture-of-Experts model || Parameters | 9.3B total parameters, 2.7B activated per inference step || Inputs | Audio and text instructions || Outputs | Text, or text with optional synthesized speech || Primary languages | Chinese and English, including varied accents and dialects || License | MIT |
## Highlights
- **Efficient audio intelligence:** Provides speech and audio understanding in a compact Mixture-of-Experts model.- **Complex speech recognition:** Handles Chinese and English speech, dialects, accents, noisy environments, and multi-speaker recordings.- **Long-audio understanding:** Comprehends and analyzes long-form recordings.- **Multidimensional perception:** Understands speech, non-speech sounds, acoustic scenes, and music.- **Audio reasoning:** Answers questions and performs reasoning over audio content.- **Audio interaction:** Produces text responses and can optionally synthesize speech with built-in voices or a reference voice.
## Architecture
Ming-3.0-audio-tiny combines an audio encoder and projector with a compact Mixture-of-Experts language backbone. An optional Talker generates speech responses from the model's output.
## Quick Start with Transformers
The model uses custom Transformers code. Review the repository code before enabling `trust_remote_code=True`.
```bashgit clone https://github.com/inclusionAI/Ming-3.0-audio-flash.gitcd Ming-3.0-audio-flash
python -m venv .venv-transformerssource .venv-transformers/bin/activatepip install -r requirements-transformers.txt```
### Audio Understanding
```bashpython examples/transformers_audio.py examples/audio/introduce_ant_group.wav \ --model inclusionAI/Ming-3.0-audio-tiny \ --prompt "Please answer the question in the audio."```
### Speech Recognition
```bashpython examples/transformers_audio.py examples/audio/introduce_ant_group.wav \ --model inclusionAI/Ming-3.0-audio-tiny \ --task asr \ --max-new-tokens 256 \ --no-repeat-ngram-size 10```
The validated ASR prompt asks the model to identify the spoken language and place a tab between the language label and transcription.
### Direct Python Usage
```pythonimport torchfrom transformers import AutoModelForCausalLM, AutoProcessor
model_id = "inclusionAI/Ming-3.0-audio-tiny"audio_path = "examples/audio/introduce_ant_group.wav"
processor = AutoProcessor.from_pretrained( model_id, trust_remote_code=True, use_fast=False,)model = AutoModelForCausalLM.from_pretrained( model_id, dtype=torch.bfloat16, device_map="auto", trust_remote_code=True,).eval()
messages = [ { "role": "user", "content": [ {"type": "audio", "audio": audio_path}, {"type": "text", "text": "Please answer the question in the audio."}, ], }]
inputs = processor(messages).to(model.device)inputs["audio_feats"] = inputs["audio_feats"].to(model.dtype)
with torch.inference_mode(): output_ids = model.generate( **inputs, max_new_tokens=512, do_sample=False, )
generated_ids = output_ids[0, inputs["input_ids"].shape[1] :]response = processor.decode(generated_ids, skip_special_tokens=True).strip()print(response)```
## Speech Output
The Talker example supports built-in voices and reference-audio voice prompting:
```bashpython examples/transformers_thinker_talker.py \ --model inclusionAI/Ming-3.0-audio-tiny \ --audio examples/audio/introduce_ant_group.wav \ --ip-name US_Stella \ --output output.wav```
See the [voice guide](https://github.com/inclusionAI/Ming-3.0-audio-flash/blob/main/docs/voices.md) for available voice names, invocation rules, and reference-audio usage.
## Serving
### vLLM-Omni
Text output or ASR uses the Tiny Thinker on one GPU:
```bashexport MODEL_PATH=inclusionAI/Ming-3.0-audio-tinyMING_MODEL_VARIANT=tiny MING_OUTPUT_MODE=text \ ./scripts/serve_vllm_omni.sh "$MODEL_PATH"```
For synthesized-speech output, select the full-audio profile:
```bashexport MODEL_PATH=inclusionAI/Ming-3.0-audio-tinyMING_MODEL_VARIANT=tiny MING_OUTPUT_MODE=audio \ ./scripts/serve_vllm_omni.sh "$MODEL_PATH"```
The reference full-audio profile places the Thinker on GPU 0 and the Talker on GPU 1. Select the deployment YAML that matches text-only, ASR, or Talker output. See the [deployment guide](https://github.com/inclusionAI/Ming-3.0-audio-flash/blob/main/README.md#vllm-omni) for details.
For speech output, vLLM-Omni uses the built-in IP voice `灵小柔` by default. The model directory also provides `灵楷` and `US_James` as preset reference voices under `voice_presets/voice_audio/`, with their matching transcripts in `voice_presets/voice_prompts.json`. Both names are also available as built-in IP voices.
### SGLang
```bashexport MODEL_PATH=inclusionAI/Ming-3.0-audio-tinyMING_MODEL_VARIANT=tiny CUDA_VISIBLE_DEVICES=0 \ ./scripts/serve_sglang.sh "$MODEL_PATH"```
The validated Tiny SGLang profile uses one GPU and provides text output. See the [SGLang example](https://github.com/inclusionAI/Ming-3.0-audio-flash/blob/main/examples/sglang_audio_chat.py) for client usage.
## Evaluation
The shared benchmark figures below include results for both Ming-3.0-audio-tiny and Ming-3.0-audio-flash.
### Speech Recognition
<p align="center"> <img src="assets/benchmark-asr.png" width="100%" alt="Speech recognition benchmarks"></p>
### Audio Intelligence
<p align="center"> <img src="assets/benchmark-audio-intelligence.png" width="100%" alt="Audio intelligence benchmarks"></p>
### Text Benchmarks
<p align="center"> <img src="assets/benchmark-text.png" width="760" alt="Text benchmarks"></p>
All benchmark values are percentages. Higher is better unless the metric is marked with a downward arrow. Results marked with an asterisk are self-evaluated. Refer to the [GitHub README](https://github.com/inclusionAI/Ming-3.0-audio-flash#benchmarks) for the latest notes and evaluation details.
## License
This model is released under the [MIT License](https://github.com/inclusionAI/Ming-3.0-audio-flash/blob/main/LICENSE). See [LEGAL.md](https://github.com/inclusionAI/Ming-3.0-audio-flash/blob/main/LEGAL.md) for the legal disclaimer.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165{#- Bailing V3 audio and text chat template -#}{#- Supports: audio/text content, enable_thinking, preserved thinking, tool calling -#}
{#- ==================== thinking normalization ==================== -#}{%- if enable_thinking is not defined %} {%- set enable_thinking = false %}{%- endif %}{%- if enable_thinking %} {%- set thinking_instruction = 'detailed thinking on' %}{%- else %} {%- set thinking_instruction = 'detailed thinking off' %}{%- endif %}
{#- ==================== preserved thinking normalization ==================== -#}{%- if preserve_thinking is not defined %} {%- set preserve_thinking = true %}{%- endif %}
{#- ==================== render_content macro ==================== -#}{%- macro render_content(content) %} {%- if content is string %} {{- content }} {%- elif content is iterable and content is not mapping %} {%- for item in content %} {%- set item_type = item.type if item.type is defined else '' %} {%- if item_type == 'audio' or (not item_type and ('audio' in item or 'audio_url' in item)) %} {{- '<|audio_start|><|audio_pad|><|audio_end|>' }} {%- elif item_type == 'text' or (not item_type and 'text' in item) %} {{- item.text }} {%- else %} {{- raise_exception('Unexpected item type in content list: each item must have type audio/text.') }} {%- endif %} {%- endfor %} {%- elif content is none or content is undefined %} {{- '' }} {%- else %} {{- raise_exception('Unexpected content type: expected string, list, or none.') }} {%- endif %}{%- endmacro %}
{#- ==================== messages guard ==================== -#}{%- if not messages %} {{- raise_exception('No messages provided.') }}{%- endif %}
{#- ==================== system message ==================== -#}{{- '<role>SYSTEM</role>' }}{%- set has_thinking_instruction = false %}{%- if messages[0].role == 'system' %} {%- set system_content = render_content(messages[0].content) %} {%- if 'detailed thinking on' in system_content or 'detailed thinking off' in system_content %} {%- set has_thinking_instruction = true %} {%- endif %} {{- system_content }} {%- if (tools or not has_thinking_instruction) and system_content and system_content[-1] != '\n' %} {{- '\n' }} {%- endif %}{%- endif %}{%- if tools %} {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }} {%- for tool in tools %} {{- "\n" }} {{- tool | tojson }} {%- endfor %} {{- "\n</tools>\n\nIf none of the functions can be used, point it out. If the given question lacks the parameters required by the function, also point it out.\nIf you need to use a function, for each function call, output the function name and arguments within the following XML format:\n<tool_call>{function-name}\n<arg_key>{arg-key-1}</arg_key>\n<arg_value>{arg-value-1}</arg_value>\n<arg_key>{arg-key-2}</arg_key>\n<arg_value>{arg-value-2}</arg_value>\n...\n</tool_call>\n" }}{%- endif %}{%- if not has_thinking_instruction %} {{- thinking_instruction }}{%- endif %}{{- '<|role_end|>' }}
{#- ==================== multi_step_tool: find last real user query ==================== -#}{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}{%- for message in messages[::-1] %} {%- set index = (messages|length - 1) - loop.index0 %} {%- if ns.multi_step_tool and message.role == "user" %} {%- set user_content = render_content(message.content) %} {%- if not(user_content.startswith('<tool_response>') and user_content.endswith('</tool_response>')) %} {%- set ns.multi_step_tool = false %} {%- set ns.last_query_index = index %} {%- endif %} {%- endif %}{%- endfor %}
{#- ==================== message loop ==================== -#}{%- for message in messages %} {%- if message.role == "user" %} {%- set content = render_content(message.content) %} {{- '<role>HUMAN</role>' + content + '<|role_end|>' }} {%- elif message.role == "system" %} {%- if not loop.first %} {%- set content = render_content(message.content) %} {{- '<role>SYSTEM</role>' + content + '<|role_end|>' }} {%- endif %} {%- elif message.role == "assistant" %} {%- set content = render_content(message.content) %} {%- set reasoning_content = '' %} {%- if message.reasoning_content is string and message.reasoning_content != '' %} {%- set reasoning_content = message.reasoning_content %} {%- else %} {%- if '</think>' in content %} {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %} {%- set content = content.split('</think>')[-1].lstrip('\n') %} {%- endif %} {%- endif %} {%- if preserve_thinking or loop.index0 > ns.last_query_index %} {%- if reasoning_content != '' %} {{- '<role>ASSISTANT</role>' + '\n<think>' + reasoning_content.strip('\n') + '</think>' + content.lstrip('\n') }} {%- else %} {{- '<role>ASSISTANT</role>\n<think></think>' + content }} {%- endif %} {%- else %} {{- '<role>ASSISTANT</role>\n<think></think>' + content }} {%- endif %} {%- if message.tool_calls %} {%- for tool_call in message.tool_calls %} {%- if (loop.first and content) or (not loop.first) %} {{- '\n' }} {%- endif %} {%- set tc = tool_call %} {%- if tool_call.function %} {%- set tc = tool_call.function %} {%- endif %} {{- '<tool_call>' + tc.name }} {%- set _args = tc.arguments %} {%- for k, v in _args.items() %} {{- '\n<arg_key>' + k + '</arg_key>' }} {{- '\n<arg_value>' }} {%- if v is string %} {{- v }} {%- else %} {{- v | tojson(ensure_ascii=False) }} {%- endif %} {{- '</arg_value>' }} {%- endfor %} {{- '\n</tool_call>' }} {%- endfor %} {%- endif %} {{- '<|role_end|>' }} {%- elif message.role == "tool" %} {%- set content = render_content(message.content) %} {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} {{- '<role>OBSERVATION</role>' }} {%- endif %} {{- '\n<tool_response>\n' }} {{- content }} {{- '\n</tool_response>' }} {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} {{- '<|role_end|>' }} {%- endif %} {%- else %} {%- set content = render_content(message.content) %} {{- '<role>' + message.role + '</role>' + content + '<|role_end|>' }} {%- endif %}{%- endfor %}
{#- ==================== generation prompt ==================== -#}{%- if add_generation_prompt %} {{- '<role>ASSISTANT</role>' }} {%- if enable_thinking %} {{- '\n<think>' }} {%- else %} {{- '\n<think></think>' }} {%- endif %}{%- endif %}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106{ "architectures": [ "BailingMoeV3AudioForConditionalGeneration" ], "audio_config": { "downsampler_kernel_size_list": [ 3, 3, 3 ], "downsampler_stride_list": [ 2, 2, 2 ], "model_type": "bailing_moe_v3_audio", "n_audio_ctx": 3000, "n_audio_head": 20, "n_audio_layer": 32, "n_audio_state": 1280, "n_mels": 128 }, "audio_token_id": 157168, "auto_map": { "AutoConfig": "configuration_bailing_moe_v3_audio.BailingMoeV3AudioConfig", "AutoModel": "modeling_bailing_moe_v3_audio.BailingMoeV3AudioForConditionalGeneration", "AutoModelForCausalLM": "modeling_bailing_moe_v3_audio.BailingMoeV3AudioForConditionalGeneration", "AutoProcessor": "processing_bailing_moe_v3_audio.BailingMoeV3AudioProcessor" }, "dtype": "bfloat16", "model_type": "bailing_moe_v3_audio", "norm_query_embeds": true, "text_config": { "attention_dropout": 0.0, "embedding_dropout": 0.0, "expert_swiglu_limit_list": null, "first_k_dense_replace": 1, "gated_attention_proj_granularity_type": "head_wise", "group_norm_size": 1, "head_dim": 128, "hidden_act": "silu", "hidden_size": 1536, "initializer_range": 0.02, "intermediate_size": 4608, "kda_lower_bound": -5, "kda_safe_gate": true, "kv_lora_rank": 512, "layer_group_size": 4, "linear_silu": true, "max_position_embeddings": 131072, "max_window_layers": 20, "model_type": "", "moe_intermediate_size": 512, "moe_router_enable_expert_bias": true, "moe_shared_expert_intermediate_size": 512, "mtp_loss_scaling_factor": 0, "mtp_use_kda": false, "n_group": 8, "no_kda_lora": true, "norm_topk_prob": true, "num_attention_heads": 16, "num_experts": 128, "num_experts_per_tok": 8, "num_hidden_layers": 24, "num_key_value_heads": 16, "num_kv_heads_for_linear_attn": 0, "num_nextn_predict_layers": 1, "num_shared_experts": 1, "output_dropout": 0.0, "output_router_logits": false, "partial_rotary_factor": 0.5, "q_lora_rank": 256, "qk_head_dim": 192, "qk_nope_head_dim": 128, "qk_rope_head_dim": 64, "rms_norm_eps": 1e-06, "rope_interleave": true, "rope_scaling": null, "rope_theta": 6000000, "rotary_dim": 64, "routed_scaling_factor": 2.5, "router_dtype": "fp32", "scale_router_input": false, "score_function": "sigmoid", "scoring_func": "sigmoid", "seq_aux": true, "share_expert_swiglu_limit_list": null, "short_conv_kernel_size": 4, "topk_group": 4, "topk_method": "noaux_tc", "up_proj_norm": false, "use_bias": false, "use_cache": true, "use_kda_lora": false, "use_mla_nope": false, "use_nGPT": false, "use_qk_norm": true, "use_qkv_bias": false, "v_head_dim": 128, "value_norm": false, "vocab_size": 157184 }, "tie_word_embeddings": false, "transformers_version": "5.14.1", "torch_dtype": "bfloat16"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130"""Bailing MoE V2 model configuration"""
from transformers.configuration_utils import PretrainedConfig
class BailingMoeV3Config(PretrainedConfig):
def __init__( self, vocab_size=157184, hidden_size=2048, intermediate_size=5120, num_hidden_layers=20, num_attention_heads=16, num_key_value_heads=4, hidden_act="silu", use_qkv_bias=False, # bailing only use_bias=False, # bailing only rms_norm_eps=1e-06, tie_word_embeddings=False, # PretrainedConfig key, here change default value. embedding_dropout=0.0, attention_dropout=0.0, output_dropout=0.0, initializer_range=0.02, max_position_embeddings=32768, rope_theta=600000.0, use_cache=True, max_window_layers=20, rope_scaling=None, pad_token_id=156892, eos_token_id=156892, num_experts=256, num_shared_experts=1, num_experts_per_tok=8, n_group=8, topk_group=4, moe_intermediate_size=512, moe_shared_expert_intermediate_size=512, expert_swiglu_limit_list=None, share_expert_swiglu_limit_list=None, first_k_dense_replace=1, head_dim=128, output_router_logits=False, use_qk_norm=True, num_nextn_predict_layers=0, mtp_loss_scaling_factor=0, moe_router_enable_expert_bias=True, routed_scaling_factor=1.0, layer_group_size=5, kv_lora_rank=512, q_lora_rank=None, qk_rope_head_dim=64, v_head_dim=128, qk_nope_head_dim=128, rope_interleave=True, score_function="sigmoid", scoring_func="sigmoid", seq_aux=True, topk_method="noaux_tc", router_dtype="fp32", gated_attention_proj_granularity_type=None, no_kda_lora=False, kda_safe_gate=False, kda_lower_bound=None, short_conv_kernel_size=4, **kwargs, ): self.num_hidden_layers = num_hidden_layers self.vocab_size = vocab_size self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.hidden_act = hidden_act self.use_qkv_bias = use_qkv_bias self.use_bias = use_bias self.rms_norm_eps = rms_norm_eps self.embedding_dropout = embedding_dropout self.attention_dropout = attention_dropout self.output_dropout = output_dropout self.num_nextn_predict_layers = num_nextn_predict_layers self.mtp_loss_scaling_factor = mtp_loss_scaling_factor self.initializer_range = initializer_range self.max_position_embeddings = max_position_embeddings self.rope_theta = rope_theta self.use_cache = use_cache self.max_window_layers = max_window_layers self.head_dim = head_dim or self.hidden_size // self.num_attention_heads self.rope_scaling = rope_scaling self.use_qk_norm = use_qk_norm self.moe_router_enable_expert_bias = moe_router_enable_expert_bias self.routed_scaling_factor = routed_scaling_factor
# MoE configs self.num_experts = num_experts self.num_shared_experts = num_shared_experts self.num_experts_per_tok = num_experts_per_tok self.n_group = n_group self.topk_group = topk_group self.moe_intermediate_size = moe_intermediate_size self.moe_shared_expert_intermediate_size = moe_shared_expert_intermediate_size self.expert_swiglu_limit_list = expert_swiglu_limit_list self.share_expert_swiglu_limit_list = share_expert_swiglu_limit_list self.first_k_dense_replace = first_k_dense_replace self.output_router_logits = output_router_logits
# Linear configs self.layer_group_size = layer_group_size # mla self.kv_lora_rank = kv_lora_rank self.q_lora_rank = q_lora_rank self.qk_rope_head_dim = qk_rope_head_dim
self.score_function = score_function self.scoring_func = scoring_func self.seq_aux = seq_aux self.topk_method = topk_method self.v_head_dim = v_head_dim self.qk_nope_head_dim = qk_nope_head_dim self.qk_head_dim = qk_nope_head_dim + qk_rope_head_dim self.rope_interleave = rope_interleave self.router_dtype = router_dtype self.gated_attention_proj_granularity_type = gated_attention_proj_granularity_type self.no_kda_lora = no_kda_lora self.kda_safe_gate = kda_safe_gate self.kda_lower_bound = kda_lower_bound self.short_conv_kernel_size = short_conv_kernel_size super().__init__( pad_token_id=pad_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226# Copyright 2025 Antgroup and The HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
"""BailingMoE V3 Audio model configuration."""
import osfrom typing import Union
from transformers.configuration_utils import PretrainedConfigfrom transformers.utils import logging
logger = logging.get_logger(__name__)
class BailingMoeV3Config(PretrainedConfig):
def __init__( self, vocab_size=157184, hidden_size=2048, intermediate_size=5120, num_hidden_layers=20, num_attention_heads=16, num_key_value_heads=4, hidden_act="silu", use_qkv_bias=False, # bailing only use_bias=False, # bailing only rms_norm_eps=1e-06, tie_word_embeddings=False, # PretrainedConfig key, here change default value. embedding_dropout=0.0, attention_dropout=0.0, output_dropout=0.0, initializer_range=0.02, max_position_embeddings=32768, rope_theta=600000.0, use_cache=True, max_window_layers=20, rope_scaling=None, pad_token_id=156892, eos_token_id=156892, num_experts=256, num_shared_experts=1, num_experts_per_tok=8, n_group=8, topk_group=4, moe_intermediate_size=512, moe_shared_expert_intermediate_size=512, expert_swiglu_limit_list=None, share_expert_swiglu_limit_list=None, first_k_dense_replace=1, head_dim=128, output_router_logits=False, use_qk_norm=True, num_nextn_predict_layers=0, mtp_loss_scaling_factor=0, moe_router_enable_expert_bias=True, routed_scaling_factor=1.0, layer_group_size=5, kv_lora_rank=512, q_lora_rank=None, qk_rope_head_dim=64, v_head_dim=128, qk_nope_head_dim=128, rope_interleave=True, score_function="sigmoid", scoring_func="sigmoid", seq_aux=True, topk_method="noaux_tc", router_dtype="fp32", gated_attention_proj_granularity_type=None, no_kda_lora=False, kda_safe_gate=False, kda_lower_bound=None, short_conv_kernel_size=4, **kwargs, ): self.num_hidden_layers = num_hidden_layers self.vocab_size = vocab_size self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.hidden_act = hidden_act self.use_qkv_bias = use_qkv_bias self.use_bias = use_bias self.rms_norm_eps = rms_norm_eps self.embedding_dropout = embedding_dropout self.attention_dropout = attention_dropout self.output_dropout = output_dropout self.num_nextn_predict_layers = num_nextn_predict_layers self.mtp_loss_scaling_factor = mtp_loss_scaling_factor self.initializer_range = initializer_range self.max_position_embeddings = max_position_embeddings self.rope_theta = rope_theta self.use_cache = use_cache self.max_window_layers = max_window_layers self.head_dim = head_dim or self.hidden_size // self.num_attention_heads self.rope_scaling = rope_scaling self.use_qk_norm = use_qk_norm self.moe_router_enable_expert_bias = moe_router_enable_expert_bias self.routed_scaling_factor = routed_scaling_factor
# MoE configs self.num_experts = num_experts self.num_shared_experts = num_shared_experts self.num_experts_per_tok = num_experts_per_tok self.n_group = n_group self.topk_group = topk_group self.moe_intermediate_size = moe_intermediate_size self.moe_shared_expert_intermediate_size = moe_shared_expert_intermediate_size self.expert_swiglu_limit_list = expert_swiglu_limit_list self.share_expert_swiglu_limit_list = share_expert_swiglu_limit_list self.first_k_dense_replace = first_k_dense_replace self.output_router_logits = output_router_logits
# Linear configs self.layer_group_size = layer_group_size # mla self.kv_lora_rank = kv_lora_rank self.q_lora_rank = q_lora_rank self.qk_rope_head_dim = qk_rope_head_dim
self.score_function = score_function self.scoring_func = scoring_func self.seq_aux = seq_aux self.topk_method = topk_method self.v_head_dim = v_head_dim self.qk_nope_head_dim = qk_nope_head_dim self.qk_head_dim = qk_nope_head_dim + qk_rope_head_dim self.rope_interleave = rope_interleave self.router_dtype = router_dtype self.gated_attention_proj_granularity_type = gated_attention_proj_granularity_type self.no_kda_lora = no_kda_lora self.kda_safe_gate = kda_safe_gate self.kda_lower_bound = kda_lower_bound self.short_conv_kernel_size = short_conv_kernel_size super().__init__( pad_token_id=pad_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs )
class BailingMoeV3AudioEncoderConfig(PretrainedConfig): model_type = "bailing_moe_v3_audio_encoder"
def __init__( self, n_mels=128, n_audio_ctx=3000, n_audio_state=1280, n_audio_head=20, n_audio_layer=32, downsampler_kernel_size_list=None, downsampler_stride_list=None, downsampler_padding_list=None, whisper_chunk_size=3000, **kwargs, ): super().__init__(**kwargs) self.n_mels = n_mels self.n_audio_ctx = n_audio_ctx self.n_audio_state = n_audio_state self.n_audio_head = n_audio_head self.n_audio_layer = n_audio_layer self.downsampler_kernel_size_list = downsampler_kernel_size_list or [3] self.downsampler_stride_list = downsampler_stride_list or [2] self.downsampler_padding_list = downsampler_padding_list or [ kernel // 2 for kernel in self.downsampler_kernel_size_list ] self.whisper_chunk_size = whisper_chunk_size
@classmethod def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig": config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs) if "audio_config" in config_dict: config_dict = config_dict["audio_config"] return cls.from_dict(config_dict, **kwargs)
class BailingMoeV3AudioConfig(PretrainedConfig): model_type = "bailing_moe_v3_audio"
def __init__( self, text_config=None, audio_config=None, audio_token_id=157168, norm_query_embeds=False, tie_word_embeddings=False, **kwargs, ): if isinstance(text_config, dict): text_config = BailingMoeV3Config(**text_config) elif text_config is None: text_config = BailingMoeV3Config()
if isinstance(audio_config, dict): audio_config = BailingMoeV3AudioEncoderConfig(**audio_config) elif audio_config is None: audio_config = BailingMoeV3AudioEncoderConfig()
self.text_config = text_config self.audio_config = audio_config self.audio_token_id = audio_token_id self.norm_query_embeds = norm_query_embeds
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
@classmethod def from_pretrained( cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs ) -> "BailingMoeV3AudioConfig": config_dict, kwargs = cls.get_config_dict( pretrained_model_name_or_path, **kwargs ) config_dict["model_type"] = cls.model_type return cls.from_dict(config_dict, **kwargs)1234567{ "eos_token_id": [ 156892, 156895 ], "pad_token_id": 156892}123version https://git-lfs.github.com/spec/v1oid sha256:53b7663c7c52aa36e487977d6e9bb2f5666b7aaa543bd5d5dd4e96ec88cfd957size 9551820960123version https://git-lfs.github.com/spec/v1oid sha256:08d9e7bd9d885a0d6608953c6bbe40dbfb67f673a0cce9382414b55a9380053asize 81921226491234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687# coding=utf-8# Copyright 2025 Antgroup and The HuggingFace Inc. team. All rights reserved.## This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX# and OPT implementations in this library. It has been modified from its# original forms to accommodate minor architectural differences compared# to GPT-NeoX and OPT used by the Meta AI team that trained the model.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""PyTorch BailingMoE model."""
import mathimport warningsfrom typing import List, Optional, Tuple, Union, Callablefrom copy import deepcopy
import torchimport torch.nn.functional as Ffrom torch import nn
from transformers.activations import ACT2FNfrom transformers.cache_utils import Cache, DynamicCachefrom transformers.modeling_attn_mask_utils import ( AttentionMaskConverter, _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa,)from transformers.modeling_outputs import MoeModelOutputWithPastfrom transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_updatefrom transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModelfrom transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13from transformers.utils import ( add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings,)try: from transformers.utils.import_utils import is_torch_fx_availableexcept ImportError: def is_torch_fx_available(): return Falsefrom .configuration_bailing_moe_v3 import BailingMoeV3Configfrom transformers.generation.utils import GenerationMixinfrom dataclasses import dataclassfrom transformers.utils import ModelOutputfrom transformers import DynamicLayerfrom transformers.processing_utils import Unpackfrom transformers.utils import TransformersKwargsfrom transformers.utils.deprecation import deprecate_kwargfrom transformers.modeling_flash_attention_utils import FlashAttentionKwargs
from fla.ops.simple_gla.fused_recurrent import fused_recurrent_simple_glafrom fla.ops.simple_gla.chunk import chunk_simple_glafrom einops import rearrange, repeat
try: from fla.modules import FusedRMSNormGated, ShortConvolution from fla.ops.kda import chunk_kda, fused_recurrent_kda
from fla.ops.utils.index import prepare_cu_seqlens_from_mask, prepare_lens_from_mask from fla.utils import tensor_cacheexcept ImportError: raise ImportError("Plese run `pip install -U fla-core`")
# This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.# It means that the function will not be traced through and simply appear as a node in the graph.if is_torch_fx_available(): if not is_torch_greater_or_equal_than_1_13: import torch.fx
_prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
logger = logging.get_logger(__name__)
_CONFIG_FOR_DOC = "BailingMoeV3Config"
def roll_tensor(tensor, shifts=-1, dims=-1, fill_value=0): """Roll the tensor input along the given dimension(s). Inserted elements are set to be 0.0. """ rolled_tensor = torch.roll(tensor, shifts=shifts, dims=dims) rolled_tensor.select(dims, shifts).fill_(fill_value) return rolled_tensor, rolled_tensor.sum()
@dataclassclass MoEV3CausalLMOutputWithPast(ModelOutput): """ Base class for causal language model (or autoregressive) outputs as well as Mixture of Expert's router hidden states terms, to train a MoE model. Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Language modeling loss (for next-token prediction). logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. z_loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided): z_loss for the sparse modules. aux_loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided): aux_loss for the sparse modules. router_logits (`tuple(torch.FloatTensor)`, *optional*, returned when `output_router_logits=True` is passed or when `config.add_router_probs=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_experts)`. Router logits of the encoder model, useful to compute the auxiliary loss and the z_loss for the sparse modules. """
loss: Optional[torch.FloatTensor] = None logits: Optional[torch.FloatTensor] = None past_key_values: Optional[Cache] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None z_loss: Optional[torch.FloatTensor] = None aux_loss: Optional[torch.FloatTensor] = None router_logits: Optional[tuple[torch.FloatTensor]] = None mtp_loss: Optional[torch.FloatTensor] = None mtp_logits: Optional[tuple[torch.FloatTensor, ...]] = None
class MoeV3ModelOutputWithPast(MoeModelOutputWithPast):
def __init__(self, mtp_hidden_states=None, **kwargs): super().__init__(**kwargs) self.mtp_hidden_states = mtp_hidden_states
def index_first_axis(x, indices): other_shape = x.shape[1:] second_dim = other_shape.numel() return torch.gather( rearrange(x, "b ... -> b (...)"), 0, repeat(indices, "z -> z d", d=second_dim), ).reshape(-1, *other_shape)
def index_put_first_axis(x, indices, first_axis_dim): y = torch.zeros(first_axis_dim, *x.shape[1:], device=x.device, dtype=x.dtype) y[indices] = x # y.scatter_(0, repeat(indices, 'z -> z d', d=x.shape[1]), x) return y
def pad_input( hidden_states: torch.Tensor, indices: torch.LongTensor, batch_size: int, seq_len: int,) -> torch.Tensor: output = index_put_first_axis(hidden_states, indices, batch_size * seq_len) return rearrange(output, "(b s) ... -> b s ...", b=batch_size)
@tensor_cachedef _get_unpad_data(attention_mask): seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32) indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten() max_seqlen_in_batch = seqlens_in_batch.max().item() cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)) return ( indices, cu_seqlens, max_seqlen_in_batch, )
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): warnings.warn( "Calling `transformers.models.BailingMoeV3.modeling_BailingMoeV3._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask" ) return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
def _make_causal_mask( input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0): warnings.warn( "Calling `transformers.models.BailingMoeV3.modeling_BailingMoeV3._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.BailingMoeV3.modeling_BailingMoeV3.AttentionMaskConverter._make_causal_mask" ) return AttentionMaskConverter._make_causal_mask( input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length )
class BailingMoeV3RMSNorm(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ BailingMoeV3RMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps
def forward(self, hidden_states): input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) return self.weight * hidden_states.to(input_dtype)
class BailingMoeV3GroupRMSNorm(nn.Module): def __init__(self, hidden_size, group_norm_size, eps=1e-6): """ BailingMoeV3RMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.group_norm_size = group_norm_size assert hidden_size % group_norm_size == 0, "hidden_size must be divisible by group_norm_size" self.variance_epsilon = eps
def forward(self, hidden_states): input_dtype = hidden_states.dtype input_shape = hidden_states.size() group_input_shape = input_shape[:-1] + (self.group_norm_size, input_shape[-1] // self.group_norm_size) hidden_states = hidden_states.view(group_input_shape) hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) return self.weight * hidden_states.to(input_dtype).view(input_shape)
ALL_LAYERNORM_LAYERS.append(BailingMoeV3RMSNorm)
def _compute_default_rope_parameters(config, device=None, seq_len=None): # Transformers 5 no longer includes the unscaled initializer in its registry. dim = int(config.head_dim * getattr(config, "partial_rotary_factor", 1.0)) inv_freq = 1.0 / ( config.rope_theta ** (torch.arange(0, dim, 2, device=device).float() / dim) ) return inv_freq, 1.0
class BailingMoeV3RotaryEmbedding(nn.Module): def __init__(self, config: BailingMoeV3Config, device=None): super().__init__() # BC: "rope_type" was originally "type" if hasattr(config, "rope_scaling") and config.rope_scaling is not None: self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type")) else: self.rope_type = "default" self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings
self.config = deepcopy(config) self.config.head_dim = config.qk_rope_head_dim self.config.partial_rotary_factor = 1.0 self.rope_init_fn = ( _compute_default_rope_parameters if self.rope_type == "default" else ROPE_INIT_FUNCTIONS[self.rope_type] )
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device) self.register_buffer("inv_freq", inv_freq, persistent=False) self.original_inv_freq = self.inv_freq
@torch.no_grad() @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device) position_ids_expanded = position_ids[:, None, :].float()
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with torch.autocast(device_type=device_type, enabled=False): # Force float32 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2) emb = torch.cat((freqs, freqs), dim=-1) cos = emb.cos() * self.attention_scaling sin = emb.sin() * self.attention_scaling
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
# Copied from transformers.models.llama.modeling_llama.rotate_halfdef rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1)
# Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_embdef apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1): """Applies Rotary Position Embedding to the query and key tensors. Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. Returns: `tuple(torch.Tensor)` comprising the query and key tensors rotated using the Rotary Position Embedding. """ cos = cos.unsqueeze(unsqueeze_dim) sin = sin.unsqueeze(unsqueeze_dim)
# Keep half or full tensor for later concatenation rotary_dim = cos.shape[-1] q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:] k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
# Apply rotary embeddings on the first half or full tensor q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin) k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
# Concatenate back to full shape q_embed = torch.cat([q_embed, q_pass], dim=-1) k_embed = torch.cat([k_embed, k_pass], dim=-1) return q_embed, k_embed
class BailingMoeV3MLP(nn.Module): def __init__( self, config: BailingMoeV3Config, intermediate_size: int, swiglu_limit: Optional[float] = None, ): super().__init__() self.config = config self.hidden_size = config.hidden_size self.intermediate_size = intermediate_size self.swiglu_limit = swiglu_limit
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False) self.act_fn = ACT2FN[config.hidden_act]
def forward(self, x): gate = self.act_fn(self.gate_proj(x)) up = self.up_proj(x) if self.swiglu_limit is not None: gate = gate.clamp(max=self.swiglu_limit) up = up.clamp(min=-self.swiglu_limit, max=self.swiglu_limit) return self.down_proj(gate * up)
class BailingMoeV3Gate(nn.Module): def __init__(self, config): super().__init__() self.config = config self.top_k = config.num_experts_per_tok self.num_experts = config.num_experts
self.n_group = config.n_group self.topk_group = config.topk_group
# topk selection algorithm self.gating_dim = config.hidden_size self.weight = nn.Parameter(torch.empty((self.num_experts, self.gating_dim))) self.routed_scaling_factor = config.routed_scaling_factor
self.register_buffer("expert_bias", torch.zeros((self.num_experts))) self.reset_parameters()
def reset_parameters(self) -> None: import torch.nn.init as init
init.kaiming_uniform_(self.weight, a=math.sqrt(5))
def group_limited_topk( self, scores: torch.Tensor, ): num_tokens, _ = scores.size() # Organize the experts into groups group_scores = scores.view(num_tokens, self.n_group, -1).topk(2, dim=-1)[0].sum(dim=-1) group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1] group_mask = torch.zeros_like(group_scores) group_mask.scatter_(1, group_idx, 1)
# Mask the experts based on selection groups score_mask = ( group_mask.unsqueeze(-1) .expand(num_tokens, self.n_group, self.num_experts // self.n_group) .reshape(num_tokens, -1) )
masked_scores = scores.masked_fill(~score_mask.bool(), float('-inf')) probs, top_indices = torch.topk(masked_scores, k=self.top_k, dim=-1)
return probs, top_indices
def forward(self, hidden_states): # compute gating score hidden_states = hidden_states.view(-1, hidden_states.shape[-1]) logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))
scores = torch.sigmoid(logits.float()).type_as(logits)
scores_for_routing = scores + self.expert_bias _, topk_idx = self.group_limited_topk(scores_for_routing)
scores = torch.gather(scores, dim=1, index=topk_idx).type_as(logits)
topk_weight = scores / (scores.sum(dim=-1, keepdim=True) + 1e-20) if self.top_k > 1 else scores topk_weight = topk_weight * self.routed_scaling_factor
return topk_idx, topk_weight, logits
class BailingMoeV3SparseMoeBlock(nn.Module): """ A mixed expert module containing shared experts. """
@staticmethod def _get_swiglu_limit(limit_list, layer_idx): if limit_list is None or layer_idx < 0 or layer_idx >= len(limit_list): return None limit = limit_list[layer_idx] return None if limit == 0 else limit
def __init__(self, config: BailingMoeV3Config, layer_idx: int): super().__init__() self.config = config self.num_experts_per_tok = config.num_experts_per_tok self.expert_swiglu_limit = self._get_swiglu_limit( getattr(config, "expert_swiglu_limit_list", None), layer_idx ) self.share_expert_swiglu_limit = self._get_swiglu_limit( getattr(config, "share_expert_swiglu_limit_list", None), layer_idx ) self._setup_experts() self.gate = BailingMoeV3Gate(config) if config.num_shared_experts is not None: self.shared_experts = BailingMoeV3MLP( config=config, intermediate_size=config.moe_shared_expert_intermediate_size * config.num_shared_experts, swiglu_limit=self.share_expert_swiglu_limit, )
def _setup_experts(self): self.experts = nn.ModuleList( [ BailingMoeV3MLP( config=self.config, intermediate_size=self.config.moe_intermediate_size, swiglu_limit=self.expert_swiglu_limit, ) for _ in range(self.config.num_experts) ] )
def forward(self, hidden_states): identity = hidden_states bsz, seq_len, h = hidden_states.shape topk_idx, topk_weight, router_logits = self.gate(hidden_states) hidden_states = hidden_states.view(-1, hidden_states.shape[-1]) flat_topk_idx = topk_idx.view(-1) if self.training: hidden_states = hidden_states.repeat_interleave(self.num_experts_per_tok, dim=0) y = torch.empty_like(hidden_states) for i, expert in enumerate(self.experts): y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i]) y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1) y = y.to(hidden_states.dtype).view(bsz, seq_len, h) else: y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(bsz, seq_len, h) if self.config.num_shared_experts is not None: y = y + self.shared_experts(identity) return y, (router_logits.view(bsz, seq_len, -1), topk_idx.view(bsz, seq_len, -1))
@torch.no_grad() def moe_infer(self, x, topk_ids, topk_weight): cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts))) cnts.scatter_(1, topk_ids, 1) tokens_per_expert = cnts.sum(dim=0) idxs = topk_ids.view(-1).argsort() sorted_tokens = x[idxs // topk_ids.shape[1]] tokens_per_expert = tokens_per_expert.cpu().numpy() outputs = [] start_idx = 0 for i, num_tokens in enumerate(tokens_per_expert): end_idx = start_idx + num_tokens if num_tokens == 0: continue expert = self.experts[i] tokens_for_this_expert = sorted_tokens[start_idx:end_idx] expert_out = expert(tokens_for_this_expert) outputs.append(expert_out.to(x.device)) start_idx = end_idx
outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0) new_x = torch.empty_like(outs) new_x[idxs] = outs final_out = ( new_x.view(*topk_ids.shape, -1) .type(topk_weight.dtype) .mul_(topk_weight.unsqueeze(dim=-1)) .sum(dim=1) .type(new_x.dtype) ) return final_out
# Copied from transformers.models.llama.modeling_llama.repeat_kvdef repeat_kv(hidden_states: torch.Tensor, n_rep: int, head_first: bool = True) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). If head_first is True, the hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ if n_rep == 1: return hidden_states if head_first: batch, num_key_value_heads, slen, head_dim = hidden_states.shape hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) else: batch, slen, num_key_value_heads, head_dim = hidden_states.shape hidden_states = hidden_states[:, :, :, None, :].expand(batch, slen, num_key_value_heads, n_rep, head_dim) return hidden_states.reshape(batch, slen, num_key_value_heads * n_rep, head_dim)
def repeat_kv2(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
def eager_attention_forward( module: nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: Optional[torch.Tensor], scaling: float, dropout: float = 0.0, **kwargs: Unpack[TransformersKwargs],): key_states = repeat_kv2(key, module.num_key_value_groups) value_states = repeat_kv2(value, module.num_key_value_groups)
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling if attention_mask is not None: causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] attn_weights = attn_weights + causal_mask
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) attn_output = torch.matmul(attn_weights, value_states) attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
def apply_rotary_pos_emb_interleave(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): r""" TODO let's just use the original freqcis computation to not have the view transpose + reshape! This is not optimized! Applies Rotary Position Embedding to the query and key tensors.
Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. position_ids (`torch.Tensor`): The position indices of the tokens corresponding to the query and key tensors. For example, this can be used to pass offsetted position ids when working with a KV-cache. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ cos = cos.unsqueeze(unsqueeze_dim) sin = sin.unsqueeze(unsqueeze_dim)
def rotate_pairs(x): half_dim = x.shape[-1] // 2 x_pairs = x.reshape(*x.shape[:-1], half_dim, 2) x_even, x_odd = x_pairs.unbind(dim=-1) pair_cos = cos[..., :half_dim] pair_sin = sin[..., :half_dim] return torch.stack( ( x_even * pair_cos - x_odd * pair_sin, x_odd * pair_cos + x_even * pair_sin, ), dim=-1, ).flatten(-2)
return rotate_pairs(q), rotate_pairs(k)
def yarn_get_mscale(scale=1, mscale=1): if scale <= 1: return 1.0 return 0.1 * mscale * math.log(scale) + 1.0
class BailingMoeV3MultiLatentAttention(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: BailingMoeV3Config, layer_idx: int): super().__init__() self.config = config self.layer_idx = layer_idx self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads self.attention_dropout = config.attention_dropout self.num_heads = config.num_attention_heads self.rope_theta = config.rope_theta self.q_lora_rank = config.q_lora_rank self.qk_rope_head_dim = config.qk_rope_head_dim self.kv_lora_rank = config.kv_lora_rank self.v_head_dim = config.v_head_dim self.qk_nope_head_dim = config.qk_nope_head_dim self.qk_head_dim = config.qk_head_dim self.gated_attention_proj_granularity_type = config.gated_attention_proj_granularity_type
self.is_causal = True if self.q_lora_rank is None: self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.qk_head_dim, bias=False) else: self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=config.use_qkv_bias) self.q_a_layernorm = BailingMoeV3RMSNorm(config.q_lora_rank) self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
self.kv_a_proj_with_mqa = nn.Linear( config.hidden_size, self.kv_lora_rank + self.qk_rope_head_dim, bias=config.use_qkv_bias, ) self.kv_a_layernorm = BailingMoeV3RMSNorm(self.kv_lora_rank) self.kv_b_proj = nn.Linear( self.kv_lora_rank, self.num_heads * (self.qk_nope_head_dim + self.v_head_dim), bias=False, ) if self.gated_attention_proj_granularity_type is None: self.g_proj = None elif self.gated_attention_proj_granularity_type == "head_wise": self.g_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False) elif self.gated_attention_proj_granularity_type == "element_wise": self.g_proj = nn.Linear(config.hidden_size, self.num_heads * self.v_head_dim, bias=False)
self.dense = nn.Linear( self.num_heads * self.v_head_dim, config.hidden_size, bias=config.use_qkv_bias, )
self.scaling = self.qk_head_dim ** (-0.5) if self.config.rope_scaling is not None: mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0) if mscale_all_dim: scaling_factor = self.config.rope_scaling["factor"] mscale = yarn_get_mscale(scaling_factor, mscale_all_dim) self.scaling = self.scaling * mscale * mscale
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58") def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: Optional[torch.Tensor], past_key_values: Optional[Cache] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
batch_size, seq_length = hidden_states.shape[:-1] query_shape = (batch_size, seq_length, -1, self.qk_head_dim) key_shape = (batch_size, seq_length, -1, self.qk_nope_head_dim + self.v_head_dim)
if self.q_lora_rank is None: q_states = self.q_proj(hidden_states) else: q_states = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states))) q_states = q_states.view(query_shape).transpose(1, 2) q_pass, q_rot = torch.split(q_states, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
compressed_kv = self.kv_a_proj_with_mqa(hidden_states) k_pass, k_rot = torch.split(compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
k_pass = self.kv_b_proj(self.kv_a_layernorm(k_pass)).view(key_shape).transpose(1, 2) k_pass, value_states = torch.split(k_pass, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
k_rot = k_rot.view(batch_size, 1, seq_length, self.qk_rope_head_dim)
cos, sin = position_embeddings # tptest if self.config.rope_interleave: # support using interleaved weights for efficiency q_rot, k_rot = apply_rotary_pos_emb_interleave(q_rot, k_rot, cos, sin) else: x = 1 / 0 q_rot, k_rot = apply_rotary_pos_emb(q_rot, k_rot, cos, sin) k_rot = k_rot.expand(*k_pass.shape[:-1], -1)
query_states = torch.cat((q_pass, q_rot), dim=-1) key_states = torch.cat((k_pass, k_rot), dim=-1)
if past_key_values is not None: # sin and cos are specific to RoPE models; cache_position needed for the static cache cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
if self.config._attn_implementation == "flash_attention_2" and self.qk_head_dim != self.v_head_dim: value_states = F.pad(value_states, [0, self.qk_head_dim - self.v_head_dim])
attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": attention_interface = ALL_ATTENTION_FUNCTIONS.get( self.config._attn_implementation, eager_attention_forward )
attn_output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, **kwargs, )
if self.config._attn_implementation == "flash_attention_2" and self.qk_head_dim != self.v_head_dim: attn_output = attn_output[:, :, :, : self.v_head_dim]
if self.g_proj is not None: gate = self.g_proj(hidden_states) gate = F.sigmoid(gate.float()).type_as(hidden_states) if self.gated_attention_proj_granularity_type == "head_wise": attn_output = attn_output * gate[:, :, :, None] else: attn_output = attn_output * gate.view(batch_size, seq_length, self.num_heads, self.v_head_dim)
attn_output = attn_output.reshape(batch_size, seq_length, -1).contiguous() attn_output = self.dense(attn_output) return attn_output, attn_weights, past_key_values
class BailingMoeV3KimiDeltaAttention(nn.Module): def __init__(self, config: BailingMoeV3Config, layer_idx: int): super().__init__() self.config = config self.mode = "chunk"
self.hidden_size = config.hidden_size self.conv_size = config.short_conv_kernel_size self.head_dim = config.head_dim self.num_heads = config.num_attention_heads self.head_k_dim = self.head_dim self.num_k_heads = self.num_heads self.no_kda_lora = config.no_kda_lora self.safe_gate = config.kda_safe_gate self.lower_bound = config.kda_lower_bound
self.layer_idx = layer_idx
assert self.mode in ['chunk', 'fused_recurrent'], f"Not suppoerted mode `{self.mode}`."
projection_k_size = self.head_k_dim * self.num_k_heads projection_size = self.head_dim * self.num_heads
self.q_proj = nn.Linear(self.hidden_size, projection_k_size, bias=False) self.k_proj = nn.Linear(self.hidden_size, projection_k_size, bias=False) self.v_proj = nn.Linear(self.hidden_size, projection_size, bias=False)
self.q_conv1d = ShortConvolution( hidden_size=projection_k_size, kernel_size=self.conv_size, activation='silu', ) self.k_conv1d = ShortConvolution( hidden_size=projection_k_size, kernel_size=self.conv_size, activation='silu', ) self.v_conv1d = ShortConvolution( hidden_size=projection_size, kernel_size=self.conv_size, activation='silu', )
self.A_log = torch.nn.Parameter(torch.log(torch.empty(self.num_heads, dtype=torch.float32).uniform_(1, 16)))
if self.no_kda_lora: self.f_proj = nn.Linear(self.hidden_size, projection_size, bias=False) else: self.f_a_proj = nn.Linear(self.hidden_size, self.head_dim, bias=False) self.f_b_proj = nn.Linear(self.head_dim, projection_size, bias=False)
self.dt_bias = nn.Parameter(torch.empty(projection_size, dtype=torch.float32))
self.b_proj = nn.Linear(self.hidden_size, self.num_heads, bias=False)
if self.no_kda_lora: self.g_proj = nn.Linear(self.hidden_size, projection_size, bias=False) else: self.g_a_proj = nn.Linear(self.hidden_size, self.head_dim, bias=False) self.g_b_proj = nn.Linear(self.head_dim, projection_size, bias=False)
self.o_norm = FusedRMSNormGated(self.head_dim, eps=config.rms_norm_eps, activation='sigmoid') self.o_proj = nn.Linear(projection_size, self.hidden_size, bias=False)
def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None = None, past_key_value=None, **kwargs: Unpack[dict], ) -> tuple[torch.Tensor, torch.Tensor | None, Cache | None]: attention_mask = None if attention_mask is not None: if attention_mask.dim() != 2: attention_mask = kwargs.get("padding_mask")
if attention_mask is not None and attention_mask.dim() != 2: raise ValueError( "attention_mask must be a 0-1 matrix of shape [batch_size, seq_len] " "(0 = padding). 3D masks are not supported here.", ) use_cache = past_key_value is not None batch_size, q_len, _ = hidden_states.shape mode = 'fused_recurrent' if q_len <= 64 else self.mode if self.training: assert mode == 'chunk', "Only chunk mode is supported in training."
cu_seqlens = kwargs.get('cu_seqlens') indices = None if attention_mask is not None: indices, cu_seqlens, _ = _get_unpad_data(attention_mask[:, -q_len:]) hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
conv_state_q, conv_state_k, conv_state_v = None, None, None recurrent_state = None
if past_key_value is not None and isinstance(past_key_value, Cache): # ensure the cache list is long enough while len(past_key_value.layers) <= self.layer_idx: past_key_value.layers.append(DynamicLayer())
if past_key_value.layers[self.layer_idx].keys is not None: recurrent_state = past_key_value.layers[self.layer_idx].keys # ensure recurrent_state is on the same device as hidden_states if recurrent_state.device != hidden_states.device: recurrent_state = recurrent_state.to(hidden_states.device).contiguous()
if past_key_value.layers[self.layer_idx].values is not None: conv_state_q, conv_state_k, conv_state_v = past_key_value.layers[self.layer_idx].values
q, conv_state_q = self.q_conv1d( x=self.q_proj(hidden_states), cache=conv_state_q, output_final_state=use_cache, cu_seqlens=cu_seqlens, ) k, conv_state_k = self.k_conv1d( x=self.k_proj(hidden_states), cache=conv_state_k, output_final_state=use_cache, cu_seqlens=cu_seqlens, ) v, conv_state_v = self.v_conv1d( x=self.v_proj(hidden_states), cache=conv_state_v, output_final_state=use_cache, cu_seqlens=cu_seqlens, )
if self.no_kda_lora: g = self.f_proj(hidden_states) else: g = self.f_b_proj(self.f_a_proj(hidden_states))
beta = self.b_proj(hidden_states).float().sigmoid()
q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_k_dim), (q, k)) v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim) g = rearrange(g, '... (h d) -> ... h d', d=self.head_dim)
if mode == 'chunk': o, recurrent_state = chunk_kda( q=q, k=k, v=v, g=g, beta=beta, A_log=self.A_log, dt_bias=self.dt_bias, initial_state=recurrent_state, output_final_state=True, use_qk_l2norm_in_kernel=True, use_gate_in_kernel=True, safe_gate=self.safe_gate, lower_bound=self.lower_bound, cu_seqlens=cu_seqlens, ) else: o, recurrent_state = fused_recurrent_kda( q=q, k=k, v=v, g=g, beta=beta, A_log=self.A_log, dt_bias=self.dt_bias, initial_state=recurrent_state, output_final_state=True, use_qk_l2norm_in_kernel=True, use_gate_in_kernel=True, lower_bound=self.lower_bound, cu_seqlens=cu_seqlens, )
if use_cache and past_key_value is not None and isinstance(past_key_value, Cache): target_device = None for cache in past_key_value.layers: if cache.keys is not None: target_device = cache.keys.device break if target_device is None: target_device = recurrent_state.device
# move to target device if recurrent_state.device != target_device: recurrent_state = recurrent_state.to(target_device)
past_key_value.layers[self.layer_idx].keys = recurrent_state past_key_value.layers[self.layer_idx].values = (conv_state_q, conv_state_k, conv_state_v)
if self.no_kda_lora: g = self.g_proj(hidden_states) else: g = self.g_b_proj(self.g_a_proj(hidden_states)) g = rearrange(g, '... (h d) -> ... h d', d=self.head_dim) o = self.o_norm(o, g)
o = rearrange(o, 'b t h d -> b t (h d)') o = self.o_proj(o) if attention_mask is not None: o = pad_input(o.squeeze(0), indices, batch_size, q_len)
return o, None, past_key_value
class BailingMoeV3MTPLayer(nn.Module): def __init__(self, config: BailingMoeV3Config, layer_idx: int): super().__init__() self.layer_idx = layer_idx self.input_layernorm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.enorm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.eh_proj = nn.Linear(config.hidden_size * 2, config.hidden_size, bias=False) self.post_attention_layernorm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.attention = BailingMoeV3MultiLatentAttention(config=config, layer_idx=layer_idx) self.mlp = BailingMoeV3SparseMoeBlock(config, layer_idx=layer_idx)
self.hnorm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.final_layernorm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
def forward( self, input_embeds, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, output_attentions: Optional[bool] = False, output_router_logits: Optional[bool] = False, use_cache: Optional[bool] = False, position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC **kwargs, ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: input_embeds = self.enorm(input_embeds) hidden_states = self.hnorm(hidden_states) hidden_states = self.eh_proj(torch.cat([input_embeds, hidden_states], dim=-1)) residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
# Self Attention hidden_states, self_attn_weights, present_key_value = self.attention( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_value, output_attentions=output_attentions, position_embeddings=position_embeddings, use_cache=use_cache, ) hidden_states = residual + hidden_states
# Fully Connected residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) if isinstance(hidden_states, tuple): hidden_states, router_logits = hidden_states else: router_logits = None hidden_states = residual + hidden_states.to(residual.device) hidden_states = self.final_layernorm(hidden_states)
outputs = (hidden_states,)
if output_attentions: outputs += (self_attn_weights,)
if use_cache: outputs += (present_key_value,)
if output_router_logits: outputs += (router_logits,)
return outputs
class BailingMoeV3DecoderLayer(nn.Module): def __init__(self, config: BailingMoeV3Config, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.layer_idx = layer_idx self.attention_layer_type = ( "attention" if (layer_idx + 1) % config.layer_group_size == 0 or layer_idx >= config.num_hidden_layers // config.layer_group_size * config.layer_group_size else "linear_attention" )
if self.attention_layer_type == "attention": self.attention = BailingMoeV3MultiLatentAttention(config=config, layer_idx=layer_idx) else: self.attention = BailingMoeV3KimiDeltaAttention(config=config, layer_idx=layer_idx)
self.mlp = ( BailingMoeV3SparseMoeBlock(config, layer_idx=layer_idx) if (config.num_experts is not None and layer_idx >= config.first_k_dense_replace) else BailingMoeV3MLP(config=config, intermediate_size=config.intermediate_size) ) self.input_layernorm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, cache_position: Optional[torch.LongTensor] = None, output_attentions: Optional[bool] = False, output_router_logits: Optional[bool] = False, use_cache: Optional[bool] = False, position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC **kwargs, ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`, *optional*): attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1, query_sequence_length, key_sequence_length)` if default attention is used. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`. past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states output_attentions (`bool`, *optional*): Whether to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_router_logits (`bool`, *optional*): Whether or not to return the logits of all the routers. They are useful for computing the router loss, and should not be returned during inference. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). """ residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
# Self Attention if self.attention_layer_type == "attention": hidden_states, self_attn_weights, present_key_value = self.attention( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_value, use_cache=use_cache, cache_position=cache_position, # position_embeddings=position_embeddings, # **kwargs, ) else: batch_size, seq_len = hidden_states.shape[0], hidden_states.shape[1] device = hidden_states.device
if attention_mask is None: # if attention_mask is None, create a full mask attention_mask = torch.ones((batch_size, seq_len), dtype=torch.int32, device=device) elif attention_mask.dim() == 4 and attention_mask.shape[1] == 1: attention_mask = attention_mask[:, 0, -1, :].to(torch.int32) attention_mask = (attention_mask > -1e4).to(torch.int32) elif attention_mask.dim() == 2: attention_mask = attention_mask.to(torch.int32) else: raise ValueError(f"Unsupported mask dimension: {attention_mask.shape}")
hidden_states, self_attn_weights, present_key_value = self.attention( hidden_states=hidden_states, attention_mask=attention_mask, past_key_value=past_key_value, position_ids=position_ids, use_cache=use_cache, output_attentions=output_attentions, )
hidden_states = residual + hidden_states
# Fully Connected residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) if isinstance(hidden_states, tuple): hidden_states, router_logits = hidden_states else: router_logits = None hidden_states = residual + hidden_states.to(residual.device)
outputs = (hidden_states,)
if output_attentions: outputs += (self_attn_weights,)
if use_cache: outputs += (present_key_value,)
if output_router_logits: outputs += (router_logits,)
return outputs
BAILINGMOEV3_START_DOCSTRING = r""" This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`BailingMoeV3Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights."""
@add_start_docstrings( "The bare BailingMoeV3 Model outputting raw hidden-states without any specific head on top.", BAILINGMOEV3_START_DOCSTRING,)class BailingMoeV3PreTrainedModel(PreTrainedModel): config_class = BailingMoeV3Config base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["BailingMoeV3DecoderLayer"] _skip_keys_device_placement = "past_key_values" _supports_flash_attn_2 = True _supports_sdpa = True _supports_cache_class = True
def _init_weights(self, module): std = self.config.initializer_range if isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_()
BAILINGMOEV3_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. If `past_key_values` is used, optionally only the last `input_ids` have to be input (see `past_key_values`). If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy. - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids) past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*): Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`. Two formats are allowed: - a [`~cache_utils.Cache`] instance; - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy cache format. The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the legacy cache format will be returned. If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids` of shape `(batch_size, sequence_length)`. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple."""
@add_start_docstrings( "The bare BailingMoeV3 Model outputting raw hidden-states without any specific head on top.", BAILINGMOEV3_START_DOCSTRING,)class BailingMoeV3Model(BailingMoeV3PreTrainedModel): """ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`BailingMoeV3DecoderLayer`] Args: config: BailingMoeV3Config """
def __init__(self, config: BailingMoeV3Config): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.num_nextn_predict_layers = config.num_nextn_predict_layers
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.layers = [] for layer_idx in range(config.num_hidden_layers + config.num_nextn_predict_layers): layer_cls = BailingMoeV3DecoderLayer if layer_idx < config.num_hidden_layers else BailingMoeV3MTPLayer self.layers.append(layer_cls(config, layer_idx))
self.layers = nn.ModuleList(self.layers)
self._use_sdpa = config._attn_implementation == "sdpa" self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2" self.norm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.rotary_emb = BailingMoeV3RotaryEmbedding(config=config) self.gradient_checkpointing = False # Initialize weights and apply final processing self.post_init()
def get_input_embeddings(self): return self.word_embeddings
def set_input_embeddings(self, value): self.word_embeddings = value
@add_start_docstrings_to_model_forward(BAILINGMOEV3_INPUTS_DOCSTRING) def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, cache_position: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, output_router_logits: Optional[bool] = None, return_dict: Optional[bool] = None, **kwargs, ) -> Union[Tuple, MoeV3ModelOutputWithPast]: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) output_router_logits = ( output_router_logits if output_router_logits is not None else self.config.output_router_logits ) use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# retrieve input_ids and inputs_embeds if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: batch_size, seq_length = input_ids.shape[:2] elif inputs_embeds is not None: batch_size, seq_length = inputs_embeds.shape[:2] else: raise ValueError("You have to specify either input_ids or inputs_embeds")
if self.gradient_checkpointing and self.training: if use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers." ) use_cache = False
if use_cache and past_key_values is None: past_key_values = DynamicCache()
if inputs_embeds is None: inputs_embeds = self.word_embeddings(input_ids)
# Recurrent KDA states do not encode sequence length. Use the first # softmax attention cache for positions as well as the causal mask. softmax_attention_layer_id = min(self.config.layer_group_size - 1, self.config.num_hidden_layers - 1) if cache_position is None: past_seen_tokens = ( past_key_values.get_seq_length(layer_idx=softmax_attention_layer_id) if past_key_values is not None else 0 ) cache_position: torch.Tensor = torch.arange( past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device )
if position_ids is None: position_ids = cache_position.unsqueeze(0)
past_seen_tokens = ( past_key_values.get_seq_length(layer_idx=softmax_attention_layer_id) if past_key_values is not None else 0 )
if position_ids is None: position_ids = torch.arange( past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device ) position_ids = position_ids.unsqueeze(0)
if self._use_flash_attention_2: # 2d mask is passed through the layers attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None elif self._use_sdpa and not output_attentions: # output_attentions=True can not be supported when using SDPA, and we fall back on # the manual implementation that requires a 4D causal mask in all cases. attention_mask = _prepare_4d_causal_attention_mask_for_sdpa( attention_mask, (batch_size, seq_length), inputs_embeds, past_seen_tokens, ) else: # 4d mask is passed through the layers attention_mask = _prepare_4d_causal_attention_mask( attention_mask, (batch_size, seq_length), inputs_embeds, past_seen_tokens )
# embed positions hidden_states = inputs_embeds
# create position embeddings to be shared across the decoder layers position_embeddings = self.rotary_emb(hidden_states, position_ids)
# decoder layers all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None all_router_logits = () if output_router_logits else None next_decoder_cache = None layers = self.layers[: -self.num_nextn_predict_layers] if self.num_nextn_predict_layers > 0 else self.layers mtp_layers = self.layers[-self.num_nextn_predict_layers :] if self.num_nextn_predict_layers > 0 else None
# tptest miss causal_mask = create_causal_mask(
for decoder_layer in layers: if output_hidden_states: all_hidden_states += (hidden_states,)
if self.gradient_checkpointing and self.training: layer_outputs = self._gradient_checkpointing_func( decoder_layer.__call__, hidden_states, attention_mask, position_ids, past_key_values, cache_position, output_attentions, output_router_logits, use_cache, position_embeddings, ) else: layer_outputs = decoder_layer( hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_values, cache_position=cache_position, output_attentions=output_attentions, output_router_logits=output_router_logits, use_cache=use_cache, position_embeddings=position_embeddings, ) hidden_states = layer_outputs[0]
if use_cache: next_decoder_cache = layer_outputs[2 if output_attentions else 1]
if output_attentions: all_self_attns += (layer_outputs[1],)
if output_router_logits and layer_outputs[-1] is not None: all_router_logits += (layer_outputs[-1],)
hidden_states = self.norm(hidden_states) main_hidden_states = hidden_states
# add hidden states from the last decoder layer if output_hidden_states: all_hidden_states += (main_hidden_states,)
mtp_hidden_states = None
if mtp_layers and input_ids is not None: for decoder_layer in mtp_layers: input_ids, _ = roll_tensor(input_ids, shifts=-1, dims=-1) inputs_embeds = self.word_embeddings(input_ids)
if self.gradient_checkpointing and self.training: layer_outputs = self._gradient_checkpointing_func( decoder_layer.__call__, inputs_embeds, hidden_states, attention_mask, position_ids, past_key_values, output_attentions, output_router_logits, use_cache, position_embeddings, ) else: layer_outputs = decoder_layer( inputs_embeds, hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_values, output_attentions=output_attentions, output_router_logits=output_router_logits, use_cache=use_cache, position_embeddings=position_embeddings, ) if mtp_hidden_states is None: mtp_hidden_states = [] hidden_states = layer_outputs[0] mtp_hidden_states.append(hidden_states)
if output_hidden_states: all_hidden_states += (hidden_states,)
if use_cache: next_decoder_cache = layer_outputs[2 if output_attentions else 1]
if output_attentions: all_self_attns += (layer_outputs[1],)
if output_router_logits and layer_outputs[-1] is not None: all_router_logits += (layer_outputs[-1],)
next_cache = None if use_cache: next_cache = next_decoder_cache if not return_dict: return tuple( v for v in [main_hidden_states, next_cache, all_hidden_states, all_self_attns, all_router_logits] if v is not None ) return MoeV3ModelOutputWithPast( last_hidden_state=main_hidden_states, past_key_values=next_cache, hidden_states=all_hidden_states, mtp_hidden_states=mtp_hidden_states, attentions=all_self_attns, router_logits=all_router_logits, )
class BailingMoeV3ForCausalLM(BailingMoeV3PreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.word_embeddings.weight"}
def __init__(self, config: BailingMoeV3Config): super().__init__(config) self.model = BailingMoeV3Model(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.num_nextn_predict_layers = config.num_nextn_predict_layers self.mtp_loss_scaling_factor = config.mtp_loss_scaling_factor
# Initialize weights and apply final processing self.post_init()
def get_input_embeddings(self): return self.model.word_embeddings
def set_input_embeddings(self, value): self.model.word_embeddings = value
def get_output_embeddings(self): return self.lm_head
def set_output_embeddings(self, new_embeddings): self.lm_head = new_embeddings
def set_decoder(self, decoder): self.model = decoder
def get_decoder(self): return self.model
@add_start_docstrings_to_model_forward(BAILINGMOEV3_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=MoEV3CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, output_router_logits: Optional[bool] = None, return_dict: Optional[bool] = None, **kwargs, ) -> Union[Tuple, MoEV3CausalLMOutputWithPast]: r""" Args: labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. Returns: Example: ```python >>> from transformers import AutoTokenizer >>> model = BailingMoeV3ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS) >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER) >>> prompt = "Hey, are you conscious? Can you talk to me?" >>> inputs = tokenizer(prompt, return_tensors="pt") >>> # Generate >>> generate_ids = model.generate(inputs.input_ids, max_length=30) >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." ```""" output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) output_router_logits = ( output_router_logits if output_router_logits is not None else self.config.output_router_logits ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) outputs = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, output_router_logits=output_router_logits, return_dict=return_dict, **kwargs, )
loss = None all_mtp_loss = None aux_loss = None hidden_states = outputs[0] logits = self.lm_head(hidden_states) logits = logits.float()
if labels is not None: loss = self.loss_function(logits, labels, self.config.vocab_size, **kwargs)
all_mtp_logits = None if self.num_nextn_predict_layers > 0: mtp_hidden_states = outputs.mtp_hidden_states shift_labels_mtp = None for i in range(self.num_nextn_predict_layers): mtp_hidden_states = mtp_hidden_states[i] mtp_logits = self.lm_head(mtp_hidden_states).float() if all_mtp_logits is None: all_mtp_logits = [] all_mtp_logits.append(mtp_logits) if labels is not None: if shift_labels_mtp is None: shift_labels_mtp = labels.clone() shift_labels_mtp, _ = roll_tensor(shift_labels_mtp, shifts=-1, dims=-1, fill_value=-100) mtp_logits_ = mtp_logits.view(-1, self.config.vocab_size) mtp_loss = self.loss_function( mtp_logits_, shift_labels_mtp.to(mtp_logits_.device).view(-1), self.config.vocab_size, **kwargs ) if loss is not None: loss += self.mtp_loss_scaling_factor * mtp_loss else: loss = self.mtp_loss_scaling_factor * mtp_loss
if all_mtp_loss is None: all_mtp_loss = [] all_mtp_loss.append(mtp_loss)
if not return_dict: output = (logits,) + outputs[1:] if output_router_logits: output = (aux_loss,) + output return (loss,) + output if loss is not None else output
return MoEV3CausalLMOutputWithPast( loss=loss, mtp_loss=all_mtp_loss, aux_loss=aux_loss, logits=logits, mtp_logits=all_mtp_logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, router_logits=outputs.router_logits, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334# coding=utf-8# Copyright 2025 Antgroup and The HuggingFace Inc. team. All rights reserved.## This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX# and OPT implementations in this library. It has been modified from its# original forms to accommodate minor architectural differences compared# to GPT-NeoX and OPT used by the Meta AI team that trained the model.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""PyTorch BailingMoE V3 Audio model."""
import osfrom typing import Optional, Union
import torchimport torch.nn.functional as Ffrom torch import nn
from transformers.cache_utils import Cachefrom transformers.modeling_utils import PreTrainedModeltry: from transformers.utils.import_utils import is_torch_fx_availableexcept ImportError: def is_torch_fx_available(): return Falsefrom .configuration_bailing_moe_v3_audio import ( BailingMoeV3AudioConfig, BailingMoeV3AudioEncoderConfig,)from transformers.generation.utils import GenerationMixinfrom dataclasses import dataclassfrom transformers.utils import ModelOutputimport whisper
# OpenAI Whisper casts LayerNorm inputs to float32. Hugging Face loads this# encoder's parameters in the requested model dtype, so that implementation# fails for BF16 weights. Keep inputs and parameters in the same dtype, as in# the LingV3 Audio reference torch client.whisper.model.LayerNorm.forward = lambda self, x: F.layer_norm( x, self.normalized_shape, self.weight, self.bias, self.eps)
class Transpose(nn.Module): def __init__(self, dim0: int, dim1: int): super().__init__() self.dim0 = dim0 self.dim1 = dim1
def forward(self, x): return x.transpose(self.dim0, self.dim1)
class WhisperEncoderForBailing(nn.Module): """Whisper encoder wrapper for audio encoding in BailingMM inference.
Unlike the original Whisper encoder, this version does not perform 30-second padding and returns output lengths along with the encoded features. """
def __init__(self, n_mels: int, n_audio_ctx: int, n_audio_state: int, n_audio_head: int, n_audio_layer: int): super().__init__() self.conv1 = nn.Conv1d(n_mels, n_audio_state, kernel_size=3, padding=1) self.conv2 = nn.Conv1d(n_audio_state, n_audio_state, kernel_size=3, stride=2, padding=1) self.positional_embedding = nn.Parameter(torch.zeros(n_audio_ctx, n_audio_state)) self.blocks = nn.ModuleList( [whisper.model.ResidualAttentionBlock(n_audio_state, n_audio_head) for _ in range(n_audio_layer)] ) self.ln_post = nn.LayerNorm(n_audio_state) self.audio_emb_dim = n_audio_state
def forward(self, x: torch.Tensor, input_lengths: torch.Tensor): """Forward pass.
Args: x: Mel spectrogram, shape (B, T, d) input_lengths: Original lengths before mel, shape (B,) Returns: Tuple of (encoded features, output_lengths). """ x = x.transpose(1, 2) x = F.gelu(self.conv1(x)) x = F.gelu(self.conv2(x)) x = x.permute(0, 2, 1) positional_embedding = self.positional_embedding[: x.shape[1], :] assert x.shape[1:] == positional_embedding.shape, "incorrect audio shape" x = (x + positional_embedding).to(x.dtype) for block in self.blocks: x = block(x) x = self.ln_post(x) output_lengths = input_lengths output_lengths = ( output_lengths + 2 * (self.conv1.kernel_size[0] // 2) - self.conv1.kernel_size[0] ) // self.conv1.stride[0] + 1 output_lengths = ( output_lengths + 2 * (self.conv2.kernel_size[0] // 2) - self.conv2.kernel_size[0] ) // self.conv2.stride[0] + 1 return x, output_lengths
@classmethod def from_pretrained(cls, audio_config: BailingMoeV3AudioEncoderConfig): return cls( n_mels=audio_config.n_mels, n_audio_ctx=audio_config.n_audio_ctx, n_audio_state=audio_config.n_audio_state, n_audio_head=audio_config.n_audio_head, n_audio_layer=audio_config.n_audio_layer, )
from .modeling_bailing_moe_v3 import BailingMoeV3Model
@dataclassclass BailingMoeV3AudioCausalLMOutputWithPast(ModelOutput): loss: Optional[torch.FloatTensor] = None logits: Optional[torch.FloatTensor] = None past_key_values: Optional[Cache] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None router_logits: Optional[tuple[torch.FloatTensor]] = None aux_loss: Optional[torch.FloatTensor] = None
class BailingMoeV3AudioPreTrainedModel(PreTrainedModel): config_class = BailingMoeV3AudioConfig base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["BailingMoeV3DecoderLayer"] _skip_keys_device_placement = "past_key_values" _supports_flash_attn_2 = True _supports_sdpa = True _supports_cache_class = True
def _init_weights(self, module): if hasattr(self.config, "initializer_range"): std = self.config.initializer_range else: std = getattr(self.config.get_text_config(), "initializer_range", 0.02) if isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_()
class BailingMoeV3AudioForConditionalGeneration(BailingMoeV3AudioPreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.word_embeddings.weight"}
def __init__(self, config: BailingMoeV3AudioConfig, **kwargs): super().__init__(config, **kwargs) self.model = BailingMoeV3Model(config.text_config) # Audio encoder lives under self.model to match checkpoint key "model.audio.*" self.model.audio = WhisperEncoderForBailing.from_pretrained(config.audio_config)
mlp_modules_audio = [] audio_feature_size = config.audio_config.n_audio_state for kernel_size, stride in zip( config.audio_config.downsampler_kernel_size_list, config.audio_config.downsampler_stride_list ): mlp_modules_audio.append(torch.nn.Conv1d( audio_feature_size, config.text_config.hidden_size, kernel_size=kernel_size, stride=stride, padding=kernel_size // 2, )) mlp_modules_audio.append(nn.GELU()) audio_feature_size = config.text_config.hidden_size mlp_modules_audio.append(Transpose(-1, -2)) mlp_modules_audio.append(nn.Linear(config.text_config.hidden_size, config.text_config.hidden_size)) self.linear_proj_audio = nn.Sequential(*mlp_modules_audio)
self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False) self.post_init()
def get_input_embeddings(self): return self.model.get_input_embeddings()
def set_input_embeddings(self, value): self.model.set_input_embeddings(value)
def get_output_embeddings(self): return self.lm_head
def set_output_embeddings(self, new_embeddings): self.lm_head = new_embeddings
def _get_audio_features(self, audio_feats, audio_feats_lengths): chunk_size = getattr(self.config.audio_config, "whisper_chunk_size", 3000) if audio_feats.ndim != 3 or audio_feats.shape[0] != 1: raise ValueError("audio_feats must have shape [1, mel_frames, n_mels]") if audio_feats_lengths is None or audio_feats_lengths.ndim != 2: raise ValueError("audio_feats_lengths must have shape [1, num_audios]") if chunk_size <= 0: raise ValueError("whisper_chunk_size must be positive") valid_lengths = [int(length) for length in audio_feats_lengths[0].tolist() if int(length) > 0] if not valid_lengths: raise ValueError("audio_feats_lengths must contain at least one positive length")
total_length = sum(valid_lengths) if audio_feats.shape[1] < total_length: raise ValueError( f"audio_feats length {audio_feats.shape[1]} is shorter than requested audio length {total_length}" )
segments = audio_feats[0, :total_length].split(valid_lengths) chunks = [] for segment in segments: chunks.extend(segment.split(chunk_size))
input_lengths = torch.tensor([chunk.shape[0] for chunk in chunks], dtype=torch.long, device=audio_feats.device) chunk_batch = torch.nn.utils.rnn.pad_sequence(chunks, batch_first=True)
# Limit Whisper activations for long recordings. An unset value keeps # the original single-batch path; each chunk has independent context. micro_batch = int(os.environ.get("HF_SFT_WHISPER_MICRO_BATCH", "0")) if micro_batch < 0: raise ValueError("HF_SFT_WHISPER_MICRO_BATCH must be nonnegative") micro_batch = micro_batch or len(chunks) projected_chunks = [] for start in range(0, len(chunks), micro_batch): end = start + micro_batch encoded, enc_lengths = self.model.audio( chunk_batch[start:end], input_lengths[start:end] )[:2] projected = self.linear_proj_audio(encoded.transpose(-1, -2)) proj_lens = enc_lengths for module in self.linear_proj_audio: if isinstance(module, nn.Conv1d): proj_lens = (proj_lens + 2 * module.padding[0] - module.kernel_size[0]) // module.stride[0] + 1 projected_chunks.extend( projected[i, :proj_lens[i]] for i in range(projected.shape[0]) ) audio_embeds = torch.cat(projected_chunks, dim=0).unsqueeze(0) if self.config.norm_query_embeds: audio_embeds = F.normalize(audio_embeds, dim=2) return audio_embeds
def prepare_inputs_for_generation( self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, **kwargs ): model_inputs = super().prepare_inputs_for_generation( input_ids, past_key_values=past_key_values, attention_mask=attention_mask, inputs_embeds=inputs_embeds, cache_position=cache_position, **kwargs, ) # Audio is injected only during prefill. Keeping it on decode steps # needlessly reruns the Whisper encoder for every generated token. is_decode_step = ( cache_position is not None and cache_position.numel() > 0 and cache_position[0].item() > 0 ) # Transformers 5 slices cached decoding with next_sequence_length # instead of passing cache_position to remote models. is_decode_step = is_decode_step or ( past_key_values is not None and kwargs.get("next_sequence_length") is not None and not kwargs.get("is_first_iteration", False) ) if is_decode_step: model_inputs.pop("audio_feats", None) model_inputs.pop("audio_feats_lengths", None) return model_inputs
def forward( self, input_ids=None, attention_mask=None, position_ids=None, past_key_values=None, inputs_embeds=None, labels=None, audio_feats=None, audio_feats_lengths=None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs, ): if inputs_embeds is None: inputs_embeds = self.model.get_input_embeddings()(input_ids)
if audio_feats is not None: audio_embeds = self._get_audio_features(audio_feats, audio_feats_lengths) audio_embeds = audio_embeds.to(inputs_embeds.device, inputs_embeds.dtype) num_audio_tokens = int((input_ids == self.config.audio_token_id).sum()) if num_audio_tokens != audio_embeds.shape[1]: raise ValueError( "audio placeholder count does not match encoded features: " f"{num_audio_tokens} != {audio_embeds.shape[1]}" ) audio_mask = (input_ids == self.config.audio_token_id).unsqueeze(-1).expand_as(inputs_embeds) inputs_embeds = inputs_embeds.masked_scatter(audio_mask, audio_embeds)
outputs = self.model( input_ids=None, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs, )
hidden_states = outputs[0] slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :])
loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size)
return BailingMoeV3AudioCausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, router_logits=outputs.router_logits, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120"""Audio processor for BailingMoE V3 Audio Hugging Face inference."""
from pathlib import Path
import torchimport torchaudioimport soundfile as sfimport whisperfrom transformers import AutoTokenizer, BatchFeaturefrom transformers.processing_utils import ProcessorMixin
from .configuration_bailing_moe_v3_audio import BailingMoeV3AudioConfig
class BailingMoeV3AudioProcessor(ProcessorMixin): attributes = ["tokenizer"] tokenizer_class = "AutoTokenizer"
ASR_PROMPT = ( "Please recognize the language of this speech and transcribe it, " "placing a `\t` between the identified language and the transcribe." )
def __init__(self, tokenizer, audio_config=None): super().__init__(tokenizer) self.audio_config = audio_config
@classmethod def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path, **kwargs) config = BailingMoeV3AudioConfig.from_pretrained( pretrained_model_name_or_path, **kwargs ) return cls(tokenizer, config.audio_config)
def _load_audio(self, audio): if isinstance(audio, (str, Path)): samples, sample_rate = sf.read(str(audio), dtype="float32", always_2d=True) waveform = torch.from_numpy(samples.T.copy()) elif isinstance(audio, tuple) and len(audio) == 2: waveform, sample_rate = audio waveform = torch.as_tensor(waveform) else: raise TypeError("audio must be a path or a (waveform, sample_rate) tuple") if waveform.ndim == 1: waveform = waveform.unsqueeze(0) if waveform.ndim != 2: raise ValueError("waveform must have shape [samples] or [channels, samples]") waveform = waveform.float() if sample_rate != 16000: waveform = torchaudio.functional.resample(waveform, sample_rate, 16000) return waveform.mean(dim=0)
def _num_audio_tokens(self, mel_length): config = self.audio_config chunk_size = getattr(config, "whisper_chunk_size", 3000) kernels = config.downsampler_kernel_size_list strides = config.downsampler_stride_list paddings = getattr(config, "downsampler_padding_list", None) paddings = paddings or [kernel // 2 for kernel in kernels]
total = 0 for offset in range(0, mel_length, chunk_size): length = min(chunk_size, mel_length - offset) length = (length + 2 - 3) // 2 + 1 for kernel, stride, padding in zip(kernels, strides, paddings): length = (length + 2 * padding - kernel) // stride + 1 total += length return total
def __call__(self, audio, text=None, return_tensors="pt"): messages = None if isinstance(audio, list) and audio and isinstance(audio[0], dict): messages = audio audio_items = [ item["audio"] for message in messages if isinstance(message.get("content"), list) for item in message["content"] if item.get("type") == "audio" ] if len(audio_items) != 1: raise ValueError("exactly one audio item is required") audio = audio_items[0] waveform = self._load_audio(audio) n_mels = getattr(self.audio_config, "n_mels", 128) mel = whisper.log_mel_spectrogram(waveform, n_mels=n_mels) mel = mel.transpose(0, 1).unsqueeze(0).contiguous() mel_length = mel.shape[1]
audio_start = "<|audio_start|>" audio_token = "<|audio_pad|>" audio_end = "<|audio_end|>" if messages is None: prompt = ( audio_start + audio_token * self._num_audio_tokens(mel_length) + audio_end + (text or self.ASR_PROMPT) ) else: prompt = self.tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True, enable_thinking=False, ) placeholder = audio_start + audio_token + audio_end if prompt.count(placeholder) != 1: raise ValueError("chat prompt must contain exactly one audio placeholder") prompt = prompt.replace( placeholder, audio_start + audio_token * self._num_audio_tokens(mel_length) + audio_end, ) inputs = self.tokenizer(prompt, return_tensors=return_tensors) inputs.pop("token_type_ids", None) inputs["audio_feats"] = mel inputs["audio_feats_lengths"] = torch.tensor([[mel_length]], dtype=torch.long) return BatchFeature(inputs)
__all__ = ["BailingMoeV3AudioProcessor"]123456{ "processor_class": "BailingMoeV3AudioProcessor", "auto_map": { "AutoProcessor": "processing_bailing_moe_v3_audio.BailingMoeV3AudioProcessor" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657{ "additional_special_tokens": [ "<role>", "</role>", "<|role_end|>", "<tool_call>", "</tool_call>", "<tool_response>", "</tool_response>", "<|vision_start|>", "<|vision_end|>", "<|image_pad|>", "<|video_start|>", "<|video_end|>", "<|video_pad|>", "<|audio_start|>", "<|audio_end|>", "<|audio_pad|>" ], "audio_bos_token": "<|audio_start|>", "audio_eos_token": "<|audio_end|>", "audio_token": "<|audio_pad|>", "bos_token": { "content": "<|startoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "cls_token": { "content": "[CLS]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "eos_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "image_token": "<|image_pad|>", "pad_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "video_bos_token": "<|video_start|>", "video_eos_token": "<|video_end|>", "video_token": "<|video_pad|>", "vision_bos_token": "<|vision_start|>", "vision_eos_token": "<|vision_end|>"}12345678910111213141516171819from transformers import PretrainedConfig
class AudioVAEconfig(PretrainedConfig): def __init__( self, sample_rate: int=16000, enc_kwargs: dict = None, dec_kwargs: dict = None, init_method='normal', patch_size=-1, **kwargs ): self.sample_rate = sample_rate self.enc_kwargs = enc_kwargs self.dec_kwargs = dec_kwargs self.init_method = init_method self.patch_size = patch_size super().__init__(**kwargs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181import torch.nn as nnimport torch
class ISTFT(nn.Module): """ Custom implementation of ISTFT since torch.istft doesn't allow custom padding (other than `center=True`) with windowing. This is because the NOLA (Nonzero Overlap Add) check fails at the edges. See issue: https://github.com/pytorch/pytorch/issues/62323 Specifically, in the context of neural vocoding we are interested in "same" padding analogous to CNNs. The NOLA constraint is met as we trim padded samples anyway.
Args: n_fft (int): Size of Fourier transform. hop_length (int): The distance between neighboring sliding window frames. win_length (int): The size of window frame and STFT filter. padding (str, optional): Type of padding. Options are "center" or "same". Defaults to "same". """
def __init__(self, n_fft: int, hop_length: int, win_length: int, padding: str = "same"): super().__init__() if padding not in ["center", "same"]: raise ValueError("Padding must be 'center' or 'same'.") self.padding = padding self.n_fft = n_fft self.hop_length = hop_length self.win_length = win_length window = torch.hann_window(win_length) self.register_buffer("window", window)
self.audio_buffer = None self.window_buffer = None self.buffer_len = self.win_length - self.hop_length
def __buffer_process(self, x, buffer, pad, last_chunk=False, streaming=False): if streaming: if buffer is None: # first chunk x = x[:, pad:] if buffer is not None: # next chunk x[:, :self.buffer_len] += buffer buffer = x[:, -self.buffer_len:] if not last_chunk: x = x[:, :-self.buffer_len] else: x = x[:, :-pad] else: x = x[:, pad:-pad]
return x, buffer
def forward( self, spec: torch.Tensor, audio_buffer=None, window_buffer=None, streaming=False, last_chunk=False ): """ Compute the Inverse Short Time Fourier Transform (ISTFT) of a complex spectrogram.
Args: spec (Tensor): Input complex spectrogram of shape (B, N, T), where B is the batch size, N is the number of frequency bins, and T is the number of time frames. audio_buffer (Tensor): [Streaming Input/State] The audio overlap buffer from the previous chunk. Shape: (B, win_length - hop_length) window_buffer (Tensor): [Streaming Input/State] The window overlap buffer from the previous chunk. streaming: If `True`, the function operates in streaming mode, processing `spec` as a single chunk. last_chunk: When `streaming=True` and `last_chunk=True`, the function can perform final "flush" operations
Returns: Tensor: Reconstructed time-domain signal of shape (B, L), where L is the length of the output signal. """ if self.padding == "center": # Fallback to pytorch native implementation return torch.istft(spec, self.n_fft, self.hop_length, self.win_length, self.window, center=True) elif self.padding == "same": pad = (self.win_length - self.hop_length) // 2 else: raise ValueError("Padding must be 'center' or 'same'.")
assert spec.dim() == 3, "Expected a 3D tensor as input" B, N, T = spec.shape
# Inverse FFT ifft = torch.fft.irfft(spec, self.n_fft, dim=1, norm="backward") ifft = ifft * self.window[None, :, None]
# Overlap and Add output_size = (T - 1) * self.hop_length + self.win_length y = torch.nn.functional.fold( ifft, output_size=(1, output_size), kernel_size=(1, self.win_length), stride=(1, self.hop_length), )[:, 0, 0, :]
y, audio_buffer = self.__buffer_process(y, audio_buffer, pad, last_chunk=last_chunk, streaming=streaming)
# Window envelope window_sq = self.window.square().expand(1, T, -1).transpose(1, 2) window_envelope = torch.nn.functional.fold( window_sq, output_size=(1, output_size), kernel_size=(1, self.win_length), stride=(1, self.hop_length), ).squeeze(0).squeeze(0)
window_envelope, window_buffer = self.__buffer_process(window_envelope, window_buffer, pad, last_chunk=last_chunk, streaming=streaming) window_envelope = window_envelope.squeeze()
# Normalize assert (window_envelope > 1e-11).all() y = y / window_envelope
return y, audio_buffer, window_buffer
class FourierHead(nn.Module): """Base class for inverse fourier modules."""
def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x (Tensor): Input tensor of shape (B, L, H), where B is the batch size, L is the sequence length, and H denotes the model dimension.
Returns: Tensor: Reconstructed time-domain audio signal of shape (B, T), where T is the length of the output signal. """ raise NotImplementedError("Subclasses must implement the forward method.")
class ISTFTHead(FourierHead): """ ISTFT Head module for predicting STFT complex coefficients.
Args: dim (int): Hidden dimension of the model. n_fft (int): Size of Fourier transform. hop_length (int): The distance between neighboring sliding window frames, which should align with the resolution of the input features. padding (str, optional): Type of padding. Options are "center" or "same". Defaults to "same". """
def __init__(self, dim: int, n_fft: int, hop_length: int, padding: str = "same"): super().__init__() out_dim = n_fft + 2 self.out = torch.nn.Linear(dim, out_dim) self.istft = ISTFT(n_fft=n_fft, hop_length=hop_length, win_length=n_fft, padding=padding)
def forward( self, x: torch.Tensor, audio_buffer=None, window_buffer=None, streaming=False, last_chunk=False ): """ Forward pass of the ISTFTHead module.
Args: x (Tensor): Input tensor of shape (B, L, H), where B is the batch size, L is the sequence length, and H denotes the model dimension.
Returns: Tensor: Reconstructed time-domain audio signal of shape (B, T), where T is the length of the output signal. """ x_pred = self.out(x ) # x_pred = x x_pred = x_pred.transpose(1, 2) mag, p = x_pred.chunk(2, dim=1) mag = torch.exp(mag) mag = torch.clip(mag, max=1e2) # safeguard to prevent excessively large magnitudes # wrapping happens here. These two lines produce real and imaginary value x = torch.cos(p) y = torch.sin(p) # recalculating phase here does not produce anything new # only costs time # phase = torch.atan2(y, x) # S = mag * torch.exp(phase * 1j) # better directly produce the complex value S = mag * (x + 1j * y) audio, audio_buffer, window_buffer = self.istft(S, audio_buffer=audio_buffer, window_buffer=window_buffer, streaming=streaming, last_chunk=last_chunk) return audio.unsqueeze(1),x_pred, audio_buffer, window_buffer1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980from diffusers.models.autoencoders.autoencoder_oobleck import OobleckDiagonalGaussianDistributionfrom transformers import PreTrainedModelimport torchimport torch.nn as nn
from .configuration_audio_vae import AudioVAEconfigfrom .vae_modules import Encoder, Decoder
class AudioVAE(PreTrainedModel): config_class = AudioVAEconfig
def __init__(self, config: AudioVAEconfig): super().__init__(config) self.encoder = Encoder( encoder_args=config.enc_kwargs['backbone'], input_dim=config.enc_kwargs['input_dim'], hop_size=config.enc_kwargs.get('hop_size', 320), latent_dim=config.enc_kwargs['latent_dim'], patch_size=config.patch_size )
self.decoder = Decoder( decoder_args=config.dec_kwargs['backbone'], output_dim=config.dec_kwargs['output_dim'], latent_dim=config.dec_kwargs['latent_dim'], patch_size=config.patch_size )
self.post_init()
def _init_weights(self, module): std = 0.02 if isinstance(module, nn.Linear): if self.config.init_method == 'kaiming': nn.init.kaiming_normal_(module.weight, mode='fan_in', nonlinearity='relu') else: module.weight.data.normal_(mean=0.0, std=std)
if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_()
def encode_latent(self, waveform, waveform_length): """ Encodes a raw waveform to obtain its acoustic latent representation. Args: waveform: The input audio waveform, shape (B, T_wav). waveform_length: The length of each waveform, shape (B,).
Returns: tuple[torch.Tensor, torch.Tensor]: A tuple containing: - z (torch.Tensor): The sampled acoustic latent vectors, shape (B, T_frame, D_latent). - frame_num (torch.Tensor): The number of frames for each audio, shape (B,). """ frame_num = torch.ceil(waveform_length/self.config.enc_kwargs['input_dim']).to(torch.int32) if self.config.patch_size != -1: frame_num = torch.ceil(frame_num/self.config.patch_size) h, y = self.encoder(waveform) h = h.transpose(1, 2) # [B, d, T]
posterior = OobleckDiagonalGaussianDistribution(h) latent = posterior.sample() # [B, d/2, T] latent = latent.transpose(1, 2) return latent, frame_num
def decode(self, latent, past_key_values=None, use_cache=False, stream_state=(None, None, None), last_chunk=False): """ Reconstructs the raw audio waveform from its acoustic latent representation. Args: latent: The acoustic latent representation, shape: (B, T_frame, D_latent).
Returns: The reconstructed raw audio waveform, shape: (B, T_wav) """ waveform, stream_state, past_key_values = self.decoder.low_level_reconstruct(latent, past_key_values=past_key_values, use_cache=use_cache, stream_state=stream_state, last_chunk=last_chunk) return waveform, stream_state, past_key_values123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204import torch.nn as nnimport torch.nn.functional as Ffrom transformers import Qwen2Model, Qwen2Configimport torch
from .istft import ISTFTHead
class StreamingLinearUpsample(nn.Module): def __init__(self, scale_factor=4): super().__init__() self.scale_factor = scale_factor self.upsampler = nn.Upsample(scale_factor=scale_factor, mode='linear', align_corners=False)
def forward(self, x, state=None, is_last=False): # 初始化状态 if state is None: state = { 'prev_chunk': None, 'history_last': None, 'is_first': True }
if x is None and not is_last: return None, state
if state['is_first'] and is_last: out = self.upsampler(x.transpose(1, 2)).transpose(1, 2) return out, None # 结束后清除状态
output_chunks = []
if state['is_first']: state['prev_chunk'] = x state['is_first'] = False if not is_last: return None, state
if state['prev_chunk'] is not None: p = state['prev_chunk'].transpose(1, 2)
if state['history_last'] is None: lookahead = x[:, :1, :].transpose(1, 2) inp = torch.cat([p, lookahead], dim=2) up = self.upsampler(inp) out_prev = up[:, :, :p.size(2) * self.scale_factor] else: lookahead = x[:, :1, :].transpose(1, 2) inp = torch.cat([state['history_last'], p, lookahead], dim=2) up = self.upsampler(inp) start = self.scale_factor end = start + p.size(2) * self.scale_factor out_prev = up[:, :, start:end]
output_chunks.append(out_prev.transpose(1, 2)) state['history_last'] = p[:, :, -1:] state['prev_chunk'] = x
if is_last: p = state['prev_chunk'].transpose(1, 2) inp = torch.cat([state['history_last'], p], dim=2) up = self.upsampler(inp) out_last = up[:, :, self.scale_factor:] output_chunks.append(out_last.transpose(1, 2)) state = None # 结束
final_out = torch.cat(output_chunks, dim=1) if output_chunks else None return final_out, state
class Encoder(nn.Module): def __init__(self, encoder_args, input_dim=320, hop_size=320, latent_dim=64, patch_size=-1): super().__init__() config = Qwen2Config.from_dict(config_dict=encoder_args) self.encoder = Qwen2Model(config) self.input_dim = input_dim self.hop_size = hop_size self.latent_dim = latent_dim self.fc1 = nn.Linear(input_dim, config.hidden_size, bias=False) self.fc2 = nn.Linear(config.hidden_size, config.hidden_size) self.fc3 = nn.Linear(config.hidden_size, latent_dim*2) self.norm = nn.LayerNorm(config.hidden_size) self.patch_size = patch_size if patch_size != -1: config.num_hidden_layers = 4 self.aggregator = Qwen2Model(config) self.cls_embed = nn.Parameter(torch.rand(1, 1, config.hidden_size)) self.cls_embed.data.normal_(0, 0.02)
def get_frames(self, x): num_frames_total = (x.size(-1) + self.hop_size - 1) // self.hop_size # 向上取整的帧数 expected_len = (num_frames_total - 1) * self.hop_size + self.input_dim padding_needed = expected_len - x.size(-1) waveform = F.pad(x, (0, padding_needed), value=0.0)
frames = waveform.unfold(dimension=-1, size=self.input_dim, step=self.hop_size) # [B, T, d] return frames
def pad_patch_insert_cls(self, x): bsz, _, dim = x.size() num_frame = x.size(1) r = num_frame % self.patch_size pad_num = self.patch_size-r if r else 0 x = F.pad(x, (0, 0, 0, pad_num), value=0.0) # 帧数对齐到patch_size倍数 x = x.reshape(-1, self.patch_size, dim) x = torch.cat((x, self.cls_embed.expand(x.size(0), -1, -1)), dim=1) # 每个patch后插入一个cls x = x.reshape(bsz, -1, dim) return x
def forward(self, waveform): x = self.get_frames(waveform)
x = self.fc1(x) x = self.fc2(x) x = self.encoder(inputs_embeds=x) x = x.last_hidden_state
# downsample if self.patch_size != -1: x = self.pad_patch_insert_cls(x) x = self.aggregator(inputs_embeds=x) x = x.last_hidden_state bsz, _, dim = x.size() x = x.reshape(-1, self.patch_size+1, dim) x = x[:, -1:, :].reshape(bsz, -1, dim)
x = self.fc3(x) return x, waveform.unsqueeze(1)
class Decoder(nn.Module): def __init__(self, decoder_args, output_dim=320, latent_dim=64, patch_size=-1): super().__init__() config = Qwen2Config.from_dict(config_dict=decoder_args) self.decoder = Qwen2Model(config) self.output_dim = output_dim self.latent_dim = latent_dim self.fc1 = nn.Linear(latent_dim, config.hidden_size) self.hop_length = output_dim self.head = ISTFTHead(dim=config.hidden_size, n_fft=self.hop_length * 4, hop_length=self.hop_length, padding="same") self.patch_size = patch_size if self.patch_size != -1: self.upsampling = StreamingLinearUpsample(scale_factor=patch_size)
def low_level_reconstruct(self, x, past_key_values=None, use_cache=False, stream_state=None, last_chunk=False): upsample_state, audio_buffer, window_buffer = stream_state bsz, device, dtype = x.size(0), x.device, x.dtype x = self.fc1(x) if self.patch_size != -1: if use_cache: # streaming x, upsample_state = self.upsampling(x, state=upsample_state, is_last=last_chunk) if x is None: stream_state = (upsample_state, audio_buffer, window_buffer) return torch.empty(bsz, 1, 0, device=device, dtype=dtype), stream_state, past_key_values else: x = self.upsampling.upsampler(x.transpose(1, 2)).transpose(1, 2)
hidden_states_list = []
if use_cache and getattr(self.decoder.config, "sliding_window", None) is not None: sw_size = self.decoder.config.sliding_window target_len = sw_size - 1 if past_key_values is None: past_len = 0 elif hasattr(past_key_values, "get_seq_length"): past_len = past_key_values.get_seq_length() elif isinstance(past_key_values, tuple) and len(past_key_values) > 0: past_len = past_key_values[0][0].shape[-2] else: past_len = 0
curr_len = x.shape[1]
if past_len < target_len and (past_len + curr_len) >= sw_size: fill_len = target_len - past_len x_fill = x[:, :fill_len, :] outputs = self.decoder(inputs_embeds=x_fill, past_key_values=past_key_values, use_cache=use_cache)
hidden_states_list.append(outputs.last_hidden_state) past_key_values = outputs.past_key_values
x = x[:, fill_len:, :]
outputs = self.decoder(inputs_embeds=x, past_key_values=past_key_values, use_cache=use_cache)
hidden_states_list.append(outputs.last_hidden_state) past_key_values = outputs.past_key_values
if len(hidden_states_list) > 1: full_hidden_state = torch.cat(hidden_states_list, dim=1) else: full_hidden_state = hidden_states_list[0]
x_out, _, audio_buffer, window_buffer = self.head( full_hidden_state, streaming=use_cache, audio_buffer=audio_buffer, window_buffer=window_buffer, last_chunk=last_chunk )
stream_state = (upsample_state, audio_buffer, window_buffer) return x_out, stream_state, past_key_values12345"""Native Ming Talker inference and checkpoint assets."""
from .inference import MingTalker
__all__ = ["MingTalker"]123version https://git-lfs.github.com/spec/v1oid sha256:a6ac6a63997761ae2997373e2ee1c47040854b4b759ea41ec48e4e42df0f4d73size 283034231234567891011121314151617181920212223242526272829303132333435{ "aggregator": { "attn_backend": "torch", "attn_mask_enabled": false, "depth": 8, "dropout": 0.0, "hidden_size": 1024, "in_channels": 64, "mlp_ratio": 4, "num_heads": 16, "pe_attn_head": null, "qk_norm": null }, "architectures": [ "BailingTalker2" ], "cfg_strength": 2.0, "flowmodel": { "attn_backend": "torch", "attn_mask_enabled": false, "depth": 8, "dropout": 0.0, "hidden_size": 1024, "in_channels": 64, "mlp_ratio": 4, "num_heads": 16, "pe_attn_head": null, "qk_norm": null }, "history_patch_size": 1, "patch_size": 1, "steps": 10, "torch_dtype": "bfloat16", "transformers_version": "4.51.3"}1234567891011121314151617181920# coding=utf-8# Copyright 2022 shunxing1234 and The HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.""" GLMAudio model configuration """from transformers.configuration_utils import PretrainedConfig
class BailingTalkerConfig(PretrainedConfig): pass12345678910# FastText language identification model
`lid.176.ftz` is the compressed language identification model published by thefastText project: https://fasttext.cc/docs/en/language-identification
The model is distributed under the Creative Commons Attribution-ShareAlike 3.0license: https://creativecommons.org/licenses/by-sa/3.0/
The fastText project states that the model was trained on Wikipedia, Tatoeba,and SETimes data.123version https://git-lfs.github.com/spec/v1oid sha256:8f3472cfe8738a7b6099e8e999c3cbfae0dcd15696aac7d7738a8039db603e83size 938013123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343import reimport inflect
'''number normalization for English'''
_inflect = inflect.engine()
# 移除逗号:1,000 → 1000_comma_number_re = re.compile(r"([0-9][0-9,]+[0-9])")
# 百分比:支持负数(-25.5%)_percent_number_re = re.compile(r"(-?[0-9.,]*[0-9]+)%")
# 英镑:£-150 → minus one hundred fifty pounds_pounds_re = re.compile(r"£(-?[0-9,]*[0-9]+(?:\.[0-9]+)?)")
# 美元:$-12.99_dollars_re = re.compile(r"\$(-?[0-9.,]*[0-9]+(?:\.[0-9]+)?)")
# 分数:3/4_fraction_re = re.compile(r"([0-9]+)\/([0-9]+)")
# 序数:1st, 2nd_ordinal_re = re.compile(r"\b[0-9]+(st|nd|rd|th)\b")
# 普通数字(最后处理)_number_re = re.compile(r"\b-?[0-9]+(?:\.[0-9]+)?\b")
# 单位:10ms, 5.5 kg 等_unit_re = re.compile( r'\b(-?\d+(?:\.\d+)?)\s*(ms|s|Hz|kHz|MHz|GHz|kb|mb|gb|tb|KB|MB|GB|TB|bps|kbps|Mbps|Gbps|cm|km|kg|V|A|W|°C|°F)\b', re.IGNORECASE)
# 正则:支持 v2, v2.1, gpt-4, gpt-4.5_version_re = re.compile(r'\b([a-zA-Z]+)([-]?)([0-9]+(?:\.[0-9]+)?)\b')
# 空白字符_whitespace_re = re.compile(r"\s+")
# 标点符号(可选)_colon_re = re.compile(r":")
_unit_mapping = { 'ms': 'milliseconds', 's': 'seconds', 'hz': 'hertz', 'khz': 'kilohertz', 'mhz': 'megahertz', 'ghz': 'gigahertz', 'kb': 'kilobytes', 'mb': 'megabytes', 'gb': 'gigabytes', 'tb': 'terabytes', 'kbps': 'kilobits per second', 'mbps': 'megabits per second', 'gbps': 'gigabits per second', 'bps': 'bits per second', 'cm': 'centimeters', 'km': 'kilometers', 'kg': 'kilograms', 'v': 'volts', 'a': 'amperes', 'w': 'watts', '°c': 'degrees celsius', '°f': 'degrees fahrenheit',}
def _remove_commas(m): return m.group(1).replace(",", "")
def _expand_colon(m): return " colon "
def _expand_unit(m): num_str = m.group(1) unit = m.group(2).lower() unit_word = _unit_mapping.get(unit, unit)
try: is_negative = num_str.startswith('-') clean_num = num_str.lstrip('-') if not clean_num: clean_num = '0'
if '.' in clean_num: parts = clean_num.split('.', 1) integer_part = parts[0] or '0' decimal_part = parts[1]
# 检查是否全为数字 if not integer_part.isdigit() or not decimal_part.isdigit(): return f" {num_str} {unit} "
integer_word = _inflect.number_to_words(int(integer_part), andword="") if integer_part != '0' else 'zero' decimal_words = " ".join( _inflect.number_to_words(int(d), andword="") for d in decimal_part if d.isdigit() ) num_word = f"{integer_word} point {decimal_words}" else: if not clean_num.isdigit(): return f" {num_str} {unit} " num_word = _inflect.number_to_words(int(clean_num), andword="")
if is_negative: num_word = f"minus {num_word}"
return f" {num_word} {unit_word} " except Exception: return f" {num_str} {unit} "
def _expand_percent(m): num_str = m.group(1) try: is_negative = num_str.startswith('-') clean_num = num_str.lstrip('-') if not clean_num: clean_num = '0'
if '.' in clean_num: parts = clean_num.split('.', 1) integer_part = parts[0] or '0' decimal_part = parts[1]
if not integer_part.isdigit() or not decimal_part.isdigit(): return f" {num_str} percent "
integer_word = _inflect.number_to_words(int(integer_part), andword="") if integer_part != '0' else 'zero' decimal_words = " ".join( _inflect.number_to_words(int(d), andword="") for d in decimal_part if d.isdigit() ) num_word = f"{integer_word} point {decimal_words}" else: if not clean_num.isdigit(): return f" {num_str} percent " num_word = _inflect.number_to_words(int(clean_num), andword="")
if is_negative: num_word = f"minus {num_word}"
return f" {num_word} percent " except Exception: return f" {num_str} percent "
def _expand_dollars(m): match = m.group(1) is_negative = match.startswith('-') clean_match = match.lstrip('-') if not clean_match: clean_match = '0'
try: if '.' in clean_match: parts = clean_match.split('.', 1) integer_part = parts[0] or '0' decimal_part = parts[1]
if not integer_part.isdigit() or not decimal_part.isdigit(): return f" {clean_match} dollars "
integer_word = _inflect.number_to_words(int(integer_part), andword="") if integer_part != '0' else 'zero' decimal_words = " ".join( _inflect.number_to_words(int(d), andword="") for d in decimal_part if d.isdigit() ) num_word = f"{integer_word} point {decimal_words}" else: if not clean_match.isdigit(): return f" {clean_match} dollars " num_word = _inflect.number_to_words(int(clean_match), andword="")
if is_negative: num_word = f"minus {num_word}"
value = float(clean_match) unit = "dollar" if abs(value) == 1.0 else "dollars" return f" {num_word} {unit} " except Exception: return f" {clean_match} dollars "
def _expand_pounds(m): num_str = m.group(1) is_negative = num_str.startswith('-') clean_num = num_str.lstrip('-') if not clean_num: clean_num = '0'
try: if '.' in clean_num: parts = clean_num.split('.', 1) integer_part = parts[0] or '0' decimal_part = parts[1]
if not integer_part.isdigit() or not decimal_part.isdigit(): return f" {clean_num} pounds "
integer_word = _inflect.number_to_words(int(integer_part), andword="") if integer_part != '0' else 'zero' decimal_words = " ".join( _inflect.number_to_words(int(d), andword="") for d in decimal_part if d.isdigit() ) num_word = f"{integer_word} point {decimal_words}" else: if not clean_num.isdigit(): return f" {clean_num} pounds " num_word = _inflect.number_to_words(int(clean_num), andword="")
if is_negative: num_word = f"minus {num_word}"
value = float(clean_num) unit = "pound" if abs(value) == 1.0 else "pounds" return f" {num_word} {unit} " except Exception: return f" {clean_num} pounds "
def fraction_to_words(numerator, denominator): try: if numerator == 1 and denominator == 2: return " one half " if numerator == 1 and denominator == 4: return " one quarter " if denominator == 2: plural = " half" if numerator == 1 else " halves" return f" {_inflect.number_to_words(numerator)}{plural} " if denominator == 4: plural = " quarter" if numerator == 1 else " quarters" return f" {_inflect.number_to_words(numerator)}{plural} " ordinal = _inflect.ordinal(_inflect.number_to_words(denominator)) return f" {_inflect.number_to_words(numerator)} {ordinal} " except Exception: return f" {numerator} over {denominator} "
def _expand_fraction(m): try: numerator = int(m.group(1)) denominator = int(m.group(2)) return fraction_to_words(numerator, denominator) except Exception: return m.group(0)
def _expand_ordinal(m): try: # 提取纯数字部分 num = int(re.sub(r"(st|nd|rd|th)", "", m.group(0))) word = _inflect.number_to_words(num) return f" {word} " except Exception: return m.group(0)
def _expand_number(m): num_str = m.group(0) try: is_negative = num_str.startswith('-') clean_num = num_str.lstrip('-') if not clean_num: clean_num = '0'
if '.' in clean_num: parts = clean_num.split('.', 1) integer_part = parts[0] decimal_part = parts[1]
if not integer_part: integer_part = '0' if not integer_part.isdigit() or not decimal_part.isdigit(): return f" {num_str} "
integer_word = _inflect.number_to_words(int(integer_part), andword="") if integer_part != '0' else 'zero' decimal_words = " ".join( _inflect.number_to_words(int(d), andword="") for d in decimal_part if d.isdigit() ) num_word = f"{integer_word} point {decimal_words}" else: if not clean_num.isdigit(): return f" {num_str} " num_word = _inflect.number_to_words(int(clean_num), andword="")
if is_negative: num_word = f"minus {num_word}"
return f" {num_word} " except Exception: return f" {num_str} "
def _expand_version(m): prefix = m.group(1) sep = m.group(2) num_str = m.group(3)
try: if '.' in num_str: parts = num_str.split('.', 1) integer_part = parts[0] decimal_part = parts[1]
if not integer_part.isdigit() or not decimal_part.isdigit(): return m.group(0)
integer_word = _inflect.number_to_words(int(integer_part)) decimal_words = " ".join( _inflect.number_to_words(int(d)) for d in decimal_part if d.isdigit() ) word = f"{integer_word} point {decimal_words}" else: if not num_str.isdigit(): return m.group(0) word = _inflect.number_to_words(int(num_str)) except Exception: return m.group(0)
# 连字符替换为空格,如 gpt-4 → gpt four if sep == '-': return f"{prefix} {word}" # 直接拼接则加空格读出:v2 → v two return f"{prefix} {word}"
def normalize_numbers(text): text = re.sub(_comma_number_re, _remove_commas, text) text = re.sub(_unit_re, _expand_unit, text) # 带单位的量(含负数) text = re.sub(_pounds_re, _expand_pounds, text) text = re.sub(_dollars_re, _expand_dollars, text) text = re.sub(_fraction_re, _expand_fraction, text) text = re.sub(_percent_number_re, _expand_percent, text) text = re.sub(_ordinal_re, _expand_ordinal, text) text = re.sub(_version_re, _expand_version, text) # 新增:处理 v2, gpt-4 text = re.sub(_number_re, _expand_number, text) # 剩余孤立数字 # text = re.sub(_colon_re, _expand_colon, text) # 冒号(可选) text = re.sub(_whitespace_re, " ", text) return text.strip()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388import reimport string
def is_chinese(text): """检测文本是否包含中文""" # 使用简单规则判断 return bool(re.search(r'[\u4e00-\u9fff]', text))
def get_lang_type(text): """ - 'zh': 只包含中文字符(及相关标点)。 - 'en': 只包含英文字符(及相关标点)。 - 'mixed': 同时包含中文字符和英文字符。 - 'other': 只包含数字、符号等,不含中英文字符。 """ has_chinese = bool(re.search(r'[\u4e00-\u9fff]', text)) has_english = bool(re.search(r'[a-zA-Z]', text))
if has_chinese and has_english: return 'mixed' if has_chinese: return 'zh' if has_english: return 'en' return 'other'
def split_and_group_sentences(text, group_by_lang=False): # 分句正则表达式,匹配中文和英文的句子结束标点 # pattern = r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=[.!?。!?])\s*' # 仅匹配中文冒号 `:` 或英文冒号 `:` 后跟空格的情况 pattern = r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=[.!?。!?]|:(?=\s)|:)\s*' sentences = [s.strip() for s in re.split(pattern, text.strip()) if s.strip()] if not group_by_lang: return sentences # 聚合相同语言的相邻子句 grouped = [] current_group = [] current_lang = None for sentence in sentences: lang = 'zh' if is_chinese(sentence) else 'en' if current_lang is None: current_group.append(sentence) current_lang = lang elif lang == current_lang: # 中文直接连接,英文添加空格 if lang == 'zh': current_group.append(sentence) else: current_group.append(' ' + sentence if sentence[0].isalnum() else sentence) else: grouped.append(''.join(current_group)) current_group = [sentence] current_lang = lang if current_group: grouped.append(''.join(current_group)) return grouped
def get_semantic_length(text): """ 计算字符串的语义长度。 一个汉字计为1,一个连续的英文字母串(单词)计为1。 """ chinese_char_count = len(re.findall(r'[\u4e00-\u9fa5]', text)) # [a-zA-Z]+ 匹配一个或多个连续的英文字母 english_word_count = len(re.findall(r'[a-zA-Z]+', text)) return chinese_char_count + english_word_count def has_valid_content(text): """ 判断文本是否包含有效字符(非标点符号) """ punctuation_and_whitespace = string.punctuation + string.whitespace for char in text: if char not in punctuation_and_whitespace: return True return False def append_text_fragment(fragments, new_text, max_len, min_tail_length): """ 将新文本追加到片段列表中,根据语义长度决定是否合并 """ # 清理 new_text 的前导标点和空格 new_text = new_text.lstrip(",,:;" + string.whitespace) if not has_valid_content(new_text): return fragments
if not fragments: fragments.append(new_text) return fragments
last_fragment = fragments[-1] last_semantic_len = get_semantic_length(last_fragment) new_semantic_len = get_semantic_length(new_text)
if last_semantic_len + new_semantic_len <= max_len: # 特殊处理:如果上一段以句号结尾且新文本很短,则开启新段落 if last_fragment.endswith(("。", "!", "?")) and new_semantic_len < min_tail_length: fragments.append(new_text) else: # 决定连接符,让中英文拼接更自然 separator = "" # 如果上一个片段结尾不是空格,且新片段以英文/数字开头,则加个空格 if not last_fragment.endswith(" ") and re.match(r'^[a-zA-Z0-9]', new_text): separator = " " fragments[-1] += separator + new_text else: # 开启新段落时,new_text 已经被清理过了 fragments.append(new_text) return fragments
def split_long_fragment(text_fragment, max_len): """ 分割超长的文本片段。优先沿标点(clause边界)切,避免从字中间断开。 仅当单个 clause 自身仍超 max_len 时,才退化到字/词级切分(保底不卡死)。 """ fragment_semantic_len = get_semantic_length(text_fragment) if fragment_semantic_len <= max_len: return [text_fragment]
# —— 第一优先级:沿标点切 clause —— # 标点(中文,、;。!? + 英文 ,;!?!) 及列表分隔(空格+[-•·]) 作为切分边界。 # 用 split 保留分隔符并并回前一 clause, 使子串拼接 == 原文(位置校准仍能 find 到)。 clause_pattern = r'([,、;。!?,;!?]|\s+[-•·])' parts = re.split(clause_pattern, text_fragment) merged_clauses = [] for part in parts: if part == "": continue if merged_clauses and re.fullmatch(clause_pattern, part): merged_clauses[-1] += part # 标点/分隔 并回前一段 else: merged_clauses.append(part)
fragments = [] current_fragment = ""
for clause in merged_clauses: clause_semantic_len = get_semantic_length(clause)
# 单个 clause 自身超 max_len: 保底字/词级切分(避免无限卡死) if clause_semantic_len > max_len: if current_fragment: fragments.append(current_fragment) current_fragment = "" fragments.extend(_split_by_char_word(clause, max_len)) continue
current_semantic_len = get_semantic_length(current_fragment) if current_semantic_len + clause_semantic_len <= max_len: current_fragment += clause else: if current_fragment: fragments.append(current_fragment) current_fragment = clause
if current_fragment: fragments.append(current_fragment)
return fragments
def _split_by_char_word(text, max_len): """ 保底切分:按字(汉字)/词(英文)等基本语义单元切,用于单个 clause 仍超长时。 """ fragments = [] current = "" tokens = re.findall(r'(\s+|[,、;。!?,;!?]|[\u4e00-\u9fa5]|[a-zA-Z]+|[^a-zA-Z\u4e00-\u9fa5]+)', text) for tok in tokens: tok_len = get_semantic_length(tok) cur_len = get_semantic_length(current) if cur_len + tok_len <= max_len: current += tok else: if current: fragments.append(current) if tok_len > max_len: fragments.append(tok) current = "" else: current = tok if current: fragments.append(current) return fragments
def calibrate_positions(fragments, positions, original_text): """ 校准fragments和positions的对齐关系 """ calibrated_positions = {} current_global_pos = 0 for frag_idx, fragment in enumerate(fragments): # 在原始文本中查找当前片段的位置 frag_len = len(fragment) found_pos = original_text.find(fragment, current_global_pos) if found_pos == -1: # 如果找不到,尝试放宽条件(如忽略空格差异) simplified_frag = fragment.replace(" ", "") simplified_original = original_text.replace(" ", "") found_pos = simplified_original.find(simplified_frag, current_global_pos) if found_pos != -1: # 找到后映射回原始位置 non_space_count = original_text[:found_pos].count(" ") found_pos += non_space_count if found_pos == -1: # 如果仍然找不到,使用原positions中的值(降级处理) if frag_idx in positions: calibrated_positions[frag_idx] = positions[frag_idx] else: calibrated_positions[frag_idx] = (current_global_pos, current_global_pos + frag_len) continue calibrated_positions[frag_idx] = (found_pos, found_pos + frag_len) current_global_pos = found_pos + frag_len return calibrated_positions
def cut_text_by_semantic_length(text, max_semantic_length=50, min_tail_length=5): """ 按照语义长度划分文本,保持语义单元的完整性,并返回位置信息 Args: text: 输入文本 max_semantic_length: 最大语义长度限制 min_tail_length: 尾部最小长度 Returns: dict: { "fragments": List[str], # 分割后的文本片段列表 "positions": Dict[int, Tuple[int, int]] # 子句位置信息(key为顺序,value为(起始index, 结束index)) } """ if not has_valid_content(text): return {"fragments": [], "positions": {}}
# 保存原始文本用于位置计算 original_text = text # 定义一个独特的占位符 DOT_PLACEHOLDER = "##DOT##" # 保护小数点和特定缩写中的点 # 使用正则表达式查找数字中的点(如 3.14)和常见缩写中的点(如 U.S.A.) # 并将它们替换为占位符 # `\d\.\d` 匹配数字间的小数点 # `([A-Z])\.([A-Z])` 匹配大写字母间的点
processed_text = re.sub(r'(\d)\.(\d)', r'\1' + DOT_PLACEHOLDER + r'\2', text) for _ in range(3): processed_text = re.sub(r'([A-Z])\.([A-Z])', r'\1' + DOT_PLACEHOLDER + r'\2', processed_text)
processed_text = processed_text.replace("\n", " ").replace("。,", "。") if get_semantic_length(processed_text) <= max_semantic_length: # 返回前恢复占位符 return { "fragments": [processed_text.replace(DOT_PLACEHOLDER, ".")], "positions": {0: (0, len(text))} # 整个文本的位置 }
# 标点标准化(只在处理时使用,不影响原始位置计算) normalized_text = processed_text.replace(".", "。").replace("!", "!").replace("?", "?").replace(",", ",") result_fragments = [] position_map = {} global_offset = 0 # 跟踪在原始文本中的位置
# 第一阶段:按句子分割 sentences = [] sentence_positions = [] current_sentence = "" start_idx = 0 for i, char in enumerate(normalized_text): current_sentence += char if char in "。!?": # 移除了 '.' 和 '!' '?' sentence = current_sentence.strip() if sentence: sentences.append(sentence) sentence_positions.append((start_idx, i + 1)) # 包含标点的结束位置 current_sentence = "" start_idx = i + 1
# 处理最后一个句子 if current_sentence: # 如果最后一部分没有标点,可以补上,也可以不补,保持原逻辑 sentences.append(current_sentence.strip()) sentence_positions.append((start_idx, len(normalized_text))) if not sentences[-1].endswith(("。", "!", "?")): sentences[-1] += "。"
# 第二阶段:处理每个句子 fragment_counter = 0 for sent_idx, (sentence, (sent_start, sent_end)) in enumerate(zip(sentences, sentence_positions)): clauses = [] clause_positions = [] current_clause = "" clause_start = 0 for i, char in enumerate(sentence): current_clause += char if char in ",;;": # 移除了 ',' clause = current_clause.strip() if clause and has_valid_content(clause): clauses.append(clause) clause_positions.append((clause_start, i + 1)) # 在句子中的相对位置 elif clause and clauses: clauses[-1] += clause clause_positions[-1] = (clause_positions[-1][0], i + 1) current_clause = "" clause_start = i + 1
if current_clause: clause = current_clause.strip() if clause and has_valid_content(clause): clauses.append(clause) clause_positions.append((clause_start, len(sentence))) elif clause and clauses: clauses[-1] += clause clause_positions[-1] = (clause_positions[-1][0], len(sentence))
# 第三阶段:处理每个子句 i = 0 while i < len(clauses): clause = clauses[i] clause_start_in_sent, clause_end_in_sent = clause_positions[i] # 计算在原始文本中的绝对位置 abs_start = sent_start + clause_start_in_sent abs_end = sent_start + clause_end_in_sent clause_semantic_len = get_semantic_length(clause)
# 如果当前子句很短,则尝试与下一个子句聚合 if clause_semantic_len < min_tail_length and i + 1 < len(clauses): next_clause = clauses[i + 1] next_start, next_end = clause_positions[i + 1] combined_clause = clause + next_clause combined_semantic_len = get_semantic_length(combined_clause) # 如果聚合后的子句不超过最大长度,则聚合 if combined_semantic_len <= max_semantic_length: result_fragments = append_text_fragment(result_fragments, combined_clause, max_semantic_length, min_tail_length) # 合并位置信息 merged_position = (abs_start, sent_start + next_end) position_map[fragment_counter] = merged_position fragment_counter += 1 i += 2 continue
# 如果子句仍然超过最大长度,则进一步分割 if clause_semantic_len > max_semantic_length: sub_fragments = split_long_fragment(clause, max_semantic_length) # 等分位置(简化处理,实际应根据语义分割调整) frag_len = len(clause) sub_frag_count = len(sub_fragments) for j, frag in enumerate(sub_fragments): result_fragments = append_text_fragment(result_fragments, frag, max_semantic_length, min_tail_length) frag_len_part = len(frag) frag_start = abs_start + j * (frag_len // sub_frag_count) frag_end = frag_start + frag_len_part position_map[fragment_counter] = (frag_start, frag_end) fragment_counter += 1 else: result_fragments = append_text_fragment(result_fragments, clause, max_semantic_length, min_tail_length) position_map[fragment_counter] = (abs_start, abs_end) fragment_counter += 1 i += 1
# 最终返回结果前,恢复所有片段中的占位符 final_result = [frag.replace(DOT_PLACEHOLDER, ".") for frag in result_fragments]
calibrated_positions = calibrate_positions(final_result, position_map, original_text) return { "fragments": final_result, "positions": calibrated_positions }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240import refrom typing import Iterable
TOKENIZE_PATTERN = r"(?:[a-zA-Z]\.)+|[a-zA-Z]+(?:['\-][a-zA-Z]+)*|\d+(?:\.\d+)?|[\u4e00-\u9fff]|\s+|\S"
def tokenize_mixed_text(text: str): """ 将混合文本字符串处理为标记列表,并保留原始的空格。 """ return re.findall(TOKENIZE_PATTERN, text)
def tokenize_mixed_text_iterator(text_iterator: Iterable[str]): """ Args: text_iterator (Iterable[str]): 一个产出字符串的迭代器。 例如,一个打开的文件对象,或一个生成器表达式。 Yields: Iterator[str]: 逐一产出文本中的标记(单词、中文、标点、空格等)。 """ # 函数本身就是一个生成器,将从 re.finditer 返回的迭代器中逐一产出结果 for chunk in text_iterator: # re.finditer 返回一个迭代器,而不是列表 for match in re.finditer(TOKENIZE_PATTERN, chunk): yield match.group(0)
def split_uppercase_acronyms(text): """ 将连续大写字母(缩写词)逐字母用空格隔开。 单个大写字母或首字母大写的单词不受影响。 """ return re.sub(r'[A-Z]{2,}', lambda m: ' '.join(m.group(0)), text)
def replace_parens_with_sep(text, target_sep=','): """ 将中英文括号替换为target_sep。 """ for ch in '()()': text = text.replace(ch, target_sep) return text
def clean_text_formatting(text): if not text: return text # 定义开头需要被替换为空格的“杂质标点” # 保留了:() {} [] () 【】 "" '' “” ‘’ 《》 等成对符号 # 替换掉:, 。 ! ? ; : 、 …… 等容易出现在开头且没意义的标点 leading_punct_pattern = r'^[,。!?;:、……\.\!\?\-\—]+' # 替换开头标点 text = re.sub(leading_punct_pattern, ' ', text) # # 聚合连续空格 # text = re.sub(r'\s+', ' ', text) # 去除首尾多余空格 return text.strip()
def chinese_punc_en2cn(text): """ 含中文文本清理:包含中文即处理,多个堆叠标点最终只保留一个。 1. 增加 URL和小数点 保护,防止链接内部符号被误转。 2. 增强标点优先级逻辑,确保顿号(、)正确去重。 3. 修复异类标点堆叠的匹配规则。 4、修复开头符号 """ # # 允许的字符范围:汉字、中文标点、全角符号、空格、以及常见的英文标点 # # 明确排除:a-zA-Z(英文字母)、0-9(数字) # # gen_tag = 'tn' # if re.search(r'[a-zA-Z0-9]', text): # return text # 仅检查是否包含中文,无中文则直接返回原文本 # gen_tag = 'tn_v1' if not text or not re.search(r'[\u4e00-\u9fa5]', text): return clean_text_formatting(text)
# URL 占位保护 urls = re.findall(r'https?://[^\s,。!?]+', text) for i, url in enumerate(urls): text = text.replace(url, f"URLHOLDER{i}")
# 保护数字间的小数点,防止被 punc_map 误转为 。 text = re.sub(r'(?<=\d)\.(?=\d)', 'DOTPLACEHOLDER', text)
# 基础符号转换 text = text.replace('...', '……') punc_map = { ',': ',', '.': '。', ';': ';', ':': ':', '!': '!', '?': '?', '(': '(', ')': ')', '[': '【', ']': '】', '<': '《', '>': '》', '_': '——' } map_pattern = re.compile('|'.join(re.escape(k) for k in punc_map.keys())) text = map_pattern.sub(lambda m: punc_map[m.group(0)], text)
# 还原小数点 text = text.replace('DOTPLACEHOLDER', '.')
# 修复:引号计数与转换 (改用闭包计数,避免 := 运算符在 re.sub 中的潜在崩溃) dq_count = [0] sq_count = [0]
def dq_sub(_): dq_count[0] += 1 return '“' if dq_count[0] % 2 != 0 else '”'
def sq_sub(_): sq_count[0] += 1 return '‘' if sq_count[0] % 2 != 0 else '’'
text = re.sub(r'"', dq_sub, text) text = re.sub(r"'", sq_sub, text) # 彻底消除标点周边的空格 ch_puncs = r',。!?;:“”‘’()【】《》——……、' text = re.sub(fr'[ \t\u00A0\u3000]*([{ch_puncs}])[ \t\u00A0\u3000]*', r'\1', text)
# 标点递归清理 while True: old_text = text # 压缩完全相同的重复标点 text = re.sub(r'([{ch_puncs}])\1+', r'\1', text) # 弱标点(,;、) 遇到 强标点(。!?) 时删除弱标点 text = re.sub(r'[,;、]+([。!?])', r'\1', text) text = re.sub(r'([。!?])[,;、]+', r'\1', text) # 处理 逗号/分号 与 顿号 的堆叠 text = re.sub(r'[,;]+[、]|[、][,;]+', '、', text) # 强标点间唯一化 text = re.sub(r'([。!?])[。!?]+', r'\1', text) # 剩余异类弱标点堆叠唯一化 text = re.sub(r'([,;、])[,;、]+', r'\1', text)
if old_text == text: break
# 压缩汉字/单词间连续空格 text = re.sub(r'[ \t\u00A0\u3000]+', ' ', text) # 还原 URL for i, url in enumerate(urls): text = text.replace(f"URLHOLDER{i}", url)
return clean_text_formatting(text)
# 弱标点结尾视为未收束,升格为句末标点(替换而非追加:# 纯英文不经 chinese_punc_en2cn 的标点去重,追加会留下 ",." 漏网)WEAK_TAIL_PUNCT = ',,、;;'
def add_period(text): """尾部无标点则添加句号;汉字结尾加'。',否则加'.'。弱标点(,,、;;)结尾升格为句末标点""" stripped = text.rstrip() if not stripped: # 空串或全空白 return "."
last_char = stripped[-1]
# 弱标点结尾(逗号/顿号/分号):升格为句末标点 if last_char in WEAK_TAIL_PUNCT: has_chinese = bool(re.search(r'[一-鿿]', stripped)) # U+4E00-U+9FFF 汉字区 return stripped[:-1] + ('。' if has_chinese else '.')
# 如果最后一个字符不是字母或数字,则认为它已是标点符号,直接返回 if not last_char.isalnum(): return stripped
# 判断是否为汉字(基本汉字区和扩展A区) is_chinese = ('\u4e00' <= last_char <= '\u9fff' or '\u3400' <= last_char <= '\u4dbf') suffix = '。' if is_chinese else '.' return stripped + suffix
def fallback_replace_non_alnum(text, replacement=','): """ 兜底方案:将非汉字、英文、数字及基础TTS标点的字符替换为指定符号。 并合并连续的替换符号。 保留中文基础标点:,。!?;:、 保留英文基础标点:,.!?;: 保留小数点:.和空格等 """ # 白名单新增: () () " “ ” (半角/全角括号 + 半角/中文双引号) 不再被替换成逗号 text = re.sub(r"[^\u4e00-\u9fffA-Za-z0-9,。!?;:、,.!?;:\. \u2019\u2018'\"()()\u201C\u201D]", replacement, text) text = re.sub(re.escape(replacement) + '+', replacement, text).strip() return text
def normalize_text_kit(text): """ 完整文本规范化流水线: 连续大写字母拆开(NBA → N B A) (已禁用) 中英括号替换为逗号 兜底:非汉字/英文/数字/基础标点 → 逗号 (已把 () () " “ ” 加入白名单) 英文标点→中文标点 + 标点去重 + 空格清理 """ #print(f'[normalize_text_kit] 输入 : {text!r}') # ---- 已禁用: 连续大写字母拆分(NBA → N B A)---- # text = split_uppercase_acronyms(text) #print(f'[normalize_text_kit] step1 大写拆分后 : {text!r}') # ---- 已禁用: 不再把括号替换成逗号 ---- # text = replace_parens_with_sep(text) # print(f'[normalize_text_kit] step2 括号替换后 : {text!r}') text = fallback_replace_non_alnum(text) #print(f'[normalize_text_kit] step3 兜底非白名单→, : {text!r}') text = chinese_punc_en2cn(text) #print(f'[normalize_text_kit] step4 英文标点→中文 : {text!r}') text = re.sub(r'\s+', ' ', text).strip() #print(f'[normalize_text_kit] step5 空格清理后 : {text!r}') return text
def strip_markdown_code(text): """ 清除 Markdown 行内代码标记(反引号)。 支持单反引号 `code` 和双反引号 ``code`` 两种格式。 """ # 双反引号优先匹配(避免单反引号先匹配到内层) text = re.sub(r'``(.+?)``', r'\1', text) # 单反引号 text = re.sub(r'`(.+?)`', r'\1', text) # 清除残留的未配对反引号 text = text.replace('`', '') return text
def preprosess_text(text): """ 文本预处理: 清除 Markdown 行内代码标记 """ text = strip_markdown_code(text) return text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443"""Synchronous Ming Talker, adapted from talker_transformers_inference.
Native prompt formatting, text normalization, CFM, DiT, Aggregator and AudioVAEare retained. Qwen2 uses the installed Transformers cache API; inference needsneither vLLM nor engine workers, CUDA graphs, thread pools or temporary files."""
from contextlib import nullcontextfrom functools import cached_propertyfrom pathlib import Pathimport randomimport re
import numpy as npimport onnxruntimefrom safetensors.torch import load_fileimport torchfrom torch import nnimport torchaudiofrom torchaudio.compliance import kaldifrom transformers import AutoTokenizer, Qwen2Config, Qwen2Model
from .AudioVAE.configuration_audio_vae import AudioVAEconfigfrom .AudioVAE.modeling_audio_vae import AudioVAEfrom .configuration_bailing_talker import BailingTalkerConfigfrom .front.number_en import normalize_numbersfrom .front.text_segment_cut import cut_text_by_semantic_length, is_chinesefrom .front.toolkit import ( add_period, normalize_text_kit, preprosess_text, tokenize_mixed_text_iterator,)from .talker_module.aggregator import Aggregatorfrom .talker_module.cfm import CFM, get_epss_timestepsfrom .talker_module.dit import DiTfrom .talker_tn.talker_tn import TalkerTNfrom .tts_prompt import ( DEFAULT_TTS_PROMPT, append_optional_target_language, build_task_instruction, contains_paralinguistic_tag, preserve_multilingual_text, protect_paralinguistic_tags, resolve_request_language, restore_paralinguistic_tags, target_language_from_prompt,)
class MingTalker(nn.Module): def __init__(self, path: Path): super().__init__() self.path = path self.config = BailingTalkerConfig.from_pretrained(path) self.tokenizer = AutoTokenizer.from_pretrained(path / "llm") llm_config = Qwen2Config.from_pretrained(path / "llm") llm_config._attn_implementation = "sdpa" self.model = Qwen2Model(llm_config) self.cfm = CFM( DiT(llm_cond_dim=llm_config.hidden_size, **self.config.flowmodel), steps=self.config.steps, ) self.aggregator = Aggregator( llm_input_dim=llm_config.hidden_size, **self.config.aggregator ) self.stop_head = nn.Linear(llm_config.hidden_size, 2) self.spk_head = nn.Linear(192, llm_config.hidden_size) self.normalizer = TalkerTN() self.latent_dim = 64 self.patch_size = self.config.patch_size self.history_patch_size = self.config.history_patch_size
@classmethod def from_pretrained(cls, path, *, dtype=torch.bfloat16, device="cuda:0"): path = Path(path).resolve() model = cls(path).to(dtype=dtype) weights = load_file(str(path / "model.safetensors")) # Recent x-transformers computes RoPE frequencies instead of persisting them. state_keys = model.state_dict().keys() weights = { key: value for key, value in weights.items() if not (key.endswith("rotary_embed.inv_freq") and key not in state_keys) } model.load_state_dict(weights, strict=True) vae_config = AudioVAEconfig.from_pretrained(path / "vae") vae_config._attn_implementation = "eager" for section in ( vae_config.enc_kwargs["backbone"], vae_config.dec_kwargs["backbone"], ): section["_attn_implementation"] = "eager" section["attn_implementation"] = "eager" model.audio_vae = AudioVAE(vae_config).to(dtype=dtype) model.audio_vae.load_state_dict( load_file(str(path / "vae/model.safetensors")), strict=True ) return model.to(device).eval()
@property def device(self): return next(self.model.parameters()).device
@property def dtype(self): return next(self.model.parameters()).dtype
@cached_property def speaker_encoder(self): options = onnxruntime.SessionOptions() options.graph_optimization_level = ( onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL ) options.intra_op_num_threads = 2 return onnxruntime.InferenceSession( str(self.path / "campplus.onnx"), sess_options=options, providers=["CPUExecutionProvider"], )
def reference_features(self, reference, continuation): waveform = torch.as_tensor(reference["samples"], dtype=torch.float32).reshape( 1, -1 ) sample_rate = reference["sample_rate"] speaker_waveform = torchaudio.functional.resample(waveform, sample_rate, 16000) features = kaldi.fbank( speaker_waveform, num_mel_bins=80, dither=0, sample_frequency=16000 ) features -= features.mean(dim=0, keepdim=True) embedding = self.speaker_encoder.run( None, {self.speaker_encoder.get_inputs()[0].name: features.unsqueeze(0).numpy()}, )[0] speaker = [ self.spk_head( torch.as_tensor( embedding, device=self.device, dtype=self.dtype ).reshape(1, 192) ) ] if not continuation: return speaker, None, None waveform = torchaudio.functional.resample( waveform, sample_rate, self.audio_vae.config.sample_rate ) alignment = ( self.audio_vae.encoder.hop_size * max(1, self.audio_vae.encoder.patch_size) * self.patch_size ) waveform = nn.functional.pad(waveform, ((-waveform.shape[-1]) % alignment, 0)) latents, _ = self.audio_vae.encode_latent( waveform.to(device=self.device, dtype=self.dtype), torch.tensor([waveform.shape[-1]], device=self.device), ) embeddings = self.aggregator( latents.reshape(-1, self.patch_size, self.latent_dim) ) return ( speaker, latents, embeddings.reshape(1, -1, self.model.config.hidden_size), )
def text_fragments(self, value, max_length=50): """Mirror the legacy TTS-family buffering before TN.""" streaming_text = [] count = 0 for index, ele in enumerate(tokenize_mixed_text_iterator(value)): if len(ele) == 0: continue should_process = False if ele[-1] in "!?。!?" and ( len(streaming_text) >= 12 or (count > 0 and len(streaming_text) >= 8) ): should_process = True streaming_text.append(ele) elif ele[-1] in ",," and len(streaming_text) >= 36: should_process = True streaming_text.append(ele) elif ( ele[-1] == "." and ( len(streaming_text) >= 12 or (count > 0 and len(streaming_text) >= 8) ) and (not bool(re.search("[0-9]", streaming_text[-1][-1]))) ): should_process = True streaming_text.append(ele) elif ele[-1] == "\n": if len(streaming_text) > 0: if re.search("[\\u4e00-\\u9fff]", "".join(streaming_text)): if re.search("[\\u4e00-\\u9fff]", streaming_text[-1][-1]): ele = "," streaming_text.append(ele) else: if len(ele) > 1 and re.search("[a-zA-Z]", ele[-2]): ele = ele[:-1] + "." else: ele = ele[:-1] streaming_text.append(ele) if len(streaming_text) >= 12 or ( count > 0 and len(streaming_text) >= 8 ): should_process = True else: streaming_text.append(ele) continue if should_process: buffered_text = preprosess_text("".join(streaming_text)) text_list = cut_text_by_semantic_length(buffered_text, max_length)[ "fragments" ] count += len(text_list) yield from text_list streaming_text = [] if streaming_text and re.search( "[a-zA-Z\\u4e00-\\u9fff1-9]", "".join(streaming_text) ): buffered_text = preprosess_text("".join(streaming_text)) buffered_text = add_period(buffered_text) yield from cut_text_by_semantic_length(buffered_text, max_length)[ "fragments" ]
def input_embeddings( self, text, prompt, instruction, speaker, prompt_text, prompt_embeddings ): encode = self.tokenizer.encode speaker_tokens = [] for index, _ in enumerate(speaker or []): speaker_tokens += ( encode(f" speaker_{index + 1}:") + encode("<|vision_start|>") + encode("<|vision_pad|>") + encode("<|vision_end|>\n") ) continuation = prompt_embeddings is not None and prompt_text is not None tokens = ( encode("<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n") + encode("<|im_start|>user\n") + encode(prompt) + speaker_tokens + encode(" Text input:\n") + (encode(prompt_text) if continuation else []) + encode(text) + encode("<|im_end|>\n") + encode("<|im_start|>assistant\n") + (encode(instruction) + encode("<|im_end|>") if instruction else []) + encode("<audio>") + ( encode("<audioPatch>") * prompt_embeddings.shape[1] if continuation else [] ) ) ids = torch.tensor([tokens], device=self.device) embeddings = self.model.get_input_embeddings()(ids) if speaker: positions = torch.where(ids[0] == encode("<|vision_start|>")[0])[0] for position, embedding in zip(positions, speaker): embeddings[0, position + 1] = embedding if continuation: start = torch.where(ids[0] == encode("<audio>")[0])[0][0] + 1 embeddings[0, start : start + prompt_embeddings.shape[1]] = ( prompt_embeddings[0] ) return embeddings
def generate_latents( self, embeddings, prompt_latents, max_steps, cfg, sigma, temperature ): history = embeddings.new_zeros(1, self.history_patch_size, self.latent_dim) if prompt_latents is not None: tail = prompt_latents[:, -self.history_patch_size :] history[:, -tail.shape[1] :] = tail past = None latents = [] for step in range(max_steps): output = self.model( inputs_embeds=embeddings, past_key_values=past, use_cache=True ) past = output.past_key_values hidden = output.last_hidden_state[:, -1:] noise = torch.randn( (1, self.patch_size, self.latent_dim), device=self.device, dtype=self.dtype, ) timesteps = get_epss_timesteps(self.config.steps, self.device, self.dtype) sde_noise = torch.randn( (self.config.steps, *noise.shape), device=self.device, dtype=self.dtype ) latent = self.cfm.sample( hidden, history, noise, timesteps, hidden.new_tensor([cfg, sigma, temperature]), sde_noise, ) embeddings = self.aggregator(latent) latents.append(latent) history = torch.cat([history, latent], dim=1)[:, -self.history_patch_size :] stop = self.stop_head(hidden[:, -1]).softmax(dim=-1)[0, 1] if step > 3 and stop.item() > 0.5: break return torch.cat(latents, dim=1)
@torch.inference_mode() def synthesize( self, text, *, ip_name="灵小柔", reference=None, prompt_text=None, language=None, max_steps=1000, seed=None, cfg=2.0, sigma=0.25, temperature=0.0, ): context = ( torch.cuda.device(self.device) if self.device.type == "cuda" else nullcontext() ) with context, torch.autocast(device_type=self.device.type, dtype=self.dtype): if seed is not None: random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) text = re.sub(r"^[A-Za-z]{1,16}\t", "", text) task = "IP" if reference is None else "TTS" language, text = resolve_request_language( text, language=language, taskname=task ) prompt = append_optional_target_language(DEFAULT_TTS_PROMPT, language) instruction = ( build_task_instruction("IP", ip=ip_name) if reference is None else None ) skip_tn = preserve_multilingual_text(target_language_from_prompt(prompt)) speaker, prompt_latents, prompt_embeddings = ( self.reference_features(reference, prompt_text is not None) if reference is not None else (None, None, None) ) chunks = [] for fragment in self.text_fragments(text): protected = contains_paralinguistic_tag(fragment) fragment = ( protect_paralinguistic_tags(fragment) if protected else fragment ) if not skip_tn: if not is_chinese(fragment): fragment = normalize_numbers(fragment) fragment = normalize_text_kit( self.normalizer.normalize(fragment) ).lstrip(",") if protected: fragment = restore_paralinguistic_tags(fragment) embeddings = self.input_embeddings( fragment, prompt, instruction, speaker, prompt_text, prompt_embeddings, ) latents = self.generate_latents( embeddings, prompt_latents, max_steps, cfg, sigma, temperature ) waveform, _, _ = self.audio_vae.decode( latents, use_cache=False, last_chunk=True ) chunks.append( self.silence_holder( waveform.detach().float().cpu(), self.audio_vae.config.sample_rate, )[0] ) return { "audio": torch.cat(chunks, dim=-1), "sr": self.audio_vae.config.sample_rate, }
@staticmethod def silence_holder( speech, sample_rate, sil_cache=None, last_chunk=True, sil_th=1e-3, last_sil=0.3 ): if speech.numel() == 0: assert not last_chunk return speech, sil_cache
frame_step, frame_size = int(sample_rate * 0.1), int(sample_rate * 0.1) if sil_cache is None: sil_cache = {"holder": [], "buffer": []} if sil_cache["buffer"]: speech = torch.cat([*sil_cache["buffer"], speech], dim=-1) sil_cache["buffer"] = [] if speech.shape[-1] < frame_size: sil_cache["buffer"].append(speech) if last_chunk: speech = torch.cat(sil_cache["holder"] + sil_cache["buffer"], dim=-1) return speech[..., : int(last_sil * sample_rate)], sil_cache return torch.zeros( (*speech.shape[:-1], 0), device=speech.device, dtype=speech.dtype ), sil_cache
num_frame = (speech.shape[-1] - frame_size) // frame_step + 1 cur_len = (num_frame - 1) * frame_step + frame_size if speech.shape[-1] > cur_len: sil_cache["buffer"].append(speech[..., cur_len:]) speech = speech[..., :cur_len] spe_frames = speech.unfold(-1, frame_size, frame_step) scores = spe_frames.abs().mean(dim=-1) scores = scores.mean(dim=list(range(scores.dim() - 1))) idx = scores.shape[0] - 1 while idx >= 0: if scores[idx] > sil_th: break idx -= 1 if idx < 0: sil_cache["holder"].append(speech) if last_chunk: speech = torch.cat(sil_cache["holder"] + sil_cache["buffer"], dim=-1) return speech[..., : int(last_sil * sample_rate)], sil_cache return torch.zeros( (*speech.shape[:-1], 0), device=speech.device, dtype=speech.dtype ), sil_cache non_sil_len = idx * frame_step + frame_size if last_chunk: non_sil_len += int(last_sil * sample_rate) speech = torch.cat([*sil_cache["holder"], speech[..., :non_sil_len]], dim=-1) sil_cache["holder"] = [] if non_sil_len < speech.shape[-1]: sil_cache["holder"].append(speech[..., non_sil_len:]) return speech, sil_cache123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475{ "</answer>": 151691, "</audio>": 151707, "</body>": 151681, "</gen_audio>": 151710, "</gen_image>": 151701, "</html>": 151679, "</image>": 151696, "</prompt>": 151672, "</table>": 151683, "</td>": 151687, "</think>": 151689, "</thinker_prefix>": 151674, "</tool_call>": 151658, "</tr>": 151685, "</video>": 151698, "</vp>": 151676, "<answer>": 151690, "<asr>": 151714, "<audio>": 151706, "<audioHere>": 151711, "<audioPatch>": 151705, "<audio_bos>": 151665, "<audio_eos>": 151666, "<audio_pad>": 151667, "<body>": 151680, "<end_of_audio>": 151704, "<end_of_chunk>": 151703, "<framePatch>": 151712, "<gen_audio>": 151709, "<gen_audioPatch>": 151708, "<gen_image>": 151700, "<gen_imagePatch>": 151699, "<html>": 151678, "<image>": 151695, "<imageHere>": 151702, "<imagePatch>": 151694, "<prompt>": 151671, "<table>": 151682, "<td>": 151686, "<text>": 151713, "<text_bos>": 151668, "<text_eos>": 151669, "<text_pad>": 151670, "<think>": 151688, "<thinker_prefix>": 151673, "<tool_call>": 151657, "<tr>": 151684, "<tts>": 151715, "<video>": 151697, "<vp>": 151675, "<|box_end|>": 151649, "<|box_start|>": 151648, "<|endoftext|>": 151643, "<|file_sep|>": 151664, "<|fim_middle|>": 151660, "<|fim_pad|>": 151662, "<|fim_prefix|>": 151659, "<|fim_suffix|>": 151661, "<|im_end|>": 151645, "<|im_start|>": 151644, "<|image_pad|>": 151655, "<|object_ref_end|>": 151647, "<|object_ref_start|>": 151646, "<|quad_end|>": 151651, "<|quad_start|>": 151650, "<|repo_name|>": 151663, "<|startoftext|>": 151692, "<|video_pad|>": 151656, "<|vision_end|>": 151653, "<|vision_pad|>": 151654, "<|vision_start|>": 151652, "[gMASK]": 151693, "[item]": 151677}123456789101112131415161718192021222324252627{ "architectures": [ "Qwen2ForCausalLM" ], "attention_dropout": 0.0, "bos_token_id": 151643, "eos_token_id": 151645, "hidden_act": "silu", "hidden_size": 896, "initializer_range": 0.02, "intermediate_size": 4864, "max_position_embeddings": 32768, "max_window_layers": 21, "model_type": "qwen2", "num_attention_heads": 14, "num_hidden_layers": 24, "num_key_value_heads": 2, "rms_norm_eps": 1e-06, "rope_theta": 1000000.0, "sliding_window": 32768, "tie_word_embeddings": true, "torch_dtype": "bfloat16", "transformers_version": "4.43.1", "use_cache": true, "use_sliding_window": false, "vocab_size": 151936}1234567891011121314{ "bos_token_id": 151643, "pad_token_id": 151643, "do_sample": true, "eos_token_id": [ 151645, 151643 ], "repetition_penalty": 1.1, "temperature": 0.7, "top_p": 0.8, "top_k": 20, "transformers_version": "4.37.0"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137{ "additional_special_tokens": [ { "content": "[item]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, { "content": "<html>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, { "content": "</html>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, { "content": "<body>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, { "content": "</body>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, { "content": "<table>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, { "content": "</table>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, { "content": "<tr>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, { "content": "</tr>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, { "content": "<td>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, { "content": "</td>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, { "content": "<think>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, { "content": "</think>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, { "content": "<answer>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, { "content": "</answer>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, { "content": "<|startoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, { "content": "[gMASK]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false } ], "eos_token": { "content": "<|im_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "pad_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }}.gitattributes+17-35
README.mdAdded+222
assets/benchmark-asr.pngAdded

Large File Pointer Details
- SHA256: f7558ab421fac9bf78cdc1604762221fc644e63e8ceecf5d43c9c08c17c716da
- Pointer size: 131 Bytes
- Size of remote file: 805 kB
assets/benchmark-audio-intelligence.pngAdded

Large File Pointer Details
- SHA256: 117e41cc2618d09351e510b182f935260d36aab2ef6aa2797454a8d278e8983c
- Pointer size: 131 Bytes
- Size of remote file: 389 kB
assets/benchmark-text.pngAdded

Large File Pointer Details
- SHA256: 894062a82f841b18544cae3919acb95b87bc538222e6cb116f1fa26baded0773
- Pointer size: 131 Bytes
- Size of remote file: 177 kB
assets/github-invertocat-black-17.svgAdded
assets/ming-3.0-audio-logo.pngAdded

chat_template.jinjaAdded+165
config.jsonAdded+106
configuration_bailing_moe_v3.pyAdded+130
configuration_bailing_moe_v3_audio.pyAdded+226
generation_config.jsonAdded+7
model-00001-of-00002.safetensorsAdded+3
model-00002-of-00002.safetensorsAdded+3
model.safetensors.index.jsonAdded
modeling_bailing_moe_v3.pyAdded+1687
modeling_bailing_moe_v3_audio.pyAdded+334
processing_bailing_moe_v3_audio.pyAdded+120
processor_config.jsonAdded+6
special_tokens_map.jsonAdded+57
talker/AudioVAE/__init__.pyAdded
talker/AudioVAE/__pycache__/__init__.cpython-312.pycAdded
talker/AudioVAE/__pycache__/configuration_audio_vae.cpython-312.pycAdded
talker/AudioVAE/__pycache__/istft.cpython-312.pycAdded
talker/AudioVAE/__pycache__/modeling_audio_vae.cpython-312.pycAdded
talker/AudioVAE/__pycache__/vae_modules.cpython-312.pycAdded
talker/AudioVAE/configuration_audio_vae.pyAdded+19
talker/AudioVAE/istft.pyAdded+181
talker/AudioVAE/modeling_audio_vae.pyAdded+80
talker/AudioVAE/vae_modules.pyAdded+204
talker/__init__.pyAdded+5
talker/campplus.onnxAdded+3
talker/config.jsonAdded+35
talker/configuration_bailing_talker.pyAdded+20
talker/data/lid.176.LICENSE.mdAdded+10
talker/data/lid.176.ftzAdded+3
talker/front/__init__.pyAdded
talker/front/__pycache__/__init__.cpython-312.pycAdded
talker/front/__pycache__/number_en.cpython-312.pycAdded
talker/front/__pycache__/text_segment_cut.cpython-312.pycAdded
talker/front/__pycache__/toolkit.cpython-312.pycAdded
talker/front/number_en.pyAdded+343
talker/front/text_segment_cut.pyAdded+388
talker/front/toolkit.pyAdded+240
talker/inference.pyAdded+443
talker/llm/added_tokens.jsonAdded+75
talker/llm/config.jsonAdded+27
talker/llm/generation_config.jsonAdded+14
talker/llm/merges.txtAdded
talker/llm/special_tokens_map.jsonAdded+137