Open-Source Frontier Voice AI
Python
Add streaming ASR inference
AlexTYJ900ac7169a08
diff --git a/demo/vibevoice_asr_streaming_fastapi_demo.py b/demo/vibevoice_asr_streaming_fastapi_demo.pynew file mode 100644index 0000000..89b7374--- /dev/null+++ b/demo/vibevoice_asr_streaming_fastapi_demo.py@@ -0,0 +1,372 @@+"""FastAPI streaming ASR demo for VibeVoice-ASR-Streaming.++Loads the checkpoint in-process and serves a page that transcribes while the+audio is still arriving. Run it, then open the printed URL.+"""++import argparse+import asyncio+import json+import os++import numpy as np+import torch+import uvicorn+from fastapi import FastAPI, WebSocket, WebSocketDisconnect+from fastapi.responses import HTMLResponse, JSONResponse++from vibevoice.modular.modeling_vibevoice_asr import VibeVoiceASRForConditionalGeneration+from vibevoice.processor.vibevoice_asr_processor import VibeVoiceASRProcessor++state = {}+gpu_lock = asyncio.Lock()+++def load_model(model_path: str, device: str, attn_implementation: str):+ # A local checkpoint directory or a HF repo id, the same as the+ # from_pretrained calls below.+ name = "preprocessor_config.json"+ if os.path.isdir(model_path):+ config_path = os.path.join(model_path, name)+ else:+ from huggingface_hub import hf_hub_download++ config_path = hf_hub_download(model_path, name)++ with open(config_path) as f:+ cfg = json.load(f)++ missing = [k for k in ("chunk_frames", "lookahead_frames") if k not in cfg]+ if missing:+ raise SystemExit(+ f"{config_path} has no {', '.join(missing)}, so {model_path} is not "+ "a streaming checkpoint. Serve it with "+ "demo/vibevoice_asr_gradio_demo.py instead.")++ sample_rate = cfg["target_sample_rate"]+ # Streaming model: the frame size is the checkpoint's, never a constant --+ # a wrong one mis-cuts every window without raising.+ frame_samples = cfg["speech_tok_compress_ratio"]+ chunk_samples = cfg["chunk_frames"] * frame_samples+ lookahead_samples = cfg["lookahead_frames"] * frame_samples++ processor = VibeVoiceASRProcessor.from_pretrained(model_path)+ if processor.tokenizer.text_chunk_end_id is None:+ raise SystemExit(+ f"{model_path} is not a streaming checkpoint: its tokenizer has no "+ "<|text_chunk_end|>, so no chunk would ever end.")++ model = VibeVoiceASRForConditionalGeneration.from_pretrained(+ model_path,+ dtype=torch.bfloat16,+ device_map=device,+ attn_implementation=attn_implementation,+ ).eval()++ state.update(+ model=model,+ tokenizer=processor.tokenizer,+ sample_rate=sample_rate,+ chunk_samples=chunk_samples,+ window_samples=chunk_samples + lookahead_samples,+ chunk_seconds=chunk_samples / sample_rate,+ )+ print(f"chunk {cfg['chunk_frames']} frames ({chunk_samples / sample_rate:.4f}s), "+ f"lookahead {cfg['lookahead_frames']} frames")+++def transcribe_window(window: np.ndarray, session: dict) -> str:+ """Encode one window and advance the model by one chunk."""+ model = state["model"]+ audio = torch.from_numpy(window).to(next(model.parameters()).device)+ features = model.encode_speech(audio.unsqueeze(0))+ text, _ = model.streaming_generate_step(+ audio_features=features,+ streaming_state=session["stream"],+ tokenizer=state["tokenizer"],+ max_new_tokens=session["max_tokens"],+ temperature=session["temperature"],+ )+ return text+++app = FastAPI(title="VibeVoice streaming ASR demo")++[email protected]("/healthz")+async def healthz():+ return JSONResponse({"status": "ok" if state else "loading"})++[email protected]("/config")+async def config():+ return JSONResponse({+ "sample_rate": state["sample_rate"],+ "chunk_seconds": state["chunk_seconds"],+ })++[email protected]("/", response_class=HTMLResponse)+async def index():+ return PAGE++[email protected]("/ws/asr")+async def ws_asr(ws: WebSocket):+ await ws.accept()+ try:+ opts = json.loads(await ws.receive_text())+ except Exception:+ await ws.close()+ return++ model = state["model"]+ window_samples = state["window_samples"]+ chunk_samples = state["chunk_samples"]++ async with gpu_lock:+ session = {+ "stream": model.init_streaming_state(+ state["tokenizer"], context_info=opts.get("context_info") or None),+ "max_tokens": int(opts.get("max_tokens") or 256),+ "temperature": float(opts.get("temperature") or 0.0),+ }++ buffer = np.zeros(0, dtype=np.float32)+ texts = []++ async def drain(flush: bool):+ nonlocal buffer+ while True:+ available = len(buffer)+ if available >= window_samples:+ window = buffer[:window_samples]+ elif flush and available > 0:+ window = np.zeros(window_samples, dtype=np.float32)+ window[:available] = buffer+ else:+ return+ async with gpu_lock:+ text = await asyncio.to_thread(transcribe_window, window, session)+ texts.append(text)+ # Drop the advance, keep the lookahead: it is the next chunk's+ # leading audio. Consuming rather than indexing is what bounds a+ # long recording -- an index-only cursor keeps every sample of the+ # session alive and re-copies all of it on each incoming frame.+ buffer = buffer[chunk_samples:]+ await ws.send_text(json.dumps({"chunks": len(texts),+ "text": "".join(texts)}))+ if flush and len(buffer) <= 0:+ return++ try:+ while True:+ message = await ws.receive()+ if message.get("type") == "websocket.disconnect":+ return+ if message.get("bytes") is not None:+ pcm = np.frombuffer(message["bytes"], dtype="<f4")+ buffer = np.concatenate([buffer, pcm])+ await drain(flush=False)+ elif message.get("text") == "end":+ await drain(flush=True)+ await ws.send_text(json.dumps({"chunks": len(texts),+ "text": "".join(texts),+ "done": True,+ "total_chunks": len(texts)}))+ return+ except WebSocketDisconnect:+ return+ except Exception as e:+ try:+ await ws.send_text(json.dumps({"error": str(e)}))+ except Exception:+ pass+++PAGE = """<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>VibeVoice Streaming ASR</title>+<style>+ :root {+ color-scheme: dark;+ --bg:#0f1117; --panel:#171a23; --line:#262b38; --fg:#e6e8ef;+ --muted:#8b93a7; --accent:#5b8cff; --rec:#ff4d5e; --ok:#31c48d;+ --ghost:#232838; --field:#10131c;+ }+ * { box-sizing: border-box; }+ body { margin:0; background:var(--bg); color:var(--fg); font-size:15px;+ font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,+ "Helvetica Neue","PingFang SC","Microsoft YaHei",sans-serif; }+ header { padding:18px 24px; border-bottom:1px solid var(--line);+ display:flex; align-items:center; gap:12px; flex-wrap:wrap; }+ h1 { font-size:17px; margin:0; font-weight:600; }+ .dot { width:8px; height:8px; border-radius:50%; background:var(--muted); }+ .dot.ok { background:var(--ok); }+ .dot.rec { background:var(--rec); animation:pulse 1.2s infinite; }+ @keyframes pulse { 50% { opacity:.25; } }+ main { display:grid; grid-template-columns:320px 1fr; gap:20px; padding:20px 24px;+ min-height:calc(100vh - 118px); align-content:stretch; }+ main > * { min-width:0; }+ .panel { background:var(--panel); border:1px solid var(--line);+ border-radius:10px; padding:16px; }+ .panel h2 { font-size:13px; text-transform:uppercase; letter-spacing:.06em;+ color:var(--muted); margin:0 0 12px; font-weight:600; }+ button { font:inherit; border:0; border-radius:8px; padding:10px 16px;+ background:var(--accent); color:#fff; cursor:pointer; min-height:40px; }+ button.ghost { background:var(--ghost); color:var(--fg); }+ button:disabled { opacity:.45; cursor:not-allowed; }+ label { display:block; font-size:13px; color:var(--muted); margin:14px 0 6px; }+ input[type=text], input[type=number] { width:100%; padding:9px 11px;+ border-radius:8px; border:1px solid var(--line); background:var(--field);+ color:var(--fg); font:inherit; }+ input[type=file] { width:100%; font-size:13px; color:var(--muted); }+ .row { display:flex; gap:10px; flex-wrap:wrap; }+ #out { white-space:pre-wrap; word-break:break-word; line-height:1.75;+ min-height:320px; }+ #out:empty::before { content:"Transcript appears here as you speak.";+ color:var(--muted); }+ .status { font-size:13px; color:var(--muted); margin-top:12px; }+</style>+</head>+<body>+<header>+ <h1>VibeVoice Streaming ASR</h1>+ <span class="dot" id="dot"></span>+ <span class="status" id="conn" style="margin:0">idle</span>+</header>+<main>+ <div class="panel">+ <h2>Input</h2>+ <div class="row">+ <button id="rec">Record</button>+ <button id="stop" class="ghost" disabled>Stop</button>+ </div>+ <label>Or transcribe a file</label>+ <input type="file" id="file" accept="audio/*,video/*">+ <label>Hotwords (context_info)</label>+ <input type="text" id="ctx" placeholder="Microsoft,VibeVoice">+ <label>Temperature</label>+ <input type="number" id="temp" value="0" min="0" max="2" step="0.1">+ <div class="status" id="status">ready</div>+ </div>+ <div class="panel">+ <h2>Transcript</h2>+ <div id="out"></div>+ </div>+</main>+<script>+const $ = id => document.getElementById(id);+let SR = 24000, sock = null, ctxAudio = null, node = null, media = null;++fetch('/config').then(r => r.json()).then(c => { SR = c.sample_rate; });++function setConn(text, cls) {+ $('conn').textContent = text;+ $('dot').className = 'dot' + (cls ? ' ' + cls : '');+}+function options() {+ return { context_info: $('ctx').value.trim() || null,+ temperature: parseFloat($('temp').value) || 0,+ max_tokens: 256 };+}+function connect() {+ return new Promise((resolve, reject) => {+ const proto = location.protocol === 'https:' ? 'wss' : 'ws';+ const ws = new WebSocket(proto + '://' + location.host + '/ws/asr');+ ws.onopen = () => { ws.send(JSON.stringify(options())); setConn('connected', 'ok'); resolve(ws); };+ ws.onerror = () => reject(new Error('connection failed'));+ ws.onclose = () => setConn('idle', '');+ ws.onmessage = ev => {+ const msg = JSON.parse(ev.data);+ if (msg.error) { $('status').textContent = 'error: ' + msg.error; return; }+ $('out').textContent = msg.text || '';+ $('status').textContent = msg.done+ ? 'done -- ' + msg.total_chunks + ' chunks'+ : 'receiving -- ' + msg.chunks + ' chunks';+ if (msg.done) finish();+ };+ });+}+function finish() {+ $('rec').disabled = false; $('stop').disabled = true; $('file').disabled = false;+ setConn('idle', '');+ if (node) { node.disconnect(); node = null; }+ if (media) { media.getTracks().forEach(t => t.stop()); media = null; }+ if (ctxAudio) { ctxAudio.close(); ctxAudio = null; }+}++$('rec').onclick = async () => {+ $('out').textContent = ''; $('status').textContent = 'starting...';+ try {+ media = await navigator.mediaDevices.getUserMedia({ audio: true });+ } catch (e) { $('status').textContent = 'microphone denied'; return; }+ sock = await connect();+ $('rec').disabled = true; $('stop').disabled = false; $('file').disabled = true;+ setConn('recording', 'rec');+ ctxAudio = new AudioContext({ sampleRate: SR });+ const src = ctxAudio.createMediaStreamSource(media);+ node = ctxAudio.createScriptProcessor(4096, 1, 1);+ node.onaudioprocess = e => {+ if (!sock || sock.readyState !== WebSocket.OPEN) return;+ sock.send(new Float32Array(e.inputBuffer.getChannelData(0)).buffer);+ };+ src.connect(node); node.connect(ctxAudio.destination);+};++$('stop').onclick = () => {+ $('status').textContent = 'flushing...';+ if (sock && sock.readyState === WebSocket.OPEN) sock.send('end');+ $('stop').disabled = true;+};++$('file').onchange = async ev => {+ const f = ev.target.files[0];+ if (!f) return;+ $('out').textContent = ''; $('status').textContent = 'decoding...';+ const raw = await f.arrayBuffer();+ const tmp = new AudioContext();+ const decoded = await tmp.decodeAudioData(raw);+ tmp.close();+ const off = new OfflineAudioContext(1, Math.ceil(decoded.duration * SR), SR);+ const s = off.createBufferSource();+ s.buffer = decoded; s.connect(off.destination); s.start();+ const pcm = (await off.startRendering()).getChannelData(0);++ sock = await connect();+ $('rec').disabled = true; $('file').disabled = true;+ $('status').textContent = 'streaming...';+ // Send in the cadence a microphone would produce, so text arrives gradually.+ for (let i = 0; i < pcm.length; i += SR / 2) {+ sock.send(new Float32Array(pcm.slice(i, i + SR / 2)).buffer);+ await new Promise(r => setTimeout(r, 10));+ }+ sock.send('end');+};+</script>+</body>+</html>+"""+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--model_path", required=True,+ help="Path to a streaming checkpoint")+ parser.add_argument("--host", default="0.0.0.0")+ parser.add_argument("--port", type=int, default=7870)+ parser.add_argument("--device", default="cuda")+ parser.add_argument("--attn_implementation", default="sdpa",+ choices=["sdpa", "flash_attention_2", "eager"])+ args = parser.parse_args()++ load_model(args.model_path, args.device, args.attn_implementation)+ print(f"open http://localhost:{args.port}")+ uvicorn.run(app, host=args.host, port=args.port)+++if __name__ == "__main__":+ main()diff --git a/demo/vibevoice_asr_streaming_inference_from_file.py b/demo/vibevoice_asr_streaming_inference_from_file.pynew file mode 100644index 0000000..851b727--- /dev/null+++ b/demo/vibevoice_asr_streaming_inference_from_file.py@@ -0,0 +1,158 @@+#!/usr/bin/env python+"""+VibeVoice ASR Streaming Inference Demo Script++This script transcribes audio files chunk by chunk, printing each chunk as+soon as the model emits it instead of waiting for the whole file.+"""++import argparse+import json+import os+import time++import torch++from vibevoice.modular.modeling_vibevoice_asr import VibeVoiceASRForConditionalGeneration+from vibevoice.processor.audio_utils import load_audio_use_ffmpeg+from vibevoice.processor.vibevoice_asr_processor import VibeVoiceASRProcessor+++def load_frame_config(model_path: str) -> dict:+ """Read the chunk and lookahead the checkpoint was trained on.++ Takes a local checkpoint directory or a HF repo id, the same as the+ ``from_pretrained`` calls below.+ """+ name = "preprocessor_config.json"+ if os.path.isdir(model_path):+ config_path = os.path.join(model_path, name)+ else:+ from huggingface_hub import hf_hub_download++ config_path = hf_hub_download(model_path, name)++ with open(config_path) as f:+ cfg = json.load(f)++ missing = [k for k in ("chunk_frames", "lookahead_frames") if k not in cfg]+ if missing:+ raise SystemExit(+ f"{config_path} has no {', '.join(missing)}, so {model_path} is not "+ "a streaming checkpoint. Transcribe it with "+ "demo/vibevoice_asr_inference_from_file.py instead."+ )++ sample_rate = cfg["target_sample_rate"]+ frame_seconds = cfg["speech_tok_compress_ratio"] / sample_rate+ return {+ "sample_rate": sample_rate,+ "chunk_duration": cfg["chunk_frames"] * frame_seconds,+ "text_audio_delay": cfg["lookahead_frames"] * frame_seconds,+ }+++def main():+ parser = argparse.ArgumentParser(description="VibeVoice ASR Streaming Inference Demo")+ parser.add_argument(+ "--model_path",+ type=str,+ required=True,+ help="Path to the streaming model checkpoint"+ )+ parser.add_argument(+ "--audio_files",+ type=str,+ nargs='+',+ required=True,+ help="Paths to audio files for transcription"+ )+ parser.add_argument(+ "--context_info",+ type=str,+ default=None,+ help="Hotwords to bias recognition, e.g. 'Microsoft,VibeVoice'"+ )+ parser.add_argument(+ "--device",+ type=str,+ default="cuda" if torch.cuda.is_available() else "cpu",+ choices=["cuda", "cpu", "mps", "xpu"],+ help="Device to run inference on"+ )+ parser.add_argument(+ "--max_new_tokens",+ type=int,+ default=256,+ help="Maximum number of tokens to generate per chunk"+ )+ parser.add_argument(+ "--temperature",+ type=float,+ default=0.0,+ help="Temperature for sampling (0 = greedy decoding)"+ )+ parser.add_argument(+ "--attn_implementation",+ type=str,+ default="sdpa",+ choices=["flash_attention_2", "sdpa", "eager"],+ help="Attention implementation to use"+ )++ args = parser.parse_args()++ frame_config = load_frame_config(args.model_path)+ sample_rate = frame_config["sample_rate"]++ print(f"Loading VibeVoice ASR streaming model from {args.model_path}")+ processor = VibeVoiceASRProcessor.from_pretrained(args.model_path)+ if processor.tokenizer.text_chunk_end_id is None:+ raise SystemExit(+ f"{args.model_path} is not a streaming checkpoint: its tokenizer has no "+ "<|text_chunk_end|>, so no chunk would ever end."+ )++ model_dtype = torch.bfloat16 if args.device == "cuda" else torch.float32+ model = VibeVoiceASRForConditionalGeneration.from_pretrained(+ args.model_path,+ dtype=model_dtype,+ attn_implementation=args.attn_implementation,+ ).to(args.device).eval()++ print(f"Model loaded successfully on {args.device}")+ print(f"Chunk: {frame_config['chunk_duration']:.4f}s, "+ f"lookahead: {frame_config['text_audio_delay']:.4f}s")++ for audio_file in args.audio_files:+ print("\n" + "=" * 80)+ print(f"File: {audio_file}")+ print("=" * 80)++ audio, _ = load_audio_use_ffmpeg(audio_file, resample=True, target_sr=sample_rate)+ duration = len(audio) / sample_rate++ start_time = time.time()+ chunks = []+ for chunk_index, total_chunks, chunk_text in model.streaming_generate(+ audio_tensor=torch.from_numpy(audio),+ tokenizer=processor.tokenizer,+ chunk_duration=frame_config["chunk_duration"],+ text_audio_delay=frame_config["text_audio_delay"],+ sample_rate=sample_rate,+ max_new_tokens_per_chunk=args.max_new_tokens,+ temperature=args.temperature,+ context_info=args.context_info,+ ):+ chunks.append(chunk_text)+ print(f"[{chunk_index + 1}/{total_chunks}] {chunk_text}", flush=True)++ elapsed = time.time() - start_time+ print("\n--- Transcription ---")+ print("".join(chunks))+ print(f"\nAudio: {duration:.2f}s, generation time: {elapsed:.2f}s, "+ f"RTF: {elapsed / duration:.3f}")+++if __name__ == "__main__":+ main()diff --git a/docs/vibevoice-asr-streaming.md b/docs/vibevoice-asr-streaming.mdnew file mode 100644index 0000000..e9d6e31--- /dev/null+++ b/docs/vibevoice-asr-streaming.md@@ -0,0 +1,52 @@+# VibeVoice-ASR-Streaming++**VibeVoice-ASR-Streaming** transcribes while the audio is still arriving, instead of waiting for it to end. It emits text once per audio chunk, so a transcript appears as the speaker talks.++**Non-streaming:** [VibeVoice-ASR](./vibevoice-asr.md)<br>+**vLLM:** [vLLM-asr-streaming](./vibevoice-vllm-asr-streaming.md)<br>++## Installation+We recommend using NVIDIA Deep Learning Container to manage the CUDA environment.++1. Launch docker+```bash+# NVIDIA PyTorch Container 24.07 ~ 25.12 verified.+# Previous versions are also compatible.+sudo docker run --privileged --net=host --ipc=host --ulimit memlock=-1:-1 --ulimit stack=-1:-1 --gpus all --rm -it nvcr.io/nvidia/pytorch:25.12-py3++## If flash attention is not included in your docker environment, you need to install it manually+## Refer to https://github.com/Dao-AILab/flash-attention for installation instructions+# pip install flash-attn --no-build-isolation+```++2. Install from github+```bash+git clone https://github.com/microsoft/VibeVoice.git+cd VibeVoice++pip install -e .+```++## Usages++### Usage 1: Launch the FastAPI demo+```bash+apt update && apt install ffmpeg -y # for demo++python demo/vibevoice_asr_streaming_fastapi_demo.py --model_path [add the checkpoint path here]+```++Open `http://localhost:7870`, then record from the microphone or pick a file. The page keeps a WebSocket open for the whole recording, so text appears while you are still speaking.++### Usage 2: Inference from files directly+```bash+python demo/vibevoice_asr_streaming_inference_from_file.py --model_path [add the checkpoint path here] --audio_files [add an audio path here]+```++Each chunk is printed as soon as the model emits it. Add `--context_info "Microsoft,VibeVoice"` to bias recognition toward specific terms, the same way hotwords work on the non-streaming model.++The chunk and lookahead are read from the checkpoint's `preprocessor_config.json`, so a checkpoint always runs at the chunk it was trained on.++## 📄 License++This project is licensed under the [MIT License](../LICENSE).diff --git a/vibevoice/modular/modeling_vibevoice_asr.py b/vibevoice/modular/modeling_vibevoice_asr.pyindex 4663d3f..cb8559f 100644--- a/vibevoice/modular/modeling_vibevoice_asr.py+++ b/vibevoice/modular/modeling_vibevoice_asr.py@@ -1,6 +1,8 @@-from typing import List, Optional, Tuple, Union+from typing import Callable, List, Optional, Tuple, Union+import mathimport torchimport torch.nn as nn+import torch.nn.functional as Ffrom transformers.models.auto import AutoModel, AutoModelForCausalLM@@ -423,6 +425,280 @@ class VibeVoiceASRForConditionalGeneration(VibeVoiceASRPreTrainedModel, Generatiattentions=outputs.attentions,)+ @torch.no_grad()+ def streaming_generate(+ self,+ audio_tensor: torch.FloatTensor,+ tokenizer,+ prompt_text: str = None,+ chunk_duration: float = 2.0,+ text_audio_delay: float = None,+ sample_rate: int = 24000,+ max_new_tokens_per_chunk: int = 256,+ temperature: float = 0.0,+ context_info: str = None,+ encode_mode: str = "split_then_encode",+ repetition_penalty: float = 1.0,+ pad_last_chunk: bool = True,+ ):+ """Streaming model: chunked ASR inference over a full audio tensor."""+ device = next(self.parameters()).device++ sp_start_id = tokenizer.speech_start_id+ sp_end_id = tokenizer.speech_end_id+ text_chunk_end_id = tokenizer.text_chunk_end_id+ eos_id = tokenizer.eos_token_id++ embed_tokens = self.get_input_embeddings()++ if prompt_text is None:+ keys_str = "speaker, content"+ if context_info:+ prompt_text = (+ "You are a helpful assistant that transcribes audio input into text output. "+ f"Please transcribe the following audios streamingly with these keys: {keys_str} "+ f"and extra info: {context_info}\n"+ )+ else:+ prompt_text = (+ "You are a helpful assistant that transcribes audio input into text output. "+ f"Please transcribe the following audios streamingly with these keys: {keys_str}\n"+ )++ prompt_ids = tokenizer.encode(prompt_text, add_special_tokens=False)+ prompt_tensor = torch.tensor([prompt_ids], dtype=torch.long, device=device)+ prompt_embeds = embed_tokens(prompt_tensor)++ if audio_tensor.ndim == 1:+ audio_tensor = audio_tensor.unsqueeze(0)+ audio_tensor = audio_tensor.to(device)++ if encode_mode == "encode_then_split":+ all_features = self.encode_speech(audio_tensor)+ total_tokens = all_features.shape[1]+ audio_duration = audio_tensor.shape[1] / sample_rate+ tps = total_tokens / audio_duration if audio_duration > 0 else 7.5+ tokens_per_chunk = max(1, math.ceil(chunk_duration * tps))++ _frame_dur = 3200 / sample_rate+ _delay = text_audio_delay if text_audio_delay is not None else 0.5+ lookahead_sec = round(_delay / _frame_dur) * _frame_dur+ lookahead_tokens = int(round(lookahead_sec * tps))++ feature_chunks = []+ text_start = 0+ while text_start < total_tokens:+ audio_end = min(text_start + tokens_per_chunk + lookahead_tokens, total_tokens)+ if audio_end > text_start:+ feature_chunks.append(all_features[:, text_start:audio_end, :])+ text_start = min(text_start + tokens_per_chunk, total_tokens)+ else:+ total_samples = audio_tensor.shape[1]+ chunk_samples = int(chunk_duration * sample_rate)++ _frame_dur = 3200 / sample_rate+ _delay = text_audio_delay if text_audio_delay is not None else 0.5+ lookahead_sec = round(_delay / _frame_dur) * _frame_dur+ lookahead_samples = int(lookahead_sec * sample_rate)++ feature_chunks = []+ text_start_sample = 0+ _target_samples = chunk_samples + lookahead_samples+ while text_start_sample < total_samples:+ audio_end_sample = min(text_start_sample + chunk_samples + lookahead_samples, total_samples)+ if audio_end_sample > text_start_sample:+ seg = audio_tensor[:, text_start_sample:audio_end_sample]+ if pad_last_chunk and seg.shape[1] < _target_samples:+ seg = F.pad(seg, (0, _target_samples - seg.shape[1]))+ chunk_features = self.encode_speech(seg)+ feature_chunks.append(chunk_features)+ text_start_sample = min(text_start_sample + chunk_samples, total_samples)++ total_chunks = len(feature_chunks)++ outputs = self(+ inputs_embeds=prompt_embeds,+ use_cache=True,+ return_dict=True,+ )+ past_key_values = outputs.past_key_values++ sp_start_embed = embed_tokens(torch.tensor([[sp_start_id]], device=device))+ sp_end_embed = embed_tokens(torch.tensor([[sp_end_id]], device=device))++ for chunk_idx, feat_chunk in enumerate(feature_chunks):+ audio_embeds = torch.cat([sp_start_embed, feat_chunk, sp_end_embed], dim=1)++ outputs = self(+ inputs_embeds=audio_embeds,+ past_key_values=past_key_values,+ use_cache=True,+ return_dict=True,+ )+ past_key_values = outputs.past_key_values+ next_logits = outputs.logits[:, -1:, :]++ chunk_tokens = []+ for _ in range(max_new_tokens_per_chunk):+ logits = next_logits[:, -1, :]++ if repetition_penalty != 1.0 and chunk_tokens:+ prev_ids = torch.tensor(chunk_tokens, device=logits.device)+ prev_logits = logits[:, prev_ids]+ prev_logits = torch.where(+ prev_logits > 0,+ prev_logits / repetition_penalty,+ prev_logits * repetition_penalty,+ )+ logits[:, prev_ids] = prev_logits++ if temperature <= 0:+ next_token_id = torch.argmax(logits, dim=-1).item()+ else:+ probs = F.softmax(logits / temperature, dim=-1)+ next_token_id = torch.multinomial(probs, num_samples=1).squeeze(-1).item()++ if next_token_id == text_chunk_end_id or next_token_id == eos_id:+ break++ chunk_tokens.append(next_token_id)++ next_embed = embed_tokens(torch.tensor([[next_token_id]], device=device))+ outputs = self(+ inputs_embeds=next_embed,+ past_key_values=past_key_values,+ use_cache=True,+ return_dict=True,+ )+ past_key_values = outputs.past_key_values+ next_logits = outputs.logits++ tce_embed = embed_tokens(torch.tensor([[text_chunk_end_id]], device=device))+ outputs = self(+ inputs_embeds=tce_embed,+ past_key_values=past_key_values,+ use_cache=True,+ return_dict=True,+ )+ past_key_values = outputs.past_key_values++ chunk_text = tokenizer.decode(chunk_tokens, skip_special_tokens=True)+ for _st in ['<|text_chunk_end|>', '<|object_ref_start|>', '<|object_ref_end|>',+ '<|box_start|>', '<|speech_start|>', '<|speech_end|>', '<|speech_pad|>']:+ chunk_text = chunk_text.replace(_st, '')+ yield chunk_idx, total_chunks, chunk_text++ @torch.no_grad()+ def init_streaming_state(self, tokenizer, context_info: str = None):+ """Streaming model: build the initial KV cache and cached embeddings."""+ device = next(self.parameters()).device+ embed_tokens = self.get_input_embeddings()++ keys_str = "speaker, content"+ if context_info:+ prompt_text = (+ "You are a helpful assistant that transcribes audio input into text output. "+ f"Please transcribe the following audios streamingly with these keys: {keys_str} "+ f"and extra info: {context_info}\n"+ )+ else:+ prompt_text = (+ "You are a helpful assistant that transcribes audio input into text output. "+ f"Please transcribe the following audios streamingly with these keys: {keys_str}\n"+ )++ prompt_ids = tokenizer.encode(prompt_text, add_special_tokens=False)+ prompt_tensor = torch.tensor([prompt_ids], dtype=torch.long, device=device)+ prompt_embeds = embed_tokens(prompt_tensor)++ outputs = self(+ inputs_embeds=prompt_embeds,+ use_cache=True,+ return_dict=True,+ )++ return {+ "past_key_values": outputs.past_key_values,+ "sp_start_embed": embed_tokens(torch.tensor([[tokenizer.speech_start_id]], device=device)),+ "sp_end_embed": embed_tokens(torch.tensor([[tokenizer.speech_end_id]], device=device)),+ "text_chunk_end_id": tokenizer.text_chunk_end_id,+ "eos_id": tokenizer.eos_token_id,+ "embed_tokens": embed_tokens,+ }++ @torch.no_grad()+ def streaming_generate_step(+ self,+ audio_features: torch.FloatTensor,+ streaming_state: dict,+ tokenizer,+ max_new_tokens: int = 256,+ temperature: float = 0.0,+ on_first_token: Optional[Callable[[int], None]] = None,+ ) -> Tuple[str, dict]:+ """Streaming model: advance one audio chunk against the running KV cache."""+ device = next(self.parameters()).device+ past_key_values = streaming_state["past_key_values"]+ sp_start_embed = streaming_state["sp_start_embed"]+ sp_end_embed = streaming_state["sp_end_embed"]+ text_chunk_end_id = streaming_state["text_chunk_end_id"]+ eos_id = streaming_state["eos_id"]+ embed_tokens = streaming_state["embed_tokens"]++ audio_embeds = torch.cat([sp_start_embed, audio_features, sp_end_embed], dim=1)++ outputs = self(+ inputs_embeds=audio_embeds,+ past_key_values=past_key_values,+ use_cache=True,+ return_dict=True,+ )+ past_key_values = outputs.past_key_values+ next_logits = outputs.logits[:, -1:, :]++ chunk_tokens = []+ for _ in range(max_new_tokens):+ if temperature <= 0:+ next_token_id = torch.argmax(next_logits[:, -1, :], dim=-1).item()+ else:+ probs = F.softmax(next_logits[:, -1, :] / temperature, dim=-1)+ next_token_id = torch.multinomial(probs, num_samples=1).squeeze(-1).item()++ if next_token_id == text_chunk_end_id or next_token_id == eos_id:+ break++ chunk_tokens.append(next_token_id)+ if len(chunk_tokens) == 1 and on_first_token is not None:+ on_first_token(next_token_id)++ next_embed = embed_tokens(torch.tensor([[next_token_id]], device=device))+ outputs = self(+ inputs_embeds=next_embed,+ past_key_values=past_key_values,+ use_cache=True,+ return_dict=True,+ )+ past_key_values = outputs.past_key_values+ next_logits = outputs.logits++ tce_embed = embed_tokens(torch.tensor([[text_chunk_end_id]], device=device))+ outputs = self(+ inputs_embeds=tce_embed,+ past_key_values=past_key_values,+ use_cache=True,+ return_dict=True,+ )+ past_key_values = outputs.past_key_values++ streaming_state["past_key_values"] = past_key_values++ chunk_text = tokenizer.decode(chunk_tokens, skip_special_tokens=True)+ for _st in ['<|text_chunk_end|>', '<|object_ref_start|>', '<|object_ref_end|>',+ '<|box_start|>', '<|speech_start|>', '<|speech_end|>', '<|speech_pad|>']:+ chunk_text = chunk_text.replace(_st, '')++ return chunk_text, streaming_state+def prepare_inputs_for_generation(self,input_ids,diff --git a/vibevoice/modular/modular_vibevoice_text_tokenizer.py b/vibevoice/modular/modular_vibevoice_text_tokenizer.pyindex 9532d9f..5391586 100644--- a/vibevoice/modular/modular_vibevoice_text_tokenizer.py+++ b/vibevoice/modular/modular_vibevoice_text_tokenizer.py@@ -271,11 +271,15 @@ class VibeVoiceASRTextTokenizerFast(Qwen2TokenizerFast):]}num_added = self.add_special_tokens(special_tokens)-+# Cache special token IDsself._speech_start_id = self.convert_tokens_to_ids("<|object_ref_start|>")self._speech_end_id = self.convert_tokens_to_ids("<|object_ref_end|>")self._speech_pad_id = self.convert_tokens_to_ids("<|box_start|>")+ # Streaming model: read only, never added to the vocabulary.+ self._text_chunk_end_id = self.convert_tokens_to_ids("<|text_chunk_end|>")+ if self._text_chunk_end_id == self.unk_token_id:+ self._text_chunk_end_id = Noneself._eos_id = self.eos_token_id # qwen2 / qwen3self._pad_id = self.convert_tokens_to_ids('<|image_pad|>')@@ -302,6 +306,11 @@ class VibeVoiceASRTextTokenizerFast(Qwen2TokenizerFast):"""ID of the speech diffusion token."""return self._speech_pad_id+ @property+ def text_chunk_end_id(self) -> int:+ """ID of the text chunk end token (for streaming)."""+ return self._text_chunk_end_id+@propertydef pad_id(self) -> int:return self._pad_iddiff --git a/vibevoice/processor/vibevoice_asr_processor.py b/vibevoice/processor/vibevoice_asr_processor.pyindex cacb116..0ffa666 100644--- a/vibevoice/processor/vibevoice_asr_processor.py+++ b/vibevoice/processor/vibevoice_asr_processor.py@@ -27,6 +27,21 @@ logger = logging.get_logger(__name__)SYSTEM_PROMPT = "You are a helpful assistant that transcribes audio input into text output in JSON format."+def _ships_tokenizer(pretrained_model_name_or_path, **kwargs) -> bool:+ """Whether a checkpoint carries its own tokenizer files."""+ from transformers.utils import cached_file++ if os.path.exists(os.path.join(str(pretrained_model_name_or_path),+ "tokenizer_config.json")):+ return True+ try:+ cached_file(pretrained_model_name_or_path, "tokenizer_config.json",+ **kwargs)+ return True+ except Exception:+ return False++class VibeVoiceASRProcessor:"""Processor for VibeVoice ASR (Automatic Speech Recognition) models.@@ -134,11 +149,28 @@ class VibeVoiceASRProcessor:target_sample_rate = config.get("target_sample_rate", 24000)normalize_audio = config.get("normalize_audio", True)- # Load tokenizer- language_model_pretrained_name = config.get("language_model_pretrained_name", None) or kwargs.pop("language_model_pretrained_name", "Qwen/Qwen2.5-1.5B")+ # Streaming model: its own tokenizer files win over any base-LM name,+ # because <|text_chunk_end|> lives in them and not in the base vocabulary.+ explicit_name = kwargs.pop("language_model_pretrained_name", None)+ own_tokenizer = _ships_tokenizer(pretrained_model_name_or_path, **kwargs)+ if own_tokenizer:+ language_model_pretrained_name = pretrained_model_name_or_path+ else:+ language_model_pretrained_name = (+ config.get("language_model_pretrained_name", None)+ or explicit_name+ or "Qwen/Qwen2.5-1.5B")+ if explicit_name and explicit_name != language_model_pretrained_name:+ # Dropping it silently surfaces much later as a vocabulary mismatch,+ # by which point the argument looks like it was honoured.+ logger.warning(+ f"ignoring language_model_pretrained_name={explicit_name!r}: "+ f"loading the tokenizer from {language_model_pretrained_name}, "+ + ("which ships its own tokenizer files" if own_tokenizer+ else "as named in preprocessor_config.json"))logger.info(f"Loading tokenizer from {language_model_pretrained_name}")-- if 'qwen' in language_model_pretrained_name.lower():++ if own_tokenizer or 'qwen' in str(language_model_pretrained_name).lower():tokenizer = VibeVoiceASRTextTokenizerFast.from_pretrained(language_model_pretrained_name,**kwargs