"""Babelfish-SimulST: speech-to-text simultaneous EN⇄ZH translation on ZeroGPU. This Space runs timekettle/Babelfish-SimulST (a Qwen3-Omni-30B-A3B finetune for simultaneous speech translation) locally with transformers, using the authors' native FP8 (e4m3, 128x128 blockwise) checkpoint — the 30 GiB release that fits ZeroGPU's 48 GB slice — and replays an uploaded utterance 320 ms at a time through the authors' exact streaming policy (window / anchor / context rule / repetition guard), so the visitor sees the translation grow block by block, exactly as the live engine would produce it. Committed text is never revised. The policy code below is a faithful port of the reference implementation in github.com/timekettle-lab/Babelfish-SimulST (simulst/common.py, policy.py, ctx_rule.py, loop_guard.py, engines/vllm_engine.py). The only deviation: the model is served with transformers instead of vLLM, because ZeroGPU does not support vLLM. FP8 matmuls run on the Triton kernels-community/finegrained-fp8 kernel (sm_120 has no DeepGEMM path). """ import os os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") import math # noqa: E402 import time # noqa: E402 import traceback # noqa: E402 from typing import Iterator, Optional, Tuple # noqa: E402 import spaces # noqa: E402 # must precede torch/CUDA imports import gradio as gr # noqa: E402 import numpy as np # noqa: E402 import torch # noqa: E402 from transformers import ( # noqa: E402 AutoProcessor, AutoTokenizer, Qwen3OmniMoeForConditionalGeneration, ) # --------------------------------------------------------------------------- # Defuse fp8 random-init. This checkpoint is a thinker-only release: neither the # FP8 nor the FP16 index contains a single `visual.*` key (verified by reading # both shard indexes), yet Qwen3OmniMoeThinkerModel.__init__ unconditionally # builds `self.visual = Qwen3OmniMoeVisionEncoder._from_config(...)`. The # checkpoint's 244 ignored_layers cover only the audio tower / lm_head / # mlp.gate — nothing under `visual` — so the quantizer converts the (unused) # vision linears to FP8Linear and their params end up in missing_keys. Random # init on an fp8 tensor then dies on CPU with # NotImplementedError: "normal_kernel_cpu" not implemented for 'Float8_e4m3fn' # (initialization.py:54 -> TORCH_INIT_FUNCTIONS["normal_"]). # The tower is never called in this audio-only demo, so make the guarded init # helpers no-ops for fp8 dtypes. We patch the TORCH_INIT_FUNCTIONS dict itself # because transformers/initialization.py holds direct references and # transformers/modeling_utils.py calls `init.normal_` off `from . import # initialization as init` — both would bypass a patch of torch.nn.init. # --------------------------------------------------------------------------- import transformers.initialization as _tinit # noqa: E402 _FP8_DTYPES = ( torch.float8_e4m3fn, torch.float8_e5m2, torch.float8_e8m0fnu, ) def _make_fp8_safe(fn): def _safe(tensor, *args, **kwargs): if getattr(tensor, "dtype", None) in _FP8_DTYPES: return tensor return fn(tensor, *args, **kwargs) return _safe for _init_name in ( "normal_", "uniform_", "constant_", "ones_", "zeros_", "xavier_uniform_", "xavier_normal_", "kaiming_uniform_", "kaiming_normal_", "trunc_normal_", ): _tinit.TORCH_INIT_FUNCTIONS[_init_name] = _make_fp8_safe( _tinit.TORCH_INIT_FUNCTIONS[_init_name] ) # --------------------------------------------------------------------------- # Model. The FP8 release carries its own top-level `quantization_config` # (quant_method="fp8", e4m3, 128x128 blockwise, activation_scheme="dynamic", # plus the 244 ignored_layers that keep the audio tower / router / lm_head in # bf16), so transformers auto-detects it as pre-quantized: FP8Linear + # FP8Experts are installed in place of the linear / fused-expert modules and # the fp8 storage is loaded as-is (~30 GiB instead of the FP16 58 GiB, which is # what makes the model fit ZeroGPU's 48 GB slice). Matmuls go through the # Triton fallback (sm_120 is not in DeepGEMM's sm_90/sm_100 set), which needs # the `kernels` package pinned in requirements.txt. # --------------------------------------------------------------------------- MODEL_ID = "timekettle/Babelfish-SimulST" SUBFOLDER = "Babelfish-30B-A3B-FP8" # the native-FP8 transformers checkpoint tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, subfolder=SUBFOLDER) processor = AutoProcessor.from_pretrained(MODEL_ID, subfolder=SUBFOLDER) model = Qwen3OmniMoeForConditionalGeneration.from_pretrained( MODEL_ID, subfolder=SUBFOLDER, dtype=torch.bfloat16, attn_implementation="sdpa", ).to("cuda") model.eval() THINKER = model.thinker # enable_audio_output=False; the talker is never built # `THINKER` is the ForConditionalGeneration wrapper; the audio encoder itself # lives one level down on the inner ThinkerModel (Qwen3OmniMoeThinkerModel # builds `self.audio_tower`). Resolve it robustly across either nesting. _AUDIO_TOWER = getattr(THINKER, "audio_tower", None) or THINKER.model.audio_tower _AUDIO_DTYPE = next(_AUDIO_TOWER.parameters()).dtype # --------------------------------------------------------------------------- # The authors' constants (simulst/common.py), verbatim. # --------------------------------------------------------------------------- SR = 16000 STEP_S = 0.32 STEP = 5120 END_MARK = " [audio complete]" TARGET_LANG = dict(en2zh="zh", zh2en="en") PROMPTS = { "en2zh": ( "You are a professional speech translator. Translate English speech into accurate Chinese. " "Output only the Chinese translation.", "Translate this English speech into Chinese.", ), "zh2en": ( "You are a professional speech translator. Translate Chinese speech into accurate English. " "Output only the English translation.", "Translate this Chinese speech into English.", ), } DEFAULT_WINDOW_S = 24.0 DEFAULT_CTX_TOKENS = 256 DEFAULT_MAX_NEW = 96 MAX_WINDOW_S, MAX_ANCHOR = 60, 2048 IM_END = 151645 # <|im_end|> AUDIO = 151675 # <|audio_pad|> AUDIO_START = 151669 AUDIO_END = 151670 DIRECTION_LABELS = {"en2zh": "English → Chinese", "zh2en": "Chinese → English"} LABEL2DIR = {v: k for k, v in DIRECTION_LABELS.items()} def _decode(ids) -> str: """Token ids -> text, special tokens skipped (the engine's `decode`).""" return tokenizer.decode(ids, skip_special_tokens=True) SPECIAL = set(tokenizer.all_special_ids) N_REGULAR = min(SPECIAL) assert tokenizer.convert_tokens_to_ids("<|audio_pad|>") == AUDIO assert tokenizer.convert_tokens_to_ids("<|im_end|>") == IM_END # --------------------------------------------------------------------------- # Context rule (simulst/ctx_rule.py), verbatim. # --------------------------------------------------------------------------- _END = frozenset("。!?!?") _CLOSE = "”’\"\'))》」』】]} \t\r\n" _CTX_CACHE = {} def token_sets(decode, n_regular): if n_regular not in _CTX_CACHE: ends, partial = set(), set() for i in range(n_regular): s = decode([i]) if "�" in s: partial.add(i) t = s.rstrip(_CLOSE) if t and t[-1] in _END: ends.add(i) _CTX_CACHE[n_regular] = (frozenset(ends), frozenset(partial)) return _CTX_CACHE[n_regular] def history_start(ids, end, limit, ends, partial): if limit <= 0 or end <= 0: return end lo = end - limit if lo <= 0: return 0 for i in range(lo, end): if ids[i - 1] in ends: return i while lo < end and ids[lo] in partial: lo += 1 return lo # --------------------------------------------------------------------------- # Repetition guard (simulst/loop_guard.py), verbatim. # --------------------------------------------------------------------------- HIST = 192 LCOPY_M = 24 def immediate_repeats(t, k=3): n, out = len(t), [] for p in range(k, n // 2 + 1): for s in range(0, n - 2 * p + 1): if t[s:s + p] == t[s + p:s + 2 * p]: out.append((s, p)) break return out def min_period(x, p): for q in range(1, p + 1): if p % q == 0 and all(x[i] == x[i + q] for i in range(len(x) - q)): return q return p def cut_rep(hist, t, reps): seq = list(hist) + list(t) H = len(hist) best = len(t) for s, p in reps: q = min_period(t[s:s + 2 * p], p) start = H + s while start > 0 and seq[start - 1] == seq[start - 1 + q]: start -= 1 best = min(best, max(0, start + q - H)) return best def n_copies(hist, t, s, p): seq = list(hist) + list(t) H = len(hist) q = min_period(t[s:s + 2 * p], p) if q < 3: q = p a = H + s while a > 0 and seq[a - 1] == seq[a - 1 + q]: a -= 1 b = H + s + 2 * p while b < len(seq) and seq[b] == seq[b - q]: b += 1 return (b - a) // q def xrep_cut(hist, t, max_p=64): if not t: return None seq = list(hist) + list(t) n, H = len(seq), len(hist) best = None for p in range(3, min(max_p, n // 3, len(t)) + 1): if seq[-1] != seq[-1 - p]: continue a = n - p while a > 0 and seq[a - 1] == seq[a - 1 + p]: a -= 1 if (n - a) // p >= 3: c = max(0, a + p - H) best = c if best is None else min(best, c) return best def lcopy_cut(hist, t, m=LCOPY_M): if not t: return None seq = list(hist) + list(t) H = len(hist) first = {} for e in range(m - 1, len(seq)): g = tuple(seq[e - m + 1:e + 1]) if e >= H and g in first: s, s0 = e - m + 1, first[g] - m + 1 while s > 0 and s0 > 0 and seq[s - 1] == seq[s0 - 1]: s, s0 = s - 1, s0 - 1 return max(0, s - H) first.setdefault(g, e) return None def loop_guard_check(committed, new, audio_s=None, hit_max=False): if not new: return 0, None t = list(new) hist = list(committed[-HIST:]) fired, cuts = [], [] reps = immediate_repeats(t, 3) if reps and not hit_max: reps = [(s, p) for s, p in reps if n_copies(hist, t, s, p) >= 3] if reps: fired.append("rep") cuts.append(cut_rep(hist, t, reps)) c = xrep_cut(hist, t) if c is not None: fired.append("xrep") cuts.append(c) c = lcopy_cut(hist, t) if c is not None: fired.append("lcopy") cuts.append(c) if not fired: return len(t), None return min(cuts), "+".join(fired) CTX_SETS = token_sets(_decode, N_REGULAR) # --------------------------------------------------------------------------- # Streaming policy (simulst/policy.py), adapted 1:1 to a single offline stream. # --------------------------------------------------------------------------- class Stream: """State of one utterance, advanced 320 ms at a time (see policy.py).""" def __init__(self, direction: str, wave: np.ndarray): assert direction in TARGET_LANG, direction self.direction = direction self.wave = np.asarray(wave, np.float32) self.n = len(self.wave) self.committed, self.emit = [], [] self.ws, self.anchor = 0, [] self.calls = 0 self.error: Optional[str] = None @property def blocks(self): return max(1, math.ceil(self.n / STEP)) def end_of(self, k): return min(k * STEP, self.n) def request(self, k, final): end = self.end_of(k) audio = self.wave[self.ws:end] if len(audio) < STEP: return None if len(audio) > SR * MAX_WINDOW_S or len(self.anchor) > MAX_ANCHOR: self.error = "resource limit reached (window or prefix too long)" return "limit" return audio, list(self.anchor), bool(final) def commit(self, suffix, ended, k): end = self.end_of(k) src_s = end / SR suffix = list(suffix) hit_max = (not ended) and len(suffix) >= DEFAULT_MAX_NEW if suffix and not (set(suffix) & SPECIAL): keep, rule = loop_guard_check(self.committed, suffix, src_s, hit_max) if rule: suffix, ended, hit_max = suffix[:keep], True, False if set(suffix) & SPECIAL: suffix = [] if suffix: self.committed += suffix self.emit += [end] * len(suffix) self.anchor += suffix self.crop(end) self.calls += 1 def crop(self, end): start = end - int(DEFAULT_WINDOW_S * SR) if start <= self.ws: return times = self.emit[len(self.emit) - len(self.anchor):] if self.anchor else [] k = next((i for i, t in enumerate(times) if t > start), len(self.anchor)) kept = list(self.anchor[k:]) if DEFAULT_CTX_TOKENS > 0: e = len(self.committed) - len(kept) h = history_start(self.committed, e, DEFAULT_CTX_TOKENS, *CTX_SETS) kept = list(self.committed[h:]) self.ws = start self.anchor = kept def text(self): return _decode(self.committed) # --------------------------------------------------------------------------- # One model call: audio window + committed prefix -> next target tokens. # The prompt is exactly the authors' vLLM PromptBuilder string, run through # the model's own processor so mel extraction and <|audio_pad|> expansion match # the official path 1:1. The committed prefix is appended as token ids, after # the processor (the authors append it after templating, for the same reason: # committed ids must stay token-exact). # --------------------------------------------------------------------------- PROMPT_TEXT = { (d, m): f"<|im_start|>system\n{PROMPTS[d][0]}<|im_end|>\n<|im_start|>user\n<|audio_start|><|audio_pad|>" f"<|audio_end|>{PROMPTS[d][1]}{END_MARK if m else ''}<|im_end|>\n<|im_start|>assistant\n" for d in PROMPTS for m in (False, True) } def run_model(audio: np.ndarray, anchor: list, mark: bool, direction: str) -> Tuple[list, bool]: """Greedy call on one 320 ms window state. Returns (suffix ids, ended).""" inputs = processor( text=[PROMPT_TEXT[direction, mark]], audio=[audio], return_tensors="pt", ) input_ids = inputs["input_ids"] if anchor: anchor_ids = torch.tensor([list(anchor)], dtype=input_ids.dtype) input_ids = torch.cat([input_ids, anchor_ids.to(input_ids.device)], dim=1) attention_mask = torch.ones_like(input_ids) # The audio tower stays unquantized bf16 (it is in the checkpoint's # ignored_layers) but Whisper mels are fp32 and get_audio_features does not # cast the input -> cast here, as vLLM's runner does. feats = inputs["input_features"].to(_AUDIO_DTYPE) out = THINKER.generate( input_ids=input_ids.to("cuda"), input_features=feats.to("cuda"), feature_attention_mask=inputs["feature_attention_mask"].to("cuda"), attention_mask=attention_mask.to("cuda"), max_new_tokens=DEFAULT_MAX_NEW, eos_token_id=IM_END, do_sample=False, pad_token_id=IM_END, use_cache=True, ) seq = out[0, input_ids.shape[1]:].tolist() # generate() returns a plain tensor return split_end(seq) def split_end(ids): ids = list(ids) ended = bool(ids) and ids[-1] == IM_END return (ids[:-1] if ended else ids), ended def _to_mono_16k(audio) -> np.ndarray: """gr.Audio numpy -> float32 mono 16 kHz (the model's required format).""" if audio is None: raise ValueError("Please record or upload some audio first.") sr, data = audio raw = np.asarray(data) wave = raw.astype(np.float32, copy=False) # gr.Audio(type="numpy") hands back 16-bit ints in [-32768, 32767] (and some # versions return those same values in a float array). Whisper's mel # extractor only *casts* to float32, it never rescales, so we must convert # to the [-1, 1] range soundfile.read(dtype="float32") gives the authors. if np.issubdtype(raw.dtype, np.integer): wave = wave / 32768.0 elif wave.size and float(np.abs(wave).max()) > 1.5: wave = wave / 32768.0 if wave.ndim == 2: # (samples, channels) wave = wave.mean(axis=1) if wave.shape[1] > 1 else wave[:, 0] if sr != SR: # polyphase resample, no extra deps: cheap and exact enough for speech n_out = int(round(len(wave) * SR / sr)) x = np.linspace(0.0, len(wave) - 1, n_out, dtype=np.float64) wave = wave[np.floor(x).astype(np.int64)] * (1 - (x - np.floor(x))) + \ wave[np.ceil(x).astype(np.int64).clip(max=len(wave) - 1)] * (x - np.floor(x)) wave = wave.astype(np.float32) return wave # --------------------------------------------------------------------------- # Gradio handler: replay the utterance 320 ms at a time, streaming the text. # --------------------------------------------------------------------------- def _duration(*_args, **_kwargs) -> int: """Input-dependent ZeroGPU budget. Measured on the live Space: a cold worker pays ~55 s streaming the 32.9 GB FP8 checkpoint disk -> VRAM inside the first call, then ~0.23 s per 320 ms block (a 4.3 s clip = 15 calls = 3.5 s warm). Budget the cold start plus the audio-length term, with a small margin. """ audio = _args[0] if _args else None try: n = len(_to_mono_16k(audio)) except Exception: n = 30 * SR blocks = max(1, math.ceil(n / STEP)) + 1 return min(600, 58 + int(blocks * 0.35) + 6) @spaces.GPU(duration=_duration) def translate(audio, direction: str = "en2zh") -> Iterator[Tuple[str, str]]: """Replay an EN/ZH utterance through Babelfish-SimulST's streaming policy. Args: audio: 16 kHz+ mono waveform from gr.Audio (numpy). direction: "en2zh" or "zh2en". Yields: (translation_so_far, status_line) — committed text grows block by block and is never revised. """ d = LABEL2DIR.get(direction, "en2zh") wave = _to_mono_16k(audio) if len(wave) < STEP: raise ValueError("Audio is too short (need at least 0.32 s).") s = Stream(d, wave) yield "", f"Model warmed up · streaming {len(wave) / SR:.1f} s of audio, 320 ms per step…" t0 = time.perf_counter() try: for k in range(1, s.blocks + 1): final = s.end_of(k) >= s.n for phase_final in (False, True) if final else (False,): req = s.request(k, final=phase_final) if req is None: continue if req == "limit": yield s.text() or "—", f"⏹ {s.error} (stopped at {s.end_of(k) / SR:.1f} s)" return audio_win, anchor, mark = req suffix, ended = run_model(audio_win, anchor, mark, d) s.commit(suffix, ended, k) if s.text(): status = ( f"🎧 {s.end_of(k) / SR:5.1f} s / {s.n / SR:.1f} s · {DIRECTION_LABELS[d]}" f" · step {k}/{s.blocks} · call {'(end marker)' if mark else ''}" ) yield s.text(), status done = s.n / SR wall = time.perf_counter() - t0 yield s.text() or "—", f"✓ Done in {wall:.1f} s wall · {s.calls} model calls · {done:.1f} s audio" except Exception as e: # pragma: no cover traceback.print_exc() yield s.text() or "—", f"✗ {type(e).__name__}: {e}" # --------------------------------------------------------------------------- # UI # --------------------------------------------------------------------------- CSS = """ footer {visibility: hidden} #title {text-align: center} #title h1 {font-size: 2rem; margin-bottom: .25rem} #title p {color: var(--body-text-color-subdued); margin-top: 0} .max_cont {max-width: 1100px !important; margin: 0 auto} """ with gr.Blocks(title="Babelfish-SimulST") as demo: with gr.Column(elem_classes="max_cont"): gr.HTML( """

🐟 Babelfish-SimulST

Simultaneous EN⇄ZH speech translation from timekettle/Babelfish-SimulST — the translation appears while the audio is still playing, and committed text is never revised. Audio is replayed 320 ms at a time through the authors' streaming policy (24 s window, context rule, repetition guard).

""" ) with gr.Row(): audio_in = gr.Audio( label="Speech (English or Chinese)", type="numpy", format="wav", sources=["microphone", "upload"], waveform_options=gr.WaveformOptions(show_recording_waveform=True), ) with gr.Row(): direction = gr.Radio( choices=list(DIRECTION_LABELS.values()), value=DIRECTION_LABELS["en2zh"], label="Translation direction", info="Pick the language of the audio you supply.", ) go = gr.Button("Translate", variant="primary") out_text = gr.Textbox( label="Streaming translation (never revised)", lines=5, buttons=["copy"], ) status = gr.Markdown("Ready — record/upload audio, choose a direction, then Translate.") go.click( translate, inputs=[audio_in, direction], outputs=[out_text, status], api_name="translate", ) gr.Examples( examples=[ ["en_birds.wav", DIRECTION_LABELS["en2zh"]], ["zh_birds_and_dinosaurs.wav", DIRECTION_LABELS["zh2en"]], ], inputs=[audio_in, direction], fn=translate, outputs=[out_text, status], cache_examples=True, cache_mode="lazy", label="Examples (the authors' demo audio)", ) gr.Markdown( """ **How it works.** Every 320 ms block, the model sees the last 24 s of audio plus its committed translation as the assistant prefix, and either continues the translation or waits for more audio. One final call with the end marker finishes the sentence. Policy ported 1:1 from [timekettle-lab/Babelfish-SimulST](https://github.com/timekettle-lab/Babelfish-SimulST); served here with transformers on the authors' native FP8 checkpoint (vLLM does not run on ZeroGPU). Only English⇄Chinese is supported by the model. Example audio © the Babelfish-SimulST authors (Apache-2.0). """ ) if __name__ == "__main__": demo.launch( mcp_server=True, theme=gr.themes.Citrus(), css=CSS, )