Add files using upload-large-folder tool
Browse filesFiles changed (22)
- README.md+34-3
- __init__.pyAdded+3
- bridge.ptAdded+3
- config.jsonAdded+52
- configuration_hga_thinker.pyAdded+94
- lora/README.mdAdded+207
- lora/adapter_config.jsonAdded+48
- lora/adapter_model.safetensorsAdded+3
- merges.txtAdded
- modeling_hga_thinker.pyAdded+332
- preprocessor_config.jsonAdded+14
- processor_config.jsonAdded+6
- thinker/__init__.pyAdded+1
- thinker/config.pyAdded+157
- thinker/emca.pyAdded+181
- thinker/encoder.pyAdded+253
- thinker/hyperbolic_ops.pyAdded+126
- thinker/model.pyAdded+512
- thinker/text_utils.pyAdded+109
- tokenizer.jsonAdded
- tokenizer_config.jsonAdded+207
- vocab.jsonAdded
123---license: apache-2.0---12345678910111213141516171819202122232425262728293031323334# HGA_Thinker_7B_v2_exportHGA-Thinker speech LM exported from SFT training (current train_sft.py format).## Layout- `bridge.pt` — HGA (s/b/c on 32 Whisper layers) + EMCA + audio boundary embeds- `lora/` — PEFT LoRA adapter for the LLM (has_lora=True)- `config.json` — HGAThinkerConfig (llm_dim=3584)- `processor_config.json` — inference defaults- `tokenizer.*` — Qwen2.5 tokenizer- `preprocessor_config.json` — WhisperFeatureExtractor config- `configuration_hga_thinker.py`, `modeling_hga_thinker.py`, `thinker/` —frozen inference code (so this dir loads without the training repo)## Base models- whisper: `/apdcephfs_hzlf/share_1227201/zefeng/whisper-large-v3`- llm: `/apdcephfs_hzlf/share_1227201/zefeng/Qwen2.5-7B-Instruct`- bundled: `False` trained_steps: `6000`## Load & run```pythonimport sys; sys.path.insert(0, ".") # this dirfrom modeling_hga_thinker import HGAThinkerForConditionalGenerationmodel = HGAThinkerForConditionalGeneration.from_pretrained(".", device="cuda")# If base models moved since export, pass overrides:# ...from_pretrained(".", whisper_path="/new/whisper", llm_name="/new/qwen")text = model.chat(audio="test.wav", query="Transcribe this audio.",max_new_tokens=256)print(text)```Needs `peft` and (for audio path inputs) `torchaudio` installed.
123from .configuration_hga_thinker import HGAThinkerConfigfrom .modeling_hga_thinker import ( HGAThinkerForConditionalGeneration, HGAThinkerProcessor)123version https://git-lfs.github.com/spec/v1oid sha256:ab2261431e599ce92a84d55d457de9595621955acd9c42415e851494f2d9b29dsize 20188071712345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152{ "assistant_prefix": "<|im_start|>assistant\n", "bundled": false, "dtype": "bfloat16", "emca_c_work_init": 0.5, "emca_c_work_max": 4.0, "emca_c_work_min": 0.01, "encoder_dim": 1280, "extract_layers": [ 3, 7, 11, 15, 19, 23, 27, 31 ], "freeze_llm": true, "has_lora": true, "hga_b_init_std": 0.0001, "hga_c_init": 1.0, "hga_c_max": 8.0, "hga_c_min": 0.001, "llm_dim": 3584, "llm_name": "/apdcephfs_hzlf/share_1227201/zefeng/Qwen2.5-7B-Instruct", "lora": { "bias": "none", "lora_alpha": 64, "lora_dropout": 0.05, "r": 32, "target_modules": [ "k_proj", "v_proj", "up_proj", "o_proj", "down_proj", "q_proj", "gate_proj" ] }, "max_audio_length": 30.0, "model_type": "hga_thinker", "num_whisper_layers": 32, "projector_hidden": 4096, "sample_rate": 16000, "system_prompt": "You are a helpful assistant that analyzes audio content.", "target_frame_rate_hz": 12.5, "trained_steps": 6000, "transformers_version": "4.57.0", "whisper_path": "/apdcephfs_hzlf/share_1227201/zefeng/whisper-large-v3"}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394"""HGA-Thinker HuggingFace-style configuration.
This mirrors the architecture-relevant fields of `thinker.config.ThinkerConfig`so that an exported model directory can be reconstructed identically to how itwas assembled at training time.
Only the fields needed to *rebuild the model graph and load weights* are kepthere — training-only knobs (learning rates, dataset paths, eval cadence, …)are intentionally dropped, since they have no bearing on inference.
The values below default to the current training configuration(Qwen2.5-7B-Instruct + whisper-large-v3, 32 Whisper layers, llm_dim=3584).`export.py` overwrites the path/flag fields from the actual checkpoint, so younormally never edit this by hand."""from transformers import PretrainedConfig
class HGAThinkerConfig(PretrainedConfig): model_type = "hga_thinker"
def __init__( self, # ---- Whisper encoder ---- whisper_path: str = "openai/whisper-large-v3", encoder_dim: int = 1280, num_whisper_layers: int = 32, extract_layers=None, # default [3,7,11,15,19,23,27,31] target_frame_rate_hz: float = 12.5, # ---- HGA (per-layer Q/K/V modulation) ---- hga_c_init: float = 1.0, hga_c_min: float = 0.001, hga_c_max: float = 8.0, hga_b_init_std: float = 1.0e-4, # ---- EMCA ---- emca_c_work_init: float = 0.5, emca_c_work_min: float = 0.01, emca_c_work_max: float = 4.0, projector_hidden: int = 4096, # ---- LLM ---- llm_name: str = "Qwen/Qwen2.5-7B-Instruct", llm_dim: int = 3584, freeze_llm: bool = True, # ---- LoRA (SFT) ---- lora: dict = None, has_lora: bool = False, # ---- Inference defaults ---- system_prompt: str = "You are a helpful assistant that analyzes audio content.", assistant_prefix: str = "<|im_start|>assistant\n", sample_rate: int = 16000, max_audio_length: float = 30.0, torch_dtype: str = "bfloat16", # ---- Layout / provenance ---- bundled: bool = False, # True if whisper/ or llm/ copied into dir trained_steps: int = -1, **kwargs, ): self.whisper_path = whisper_path self.encoder_dim = encoder_dim self.num_whisper_layers = num_whisper_layers self.extract_layers = ( list(extract_layers) if extract_layers is not None else [3, 7, 11, 15, 19, 23, 27, 31] ) self.target_frame_rate_hz = target_frame_rate_hz
self.hga_c_init = hga_c_init self.hga_c_min = hga_c_min self.hga_c_max = hga_c_max self.hga_b_init_std = hga_b_init_std
self.emca_c_work_init = emca_c_work_init self.emca_c_work_min = emca_c_work_min self.emca_c_work_max = emca_c_work_max self.projector_hidden = projector_hidden
self.llm_name = llm_name self.llm_dim = llm_dim self.freeze_llm = freeze_llm
self.lora = lora self.has_lora = has_lora
self.system_prompt = system_prompt self.assistant_prefix = assistant_prefix self.sample_rate = sample_rate self.max_audio_length = max_audio_length
self.bundled = bundled self.trained_steps = trained_steps
# PretrainedConfig handles torch_dtype specially; pass through kwargs. super().__init__(torch_dtype=torch_dtype, **kwargs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207---base_model: /apdcephfs_hzlf/share_1227201/zefeng/Qwen2.5-7B-Instructlibrary_name: peftpipeline_tag: text-generationtags:- base_model:adapter:/apdcephfs_hzlf/share_1227201/zefeng/Qwen2.5-7B-Instruct- lora- transformers---
# Model Card for Model ID
<!-- Provide a quick summary of what the model is/does. -->
## Model Details
### Model Description
<!-- Provide a longer summary of what this model is. -->
- **Developed by:** [More Information Needed]- **Funded by [optional]:** [More Information Needed]- **Shared by [optional]:** [More Information Needed]- **Model type:** [More Information Needed]- **Language(s) (NLP):** [More Information Needed]- **License:** [More Information Needed]- **Finetuned from model [optional]:** [More Information Needed]
### Model Sources [optional]
<!-- Provide the basic links for the model. -->
- **Repository:** [More Information Needed]- **Paper [optional]:** [More Information Needed]- **Demo [optional]:** [More Information Needed]
## Uses
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
### Direct Use
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
[More Information Needed]
### Downstream Use [optional]
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
[More Information Needed]
### Out-of-Scope Use
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
[More Information Needed]
## Bias, Risks, and Limitations
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
[More Information Needed]
### Recommendations
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
## How to Get Started with the Model
Use the code below to get started with the model.
[More Information Needed]
## Training Details
### Training Data
<!-- 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. -->
[More Information Needed]
### Training Procedure
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
#### Preprocessing [optional]
[More Information Needed]
#### Training Hyperparameters
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
#### Speeds, Sizes, Times [optional]
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
[More Information Needed]
## Evaluation
<!-- This section describes the evaluation protocols and provides the results. -->
### Testing Data, Factors & Metrics
#### Testing Data
<!-- This should link to a Dataset Card if possible. -->
[More Information Needed]
#### Factors
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
[More Information Needed]
#### Metrics
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
[More Information Needed]
### Results
[More Information Needed]
#### Summary
## Model Examination [optional]
<!-- Relevant interpretability work for the model goes here -->
[More Information Needed]
## Environmental Impact
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
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).
- **Hardware Type:** [More Information Needed]- **Hours used:** [More Information Needed]- **Cloud Provider:** [More Information Needed]- **Compute Region:** [More Information Needed]- **Carbon Emitted:** [More Information Needed]
## Technical Specifications [optional]
### Model Architecture and Objective
[More Information Needed]
### Compute Infrastructure
[More Information Needed]
#### Hardware
[More Information Needed]
#### Software
[More Information Needed]
## Citation [optional]
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
**BibTeX:**
[More Information Needed]
**APA:**
[More Information Needed]
## Glossary [optional]
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
[More Information Needed]
## More Information [optional]
[More Information Needed]
## Model Card Authors [optional]
[More Information Needed]
## Model Card Contact
[More Information Needed]### Framework versions
- PEFT 0.19.1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748{ "alora_invocation_tokens": null, "alpha_pattern": {}, "arrow_config": null, "auto_mapping": null, "base_model_name_or_path": "/apdcephfs_hzlf/share_1227201/zefeng/Qwen2.5-7B-Instruct", "bias": "none", "corda_config": null, "ensure_weight_tying": false, "eva_config": null, "exclude_modules": null, "fan_in_fan_out": false, "inference_mode": true, "init_lora_weights": true, "layer_replication": null, "layers_pattern": null, "layers_to_transform": null, "loftq_config": {}, "lora_alpha": 64, "lora_bias": false, "lora_dropout": 0.05, "lora_ga_config": null, "megatron_config": null, "megatron_core": "megatron.core", "modules_to_save": null, "peft_type": "LORA", "peft_version": "0.19.1", "qalora_group_size": 16, "r": 32, "rank_pattern": {}, "revision": null, "target_modules": [ "k_proj", "v_proj", "up_proj", "o_proj", "down_proj", "q_proj", "gate_proj" ], "target_parameters": null, "task_type": "CAUSAL_LM", "trainable_token_indices": null, "use_bdlora": null, "use_dora": false, "use_qalora": false, "use_rslora": false}123version https://git-lfs.github.com/spec/v1oid sha256:76d408900d3ecd1eadaf148993f5671108db1a8d4f2b1e983d95d992dfdcd8fasize 161533584123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332"""HGA-Thinker HuggingFace-loadable wrapper.
This is a *thin* wrapper around the training-time `thinker.model.ThinkerModel`.It does NOT reimplement the architecture — it imports the exact same modulesused during training, so the inference graph is byte-for-byte identical to whatproduced the checkpoint.
Assembly order (mirrors thinker/train_sft.py main()): 1. ThinkerModel(thinker_config) # builds encoder(HGA) + EMCA 2. AutoModelForCausalLM.from_pretrained(llm) # bf16, trust_remote_code model.load_llm(llm) # freeze base 3. load bridge.pt → hga_layers / emca / audio_start_embed / audio_end_embed 4. model.setup_lora(lora_cfg) # wrap LLM as PeftModel 5. PeftModel.load_adapter(lora/) # load trained adapter weights
Step order matters: LoRA must be set up *after* bridge.pt is loaded (HGA/EMCAare not LoRA-wrapped) and the adapter must be loaded into the already-LoRA-fiedLLM, exactly as training did."""import osimport jsonimport loggingfrom typing import Optional, List, Union
import torchimport torch.nn as nn
from transformers import ( PreTrainedModel, AutoModelForCausalLM, AutoTokenizer, WhisperFeatureExtractor,)
from .configuration_hga_thinker import HGAThinkerConfig
logger = logging.getLogger(__name__)
def _bridge_config_from_hf(hf_cfg: HGAThinkerConfig, *, whisper_path, llm_name): """Build a `thinker.config.ThinkerConfig` from the HF config.
Only the architecture fields ThinkerModel reads in __init__ are needed. Path fields are resolved by the caller (may be bundled sub-dirs). """ from thinker.config import ThinkerConfig return ThinkerConfig( whisper_path=whisper_path, encoder_dim=hf_cfg.encoder_dim, num_whisper_layers=hf_cfg.num_whisper_layers, extract_layers=list(hf_cfg.extract_layers), target_frame_rate_hz=hf_cfg.target_frame_rate_hz, hga_c_init=hf_cfg.hga_c_init, hga_c_min=hf_cfg.hga_c_min, hga_c_max=hf_cfg.hga_c_max, hga_b_init_std=hf_cfg.hga_b_init_std, emca_c_work_init=hf_cfg.emca_c_work_init, emca_c_work_min=hf_cfg.emca_c_work_min, emca_c_work_max=hf_cfg.emca_c_work_max, projector_hidden=hf_cfg.projector_hidden, llm_name=llm_name, llm_dim=hf_cfg.llm_dim, freeze_llm=hf_cfg.freeze_llm, )
class HGAThinkerForConditionalGeneration(PreTrainedModel): """Standalone, from_pretrained-able HGA-Thinker speech LM."""
config_class = HGAThinkerConfig base_model_prefix = "hga_thinker"
def __init__(self, config: HGAThinkerConfig): super().__init__(config) # The real model is built in from_pretrained (needs external weights). # Direct __init__ is only used by HF internals; we build a stub. self.thinker = None self._tokenizer = None self._feature_extractor = None
# ------------------------------------------------------------------ # Loading # ------------------------------------------------------------------ @classmethod def from_pretrained(cls, model_dir: str, *, device: Optional[str] = None, torch_dtype: Optional[torch.dtype] = None, whisper_path: Optional[str] = None, llm_name: Optional[str] = None, **kwargs) -> "HGAThinkerForConditionalGeneration": """Load an exported HGA-Thinker directory.
Args: model_dir: directory produced by export.py. device: e.g. "cuda" / "cuda:0" / "cpu". Default: cuda if available. torch_dtype: override config dtype. whisper_path / llm_name: override the paths recorded in config (useful if the base models moved since export). """ hf_cfg = HGAThinkerConfig.from_pretrained(model_dir)
# ---- resolve dtype ---- if torch_dtype is None: dtype_str = getattr(hf_cfg, "torch_dtype", "bfloat16") if isinstance(dtype_str, torch.dtype): torch_dtype = dtype_str else: torch_dtype = { "bfloat16": torch.bfloat16, "float16": torch.float16, "float32": torch.float32, }.get(str(dtype_str), torch.bfloat16)
if device is None: device = "cuda" if torch.cuda.is_available() else "cpu"
# ---- resolve base-model paths (bundled vs referenced) ---- def _resolve(sub, cfg_val, override): if override is not None: return override cand = os.path.join(model_dir, sub) if os.path.isdir(cand): # bundled return cand return cfg_val # external reference
wh_path = _resolve("whisper", hf_cfg.whisper_path, whisper_path) # Whisper "path" may be just a preprocessor ref; encoder needs the full # model. If only preprocessor_config.json was copied, fall back to the # recorded path / override. if not (os.path.isdir(wh_path) and os.path.isfile(os.path.join(wh_path, "config.json"))): wh_path = whisper_path or hf_cfg.whisper_path llm_path = _resolve("llm", hf_cfg.llm_name, llm_name)
# ---- 1. Build ThinkerModel (encoder + EMCA) ---- thinker_cfg = _bridge_config_from_hf( hf_cfg, whisper_path=wh_path, llm_name=llm_path) from thinker.model import ThinkerModel thinker = ThinkerModel(thinker_cfg)
# ---- 2. Load + attach LLM ---- logger.info(f"[load] LLM from {llm_path} ({torch_dtype})") llm = AutoModelForCausalLM.from_pretrained( llm_path, torch_dtype=torch_dtype, trust_remote_code=True) thinker.load_llm(llm)
# ---- 3. Load bridge.pt (HGA + EMCA + boundary embeds) ---- bridge_path = os.path.join(model_dir, "bridge.pt") if not os.path.isfile(bridge_path): raise FileNotFoundError(f"bridge.pt not found in {model_dir}") state = torch.load(bridge_path, map_location="cpu", weights_only=False) m1, _ = thinker.encoder.hga_layers.load_state_dict( state["hga_layers"], strict=False) m2, _ = thinker.emca.load_state_dict(state["emca"], strict=False) if m1 or m2: logger.warning(f"[load] missing keys hga={m1} emca={m2}") if "audio_start_embed" in state: thinker.audio_start_embed.data.copy_(state["audio_start_embed"]) thinker.audio_end_embed.data.copy_(state["audio_end_embed"]) logger.info("[load] bridge.pt loaded (HGA + EMCA + boundary embeds)")
# ---- 4 & 5. LoRA: load the trained adapter ---- # We use PeftModel.from_pretrained rather than setup_lora() + # manual state_dict load. Reasons: # * It reads lora/adapter_config.json and rebuilds the adapter # structure exactly as it was saved (r, alpha, target_modules, # inference_mode, peft_version-specific fields), so the export is # robust to PEFT-version drift between training and inference. # * It is the canonical PEFT load path, handling key remapping and # inference_mode=True automatically. # This attaches the adapter onto the frozen base LLM that load_llm() # already set on thinker.llm — matching training, where LoRA also wraps # the same base LLM (the only difference being PeftModel.from_pretrained # vs get_peft_model, which produce equivalent inference graphs). if hf_cfg.has_lora: lora_dir = os.path.join(model_dir, "lora") if not (os.path.isdir(lora_dir) and os.path.isfile( os.path.join(lora_dir, "adapter_config.json"))): raise FileNotFoundError( f"config says has_lora=True but no valid lora/ in {model_dir}") from peft import PeftModel thinker.llm = PeftModel.from_pretrained( thinker.llm, lora_dir, is_trainable=False) logger.info("[load] LoRA adapter loaded via PeftModel.from_pretrained")
# ---- finalize ---- thinker.to(device=device, dtype=torch_dtype) thinker.eval()
self = cls(hf_cfg) self.thinker = thinker self._device = device self._dtype = torch_dtype
# processor pieces self._tokenizer = AutoTokenizer.from_pretrained(model_dir) self._feature_extractor = WhisperFeatureExtractor.from_pretrained(wh_path) return self
# ------------------------------------------------------------------ # Inference # ------------------------------------------------------------------ @torch.no_grad() def chat(self, audio: Optional[Union[str, "torch.Tensor", List]] = None, query: str = "", *, processor=None, system_prompt: Optional[str] = None, max_new_tokens: int = 256, **gen_kwargs) -> Union[str, List[str]]: """Single-turn audio+text chat.
Builds a one-message-per-role ChatML conversation in the exact shape ThinkerModel.generate_sft expects (role/parts/type), encodes the audio via WhisperFeatureExtractor, and runs greedy generation.
`audio` may be a path, a (samples,) waveform tensor at 16k, or a list of those for a single multi-audio turn. Pass None for text-only. """ assert self.thinker is not None, "Call from_pretrained first." tok = (processor.tokenizer if processor is not None else self._tokenizer) fe = (processor.feature_extractor if processor is not None else self._feature_extractor) sys_p = system_prompt or self.config.system_prompt
# ---- load + featurize audio(s) ---- audios = [] if audio is not None: audios = audio if isinstance(audio, (list, tuple)) else [audio] mel_list, frames_list = [], [] for a in audios: wav = _load_waveform(a, self.config.sample_rate, self.config.max_audio_length) mel = fe(wav.numpy(), sampling_rate=self.config.sample_rate, return_tensors="pt").input_features[0] mel_list.append(mel) frames_list.append(min(len(wav) // 160, # 10ms hops int(self.config.max_audio_length * 100)))
if mel_list: mel_inputs = torch.stack(mel_list).to( device=self._device, dtype=self._dtype) audio_frames = torch.tensor(frames_list, device=self._device) else: mel_inputs = torch.empty(0, device=self._device, dtype=self._dtype) audio_frames = None
# ---- build conversation in generate_sft's expected schema ---- user_parts = [] for i in range(len(audios)): user_parts.append({"type": "audio", "audio_index": i}) if query: user_parts.append({"type": "text", "content": query})
conversation = [ {"role": "system", "parts": [{"type": "text", "content": sys_p}]}, {"role": "user", "parts": user_parts}, {"role": "assistant", "parts": []}, # prefix-only in gen mode ]
results = self.thinker.generate_sft( mel_inputs=mel_inputs, audio_counts=[len(audios)], conversations=[conversation], tokenizer=tok, max_new_tokens=max_new_tokens, audio_frames=audio_frames, **gen_kwargs, ) return results[0] if results else ""
# convenience accessors @property def tokenizer(self): return self._tokenizer
@property def feature_extractor(self): return self._feature_extractor
# ----------------------------------------------------------------------# Helpers# ----------------------------------------------------------------------def _load_waveform(audio, sample_rate: int, max_seconds: float) -> torch.Tensor: """Return a mono float32 waveform tensor at `sample_rate`, truncated.""" if isinstance(audio, torch.Tensor): wav = audio.float() if wav.dim() > 1: wav = wav.mean(dim=0) else: import torchaudio wav, sr = torchaudio.load(audio) if wav.dim() > 1: wav = wav.mean(dim=0) if sr != sample_rate: wav = torchaudio.functional.resample(wav, sr, sample_rate) wav = wav.float() max_len = int(max_seconds * sample_rate) if wav.numel() > max_len: wav = wav[:max_len] return wav
class HGAThinkerProcessor: """Bundles the Qwen tokenizer + Whisper feature extractor.
Mirrors what training used: AutoTokenizer(llm) + WhisperFeatureExtractor(whisper). """ def __init__(self, tokenizer, feature_extractor, config: dict = None): self.tokenizer = tokenizer self.feature_extractor = feature_extractor self.config = config or {}
@classmethod def from_pretrained(cls, model_dir: str, *, whisper_path: Optional[str] = None): tok = AutoTokenizer.from_pretrained(model_dir) # whisper ref: bundled dir, else preprocessor_config.json at root, else override wh = whisper_path if wh is None: bundled = os.path.join(model_dir, "whisper") wh = bundled if os.path.isdir(bundled) else model_dir fe = WhisperFeatureExtractor.from_pretrained(wh) proc_cfg = {} pc = os.path.join(model_dir, "processor_config.json") if os.path.isfile(pc): with open(pc) as f: proc_cfg = json.load(f) return cls(tok, fe, proc_cfg)1234567891011121314{ "chunk_length": 30, "feature_extractor_type": "WhisperFeatureExtractor", "feature_size": 128, "hop_length": 160, "n_fft": 400, "n_samples": 480000, "nb_max_frames": 3000, "padding_side": "right", "padding_value": 0.0, "processor_class": "WhisperProcessor", "return_attention_mask": false, "sampling_rate": 16000}123456{ "sample_rate": 16000, "max_audio_length": 30.0, "system_prompt": "You are a helpful assistant that analyzes audio content.", "assistant_prefix": "<|im_start|>assistant\n"}1"""HGA-Thinker: Hyperbolic Geometry Adapter for Speech Language Model."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157"""HGA-Thinker configuration."""import os, yamlfrom dataclasses import dataclass, field, asdictfrom typing import List, Dict, Optional, Anyimport dataclasses as _dc
@dataclassclass TrainingConfig: learning_rate: float = 5e-5 hga_lr_scale: float = 1.0 emca_lr_scale: float = 1.0 weight_decay: float = 0.01 warmup_ratio: float = 0.03 num_epochs: int = 3 max_steps: int = -1 batch_size: int = 6 grad_accumulation_steps: int = 2 gradient_clip_norm: float = 1.0 max_audio_length: float = 30.0 # ---- v2: per-batch audio cap ---- # Maximum total number of audios allowed in a single batch (i.e. the # first dim of the stacked mel tensor going through the Whisper encoder). # Multi-audio samples (e.g. constrain_inf_pair_audio with up to 4 audios) # can otherwise blow up the encoder forward batch to bs * 4 = 16 and OOM # the GPU. The dynamic batch sampler greedily packs samples so that the # SUM of their audio counts stays <= this cap, while never exceeding # batch_size samples. Set to 0 or a value >= batch_size*max_audios to # disable (degrades to plain batching). max_audios_per_batch: int = 6 eval_loss_steps: int = 500 eval_generate_steps: int = 2000 eval_samples_per_task: int = 100 # How many random ref/hyp pairs to print per task at each generate eval. # 5 keeps the log compact; bump to 10 if you want richer qualitative view. eval_display_samples: int = 5 save_steps: int = 2000 logging_steps: int = 50 output_dir: str = "outputs/align_hga" # Loss lambda_radius: float = 0.02 radius_margin: float = 0.05
@dataclassclass ThinkerConfig: # Whisper whisper_path: str = "" encoder_dim: int = 1280 num_whisper_layers: int = 32 extract_layers: List[int] = field( default_factory=lambda: [3, 7, 11, 15, 19, 23, 27, 31] # 0-indexed ) target_frame_rate_hz: float = 12.5
# HGA (per-layer Q/K/V weight modulation) # b_init_std=1e-4 ensures b ≠ 0 at step 0 so ∂L/∂c is non-zero from start. # All layers share the same c bounds — layer-aware bucketing removed since # Möbius bias makes c a real learnable parameter that finds its own # per-layer optimum without artificial floors. hga_c_init: float = 1.0 hga_c_min: float = 0.001 hga_c_max: float = 8.0 hga_b_init_std: float = 1.0e-4
# EMCA emca_c_work_init: float = 0.5 emca_c_work_min: float = 0.01 emca_c_work_max: float = 4.0 projector_hidden: int = 4096
# LLM llm_name: str = "" llm_dim: int = 3584 freeze_llm: bool = True
# LoRA (SFT stage only; ignored during align) lora: Optional[Dict[str, Any]] = None
# SFT system_prompt: str = "You are a helpful assistant that analyzes audio content." sft_eval_ratio: float = 0.005
# Training training: TrainingConfig = field(default_factory=TrainingConfig)
# Data datasets: List[Dict[str, Any]] = field(default_factory=list) audio_path_prefix_map: Dict[str, str] = field(default_factory=dict) rich_annotation_fields: Dict[str, Dict[str, Any]] = field(default_factory=dict)
# ---- Resume ---- # resume_from: CROSS-STAGE handoff. Loads HGA + EMCA weights ONLY from # a bridge.pt; optimizer, scheduler, and global_step all # start fresh. Typical use: # prealign → align : prealign/final/bridge.pt # align → SFT : align/final/bridge.pt # resume_state: SAME-STAGE seamless mid-run resume. Loads full training # state (model + optimizer + scheduler + RNG + global_step) # from an accelerator.save_state() directory. Use this when # continuing the SAME stage after a crash or pause. Point # it at either outputs/<stage>/checkpoint-N/ # or outputs/<stage>/checkpoint-N/state/ # The two are mutually exclusive — resume_state takes precedence if # both are set (its model weights override anything resume_from would # have loaded). resume_from: Optional[str] = None resume_state: Optional[str] = None
# Convenience properties (no setters; modify .training fields directly) @property def output_dir(self): return self.training.output_dir @property def batch_size(self): return self.training.batch_size @property def grad_accumulation_steps(self): return self.training.grad_accumulation_steps @property def max_audio_length(self): return self.training.max_audio_length @property def num_epochs(self): return self.training.num_epochs @property def max_steps(self): return self.training.max_steps @property def warmup_ratio(self): return self.training.warmup_ratio @property def learning_rate(self): return self.training.learning_rate @property def weight_decay(self): return self.training.weight_decay @property def gradient_clip_norm(self): return self.training.gradient_clip_norm @property def save_steps(self): return self.training.save_steps @property def logging_steps(self): return self.training.logging_steps
@classmethod def from_yaml(cls, path: str) -> "ThinkerConfig": with open(path) as f: data = yaml.safe_load(f) return cls.from_dict(data)
@classmethod def from_dict(cls, data: dict) -> "ThinkerConfig": training_raw = dict(data.get("training") or {}) valid = {f.name for f in _dc.fields(TrainingConfig)} training_raw = {k: v for k, v in training_raw.items() if k in valid} training = TrainingConfig(**training_raw)
valid_top = {f.name for f in _dc.fields(cls)} - {"training"} top = {k: v for k, v in data.items() if k in valid_top and k != "training"} return cls(training=training, **top)
def to_yaml(self, path: str): d = asdict(self) os.makedirs(os.path.dirname(path) or ".", exist_ok=True) with open(path, "w") as f: yaml.safe_dump(d, f, sort_keys=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181"""Enhanced Multi-scale Cross-Attention (EMCA) in the Poincaré ball.
================================================================================V1 (2B): radii_per_scale and p_fuse are no longer .detach()'d. Crucially, theradii used for L_radius are computed from `attended` (post Einstein-midpointcross-attention), NOT from `ball_features` (the bare exp_map output).
WHY: poincare_radius(exp_0^c(h), c) = (2/√c) · artanh(√c · tanh(√c‖h‖)/√c) = 2‖h‖ — c CANCELS OUT. poincare_radius(attended, c) has no such cancellation because `attended` is the output of einstein_midpoint, whose Lorentz factor γ = (1-c‖k‖²)^(-1/2) is genuinely c-dependent and not invertible by the outer artanh.
So under V1: - L_radius has real gradient flow (no .detach()) - L_radius's gradient w.r.t. c_work is non-zero (radii truly depend on c) - L_radius's gradient also reaches HGA's (s, b, c^(l)) via the multi_scale_features → attended path================================================================================"""import loggingfrom typing import Dict, List, Any
import torchimport torch.nn as nnimport torch.nn.functional as F
from .hyperbolic_ops import ( exp_map_zero, log_map_zero, clamp_norm, hyperbolic_distance, einstein_midpoint, poincare_radius, LearnableCurvature,)
logger = logging.getLogger(__name__)
class RMSNorm(nn.Module): """Root Mean Square Normalization (preserves direction, controls magnitude).""" def __init__(self, dim: int, eps: float = 1e-6): super().__init__() self.weight = nn.Parameter(torch.ones(dim)) self.eps = eps
def forward(self, x): x_f = x.float() rms = torch.sqrt(x_f.pow(2).mean(-1, keepdim=True) + self.eps) return ((x_f / rms) * self.weight.float()).to(x.dtype)
class EMCA(nn.Module): """Enhanced Multi-scale Cross-Attention.
Forward pipeline: 1. Per-scale exp_map into working Poincaré ball (c_work). 2. Pairwise hyperbolic distance → softmax → cross-scale attention scores. 3. Einstein midpoint per query scale → `attended` (B, T, S, d) in ball. ↑ This is where c truly affects values (via Lorentz factor γ). 4. Final aggregation across scales (Einstein midpoint, scale_weights) → p_fuse. 5. log_map → projector → RMSNorm → audio_tokens (Euclidean).
Outputs: audio_tokens: (B, T, llm_dim) Euclidean — feeds LLM. p_fuse: (B, T, d) in ball — available for future hyperbolic losses. radii_per_scale: (S,) — mean poincare_radius(attended[..., i, :], c_work). Gradient flows through this; L_radius uses it. """
def __init__(self, encoder_dim: int = 1280, llm_dim: int = 3584, num_scales: int = 8, c_work_init: float = 0.5, c_work_min: float = 0.01, c_work_max: float = 4.0, projector_hidden: int = 4096): super().__init__() self.encoder_dim = encoder_dim self.num_scales = num_scales
# Working curvature for the EMCA ball (separate from HGA's per-layer c^(l)) self.c_work = LearnableCurvature( init_value=c_work_init, c_min=c_work_min, c_max=c_work_max )
# Learnable temperature for attention self.log_temperature = nn.Parameter(torch.tensor(1.0).log())
# Learnable scale weights for final aggregation self.scale_logits = nn.Parameter(torch.zeros(num_scales))
# Output projection: encoder_dim → llm_dim self.projector = nn.Sequential( nn.Linear(encoder_dim, projector_hidden), nn.GELU(), nn.Linear(projector_hidden, llm_dim), ) self.output_norm = RMSNorm(llm_dim)
@property def temperature(self): return self.log_temperature.float().exp()
def forward(self, multi_scale_features: List[torch.Tensor] ) -> Dict[str, Any]: """ Args: multi_scale_features: list of S tensors, each (B, T, d). S = num_scales, features from different Whisper layers (already pooled to target frame rate by ThinkerModel).
Returns: dict containing audio_tokens (for LLM), p_fuse (for future use), radii_per_scale (for L_radius, WITH gradient), and diagnostics. """ S = len(multi_scale_features) assert S == self.num_scales, f"Expected {self.num_scales} scales, got {S}"
B, T, d = multi_scale_features[0].shape c = self.c_work().float()
# 1. Map each scale into the working Poincaré ball ball_features = [] for i in range(S): h = multi_scale_features[i].float() p = exp_map_zero(h, c) # (B, T, d) in ball ball_features.append(p) # Stack: (B, T, S, d) ball_stack = torch.stack(ball_features, dim=2)
# 2. Pairwise hyperbolic distances for cross-attention q = ball_stack.unsqueeze(3).expand(B, T, S, S, d).reshape(-1, d) k = ball_stack.unsqueeze(2).expand(B, T, S, S, d).reshape(-1, d) dists = hyperbolic_distance(q, k, c).reshape(B, T, S, S)
# Attention scores: -distance / temperature, mask diagonal scores = -dists / self.temperature diag_mask = torch.eye(S, device=scores.device, dtype=torch.bool) scores = scores.masked_fill( diag_mask.unsqueeze(0).unsqueeze(0), float('-inf') ) attn_weights = F.softmax(scores, dim=-1) # (B, T, S, S)
# 3. Einstein midpoint cross-attention per query scale points_exp = ball_stack.unsqueeze(2).expand(B, T, S, S, d) attended = einstein_midpoint(points_exp, attn_weights, c) # (B, T, S, d)
# 3b. Radii from `attended` — c truly affects values here (no cancellation) # Note: NO .detach() — radii carry gradient back to c_work, scale weights, # and through multi_scale_features to HGA parameters. radii_per_scale = [] for i in range(S): radii_per_scale.append( poincare_radius(attended[:, :, i, :], c).mean() ) radii_per_scale = torch.stack(radii_per_scale) # (S,)
# 4. Final aggregation across scales scale_w = F.softmax(self.scale_logits.float(), dim=0) # (S,) scale_w_exp = scale_w.unsqueeze(0).unsqueeze(0).expand(B, T, -1) p_fuse = einstein_midpoint(attended, scale_w_exp, c) # (B, T, d)
# 5. Log map back to Euclidean, project to LLM dim z = log_map_zero(p_fuse, c) # (B, T, d) proj_dtype = next(self.projector.parameters()).dtype audio_tokens = self.projector(z.to(proj_dtype)) audio_tokens = self.output_norm(audio_tokens)
return { "audio_tokens": audio_tokens, # p_fuse kept in graph (no detach) — available for future losses. "p_fuse": p_fuse, # radii_per_scale carries gradient → real L_radius signal. "radii_per_scale": radii_per_scale, # Below are diagnostics only; .detach() is fine here. "c_work": c.detach(), "scale_weights": scale_w.detach(), "scale_entropy": -(scale_w * (scale_w + 1e-8).log()).sum().detach(), "attention_temp": self.temperature.detach(), }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253"""Whisper encoder with HGA-modulated self-attention.
================================================================================V1 (2A): HGA now includes a Möbius bias term that breaks exp/log cancellation,making the curvature c a real, gradient-bearing parameter.
Modulation formula (per Q/K/V projection, per layer):
W_HGA = log_0^c( ( diag(s) ⊗_c exp_0^c(W_ref) ) ⊕_c exp_0^c(b) )
Without b, the chain reduces to s ⊙ W_ref (DoRA-like, c does nothing — thisis the SER paper's formula). With b ≠ 0, the Möbius addition step entangles cwith the norms of q and b in a way that cannot be algebraically cancelled.
Key properties: - b tiny-random-init (std=1e-4) → init is numerically ≈ s ⊙ W_ref but with b ≠ 0, so c receives gradient signal from step 0. (Zero-init would freeze c at a saddle ∂L/∂c = 0.) - All layers use the same (c_min, c_init, c_max) bounds; layer-aware bucketing removed because b makes c a real parameter that learns its own per-layer optimum without artificial floors.================================================================================"""import mathimport loggingfrom typing import List, Dict, Any, Optional
import torchimport torch.nn as nnimport torch.nn.functional as F
from .hyperbolic_ops import ( exp_map_zero, log_map_zero, mobius_add, clamp_norm, LearnableCurvature,)
logger = logging.getLogger(__name__)
class HGALinear(nn.Module): """Drop-in replacement for nn.Linear that applies HGA weight modulation with a Möbius bias term.
Stores a frozen reference weight W_ref. At forward time: p = exp_0^c(W_ref) # rows → ball v = log_0^c(p) # = W_ref (id) q = exp_0^c(diag(s) · v) = exp_0^c(s ⊙ W_ref)# Möbius scale b_pt = exp_0^c(b) # bias → ball r = q ⊕_c b_pt # Möbius add — c becomes essential W_mod = log_0^c(r) # ball → tangent output = x @ W_mod^T + bias_orig
Trainable: s (d_in,), b (d_in,), c (via curvature_module) Frozen: W_ref, bias_orig (from pretrained Whisper) """
def __init__(self, original_linear: nn.Linear, s: nn.Parameter, b: nn.Parameter, curvature_module: nn.Module): super().__init__() # Frozen reference weight (rows are the d_out "row vectors" in R^{d_in}) self.register_buffer("W_ref", original_linear.weight.data.clone().float()) # Keep original bias (frozen but used in forward) if original_linear.bias is not None: self.register_buffer("bias", original_linear.bias.data.clone()) else: self.bias = None # Learnable HGA parameters (shared from the per-layer container) self.s = s self.b = b self.curvature = curvature_module
def forward(self, x: torch.Tensor) -> torch.Tensor: c = self.curvature().float()
# Step 1: rows of W_ref → Poincaré ball p = exp_map_zero(self.W_ref, c) # (d_out, d_in) # Step 2: Möbius diagonal scaling diag(s) ⊗_c p # = exp_0^c( s ⊙ log_0^c(p) ) = exp_0^c( s ⊙ W_ref ) v = log_map_zero(p, c) # = W_ref (cancellation) v_scaled = v * self.s.float().unsqueeze(0) q = exp_map_zero(v_scaled, c) # (d_out, d_in) in ball # Step 3: Möbius bias addition — broadcasts b across d_out rows b_pt = exp_map_zero(self.b.float(), c) # (d_in,) in ball b_pt_b = b_pt.unsqueeze(0).expand_as(q) # (d_out, d_in) r = mobius_add(q, b_pt_b, c) # (d_out, d_in) r = clamp_norm(r, c) # numerical safety # Step 4: log_map back to tangent → modulated weight W_mod = log_map_zero(r, c) # (d_out, d_in)
with torch.amp.autocast("cuda", enabled=False): return F.linear(x.float(), W_mod.float(), self.bias.float() if self.bias is not None else None).to(x.dtype)
class HGAWhisperEncoder(nn.Module): """Whisper encoder with HGA-modulated Q/K/V on all 32 layers.
Architecture: 1. Load Whisper encoder, freeze every original parameter. 2. For each layer, create one shared LearnableCurvature c^(l) plus three pairs of (s, b) — for q_proj, k_proj, v_proj. 3. Replace q_proj/k_proj/v_proj with HGALinear wrappers that compute the modulated weight on the fly. 4. Register forward hooks to capture multi-scale features for EMCA.
Trainable params per layer: 3 × d_model (s_Q, s_K, s_V) + 3 × d_model (b_Q, b_K, b_V) + 1 (c) = 6 × d_model + 1 For d_model=1280 → 7,681 per layer × 32 layers ≈ 246K total (HGA only). """
output_dim = 1280 output_frame_rate_hz = 50.0
def __init__(self, model_path: str, extract_layers: List[int], num_encoder_layers: int = 32, hga_c_init: float = 1.0, hga_c_min: float = 0.001, hga_c_max: float = 8.0, hga_b_init_std: float = 1.0e-4): super().__init__() self.extract_layers = sorted(extract_layers) self.num_encoder_layers = num_encoder_layers self.hga_c_init = hga_c_init self.hga_c_min = hga_c_min self.hga_c_max = hga_c_max self.hga_b_init_std = hga_b_init_std
# --- Load Whisper encoder --- from transformers import WhisperModel whisper = WhisperModel.from_pretrained(model_path) self.encoder = whisper.encoder del whisper
# Freeze ALL original encoder parameters for p in self.encoder.parameters(): p.requires_grad = False
# --- Create HGA params and inject into Whisper --- self.hga_layers = nn.ModuleList() d = self.output_dim for i, layer in enumerate(self.encoder.layers): attn = layer.self_attn
# Shared curvature for Q/K/V of this layer curvature = LearnableCurvature( init_value=hga_c_init, c_min=hga_c_min, c_max=hga_c_max )
# Diagonal scaling: identity (s=1) at init → first-step output ≈ W_ref s_q = nn.Parameter(torch.ones(d)) s_k = nn.Parameter(torch.ones(d)) s_v = nn.Parameter(torch.ones(d))
# Möbius bias: tiny random init so b ≠ 0 from step 0 and ∂L/∂c ≠ 0 b_q = nn.Parameter(torch.randn(d) * hga_b_init_std) b_k = nn.Parameter(torch.randn(d) * hga_b_init_std) b_v = nn.Parameter(torch.randn(d) * hga_b_init_std)
# Replace q/k/v_proj with HGA-modulated versions attn.q_proj = HGALinear(attn.q_proj, s_q, b_q, curvature) attn.k_proj = HGALinear(attn.k_proj, s_k, b_k, curvature) attn.v_proj = HGALinear(attn.v_proj, s_v, b_v, curvature)
# Container so optimizer sees these params cont = nn.Module() cont.curvature = curvature cont.s_q, cont.s_k, cont.s_v = s_q, s_k, s_v cont.b_q, cont.b_k, cont.b_v = b_q, b_k, b_v self.hga_layers.append(cont)
logger.info( f"Whisper encoder: {num_encoder_layers} layers, " f"all Q/K/V wrapped in HGALinear " f"(c_init={hga_c_init}, c_min={hga_c_min}, c_max={hga_c_max}, " f"b_std={hga_b_init_std})" )
# --- Feature capture hooks --- self._features: Dict[int, torch.Tensor] = {} self._hooks = [] for idx, layer in enumerate(self.encoder.layers): if idx in self.extract_layers: self._hooks.append( layer.register_forward_hook(self._make_hook(idx)) )
def _make_hook(self, layer_idx: int): def hook_fn(module, input, output): self._features[layer_idx] = ( output[0] if isinstance(output, tuple) else output ) return hook_fn
def forward(self, mel_input: torch.Tensor) -> List[torch.Tensor]: """Run Whisper with HGA-modulated attention.
Args: mel_input: (B, n_mels, T_mel) Returns: List of (B, T, 1280) tensors, one per extract_layer (sorted). """ encoder_dtype = self.encoder.layer_norm.weight.dtype mel = mel_input.to(dtype=encoder_dtype)
self._features.clear() _ = self.encoder(mel)
features = [] for ln in self.extract_layers: if ln not in self._features: raise RuntimeError( f"Layer {ln} not captured. Got: {sorted(self._features.keys())}" ) features.append(self._features[ln]) return features
def num_audio_frames(self, audio_samples_16khz: int) -> int: return min(math.ceil(audio_samples_16khz / 320), 1500)
# ---- Diagnostics ----
def get_hga_diagnostics(self) -> Dict[str, float]: """Per-layer scalars logged to TensorBoard.""" diag = {} for i, hga in enumerate(self.hga_layers): diag[f"hga/c_L{i}"] = hga.curvature().item() diag[f"hga/s_q_mean_L{i}"] = hga.s_q.data.mean().item() diag[f"hga/s_v_mean_L{i}"] = hga.s_v.data.mean().item() # b norms — key indicator: if these stay ~0, c won't learn diag[f"hga/b_q_norm_L{i}"] = hga.b_q.data.norm().item() diag[f"hga/b_k_norm_L{i}"] = hga.b_k.data.norm().item() diag[f"hga/b_v_norm_L{i}"] = hga.b_v.data.norm().item() return diag
def get_curvatures_summary(self) -> str: """Compact c-per-layer string for log lines (grouped 8 per row).""" vals = [f"{hga.curvature().item():.4f}" for hga in self.hga_layers] groups = [] for i in range(0, len(vals), 8): groups.append("/".join(vals[i:i+8])) return " | ".join(groups)
def get_b_norm_summary(self) -> str: """Compact b_q-per-layer norm string (grouped 8 per row). Used to verify the 'b grows → c learns' training dynamic.""" vals = [f"{hga.b_q.data.norm().item():.4f}" for hga in self.hga_layers] groups = [] for i in range(0, len(vals), 8): groups.append("/".join(vals[i:i+8])) return " | ".join(groups)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126"""Core Poincaré Ball Operations.
All ops run in fp32 via @_fp32 decorator regardless of ambient mixed-precision."""import torchimport torch.nn as nnimport torch.nn.functional as Fimport functools
MIN_NORM = 1e-15BALL_EPS = 1e-5TANH_CLAMP = 15.0
def _fp32(fn): """Disable autocast, cast inputs to fp32, cast output back.""" @functools.wraps(fn) def wrapper(*args, **kwargs): with torch.amp.autocast(device_type="cuda", enabled=False): orig = None for a in args: if torch.is_tensor(a): orig = a.dtype; break if orig is None: for v in kwargs.values(): if torch.is_tensor(v): orig = v.dtype; break orig = orig or torch.float32 a32 = [a.float() if torch.is_tensor(a) else a for a in args] k32 = {k: v.float() if torch.is_tensor(v) else v for k, v in kwargs.items()} r = fn(*a32, **k32) return r.to(orig) if torch.is_tensor(r) else r return wrapper
def safe_arctanh(x): return torch.atanh(x.clamp(-1 + 1e-7, 1 - 1e-7))
def safe_tanh(x): return torch.tanh(x.clamp(-TANH_CLAMP, TANH_CLAMP))
def clamp_norm(x, c, eps=BALL_EPS): max_norm = (1.0 / torch.sqrt(c)) - eps norm = x.norm(dim=-1, keepdim=True).clamp(min=MIN_NORM) return torch.where(norm > max_norm, x / norm * max_norm, x)
@_fp32def exp_map_zero(v, c): """Tangent space → Poincaré ball at origin.""" sqrt_c = torch.sqrt(c) v_norm = v.norm(dim=-1, keepdim=True).clamp(min=MIN_NORM) factor = safe_tanh(sqrt_c * v_norm) / sqrt_c return clamp_norm(factor * (v / v_norm), c)
@_fp32def log_map_zero(x, c): """Poincaré ball → tangent space at origin.""" sqrt_c = torch.sqrt(c) x_norm = x.norm(dim=-1, keepdim=True).clamp(min=MIN_NORM) factor = safe_arctanh(sqrt_c * x_norm) / (sqrt_c * x_norm) return factor * x
@_fp32def mobius_add(u, v, c): """Möbius addition u ⊕_c v.""" u2 = (u * u).sum(-1, keepdim=True) v2 = (v * v).sum(-1, keepdim=True) uv = (u * v).sum(-1, keepdim=True) num = (1 + 2 * c * uv + c * v2) * u + (1 - c * u2) * v den = (1 + 2 * c * uv + c * c * u2 * v2).clamp(min=MIN_NORM) return num / den
@_fp32def hyperbolic_distance(x, y, c): """d_c(x, y) in Poincaré ball.""" sqrt_c = torch.sqrt(c) diff = mobius_add(-x, y, c) return (2.0 / sqrt_c) * safe_arctanh(sqrt_c * diff.norm(dim=-1).clamp(min=MIN_NORM))
@_fp32def poincare_radius(x, c): """d_c(0, x) = (2/√c) · artanh(√c · ‖x‖).""" sqrt_c = torch.sqrt(c) return (2.0 / sqrt_c) * safe_arctanh(sqrt_c * x.norm(dim=-1).clamp(min=MIN_NORM))
@_fp32def einstein_midpoint(points, weights, c): """Weighted Einstein midpoint. points: (..., N, d), weights: (..., N).""" p2 = (points * points).sum(-1, keepdim=True) klein = 2.0 * points / (1.0 + c * p2).clamp(min=MIN_NORM) k2 = (klein * klein).sum(-1, keepdim=True) gamma = 1.0 / torch.sqrt((1.0 - c * k2).clamp(min=MIN_NORM)) w = weights.unsqueeze(-1) wg = w * gamma k_bar = (wg * klein).sum(-2) / wg.sum(-2).clamp(min=MIN_NORM) kb2 = (k_bar * k_bar).sum(-1, keepdim=True) denom = 1.0 + torch.sqrt((1.0 - c * kb2).clamp(min=MIN_NORM)) return clamp_norm(k_bar / denom.clamp(min=MIN_NORM), c)
class LearnableCurvature(nn.Module): """c = clamp(softplus(hat_c) + c_min, max=c_max).""" def __init__(self, init_value=1.0, c_min=0.01, c_max=None): super().__init__() self.c_min = c_min self.c_max = c_max delta = init_value - c_min assert delta > 0, f"init_value({init_value}) must > c_min({c_min})" if delta > 20.0: init_hat = torch.tensor(delta, dtype=torch.float32) else: init_hat = torch.log(torch.expm1(torch.tensor(delta, dtype=torch.float32))) self.hat_c = nn.Parameter(init_hat)
def forward(self): c = F.softplus(self.hat_c) + self.c_min if self.c_max is not None: c = c.clamp(max=self.c_max) return c123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512"""HGA-Thinker Model.
Architecture: HGAWhisperEncoder (frozen Whisper + HGA on all 32 layers Q/K/V) → extract 8 scale features → mean-pool to target frame rate EMCA (Poincaré ball cross-attention fusion) → p_fuse (for L_radius) → log_map → projector → RMSNorm → audio_tokens Frozen Qwen 7B LLM → [audio_tokens, text_embeds] → L_CE
SFT extensions (appended, align code untouched): setup_lora() — add LoRA to frozen LLM get_sft_param_groups — three groups: LoRA / EMCA / HGA forward_sft() — multi-audio + conversation-based input generate_sft() — multi-audio generation"""import mathimport loggingfrom typing import Dict, Any, Optional, List, Tuple
import torchimport torch.nn as nnimport torch.nn.functional as F
logger = logging.getLogger(__name__)
class ThinkerModel(nn.Module): """HGA-Thinker: Whisper(HGA) → EMCA → Bridge → frozen LLM."""
def __init__(self, config): super().__init__() self.config = config
# 1. Whisper encoder with HGA from .encoder import HGAWhisperEncoder self.encoder = HGAWhisperEncoder( model_path=config.whisper_path, extract_layers=config.extract_layers, num_encoder_layers=config.num_whisper_layers, hga_c_init=config.hga_c_init, hga_c_min=config.hga_c_min, hga_c_max=config.hga_c_max, hga_b_init_std=config.hga_b_init_std, )
# 2. EMCA from .emca import EMCA self.emca = EMCA( encoder_dim=config.encoder_dim, llm_dim=config.llm_dim, num_scales=len(config.extract_layers), c_work_init=config.emca_c_work_init, c_work_min=config.emca_c_work_min, c_work_max=config.emca_c_work_max, projector_hidden=config.projector_hidden, )
# 3. LLM (loaded externally) self.llm = None self.target_frame_rate_hz = config.target_frame_rate_hz
# Audio boundary markers for multi-audio SFT. # Learnable embeddings inserted before / after each audio token # sequence so the LLM can distinguish separate audio inputs. # Dimensions match llm_dim; initialised with small random values # (std=0.02, same as typical transformer embedding init). # They are part of the bridge (not the frozen LLM), so they are # naturally trainable and saved in bridge.pt. self.audio_start_embed = nn.Parameter(torch.randn(config.llm_dim) * 0.02) self.audio_end_embed = nn.Parameter(torch.randn(config.llm_dim) * 0.02)
def load_llm(self, llm_model): self.llm = llm_model if self.config.freeze_llm: for p in self.llm.parameters(): p.requires_grad = False
def trainable_parameters(self): return [p for p in self.parameters() if p.requires_grad]
def count_trainable_parameters(self) -> int: return sum(p.numel() for p in self.parameters() if p.requires_grad)
def get_param_groups(self, base_lr: float, hga_lr_scale: float = 1.0, emca_lr_scale: float = 1.0): hga_ids = set(id(p) for p in self.encoder.hga_layers.parameters()) emca_ids = set(id(p) for p in self.emca.parameters()) hga_params, emca_params, other_params = [], [], [] for p in self.parameters(): if not p.requires_grad: continue pid = id(p) if pid in hga_ids: hga_params.append(p) elif pid in emca_ids: emca_params.append(p) else: other_params.append(p) groups = [] if hga_params: groups.append({"params": hga_params, "lr": base_lr * hga_lr_scale, "_group_name": "hga"}) if emca_params: groups.append({"params": emca_params, "lr": base_lr * emca_lr_scale, "_group_name": "emca"}) if other_params: groups.append({"params": other_params, "lr": base_lr, "_group_name": "other"}) return groups
# ---- Time-axis pooling ----
@staticmethod def _pool_time(x, in_rate, target_rate): if abs(in_rate - target_rate) < 1e-6: return x k = max(1, int(round(in_rate / target_rate))) B, T, D = x.shape T_new = T // k if T_new == 0: return x.mean(dim=1, keepdim=True) return x[:, :T_new * k, :].reshape(B, T_new, k, D).mean(dim=2)
# ============================================================ # Align forward (unchanged) # ============================================================
def get_audio_tokens(self, mel_input, audio_frames=None): multi_scale = self.encoder(mel_input) in_rate = self.encoder.output_frame_rate_hz pooled = [self._pool_time(f, in_rate, self.target_frame_rate_hz) for f in multi_scale] emca_out = self.emca(pooled) audio_tokens = emca_out["audio_tokens"] B, T_audio, _ = audio_tokens.shape audio_token_mask = None if audio_frames is not None: ratio = 50.0 / self.target_frame_rate_hz valid = torch.ceil(audio_frames.float() / ratio).long() audio_token_mask = ( torch.arange(T_audio, device=audio_tokens.device).unsqueeze(0) < valid.unsqueeze(1) ).long() return { "audio_tokens": audio_tokens, "audio_token_mask": audio_token_mask, "radii_per_scale": emca_out["radii_per_scale"], "c_work": emca_out["c_work"], "scale_weights": emca_out["scale_weights"], "scale_entropy": emca_out["scale_entropy"], "attention_temp": emca_out["attention_temp"], }
def forward(self, mel_input=None, text_input_ids=None, text_attention_mask=None, labels=None, audio_frames=None, **kwargs): assert self.llm is not None, "Call load_llm() first." bridge_out = self.get_audio_tokens(mel_input, audio_frames) llm_dtype = next(self.llm.parameters()).dtype audio_tokens = bridge_out["audio_tokens"].to(dtype=llm_dtype) B, T_audio, _ = audio_tokens.shape text_embeds = self.llm.get_input_embeddings()(text_input_ids) inputs_embeds = torch.cat([audio_tokens, text_embeds], dim=1) atm = bridge_out.get("audio_token_mask") audio_mask = atm if atm is not None else torch.ones( B, T_audio, device=audio_tokens.device, dtype=torch.long) full_mask = torch.cat([audio_mask, text_attention_mask], dim=1) \ if text_attention_mask is not None else \ torch.ones(B, inputs_embeds.shape[1], device=audio_tokens.device, dtype=torch.long) if labels is not None: audio_labels = torch.full((B, T_audio), -100, device=labels.device, dtype=labels.dtype) full_labels = torch.cat([audio_labels, labels], dim=1) else: full_labels = None llm_out = self.llm(inputs_embeds=inputs_embeds, attention_mask=full_mask, labels=full_labels, return_dict=True) bridge_out["lm_loss"] = llm_out.loss bridge_out["logits"] = llm_out.logits return bridge_out
@torch.no_grad() def generate(self, mel_input=None, prompt_input_ids=None, prompt_attention_mask=None, max_new_tokens=256, audio_frames=None, **kwargs): assert self.llm is not None was_training = self.training self.eval() bridge_out = self.get_audio_tokens(mel_input, audio_frames) llm_dtype = next(self.llm.parameters()).dtype audio_tokens = bridge_out["audio_tokens"].to(dtype=llm_dtype) B, T_audio, _ = audio_tokens.shape prompt_embeds = self.llm.get_input_embeddings()(prompt_input_ids) inputs_embeds = torch.cat([audio_tokens, prompt_embeds], dim=1) atm = bridge_out.get("audio_token_mask") audio_mask = atm if atm is not None else torch.ones( B, T_audio, device=audio_tokens.device, dtype=torch.long) full_mask = torch.cat([audio_mask, prompt_attention_mask], dim=1) \ if prompt_attention_mask is not None else \ torch.ones(B, inputs_embeds.shape[1], device=audio_tokens.device, dtype=torch.long) default_eos = getattr(self.llm.generation_config, "eos_token_id", None) if default_eos is None: default_eos = self.llm.config.eos_token_id if isinstance(default_eos, int): default_eos = [default_eos] gen_kwargs = dict(inputs_embeds=inputs_embeds, attention_mask=full_mask, max_new_tokens=max_new_tokens, do_sample=False, eos_token_id=default_eos, pad_token_id=default_eos[0] if default_eos else 0) gen_kwargs.update(kwargs) result = self.llm.generate(**gen_kwargs) if was_training: self.train() return result
# ============================================================ # SFT extensions # ============================================================
def setup_lora(self, lora_config: Dict): """Add LoRA adapters to the frozen LLM for SFT.""" try: from peft import get_peft_model, LoraConfig, TaskType except ImportError: raise ImportError("pip install peft (required for SFT LoRA)") default_targets = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"] cfg = LoraConfig( r=lora_config.get("r", 32), lora_alpha=lora_config.get("lora_alpha", 64), target_modules=lora_config.get("target_modules", default_targets), lora_dropout=lora_config.get("lora_dropout", 0.05), bias=lora_config.get("bias", "none"), task_type=TaskType.CAUSAL_LM, ) logger.info(f"[LoRA] r={cfg.r}, alpha={cfg.lora_alpha}, " f"targets={cfg.target_modules}") self.llm = get_peft_model(self.llm, cfg) self.llm.print_trainable_parameters() self._lora_config = cfg
def get_sft_param_groups(self, base_lr: float, hga_lr_scale: float = 0.3, emca_lr_scale: float = 0.5): hga_ids = set(id(p) for p in self.encoder.hga_layers.parameters()) emca_ids = set(id(p) for p in self.emca.parameters()) hga_p, emca_p, lora_p = [], [], [] for p in self.parameters(): if not p.requires_grad: continue pid = id(p) if pid in hga_ids: hga_p.append(p) elif pid in emca_ids: emca_p.append(p) else: lora_p.append(p) groups = [] if lora_p: groups.append({"params": lora_p, "lr": base_lr, "_group_name": "lora"}) if emca_p: groups.append({"params": emca_p, "lr": base_lr * emca_lr_scale, "_group_name": "emca"}) if hga_p: groups.append({"params": hga_p, "lr": base_lr * hga_lr_scale, "_group_name": "hga"}) for g in groups: n = sum(p.numel() for p in g["params"]) logger.info(f" SFT group [{g['_group_name']}]: " f"{n:,} params, lr={g['lr']:.2e}") return groups
# ---- multi-audio encoding ----
def encode_audio_batch(self, mel_inputs, audio_frames=None): if mel_inputs is None or mel_inputs.numel() == 0: return [], None bridge = self.get_audio_tokens(mel_inputs, audio_frames) tokens = bridge["audio_tokens"] radii = bridge.get("radii_per_scale") return [tokens[i] for i in range(tokens.shape[0])], radii
# ---- SFT forward ----
def forward_sft(self, mel_inputs, audio_counts, conversations, tokenizer, audio_frames=None): assert self.llm is not None, "Call load_llm() first." device = next(self.llm.parameters()).device llm_dtype = next(self.llm.parameters()).dtype batch_size = len(conversations)
has_audio = (mel_inputs is not None and mel_inputs.numel() > 0) if has_audio: all_tokens, radii = self.encode_audio_batch(mel_inputs, audio_frames) else: all_tokens, radii = [], None
offset = 0 per_sample_tokens = [] for cnt in audio_counts: per_sample_tokens.append( [t.to(dtype=llm_dtype) for t in all_tokens[offset:offset + cnt]]) offset += cnt
embed_fn = self.llm.get_input_embeddings() all_embeds, all_labels = [], [] for i in range(batch_size): e, l = self._build_sft_sample( conversations[i], per_sample_tokens[i], tokenizer, embed_fn, device, llm_dtype, generation_mode=False) all_embeds.append(e) all_labels.append(l)
if not all_embeds: dummy = torch.tensor(0.0, device=device, requires_grad=True) return {"lm_loss": dummy, "radii_per_scale": radii, "c_work": torch.tensor(0.0, device=device), "scale_entropy": torch.tensor(0.0, device=device)}
max_len = max(e.shape[0] for e in all_embeds) pad_embeds, pad_masks, pad_labels = [], [], [] for e, l in zip(all_embeds, all_labels): seq_len = e.shape[0] gap = max_len - seq_len if gap > 0: e = torch.cat([e, torch.zeros(gap, e.shape[-1], device=device, dtype=llm_dtype)]) l = torch.cat([l, torch.full((gap,), -100, device=device, dtype=torch.long)]) amask = torch.cat([ torch.ones(seq_len, device=device, dtype=torch.long), torch.zeros(gap, device=device, dtype=torch.long), ]) if gap > 0 else torch.ones(max_len, device=device, dtype=torch.long) pad_embeds.append(e) pad_masks.append(amask) pad_labels.append(l)
llm_out = self.llm( inputs_embeds=torch.stack(pad_embeds), attention_mask=torch.stack(pad_masks), labels=torch.stack(pad_labels), return_dict=True)
return { "lm_loss": llm_out.loss, "logits": llm_out.logits, "radii_per_scale": radii, "c_work": self.emca.c_work().detach() if radii is not None else torch.tensor(0.0, device=device), "scale_entropy": torch.tensor(0.0, device=device), }
# ---- build one sample ----
def _build_sft_sample(self, conversation, audio_tokens, tokenizer, embed_fn, device, dtype, generation_mode=False): """Build input embeds + labels for one SFT sample.
generation_mode=True: emit only up to the assistant prefix (<|im_start|>assistant\\n), then stop. No response text, no <|im_end|>. """ segs_e, segs_l = [], [] n_aud = len(audio_tokens)
def _tok(text): return tokenizer.encode(text, add_special_tokens=False)
def _embed(ids): return embed_fn(torch.tensor(ids, device=device, dtype=torch.long))
def _text_parts(parts): return "".join( p.get("content", "") or p.get("text", "") for p in parts if p.get("type") == "text")
for msg in conversation: role = msg.get("role", "") parts = msg.get("parts", [])
if role == "system": txt = _text_parts(parts) ids = _tok(f"<|im_start|>system\n{txt}<|im_end|>\n") if ids: segs_e.append(_embed(ids)) segs_l.extend([-100] * len(ids))
elif role == "user": pre = _tok("<|im_start|>user\n") if pre: segs_e.append(_embed(pre)) segs_l.extend([-100] * len(pre)) for p in parts: pt = p.get("type", "") if pt == "audio": idx = p.get("audio_index", -1) if 0 <= idx < n_aud: at = audio_tokens[idx] # Boundary markers: <|audio_start|> ... <|audio_end|> segs_e.append(self.audio_start_embed.unsqueeze(0).to(dtype=dtype)) segs_l.append(-100) segs_e.append(at) segs_l.extend([-100] * at.shape[0]) segs_e.append(self.audio_end_embed.unsqueeze(0).to(dtype=dtype)) segs_l.append(-100) elif pt == "text": txt = p.get("content", "") or p.get("text", "") if txt: ids = _tok(txt) if ids: segs_e.append(_embed(ids)) segs_l.extend([-100] * len(ids)) suf = _tok("<|im_end|>\n") if suf: segs_e.append(_embed(suf)) segs_l.extend([-100] * len(suf))
elif role == "assistant": # Standard ChatML assistant prefix (no thinking placeholder) pre = _tok("<|im_start|>assistant\n") if pre: segs_e.append(_embed(pre)) segs_l.extend([-100] * len(pre))
# ---- generation_mode: STOP HERE ---- # No response text, no <|im_end|>. # LLM continues generating from this point. if generation_mode: break
# Training mode: add response (compute loss) + eos txt = _text_parts(parts) if txt: resp_ids = _tok(txt) if resp_ids: segs_e.append(_embed(resp_ids)) segs_l.extend(resp_ids) eos = _tok("<|im_end|>") if eos: segs_e.append(_embed(eos)) segs_l.extend(eos)
if not segs_e: placeholder = _embed([tokenizer.pad_token_id or 0]) return placeholder, torch.tensor([-100], device=device, dtype=torch.long) return (torch.cat(segs_e, dim=0), torch.tensor(segs_l, device=device, dtype=torch.long))
# ---- SFT generate ----
@torch.no_grad() def generate_sft(self, mel_inputs, audio_counts, conversations, tokenizer, max_new_tokens=256, audio_frames=None, **kwargs): assert self.llm is not None was_training = self.training self.eval() device = next(self.llm.parameters()).device llm_dtype = next(self.llm.parameters()).dtype
if mel_inputs is not None and mel_inputs.numel() > 0: all_tokens, _ = self.encode_audio_batch(mel_inputs, audio_frames) else: all_tokens = [] offset = 0 per_sample = [] for cnt in audio_counts: per_sample.append( [t.to(dtype=llm_dtype) for t in all_tokens[offset:offset + cnt]]) offset += cnt
embed_fn = self.llm.get_input_embeddings() results = [] for i, conv in enumerate(conversations): # generation_mode=True → stops after assistant prefix, # no <|im_end|>, model continues generating. e, _ = self._build_sft_sample( conv, per_sample[i], tokenizer, embed_fn, device, llm_dtype, generation_mode=True) embeds = e.unsqueeze(0) mask = torch.ones(1, embeds.shape[1], device=device, dtype=torch.long)
default_eos = getattr(self.llm.generation_config, "eos_token_id", None) if default_eos is None: default_eos = getattr(self.llm.config, "eos_token_id", None) if isinstance(default_eos, int): default_eos = [default_eos]
gen_kwargs = dict( inputs_embeds=embeds, attention_mask=mask, max_new_tokens=max_new_tokens, do_sample=False, eos_token_id=default_eos, pad_token_id=default_eos[0] if default_eos else 0) gen_kwargs.update(kwargs) gen_ids = self.llm.generate(**gen_kwargs) text = tokenizer.decode(gen_ids[0], skip_special_tokens=True) results.append(text)
if was_training: self.train() return results123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109"""Text utilities for V4 multi-task evaluation.Includes: WER/CER (from v3) + accuracy + F1 + simple BLEU."""import reimport unicodedatafrom collections import Counter
# =============================================================# Language detection & normalization (from v3)# =============================================================def detect_language(text: str) -> str: if not text: return "en" cjk = sum(1 for c in text if '\u4e00' <= c <= '\u9fff') return "zh" if cjk / max(len(text), 1) >= 0.3 else "en"
def normalize_text(text: str, lang: str = None) -> str: if lang is None: lang = detect_language(text) text = text.strip().lower() text = unicodedata.normalize("NFKC", text) text = re.sub(r'[^\w\s]', '', text) if lang == "zh": text = re.sub(r'\s+', '', text) else: text = re.sub(r'\s+', ' ', text).strip() return text
# =============================================================# WER / CER# =============================================================def _edit_distance(a, b): m, n = len(a), len(b) dp = list(range(n + 1)) for i in range(1, m + 1): prev, dp[0] = dp[0], i for j in range(1, n + 1): temp = dp[j] dp[j] = prev if a[i-1] == b[j-1] else 1 + min(dp[j], dp[j-1], prev) prev = temp return dp[n]
def compute_wer(ref: str, hyp: str) -> float: ref_w = normalize_text(ref, "en").split() hyp_w = normalize_text(hyp, "en").split() if not ref_w: return 0.0 if not hyp_w else float(len(hyp_w)) return _edit_distance(ref_w, hyp_w) / len(ref_w)
def compute_cer(ref: str, hyp: str) -> float: ref_c = list(normalize_text(ref, "zh")) hyp_c = list(normalize_text(hyp, "zh")) if not ref_c: return 0.0 if not hyp_c else float(len(hyp_c)) return _edit_distance(ref_c, hyp_c) / len(ref_c)
# =============================================================# Accuracy (exact match after normalization)# =============================================================def compute_accuracy(refs: list, hyps: list) -> float: if not refs: return 0.0 correct = 0 for r, h in zip(refs, hyps): rn = normalize_text(r).strip() hn = normalize_text(h).strip() if rn == hn: correct += 1 return correct / len(refs)
# =============================================================# F1 for comma-separated labels (audio events)# =============================================================def compute_label_f1(refs: list, hyps: list) -> float: """Macro-averaged F1 over samples. Each ref/hyp is comma-separated labels.""" if not refs: return 0.0 total_f1 = 0.0 for r, h in zip(refs, hyps): ref_set = set(x.strip().lower() for x in r.split(",") if x.strip()) hyp_set = set(x.strip().lower() for x in h.split(",") if x.strip()) if not ref_set and not hyp_set: total_f1 += 1.0; continue if not ref_set or not hyp_set: continue tp = len(ref_set & hyp_set) prec = tp / len(hyp_set) if hyp_set else 0 rec = tp / len(ref_set) if ref_set else 0 total_f1 += 2*prec*rec / (prec+rec) if (prec+rec) > 0 else 0 return total_f1 / len(refs)
# =============================================================# Simple BLEU-4 (sentence level, for translation)# =============================================================def _ngrams(tokens, n): return [tuple(tokens[i:i+n]) for i in range(len(tokens)-n+1)]
def compute_bleu4(refs: list, hyps: list) -> float: if not refs: return 0.0 total = 0.0 for r, h in zip(refs, hyps): ref_tok = normalize_text(r).split() or list(normalize_text(r)) hyp_tok = normalize_text(h).split() or list(normalize_text(h)) if not ref_tok or not hyp_tok: continue bp = min(1.0, len(hyp_tok) / len(ref_tok)) if ref_tok else 0 score = bp for n in range(1, 5): ref_ng = Counter(_ngrams(ref_tok, n)) hyp_ng = Counter(_ngrams(hyp_tok, n)) matches = sum((hyp_ng & ref_ng).values()) total_hyp = max(sum(hyp_ng.values()), 1) prec = matches / total_hyp score *= max(prec, 1e-10) ** 0.25 total += score return total / len(refs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207{ "add_bos_token": false, "add_prefix_space": false, "added_tokens_decoder": { "151643": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151644": { "content": "<|im_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151645": { "content": "<|im_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151646": { "content": "<|object_ref_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151647": { "content": "<|object_ref_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151648": { "content": "<|box_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151649": { "content": "<|box_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151650": { "content": "<|quad_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151651": { "content": "<|quad_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151652": { "content": "<|vision_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151653": { "content": "<|vision_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151654": { "content": "<|vision_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151655": { "content": "<|image_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151656": { "content": "<|video_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151657": { "content": "<tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151658": { "content": "</tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151659": { "content": "<|fim_prefix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151660": { "content": "<|fim_middle|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151661": { "content": "<|fim_suffix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151662": { "content": "<|fim_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151663": { "content": "<|repo_name|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151664": { "content": "<|file_sep|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false } }, "additional_special_tokens": [ "<|im_start|>", "<|im_end|>", "<|object_ref_start|>", "<|object_ref_end|>", "<|box_start|>", "<|box_end|>", "<|quad_start|>", "<|quad_end|>", "<|vision_start|>", "<|vision_end|>", "<|vision_pad|>", "<|image_pad|>", "<|video_pad|>" ], "bos_token": null, "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", "clean_up_tokenization_spaces": false, "eos_token": "<|im_end|>", "errors": "replace", "model_max_length": 131072, "pad_token": "<|endoftext|>", "split_special_tokens": false, "tokenizer_class": "Qwen2Tokenizer", "unk_token": null}README.md+34-3
__init__.pyAdded+3
bridge.ptAdded+3
config.jsonAdded+52
configuration_hga_thinker.pyAdded+94
lora/README.mdAdded+207
lora/adapter_config.jsonAdded+48
lora/adapter_model.safetensorsAdded+3
merges.txtAdded
modeling_hga_thinker.pyAdded+332
preprocessor_config.jsonAdded+14
processor_config.jsonAdded+6
thinker/__init__.pyAdded+1
thinker/config.pyAdded+157
thinker/emca.pyAdded+181
thinker/encoder.pyAdded+253
thinker/hyperbolic_ops.pyAdded+126
thinker/model.pyAdded+512
thinker/text_utils.pyAdded+109
tokenizer.jsonAdded
tokenizer_config.jsonAdded+207
vocab.jsonAdded