"""Ultravox-style model: frozen Whisper-large-v3-turbo encoder -> stack x8 -> SwiGLU projector -> (Kev) Qwen3.5. Everything here mirrors llama.cpp so the trained projector behaves the same in GGUF: mel tools/mtmd/mtmd-audio.cpp: 128-bin log-mel, reflect pad 200 at the start, 30 s of zeros at the end, power floor 2^-24 (llama.cpp's mel_floor, NOT Whisper's 1e-10: it matters for quiet clips), cut into 3000-frame windows, the last incomplete window dropped (clips < 29.99 s give one window) encoder tools/mtmd/models/whisper-enc.cpp: conv x2 + 32 layers -> 1500 frames x 1280 per window stack clip.cpp build_stack: concat 8 consecutive frames; llama.cpp keeps 1500 // 8 = 187 tokens per window (the 188th, half zero padding, is dropped) projector whisper-enc.cpp ULTRAVOX: rms_norm(1e-6)*ln_pre -> linear_1 -> swiglu_swapped (a * silu(b), a = first half) -> rms_norm(1e-6)*ln_mid -> linear_2 The mel is checked against llama.cpp by the parity gate (scripts/parity.py), not just assumed. """ from __future__ import annotations import numpy as np import torch import torch.nn as nn import torch.nn.functional as F SR = 16000 N_FFT, HOP, N_MEL = 400, 160, 128 WIN_FRAMES = 3000 STACK = 8 MEL_FLOOR = 5.960464477539063e-08 TOK_PER_WIN = (WIN_FRAMES // 2) // STACK # 187 class RMSNorm(nn.Module): def __init__(self, dim: int, init: float = 1.0, eps: float = 1e-6): super().__init__() self.weight = nn.Parameter(torch.full((dim,), init)) self.eps = eps def forward(self, x): xf = x.float() return (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps)).to(x.dtype) * self.weight class Projector(nn.Module): def __init__(self, d_audio: int = 1280, hidden: int = 4096, d_text: int = 1024, stack: int = STACK, norm_init: float = 0.4): super().__init__() self.ln_pre = RMSNorm(d_audio * stack, init=norm_init) self.linear_1 = nn.Linear(d_audio * stack, hidden, bias=False) self.ln_mid = RMSNorm(hidden // 2, init=norm_init) self.linear_2 = nn.Linear(hidden // 2, d_text, bias=False) def forward(self, x): x = self.linear_1(self.ln_pre(x)) a, b = x.chunk(2, dim=-1) x = a * F.silu(b) return self.linear_2(self.ln_mid(x)) def stack_frames(h: torch.Tensor, k: int = STACK) -> torch.Tensor: """(B, T, D) -> (B, ceil(T/k), k*D), zero padded at the end.""" b, t, d = h.shape pad = (-t) % k if pad: h = F.pad(h, (0, 0, 0, pad)) return h.reshape(b, (t + pad) // k, k * d) _MEL_FB = None def mel_filters() -> np.ndarray: """Slaney mel filterbank (128 x 201), same as Whisper/librosa.""" global _MEL_FB if _MEL_FB is None: from transformers.audio_utils import mel_filter_bank _MEL_FB = mel_filter_bank(num_frequency_bins=1 + N_FFT // 2, num_mel_filters=N_MEL, min_frequency=0.0, max_frequency=8000.0, sampling_rate=SR, norm="slaney", mel_scale="slaney").T return _MEL_FB def log_mel_windows(wav: np.ndarray) -> np.ndarray: """float32 16 kHz mono -> (n_windows, 128, 3000) exactly as llama.cpp's whisper preprocessor.""" wav = np.asarray(wav, dtype=np.float32) pad = N_FFT // 2 n = len(wav) x = np.zeros(n + SR * 30 + 2 * pad, dtype=np.float32) x[pad:pad + n] = wav x[:pad] = wav[1:pad + 1][::-1] if n > pad else 0.0 n_len = (len(x) - N_FFT) // HOP + 1 win = np.hanning(N_FFT + 1)[:-1].astype(np.float64) # periodic hann idx = np.arange(N_FFT)[None, :] + HOP * np.arange(n_len)[:, None] spec = np.abs(np.fft.rfft(x[idx].astype(np.float64) * win, axis=1)) ** 2 # (n_len, 201) mel = mel_filters() @ spec.T # (128, n_len) mel = np.log10(np.maximum(mel, MEL_FLOOR)) mel = np.maximum(mel, mel.max() - 8.0) mel = (mel + 4.0) / 4.0 n_win = n_len // WIN_FRAMES return np.stack([mel[:, i * WIN_FRAMES:(i + 1) * WIN_FRAMES] for i in range(n_win)]).astype(np.float32) def load_encoder(path, device, dtype=torch.float16): from transformers import WhisperModel enc = WhisperModel.from_pretrained(path, dtype=dtype).encoder.to(device).eval() for p in enc.parameters(): p.requires_grad_(False) return enc @torch.no_grad() def encode_audio(enc, wav: np.ndarray, device, dtype=torch.float16) -> torch.Tensor: """-> (n_windows*187, 10240) stacked encoder frames (projector input), as many tokens as llama.cpp makes.""" mel = torch.from_numpy(log_mel_windows(wav)).to(device, dtype) h = enc(mel).last_hidden_state # (n_win, 1500, 1280) return stack_frames(h)[:, :TOK_PER_WIN].reshape(-1, h.shape[-1] * STACK)