sft-6k / modeling_hga_thinker.py
VOLBEM's picture
Add files using upload-large-folder tool
ebcf321 verified
Raw
History Blame Contribute Delete
13.9 kB
"""
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 modules
used during training, so the inference graph is byte-for-byte identical to what
produced 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/EMCA
are not LoRA-wrapped) and the adapter must be loaded into the already-LoRA-fied
LLM, exactly as training did.
"""
import os
import json
import logging
from typing import Optional, List, Union
import torch
import 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)