Add files using upload-large-folder tool
Browse files- README.md +34 -3
- __init__.py +3 -0
- bridge.pt +3 -0
- config.json +52 -0
- configuration_hga_thinker.py +94 -0
- lora/README.md +207 -0
- lora/adapter_config.json +48 -0
- lora/adapter_model.safetensors +3 -0
- merges.txt +0 -0
- modeling_hga_thinker.py +332 -0
- preprocessor_config.json +14 -0
- processor_config.json +6 -0
- thinker/__init__.py +1 -0
- thinker/config.py +157 -0
- thinker/emca.py +181 -0
- thinker/encoder.py +253 -0
- thinker/hyperbolic_ops.py +126 -0
- thinker/model.py +512 -0
- thinker/text_utils.py +109 -0
- tokenizer.json +0 -0
- tokenizer_config.json +207 -0
- vocab.json +0 -0
README.md
CHANGED
|
@@ -1,3 +1,34 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# HGA_Thinker_7B_v2_export
|
| 2 |
+
|
| 3 |
+
HGA-Thinker speech LM exported from SFT training (current train_sft.py format).
|
| 4 |
+
|
| 5 |
+
## Layout
|
| 6 |
+
- `bridge.pt` — HGA (s/b/c on 32 Whisper layers) + EMCA + audio boundary embeds
|
| 7 |
+
- `lora/` — PEFT LoRA adapter for the LLM (has_lora=True)
|
| 8 |
+
- `config.json` — HGAThinkerConfig (llm_dim=3584)
|
| 9 |
+
- `processor_config.json` — inference defaults
|
| 10 |
+
- `tokenizer.*` — Qwen2.5 tokenizer
|
| 11 |
+
- `preprocessor_config.json` — WhisperFeatureExtractor config
|
| 12 |
+
- `configuration_hga_thinker.py`, `modeling_hga_thinker.py`, `thinker/` —
|
| 13 |
+
frozen inference code (so this dir loads without the training repo)
|
| 14 |
+
|
| 15 |
+
## Base models
|
| 16 |
+
- whisper: `/apdcephfs_hzlf/share_1227201/zefeng/whisper-large-v3`
|
| 17 |
+
- llm: `/apdcephfs_hzlf/share_1227201/zefeng/Qwen2.5-7B-Instruct`
|
| 18 |
+
- bundled: `False` trained_steps: `6000`
|
| 19 |
+
|
| 20 |
+
## Load & run
|
| 21 |
+
```python
|
| 22 |
+
import sys; sys.path.insert(0, ".") # this dir
|
| 23 |
+
from modeling_hga_thinker import HGAThinkerForConditionalGeneration
|
| 24 |
+
|
| 25 |
+
model = HGAThinkerForConditionalGeneration.from_pretrained(".", device="cuda")
|
| 26 |
+
# If base models moved since export, pass overrides:
|
| 27 |
+
# ...from_pretrained(".", whisper_path="/new/whisper", llm_name="/new/qwen")
|
| 28 |
+
|
| 29 |
+
text = model.chat(audio="test.wav", query="Transcribe this audio.",
|
| 30 |
+
max_new_tokens=256)
|
| 31 |
+
print(text)
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
Needs `peft` and (for audio path inputs) `torchaudio` installed.
|
__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .configuration_hga_thinker import HGAThinkerConfig
|
| 2 |
+
from .modeling_hga_thinker import (
|
| 3 |
+
HGAThinkerForConditionalGeneration, HGAThinkerProcessor)
|
bridge.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ab2261431e599ce92a84d55d457de9595621955acd9c42415e851494f2d9b29d
|
| 3 |
+
size 201880717
|
config.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"assistant_prefix": "<|im_start|>assistant\n",
|
| 3 |
+
"bundled": false,
|
| 4 |
+
"dtype": "bfloat16",
|
| 5 |
+
"emca_c_work_init": 0.5,
|
| 6 |
+
"emca_c_work_max": 4.0,
|
| 7 |
+
"emca_c_work_min": 0.01,
|
| 8 |
+
"encoder_dim": 1280,
|
| 9 |
+
"extract_layers": [
|
| 10 |
+
3,
|
| 11 |
+
7,
|
| 12 |
+
11,
|
| 13 |
+
15,
|
| 14 |
+
19,
|
| 15 |
+
23,
|
| 16 |
+
27,
|
| 17 |
+
31
|
| 18 |
+
],
|
| 19 |
+
"freeze_llm": true,
|
| 20 |
+
"has_lora": true,
|
| 21 |
+
"hga_b_init_std": 0.0001,
|
| 22 |
+
"hga_c_init": 1.0,
|
| 23 |
+
"hga_c_max": 8.0,
|
| 24 |
+
"hga_c_min": 0.001,
|
| 25 |
+
"llm_dim": 3584,
|
| 26 |
+
"llm_name": "/apdcephfs_hzlf/share_1227201/zefeng/Qwen2.5-7B-Instruct",
|
| 27 |
+
"lora": {
|
| 28 |
+
"bias": "none",
|
| 29 |
+
"lora_alpha": 64,
|
| 30 |
+
"lora_dropout": 0.05,
|
| 31 |
+
"r": 32,
|
| 32 |
+
"target_modules": [
|
| 33 |
+
"k_proj",
|
| 34 |
+
"v_proj",
|
| 35 |
+
"up_proj",
|
| 36 |
+
"o_proj",
|
| 37 |
+
"down_proj",
|
| 38 |
+
"q_proj",
|
| 39 |
+
"gate_proj"
|
| 40 |
+
]
|
| 41 |
+
},
|
| 42 |
+
"max_audio_length": 30.0,
|
| 43 |
+
"model_type": "hga_thinker",
|
| 44 |
+
"num_whisper_layers": 32,
|
| 45 |
+
"projector_hidden": 4096,
|
| 46 |
+
"sample_rate": 16000,
|
| 47 |
+
"system_prompt": "You are a helpful assistant that analyzes audio content.",
|
| 48 |
+
"target_frame_rate_hz": 12.5,
|
| 49 |
+
"trained_steps": 6000,
|
| 50 |
+
"transformers_version": "4.57.0",
|
| 51 |
+
"whisper_path": "/apdcephfs_hzlf/share_1227201/zefeng/whisper-large-v3"
|
| 52 |
+
}
|
configuration_hga_thinker.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
HGA-Thinker HuggingFace-style configuration.
|
| 3 |
+
|
| 4 |
+
This mirrors the architecture-relevant fields of `thinker.config.ThinkerConfig`
|
| 5 |
+
so that an exported model directory can be reconstructed identically to how it
|
| 6 |
+
was assembled at training time.
|
| 7 |
+
|
| 8 |
+
Only the fields needed to *rebuild the model graph and load weights* are kept
|
| 9 |
+
here — training-only knobs (learning rates, dataset paths, eval cadence, …)
|
| 10 |
+
are intentionally dropped, since they have no bearing on inference.
|
| 11 |
+
|
| 12 |
+
The values below default to the current training configuration
|
| 13 |
+
(Qwen2.5-7B-Instruct + whisper-large-v3, 32 Whisper layers, llm_dim=3584).
|
| 14 |
+
`export.py` overwrites the path/flag fields from the actual checkpoint, so you
|
| 15 |
+
normally never edit this by hand.
|
| 16 |
+
"""
|
| 17 |
+
from transformers import PretrainedConfig
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class HGAThinkerConfig(PretrainedConfig):
|
| 21 |
+
model_type = "hga_thinker"
|
| 22 |
+
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
# ---- Whisper encoder ----
|
| 26 |
+
whisper_path: str = "openai/whisper-large-v3",
|
| 27 |
+
encoder_dim: int = 1280,
|
| 28 |
+
num_whisper_layers: int = 32,
|
| 29 |
+
extract_layers=None, # default [3,7,11,15,19,23,27,31]
|
| 30 |
+
target_frame_rate_hz: float = 12.5,
|
| 31 |
+
# ---- HGA (per-layer Q/K/V modulation) ----
|
| 32 |
+
hga_c_init: float = 1.0,
|
| 33 |
+
hga_c_min: float = 0.001,
|
| 34 |
+
hga_c_max: float = 8.0,
|
| 35 |
+
hga_b_init_std: float = 1.0e-4,
|
| 36 |
+
# ---- EMCA ----
|
| 37 |
+
emca_c_work_init: float = 0.5,
|
| 38 |
+
emca_c_work_min: float = 0.01,
|
| 39 |
+
emca_c_work_max: float = 4.0,
|
| 40 |
+
projector_hidden: int = 4096,
|
| 41 |
+
# ---- LLM ----
|
| 42 |
+
llm_name: str = "Qwen/Qwen2.5-7B-Instruct",
|
| 43 |
+
llm_dim: int = 3584,
|
| 44 |
+
freeze_llm: bool = True,
|
| 45 |
+
# ---- LoRA (SFT) ----
|
| 46 |
+
lora: dict = None,
|
| 47 |
+
has_lora: bool = False,
|
| 48 |
+
# ---- Inference defaults ----
|
| 49 |
+
system_prompt: str = "You are a helpful assistant that analyzes audio content.",
|
| 50 |
+
assistant_prefix: str = "<|im_start|>assistant\n",
|
| 51 |
+
sample_rate: int = 16000,
|
| 52 |
+
max_audio_length: float = 30.0,
|
| 53 |
+
torch_dtype: str = "bfloat16",
|
| 54 |
+
# ---- Layout / provenance ----
|
| 55 |
+
bundled: bool = False, # True if whisper/ or llm/ copied into dir
|
| 56 |
+
trained_steps: int = -1,
|
| 57 |
+
**kwargs,
|
| 58 |
+
):
|
| 59 |
+
self.whisper_path = whisper_path
|
| 60 |
+
self.encoder_dim = encoder_dim
|
| 61 |
+
self.num_whisper_layers = num_whisper_layers
|
| 62 |
+
self.extract_layers = (
|
| 63 |
+
list(extract_layers) if extract_layers is not None
|
| 64 |
+
else [3, 7, 11, 15, 19, 23, 27, 31]
|
| 65 |
+
)
|
| 66 |
+
self.target_frame_rate_hz = target_frame_rate_hz
|
| 67 |
+
|
| 68 |
+
self.hga_c_init = hga_c_init
|
| 69 |
+
self.hga_c_min = hga_c_min
|
| 70 |
+
self.hga_c_max = hga_c_max
|
| 71 |
+
self.hga_b_init_std = hga_b_init_std
|
| 72 |
+
|
| 73 |
+
self.emca_c_work_init = emca_c_work_init
|
| 74 |
+
self.emca_c_work_min = emca_c_work_min
|
| 75 |
+
self.emca_c_work_max = emca_c_work_max
|
| 76 |
+
self.projector_hidden = projector_hidden
|
| 77 |
+
|
| 78 |
+
self.llm_name = llm_name
|
| 79 |
+
self.llm_dim = llm_dim
|
| 80 |
+
self.freeze_llm = freeze_llm
|
| 81 |
+
|
| 82 |
+
self.lora = lora
|
| 83 |
+
self.has_lora = has_lora
|
| 84 |
+
|
| 85 |
+
self.system_prompt = system_prompt
|
| 86 |
+
self.assistant_prefix = assistant_prefix
|
| 87 |
+
self.sample_rate = sample_rate
|
| 88 |
+
self.max_audio_length = max_audio_length
|
| 89 |
+
|
| 90 |
+
self.bundled = bundled
|
| 91 |
+
self.trained_steps = trained_steps
|
| 92 |
+
|
| 93 |
+
# PretrainedConfig handles torch_dtype specially; pass through kwargs.
|
| 94 |
+
super().__init__(torch_dtype=torch_dtype, **kwargs)
|
lora/README.md
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
base_model: /apdcephfs_hzlf/share_1227201/zefeng/Qwen2.5-7B-Instruct
|
| 3 |
+
library_name: peft
|
| 4 |
+
pipeline_tag: text-generation
|
| 5 |
+
tags:
|
| 6 |
+
- base_model:adapter:/apdcephfs_hzlf/share_1227201/zefeng/Qwen2.5-7B-Instruct
|
| 7 |
+
- lora
|
| 8 |
+
- transformers
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
# Model Card for Model ID
|
| 12 |
+
|
| 13 |
+
<!-- Provide a quick summary of what the model is/does. -->
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
## Model Details
|
| 18 |
+
|
| 19 |
+
### Model Description
|
| 20 |
+
|
| 21 |
+
<!-- Provide a longer summary of what this model is. -->
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
- **Developed by:** [More Information Needed]
|
| 26 |
+
- **Funded by [optional]:** [More Information Needed]
|
| 27 |
+
- **Shared by [optional]:** [More Information Needed]
|
| 28 |
+
- **Model type:** [More Information Needed]
|
| 29 |
+
- **Language(s) (NLP):** [More Information Needed]
|
| 30 |
+
- **License:** [More Information Needed]
|
| 31 |
+
- **Finetuned from model [optional]:** [More Information Needed]
|
| 32 |
+
|
| 33 |
+
### Model Sources [optional]
|
| 34 |
+
|
| 35 |
+
<!-- Provide the basic links for the model. -->
|
| 36 |
+
|
| 37 |
+
- **Repository:** [More Information Needed]
|
| 38 |
+
- **Paper [optional]:** [More Information Needed]
|
| 39 |
+
- **Demo [optional]:** [More Information Needed]
|
| 40 |
+
|
| 41 |
+
## Uses
|
| 42 |
+
|
| 43 |
+
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
|
| 44 |
+
|
| 45 |
+
### Direct Use
|
| 46 |
+
|
| 47 |
+
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
|
| 48 |
+
|
| 49 |
+
[More Information Needed]
|
| 50 |
+
|
| 51 |
+
### Downstream Use [optional]
|
| 52 |
+
|
| 53 |
+
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
|
| 54 |
+
|
| 55 |
+
[More Information Needed]
|
| 56 |
+
|
| 57 |
+
### Out-of-Scope Use
|
| 58 |
+
|
| 59 |
+
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
|
| 60 |
+
|
| 61 |
+
[More Information Needed]
|
| 62 |
+
|
| 63 |
+
## Bias, Risks, and Limitations
|
| 64 |
+
|
| 65 |
+
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
|
| 66 |
+
|
| 67 |
+
[More Information Needed]
|
| 68 |
+
|
| 69 |
+
### Recommendations
|
| 70 |
+
|
| 71 |
+
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
|
| 72 |
+
|
| 73 |
+
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
|
| 74 |
+
|
| 75 |
+
## How to Get Started with the Model
|
| 76 |
+
|
| 77 |
+
Use the code below to get started with the model.
|
| 78 |
+
|
| 79 |
+
[More Information Needed]
|
| 80 |
+
|
| 81 |
+
## Training Details
|
| 82 |
+
|
| 83 |
+
### Training Data
|
| 84 |
+
|
| 85 |
+
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
|
| 86 |
+
|
| 87 |
+
[More Information Needed]
|
| 88 |
+
|
| 89 |
+
### Training Procedure
|
| 90 |
+
|
| 91 |
+
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
| 92 |
+
|
| 93 |
+
#### Preprocessing [optional]
|
| 94 |
+
|
| 95 |
+
[More Information Needed]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
#### Training Hyperparameters
|
| 99 |
+
|
| 100 |
+
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
|
| 101 |
+
|
| 102 |
+
#### Speeds, Sizes, Times [optional]
|
| 103 |
+
|
| 104 |
+
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
|
| 105 |
+
|
| 106 |
+
[More Information Needed]
|
| 107 |
+
|
| 108 |
+
## Evaluation
|
| 109 |
+
|
| 110 |
+
<!-- This section describes the evaluation protocols and provides the results. -->
|
| 111 |
+
|
| 112 |
+
### Testing Data, Factors & Metrics
|
| 113 |
+
|
| 114 |
+
#### Testing Data
|
| 115 |
+
|
| 116 |
+
<!-- This should link to a Dataset Card if possible. -->
|
| 117 |
+
|
| 118 |
+
[More Information Needed]
|
| 119 |
+
|
| 120 |
+
#### Factors
|
| 121 |
+
|
| 122 |
+
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
|
| 123 |
+
|
| 124 |
+
[More Information Needed]
|
| 125 |
+
|
| 126 |
+
#### Metrics
|
| 127 |
+
|
| 128 |
+
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
|
| 129 |
+
|
| 130 |
+
[More Information Needed]
|
| 131 |
+
|
| 132 |
+
### Results
|
| 133 |
+
|
| 134 |
+
[More Information Needed]
|
| 135 |
+
|
| 136 |
+
#### Summary
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
## Model Examination [optional]
|
| 141 |
+
|
| 142 |
+
<!-- Relevant interpretability work for the model goes here -->
|
| 143 |
+
|
| 144 |
+
[More Information Needed]
|
| 145 |
+
|
| 146 |
+
## Environmental Impact
|
| 147 |
+
|
| 148 |
+
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
|
| 149 |
+
|
| 150 |
+
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
|
| 151 |
+
|
| 152 |
+
- **Hardware Type:** [More Information Needed]
|
| 153 |
+
- **Hours used:** [More Information Needed]
|
| 154 |
+
- **Cloud Provider:** [More Information Needed]
|
| 155 |
+
- **Compute Region:** [More Information Needed]
|
| 156 |
+
- **Carbon Emitted:** [More Information Needed]
|
| 157 |
+
|
| 158 |
+
## Technical Specifications [optional]
|
| 159 |
+
|
| 160 |
+
### Model Architecture and Objective
|
| 161 |
+
|
| 162 |
+
[More Information Needed]
|
| 163 |
+
|
| 164 |
+
### Compute Infrastructure
|
| 165 |
+
|
| 166 |
+
[More Information Needed]
|
| 167 |
+
|
| 168 |
+
#### Hardware
|
| 169 |
+
|
| 170 |
+
[More Information Needed]
|
| 171 |
+
|
| 172 |
+
#### Software
|
| 173 |
+
|
| 174 |
+
[More Information Needed]
|
| 175 |
+
|
| 176 |
+
## Citation [optional]
|
| 177 |
+
|
| 178 |
+
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
| 179 |
+
|
| 180 |
+
**BibTeX:**
|
| 181 |
+
|
| 182 |
+
[More Information Needed]
|
| 183 |
+
|
| 184 |
+
**APA:**
|
| 185 |
+
|
| 186 |
+
[More Information Needed]
|
| 187 |
+
|
| 188 |
+
## Glossary [optional]
|
| 189 |
+
|
| 190 |
+
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
|
| 191 |
+
|
| 192 |
+
[More Information Needed]
|
| 193 |
+
|
| 194 |
+
## More Information [optional]
|
| 195 |
+
|
| 196 |
+
[More Information Needed]
|
| 197 |
+
|
| 198 |
+
## Model Card Authors [optional]
|
| 199 |
+
|
| 200 |
+
[More Information Needed]
|
| 201 |
+
|
| 202 |
+
## Model Card Contact
|
| 203 |
+
|
| 204 |
+
[More Information Needed]
|
| 205 |
+
### Framework versions
|
| 206 |
+
|
| 207 |
+
- PEFT 0.19.1
|
lora/adapter_config.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"alora_invocation_tokens": null,
|
| 3 |
+
"alpha_pattern": {},
|
| 4 |
+
"arrow_config": null,
|
| 5 |
+
"auto_mapping": null,
|
| 6 |
+
"base_model_name_or_path": "/apdcephfs_hzlf/share_1227201/zefeng/Qwen2.5-7B-Instruct",
|
| 7 |
+
"bias": "none",
|
| 8 |
+
"corda_config": null,
|
| 9 |
+
"ensure_weight_tying": false,
|
| 10 |
+
"eva_config": null,
|
| 11 |
+
"exclude_modules": null,
|
| 12 |
+
"fan_in_fan_out": false,
|
| 13 |
+
"inference_mode": true,
|
| 14 |
+
"init_lora_weights": true,
|
| 15 |
+
"layer_replication": null,
|
| 16 |
+
"layers_pattern": null,
|
| 17 |
+
"layers_to_transform": null,
|
| 18 |
+
"loftq_config": {},
|
| 19 |
+
"lora_alpha": 64,
|
| 20 |
+
"lora_bias": false,
|
| 21 |
+
"lora_dropout": 0.05,
|
| 22 |
+
"lora_ga_config": null,
|
| 23 |
+
"megatron_config": null,
|
| 24 |
+
"megatron_core": "megatron.core",
|
| 25 |
+
"modules_to_save": null,
|
| 26 |
+
"peft_type": "LORA",
|
| 27 |
+
"peft_version": "0.19.1",
|
| 28 |
+
"qalora_group_size": 16,
|
| 29 |
+
"r": 32,
|
| 30 |
+
"rank_pattern": {},
|
| 31 |
+
"revision": null,
|
| 32 |
+
"target_modules": [
|
| 33 |
+
"k_proj",
|
| 34 |
+
"v_proj",
|
| 35 |
+
"up_proj",
|
| 36 |
+
"o_proj",
|
| 37 |
+
"down_proj",
|
| 38 |
+
"q_proj",
|
| 39 |
+
"gate_proj"
|
| 40 |
+
],
|
| 41 |
+
"target_parameters": null,
|
| 42 |
+
"task_type": "CAUSAL_LM",
|
| 43 |
+
"trainable_token_indices": null,
|
| 44 |
+
"use_bdlora": null,
|
| 45 |
+
"use_dora": false,
|
| 46 |
+
"use_qalora": false,
|
| 47 |
+
"use_rslora": false
|
| 48 |
+
}
|
lora/adapter_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:76d408900d3ecd1eadaf148993f5671108db1a8d4f2b1e983d95d992dfdcd8fa
|
| 3 |
+
size 161533584
|
merges.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
modeling_hga_thinker.py
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
HGA-Thinker HuggingFace-loadable wrapper.
|
| 3 |
+
|
| 4 |
+
This is a *thin* wrapper around the training-time `thinker.model.ThinkerModel`.
|
| 5 |
+
It does NOT reimplement the architecture — it imports the exact same modules
|
| 6 |
+
used during training, so the inference graph is byte-for-byte identical to what
|
| 7 |
+
produced the checkpoint.
|
| 8 |
+
|
| 9 |
+
Assembly order (mirrors thinker/train_sft.py main()):
|
| 10 |
+
1. ThinkerModel(thinker_config) # builds encoder(HGA) + EMCA
|
| 11 |
+
2. AutoModelForCausalLM.from_pretrained(llm) # bf16, trust_remote_code
|
| 12 |
+
model.load_llm(llm) # freeze base
|
| 13 |
+
3. load bridge.pt → hga_layers / emca / audio_start_embed / audio_end_embed
|
| 14 |
+
4. model.setup_lora(lora_cfg) # wrap LLM as PeftModel
|
| 15 |
+
5. PeftModel.load_adapter(lora/) # load trained adapter weights
|
| 16 |
+
|
| 17 |
+
Step order matters: LoRA must be set up *after* bridge.pt is loaded (HGA/EMCA
|
| 18 |
+
are not LoRA-wrapped) and the adapter must be loaded into the already-LoRA-fied
|
| 19 |
+
LLM, exactly as training did.
|
| 20 |
+
"""
|
| 21 |
+
import os
|
| 22 |
+
import json
|
| 23 |
+
import logging
|
| 24 |
+
from typing import Optional, List, Union
|
| 25 |
+
|
| 26 |
+
import torch
|
| 27 |
+
import torch.nn as nn
|
| 28 |
+
|
| 29 |
+
from transformers import (
|
| 30 |
+
PreTrainedModel,
|
| 31 |
+
AutoModelForCausalLM,
|
| 32 |
+
AutoTokenizer,
|
| 33 |
+
WhisperFeatureExtractor,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
from .configuration_hga_thinker import HGAThinkerConfig
|
| 37 |
+
|
| 38 |
+
logger = logging.getLogger(__name__)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _bridge_config_from_hf(hf_cfg: HGAThinkerConfig, *, whisper_path, llm_name):
|
| 42 |
+
"""Build a `thinker.config.ThinkerConfig` from the HF config.
|
| 43 |
+
|
| 44 |
+
Only the architecture fields ThinkerModel reads in __init__ are needed.
|
| 45 |
+
Path fields are resolved by the caller (may be bundled sub-dirs).
|
| 46 |
+
"""
|
| 47 |
+
from thinker.config import ThinkerConfig
|
| 48 |
+
return ThinkerConfig(
|
| 49 |
+
whisper_path=whisper_path,
|
| 50 |
+
encoder_dim=hf_cfg.encoder_dim,
|
| 51 |
+
num_whisper_layers=hf_cfg.num_whisper_layers,
|
| 52 |
+
extract_layers=list(hf_cfg.extract_layers),
|
| 53 |
+
target_frame_rate_hz=hf_cfg.target_frame_rate_hz,
|
| 54 |
+
hga_c_init=hf_cfg.hga_c_init,
|
| 55 |
+
hga_c_min=hf_cfg.hga_c_min,
|
| 56 |
+
hga_c_max=hf_cfg.hga_c_max,
|
| 57 |
+
hga_b_init_std=hf_cfg.hga_b_init_std,
|
| 58 |
+
emca_c_work_init=hf_cfg.emca_c_work_init,
|
| 59 |
+
emca_c_work_min=hf_cfg.emca_c_work_min,
|
| 60 |
+
emca_c_work_max=hf_cfg.emca_c_work_max,
|
| 61 |
+
projector_hidden=hf_cfg.projector_hidden,
|
| 62 |
+
llm_name=llm_name,
|
| 63 |
+
llm_dim=hf_cfg.llm_dim,
|
| 64 |
+
freeze_llm=hf_cfg.freeze_llm,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class HGAThinkerForConditionalGeneration(PreTrainedModel):
|
| 69 |
+
"""Standalone, from_pretrained-able HGA-Thinker speech LM."""
|
| 70 |
+
|
| 71 |
+
config_class = HGAThinkerConfig
|
| 72 |
+
base_model_prefix = "hga_thinker"
|
| 73 |
+
|
| 74 |
+
def __init__(self, config: HGAThinkerConfig):
|
| 75 |
+
super().__init__(config)
|
| 76 |
+
# The real model is built in from_pretrained (needs external weights).
|
| 77 |
+
# Direct __init__ is only used by HF internals; we build a stub.
|
| 78 |
+
self.thinker = None
|
| 79 |
+
self._tokenizer = None
|
| 80 |
+
self._feature_extractor = None
|
| 81 |
+
|
| 82 |
+
# ------------------------------------------------------------------
|
| 83 |
+
# Loading
|
| 84 |
+
# ------------------------------------------------------------------
|
| 85 |
+
@classmethod
|
| 86 |
+
def from_pretrained(cls, model_dir: str, *,
|
| 87 |
+
device: Optional[str] = None,
|
| 88 |
+
torch_dtype: Optional[torch.dtype] = None,
|
| 89 |
+
whisper_path: Optional[str] = None,
|
| 90 |
+
llm_name: Optional[str] = None,
|
| 91 |
+
**kwargs) -> "HGAThinkerForConditionalGeneration":
|
| 92 |
+
"""Load an exported HGA-Thinker directory.
|
| 93 |
+
|
| 94 |
+
Args:
|
| 95 |
+
model_dir: directory produced by export.py.
|
| 96 |
+
device: e.g. "cuda" / "cuda:0" / "cpu". Default: cuda if available.
|
| 97 |
+
torch_dtype: override config dtype.
|
| 98 |
+
whisper_path / llm_name: override the paths recorded in config
|
| 99 |
+
(useful if the base models moved since export).
|
| 100 |
+
"""
|
| 101 |
+
hf_cfg = HGAThinkerConfig.from_pretrained(model_dir)
|
| 102 |
+
|
| 103 |
+
# ---- resolve dtype ----
|
| 104 |
+
if torch_dtype is None:
|
| 105 |
+
dtype_str = getattr(hf_cfg, "torch_dtype", "bfloat16")
|
| 106 |
+
if isinstance(dtype_str, torch.dtype):
|
| 107 |
+
torch_dtype = dtype_str
|
| 108 |
+
else:
|
| 109 |
+
torch_dtype = {
|
| 110 |
+
"bfloat16": torch.bfloat16,
|
| 111 |
+
"float16": torch.float16,
|
| 112 |
+
"float32": torch.float32,
|
| 113 |
+
}.get(str(dtype_str), torch.bfloat16)
|
| 114 |
+
|
| 115 |
+
if device is None:
|
| 116 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 117 |
+
|
| 118 |
+
# ---- resolve base-model paths (bundled vs referenced) ----
|
| 119 |
+
def _resolve(sub, cfg_val, override):
|
| 120 |
+
if override is not None:
|
| 121 |
+
return override
|
| 122 |
+
cand = os.path.join(model_dir, sub)
|
| 123 |
+
if os.path.isdir(cand): # bundled
|
| 124 |
+
return cand
|
| 125 |
+
return cfg_val # external reference
|
| 126 |
+
|
| 127 |
+
wh_path = _resolve("whisper", hf_cfg.whisper_path, whisper_path)
|
| 128 |
+
# Whisper "path" may be just a preprocessor ref; encoder needs the full
|
| 129 |
+
# model. If only preprocessor_config.json was copied, fall back to the
|
| 130 |
+
# recorded path / override.
|
| 131 |
+
if not (os.path.isdir(wh_path) and
|
| 132 |
+
os.path.isfile(os.path.join(wh_path, "config.json"))):
|
| 133 |
+
wh_path = whisper_path or hf_cfg.whisper_path
|
| 134 |
+
llm_path = _resolve("llm", hf_cfg.llm_name, llm_name)
|
| 135 |
+
|
| 136 |
+
# ---- 1. Build ThinkerModel (encoder + EMCA) ----
|
| 137 |
+
thinker_cfg = _bridge_config_from_hf(
|
| 138 |
+
hf_cfg, whisper_path=wh_path, llm_name=llm_path)
|
| 139 |
+
from thinker.model import ThinkerModel
|
| 140 |
+
thinker = ThinkerModel(thinker_cfg)
|
| 141 |
+
|
| 142 |
+
# ---- 2. Load + attach LLM ----
|
| 143 |
+
logger.info(f"[load] LLM from {llm_path} ({torch_dtype})")
|
| 144 |
+
llm = AutoModelForCausalLM.from_pretrained(
|
| 145 |
+
llm_path, torch_dtype=torch_dtype, trust_remote_code=True)
|
| 146 |
+
thinker.load_llm(llm)
|
| 147 |
+
|
| 148 |
+
# ---- 3. Load bridge.pt (HGA + EMCA + boundary embeds) ----
|
| 149 |
+
bridge_path = os.path.join(model_dir, "bridge.pt")
|
| 150 |
+
if not os.path.isfile(bridge_path):
|
| 151 |
+
raise FileNotFoundError(f"bridge.pt not found in {model_dir}")
|
| 152 |
+
state = torch.load(bridge_path, map_location="cpu", weights_only=False)
|
| 153 |
+
m1, _ = thinker.encoder.hga_layers.load_state_dict(
|
| 154 |
+
state["hga_layers"], strict=False)
|
| 155 |
+
m2, _ = thinker.emca.load_state_dict(state["emca"], strict=False)
|
| 156 |
+
if m1 or m2:
|
| 157 |
+
logger.warning(f"[load] missing keys hga={m1} emca={m2}")
|
| 158 |
+
if "audio_start_embed" in state:
|
| 159 |
+
thinker.audio_start_embed.data.copy_(state["audio_start_embed"])
|
| 160 |
+
thinker.audio_end_embed.data.copy_(state["audio_end_embed"])
|
| 161 |
+
logger.info("[load] bridge.pt loaded (HGA + EMCA + boundary embeds)")
|
| 162 |
+
|
| 163 |
+
# ---- 4 & 5. LoRA: load the trained adapter ----
|
| 164 |
+
# We use PeftModel.from_pretrained rather than setup_lora() +
|
| 165 |
+
# manual state_dict load. Reasons:
|
| 166 |
+
# * It reads lora/adapter_config.json and rebuilds the adapter
|
| 167 |
+
# structure exactly as it was saved (r, alpha, target_modules,
|
| 168 |
+
# inference_mode, peft_version-specific fields), so the export is
|
| 169 |
+
# robust to PEFT-version drift between training and inference.
|
| 170 |
+
# * It is the canonical PEFT load path, handling key remapping and
|
| 171 |
+
# inference_mode=True automatically.
|
| 172 |
+
# This attaches the adapter onto the frozen base LLM that load_llm()
|
| 173 |
+
# already set on thinker.llm — matching training, where LoRA also wraps
|
| 174 |
+
# the same base LLM (the only difference being PeftModel.from_pretrained
|
| 175 |
+
# vs get_peft_model, which produce equivalent inference graphs).
|
| 176 |
+
if hf_cfg.has_lora:
|
| 177 |
+
lora_dir = os.path.join(model_dir, "lora")
|
| 178 |
+
if not (os.path.isdir(lora_dir) and os.path.isfile(
|
| 179 |
+
os.path.join(lora_dir, "adapter_config.json"))):
|
| 180 |
+
raise FileNotFoundError(
|
| 181 |
+
f"config says has_lora=True but no valid lora/ in {model_dir}")
|
| 182 |
+
from peft import PeftModel
|
| 183 |
+
thinker.llm = PeftModel.from_pretrained(
|
| 184 |
+
thinker.llm, lora_dir, is_trainable=False)
|
| 185 |
+
logger.info("[load] LoRA adapter loaded via PeftModel.from_pretrained")
|
| 186 |
+
|
| 187 |
+
# ---- finalize ----
|
| 188 |
+
thinker.to(device=device, dtype=torch_dtype)
|
| 189 |
+
thinker.eval()
|
| 190 |
+
|
| 191 |
+
self = cls(hf_cfg)
|
| 192 |
+
self.thinker = thinker
|
| 193 |
+
self._device = device
|
| 194 |
+
self._dtype = torch_dtype
|
| 195 |
+
|
| 196 |
+
# processor pieces
|
| 197 |
+
self._tokenizer = AutoTokenizer.from_pretrained(model_dir)
|
| 198 |
+
self._feature_extractor = WhisperFeatureExtractor.from_pretrained(wh_path)
|
| 199 |
+
return self
|
| 200 |
+
|
| 201 |
+
# ------------------------------------------------------------------
|
| 202 |
+
# Inference
|
| 203 |
+
# ------------------------------------------------------------------
|
| 204 |
+
@torch.no_grad()
|
| 205 |
+
def chat(self,
|
| 206 |
+
audio: Optional[Union[str, "torch.Tensor", List]] = None,
|
| 207 |
+
query: str = "",
|
| 208 |
+
*,
|
| 209 |
+
processor=None,
|
| 210 |
+
system_prompt: Optional[str] = None,
|
| 211 |
+
max_new_tokens: int = 256,
|
| 212 |
+
**gen_kwargs) -> Union[str, List[str]]:
|
| 213 |
+
"""Single-turn audio+text chat.
|
| 214 |
+
|
| 215 |
+
Builds a one-message-per-role ChatML conversation in the exact shape
|
| 216 |
+
ThinkerModel.generate_sft expects (role/parts/type), encodes the audio
|
| 217 |
+
via WhisperFeatureExtractor, and runs greedy generation.
|
| 218 |
+
|
| 219 |
+
`audio` may be a path, a (samples,) waveform tensor at 16k, or a list
|
| 220 |
+
of those for a single multi-audio turn. Pass None for text-only.
|
| 221 |
+
"""
|
| 222 |
+
assert self.thinker is not None, "Call from_pretrained first."
|
| 223 |
+
tok = (processor.tokenizer if processor is not None
|
| 224 |
+
else self._tokenizer)
|
| 225 |
+
fe = (processor.feature_extractor if processor is not None
|
| 226 |
+
else self._feature_extractor)
|
| 227 |
+
sys_p = system_prompt or self.config.system_prompt
|
| 228 |
+
|
| 229 |
+
# ---- load + featurize audio(s) ----
|
| 230 |
+
audios = []
|
| 231 |
+
if audio is not None:
|
| 232 |
+
audios = audio if isinstance(audio, (list, tuple)) else [audio]
|
| 233 |
+
mel_list, frames_list = [], []
|
| 234 |
+
for a in audios:
|
| 235 |
+
wav = _load_waveform(a, self.config.sample_rate,
|
| 236 |
+
self.config.max_audio_length)
|
| 237 |
+
mel = fe(wav.numpy(), sampling_rate=self.config.sample_rate,
|
| 238 |
+
return_tensors="pt").input_features[0]
|
| 239 |
+
mel_list.append(mel)
|
| 240 |
+
frames_list.append(min(len(wav) // 160, # 10ms hops
|
| 241 |
+
int(self.config.max_audio_length * 100)))
|
| 242 |
+
|
| 243 |
+
if mel_list:
|
| 244 |
+
mel_inputs = torch.stack(mel_list).to(
|
| 245 |
+
device=self._device, dtype=self._dtype)
|
| 246 |
+
audio_frames = torch.tensor(frames_list, device=self._device)
|
| 247 |
+
else:
|
| 248 |
+
mel_inputs = torch.empty(0, device=self._device, dtype=self._dtype)
|
| 249 |
+
audio_frames = None
|
| 250 |
+
|
| 251 |
+
# ---- build conversation in generate_sft's expected schema ----
|
| 252 |
+
user_parts = []
|
| 253 |
+
for i in range(len(audios)):
|
| 254 |
+
user_parts.append({"type": "audio", "audio_index": i})
|
| 255 |
+
if query:
|
| 256 |
+
user_parts.append({"type": "text", "content": query})
|
| 257 |
+
|
| 258 |
+
conversation = [
|
| 259 |
+
{"role": "system", "parts": [{"type": "text", "content": sys_p}]},
|
| 260 |
+
{"role": "user", "parts": user_parts},
|
| 261 |
+
{"role": "assistant", "parts": []}, # prefix-only in gen mode
|
| 262 |
+
]
|
| 263 |
+
|
| 264 |
+
results = self.thinker.generate_sft(
|
| 265 |
+
mel_inputs=mel_inputs,
|
| 266 |
+
audio_counts=[len(audios)],
|
| 267 |
+
conversations=[conversation],
|
| 268 |
+
tokenizer=tok,
|
| 269 |
+
max_new_tokens=max_new_tokens,
|
| 270 |
+
audio_frames=audio_frames,
|
| 271 |
+
**gen_kwargs,
|
| 272 |
+
)
|
| 273 |
+
return results[0] if results else ""
|
| 274 |
+
|
| 275 |
+
# convenience accessors
|
| 276 |
+
@property
|
| 277 |
+
def tokenizer(self):
|
| 278 |
+
return self._tokenizer
|
| 279 |
+
|
| 280 |
+
@property
|
| 281 |
+
def feature_extractor(self):
|
| 282 |
+
return self._feature_extractor
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
# ----------------------------------------------------------------------
|
| 286 |
+
# Helpers
|
| 287 |
+
# ----------------------------------------------------------------------
|
| 288 |
+
def _load_waveform(audio, sample_rate: int, max_seconds: float) -> torch.Tensor:
|
| 289 |
+
"""Return a mono float32 waveform tensor at `sample_rate`, truncated."""
|
| 290 |
+
if isinstance(audio, torch.Tensor):
|
| 291 |
+
wav = audio.float()
|
| 292 |
+
if wav.dim() > 1:
|
| 293 |
+
wav = wav.mean(dim=0)
|
| 294 |
+
else:
|
| 295 |
+
import torchaudio
|
| 296 |
+
wav, sr = torchaudio.load(audio)
|
| 297 |
+
if wav.dim() > 1:
|
| 298 |
+
wav = wav.mean(dim=0)
|
| 299 |
+
if sr != sample_rate:
|
| 300 |
+
wav = torchaudio.functional.resample(wav, sr, sample_rate)
|
| 301 |
+
wav = wav.float()
|
| 302 |
+
max_len = int(max_seconds * sample_rate)
|
| 303 |
+
if wav.numel() > max_len:
|
| 304 |
+
wav = wav[:max_len]
|
| 305 |
+
return wav
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
class HGAThinkerProcessor:
|
| 309 |
+
"""Bundles the Qwen tokenizer + Whisper feature extractor.
|
| 310 |
+
|
| 311 |
+
Mirrors what training used: AutoTokenizer(llm) + WhisperFeatureExtractor(whisper).
|
| 312 |
+
"""
|
| 313 |
+
def __init__(self, tokenizer, feature_extractor, config: dict = None):
|
| 314 |
+
self.tokenizer = tokenizer
|
| 315 |
+
self.feature_extractor = feature_extractor
|
| 316 |
+
self.config = config or {}
|
| 317 |
+
|
| 318 |
+
@classmethod
|
| 319 |
+
def from_pretrained(cls, model_dir: str, *, whisper_path: Optional[str] = None):
|
| 320 |
+
tok = AutoTokenizer.from_pretrained(model_dir)
|
| 321 |
+
# whisper ref: bundled dir, else preprocessor_config.json at root, else override
|
| 322 |
+
wh = whisper_path
|
| 323 |
+
if wh is None:
|
| 324 |
+
bundled = os.path.join(model_dir, "whisper")
|
| 325 |
+
wh = bundled if os.path.isdir(bundled) else model_dir
|
| 326 |
+
fe = WhisperFeatureExtractor.from_pretrained(wh)
|
| 327 |
+
proc_cfg = {}
|
| 328 |
+
pc = os.path.join(model_dir, "processor_config.json")
|
| 329 |
+
if os.path.isfile(pc):
|
| 330 |
+
with open(pc) as f:
|
| 331 |
+
proc_cfg = json.load(f)
|
| 332 |
+
return cls(tok, fe, proc_cfg)
|
preprocessor_config.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"chunk_length": 30,
|
| 3 |
+
"feature_extractor_type": "WhisperFeatureExtractor",
|
| 4 |
+
"feature_size": 128,
|
| 5 |
+
"hop_length": 160,
|
| 6 |
+
"n_fft": 400,
|
| 7 |
+
"n_samples": 480000,
|
| 8 |
+
"nb_max_frames": 3000,
|
| 9 |
+
"padding_side": "right",
|
| 10 |
+
"padding_value": 0.0,
|
| 11 |
+
"processor_class": "WhisperProcessor",
|
| 12 |
+
"return_attention_mask": false,
|
| 13 |
+
"sampling_rate": 16000
|
| 14 |
+
}
|
processor_config.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"sample_rate": 16000,
|
| 3 |
+
"max_audio_length": 30.0,
|
| 4 |
+
"system_prompt": "You are a helpful assistant that analyzes audio content.",
|
| 5 |
+
"assistant_prefix": "<|im_start|>assistant\n"
|
| 6 |
+
}
|
thinker/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""HGA-Thinker: Hyperbolic Geometry Adapter for Speech Language Model."""
|
thinker/config.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""HGA-Thinker configuration."""
|
| 2 |
+
import os, yaml
|
| 3 |
+
from dataclasses import dataclass, field, asdict
|
| 4 |
+
from typing import List, Dict, Optional, Any
|
| 5 |
+
import dataclasses as _dc
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@dataclass
|
| 9 |
+
class TrainingConfig:
|
| 10 |
+
learning_rate: float = 5e-5
|
| 11 |
+
hga_lr_scale: float = 1.0
|
| 12 |
+
emca_lr_scale: float = 1.0
|
| 13 |
+
weight_decay: float = 0.01
|
| 14 |
+
warmup_ratio: float = 0.03
|
| 15 |
+
num_epochs: int = 3
|
| 16 |
+
max_steps: int = -1
|
| 17 |
+
batch_size: int = 6
|
| 18 |
+
grad_accumulation_steps: int = 2
|
| 19 |
+
gradient_clip_norm: float = 1.0
|
| 20 |
+
max_audio_length: float = 30.0
|
| 21 |
+
# ---- v2: per-batch audio cap ----
|
| 22 |
+
# Maximum total number of audios allowed in a single batch (i.e. the
|
| 23 |
+
# first dim of the stacked mel tensor going through the Whisper encoder).
|
| 24 |
+
# Multi-audio samples (e.g. constrain_inf_pair_audio with up to 4 audios)
|
| 25 |
+
# can otherwise blow up the encoder forward batch to bs * 4 = 16 and OOM
|
| 26 |
+
# the GPU. The dynamic batch sampler greedily packs samples so that the
|
| 27 |
+
# SUM of their audio counts stays <= this cap, while never exceeding
|
| 28 |
+
# batch_size samples. Set to 0 or a value >= batch_size*max_audios to
|
| 29 |
+
# disable (degrades to plain batching).
|
| 30 |
+
max_audios_per_batch: int = 6
|
| 31 |
+
eval_loss_steps: int = 500
|
| 32 |
+
eval_generate_steps: int = 2000
|
| 33 |
+
eval_samples_per_task: int = 100
|
| 34 |
+
# How many random ref/hyp pairs to print per task at each generate eval.
|
| 35 |
+
# 5 keeps the log compact; bump to 10 if you want richer qualitative view.
|
| 36 |
+
eval_display_samples: int = 5
|
| 37 |
+
save_steps: int = 2000
|
| 38 |
+
logging_steps: int = 50
|
| 39 |
+
output_dir: str = "outputs/align_hga"
|
| 40 |
+
# Loss
|
| 41 |
+
lambda_radius: float = 0.02
|
| 42 |
+
radius_margin: float = 0.05
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@dataclass
|
| 46 |
+
class ThinkerConfig:
|
| 47 |
+
# Whisper
|
| 48 |
+
whisper_path: str = ""
|
| 49 |
+
encoder_dim: int = 1280
|
| 50 |
+
num_whisper_layers: int = 32
|
| 51 |
+
extract_layers: List[int] = field(
|
| 52 |
+
default_factory=lambda: [3, 7, 11, 15, 19, 23, 27, 31] # 0-indexed
|
| 53 |
+
)
|
| 54 |
+
target_frame_rate_hz: float = 12.5
|
| 55 |
+
|
| 56 |
+
# HGA (per-layer Q/K/V weight modulation)
|
| 57 |
+
# b_init_std=1e-4 ensures b ≠ 0 at step 0 so ∂L/∂c is non-zero from start.
|
| 58 |
+
# All layers share the same c bounds — layer-aware bucketing removed since
|
| 59 |
+
# Möbius bias makes c a real learnable parameter that finds its own
|
| 60 |
+
# per-layer optimum without artificial floors.
|
| 61 |
+
hga_c_init: float = 1.0
|
| 62 |
+
hga_c_min: float = 0.001
|
| 63 |
+
hga_c_max: float = 8.0
|
| 64 |
+
hga_b_init_std: float = 1.0e-4
|
| 65 |
+
|
| 66 |
+
# EMCA
|
| 67 |
+
emca_c_work_init: float = 0.5
|
| 68 |
+
emca_c_work_min: float = 0.01
|
| 69 |
+
emca_c_work_max: float = 4.0
|
| 70 |
+
projector_hidden: int = 4096
|
| 71 |
+
|
| 72 |
+
# LLM
|
| 73 |
+
llm_name: str = ""
|
| 74 |
+
llm_dim: int = 3584
|
| 75 |
+
freeze_llm: bool = True
|
| 76 |
+
|
| 77 |
+
# LoRA (SFT stage only; ignored during align)
|
| 78 |
+
lora: Optional[Dict[str, Any]] = None
|
| 79 |
+
|
| 80 |
+
# SFT
|
| 81 |
+
system_prompt: str = "You are a helpful assistant that analyzes audio content."
|
| 82 |
+
sft_eval_ratio: float = 0.005
|
| 83 |
+
|
| 84 |
+
# Training
|
| 85 |
+
training: TrainingConfig = field(default_factory=TrainingConfig)
|
| 86 |
+
|
| 87 |
+
# Data
|
| 88 |
+
datasets: List[Dict[str, Any]] = field(default_factory=list)
|
| 89 |
+
audio_path_prefix_map: Dict[str, str] = field(default_factory=dict)
|
| 90 |
+
rich_annotation_fields: Dict[str, Dict[str, Any]] = field(default_factory=dict)
|
| 91 |
+
|
| 92 |
+
# ---- Resume ----
|
| 93 |
+
# resume_from: CROSS-STAGE handoff. Loads HGA + EMCA weights ONLY from
|
| 94 |
+
# a bridge.pt; optimizer, scheduler, and global_step all
|
| 95 |
+
# start fresh. Typical use:
|
| 96 |
+
# prealign → align : prealign/final/bridge.pt
|
| 97 |
+
# align → SFT : align/final/bridge.pt
|
| 98 |
+
# resume_state: SAME-STAGE seamless mid-run resume. Loads full training
|
| 99 |
+
# state (model + optimizer + scheduler + RNG + global_step)
|
| 100 |
+
# from an accelerator.save_state() directory. Use this when
|
| 101 |
+
# continuing the SAME stage after a crash or pause. Point
|
| 102 |
+
# it at either outputs/<stage>/checkpoint-N/
|
| 103 |
+
# or outputs/<stage>/checkpoint-N/state/
|
| 104 |
+
# The two are mutually exclusive — resume_state takes precedence if
|
| 105 |
+
# both are set (its model weights override anything resume_from would
|
| 106 |
+
# have loaded).
|
| 107 |
+
resume_from: Optional[str] = None
|
| 108 |
+
resume_state: Optional[str] = None
|
| 109 |
+
|
| 110 |
+
# Convenience properties (no setters; modify .training fields directly)
|
| 111 |
+
@property
|
| 112 |
+
def output_dir(self): return self.training.output_dir
|
| 113 |
+
@property
|
| 114 |
+
def batch_size(self): return self.training.batch_size
|
| 115 |
+
@property
|
| 116 |
+
def grad_accumulation_steps(self): return self.training.grad_accumulation_steps
|
| 117 |
+
@property
|
| 118 |
+
def max_audio_length(self): return self.training.max_audio_length
|
| 119 |
+
@property
|
| 120 |
+
def num_epochs(self): return self.training.num_epochs
|
| 121 |
+
@property
|
| 122 |
+
def max_steps(self): return self.training.max_steps
|
| 123 |
+
@property
|
| 124 |
+
def warmup_ratio(self): return self.training.warmup_ratio
|
| 125 |
+
@property
|
| 126 |
+
def learning_rate(self): return self.training.learning_rate
|
| 127 |
+
@property
|
| 128 |
+
def weight_decay(self): return self.training.weight_decay
|
| 129 |
+
@property
|
| 130 |
+
def gradient_clip_norm(self): return self.training.gradient_clip_norm
|
| 131 |
+
@property
|
| 132 |
+
def save_steps(self): return self.training.save_steps
|
| 133 |
+
@property
|
| 134 |
+
def logging_steps(self): return self.training.logging_steps
|
| 135 |
+
|
| 136 |
+
@classmethod
|
| 137 |
+
def from_yaml(cls, path: str) -> "ThinkerConfig":
|
| 138 |
+
with open(path) as f:
|
| 139 |
+
data = yaml.safe_load(f)
|
| 140 |
+
return cls.from_dict(data)
|
| 141 |
+
|
| 142 |
+
@classmethod
|
| 143 |
+
def from_dict(cls, data: dict) -> "ThinkerConfig":
|
| 144 |
+
training_raw = dict(data.get("training") or {})
|
| 145 |
+
valid = {f.name for f in _dc.fields(TrainingConfig)}
|
| 146 |
+
training_raw = {k: v for k, v in training_raw.items() if k in valid}
|
| 147 |
+
training = TrainingConfig(**training_raw)
|
| 148 |
+
|
| 149 |
+
valid_top = {f.name for f in _dc.fields(cls)} - {"training"}
|
| 150 |
+
top = {k: v for k, v in data.items() if k in valid_top and k != "training"}
|
| 151 |
+
return cls(training=training, **top)
|
| 152 |
+
|
| 153 |
+
def to_yaml(self, path: str):
|
| 154 |
+
d = asdict(self)
|
| 155 |
+
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
| 156 |
+
with open(path, "w") as f:
|
| 157 |
+
yaml.safe_dump(d, f, sort_keys=False)
|
thinker/emca.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Enhanced Multi-scale Cross-Attention (EMCA) in the Poincaré ball.
|
| 3 |
+
|
| 4 |
+
================================================================================
|
| 5 |
+
V1 (2B): radii_per_scale and p_fuse are no longer .detach()'d. Crucially, the
|
| 6 |
+
radii used for L_radius are computed from `attended` (post Einstein-midpoint
|
| 7 |
+
cross-attention), NOT from `ball_features` (the bare exp_map output).
|
| 8 |
+
|
| 9 |
+
WHY:
|
| 10 |
+
poincare_radius(exp_0^c(h), c) = (2/√c) · artanh(√c · tanh(√c‖h‖)/√c)
|
| 11 |
+
= 2‖h‖ — c CANCELS OUT.
|
| 12 |
+
poincare_radius(attended, c) has no such cancellation because `attended`
|
| 13 |
+
is the output of einstein_midpoint, whose Lorentz factor γ = (1-c‖k‖²)^(-1/2)
|
| 14 |
+
is genuinely c-dependent and not invertible by the outer artanh.
|
| 15 |
+
|
| 16 |
+
So under V1:
|
| 17 |
+
- L_radius has real gradient flow (no .detach())
|
| 18 |
+
- L_radius's gradient w.r.t. c_work is non-zero (radii truly depend on c)
|
| 19 |
+
- L_radius's gradient also reaches HGA's (s, b, c^(l)) via the
|
| 20 |
+
multi_scale_features → attended path
|
| 21 |
+
================================================================================
|
| 22 |
+
"""
|
| 23 |
+
import logging
|
| 24 |
+
from typing import Dict, List, Any
|
| 25 |
+
|
| 26 |
+
import torch
|
| 27 |
+
import torch.nn as nn
|
| 28 |
+
import torch.nn.functional as F
|
| 29 |
+
|
| 30 |
+
from .hyperbolic_ops import (
|
| 31 |
+
exp_map_zero, log_map_zero, clamp_norm,
|
| 32 |
+
hyperbolic_distance, einstein_midpoint,
|
| 33 |
+
poincare_radius, LearnableCurvature,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
logger = logging.getLogger(__name__)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class RMSNorm(nn.Module):
|
| 40 |
+
"""Root Mean Square Normalization (preserves direction, controls magnitude)."""
|
| 41 |
+
def __init__(self, dim: int, eps: float = 1e-6):
|
| 42 |
+
super().__init__()
|
| 43 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 44 |
+
self.eps = eps
|
| 45 |
+
|
| 46 |
+
def forward(self, x):
|
| 47 |
+
x_f = x.float()
|
| 48 |
+
rms = torch.sqrt(x_f.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 49 |
+
return ((x_f / rms) * self.weight.float()).to(x.dtype)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class EMCA(nn.Module):
|
| 53 |
+
"""Enhanced Multi-scale Cross-Attention.
|
| 54 |
+
|
| 55 |
+
Forward pipeline:
|
| 56 |
+
1. Per-scale exp_map into working Poincaré ball (c_work).
|
| 57 |
+
2. Pairwise hyperbolic distance → softmax → cross-scale attention scores.
|
| 58 |
+
3. Einstein midpoint per query scale → `attended` (B, T, S, d) in ball.
|
| 59 |
+
↑ This is where c truly affects values (via Lorentz factor γ).
|
| 60 |
+
4. Final aggregation across scales (Einstein midpoint, scale_weights) → p_fuse.
|
| 61 |
+
5. log_map → projector → RMSNorm → audio_tokens (Euclidean).
|
| 62 |
+
|
| 63 |
+
Outputs:
|
| 64 |
+
audio_tokens: (B, T, llm_dim) Euclidean — feeds LLM.
|
| 65 |
+
p_fuse: (B, T, d) in ball — available for future hyperbolic losses.
|
| 66 |
+
radii_per_scale: (S,) — mean poincare_radius(attended[..., i, :], c_work).
|
| 67 |
+
Gradient flows through this; L_radius uses it.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
def __init__(self,
|
| 71 |
+
encoder_dim: int = 1280,
|
| 72 |
+
llm_dim: int = 3584,
|
| 73 |
+
num_scales: int = 8,
|
| 74 |
+
c_work_init: float = 0.5,
|
| 75 |
+
c_work_min: float = 0.01,
|
| 76 |
+
c_work_max: float = 4.0,
|
| 77 |
+
projector_hidden: int = 4096):
|
| 78 |
+
super().__init__()
|
| 79 |
+
self.encoder_dim = encoder_dim
|
| 80 |
+
self.num_scales = num_scales
|
| 81 |
+
|
| 82 |
+
# Working curvature for the EMCA ball (separate from HGA's per-layer c^(l))
|
| 83 |
+
self.c_work = LearnableCurvature(
|
| 84 |
+
init_value=c_work_init, c_min=c_work_min, c_max=c_work_max
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
# Learnable temperature for attention
|
| 88 |
+
self.log_temperature = nn.Parameter(torch.tensor(1.0).log())
|
| 89 |
+
|
| 90 |
+
# Learnable scale weights for final aggregation
|
| 91 |
+
self.scale_logits = nn.Parameter(torch.zeros(num_scales))
|
| 92 |
+
|
| 93 |
+
# Output projection: encoder_dim → llm_dim
|
| 94 |
+
self.projector = nn.Sequential(
|
| 95 |
+
nn.Linear(encoder_dim, projector_hidden),
|
| 96 |
+
nn.GELU(),
|
| 97 |
+
nn.Linear(projector_hidden, llm_dim),
|
| 98 |
+
)
|
| 99 |
+
self.output_norm = RMSNorm(llm_dim)
|
| 100 |
+
|
| 101 |
+
@property
|
| 102 |
+
def temperature(self):
|
| 103 |
+
return self.log_temperature.float().exp()
|
| 104 |
+
|
| 105 |
+
def forward(self, multi_scale_features: List[torch.Tensor]
|
| 106 |
+
) -> Dict[str, Any]:
|
| 107 |
+
"""
|
| 108 |
+
Args:
|
| 109 |
+
multi_scale_features: list of S tensors, each (B, T, d).
|
| 110 |
+
S = num_scales, features from different Whisper layers
|
| 111 |
+
(already pooled to target frame rate by ThinkerModel).
|
| 112 |
+
|
| 113 |
+
Returns:
|
| 114 |
+
dict containing audio_tokens (for LLM), p_fuse (for future use),
|
| 115 |
+
radii_per_scale (for L_radius, WITH gradient), and diagnostics.
|
| 116 |
+
"""
|
| 117 |
+
S = len(multi_scale_features)
|
| 118 |
+
assert S == self.num_scales, f"Expected {self.num_scales} scales, got {S}"
|
| 119 |
+
|
| 120 |
+
B, T, d = multi_scale_features[0].shape
|
| 121 |
+
c = self.c_work().float()
|
| 122 |
+
|
| 123 |
+
# 1. Map each scale into the working Poincaré ball
|
| 124 |
+
ball_features = []
|
| 125 |
+
for i in range(S):
|
| 126 |
+
h = multi_scale_features[i].float()
|
| 127 |
+
p = exp_map_zero(h, c) # (B, T, d) in ball
|
| 128 |
+
ball_features.append(p)
|
| 129 |
+
# Stack: (B, T, S, d)
|
| 130 |
+
ball_stack = torch.stack(ball_features, dim=2)
|
| 131 |
+
|
| 132 |
+
# 2. Pairwise hyperbolic distances for cross-attention
|
| 133 |
+
q = ball_stack.unsqueeze(3).expand(B, T, S, S, d).reshape(-1, d)
|
| 134 |
+
k = ball_stack.unsqueeze(2).expand(B, T, S, S, d).reshape(-1, d)
|
| 135 |
+
dists = hyperbolic_distance(q, k, c).reshape(B, T, S, S)
|
| 136 |
+
|
| 137 |
+
# Attention scores: -distance / temperature, mask diagonal
|
| 138 |
+
scores = -dists / self.temperature
|
| 139 |
+
diag_mask = torch.eye(S, device=scores.device, dtype=torch.bool)
|
| 140 |
+
scores = scores.masked_fill(
|
| 141 |
+
diag_mask.unsqueeze(0).unsqueeze(0), float('-inf')
|
| 142 |
+
)
|
| 143 |
+
attn_weights = F.softmax(scores, dim=-1) # (B, T, S, S)
|
| 144 |
+
|
| 145 |
+
# 3. Einstein midpoint cross-attention per query scale
|
| 146 |
+
points_exp = ball_stack.unsqueeze(2).expand(B, T, S, S, d)
|
| 147 |
+
attended = einstein_midpoint(points_exp, attn_weights, c) # (B, T, S, d)
|
| 148 |
+
|
| 149 |
+
# 3b. Radii from `attended` — c truly affects values here (no cancellation)
|
| 150 |
+
# Note: NO .detach() — radii carry gradient back to c_work, scale weights,
|
| 151 |
+
# and through multi_scale_features to HGA parameters.
|
| 152 |
+
radii_per_scale = []
|
| 153 |
+
for i in range(S):
|
| 154 |
+
radii_per_scale.append(
|
| 155 |
+
poincare_radius(attended[:, :, i, :], c).mean()
|
| 156 |
+
)
|
| 157 |
+
radii_per_scale = torch.stack(radii_per_scale) # (S,)
|
| 158 |
+
|
| 159 |
+
# 4. Final aggregation across scales
|
| 160 |
+
scale_w = F.softmax(self.scale_logits.float(), dim=0) # (S,)
|
| 161 |
+
scale_w_exp = scale_w.unsqueeze(0).unsqueeze(0).expand(B, T, -1)
|
| 162 |
+
p_fuse = einstein_midpoint(attended, scale_w_exp, c) # (B, T, d)
|
| 163 |
+
|
| 164 |
+
# 5. Log map back to Euclidean, project to LLM dim
|
| 165 |
+
z = log_map_zero(p_fuse, c) # (B, T, d)
|
| 166 |
+
proj_dtype = next(self.projector.parameters()).dtype
|
| 167 |
+
audio_tokens = self.projector(z.to(proj_dtype))
|
| 168 |
+
audio_tokens = self.output_norm(audio_tokens)
|
| 169 |
+
|
| 170 |
+
return {
|
| 171 |
+
"audio_tokens": audio_tokens,
|
| 172 |
+
# p_fuse kept in graph (no detach) — available for future losses.
|
| 173 |
+
"p_fuse": p_fuse,
|
| 174 |
+
# radii_per_scale carries gradient → real L_radius signal.
|
| 175 |
+
"radii_per_scale": radii_per_scale,
|
| 176 |
+
# Below are diagnostics only; .detach() is fine here.
|
| 177 |
+
"c_work": c.detach(),
|
| 178 |
+
"scale_weights": scale_w.detach(),
|
| 179 |
+
"scale_entropy": -(scale_w * (scale_w + 1e-8).log()).sum().detach(),
|
| 180 |
+
"attention_temp": self.temperature.detach(),
|
| 181 |
+
}
|
thinker/encoder.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Whisper encoder with HGA-modulated self-attention.
|
| 3 |
+
|
| 4 |
+
================================================================================
|
| 5 |
+
V1 (2A): HGA now includes a Möbius bias term that breaks exp/log cancellation,
|
| 6 |
+
making the curvature c a real, gradient-bearing parameter.
|
| 7 |
+
|
| 8 |
+
Modulation formula (per Q/K/V projection, per layer):
|
| 9 |
+
|
| 10 |
+
W_HGA = log_0^c( ( diag(s) ⊗_c exp_0^c(W_ref) ) ⊕_c exp_0^c(b) )
|
| 11 |
+
|
| 12 |
+
Without b, the chain reduces to s ⊙ W_ref (DoRA-like, c does nothing — this
|
| 13 |
+
is the SER paper's formula). With b ≠ 0, the Möbius addition step entangles c
|
| 14 |
+
with the norms of q and b in a way that cannot be algebraically cancelled.
|
| 15 |
+
|
| 16 |
+
Key properties:
|
| 17 |
+
- b tiny-random-init (std=1e-4) → init is numerically ≈ s ⊙ W_ref but with
|
| 18 |
+
b ≠ 0, so c receives gradient signal from step 0. (Zero-init would freeze
|
| 19 |
+
c at a saddle ∂L/∂c = 0.)
|
| 20 |
+
- All layers use the same (c_min, c_init, c_max) bounds; layer-aware bucketing
|
| 21 |
+
removed because b makes c a real parameter that learns its own per-layer
|
| 22 |
+
optimum without artificial floors.
|
| 23 |
+
================================================================================
|
| 24 |
+
"""
|
| 25 |
+
import math
|
| 26 |
+
import logging
|
| 27 |
+
from typing import List, Dict, Any, Optional
|
| 28 |
+
|
| 29 |
+
import torch
|
| 30 |
+
import torch.nn as nn
|
| 31 |
+
import torch.nn.functional as F
|
| 32 |
+
|
| 33 |
+
from .hyperbolic_ops import (
|
| 34 |
+
exp_map_zero, log_map_zero, mobius_add, clamp_norm,
|
| 35 |
+
LearnableCurvature,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
logger = logging.getLogger(__name__)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class HGALinear(nn.Module):
|
| 42 |
+
"""Drop-in replacement for nn.Linear that applies HGA weight modulation
|
| 43 |
+
with a Möbius bias term.
|
| 44 |
+
|
| 45 |
+
Stores a frozen reference weight W_ref. At forward time:
|
| 46 |
+
p = exp_0^c(W_ref) # rows → ball
|
| 47 |
+
v = log_0^c(p) # = W_ref (id)
|
| 48 |
+
q = exp_0^c(diag(s) · v) = exp_0^c(s ⊙ W_ref)# Möbius scale
|
| 49 |
+
b_pt = exp_0^c(b) # bias → ball
|
| 50 |
+
r = q ⊕_c b_pt # Möbius add — c becomes essential
|
| 51 |
+
W_mod = log_0^c(r) # ball → tangent
|
| 52 |
+
output = x @ W_mod^T + bias_orig
|
| 53 |
+
|
| 54 |
+
Trainable: s (d_in,), b (d_in,), c (via curvature_module)
|
| 55 |
+
Frozen: W_ref, bias_orig (from pretrained Whisper)
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
def __init__(self, original_linear: nn.Linear,
|
| 59 |
+
s: nn.Parameter, b: nn.Parameter,
|
| 60 |
+
curvature_module: nn.Module):
|
| 61 |
+
super().__init__()
|
| 62 |
+
# Frozen reference weight (rows are the d_out "row vectors" in R^{d_in})
|
| 63 |
+
self.register_buffer("W_ref", original_linear.weight.data.clone().float())
|
| 64 |
+
# Keep original bias (frozen but used in forward)
|
| 65 |
+
if original_linear.bias is not None:
|
| 66 |
+
self.register_buffer("bias", original_linear.bias.data.clone())
|
| 67 |
+
else:
|
| 68 |
+
self.bias = None
|
| 69 |
+
# Learnable HGA parameters (shared from the per-layer container)
|
| 70 |
+
self.s = s
|
| 71 |
+
self.b = b
|
| 72 |
+
self.curvature = curvature_module
|
| 73 |
+
|
| 74 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 75 |
+
c = self.curvature().float()
|
| 76 |
+
|
| 77 |
+
# Step 1: rows of W_ref → Poincaré ball
|
| 78 |
+
p = exp_map_zero(self.W_ref, c) # (d_out, d_in)
|
| 79 |
+
# Step 2: Möbius diagonal scaling diag(s) ⊗_c p
|
| 80 |
+
# = exp_0^c( s ⊙ log_0^c(p) ) = exp_0^c( s ⊙ W_ref )
|
| 81 |
+
v = log_map_zero(p, c) # = W_ref (cancellation)
|
| 82 |
+
v_scaled = v * self.s.float().unsqueeze(0)
|
| 83 |
+
q = exp_map_zero(v_scaled, c) # (d_out, d_in) in ball
|
| 84 |
+
# Step 3: Möbius bias addition — broadcasts b across d_out rows
|
| 85 |
+
b_pt = exp_map_zero(self.b.float(), c) # (d_in,) in ball
|
| 86 |
+
b_pt_b = b_pt.unsqueeze(0).expand_as(q) # (d_out, d_in)
|
| 87 |
+
r = mobius_add(q, b_pt_b, c) # (d_out, d_in)
|
| 88 |
+
r = clamp_norm(r, c) # numerical safety
|
| 89 |
+
# Step 4: log_map back to tangent → modulated weight
|
| 90 |
+
W_mod = log_map_zero(r, c) # (d_out, d_in)
|
| 91 |
+
|
| 92 |
+
with torch.amp.autocast("cuda", enabled=False):
|
| 93 |
+
return F.linear(x.float(), W_mod.float(),
|
| 94 |
+
self.bias.float() if self.bias is not None else None).to(x.dtype)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class HGAWhisperEncoder(nn.Module):
|
| 98 |
+
"""Whisper encoder with HGA-modulated Q/K/V on all 32 layers.
|
| 99 |
+
|
| 100 |
+
Architecture:
|
| 101 |
+
1. Load Whisper encoder, freeze every original parameter.
|
| 102 |
+
2. For each layer, create one shared LearnableCurvature c^(l) plus three
|
| 103 |
+
pairs of (s, b) — for q_proj, k_proj, v_proj.
|
| 104 |
+
3. Replace q_proj/k_proj/v_proj with HGALinear wrappers that compute
|
| 105 |
+
the modulated weight on the fly.
|
| 106 |
+
4. Register forward hooks to capture multi-scale features for EMCA.
|
| 107 |
+
|
| 108 |
+
Trainable params per layer:
|
| 109 |
+
3 × d_model (s_Q, s_K, s_V) + 3 × d_model (b_Q, b_K, b_V) + 1 (c)
|
| 110 |
+
= 6 × d_model + 1
|
| 111 |
+
For d_model=1280 → 7,681 per layer × 32 layers ≈ 246K total (HGA only).
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
output_dim = 1280
|
| 115 |
+
output_frame_rate_hz = 50.0
|
| 116 |
+
|
| 117 |
+
def __init__(self, model_path: str, extract_layers: List[int],
|
| 118 |
+
num_encoder_layers: int = 32,
|
| 119 |
+
hga_c_init: float = 1.0,
|
| 120 |
+
hga_c_min: float = 0.001,
|
| 121 |
+
hga_c_max: float = 8.0,
|
| 122 |
+
hga_b_init_std: float = 1.0e-4):
|
| 123 |
+
super().__init__()
|
| 124 |
+
self.extract_layers = sorted(extract_layers)
|
| 125 |
+
self.num_encoder_layers = num_encoder_layers
|
| 126 |
+
self.hga_c_init = hga_c_init
|
| 127 |
+
self.hga_c_min = hga_c_min
|
| 128 |
+
self.hga_c_max = hga_c_max
|
| 129 |
+
self.hga_b_init_std = hga_b_init_std
|
| 130 |
+
|
| 131 |
+
# --- Load Whisper encoder ---
|
| 132 |
+
from transformers import WhisperModel
|
| 133 |
+
whisper = WhisperModel.from_pretrained(model_path)
|
| 134 |
+
self.encoder = whisper.encoder
|
| 135 |
+
del whisper
|
| 136 |
+
|
| 137 |
+
# Freeze ALL original encoder parameters
|
| 138 |
+
for p in self.encoder.parameters():
|
| 139 |
+
p.requires_grad = False
|
| 140 |
+
|
| 141 |
+
# --- Create HGA params and inject into Whisper ---
|
| 142 |
+
self.hga_layers = nn.ModuleList()
|
| 143 |
+
d = self.output_dim
|
| 144 |
+
for i, layer in enumerate(self.encoder.layers):
|
| 145 |
+
attn = layer.self_attn
|
| 146 |
+
|
| 147 |
+
# Shared curvature for Q/K/V of this layer
|
| 148 |
+
curvature = LearnableCurvature(
|
| 149 |
+
init_value=hga_c_init, c_min=hga_c_min, c_max=hga_c_max
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
# Diagonal scaling: identity (s=1) at init → first-step output ≈ W_ref
|
| 153 |
+
s_q = nn.Parameter(torch.ones(d))
|
| 154 |
+
s_k = nn.Parameter(torch.ones(d))
|
| 155 |
+
s_v = nn.Parameter(torch.ones(d))
|
| 156 |
+
|
| 157 |
+
# Möbius bias: tiny random init so b ≠ 0 from step 0 and ∂L/∂c ≠ 0
|
| 158 |
+
b_q = nn.Parameter(torch.randn(d) * hga_b_init_std)
|
| 159 |
+
b_k = nn.Parameter(torch.randn(d) * hga_b_init_std)
|
| 160 |
+
b_v = nn.Parameter(torch.randn(d) * hga_b_init_std)
|
| 161 |
+
|
| 162 |
+
# Replace q/k/v_proj with HGA-modulated versions
|
| 163 |
+
attn.q_proj = HGALinear(attn.q_proj, s_q, b_q, curvature)
|
| 164 |
+
attn.k_proj = HGALinear(attn.k_proj, s_k, b_k, curvature)
|
| 165 |
+
attn.v_proj = HGALinear(attn.v_proj, s_v, b_v, curvature)
|
| 166 |
+
|
| 167 |
+
# Container so optimizer sees these params
|
| 168 |
+
cont = nn.Module()
|
| 169 |
+
cont.curvature = curvature
|
| 170 |
+
cont.s_q, cont.s_k, cont.s_v = s_q, s_k, s_v
|
| 171 |
+
cont.b_q, cont.b_k, cont.b_v = b_q, b_k, b_v
|
| 172 |
+
self.hga_layers.append(cont)
|
| 173 |
+
|
| 174 |
+
logger.info(
|
| 175 |
+
f"Whisper encoder: {num_encoder_layers} layers, "
|
| 176 |
+
f"all Q/K/V wrapped in HGALinear "
|
| 177 |
+
f"(c_init={hga_c_init}, c_min={hga_c_min}, c_max={hga_c_max}, "
|
| 178 |
+
f"b_std={hga_b_init_std})"
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
# --- Feature capture hooks ---
|
| 182 |
+
self._features: Dict[int, torch.Tensor] = {}
|
| 183 |
+
self._hooks = []
|
| 184 |
+
for idx, layer in enumerate(self.encoder.layers):
|
| 185 |
+
if idx in self.extract_layers:
|
| 186 |
+
self._hooks.append(
|
| 187 |
+
layer.register_forward_hook(self._make_hook(idx))
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
def _make_hook(self, layer_idx: int):
|
| 191 |
+
def hook_fn(module, input, output):
|
| 192 |
+
self._features[layer_idx] = (
|
| 193 |
+
output[0] if isinstance(output, tuple) else output
|
| 194 |
+
)
|
| 195 |
+
return hook_fn
|
| 196 |
+
|
| 197 |
+
def forward(self, mel_input: torch.Tensor) -> List[torch.Tensor]:
|
| 198 |
+
"""Run Whisper with HGA-modulated attention.
|
| 199 |
+
|
| 200 |
+
Args:
|
| 201 |
+
mel_input: (B, n_mels, T_mel)
|
| 202 |
+
Returns:
|
| 203 |
+
List of (B, T, 1280) tensors, one per extract_layer (sorted).
|
| 204 |
+
"""
|
| 205 |
+
encoder_dtype = self.encoder.layer_norm.weight.dtype
|
| 206 |
+
mel = mel_input.to(dtype=encoder_dtype)
|
| 207 |
+
|
| 208 |
+
self._features.clear()
|
| 209 |
+
_ = self.encoder(mel)
|
| 210 |
+
|
| 211 |
+
features = []
|
| 212 |
+
for ln in self.extract_layers:
|
| 213 |
+
if ln not in self._features:
|
| 214 |
+
raise RuntimeError(
|
| 215 |
+
f"Layer {ln} not captured. Got: {sorted(self._features.keys())}"
|
| 216 |
+
)
|
| 217 |
+
features.append(self._features[ln])
|
| 218 |
+
return features
|
| 219 |
+
|
| 220 |
+
def num_audio_frames(self, audio_samples_16khz: int) -> int:
|
| 221 |
+
return min(math.ceil(audio_samples_16khz / 320), 1500)
|
| 222 |
+
|
| 223 |
+
# ---- Diagnostics ----
|
| 224 |
+
|
| 225 |
+
def get_hga_diagnostics(self) -> Dict[str, float]:
|
| 226 |
+
"""Per-layer scalars logged to TensorBoard."""
|
| 227 |
+
diag = {}
|
| 228 |
+
for i, hga in enumerate(self.hga_layers):
|
| 229 |
+
diag[f"hga/c_L{i}"] = hga.curvature().item()
|
| 230 |
+
diag[f"hga/s_q_mean_L{i}"] = hga.s_q.data.mean().item()
|
| 231 |
+
diag[f"hga/s_v_mean_L{i}"] = hga.s_v.data.mean().item()
|
| 232 |
+
# b norms — key indicator: if these stay ~0, c won't learn
|
| 233 |
+
diag[f"hga/b_q_norm_L{i}"] = hga.b_q.data.norm().item()
|
| 234 |
+
diag[f"hga/b_k_norm_L{i}"] = hga.b_k.data.norm().item()
|
| 235 |
+
diag[f"hga/b_v_norm_L{i}"] = hga.b_v.data.norm().item()
|
| 236 |
+
return diag
|
| 237 |
+
|
| 238 |
+
def get_curvatures_summary(self) -> str:
|
| 239 |
+
"""Compact c-per-layer string for log lines (grouped 8 per row)."""
|
| 240 |
+
vals = [f"{hga.curvature().item():.4f}" for hga in self.hga_layers]
|
| 241 |
+
groups = []
|
| 242 |
+
for i in range(0, len(vals), 8):
|
| 243 |
+
groups.append("/".join(vals[i:i+8]))
|
| 244 |
+
return " | ".join(groups)
|
| 245 |
+
|
| 246 |
+
def get_b_norm_summary(self) -> str:
|
| 247 |
+
"""Compact b_q-per-layer norm string (grouped 8 per row).
|
| 248 |
+
Used to verify the 'b grows → c learns' training dynamic."""
|
| 249 |
+
vals = [f"{hga.b_q.data.norm().item():.4f}" for hga in self.hga_layers]
|
| 250 |
+
groups = []
|
| 251 |
+
for i in range(0, len(vals), 8):
|
| 252 |
+
groups.append("/".join(vals[i:i+8]))
|
| 253 |
+
return " | ".join(groups)
|
thinker/hyperbolic_ops.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Core Poincaré Ball Operations.
|
| 3 |
+
|
| 4 |
+
All ops run in fp32 via @_fp32 decorator regardless of ambient mixed-precision.
|
| 5 |
+
"""
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
import functools
|
| 10 |
+
|
| 11 |
+
MIN_NORM = 1e-15
|
| 12 |
+
BALL_EPS = 1e-5
|
| 13 |
+
TANH_CLAMP = 15.0
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _fp32(fn):
|
| 17 |
+
"""Disable autocast, cast inputs to fp32, cast output back."""
|
| 18 |
+
@functools.wraps(fn)
|
| 19 |
+
def wrapper(*args, **kwargs):
|
| 20 |
+
with torch.amp.autocast(device_type="cuda", enabled=False):
|
| 21 |
+
orig = None
|
| 22 |
+
for a in args:
|
| 23 |
+
if torch.is_tensor(a):
|
| 24 |
+
orig = a.dtype; break
|
| 25 |
+
if orig is None:
|
| 26 |
+
for v in kwargs.values():
|
| 27 |
+
if torch.is_tensor(v):
|
| 28 |
+
orig = v.dtype; break
|
| 29 |
+
orig = orig or torch.float32
|
| 30 |
+
a32 = [a.float() if torch.is_tensor(a) else a for a in args]
|
| 31 |
+
k32 = {k: v.float() if torch.is_tensor(v) else v for k, v in kwargs.items()}
|
| 32 |
+
r = fn(*a32, **k32)
|
| 33 |
+
return r.to(orig) if torch.is_tensor(r) else r
|
| 34 |
+
return wrapper
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def safe_arctanh(x):
|
| 38 |
+
return torch.atanh(x.clamp(-1 + 1e-7, 1 - 1e-7))
|
| 39 |
+
|
| 40 |
+
def safe_tanh(x):
|
| 41 |
+
return torch.tanh(x.clamp(-TANH_CLAMP, TANH_CLAMP))
|
| 42 |
+
|
| 43 |
+
def clamp_norm(x, c, eps=BALL_EPS):
|
| 44 |
+
max_norm = (1.0 / torch.sqrt(c)) - eps
|
| 45 |
+
norm = x.norm(dim=-1, keepdim=True).clamp(min=MIN_NORM)
|
| 46 |
+
return torch.where(norm > max_norm, x / norm * max_norm, x)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@_fp32
|
| 50 |
+
def exp_map_zero(v, c):
|
| 51 |
+
"""Tangent space → Poincaré ball at origin."""
|
| 52 |
+
sqrt_c = torch.sqrt(c)
|
| 53 |
+
v_norm = v.norm(dim=-1, keepdim=True).clamp(min=MIN_NORM)
|
| 54 |
+
factor = safe_tanh(sqrt_c * v_norm) / sqrt_c
|
| 55 |
+
return clamp_norm(factor * (v / v_norm), c)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@_fp32
|
| 59 |
+
def log_map_zero(x, c):
|
| 60 |
+
"""Poincaré ball → tangent space at origin."""
|
| 61 |
+
sqrt_c = torch.sqrt(c)
|
| 62 |
+
x_norm = x.norm(dim=-1, keepdim=True).clamp(min=MIN_NORM)
|
| 63 |
+
factor = safe_arctanh(sqrt_c * x_norm) / (sqrt_c * x_norm)
|
| 64 |
+
return factor * x
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@_fp32
|
| 68 |
+
def mobius_add(u, v, c):
|
| 69 |
+
"""Möbius addition u ⊕_c v."""
|
| 70 |
+
u2 = (u * u).sum(-1, keepdim=True)
|
| 71 |
+
v2 = (v * v).sum(-1, keepdim=True)
|
| 72 |
+
uv = (u * v).sum(-1, keepdim=True)
|
| 73 |
+
num = (1 + 2 * c * uv + c * v2) * u + (1 - c * u2) * v
|
| 74 |
+
den = (1 + 2 * c * uv + c * c * u2 * v2).clamp(min=MIN_NORM)
|
| 75 |
+
return num / den
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@_fp32
|
| 79 |
+
def hyperbolic_distance(x, y, c):
|
| 80 |
+
"""d_c(x, y) in Poincaré ball."""
|
| 81 |
+
sqrt_c = torch.sqrt(c)
|
| 82 |
+
diff = mobius_add(-x, y, c)
|
| 83 |
+
return (2.0 / sqrt_c) * safe_arctanh(sqrt_c * diff.norm(dim=-1).clamp(min=MIN_NORM))
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@_fp32
|
| 87 |
+
def poincare_radius(x, c):
|
| 88 |
+
"""d_c(0, x) = (2/√c) · artanh(√c · ‖x‖)."""
|
| 89 |
+
sqrt_c = torch.sqrt(c)
|
| 90 |
+
return (2.0 / sqrt_c) * safe_arctanh(sqrt_c * x.norm(dim=-1).clamp(min=MIN_NORM))
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@_fp32
|
| 94 |
+
def einstein_midpoint(points, weights, c):
|
| 95 |
+
"""Weighted Einstein midpoint. points: (..., N, d), weights: (..., N)."""
|
| 96 |
+
p2 = (points * points).sum(-1, keepdim=True)
|
| 97 |
+
klein = 2.0 * points / (1.0 + c * p2).clamp(min=MIN_NORM)
|
| 98 |
+
k2 = (klein * klein).sum(-1, keepdim=True)
|
| 99 |
+
gamma = 1.0 / torch.sqrt((1.0 - c * k2).clamp(min=MIN_NORM))
|
| 100 |
+
w = weights.unsqueeze(-1)
|
| 101 |
+
wg = w * gamma
|
| 102 |
+
k_bar = (wg * klein).sum(-2) / wg.sum(-2).clamp(min=MIN_NORM)
|
| 103 |
+
kb2 = (k_bar * k_bar).sum(-1, keepdim=True)
|
| 104 |
+
denom = 1.0 + torch.sqrt((1.0 - c * kb2).clamp(min=MIN_NORM))
|
| 105 |
+
return clamp_norm(k_bar / denom.clamp(min=MIN_NORM), c)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class LearnableCurvature(nn.Module):
|
| 109 |
+
"""c = clamp(softplus(hat_c) + c_min, max=c_max)."""
|
| 110 |
+
def __init__(self, init_value=1.0, c_min=0.01, c_max=None):
|
| 111 |
+
super().__init__()
|
| 112 |
+
self.c_min = c_min
|
| 113 |
+
self.c_max = c_max
|
| 114 |
+
delta = init_value - c_min
|
| 115 |
+
assert delta > 0, f"init_value({init_value}) must > c_min({c_min})"
|
| 116 |
+
if delta > 20.0:
|
| 117 |
+
init_hat = torch.tensor(delta, dtype=torch.float32)
|
| 118 |
+
else:
|
| 119 |
+
init_hat = torch.log(torch.expm1(torch.tensor(delta, dtype=torch.float32)))
|
| 120 |
+
self.hat_c = nn.Parameter(init_hat)
|
| 121 |
+
|
| 122 |
+
def forward(self):
|
| 123 |
+
c = F.softplus(self.hat_c) + self.c_min
|
| 124 |
+
if self.c_max is not None:
|
| 125 |
+
c = c.clamp(max=self.c_max)
|
| 126 |
+
return c
|
thinker/model.py
ADDED
|
@@ -0,0 +1,512 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
HGA-Thinker Model.
|
| 3 |
+
|
| 4 |
+
Architecture:
|
| 5 |
+
HGAWhisperEncoder (frozen Whisper + HGA on all 32 layers Q/K/V)
|
| 6 |
+
→ extract 8 scale features
|
| 7 |
+
→ mean-pool to target frame rate
|
| 8 |
+
EMCA (Poincaré ball cross-attention fusion)
|
| 9 |
+
→ p_fuse (for L_radius)
|
| 10 |
+
→ log_map → projector → RMSNorm → audio_tokens
|
| 11 |
+
Frozen Qwen 7B LLM
|
| 12 |
+
→ [audio_tokens, text_embeds] → L_CE
|
| 13 |
+
|
| 14 |
+
SFT extensions (appended, align code untouched):
|
| 15 |
+
setup_lora() — add LoRA to frozen LLM
|
| 16 |
+
get_sft_param_groups — three groups: LoRA / EMCA / HGA
|
| 17 |
+
forward_sft() — multi-audio + conversation-based input
|
| 18 |
+
generate_sft() — multi-audio generation
|
| 19 |
+
"""
|
| 20 |
+
import math
|
| 21 |
+
import logging
|
| 22 |
+
from typing import Dict, Any, Optional, List, Tuple
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
import torch.nn as nn
|
| 26 |
+
import torch.nn.functional as F
|
| 27 |
+
|
| 28 |
+
logger = logging.getLogger(__name__)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class ThinkerModel(nn.Module):
|
| 32 |
+
"""HGA-Thinker: Whisper(HGA) → EMCA → Bridge → frozen LLM."""
|
| 33 |
+
|
| 34 |
+
def __init__(self, config):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.config = config
|
| 37 |
+
|
| 38 |
+
# 1. Whisper encoder with HGA
|
| 39 |
+
from .encoder import HGAWhisperEncoder
|
| 40 |
+
self.encoder = HGAWhisperEncoder(
|
| 41 |
+
model_path=config.whisper_path,
|
| 42 |
+
extract_layers=config.extract_layers,
|
| 43 |
+
num_encoder_layers=config.num_whisper_layers,
|
| 44 |
+
hga_c_init=config.hga_c_init,
|
| 45 |
+
hga_c_min=config.hga_c_min,
|
| 46 |
+
hga_c_max=config.hga_c_max,
|
| 47 |
+
hga_b_init_std=config.hga_b_init_std,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
# 2. EMCA
|
| 51 |
+
from .emca import EMCA
|
| 52 |
+
self.emca = EMCA(
|
| 53 |
+
encoder_dim=config.encoder_dim,
|
| 54 |
+
llm_dim=config.llm_dim,
|
| 55 |
+
num_scales=len(config.extract_layers),
|
| 56 |
+
c_work_init=config.emca_c_work_init,
|
| 57 |
+
c_work_min=config.emca_c_work_min,
|
| 58 |
+
c_work_max=config.emca_c_work_max,
|
| 59 |
+
projector_hidden=config.projector_hidden,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
# 3. LLM (loaded externally)
|
| 63 |
+
self.llm = None
|
| 64 |
+
self.target_frame_rate_hz = config.target_frame_rate_hz
|
| 65 |
+
|
| 66 |
+
# Audio boundary markers for multi-audio SFT.
|
| 67 |
+
# Learnable embeddings inserted before / after each audio token
|
| 68 |
+
# sequence so the LLM can distinguish separate audio inputs.
|
| 69 |
+
# Dimensions match llm_dim; initialised with small random values
|
| 70 |
+
# (std=0.02, same as typical transformer embedding init).
|
| 71 |
+
# They are part of the bridge (not the frozen LLM), so they are
|
| 72 |
+
# naturally trainable and saved in bridge.pt.
|
| 73 |
+
self.audio_start_embed = nn.Parameter(torch.randn(config.llm_dim) * 0.02)
|
| 74 |
+
self.audio_end_embed = nn.Parameter(torch.randn(config.llm_dim) * 0.02)
|
| 75 |
+
|
| 76 |
+
def load_llm(self, llm_model):
|
| 77 |
+
self.llm = llm_model
|
| 78 |
+
if self.config.freeze_llm:
|
| 79 |
+
for p in self.llm.parameters():
|
| 80 |
+
p.requires_grad = False
|
| 81 |
+
|
| 82 |
+
def trainable_parameters(self):
|
| 83 |
+
return [p for p in self.parameters() if p.requires_grad]
|
| 84 |
+
|
| 85 |
+
def count_trainable_parameters(self) -> int:
|
| 86 |
+
return sum(p.numel() for p in self.parameters() if p.requires_grad)
|
| 87 |
+
|
| 88 |
+
def get_param_groups(self, base_lr: float, hga_lr_scale: float = 1.0,
|
| 89 |
+
emca_lr_scale: float = 1.0):
|
| 90 |
+
hga_ids = set(id(p) for p in self.encoder.hga_layers.parameters())
|
| 91 |
+
emca_ids = set(id(p) for p in self.emca.parameters())
|
| 92 |
+
hga_params, emca_params, other_params = [], [], []
|
| 93 |
+
for p in self.parameters():
|
| 94 |
+
if not p.requires_grad:
|
| 95 |
+
continue
|
| 96 |
+
pid = id(p)
|
| 97 |
+
if pid in hga_ids:
|
| 98 |
+
hga_params.append(p)
|
| 99 |
+
elif pid in emca_ids:
|
| 100 |
+
emca_params.append(p)
|
| 101 |
+
else:
|
| 102 |
+
other_params.append(p)
|
| 103 |
+
groups = []
|
| 104 |
+
if hga_params:
|
| 105 |
+
groups.append({"params": hga_params, "lr": base_lr * hga_lr_scale,
|
| 106 |
+
"_group_name": "hga"})
|
| 107 |
+
if emca_params:
|
| 108 |
+
groups.append({"params": emca_params, "lr": base_lr * emca_lr_scale,
|
| 109 |
+
"_group_name": "emca"})
|
| 110 |
+
if other_params:
|
| 111 |
+
groups.append({"params": other_params, "lr": base_lr,
|
| 112 |
+
"_group_name": "other"})
|
| 113 |
+
return groups
|
| 114 |
+
|
| 115 |
+
# ---- Time-axis pooling ----
|
| 116 |
+
|
| 117 |
+
@staticmethod
|
| 118 |
+
def _pool_time(x, in_rate, target_rate):
|
| 119 |
+
if abs(in_rate - target_rate) < 1e-6:
|
| 120 |
+
return x
|
| 121 |
+
k = max(1, int(round(in_rate / target_rate)))
|
| 122 |
+
B, T, D = x.shape
|
| 123 |
+
T_new = T // k
|
| 124 |
+
if T_new == 0:
|
| 125 |
+
return x.mean(dim=1, keepdim=True)
|
| 126 |
+
return x[:, :T_new * k, :].reshape(B, T_new, k, D).mean(dim=2)
|
| 127 |
+
|
| 128 |
+
# ============================================================
|
| 129 |
+
# Align forward (unchanged)
|
| 130 |
+
# ============================================================
|
| 131 |
+
|
| 132 |
+
def get_audio_tokens(self, mel_input, audio_frames=None):
|
| 133 |
+
multi_scale = self.encoder(mel_input)
|
| 134 |
+
in_rate = self.encoder.output_frame_rate_hz
|
| 135 |
+
pooled = [self._pool_time(f, in_rate, self.target_frame_rate_hz)
|
| 136 |
+
for f in multi_scale]
|
| 137 |
+
emca_out = self.emca(pooled)
|
| 138 |
+
audio_tokens = emca_out["audio_tokens"]
|
| 139 |
+
B, T_audio, _ = audio_tokens.shape
|
| 140 |
+
audio_token_mask = None
|
| 141 |
+
if audio_frames is not None:
|
| 142 |
+
ratio = 50.0 / self.target_frame_rate_hz
|
| 143 |
+
valid = torch.ceil(audio_frames.float() / ratio).long()
|
| 144 |
+
audio_token_mask = (
|
| 145 |
+
torch.arange(T_audio, device=audio_tokens.device).unsqueeze(0)
|
| 146 |
+
< valid.unsqueeze(1)
|
| 147 |
+
).long()
|
| 148 |
+
return {
|
| 149 |
+
"audio_tokens": audio_tokens,
|
| 150 |
+
"audio_token_mask": audio_token_mask,
|
| 151 |
+
"radii_per_scale": emca_out["radii_per_scale"],
|
| 152 |
+
"c_work": emca_out["c_work"],
|
| 153 |
+
"scale_weights": emca_out["scale_weights"],
|
| 154 |
+
"scale_entropy": emca_out["scale_entropy"],
|
| 155 |
+
"attention_temp": emca_out["attention_temp"],
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
def forward(self, mel_input=None, text_input_ids=None,
|
| 159 |
+
text_attention_mask=None, labels=None, audio_frames=None,
|
| 160 |
+
**kwargs):
|
| 161 |
+
assert self.llm is not None, "Call load_llm() first."
|
| 162 |
+
bridge_out = self.get_audio_tokens(mel_input, audio_frames)
|
| 163 |
+
llm_dtype = next(self.llm.parameters()).dtype
|
| 164 |
+
audio_tokens = bridge_out["audio_tokens"].to(dtype=llm_dtype)
|
| 165 |
+
B, T_audio, _ = audio_tokens.shape
|
| 166 |
+
text_embeds = self.llm.get_input_embeddings()(text_input_ids)
|
| 167 |
+
inputs_embeds = torch.cat([audio_tokens, text_embeds], dim=1)
|
| 168 |
+
atm = bridge_out.get("audio_token_mask")
|
| 169 |
+
audio_mask = atm if atm is not None else torch.ones(
|
| 170 |
+
B, T_audio, device=audio_tokens.device, dtype=torch.long)
|
| 171 |
+
full_mask = torch.cat([audio_mask, text_attention_mask], dim=1) \
|
| 172 |
+
if text_attention_mask is not None else \
|
| 173 |
+
torch.ones(B, inputs_embeds.shape[1],
|
| 174 |
+
device=audio_tokens.device, dtype=torch.long)
|
| 175 |
+
if labels is not None:
|
| 176 |
+
audio_labels = torch.full((B, T_audio), -100,
|
| 177 |
+
device=labels.device, dtype=labels.dtype)
|
| 178 |
+
full_labels = torch.cat([audio_labels, labels], dim=1)
|
| 179 |
+
else:
|
| 180 |
+
full_labels = None
|
| 181 |
+
llm_out = self.llm(inputs_embeds=inputs_embeds,
|
| 182 |
+
attention_mask=full_mask, labels=full_labels,
|
| 183 |
+
return_dict=True)
|
| 184 |
+
bridge_out["lm_loss"] = llm_out.loss
|
| 185 |
+
bridge_out["logits"] = llm_out.logits
|
| 186 |
+
return bridge_out
|
| 187 |
+
|
| 188 |
+
@torch.no_grad()
|
| 189 |
+
def generate(self, mel_input=None, prompt_input_ids=None,
|
| 190 |
+
prompt_attention_mask=None, max_new_tokens=256,
|
| 191 |
+
audio_frames=None, **kwargs):
|
| 192 |
+
assert self.llm is not None
|
| 193 |
+
was_training = self.training
|
| 194 |
+
self.eval()
|
| 195 |
+
bridge_out = self.get_audio_tokens(mel_input, audio_frames)
|
| 196 |
+
llm_dtype = next(self.llm.parameters()).dtype
|
| 197 |
+
audio_tokens = bridge_out["audio_tokens"].to(dtype=llm_dtype)
|
| 198 |
+
B, T_audio, _ = audio_tokens.shape
|
| 199 |
+
prompt_embeds = self.llm.get_input_embeddings()(prompt_input_ids)
|
| 200 |
+
inputs_embeds = torch.cat([audio_tokens, prompt_embeds], dim=1)
|
| 201 |
+
atm = bridge_out.get("audio_token_mask")
|
| 202 |
+
audio_mask = atm if atm is not None else torch.ones(
|
| 203 |
+
B, T_audio, device=audio_tokens.device, dtype=torch.long)
|
| 204 |
+
full_mask = torch.cat([audio_mask, prompt_attention_mask], dim=1) \
|
| 205 |
+
if prompt_attention_mask is not None else \
|
| 206 |
+
torch.ones(B, inputs_embeds.shape[1],
|
| 207 |
+
device=audio_tokens.device, dtype=torch.long)
|
| 208 |
+
default_eos = getattr(self.llm.generation_config, "eos_token_id", None)
|
| 209 |
+
if default_eos is None:
|
| 210 |
+
default_eos = self.llm.config.eos_token_id
|
| 211 |
+
if isinstance(default_eos, int):
|
| 212 |
+
default_eos = [default_eos]
|
| 213 |
+
gen_kwargs = dict(inputs_embeds=inputs_embeds, attention_mask=full_mask,
|
| 214 |
+
max_new_tokens=max_new_tokens, do_sample=False,
|
| 215 |
+
eos_token_id=default_eos,
|
| 216 |
+
pad_token_id=default_eos[0] if default_eos else 0)
|
| 217 |
+
gen_kwargs.update(kwargs)
|
| 218 |
+
result = self.llm.generate(**gen_kwargs)
|
| 219 |
+
if was_training:
|
| 220 |
+
self.train()
|
| 221 |
+
return result
|
| 222 |
+
|
| 223 |
+
# ============================================================
|
| 224 |
+
# SFT extensions
|
| 225 |
+
# ============================================================
|
| 226 |
+
|
| 227 |
+
def setup_lora(self, lora_config: Dict):
|
| 228 |
+
"""Add LoRA adapters to the frozen LLM for SFT."""
|
| 229 |
+
try:
|
| 230 |
+
from peft import get_peft_model, LoraConfig, TaskType
|
| 231 |
+
except ImportError:
|
| 232 |
+
raise ImportError("pip install peft (required for SFT LoRA)")
|
| 233 |
+
default_targets = ["q_proj", "k_proj", "v_proj", "o_proj",
|
| 234 |
+
"gate_proj", "up_proj", "down_proj"]
|
| 235 |
+
cfg = LoraConfig(
|
| 236 |
+
r=lora_config.get("r", 32),
|
| 237 |
+
lora_alpha=lora_config.get("lora_alpha", 64),
|
| 238 |
+
target_modules=lora_config.get("target_modules", default_targets),
|
| 239 |
+
lora_dropout=lora_config.get("lora_dropout", 0.05),
|
| 240 |
+
bias=lora_config.get("bias", "none"),
|
| 241 |
+
task_type=TaskType.CAUSAL_LM,
|
| 242 |
+
)
|
| 243 |
+
logger.info(f"[LoRA] r={cfg.r}, alpha={cfg.lora_alpha}, "
|
| 244 |
+
f"targets={cfg.target_modules}")
|
| 245 |
+
self.llm = get_peft_model(self.llm, cfg)
|
| 246 |
+
self.llm.print_trainable_parameters()
|
| 247 |
+
self._lora_config = cfg
|
| 248 |
+
|
| 249 |
+
def get_sft_param_groups(self, base_lr: float,
|
| 250 |
+
hga_lr_scale: float = 0.3,
|
| 251 |
+
emca_lr_scale: float = 0.5):
|
| 252 |
+
hga_ids = set(id(p) for p in self.encoder.hga_layers.parameters())
|
| 253 |
+
emca_ids = set(id(p) for p in self.emca.parameters())
|
| 254 |
+
hga_p, emca_p, lora_p = [], [], []
|
| 255 |
+
for p in self.parameters():
|
| 256 |
+
if not p.requires_grad:
|
| 257 |
+
continue
|
| 258 |
+
pid = id(p)
|
| 259 |
+
if pid in hga_ids:
|
| 260 |
+
hga_p.append(p)
|
| 261 |
+
elif pid in emca_ids:
|
| 262 |
+
emca_p.append(p)
|
| 263 |
+
else:
|
| 264 |
+
lora_p.append(p)
|
| 265 |
+
groups = []
|
| 266 |
+
if lora_p:
|
| 267 |
+
groups.append({"params": lora_p, "lr": base_lr,
|
| 268 |
+
"_group_name": "lora"})
|
| 269 |
+
if emca_p:
|
| 270 |
+
groups.append({"params": emca_p, "lr": base_lr * emca_lr_scale,
|
| 271 |
+
"_group_name": "emca"})
|
| 272 |
+
if hga_p:
|
| 273 |
+
groups.append({"params": hga_p, "lr": base_lr * hga_lr_scale,
|
| 274 |
+
"_group_name": "hga"})
|
| 275 |
+
for g in groups:
|
| 276 |
+
n = sum(p.numel() for p in g["params"])
|
| 277 |
+
logger.info(f" SFT group [{g['_group_name']}]: "
|
| 278 |
+
f"{n:,} params, lr={g['lr']:.2e}")
|
| 279 |
+
return groups
|
| 280 |
+
|
| 281 |
+
# ---- multi-audio encoding ----
|
| 282 |
+
|
| 283 |
+
def encode_audio_batch(self, mel_inputs, audio_frames=None):
|
| 284 |
+
if mel_inputs is None or mel_inputs.numel() == 0:
|
| 285 |
+
return [], None
|
| 286 |
+
bridge = self.get_audio_tokens(mel_inputs, audio_frames)
|
| 287 |
+
tokens = bridge["audio_tokens"]
|
| 288 |
+
radii = bridge.get("radii_per_scale")
|
| 289 |
+
return [tokens[i] for i in range(tokens.shape[0])], radii
|
| 290 |
+
|
| 291 |
+
# ---- SFT forward ----
|
| 292 |
+
|
| 293 |
+
def forward_sft(self, mel_inputs, audio_counts, conversations, tokenizer,
|
| 294 |
+
audio_frames=None):
|
| 295 |
+
assert self.llm is not None, "Call load_llm() first."
|
| 296 |
+
device = next(self.llm.parameters()).device
|
| 297 |
+
llm_dtype = next(self.llm.parameters()).dtype
|
| 298 |
+
batch_size = len(conversations)
|
| 299 |
+
|
| 300 |
+
has_audio = (mel_inputs is not None and mel_inputs.numel() > 0)
|
| 301 |
+
if has_audio:
|
| 302 |
+
all_tokens, radii = self.encode_audio_batch(mel_inputs, audio_frames)
|
| 303 |
+
else:
|
| 304 |
+
all_tokens, radii = [], None
|
| 305 |
+
|
| 306 |
+
offset = 0
|
| 307 |
+
per_sample_tokens = []
|
| 308 |
+
for cnt in audio_counts:
|
| 309 |
+
per_sample_tokens.append(
|
| 310 |
+
[t.to(dtype=llm_dtype) for t in all_tokens[offset:offset + cnt]])
|
| 311 |
+
offset += cnt
|
| 312 |
+
|
| 313 |
+
embed_fn = self.llm.get_input_embeddings()
|
| 314 |
+
all_embeds, all_labels = [], []
|
| 315 |
+
for i in range(batch_size):
|
| 316 |
+
e, l = self._build_sft_sample(
|
| 317 |
+
conversations[i], per_sample_tokens[i],
|
| 318 |
+
tokenizer, embed_fn, device, llm_dtype,
|
| 319 |
+
generation_mode=False)
|
| 320 |
+
all_embeds.append(e)
|
| 321 |
+
all_labels.append(l)
|
| 322 |
+
|
| 323 |
+
if not all_embeds:
|
| 324 |
+
dummy = torch.tensor(0.0, device=device, requires_grad=True)
|
| 325 |
+
return {"lm_loss": dummy, "radii_per_scale": radii,
|
| 326 |
+
"c_work": torch.tensor(0.0, device=device),
|
| 327 |
+
"scale_entropy": torch.tensor(0.0, device=device)}
|
| 328 |
+
|
| 329 |
+
max_len = max(e.shape[0] for e in all_embeds)
|
| 330 |
+
pad_embeds, pad_masks, pad_labels = [], [], []
|
| 331 |
+
for e, l in zip(all_embeds, all_labels):
|
| 332 |
+
seq_len = e.shape[0]
|
| 333 |
+
gap = max_len - seq_len
|
| 334 |
+
if gap > 0:
|
| 335 |
+
e = torch.cat([e, torch.zeros(gap, e.shape[-1],
|
| 336 |
+
device=device, dtype=llm_dtype)])
|
| 337 |
+
l = torch.cat([l, torch.full((gap,), -100,
|
| 338 |
+
device=device, dtype=torch.long)])
|
| 339 |
+
amask = torch.cat([
|
| 340 |
+
torch.ones(seq_len, device=device, dtype=torch.long),
|
| 341 |
+
torch.zeros(gap, device=device, dtype=torch.long),
|
| 342 |
+
]) if gap > 0 else torch.ones(max_len, device=device,
|
| 343 |
+
dtype=torch.long)
|
| 344 |
+
pad_embeds.append(e)
|
| 345 |
+
pad_masks.append(amask)
|
| 346 |
+
pad_labels.append(l)
|
| 347 |
+
|
| 348 |
+
llm_out = self.llm(
|
| 349 |
+
inputs_embeds=torch.stack(pad_embeds),
|
| 350 |
+
attention_mask=torch.stack(pad_masks),
|
| 351 |
+
labels=torch.stack(pad_labels),
|
| 352 |
+
return_dict=True)
|
| 353 |
+
|
| 354 |
+
return {
|
| 355 |
+
"lm_loss": llm_out.loss,
|
| 356 |
+
"logits": llm_out.logits,
|
| 357 |
+
"radii_per_scale": radii,
|
| 358 |
+
"c_work": self.emca.c_work().detach() if radii is not None
|
| 359 |
+
else torch.tensor(0.0, device=device),
|
| 360 |
+
"scale_entropy": torch.tensor(0.0, device=device),
|
| 361 |
+
}
|
| 362 |
+
|
| 363 |
+
# ---- build one sample ----
|
| 364 |
+
|
| 365 |
+
def _build_sft_sample(self, conversation, audio_tokens, tokenizer,
|
| 366 |
+
embed_fn, device, dtype, generation_mode=False):
|
| 367 |
+
"""Build input embeds + labels for one SFT sample.
|
| 368 |
+
|
| 369 |
+
generation_mode=True: emit only up to the assistant prefix
|
| 370 |
+
(<|im_start|>assistant\\n), then stop.
|
| 371 |
+
No response text, no <|im_end|>.
|
| 372 |
+
"""
|
| 373 |
+
segs_e, segs_l = [], []
|
| 374 |
+
n_aud = len(audio_tokens)
|
| 375 |
+
|
| 376 |
+
def _tok(text):
|
| 377 |
+
return tokenizer.encode(text, add_special_tokens=False)
|
| 378 |
+
|
| 379 |
+
def _embed(ids):
|
| 380 |
+
return embed_fn(torch.tensor(ids, device=device, dtype=torch.long))
|
| 381 |
+
|
| 382 |
+
def _text_parts(parts):
|
| 383 |
+
return "".join(
|
| 384 |
+
p.get("content", "") or p.get("text", "")
|
| 385 |
+
for p in parts if p.get("type") == "text")
|
| 386 |
+
|
| 387 |
+
for msg in conversation:
|
| 388 |
+
role = msg.get("role", "")
|
| 389 |
+
parts = msg.get("parts", [])
|
| 390 |
+
|
| 391 |
+
if role == "system":
|
| 392 |
+
txt = _text_parts(parts)
|
| 393 |
+
ids = _tok(f"<|im_start|>system\n{txt}<|im_end|>\n")
|
| 394 |
+
if ids:
|
| 395 |
+
segs_e.append(_embed(ids))
|
| 396 |
+
segs_l.extend([-100] * len(ids))
|
| 397 |
+
|
| 398 |
+
elif role == "user":
|
| 399 |
+
pre = _tok("<|im_start|>user\n")
|
| 400 |
+
if pre:
|
| 401 |
+
segs_e.append(_embed(pre))
|
| 402 |
+
segs_l.extend([-100] * len(pre))
|
| 403 |
+
for p in parts:
|
| 404 |
+
pt = p.get("type", "")
|
| 405 |
+
if pt == "audio":
|
| 406 |
+
idx = p.get("audio_index", -1)
|
| 407 |
+
if 0 <= idx < n_aud:
|
| 408 |
+
at = audio_tokens[idx]
|
| 409 |
+
# Boundary markers: <|audio_start|> ... <|audio_end|>
|
| 410 |
+
segs_e.append(self.audio_start_embed.unsqueeze(0).to(dtype=dtype))
|
| 411 |
+
segs_l.append(-100)
|
| 412 |
+
segs_e.append(at)
|
| 413 |
+
segs_l.extend([-100] * at.shape[0])
|
| 414 |
+
segs_e.append(self.audio_end_embed.unsqueeze(0).to(dtype=dtype))
|
| 415 |
+
segs_l.append(-100)
|
| 416 |
+
elif pt == "text":
|
| 417 |
+
txt = p.get("content", "") or p.get("text", "")
|
| 418 |
+
if txt:
|
| 419 |
+
ids = _tok(txt)
|
| 420 |
+
if ids:
|
| 421 |
+
segs_e.append(_embed(ids))
|
| 422 |
+
segs_l.extend([-100] * len(ids))
|
| 423 |
+
suf = _tok("<|im_end|>\n")
|
| 424 |
+
if suf:
|
| 425 |
+
segs_e.append(_embed(suf))
|
| 426 |
+
segs_l.extend([-100] * len(suf))
|
| 427 |
+
|
| 428 |
+
elif role == "assistant":
|
| 429 |
+
# Standard ChatML assistant prefix (no thinking placeholder)
|
| 430 |
+
pre = _tok("<|im_start|>assistant\n")
|
| 431 |
+
if pre:
|
| 432 |
+
segs_e.append(_embed(pre))
|
| 433 |
+
segs_l.extend([-100] * len(pre))
|
| 434 |
+
|
| 435 |
+
# ---- generation_mode: STOP HERE ----
|
| 436 |
+
# No response text, no <|im_end|>.
|
| 437 |
+
# LLM continues generating from this point.
|
| 438 |
+
if generation_mode:
|
| 439 |
+
break
|
| 440 |
+
|
| 441 |
+
# Training mode: add response (compute loss) + eos
|
| 442 |
+
txt = _text_parts(parts)
|
| 443 |
+
if txt:
|
| 444 |
+
resp_ids = _tok(txt)
|
| 445 |
+
if resp_ids:
|
| 446 |
+
segs_e.append(_embed(resp_ids))
|
| 447 |
+
segs_l.extend(resp_ids)
|
| 448 |
+
eos = _tok("<|im_end|>")
|
| 449 |
+
if eos:
|
| 450 |
+
segs_e.append(_embed(eos))
|
| 451 |
+
segs_l.extend(eos)
|
| 452 |
+
|
| 453 |
+
if not segs_e:
|
| 454 |
+
placeholder = _embed([tokenizer.pad_token_id or 0])
|
| 455 |
+
return placeholder, torch.tensor([-100], device=device,
|
| 456 |
+
dtype=torch.long)
|
| 457 |
+
return (torch.cat(segs_e, dim=0),
|
| 458 |
+
torch.tensor(segs_l, device=device, dtype=torch.long))
|
| 459 |
+
|
| 460 |
+
# ---- SFT generate ----
|
| 461 |
+
|
| 462 |
+
@torch.no_grad()
|
| 463 |
+
def generate_sft(self, mel_inputs, audio_counts, conversations, tokenizer,
|
| 464 |
+
max_new_tokens=256, audio_frames=None, **kwargs):
|
| 465 |
+
assert self.llm is not None
|
| 466 |
+
was_training = self.training
|
| 467 |
+
self.eval()
|
| 468 |
+
device = next(self.llm.parameters()).device
|
| 469 |
+
llm_dtype = next(self.llm.parameters()).dtype
|
| 470 |
+
|
| 471 |
+
if mel_inputs is not None and mel_inputs.numel() > 0:
|
| 472 |
+
all_tokens, _ = self.encode_audio_batch(mel_inputs, audio_frames)
|
| 473 |
+
else:
|
| 474 |
+
all_tokens = []
|
| 475 |
+
offset = 0
|
| 476 |
+
per_sample = []
|
| 477 |
+
for cnt in audio_counts:
|
| 478 |
+
per_sample.append(
|
| 479 |
+
[t.to(dtype=llm_dtype) for t in all_tokens[offset:offset + cnt]])
|
| 480 |
+
offset += cnt
|
| 481 |
+
|
| 482 |
+
embed_fn = self.llm.get_input_embeddings()
|
| 483 |
+
results = []
|
| 484 |
+
for i, conv in enumerate(conversations):
|
| 485 |
+
# generation_mode=True → stops after assistant prefix,
|
| 486 |
+
# no <|im_end|>, model continues generating.
|
| 487 |
+
e, _ = self._build_sft_sample(
|
| 488 |
+
conv, per_sample[i], tokenizer, embed_fn, device, llm_dtype,
|
| 489 |
+
generation_mode=True)
|
| 490 |
+
embeds = e.unsqueeze(0)
|
| 491 |
+
mask = torch.ones(1, embeds.shape[1], device=device, dtype=torch.long)
|
| 492 |
+
|
| 493 |
+
default_eos = getattr(self.llm.generation_config,
|
| 494 |
+
"eos_token_id", None)
|
| 495 |
+
if default_eos is None:
|
| 496 |
+
default_eos = getattr(self.llm.config, "eos_token_id", None)
|
| 497 |
+
if isinstance(default_eos, int):
|
| 498 |
+
default_eos = [default_eos]
|
| 499 |
+
|
| 500 |
+
gen_kwargs = dict(
|
| 501 |
+
inputs_embeds=embeds, attention_mask=mask,
|
| 502 |
+
max_new_tokens=max_new_tokens, do_sample=False,
|
| 503 |
+
eos_token_id=default_eos,
|
| 504 |
+
pad_token_id=default_eos[0] if default_eos else 0)
|
| 505 |
+
gen_kwargs.update(kwargs)
|
| 506 |
+
gen_ids = self.llm.generate(**gen_kwargs)
|
| 507 |
+
text = tokenizer.decode(gen_ids[0], skip_special_tokens=True)
|
| 508 |
+
results.append(text)
|
| 509 |
+
|
| 510 |
+
if was_training:
|
| 511 |
+
self.train()
|
| 512 |
+
return results
|
thinker/text_utils.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Text utilities for V4 multi-task evaluation.
|
| 3 |
+
Includes: WER/CER (from v3) + accuracy + F1 + simple BLEU.
|
| 4 |
+
"""
|
| 5 |
+
import re
|
| 6 |
+
import unicodedata
|
| 7 |
+
from collections import Counter
|
| 8 |
+
|
| 9 |
+
# =============================================================
|
| 10 |
+
# Language detection & normalization (from v3)
|
| 11 |
+
# =============================================================
|
| 12 |
+
def detect_language(text: str) -> str:
|
| 13 |
+
if not text: return "en"
|
| 14 |
+
cjk = sum(1 for c in text if '\u4e00' <= c <= '\u9fff')
|
| 15 |
+
return "zh" if cjk / max(len(text), 1) >= 0.3 else "en"
|
| 16 |
+
|
| 17 |
+
def normalize_text(text: str, lang: str = None) -> str:
|
| 18 |
+
if lang is None: lang = detect_language(text)
|
| 19 |
+
text = text.strip().lower()
|
| 20 |
+
text = unicodedata.normalize("NFKC", text)
|
| 21 |
+
text = re.sub(r'[^\w\s]', '', text)
|
| 22 |
+
if lang == "zh":
|
| 23 |
+
text = re.sub(r'\s+', '', text)
|
| 24 |
+
else:
|
| 25 |
+
text = re.sub(r'\s+', ' ', text).strip()
|
| 26 |
+
return text
|
| 27 |
+
|
| 28 |
+
# =============================================================
|
| 29 |
+
# WER / CER
|
| 30 |
+
# =============================================================
|
| 31 |
+
def _edit_distance(a, b):
|
| 32 |
+
m, n = len(a), len(b)
|
| 33 |
+
dp = list(range(n + 1))
|
| 34 |
+
for i in range(1, m + 1):
|
| 35 |
+
prev, dp[0] = dp[0], i
|
| 36 |
+
for j in range(1, n + 1):
|
| 37 |
+
temp = dp[j]
|
| 38 |
+
dp[j] = prev if a[i-1] == b[j-1] else 1 + min(dp[j], dp[j-1], prev)
|
| 39 |
+
prev = temp
|
| 40 |
+
return dp[n]
|
| 41 |
+
|
| 42 |
+
def compute_wer(ref: str, hyp: str) -> float:
|
| 43 |
+
ref_w = normalize_text(ref, "en").split()
|
| 44 |
+
hyp_w = normalize_text(hyp, "en").split()
|
| 45 |
+
if not ref_w: return 0.0 if not hyp_w else float(len(hyp_w))
|
| 46 |
+
return _edit_distance(ref_w, hyp_w) / len(ref_w)
|
| 47 |
+
|
| 48 |
+
def compute_cer(ref: str, hyp: str) -> float:
|
| 49 |
+
ref_c = list(normalize_text(ref, "zh"))
|
| 50 |
+
hyp_c = list(normalize_text(hyp, "zh"))
|
| 51 |
+
if not ref_c: return 0.0 if not hyp_c else float(len(hyp_c))
|
| 52 |
+
return _edit_distance(ref_c, hyp_c) / len(ref_c)
|
| 53 |
+
|
| 54 |
+
# =============================================================
|
| 55 |
+
# Accuracy (exact match after normalization)
|
| 56 |
+
# =============================================================
|
| 57 |
+
def compute_accuracy(refs: list, hyps: list) -> float:
|
| 58 |
+
if not refs: return 0.0
|
| 59 |
+
correct = 0
|
| 60 |
+
for r, h in zip(refs, hyps):
|
| 61 |
+
rn = normalize_text(r).strip()
|
| 62 |
+
hn = normalize_text(h).strip()
|
| 63 |
+
if rn == hn: correct += 1
|
| 64 |
+
return correct / len(refs)
|
| 65 |
+
|
| 66 |
+
# =============================================================
|
| 67 |
+
# F1 for comma-separated labels (audio events)
|
| 68 |
+
# =============================================================
|
| 69 |
+
def compute_label_f1(refs: list, hyps: list) -> float:
|
| 70 |
+
"""Macro-averaged F1 over samples. Each ref/hyp is comma-separated labels."""
|
| 71 |
+
if not refs: return 0.0
|
| 72 |
+
total_f1 = 0.0
|
| 73 |
+
for r, h in zip(refs, hyps):
|
| 74 |
+
ref_set = set(x.strip().lower() for x in r.split(",") if x.strip())
|
| 75 |
+
hyp_set = set(x.strip().lower() for x in h.split(",") if x.strip())
|
| 76 |
+
if not ref_set and not hyp_set:
|
| 77 |
+
total_f1 += 1.0; continue
|
| 78 |
+
if not ref_set or not hyp_set:
|
| 79 |
+
continue
|
| 80 |
+
tp = len(ref_set & hyp_set)
|
| 81 |
+
prec = tp / len(hyp_set) if hyp_set else 0
|
| 82 |
+
rec = tp / len(ref_set) if ref_set else 0
|
| 83 |
+
total_f1 += 2*prec*rec / (prec+rec) if (prec+rec) > 0 else 0
|
| 84 |
+
return total_f1 / len(refs)
|
| 85 |
+
|
| 86 |
+
# =============================================================
|
| 87 |
+
# Simple BLEU-4 (sentence level, for translation)
|
| 88 |
+
# =============================================================
|
| 89 |
+
def _ngrams(tokens, n):
|
| 90 |
+
return [tuple(tokens[i:i+n]) for i in range(len(tokens)-n+1)]
|
| 91 |
+
|
| 92 |
+
def compute_bleu4(refs: list, hyps: list) -> float:
|
| 93 |
+
if not refs: return 0.0
|
| 94 |
+
total = 0.0
|
| 95 |
+
for r, h in zip(refs, hyps):
|
| 96 |
+
ref_tok = normalize_text(r).split() or list(normalize_text(r))
|
| 97 |
+
hyp_tok = normalize_text(h).split() or list(normalize_text(h))
|
| 98 |
+
if not ref_tok or not hyp_tok: continue
|
| 99 |
+
bp = min(1.0, len(hyp_tok) / len(ref_tok)) if ref_tok else 0
|
| 100 |
+
score = bp
|
| 101 |
+
for n in range(1, 5):
|
| 102 |
+
ref_ng = Counter(_ngrams(ref_tok, n))
|
| 103 |
+
hyp_ng = Counter(_ngrams(hyp_tok, n))
|
| 104 |
+
matches = sum((hyp_ng & ref_ng).values())
|
| 105 |
+
total_hyp = max(sum(hyp_ng.values()), 1)
|
| 106 |
+
prec = matches / total_hyp
|
| 107 |
+
score *= max(prec, 1e-10) ** 0.25
|
| 108 |
+
total += score
|
| 109 |
+
return total / len(refs)
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_bos_token": false,
|
| 3 |
+
"add_prefix_space": false,
|
| 4 |
+
"added_tokens_decoder": {
|
| 5 |
+
"151643": {
|
| 6 |
+
"content": "<|endoftext|>",
|
| 7 |
+
"lstrip": false,
|
| 8 |
+
"normalized": false,
|
| 9 |
+
"rstrip": false,
|
| 10 |
+
"single_word": false,
|
| 11 |
+
"special": true
|
| 12 |
+
},
|
| 13 |
+
"151644": {
|
| 14 |
+
"content": "<|im_start|>",
|
| 15 |
+
"lstrip": false,
|
| 16 |
+
"normalized": false,
|
| 17 |
+
"rstrip": false,
|
| 18 |
+
"single_word": false,
|
| 19 |
+
"special": true
|
| 20 |
+
},
|
| 21 |
+
"151645": {
|
| 22 |
+
"content": "<|im_end|>",
|
| 23 |
+
"lstrip": false,
|
| 24 |
+
"normalized": false,
|
| 25 |
+
"rstrip": false,
|
| 26 |
+
"single_word": false,
|
| 27 |
+
"special": true
|
| 28 |
+
},
|
| 29 |
+
"151646": {
|
| 30 |
+
"content": "<|object_ref_start|>",
|
| 31 |
+
"lstrip": false,
|
| 32 |
+
"normalized": false,
|
| 33 |
+
"rstrip": false,
|
| 34 |
+
"single_word": false,
|
| 35 |
+
"special": true
|
| 36 |
+
},
|
| 37 |
+
"151647": {
|
| 38 |
+
"content": "<|object_ref_end|>",
|
| 39 |
+
"lstrip": false,
|
| 40 |
+
"normalized": false,
|
| 41 |
+
"rstrip": false,
|
| 42 |
+
"single_word": false,
|
| 43 |
+
"special": true
|
| 44 |
+
},
|
| 45 |
+
"151648": {
|
| 46 |
+
"content": "<|box_start|>",
|
| 47 |
+
"lstrip": false,
|
| 48 |
+
"normalized": false,
|
| 49 |
+
"rstrip": false,
|
| 50 |
+
"single_word": false,
|
| 51 |
+
"special": true
|
| 52 |
+
},
|
| 53 |
+
"151649": {
|
| 54 |
+
"content": "<|box_end|>",
|
| 55 |
+
"lstrip": false,
|
| 56 |
+
"normalized": false,
|
| 57 |
+
"rstrip": false,
|
| 58 |
+
"single_word": false,
|
| 59 |
+
"special": true
|
| 60 |
+
},
|
| 61 |
+
"151650": {
|
| 62 |
+
"content": "<|quad_start|>",
|
| 63 |
+
"lstrip": false,
|
| 64 |
+
"normalized": false,
|
| 65 |
+
"rstrip": false,
|
| 66 |
+
"single_word": false,
|
| 67 |
+
"special": true
|
| 68 |
+
},
|
| 69 |
+
"151651": {
|
| 70 |
+
"content": "<|quad_end|>",
|
| 71 |
+
"lstrip": false,
|
| 72 |
+
"normalized": false,
|
| 73 |
+
"rstrip": false,
|
| 74 |
+
"single_word": false,
|
| 75 |
+
"special": true
|
| 76 |
+
},
|
| 77 |
+
"151652": {
|
| 78 |
+
"content": "<|vision_start|>",
|
| 79 |
+
"lstrip": false,
|
| 80 |
+
"normalized": false,
|
| 81 |
+
"rstrip": false,
|
| 82 |
+
"single_word": false,
|
| 83 |
+
"special": true
|
| 84 |
+
},
|
| 85 |
+
"151653": {
|
| 86 |
+
"content": "<|vision_end|>",
|
| 87 |
+
"lstrip": false,
|
| 88 |
+
"normalized": false,
|
| 89 |
+
"rstrip": false,
|
| 90 |
+
"single_word": false,
|
| 91 |
+
"special": true
|
| 92 |
+
},
|
| 93 |
+
"151654": {
|
| 94 |
+
"content": "<|vision_pad|>",
|
| 95 |
+
"lstrip": false,
|
| 96 |
+
"normalized": false,
|
| 97 |
+
"rstrip": false,
|
| 98 |
+
"single_word": false,
|
| 99 |
+
"special": true
|
| 100 |
+
},
|
| 101 |
+
"151655": {
|
| 102 |
+
"content": "<|image_pad|>",
|
| 103 |
+
"lstrip": false,
|
| 104 |
+
"normalized": false,
|
| 105 |
+
"rstrip": false,
|
| 106 |
+
"single_word": false,
|
| 107 |
+
"special": true
|
| 108 |
+
},
|
| 109 |
+
"151656": {
|
| 110 |
+
"content": "<|video_pad|>",
|
| 111 |
+
"lstrip": false,
|
| 112 |
+
"normalized": false,
|
| 113 |
+
"rstrip": false,
|
| 114 |
+
"single_word": false,
|
| 115 |
+
"special": true
|
| 116 |
+
},
|
| 117 |
+
"151657": {
|
| 118 |
+
"content": "<tool_call>",
|
| 119 |
+
"lstrip": false,
|
| 120 |
+
"normalized": false,
|
| 121 |
+
"rstrip": false,
|
| 122 |
+
"single_word": false,
|
| 123 |
+
"special": false
|
| 124 |
+
},
|
| 125 |
+
"151658": {
|
| 126 |
+
"content": "</tool_call>",
|
| 127 |
+
"lstrip": false,
|
| 128 |
+
"normalized": false,
|
| 129 |
+
"rstrip": false,
|
| 130 |
+
"single_word": false,
|
| 131 |
+
"special": false
|
| 132 |
+
},
|
| 133 |
+
"151659": {
|
| 134 |
+
"content": "<|fim_prefix|>",
|
| 135 |
+
"lstrip": false,
|
| 136 |
+
"normalized": false,
|
| 137 |
+
"rstrip": false,
|
| 138 |
+
"single_word": false,
|
| 139 |
+
"special": false
|
| 140 |
+
},
|
| 141 |
+
"151660": {
|
| 142 |
+
"content": "<|fim_middle|>",
|
| 143 |
+
"lstrip": false,
|
| 144 |
+
"normalized": false,
|
| 145 |
+
"rstrip": false,
|
| 146 |
+
"single_word": false,
|
| 147 |
+
"special": false
|
| 148 |
+
},
|
| 149 |
+
"151661": {
|
| 150 |
+
"content": "<|fim_suffix|>",
|
| 151 |
+
"lstrip": false,
|
| 152 |
+
"normalized": false,
|
| 153 |
+
"rstrip": false,
|
| 154 |
+
"single_word": false,
|
| 155 |
+
"special": false
|
| 156 |
+
},
|
| 157 |
+
"151662": {
|
| 158 |
+
"content": "<|fim_pad|>",
|
| 159 |
+
"lstrip": false,
|
| 160 |
+
"normalized": false,
|
| 161 |
+
"rstrip": false,
|
| 162 |
+
"single_word": false,
|
| 163 |
+
"special": false
|
| 164 |
+
},
|
| 165 |
+
"151663": {
|
| 166 |
+
"content": "<|repo_name|>",
|
| 167 |
+
"lstrip": false,
|
| 168 |
+
"normalized": false,
|
| 169 |
+
"rstrip": false,
|
| 170 |
+
"single_word": false,
|
| 171 |
+
"special": false
|
| 172 |
+
},
|
| 173 |
+
"151664": {
|
| 174 |
+
"content": "<|file_sep|>",
|
| 175 |
+
"lstrip": false,
|
| 176 |
+
"normalized": false,
|
| 177 |
+
"rstrip": false,
|
| 178 |
+
"single_word": false,
|
| 179 |
+
"special": false
|
| 180 |
+
}
|
| 181 |
+
},
|
| 182 |
+
"additional_special_tokens": [
|
| 183 |
+
"<|im_start|>",
|
| 184 |
+
"<|im_end|>",
|
| 185 |
+
"<|object_ref_start|>",
|
| 186 |
+
"<|object_ref_end|>",
|
| 187 |
+
"<|box_start|>",
|
| 188 |
+
"<|box_end|>",
|
| 189 |
+
"<|quad_start|>",
|
| 190 |
+
"<|quad_end|>",
|
| 191 |
+
"<|vision_start|>",
|
| 192 |
+
"<|vision_end|>",
|
| 193 |
+
"<|vision_pad|>",
|
| 194 |
+
"<|image_pad|>",
|
| 195 |
+
"<|video_pad|>"
|
| 196 |
+
],
|
| 197 |
+
"bos_token": null,
|
| 198 |
+
"chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0]['role'] == 'system' %}\n {{- messages[0]['content'] }}\n {%- else %}\n {{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }}\n {%- endif %}\n {{- \"\\n\\n# 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>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0]['role'] == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>system\\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) or (message.role == \"assistant\" and not message.tool_calls) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role }}\n {%- if message.content %}\n {{- '\\n' + message.content }}\n {%- endif %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '\\n<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n",
|
| 199 |
+
"clean_up_tokenization_spaces": false,
|
| 200 |
+
"eos_token": "<|im_end|>",
|
| 201 |
+
"errors": "replace",
|
| 202 |
+
"model_max_length": 131072,
|
| 203 |
+
"pad_token": "<|endoftext|>",
|
| 204 |
+
"split_special_tokens": false,
|
| 205 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
| 206 |
+
"unk_token": null
|
| 207 |
+
}
|
vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|