Spaces:
lolab
/
Paused

Gatozu35 commited on
Commit
d963eb6
·
verified ·
1 Parent(s): 64996b2

Deploy ZONOS3 212cb76-dirty

Browse files
app.py CHANGED
@@ -13,6 +13,13 @@ huggingface.co (studio/src/lib/zerogpu.ts).
13
 
14
  import spaces # noqa: I001 (ZeroGPU: must be imported before torch)
15
 
 
 
 
 
 
 
 
16
  import asyncio
17
  import base64
18
  import contextvars
@@ -32,34 +39,58 @@ import soundfile as sf
32
  import torch
33
  from fastapi import Header, HTTPException, Request
34
  from fastapi.responses import FileResponse, Response, StreamingResponse
 
 
35
  from gradio.context import LocalContext
36
-
37
  from zonos3 import languages
38
  from zonos3.generation import (
39
  DECODE_CONTEXT_FRAMES,
40
- EDIT_MAX_SECONDS,
41
  SAMPLE_RATE,
42
  TAG_CFG_MAX_SCALE,
43
  TAG_CFG_MIN_SCALE,
44
  )
 
 
45
  from zonos3.reference.lm import Zonos3LM
46
  from zonos3.reference.synth import (
 
47
  ReferenceAssets,
48
  ReferenceContext,
49
  StreamSettings,
50
  _speaker_embedding,
51
  decode_base64_blob,
 
52
  load_embedding_vector,
 
53
  synthesize,
54
  )
55
- from zonos3.server.schemas import GenerateRequest, SpeakerCreateRequest
 
 
 
 
 
 
 
56
  from zonos3.tokenizer import matched_codec
 
 
57
  from zonos3.tts import plan as P
58
- from zonos3.tts.audio import _transcode_audio_bytes_to_wav
 
59
  from zonos3.tts.edit import edit_marker_rows
 
60
  from zonos3.tts.markup import NONVERBAL_MARKUP_TAGS, trained_on_tags
61
- from zonos3.tts.steering import controls_document, disabled_controls
62
- from zonos3.utils.release import RELEASE_LM, resolve_dir_or_local
 
 
 
 
 
 
 
63
 
64
  ROOT = Path(__file__).resolve().parent
65
  STUDIO = ROOT / "studio"
@@ -69,9 +100,16 @@ DEVICE = torch.device("cuda:0")
69
  CPU = torch.device("cpu")
70
 
71
  LM = Zonos3LM.load(RELEASE_LM, device="cpu", dtype=torch.float32).to(DEVICE)
 
 
 
 
 
 
72
  CONFIG = LM.config
73
  ASSETS = ReferenceAssets.load(steer_bundle=str(ROOT / "steering" / "studio_bundle_mect60k.json"))
74
  CONTEXT = ReferenceContext(LM, ASSETS, DEVICE) # the request rules' view of the checkpoint (no GPU work)
 
75
  ASSETS.decoder(CONFIG.audio_codec, DEVICE)
76
  ASSETS.speaker_encoder(CONFIG.speaker_embedding_codec, CONFIG.speaker_embedding_dim, CPU)
77
  # A clip in reference mode is encoded by the dual codec inside the GPU call; fetch its teacher folder now.
@@ -84,6 +122,12 @@ ASSETS.normalizer().warmup()
84
  # --------------------------------------------------------------------------------------------- capabilities
85
 
86
 
 
 
 
 
 
 
87
  def capabilities() -> dict:
88
  """GET /v2/capabilities (the MLX server's document, for the reference and this Space's routes)."""
89
  c, modes = CONFIG, list(CONTEXT.speaker_modes)
@@ -94,9 +138,6 @@ def capabilities() -> dict:
94
  silence = P.silence_prefill_default()
95
  spec = CONTEXT.text_tokenizer_spec
96
  phonemes = None if not spec else spec.get("phonemes")
97
- # zonos3.tts.edit_runtime.edit_capabilities(model, available=False): that module locates the ASR / FuseAlign
98
- # workers in the repo checkout at import and cannot load from the Space's flat layout.
99
- max_spans = edit_marker_rows(c.text_extra_tokens, spec or None) if c.span_end_id is not None else 0
100
  return {
101
  "text_tokenizer_spec": spec or None,
102
  "text_normalization_enabled": True,
@@ -151,11 +192,7 @@ def capabilities() -> dict:
151
  "speaker_embedding_blend": True,
152
  "default_voices_enabled": True,
153
  "projects": {"enabled": False},
154
- "speech_editing": False,
155
- "edit_max_spans": max_spans,
156
- "edit_frame_rate": SAMPLE_RATE / hop if max_spans else None,
157
- "edit_max_seconds": EDIT_MAX_SECONDS,
158
- "edit_align_max_seconds": EDIT_MAX_SECONDS,
159
  "phoneme_tokens": None if phonemes is None else {
160
  "open_marker": phonemes["open_marker"], "close_marker": phonemes["close_marker"],
161
  "symbols": list(phonemes["symbols"])},
@@ -324,14 +361,87 @@ async def prepare(body: dict, session_id: str | None) -> dict:
324
  # ------------------------------------------------------------------------------------------------------ GPU
325
 
326
 
327
- def gpu_seconds(body: dict) -> int:
328
- """A take's worst-case GPU time: 10 s, +60 s for encoding an uploaded clip in reference mode (a fresh GPU worker
329
- loads the dual codec first), and 0.15 s per character (twice that with a guidance twin)."""
 
 
 
330
  clip = 60 if body["speaker_mode"] == "reference" and body["speaker_audio_base64"] else 0
331
  guided = any(float(body[k]) != 1.0 for k in ("speaker_cfg_scale", "tag_cfg_scale", "controls_cfg_scale"))
332
  return min(240, int(10 + clip + 0.15 * len(body["text"]) * (2 if guided else 1)))
333
 
334
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
335
  # Takes run in a GPU session: one ZeroGPU call that holds its GPU and serves takes over a pipe until HOLD_SECONDS pass
336
  # without one or its SESSION_SECONDS run out. A ZeroGPU call per take paid for a fresh GPU worker every time
337
  # (measured: each call got a new process, ~1.2 s to start, plus ~5 s "Waiting for a GPU" when the node was busy, and
@@ -352,29 +462,33 @@ STREAM = StreamSettings(first_chunk=4)
352
 
353
  @spaces.GPU(duration=lambda seconds: seconds)
354
  def gpu_session(seconds: int) -> int:
355
- """Serve takes until none comes for HOLD_SECONDS, None arrives or ``seconds`` (less the margin) are up; returns the
356
- number served. A take's messages: "start" (seed, whether painted spans follow the reading) once planned, "audio"
357
- (a float32 PCM chunk) as it is decoded, then "end", or "invalid" (a request the reference refused) or "error" (the
358
- session then ends: the next take gets a fresh worker)."""
 
359
  deadline, served = time.monotonic() + seconds - MARGIN_SECONDS, 0
360
  while (left := deadline - time.monotonic()) > 0 and TAKE_RX.poll(min(HOLD_SECONDS, left)):
361
  message = TAKE_RX.recv()
362
  if message is None:
363
  break
364
- take_id, body = message
365
  served += 1
366
  try:
 
 
 
367
  synthesize(LM, body, assets=ASSETS, device=DEVICE, stream=STREAM,
368
- on_plan=lambda plan: RESULT_TX.send((take_id, "start",
369
  (plan.seed, plan.follow_tokens is not None))),
370
- on_audio=lambda pcm: RESULT_TX.send((take_id, "audio", pcm)))
371
  except ValueError as exc:
372
- RESULT_TX.send((take_id, "invalid", str(exc)))
373
  except Exception as exc:
374
- RESULT_TX.send((take_id, "error", f"{type(exc).__name__}: {exc}"))
375
  break
376
  else:
377
- RESULT_TX.send((take_id, "end", None))
378
  return served
379
 
380
 
@@ -479,7 +593,7 @@ class GpuSessions:
479
  continue
480
  began = True
481
  out.put_nowait((kind, payload))
482
- if kind in ("end", "invalid", "error"):
483
  return True
484
  elif self.session.done() and not RESULT_RX.poll(0):
485
  return began or None
@@ -495,6 +609,110 @@ class GpuSessions:
495
  GPU = GpuSessions()
496
 
497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
498
  async def audio_of(take: Take):
499
  """The take's PCM chunks until its audio ends (``take.last`` says how)."""
500
  while (message := await take.out.get())[0] == "audio":
@@ -515,6 +733,24 @@ def pcm16_wav(pcm: np.ndarray) -> bytes:
515
  app = gr.Server(title="ZONOS3 Mini", openapi_url=None, docs_url=None, redoc_url=None)
516
 
517
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
518
  @app.get("/v2/capabilities")
519
  async def get_capabilities():
520
  return CAPABILITIES
 
13
 
14
  import spaces # noqa: I001 (ZeroGPU: must be imported before torch)
15
 
16
+ import subprocess
17
+ import sys
18
+
19
+ # qwen-asr pins transformers==4.57.6, which the Space's pins (4.57.3, ZONOS3's lock) exclude; it runs on 4.57.3, so it
20
+ # is installed without its dependencies (its runtime ones are in requirements.txt) before anything imports it.
21
+ subprocess.run([sys.executable, "-m", "pip", "install", "--no-deps", "--quiet", "qwen-asr==0.0.6"], check=True)
22
+
23
  import asyncio
24
  import base64
25
  import contextvars
 
39
  import torch
40
  from fastapi import Header, HTTPException, Request
41
  from fastapi.responses import FileResponse, Response, StreamingResponse
42
+ from fusealign_hub.aligner import CHECKPOINT_FILE as FUSEALIGN_CHECKPOINT
43
+ from fusealign_hub.aligner import HF_REPO as FUSEALIGN_REPO
44
  from gradio.context import LocalContext
45
+ from qwen_asr.inference.utils import SUPPORTED_LANGUAGES
46
  from zonos3 import languages
47
  from zonos3.generation import (
48
  DECODE_CONTEXT_FRAMES,
 
49
  SAMPLE_RATE,
50
  TAG_CFG_MAX_SCALE,
51
  TAG_CFG_MIN_SCALE,
52
  )
53
+ from zonos3.models.accent_format import load_adapter
54
+ from zonos3.reference.accents import AccentState
55
  from zonos3.reference.lm import Zonos3LM
56
  from zonos3.reference.synth import (
57
+ EditLayout,
58
  ReferenceAssets,
59
  ReferenceContext,
60
  StreamSettings,
61
  _speaker_embedding,
62
  decode_base64_blob,
63
+ edit_region,
64
  load_embedding_vector,
65
+ output_gain,
66
  synthesize,
67
  )
68
+ from zonos3.server.edit import call as edit_errors
69
+ from zonos3.server.schemas import (
70
+ EditAlignRequest,
71
+ EditRequest,
72
+ EditTranscribeRequest,
73
+ GenerateRequest,
74
+ SpeakerCreateRequest,
75
+ )
76
  from zonos3.tokenizer import matched_codec
77
+ from zonos3.tokenizer.dual_reference import encode_dual_reference
78
+ from zonos3.tokenizer.matched_codec import decode_model
79
  from zonos3.tts import plan as P
80
+ from zonos3.tts.audio import _decode_audio_bytes, _transcode_audio_bytes_to_wav
81
+ from zonos3.tts.directions import RAW_SPACE
82
  from zonos3.tts.edit import edit_marker_rows
83
+ from zonos3.tts.edit_runtime import EditModel, EditRuntime, FillJob, edit_capabilities
84
  from zonos3.tts.markup import NONVERBAL_MARKUP_TAGS, trained_on_tags
85
+ from zonos3.tts.steering import (
86
+ check_controls,
87
+ controls_document,
88
+ disabled_controls,
89
+ resolve_controls,
90
+ )
91
+ from zonos3.utils.release import RELEASE_LM, resolve_dir_or_local, resolve_file
92
+ from zonos3.workers import asr as asr_worker
93
+ from zonos3.workers import fusealign as fusealign_worker
94
 
95
  ROOT = Path(__file__).resolve().parent
96
  STUDIO = ROOT / "studio"
 
100
  CPU = torch.device("cpu")
101
 
102
  LM = Zonos3LM.load(RELEASE_LM, device="cpu", dtype=torch.float32).to(DEVICE)
103
+ # The edit checkpoint's vocabulary: its span-end audio row and edit-marker text rows, which plain takes never read or
104
+ # sample (so they run exactly as on the release LM). Edit regions add the edit LoRA per request (EDIT_LORA).
105
+ _EDIT = f"{RELEASE_LM}/edit_lora"
106
+ _GROWN = torch.load(resolve_file(f"{_EDIT}/grown_rows.pt"), map_location="cpu", weights_only=True)
107
+ LM.grow({k: v.to(DEVICE) for k, v in _GROWN["rows"].items()}, span_end_id=_GROWN["span_end_id"],
108
+ text_extra_tokens=_GROWN["text_extra_tokens"])
109
  CONFIG = LM.config
110
  ASSETS = ReferenceAssets.load(steer_bundle=str(ROOT / "steering" / "studio_bundle_mect60k.json"))
111
  CONTEXT = ReferenceContext(LM, ASSETS, DEVICE) # the request rules' view of the checkpoint (no GPU work)
112
+ EDIT_LORA = AccentState.for_model(LM, load_adapter(resolve_file(f"{_EDIT}/z3m_omni3b_edit_lora.pt"), tables=True), 1.0)
113
  ASSETS.decoder(CONFIG.audio_codec, DEVICE)
114
  ASSETS.speaker_encoder(CONFIG.speaker_embedding_codec, CONFIG.speaker_embedding_dim, CPU)
115
  # A clip in reference mode is encoded by the dual codec inside the GPU call; fetch its teacher folder now.
 
122
  # --------------------------------------------------------------------------------------------- capabilities
123
 
124
 
125
+ EDIT_MODEL = EditModel(
126
+ frame_rate=SAMPLE_RATE / int(matched_codec.entry(CONFIG.audio_codec)["hop"]), n_codebooks=CONFIG.n_codebooks,
127
+ audio_pad_id=CONFIG.audio_pad_id, codebook_sizes=CONFIG.codebook_sizes,
128
+ max_spans=edit_marker_rows(CONFIG.text_extra_tokens, CONTEXT.text_tokenizer_spec), speaker_row=True)
129
+
130
+
131
  def capabilities() -> dict:
132
  """GET /v2/capabilities (the MLX server's document, for the reference and this Space's routes)."""
133
  c, modes = CONFIG, list(CONTEXT.speaker_modes)
 
138
  silence = P.silence_prefill_default()
139
  spec = CONTEXT.text_tokenizer_spec
140
  phonemes = None if not spec else spec.get("phonemes")
 
 
 
141
  return {
142
  "text_tokenizer_spec": spec or None,
143
  "text_normalization_enabled": True,
 
192
  "speaker_embedding_blend": True,
193
  "default_voices_enabled": True,
194
  "projects": {"enabled": False},
195
+ **edit_capabilities(EDIT_MODEL, True),
 
 
 
 
196
  "phoneme_tokens": None if phonemes is None else {
197
  "open_marker": phonemes["open_marker"], "close_marker": phonemes["close_marker"],
198
  "symbols": list(phonemes["symbols"])},
 
361
  # ------------------------------------------------------------------------------------------------------ GPU
362
 
363
 
364
+ def gpu_seconds(body) -> int:
365
+ """A job's worst-case GPU time. A take: 10 s, +60 s for encoding an uploaded clip in reference mode (a fresh GPU
366
+ worker loads the dual codec first), and 0.15 s per character (twice that with a guidance twin). An edit call: 90 s
367
+ (a fresh worker loads Qwen3-ASR or FuseAlign or the dual codec on its first one)."""
368
+ if isinstance(body, tuple):
369
+ return 90
370
  clip = 60 if body["speaker_mode"] == "reference" and body["speaker_audio_base64"] else 0
371
  guided = any(float(body[k]) != 1.0 for k in ("speaker_cfg_scale", "tag_cfg_scale", "controls_cfg_scale"))
372
  return min(240, int(10 + clip + 0.15 * len(body["text"]) * (2 if guided else 1)))
373
 
374
 
375
+ # ------------------------------------------------------------------------------------------------- speech editing
376
+
377
+ # Speech editing (/v2/edit/transcribe, /v2/edit/align, /v2/edit): zonos3.tts.edit_runtime.EditRuntime in this process,
378
+ # its EditEngine (SpaceEditEngine) and its ASR / aligner calls (InProcessAsr, InProcessAligner) sent to the GPU session
379
+ # as edit jobs. The LM is the release LM grown to the edit checkpoint's vocabulary (its span-end and marker rows; plain
380
+ # takes never read or sample them, so they are unchanged), and every edit region runs with the edit LoRA applied per
381
+ # request (zonos3.reference.accents, strength 1): release + LoRA, as trained. Qwen3-ASR and FuseAlign load in the GPU
382
+ # worker on first use, beside the LM.
383
+ # Fetched now (no GPU time on downloads); loaded by a GPU worker's first edit job.
384
+ resolve_dir_or_local("hf://Qwen/Qwen3-ASR-1.7B")
385
+ resolve_file(f"hf://{FUSEALIGN_REPO}/{FUSEALIGN_CHECKPOINT}")
386
+ _WORKERS: dict = {} # the GPU worker's Qwen3-ASR model and FuseAlign aligner (each GPU worker loads its own)
387
+
388
+
389
+ def _asr():
390
+ if "asr" not in _WORKERS:
391
+ from qwen_asr import Qwen3ASRModel
392
+
393
+ _WORKERS["asr"] = Qwen3ASRModel.from_pretrained(resolve_dir_or_local("hf://Qwen/Qwen3-ASR-1.7B"),
394
+ dtype=torch.bfloat16, device_map="cuda:0",
395
+ max_inference_batch_size=32, max_new_tokens=1024)
396
+ return _WORKERS["asr"]
397
+
398
+
399
+ def _aligner():
400
+ if "aligner" not in _WORKERS:
401
+ from fusealign_hub import load_aligner
402
+
403
+ aligner = load_aligner(resolve_file(f"hf://{FUSEALIGN_REPO}/{FUSEALIGN_CHECKPOINT}"), device="cuda:0")
404
+ aligner.whisper_words = fusealign_worker.no_whisper # anchors always come from Qwen3-ASR
405
+ _WORKERS["aligner"] = aligner
406
+ return _WORKERS["aligner"]
407
+
408
+
409
+ def edit_job(op: str, args: dict):
410
+ """One edit call in the GPU worker: the ops of zonos3/workers/asr.py and fusealign.py, run in-process, and the
411
+ EditEngine's GPU work (encode, fill, decode)."""
412
+ from fusealign_hub.longform import guide_words
413
+ from fusealign_hub.vad import speech_regions
414
+
415
+ if op == "transcribe":
416
+ return asr_worker.transcribe(_asr(), SUPPORTED_LANGUAGES, args["items"])
417
+ if op == "segments":
418
+ return fusealign_worker.segments(args["items"], speech_regions)
419
+ if op == "speech":
420
+ return fusealign_worker.speech(args["items"], speech_regions)
421
+ if op == "align":
422
+ return fusealign_worker.align(_aligner(), args["items"], guide_words)
423
+ if op == "encode":
424
+ wav, sample_rate = _decode_audio_bytes(args["audio"])
425
+ return encode_dual_reference(wav, sample_rate, max_seconds=args["max_seconds"], device="cuda:0").numpy()
426
+ if op == "decode":
427
+ codes = torch.as_tensor(args["codes"], dtype=torch.int64)
428
+ model = ASSETS.decoder(CONFIG.audio_codec, DEVICE)
429
+ audio = decode_model(model, codes.unsqueeze(0), matched_codec.entry(CONFIG.audio_codec))[0].numpy()
430
+ return (audio * np.float32(output_gain(CONFIG.audio_codec, None))).astype(np.float32)
431
+ if op == "fill":
432
+ layout = EditLayout(torch.as_tensor(args["codes"], dtype=torch.int64), args["spans"],
433
+ [torch.as_tensor(f, dtype=torch.int32) for f in args["fills"]])
434
+ embedding = args["embedding"]
435
+ rows, eos_frame = edit_region(LM, args["body"], assets=ASSETS, layout=layout, min_frames=args["min_frames"],
436
+ speaker_embedding=None if embedding is None else embedding.to(DEVICE),
437
+ hidden_delta=args["hidden_delta"], accents=EDIT_LORA, device=DEVICE)
438
+ n_cb = CONFIG.n_codebooks
439
+ # the finishing row is not part of the generated span (it only completes the delayed codebooks' flush)
440
+ out = (torch.stack(rows[:-1])[:, :n_cb].numpy() if len(rows) > 1 else np.zeros((0, n_cb), dtype=np.int32))
441
+ return out, -1 if eos_frame is None else int(eos_frame)
442
+ raise ValueError(f"unknown edit job {op!r}")
443
+
444
+
445
  # Takes run in a GPU session: one ZeroGPU call that holds its GPU and serves takes over a pipe until HOLD_SECONDS pass
446
  # without one or its SESSION_SECONDS run out. A ZeroGPU call per take paid for a fresh GPU worker every time
447
  # (measured: each call got a new process, ~1.2 s to start, plus ~5 s "Waiting for a GPU" when the node was busy, and
 
462
 
463
  @spaces.GPU(duration=lambda seconds: seconds)
464
  def gpu_session(seconds: int) -> int:
465
+ """Serve jobs until none comes for HOLD_SECONDS, None arrives or ``seconds`` (less the margin) are up; returns the
466
+ number served. A job is a take (a GenerateRequest body) or an edit call (``("edit", op, args)``: ``edit_job``). A
467
+ take's messages: "start" (seed, whether painted spans follow the reading) once planned, "audio" (a float32 PCM chunk)
468
+ as it is decoded, then "end"; an edit call's: "result" (its value). Either may end "invalid" (a request the
469
+ reference refused) or "error" (the session then ends: the next job gets a fresh worker)."""
470
  deadline, served = time.monotonic() + seconds - MARGIN_SECONDS, 0
471
  while (left := deadline - time.monotonic()) > 0 and TAKE_RX.poll(min(HOLD_SECONDS, left)):
472
  message = TAKE_RX.recv()
473
  if message is None:
474
  break
475
+ job_id, body = message
476
  served += 1
477
  try:
478
+ if isinstance(body, tuple):
479
+ RESULT_TX.send((job_id, "result", edit_job(*body[1:])))
480
+ continue
481
  synthesize(LM, body, assets=ASSETS, device=DEVICE, stream=STREAM,
482
+ on_plan=lambda plan: RESULT_TX.send((job_id, "start",
483
  (plan.seed, plan.follow_tokens is not None))),
484
+ on_audio=lambda pcm: RESULT_TX.send((job_id, "audio", pcm)))
485
  except ValueError as exc:
486
+ RESULT_TX.send((job_id, "invalid", str(exc)))
487
  except Exception as exc:
488
+ RESULT_TX.send((job_id, "error", f"{type(exc).__name__}: {exc}"))
489
  break
490
  else:
491
+ RESULT_TX.send((job_id, "end", None))
492
  return served
493
 
494
 
 
593
  continue
594
  began = True
595
  out.put_nowait((kind, payload))
596
+ if kind in ("end", "result", "invalid", "error"):
597
  return True
598
  elif self.session.done() and not RESULT_RX.poll(0):
599
  return began or None
 
609
  GPU = GpuSessions()
610
 
611
 
612
+ async def edit_call(request: Request, op: str, **args):
613
+ """One edit job on the GPU session (``edit_job``), on behalf of ``request``'s visitor: its value, ValueError for
614
+ a request the reference refused, RuntimeError for a failed job."""
615
+ job = GPU.submit(("edit", op, args), request)
616
+ kind, payload = await job.out.get()
617
+ if kind == "result":
618
+ return payload
619
+ if kind == "skipped":
620
+ raise RuntimeError("the client left before the edit ran")
621
+ if kind == "failed":
622
+ raise payload
623
+ raise (ValueError if kind == "invalid" else RuntimeError)(payload)
624
+
625
+
626
+ # The HTTP request and the event loop of the edit route being served (set by the edit_request_context middleware):
627
+ # the runtime's ASR / aligner calls run in worker threads (asyncio.to_thread copies this context into them).
628
+ EDIT_REQUEST: contextvars.ContextVar[tuple[Request, asyncio.AbstractEventLoop]] = contextvars.ContextVar("edit_request")
629
+
630
+
631
+ def edit_call_sync(op: str, **args):
632
+ """``edit_call`` from a worker thread of the edit runtime."""
633
+ request, loop = EDIT_REQUEST.get()
634
+ return asyncio.run_coroutine_threadsafe(edit_call(request, op, **args), loop).result()
635
+
636
+
637
+ class InProcessAsr:
638
+ """``zonos3.tts.edit_align.AsrWorker`` on the GPU session (Qwen3-ASR loaded in the GPU worker). Audio items are the
639
+ runtime's temp WAV paths: the forked GPU worker shares this file system."""
640
+
641
+ def languages(self) -> list[str]:
642
+ return list(SUPPORTED_LANGUAGES)
643
+
644
+ def transcribe(self, items: list[dict]) -> list[dict]:
645
+ return edit_call_sync("transcribe", items=items)
646
+
647
+
648
+ class InProcessAligner:
649
+ """``zonos3.tts.edit_align.FuseAlignWorker`` on the GPU session (FuseAlign loaded in the GPU worker)."""
650
+
651
+ def segments(self, audios: list[str]) -> list[list[list[float]]]:
652
+ return [r["chunks"] for r in edit_call_sync("segments", items=[{"audio": a} for a in audios])]
653
+
654
+ def speech(self, audios: list[str]) -> list[list[list[float]]]:
655
+ return [r["regions"] for r in edit_call_sync("speech", items=[{"audio": a} for a in audios])]
656
+
657
+ def align(self, items: list[dict]) -> list[list[dict]]:
658
+ return [r["words"] for r in edit_call_sync("align", items=items)]
659
+
660
+
661
+ class SpaceEditEngine:
662
+ """``zonos3.tts.edit_runtime.EditEngine`` of the Space: uploads decode and the speaker row embeds on this process's
663
+ CPU; encoding the clip, each region's fill (the edit LoRA on) and the decode run on the GPU session."""
664
+
665
+ model = EDIT_MODEL
666
+
667
+ async def decode_audio(self, audio: bytes) -> tuple[np.ndarray, int]:
668
+ wav, sample_rate = await asyncio.to_thread(_decode_audio_bytes, audio)
669
+ return wav[0].numpy(), int(sample_rate)
670
+
671
+ async def embed(self, audio: bytes) -> torch.Tensor:
672
+ return await asyncio.to_thread(embed_audio, audio)
673
+
674
+ async def encode(self, audio: bytes, max_seconds: float) -> np.ndarray:
675
+ codes = await edit_call(EDIT_REQUEST.get()[0], "encode", audio=audio, max_seconds=float(max_seconds))
676
+ return np.asarray(codes, dtype=np.int64)
677
+
678
+ async def check(self, target_text: str, doses, condition_buckets, condition_values) -> set[str]:
679
+ P.validate_phoneme_groups(CONTEXT.text_tokenizer_spec, target_text)
680
+ raw = set()
681
+ if doses is not None:
682
+ for region in doses:
683
+ check_controls(ASSETS.steer_bundle, region)
684
+ raw = {did for region in doses for did in region if ASSETS.steer_bundle.directions[did].space == RAW_SPACE}
685
+ P.resolve_condition_buckets(CONTEXT, condition_buckets, condition_values)
686
+ return raw
687
+
688
+ async def fill(self, job: FillJob) -> tuple[np.ndarray, int]:
689
+ embedding, delta = job.speaker_embedding, None
690
+ if job.controls:
691
+ resolved = resolve_controls(ASSETS.steer_bundle, job.controls, None, text=job.controls_text,
692
+ speaker_embedding=embedding, sources=CONTEXT.steering_sources,
693
+ hidden_size=CONTEXT.hidden_size)
694
+ embedding, delta = resolved.speaker_embedding, resolved.hidden_delta
695
+ request = {"text": job.text, "language": job.language, "text_normalization": job.text_normalization,
696
+ **job.sampling, "seed": job.seed, "max_tokens": job.max_tokens, "speaker_mode": "embedding",
697
+ "condition_buckets": job.condition_buckets, "condition_values": job.condition_values,
698
+ "stream": False}
699
+ return await edit_call(EDIT_REQUEST.get()[0], "fill", body=request, codes=np.asarray(job.window_codes),
700
+ spans=job.spans, fills=[np.asarray(f) for f in job.fills], min_frames=int(job.min_frames),
701
+ embedding=embedding, hidden_delta=delta)
702
+
703
+ async def decode(self, codes: np.ndarray) -> np.ndarray:
704
+ return await edit_call(EDIT_REQUEST.get()[0], "decode", codes=np.asarray(codes))
705
+
706
+
707
+ EDIT_RUNTIME = EditRuntime(SpaceEditEngine(), InProcessAsr(), InProcessAligner())
708
+
709
+
710
+ async def edit_route(request: Request, run):
711
+ """An edit route (zonos3.server.edit): its GPU jobs run on behalf of its visitor (their X-IP-Token)."""
712
+ EDIT_REQUEST.set((request, asyncio.get_running_loop()))
713
+ return await edit_errors(run(EDIT_RUNTIME))
714
+
715
+
716
  async def audio_of(take: Take):
717
  """The take's PCM chunks until its audio ends (``take.last`` says how)."""
718
  while (message := await take.out.get())[0] == "audio":
 
733
  app = gr.Server(title="ZONOS3 Mini", openapi_url=None, docs_url=None, redoc_url=None)
734
 
735
 
736
+ @app.post("/v2/edit/transcribe")
737
+ async def edit_transcribe(req: EditTranscribeRequest, request: Request):
738
+ """Qwen3-ASR transcript of the audio to edit (chunk-wise past 30 s) and its words' FuseAlign timings."""
739
+ return await edit_route(request, lambda rt: rt.transcribe(req))
740
+
741
+
742
+ @app.post("/v2/edit/align")
743
+ async def edit_align(req: EditAlignRequest, request: Request):
744
+ """FuseAlign forced alignment of the audio to ``text``: word timings, presences and edit tokens."""
745
+ return await edit_route(request, lambda rt: rt.align(req))
746
+
747
+
748
+ @app.post("/v2/edit")
749
+ async def edit(req: EditRequest, request: Request):
750
+ """Regenerate the edited regions of recorded speech (the edit LoRA on); unedited codec frames are kept exactly."""
751
+ return await edit_route(request, lambda rt: rt.edit(req))
752
+
753
+
754
  @app.get("/v2/capabilities")
755
  async def get_capabilities():
756
  return CAPABILITIES
fusealign_hub/LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
fusealign_hub/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FuseAlign word-level forced aligner (multilingual CJK fine-tune, step 2500)."""
2
+
3
+ from . import aligner, longform, model, text_encoder, vad
4
+ from .aligner import SAMPLE_RATE, FuseAlignAligner, WordAlignment, load_aligner
5
+ from .longform import fill_unplaced, guide_words
6
+ from .model import FuseAlign, FuseAlignArgs
7
+ from .text_encoder import DiaTextEncoder
8
+
9
+ __all__ = [
10
+ "SAMPLE_RATE",
11
+ "DiaTextEncoder",
12
+ "FuseAlign",
13
+ "FuseAlignAligner",
14
+ "FuseAlignArgs",
15
+ "WordAlignment",
16
+ "fill_unplaced",
17
+ "guide_words",
18
+ "load_aligner",
19
+ ]
fusealign_hub/aligner.py ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FuseAlign word-level forced aligner: batching, long-form routing, the checkpoint loader.
2
+
3
+ FuseAlign (arXiv 2609.33650) is not a CTC model. A joint audio/text transformer reads the waveform
4
+ and the UTF-8 bytes of the transcript and predicts, for each word, a start and an end on a 1 ms
5
+ grid plus a presence probability. A word whose presence is below ``PRESENCE_THRESHOLD`` is "not
6
+ found" and takes the paper's uniform fallback interval (``fill_unplaced``).
7
+
8
+ Recordings over ``MAX_SECONDS`` (or transcripts over 1022 UTF-8 bytes) are handled as in the
9
+ paper's Appendix G.3: approximate per-word times (supplied by the caller, otherwise Whisper
10
+ large-v3 run once on the recording) route the words into 26 s cores with 2 s of context, Silero
11
+ VAD picks the cuts, and the chunk predictions are stitched.
12
+ """
13
+
14
+ from dataclasses import dataclass
15
+ import json
16
+ import os
17
+ import unicodedata
18
+
19
+ import torch
20
+
21
+ from . import longform, vad
22
+ from .longform import MAX_TEXT_BYTES, fill_unplaced
23
+ from .model import FuseAlign, FuseAlignArgs, cast_autocast_weights
24
+ from .text_encoder import DiaTextEncoder
25
+
26
+ SAMPLE_RATE = 16000
27
+ MAX_SECONDS = 30.0
28
+ PRESENCE_THRESHOLD = 0.1
29
+ WHISPER_MODEL = "openai/whisper-large-v3"
30
+ HF_REPO = "Zyphra/fusealign"
31
+ CHECKPOINT_FILE = "fusealign-multilingual-cjkft-step2500.safetensors"
32
+ CHECKPOINT_FORMAT = "fusealign-hub/1"
33
+
34
+ # Padded audio per forward. Measured peak CUDA memory per process (H100, bf16, ~1 GB of it resident weights):
35
+ # 4.4 GB for 64 corpus-like spans (median 11 s), 5.4 GB for 32 x 30 s clips with ~1000-byte transcripts.
36
+ # At 120 s the forward was launch-bound (1.7x slower on corpus-like spans); past 960 s it gains nothing.
37
+ _BATCH_SAMPLES = 960 * SAMPLE_RATE
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class WordAlignment:
42
+ """One transcript token. Times are in seconds.
43
+
44
+ ``presence`` is the model's probability that the word is in the audio. ``placed`` is False
45
+ when the word took the paper's uniform fallback (presence under ``PRESENCE_THRESHOLD``, audio
46
+ under one patch, or a token no long-form chunk could hold) or is punctuation only, in which
47
+ case it is zero-width at the previous token's end.
48
+ """
49
+
50
+ word: str
51
+ start: float
52
+ end: float
53
+ presence: float
54
+ placed: bool
55
+
56
+
57
+ def _is_wordy(token: str) -> bool:
58
+ """True if ``token`` carries a letter or a digit, i.e. anything to say."""
59
+ return any(unicodedata.category(ch)[0] in ("L", "N") for ch in token)
60
+
61
+
62
+ def _tokens(transcript) -> list[str]:
63
+ if isinstance(transcript, str):
64
+ return transcript.split()
65
+ tokens = list(transcript)
66
+ if any(not isinstance(t, str) or not t or any(ch.isspace() for ch in t) for t in tokens):
67
+ raise ValueError("tokens must be non-empty strings without whitespace")
68
+ return tokens
69
+
70
+
71
+ class FuseAlignAligner:
72
+ """Word-level forced alignment with a FuseAlign network and its frozen Dia text encoder.
73
+
74
+ ``batch_size`` clips (or long-form chunks) share one forward, length-sorted. Batches are not
75
+ bit-identical to ``batch_size=1``, because bf16 GEMM rounding depends on the batch shape
76
+ (Buckeye MAE 33.36 → 33.38 ms); set ``aligner.batch_size = 1`` for the exact per-clip outputs.
77
+ """
78
+
79
+ def __init__(self, model: FuseAlign, encoder: DiaTextEncoder, *, batch_size: int = 64,
80
+ whisper_model: str = WHISPER_MODEL):
81
+ self.model = model
82
+ self.encoder = encoder
83
+ self.whisper_model = whisper_model
84
+ self.batch_size = batch_size
85
+ self._whisper = None
86
+
87
+ @property
88
+ def device(self) -> torch.device:
89
+ return next(self.model.parameters()).device
90
+
91
+ # ── model forward ────────────────────────────────────────────────────────
92
+
93
+ @torch.inference_mode()
94
+ def _forward_batch(self, items: list[tuple[torch.Tensor, list[str]]]):
95
+ """``(intervals | None, presence)`` per word for each ``(wav, words)`` item.
96
+
97
+ Items are 1-D float32 CPU waveforms at 16 kHz. They are stable-sorted by length and
98
+ forwarded in groups of at most ``batch_size`` clips and ``_BATCH_SAMPLES`` padded
99
+ samples, so each padded batch holds similar lengths; results come back in input order.
100
+ An item without words gets ``([], [])`` and no forward.
101
+ """
102
+ results = [([], []) for _ in items]
103
+ order = sorted(
104
+ (i for i, (_, words) in enumerate(items) if words),
105
+ key=lambda i: items[i][0].numel(),
106
+ )
107
+ groups, group = [], []
108
+ for i in order:
109
+ # Ascending lengths: this item's is the padded length of its group.
110
+ if group and (len(group) == self.batch_size
111
+ or (len(group) + 1) * items[i][0].numel() > _BATCH_SAMPLES):
112
+ groups.append(group)
113
+ group = []
114
+ group.append(i)
115
+ if group:
116
+ groups.append(group)
117
+ for group in groups:
118
+ for i, result in zip(group, self._forward_group([items[i] for i in group])):
119
+ results[i] = result
120
+ return results
121
+
122
+ def _forward_group(self, items: list[tuple[torch.Tensor, list[str]]]):
123
+ """One padded forward over mono 16 kHz clips: (intervals | None, presence) per word.
124
+
125
+ Word spans exclude the two-token speaker/space prefix and count UTF-8
126
+ bytes. Only each clip's valid frames participate in decoding.
127
+ """
128
+ model, encoder = self.model, self.encoder
129
+ device = self.device
130
+ id_rows, span_rows = [], []
131
+ for wav, words in items:
132
+ if wav.numel() < model.args.patch_window:
133
+ raise ValueError("Waveform must contain at least one complete audio patch")
134
+ transcript = bytearray()
135
+ spans = []
136
+ for index, word in enumerate(words):
137
+ if index:
138
+ transcript.append(32)
139
+ start = len(transcript)
140
+ transcript.extend(word.encode("utf-8"))
141
+ spans.append((start, len(transcript)))
142
+ if len(transcript) > MAX_TEXT_BYTES:
143
+ raise ValueError(
144
+ f"Use long-form alignment for transcripts over {MAX_TEXT_BYTES} UTF-8 bytes"
145
+ )
146
+ id_rows.append([1, 32, *transcript])
147
+ span_rows.append(spans)
148
+
149
+ batch = len(items)
150
+ max_ids = max(len(row) for row in id_rows)
151
+ max_words = max(len(row) for row in span_rows)
152
+ wav = torch.zeros(batch, max(w.numel() for w, _ in items))
153
+ text_ids = torch.zeros(batch, max_ids, dtype=torch.long)
154
+ text_mask = torch.zeros(batch, max_ids, dtype=torch.bool)
155
+ word_spans = torch.zeros(batch, max_words, 2, dtype=torch.long)
156
+ word_mask = torch.zeros(batch, max_words, dtype=torch.bool)
157
+ for row, ((clip, _), ids, spans) in enumerate(zip(items, id_rows, span_rows)):
158
+ wav[row, :clip.numel()] = clip
159
+ text_ids[row, :len(ids)] = torch.tensor(ids, dtype=torch.long)
160
+ text_mask[row, :len(ids)] = True
161
+ word_spans[row, :len(spans)] = torch.tensor(spans, dtype=torch.long)
162
+ word_mask[row, :len(spans)] = True
163
+ wav_lengths = torch.tensor([w.numel() for w, _ in items], dtype=torch.long)
164
+ wav, wav_lengths, text_ids, text_mask, word_spans, word_mask = (
165
+ t.to(device) for t in (wav, wav_lengths, text_ids, text_mask, word_spans, word_mask)
166
+ )
167
+
168
+ with torch.autocast(
169
+ device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"
170
+ ):
171
+ text_feats = encoder(text_ids, text_mask)
172
+ # Dia stays bf16 on CPU too, but the trainable model is stored in fp32 there.
173
+ if device.type != "cuda":
174
+ text_feats = text_feats.float()
175
+ predictions = model(
176
+ wav=wav,
177
+ wav_lengths=wav_lengths,
178
+ text_feats=text_feats,
179
+ text_mask=text_mask,
180
+ word_spans=word_spans,
181
+ word_mask=word_mask,
182
+ )
183
+
184
+ frames = torch.arange(predictions["start_logits"].shape[-1], device=device)
185
+ beyond = frames[None, None, :] >= predictions["frame_lengths"][:, None, None]
186
+ start = predictions["start_logits"].masked_fill(beyond, float("-inf")).argmax(dim=-1)
187
+ end = predictions["end_logits"].masked_fill(beyond, float("-inf")).argmax(dim=-1)
188
+ end = torch.maximum(end, start)
189
+ decoded = torch.stack((start, end), dim=-1).cpu().tolist()
190
+ # A forward can come back NaN for a clip (observed on some sub-second clips); its words are
191
+ # then unplaced, and presence 0 says so where NaN would reach JSON as a non-standard literal.
192
+ presence = predictions["presence_logits"].sigmoid().nan_to_num(0.0).cpu().tolist()
193
+ results = []
194
+ for row, spans in enumerate(span_rows):
195
+ probs = presence[row][:len(spans)]
196
+ results.append((
197
+ [
198
+ (start_ms / 1000.0, end_ms / 1000.0) if p >= PRESENCE_THRESHOLD else None
199
+ for (start_ms, end_ms), p in zip(decoded[row], probs)
200
+ ],
201
+ probs,
202
+ ))
203
+ return results
204
+
205
+ # ── approximate word times ───────────────────────────────────────────────
206
+
207
+ def whisper_words(self, waveform: torch.Tensor, language: str | None = None) -> list[dict]:
208
+ """Whisper word times for a 16 kHz mono waveform; the pipeline is loaded once.
209
+
210
+ ``language`` is a Whisper language (``"en"``, ``"ja"``, ...); ``None`` auto-detects.
211
+ """
212
+ wav = torch.as_tensor(waveform, dtype=torch.float32, device="cpu")
213
+ if wav.ndim != 1:
214
+ raise ValueError("expected a mono 1-D waveform")
215
+ if self._whisper is None:
216
+ from transformers import pipeline
217
+
218
+ device = self.device
219
+ self._whisper = pipeline(
220
+ "automatic-speech-recognition",
221
+ model=self.whisper_model,
222
+ dtype=torch.float16 if device.type == "cuda" else torch.float32,
223
+ device=device,
224
+ chunk_length_s=30,
225
+ batch_size=16,
226
+ )
227
+ duration = wav.numel() / SAMPLE_RATE
228
+ generate_kwargs = {"task": "transcribe"}
229
+ if language is not None:
230
+ generate_kwargs["language"] = language
231
+ result = self._whisper(
232
+ {"raw": wav.numpy(), "sampling_rate": SAMPLE_RATE},
233
+ return_timestamps="word",
234
+ generate_kwargs=generate_kwargs,
235
+ )
236
+ if self.device.type == "cuda":
237
+ # Word-timestamp decoding peaks at tens of GB; the allocator would keep it cached and
238
+ # starve other processes sharing the GPU.
239
+ torch.cuda.empty_cache()
240
+ words = []
241
+ for chunk in result.get("chunks", []):
242
+ start, end = chunk["timestamp"]
243
+ # Missing word edges are bounded by the actual recording.
244
+ words.append({
245
+ "word": chunk["text"].strip(),
246
+ "start": float(start if start is not None else 0.0),
247
+ "end": float(end if end is not None else duration),
248
+ })
249
+ return words
250
+
251
+ # ── alignment ────────────────────────────────────────────────────────────
252
+
253
+ def intervals_batch(self, waveforms: list[torch.Tensor], word_lists: list[list[str]],
254
+ asr_word_lists: list[list[dict] | None] | None = None,
255
+ language: str | None = None):
256
+ """Per item, ``(intervals | None, presence)`` per word for 16 kHz mono waveforms.
257
+
258
+ Routing is the paper's, per item: under one patch every word is unplaced; up to
259
+ ``MAX_SECONDS`` and 1022 transcript bytes one forward (shared with the other short
260
+ items); otherwise long-form. ``asr_word_lists`` holds the approximate word times for
261
+ long-form items (``None`` runs Whisper; an item's ``[]`` falls back to the VAD
262
+ character-time map). ``language`` is Whisper's language for those runs (``None``
263
+ auto-detects).
264
+ """
265
+ if asr_word_lists is None:
266
+ asr_word_lists = [None] * len(waveforms)
267
+ if not len(waveforms) == len(word_lists) == len(asr_word_lists):
268
+ raise ValueError("waveforms, word lists and asr word lists differ in length")
269
+ wavs = [torch.as_tensor(w, dtype=torch.float32, device="cpu") for w in waveforms]
270
+ if any(wav.ndim != 1 for wav in wavs):
271
+ raise ValueError("expected a mono 1-D waveform")
272
+ results = [None] * len(wavs)
273
+ short, short_at = [], []
274
+ for i, (wav, words) in enumerate(zip(wavs, word_lists)):
275
+ n = len(words)
276
+ if not n:
277
+ results[i] = ([], [])
278
+ elif wav.numel() < self.model.args.patch_window:
279
+ results[i] = ([None] * n, [0.0] * n)
280
+ elif (wav.numel() <= MAX_SECONDS * SAMPLE_RATE
281
+ and len(" ".join(words).encode("utf-8")) <= MAX_TEXT_BYTES):
282
+ short.append((wav, words))
283
+ short_at.append(i)
284
+ else:
285
+ results[i] = self._long(wav, words, asr_word_lists[i], language)
286
+ for i, result in zip(short_at, self._forward_batch(short)):
287
+ results[i] = result
288
+ return results
289
+
290
+ @torch.inference_mode()
291
+ def _long(self, wav: torch.Tensor, words: list[str], asr_words, language: str | None):
292
+ """ASR anchors, VAD cores and context stitching."""
293
+ if asr_words is None:
294
+ asr_words = self.whisper_words(wav, language)
295
+ duration = wav.numel() / SAMPLE_RATE
296
+ speech_regions = vad.speech_regions(wav)
297
+ approx = longform.approximate_times(words, asr_words, speech_regions, duration)
298
+ # plan_chunks raises for words no chunk can hold, which would fail the whole recording for
299
+ # one oversized token; they are left unplaced instead and take the uniform fallback.
300
+ skipped = longform.unroutable(words, approx)
301
+ keep = [i for i in range(len(words)) if i not in skipped]
302
+ chunks = longform.plan_chunks([words[i] for i in keep], [approx[i] for i in keep],
303
+ speech_regions, duration)
304
+ for chunk in chunks:
305
+ chunk["indices"] = [keep[i] for i in chunk["indices"]]
306
+ items, offsets = [], []
307
+ for chunk in chunks:
308
+ start_seconds, end_seconds = chunk["audio"]
309
+ start_sample = max(0, min(wav.numel(), round(start_seconds * SAMPLE_RATE)))
310
+ end_sample = max(start_sample, min(wav.numel(), round(end_seconds * SAMPLE_RATE)))
311
+ chunk_words = [words[index] for index in chunk["indices"]]
312
+ items.append((wav[start_sample:end_sample], chunk_words))
313
+ offsets.append(start_sample / SAMPLE_RATE)
314
+ predictions, presences = [], []
315
+ for offset, (ivs, probs) in zip(offsets, self._forward_batch(items)):
316
+ predictions.append([
317
+ None if iv is None else (iv[0] + offset, iv[1] + offset) for iv in ivs
318
+ ])
319
+ presences.append(probs)
320
+ stitched = longform.stitch_predictions(len(words), chunks, predictions)
321
+
322
+ presence = [0.0] * len(words)
323
+ found = [False] * len(words)
324
+ for chunk, placed, probs in zip(chunks, predictions, presences, strict=True):
325
+ for index, iv, p in zip(chunk["indices"], placed, probs, strict=True):
326
+ if stitched[index] is not None:
327
+ if not found[index] and iv == stitched[index]:
328
+ presence[index], found[index] = p, True
329
+ else:
330
+ presence[index] = max(presence[index], p)
331
+ return stitched, presence
332
+
333
+ def align_batch(self, waveforms: list[torch.Tensor], sample_rate: int, transcripts,
334
+ asr_words: list[list[dict] | None] | None = None,
335
+ language: str | None = None) -> list[list[WordAlignment]]:
336
+ """One list of ``WordAlignment`` per transcript, one per token, in order.
337
+
338
+ A transcript is a ``str`` (tokens are ``transcript.split()``) or a list of tokens
339
+ (pre-segmented text for ja/zh/yue/th). Waveforms are mono, resampled to 16 kHz when
340
+ ``sample_rate`` differs. Tokens with a letter or digit go to the model; unplaced ones take
341
+ the uniform fallback. Punctuation-only tokens are zero-width at the previous token's end.
342
+ No snapping and no order repair. The clips share batched forwards. ``asr_words`` and
343
+ ``language`` are as in ``intervals_batch``.
344
+ """
345
+ if asr_words is None:
346
+ asr_words = [None] * len(waveforms)
347
+ if not len(waveforms) == len(transcripts) == len(asr_words):
348
+ raise ValueError("waveforms, transcripts and asr_words differ in length")
349
+ out = [[] for _ in waveforms]
350
+ prepared = [] # (index, tokens, wav, wordy)
351
+ for i, (waveform, transcript) in enumerate(zip(waveforms, transcripts)):
352
+ tokens = _tokens(transcript)
353
+ if not tokens:
354
+ continue
355
+ wav = torch.as_tensor(waveform, dtype=torch.float32, device="cpu")
356
+ if wav.ndim != 1:
357
+ raise ValueError("expected a mono 1-D waveform")
358
+ if sample_rate != SAMPLE_RATE:
359
+ import torchaudio
360
+
361
+ wav = torchaudio.functional.resample(wav, sample_rate, SAMPLE_RATE)
362
+ wordy = [k for k, token in enumerate(tokens) if _is_wordy(token)]
363
+ prepared.append((i, tokens, wav, wordy))
364
+
365
+ results = self.intervals_batch(
366
+ [wav for _, _, wav, _ in prepared],
367
+ [[tokens[k] for k in wordy] for _, tokens, _, wordy in prepared],
368
+ [asr_words[i] for i, _, _, _ in prepared],
369
+ language,
370
+ )
371
+ for (i, tokens, wav, wordy), (ivs, probs) in zip(prepared, results):
372
+ duration = wav.numel() / SAMPLE_RATE
373
+ filled = fill_unplaced(ivs, duration)
374
+ by_token = {
375
+ k: (filled[j], probs[j], ivs[j] is not None) for j, k in enumerate(wordy)
376
+ }
377
+
378
+ first_start = filled[0][0] if filled else 0.0
379
+ previous_end = None
380
+ words = []
381
+ for k, token in enumerate(tokens):
382
+ if k in by_token:
383
+ (start, end), p, placed = by_token[k]
384
+ words.append(WordAlignment(token, start, end, p, placed))
385
+ previous_end = end
386
+ else:
387
+ t = previous_end if previous_end is not None else first_start
388
+ words.append(WordAlignment(token, t, t, 0.0, False))
389
+ previous_end = t
390
+ out[i] = words
391
+ return out
392
+
393
+ def align(self, waveform: torch.Tensor, sample_rate: int, transcript,
394
+ asr_words: list[dict] | None = None,
395
+ language: str | None = None) -> list[WordAlignment]:
396
+ """``align_batch`` for one waveform."""
397
+ return self.align_batch([waveform], sample_rate, [transcript], [asr_words], language)[0]
398
+
399
+
400
+ def load_aligner(checkpoint: str | os.PathLike | None = None,
401
+ device: str | torch.device | None = None, compile_model: bool = False,
402
+ batch_size: int = 64) -> FuseAlignAligner:
403
+ """Load a ``fusealign-hub/1`` safetensors checkpoint (default: ``CHECKPOINT_FILE`` from the
404
+ Hugging Face repo ``HF_REPO``) onto ``device`` (default: CUDA when available).
405
+
406
+ ``compile_model`` wraps the network in ``torch.compile``; compiled outputs are not
407
+ bit-identical to eager.
408
+ """
409
+ from safetensors import safe_open
410
+ from safetensors.torch import load_file
411
+
412
+ if checkpoint is None:
413
+ from huggingface_hub import hf_hub_download
414
+
415
+ checkpoint = hf_hub_download(repo_id=HF_REPO, filename=CHECKPOINT_FILE)
416
+ device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
417
+ with safe_open(checkpoint, framework="pt") as handle:
418
+ metadata = handle.metadata() or {}
419
+ if metadata.get("format") != CHECKPOINT_FORMAT:
420
+ raise ValueError(
421
+ f"{checkpoint} is not a {CHECKPOINT_FORMAT} checkpoint; "
422
+ "build one with scripts/build_checkpoint.py"
423
+ )
424
+ model_state, text_state = {}, {}
425
+ for key, value in load_file(checkpoint).items():
426
+ if key.startswith("model."):
427
+ model_state[key.removeprefix("model.")] = value
428
+ elif key.startswith("text_encoder."):
429
+ text_state[key.removeprefix("text_encoder.")] = value
430
+ else:
431
+ raise ValueError(f"unexpected tensor {key!r} in {checkpoint}")
432
+
433
+ net = FuseAlign(FuseAlignArgs(**json.loads(metadata["model_args"])))
434
+ net.load_state_dict(model_state, strict=True)
435
+ net.to(device).eval()
436
+ if device.type == "cuda":
437
+ cast_autocast_weights(net)
438
+ if compile_model:
439
+ # Inductor fuses the RoPE/RMSNorm/mask elementwise chains and cuts launch overhead:
440
+ # -20% forward on fresh corpus-like shapes at 960 s / 64 batches, MAE 39.41 -> 39.39 ms
441
+ # on 400 Buckeye clips. Costs ~70 s of compilation on a cold cache (~11 s warm) and
442
+ # ~30 s per new specialization; worth it only in long-running processes.
443
+ # dynamic=True because every batch has new lengths. Inductor's coalesce tiling analysis
444
+ # (default on in torch 2.11) fails an assertion in tiling_utils.get_pw_red_splits on
445
+ # this graph's dynamic shapes; its own config notes it does not apply to them.
446
+ from torch._inductor import config as inductor_config
447
+
448
+ options = ({"triton.coalesce_tiling_analysis": False}
449
+ if hasattr(inductor_config.triton, "coalesce_tiling_analysis") else None)
450
+ net.compile(dynamic=True, options=options)
451
+ encoder = DiaTextEncoder(json.loads(metadata["text_encoder_config"]), text_state).to(device)
452
+ return FuseAlignAligner(net, encoder, batch_size=batch_size)
fusealign_hub/longform.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Long-form routing (FuseAlign paper, arXiv:2609.33650, Appendix G.3): approximate word times,
2
+ 26 s cores with 2 s of context cut at silences, and stitching. ``fill_unplaced`` is the paper's
3
+ uniform fallback for unplaced words (Section 3).
4
+ """
5
+
6
+ from bisect import bisect_left, bisect_right
7
+ from difflib import SequenceMatcher
8
+ import re
9
+
10
+ _CORE_SECONDS = 26.0
11
+ _CONTEXT_SECONDS = 2.0
12
+ MAX_TEXT_BYTES = 1022
13
+
14
+
15
+ def _oversized_start_group(words, approx):
16
+ previous = None
17
+ size = 0
18
+ for word, (start, _) in zip(words, approx):
19
+ size = size + 1 if start == previous else 0
20
+ size += len(word.encode("utf-8"))
21
+ if size > MAX_TEXT_BYTES:
22
+ return True
23
+ previous = start
24
+ return False
25
+
26
+
27
+ def unroutable(words, approx) -> set[int]:
28
+ """Indices of the words no chunk can hold: one over ``MAX_TEXT_BYTES``, and every word of a
29
+ run sharing one approximate start (no time cut separates them) whose text, once those are
30
+ left out, is over it too. ``plan_chunks`` raises for either; ``_long`` leaves them unplaced."""
31
+ out = {i for i, word in enumerate(words) if len(word.encode("utf-8")) > MAX_TEXT_BYTES}
32
+ run, size, previous = [], 0, None
33
+ for i, (word, (start, _)) in enumerate(zip(words, approx)):
34
+ if i in out:
35
+ continue
36
+ length = len(word.encode("utf-8"))
37
+ if run and start == previous:
38
+ run.append(i)
39
+ size += 1 + length
40
+ else:
41
+ if size > MAX_TEXT_BYTES:
42
+ out.update(run)
43
+ run, size = [i], length
44
+ previous = start
45
+ if size > MAX_TEXT_BYTES:
46
+ out.update(run)
47
+ return out
48
+
49
+
50
+ def _speech_intervals(speech_regions, duration):
51
+ """Clip and union speech regions before measuring speech or its complement."""
52
+ intervals = []
53
+ for region in speech_regions:
54
+ if isinstance(region, dict):
55
+ start, end = region["start"], region["end"]
56
+ else:
57
+ start, end = region
58
+ start, end = max(0.0, float(start)), min(duration, float(end))
59
+ if end > start:
60
+ intervals.append((start, end))
61
+ merged = []
62
+ for start, end in sorted(intervals):
63
+ if merged and start <= merged[-1][1]:
64
+ merged[-1] = (merged[-1][0], max(merged[-1][1], end))
65
+ else:
66
+ merged.append((start, end))
67
+ return merged
68
+
69
+
70
+ def _speech_fallback(words, speech_regions, duration):
71
+ regions = _speech_intervals(speech_regions, duration)
72
+ if not regions:
73
+ return [(0.0, 0.0) for _ in words]
74
+ cumulative = [0.0]
75
+ for start, end in regions:
76
+ cumulative.append(cumulative[-1] + end - start)
77
+ lengths = [len(word) for word in words]
78
+ if not sum(lengths):
79
+ lengths = [1] * len(words)
80
+ total_chars = sum(lengths)
81
+
82
+ def recording_time(speech_time, *, is_end):
83
+ # At a speech-region seam, starts belong to the next region and ends
84
+ # to the preceding one, so a word ending at a seam excludes silence.
85
+ search = bisect_left if is_end else bisect_right
86
+ index = max(0, min(len(regions) - 1, search(cumulative, speech_time) - 1))
87
+ return regions[index][0] + speech_time - cumulative[index]
88
+
89
+ times = []
90
+ chars = 0
91
+ for length in lengths:
92
+ start = recording_time(cumulative[-1] * chars / total_chars, is_end=False)
93
+ chars += length
94
+ end = recording_time(cumulative[-1] * chars / total_chars, is_end=True)
95
+ times.append((start, max(start, end)))
96
+ return times
97
+
98
+
99
+ def approximate_times(words, asr_words, speech_regions, duration):
100
+ """Match gated ASR anchors, interpolate, or use a VAD character-time map.
101
+
102
+ ``asr_words`` contains dictionaries with ``word``, ``start``, and ``end``;
103
+ VAD regions may be dictionaries or ``(start, end)`` pairs in seconds.
104
+ """
105
+ if not words:
106
+ return []
107
+ asr = [
108
+ word for word in asr_words
109
+ if word.get("start") is not None and word.get("end") is not None
110
+ ]
111
+ key = lambda word: re.sub(r"[^0-9a-z]", "", word.lower())
112
+ matcher = SequenceMatcher(
113
+ None, [key(word) for word in words], [key(word["word"]) for word in asr],
114
+ autojunk=False,
115
+ )
116
+ candidates = [
117
+ (target + offset, source + offset)
118
+ for target, source, size in matcher.get_matching_blocks()
119
+ for offset in range(size)
120
+ ]
121
+ anchors = []
122
+ for target, source in candidates:
123
+ start, end = float(asr[source]["start"]), float(asr[source]["end"])
124
+ if not anchors or start - anchors[-1][2] <= 10.0 + 0.5 * (target - anchors[-1][0] - 1):
125
+ anchors.append((target, start, end))
126
+ minimum = 1 if len(words) <= 2 else 2
127
+ if len(anchors) < minimum or len(anchors) < 0.5 * len(candidates):
128
+ return _speech_fallback(words, speech_regions, duration)
129
+
130
+ times = [None] * len(words)
131
+ for index, start, end in anchors:
132
+ times[index] = (start, end)
133
+
134
+ def spread(lo, hi, start, end):
135
+ count = hi - lo
136
+ for offset in range(count):
137
+ times[lo + offset] = (
138
+ start + (end - start) * offset / count,
139
+ start + (end - start) * (offset + 1) / count,
140
+ )
141
+
142
+ first, last = anchors[0], anchors[-1]
143
+ spread(0, first[0], float(asr[0]["start"]), first[1])
144
+ for left, right in zip(anchors, anchors[1:]):
145
+ spread(left[0] + 1, right[0], left[2], right[1])
146
+ spread(last[0] + 1, len(words), last[2], float(asr[-1]["end"]))
147
+ previous_start = float("-inf")
148
+ result = []
149
+ for start, end in times:
150
+ start = max(start, previous_start)
151
+ result.append((start, max(start, end)))
152
+ previous_start = start
153
+ if _oversized_start_group(words, result):
154
+ # Time cuts cannot separate words that share one approximate start; a run of them over
155
+ # MAX_TEXT_BYTES falls back to the VAD character-time map.
156
+ return _speech_fallback(words, speech_regions, duration)
157
+ return result
158
+
159
+
160
+ def _cut_tiers(approx, speech_regions, duration):
161
+ silences = []
162
+ previous_end = 0.0
163
+ for start, end in _speech_intervals(speech_regions, duration):
164
+ if start - previous_end >= 0.5:
165
+ silences.append((start + previous_end) / 2.0)
166
+ previous_end = end
167
+ if duration - previous_end >= 0.5:
168
+ silences.append((duration + previous_end) / 2.0)
169
+
170
+ # Test silence midpoints against the union of approximate word intervals.
171
+ # Keeping cumulative maximum ends also handles overlapping word maps.
172
+ ordered = sorted(approx)
173
+ starts, furthest_ends = [], []
174
+ furthest = float("-inf")
175
+ for start, end in ordered:
176
+ starts.append(start)
177
+ furthest = max(furthest, end)
178
+ furthest_ends.append(furthest)
179
+ safe_silences = []
180
+ for point in silences:
181
+ index = bisect_right(starts, point) - 1
182
+ if index < 0 or furthest_ends[index] < point:
183
+ safe_silences.append(point)
184
+ word_gaps = sorted({(left[1] + right[0]) / 2.0 for left, right in zip(approx, approx[1:])})
185
+ return safe_silences, silences, word_gaps
186
+
187
+
188
+ def plan_chunks(words, approx, speech_regions, duration):
189
+ """Return cores, context audio ranges, and original word indices.
190
+
191
+ Cores are at most 26 seconds and audio adds at most two seconds on either
192
+ side. Oversized transcripts first lose context and then split their core
193
+ recursively, preserving time-based word ownership.
194
+ """
195
+ if not words:
196
+ return []
197
+ if len(words) != len(approx):
198
+ raise ValueError("Word and approximate-time counts differ")
199
+ starts = [float(interval[0]) for interval in approx]
200
+ byte_prefix = [0]
201
+ for word in words:
202
+ length = len(word.encode("utf-8"))
203
+ if length > MAX_TEXT_BYTES:
204
+ raise ValueError("A single word exceeds the 1022-byte transcript limit")
205
+ byte_prefix.append(byte_prefix[-1] + length)
206
+
207
+ def text_bytes(lo, hi):
208
+ return byte_prefix[hi] - byte_prefix[lo] + max(0, hi - lo - 1)
209
+
210
+ # Equal approximate starts cannot be separated by any time-based cut.
211
+ if _oversized_start_group(words, approx):
212
+ raise ValueError("Words sharing an approximate start exceed the 1022-byte limit")
213
+
214
+ tiers = _cut_tiers(approx, speech_regions, duration)
215
+ cores = []
216
+ a = 0.0
217
+ while duration - a > _CORE_SECONDS:
218
+ b = a + _CORE_SECONDS
219
+ for tier in tiers:
220
+ right = bisect_right(tier, b)
221
+ if right and tier[right - 1] > a:
222
+ b = tier[right - 1]
223
+ break
224
+ cores.append((a, b))
225
+ a = b
226
+ cores.append((a, float(duration)))
227
+
228
+ def route(core):
229
+ a, b = core
230
+ audio = (max(0.0, a - _CONTEXT_SECONDS), min(duration, b + _CONTEXT_SECONDS))
231
+ # The first/last cores also own starts on the recording's outer edges.
232
+ owned_lo = 0 if a == 0.0 else bisect_left(starts, a)
233
+ owned_hi = len(words) if b == duration else bisect_left(starts, b)
234
+ lo, hi = owned_lo, owned_hi
235
+
236
+ def overlaps(index):
237
+ start, end = approx[index]
238
+ return start < audio[1] and end > audio[0]
239
+
240
+ while lo > 0 and overlaps(lo - 1):
241
+ lo -= 1
242
+ while hi < len(words) and overlaps(hi):
243
+ hi += 1
244
+ if text_bytes(lo, hi) > MAX_TEXT_BYTES:
245
+ lo, hi = owned_lo, owned_hi
246
+ if text_bytes(lo, hi) <= MAX_TEXT_BYTES:
247
+ return {"core": core, "audio": audio, "indices": list(range(lo, hi))}
248
+ return None
249
+
250
+ result = []
251
+ pending = list(reversed(cores))
252
+ while pending:
253
+ core = pending.pop()
254
+ chunk = route(core)
255
+ if chunk is not None:
256
+ result.append(chunk)
257
+ continue
258
+ a, b = core
259
+ midpoint = (a + b) / 2.0
260
+ cut = midpoint
261
+ for tier in tiers:
262
+ lo, hi = bisect_right(tier, a), bisect_left(tier, b)
263
+ if lo < hi:
264
+ near = bisect_left(tier, midpoint, lo, hi)
265
+ choices = tier[max(lo, near - 1):min(hi, near + 1)]
266
+ cut = min(choices, key=lambda point: (abs(point - midpoint), -point))
267
+ break
268
+ if not a < cut < b:
269
+ raise ValueError("Cannot split an oversized transcript at distinct recording times")
270
+ pending.append((cut, b))
271
+ pending.append((a, cut))
272
+ return result
273
+
274
+
275
+ def stitch_predictions(n_words, chunks, predictions):
276
+ """Select one placed recording-time prediction for each original word.
277
+
278
+ An in-core center beats every out-of-core center; among in-core centers,
279
+ prefer the largest margin to an edge. Otherwise prefer the smallest
280
+ distance to the core. Ties retain the first prediction in chunk order.
281
+ """
282
+ result = [None] * n_words
283
+ if not n_words:
284
+ return result
285
+ priorities = [None] * n_words
286
+ for chunk, placed in zip(chunks, predictions, strict=True):
287
+ a, b = chunk["core"]
288
+ for index, interval in zip(chunk["indices"], placed, strict=True):
289
+ if interval is None:
290
+ continue
291
+ start, end = interval
292
+ center = (start + end) / 2.0
293
+ if a <= center <= b:
294
+ priority = (1, min(center - a, b - center))
295
+ else:
296
+ priority = (0, -max(a - center, center - b))
297
+ if priorities[index] is None or priority > priorities[index]:
298
+ priorities[index] = priority
299
+ result[index] = (start, end)
300
+ return result
301
+
302
+
303
+ def fill_unplaced(intervals, duration):
304
+ """Fill each maximal null run with equal parts of its surrounding gap.
305
+
306
+ A leading gap begins at zero; a trailing gap ends at ``duration``. With no
307
+ placed words the entire clip is divided equally. Placed entries are kept
308
+ verbatim, without clamping, reordering, or correcting overlapping intervals.
309
+ """
310
+ filled = list(intervals)
311
+ index = 0
312
+ while index < len(filled):
313
+ if filled[index] is not None:
314
+ index += 1
315
+ continue
316
+ lo = index
317
+ while index < len(filled) and filled[index] is None:
318
+ index += 1
319
+ left = filled[lo - 1][1] if lo else 0.0
320
+ right = filled[index][0] if index < len(filled) else duration
321
+ width = (right - left) / (index - lo)
322
+ for offset in range(index - lo):
323
+ filled[lo + offset] = (left + offset * width,
324
+ right if lo + offset + 1 == index
325
+ else left + (offset + 1) * width)
326
+ return filled
327
+
328
+
329
+ def guide_words(utterances, words_of=str.split) -> list[dict]:
330
+ """Turn timed utterances into the per-token ``{"word", "start", "end"}``
331
+ list that ``approximate_times`` consumes.
332
+
333
+ Token ``i`` of ``n`` spans ``[start + i/n*(end-start), start + (i+1)/n*(end-start)]``:
334
+ the paper's interpolation between anchors, with the utterance edges as the
335
+ anchors. Utterances with a missing time or no tokens are skipped.
336
+ """
337
+ out = []
338
+ for utterance in utterances:
339
+ start, end = utterance.get("start"), utterance.get("end")
340
+ tokens = words_of(utterance["text"])
341
+ if start is None or end is None or not tokens:
342
+ continue
343
+ n = len(tokens)
344
+ for i, token in enumerate(tokens):
345
+ out.append({
346
+ "word": token,
347
+ "start": start + i / n * (end - start),
348
+ "end": start + (i + 1) / n * (end - start),
349
+ })
350
+ return out
fusealign_hub/model.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FuseAlign network (inference only).
2
+
3
+ Parameter names match the training code's state dicts, so exports load with ``strict=True``.
4
+ Deviation from the training code: ``RefinementHead`` masks each sample's padded frames, so a padded
5
+ batch scores every clip as it would alone.
6
+ """
7
+
8
+ from dataclasses import dataclass
9
+
10
+ import torch
11
+ from torch import nn
12
+ from torch.nn import functional as F
13
+
14
+
15
+ class RMSNorm(nn.Module):
16
+ def __init__(self, dim: int, eps: float = 1e-6):
17
+ super().__init__()
18
+ self.weight = nn.Parameter(torch.ones(dim))
19
+ self.eps = eps
20
+
21
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
22
+ normalized = x.float()
23
+ normalized = normalized * torch.rsqrt(
24
+ normalized.square().mean(dim=-1, keepdim=True) + self.eps
25
+ )
26
+ return normalized.to(x.dtype) * self.weight.to(x.dtype)
27
+
28
+
29
+ class RotaryEmbedding(nn.Module):
30
+ """RoPE with real-valued positions, shared across the joint blocks."""
31
+
32
+ def __init__(self, head_dim: int, theta: float):
33
+ super().__init__()
34
+ inv_freq = theta ** (-torch.arange(0, head_dim, 2, dtype=torch.float32) / head_dim)
35
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
36
+
37
+ def forward(self, positions: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
38
+ # Keep fractional text positions and their phases in fp32 under autocast.
39
+ with torch.autocast(device_type=positions.device.type, enabled=False):
40
+ angles = positions.float().unsqueeze(-1) * self.inv_freq.float()
41
+ angles = torch.cat((angles, angles), dim=-1).unsqueeze(1)
42
+ return angles.cos(), angles.sin()
43
+
44
+
45
+ def _apply_rope(
46
+ x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor
47
+ ) -> torch.Tensor:
48
+ first, second = x.chunk(2, dim=-1)
49
+ rotated = torch.cat((-second, first), dim=-1)
50
+ return x * cos + rotated * sin
51
+
52
+
53
+ class JointAttention(nn.Module):
54
+ def __init__(self, dim: int, n_heads: int):
55
+ super().__init__()
56
+ self.n_heads = n_heads
57
+ self.head_dim = dim // n_heads
58
+ self.qkv = nn.Linear(dim, 3 * dim, bias=False)
59
+ self.out = nn.Linear(dim, dim, bias=False)
60
+
61
+ def forward(
62
+ self,
63
+ x: torch.Tensor,
64
+ key_mask: torch.Tensor,
65
+ cos: torch.Tensor,
66
+ sin: torch.Tensor,
67
+ ) -> torch.Tensor:
68
+ batch_size, sequence_length, dim = x.shape
69
+ qkv = self.qkv(x).reshape(
70
+ batch_size, sequence_length, 3, self.n_heads, self.head_dim
71
+ )
72
+ q, k, v = qkv.permute(2, 0, 3, 1, 4).unbind(0)
73
+ cos, sin = cos.to(q.dtype), sin.to(q.dtype)
74
+ q = _apply_rope(q, cos, sin)
75
+ k = _apply_rope(k, cos, sin)
76
+ # True means an allowed key. Padded queries still see valid keys, so
77
+ # no query has an all-masked softmax; blocks zero their outputs below.
78
+ attended = F.scaled_dot_product_attention(q, k, v, attn_mask=key_mask)
79
+ attended = attended.transpose(1, 2).reshape(batch_size, sequence_length, dim)
80
+ return self.out(attended)
81
+
82
+
83
+ class SwiGLU(nn.Module):
84
+ def __init__(self, dim: int, ffn_dim: int):
85
+ super().__init__()
86
+ self.w1 = nn.Linear(dim, ffn_dim, bias=False)
87
+ self.w3 = nn.Linear(dim, ffn_dim, bias=False)
88
+ self.w2 = nn.Linear(ffn_dim, dim, bias=False)
89
+
90
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
91
+ return self.w2(F.silu(self.w1(x)) * self.w3(x))
92
+
93
+
94
+ class JointBlock(nn.Module):
95
+ def __init__(self, dim: int, n_heads: int, ffn_dim: int):
96
+ super().__init__()
97
+ self.attn_norm = RMSNorm(dim)
98
+ self.attn = JointAttention(dim, n_heads)
99
+ self.ffn_norm = RMSNorm(dim)
100
+ self.ffn = SwiGLU(dim, ffn_dim)
101
+
102
+ def forward(
103
+ self,
104
+ x: torch.Tensor,
105
+ key_mask: torch.Tensor,
106
+ padding_mask: torch.Tensor,
107
+ cos: torch.Tensor,
108
+ sin: torch.Tensor,
109
+ ) -> torch.Tensor:
110
+ x = x + self.attn(self.attn_norm(x), key_mask, cos, sin)
111
+ x = x + self.ffn(self.ffn_norm(x))
112
+ return x.masked_fill(padding_mask, 0)
113
+
114
+
115
+ class RefinementHead(nn.Sequential):
116
+ def __init__(self, dim: int, feat_dim: int, n_upsample: int):
117
+ layers = [nn.Conv1d(dim, feat_dim, kernel_size=1)]
118
+ for _ in range(n_upsample):
119
+ layers.extend(
120
+ [
121
+ nn.ConvTranspose1d(
122
+ feat_dim, feat_dim, kernel_size=4, stride=2, padding=1
123
+ ),
124
+ nn.GELU(),
125
+ ]
126
+ )
127
+ layers.extend(
128
+ [
129
+ nn.Conv1d(feat_dim, feat_dim, kernel_size=5, padding=2),
130
+ nn.GELU(),
131
+ nn.Conv1d(feat_dim, feat_dim, kernel_size=1),
132
+ ]
133
+ )
134
+ super().__init__(*layers)
135
+
136
+ def forward(self, x: torch.Tensor, lengths: torch.Tensor) -> torch.Tensor:
137
+ """Zero each sample's frames past ``lengths`` after every convolution.
138
+
139
+ Unlike the plain ``nn.Sequential`` used in training: without the masking, conv bias in a
140
+ padded batch's padded frames reaches the last valid frames of shorter samples through the
141
+ upsampling and kernel-5 convolutions, so a clip's end-of-clip logits would depend on its
142
+ batch companions. A no-op for an unpadded batch.
143
+ """
144
+ for layer in self:
145
+ x = layer(x)
146
+ if isinstance(layer, nn.ConvTranspose1d):
147
+ lengths = lengths * 2
148
+ if not isinstance(layer, nn.GELU):
149
+ frames = torch.arange(x.shape[-1], device=x.device)
150
+ x = x.masked_fill(frames[None, None, :] >= lengths[:, None, None], 0)
151
+ return x
152
+
153
+
154
+ def _word_mlp(dim: int, output_dim: int) -> nn.Sequential:
155
+ return nn.Sequential(nn.Linear(dim, dim), nn.GELU(), nn.Linear(dim, output_dim))
156
+
157
+
158
+ class FuseAlign(nn.Module):
159
+ def __init__(self, args):
160
+ super().__init__()
161
+ self.args = args
162
+ self.audio_patch = nn.Conv1d(
163
+ 1, args.dim, kernel_size=args.patch_window, stride=args.patch_hop
164
+ )
165
+ self.text_proj = nn.Linear(args.text_dim, args.dim)
166
+ self.mod_emb = nn.Parameter(torch.empty(2, args.dim))
167
+ nn.init.normal_(self.mod_emb, mean=0.0, std=0.02)
168
+ self.rope = RotaryEmbedding(args.dim // args.n_heads, args.rope_theta)
169
+ self.blocks = nn.ModuleList(
170
+ JointBlock(args.dim, args.n_heads, args.ffn_dim)
171
+ for _ in range(args.n_layers)
172
+ )
173
+ self.final_norm = RMSNorm(args.dim)
174
+ self.start_refinement = RefinementHead(args.dim, args.feat_dim, args.n_upsample)
175
+ self.end_refinement = RefinementHead(args.dim, args.feat_dim, args.n_upsample)
176
+ self.start_mlp = _word_mlp(args.dim, args.feat_dim)
177
+ self.end_mlp = _word_mlp(args.dim, args.feat_dim)
178
+ self.presence_mlp = _word_mlp(args.dim, 1)
179
+ nn.init.constant_(self.presence_mlp[-1].bias, args.presence_bias_init)
180
+
181
+ @staticmethod
182
+ def _standardize(wav: torch.Tensor, lengths: torch.Tensor) -> torch.Tensor:
183
+ sample_mask = torch.arange(wav.shape[1], device=wav.device)[None, :] < lengths[:, None]
184
+ with torch.autocast(device_type=wav.device.type, enabled=False):
185
+ samples = wav.float().masked_fill(~sample_mask, 0)
186
+ counts = lengths[:, None].float()
187
+ mean = samples.sum(dim=1, keepdim=True) / counts
188
+ centered = (samples - mean).masked_fill(~sample_mask, 0)
189
+ std = (centered.square().sum(dim=1, keepdim=True) / counts).sqrt()
190
+ return centered / (std + 1e-5)
191
+
192
+ def forward(
193
+ self,
194
+ wav: torch.Tensor,
195
+ wav_lengths: torch.Tensor,
196
+ text_feats: torch.Tensor,
197
+ text_mask: torch.Tensor,
198
+ word_spans: torch.Tensor,
199
+ word_mask: torch.Tensor,
200
+ ) -> dict[str, torch.Tensor]:
201
+ audio = self.audio_patch(self._standardize(wav, wav_lengths).unsqueeze(1))
202
+ audio = audio.transpose(1, 2)
203
+ audio_lengths = (wav_lengths - self.args.patch_window) // self.args.patch_hop + 1
204
+ audio_positions = torch.arange(audio.shape[1], device=wav.device)
205
+ audio_mask = audio_positions[None, :] < audio_lengths[:, None]
206
+
207
+ text = self.text_proj(text_feats)
208
+ byte_mask = text_mask[:, 2:].bool()
209
+ byte_positions = torch.arange(text.shape[1], device=wav.device)
210
+ text_lengths = byte_mask.sum(dim=1)
211
+ text_scale = audio_lengths.float() / (text_lengths - 1).clamp_min(1).float()
212
+ text_positions = byte_positions[None, :].float() * text_scale[:, None]
213
+ text_positions = text_positions.masked_fill(~byte_mask, 0)
214
+ audio_rope_positions = audio_positions[None, :].expand(wav.shape[0], -1).float()
215
+ audio_rope_positions = audio_rope_positions.masked_fill(~audio_mask, 0)
216
+ positions = torch.cat((audio_rope_positions, text_positions), dim=1)
217
+ cos, sin = self.rope(positions)
218
+ cos, sin = cos.to(audio.dtype), sin.to(audio.dtype)
219
+
220
+ # Rectangular modality padding does not change the valid joint sequence:
221
+ # attention masks out those keys, and RoPE uses per-sample positions.
222
+ joint = torch.cat((audio + self.mod_emb[0], text + self.mod_emb[1]), dim=1)
223
+ valid_mask = torch.cat((audio_mask, byte_mask), dim=1)
224
+ padding_mask = ~valid_mask.unsqueeze(-1)
225
+ joint = joint.masked_fill(padding_mask, 0)
226
+ key_mask = valid_mask[:, None, None, :]
227
+ for block in self.blocks:
228
+ joint = block(joint, key_mask, padding_mask, cos, sin)
229
+ joint = self.final_norm(joint).masked_fill(padding_mask, 0)
230
+ audio_out = joint[:, :audio.shape[1]].transpose(1, 2)
231
+ text_out = joint[:, audio.shape[1]:]
232
+
233
+ membership = (
234
+ (byte_positions[None, None, :] >= word_spans[:, :, 0, None])
235
+ & (byte_positions[None, None, :] < word_spans[:, :, 1, None])
236
+ & byte_mask[:, None, :]
237
+ & word_mask[:, :, None]
238
+ )
239
+ pooling = membership.to(text_out.dtype)
240
+ pooling = pooling / pooling.sum(dim=-1, keepdim=True).clamp_min(1)
241
+ word_vectors = torch.bmm(pooling, text_out)
242
+ start_features = self.start_refinement(audio_out, audio_lengths)
243
+ end_features = self.end_refinement(audio_out, audio_lengths)
244
+
245
+ with torch.autocast(device_type=wav.device.type, enabled=False):
246
+ word_vectors = word_vectors.float()
247
+ start_logits = torch.einsum(
248
+ "bwf,bft->bwt", self.start_mlp(word_vectors), start_features.float()
249
+ )
250
+ end_logits = torch.einsum(
251
+ "bwf,bft->bwt", self.end_mlp(word_vectors), end_features.float()
252
+ )
253
+ presence_logits = self.presence_mlp(word_vectors).squeeze(-1)
254
+ return {
255
+ "start_logits": start_logits,
256
+ "end_logits": end_logits,
257
+ "presence_logits": presence_logits,
258
+ "frame_lengths": audio_lengths * (2 ** self.args.n_upsample),
259
+ }
260
+
261
+
262
+ @dataclass
263
+ class FuseAlignArgs:
264
+ dim: int = 1024
265
+ n_layers: int = 12
266
+ n_heads: int = 16
267
+ ffn_dim: int = 4096
268
+ feat_dim: int = 256
269
+ patch_window: int = 512
270
+ patch_hop: int = 256
271
+ n_upsample: int = 4
272
+ text_dim: int = 1024
273
+ rope_theta: float = 1e4
274
+ presence_bias_init: float = 2.0
275
+ dia_repo: str = "nari-labs/Dia-1.6B-0626"
276
+
277
+
278
+ def cast_autocast_weights(net: FuseAlign) -> None:
279
+ """Store in bf16 the weights CUDA autocast casts to bf16 on every forward.
280
+
281
+ Bit-identical (autocast rounds the same fp32 values the same way) and drops ~200 cast
282
+ kernels per forward. RMSNorm weights, ``mod_emb`` and the word MLPs, which run with
283
+ autocast disabled, stay fp32.
284
+ """
285
+ fp32 = {id(layer) for mlp in (net.start_mlp, net.end_mlp, net.presence_mlp) for layer in mlp}
286
+ for module in net.modules():
287
+ if isinstance(module, (nn.Linear, nn.Conv1d, nn.ConvTranspose1d)) and id(module) not in fp32:
288
+ module.to(torch.bfloat16)
fusealign_hub/text_encoder.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Frozen Dia UTF-8 text features, excluding the two-token ``[S1] `` prefix."""
2
+
3
+ import torch
4
+ from torch import nn
5
+
6
+
7
+ class DiaTextEncoder(nn.Module):
8
+ """Dia's text encoder built from its config and the 98 encoder tensors, stored in bf16.
9
+
10
+ ``config`` is Dia's ``encoder_config``; ``state`` is keyed as ``DiaEncoder`` expects
11
+ (``model.encoder.`` stripped). Inputs contain the speaker/space prefix and right padding. The
12
+ returned bf16 features retain transcript padding but omit the two prefix positions. This
13
+ module remains frozen and in evaluation mode even when its parent enters training mode.
14
+ """
15
+
16
+ def __init__(self, config: dict, state: dict[str, torch.Tensor]):
17
+ from transformers.models.dia.configuration_dia import DiaEncoderConfig
18
+ from transformers.models.dia.modeling_dia import DiaEncoder
19
+
20
+ super().__init__()
21
+ self.encoder = DiaEncoder(DiaEncoderConfig(**config))
22
+ self.encoder.to(dtype=torch.bfloat16)
23
+ self.encoder.load_state_dict(
24
+ {key: value.to(torch.bfloat16) for key, value in state.items()}, strict=True
25
+ )
26
+ self.requires_grad_(False)
27
+ self.eval()
28
+
29
+ def train(self, mode: bool = True):
30
+ return super().train(False)
31
+
32
+ @torch.no_grad()
33
+ def forward(self, text_ids: torch.Tensor, text_mask: torch.Tensor) -> torch.Tensor:
34
+ if text_ids.shape[-1] > 1024:
35
+ raise ValueError(
36
+ f"Dia accepts at most 1024 tokens including the prefix; "
37
+ f"received {text_ids.shape[-1]}"
38
+ )
39
+ return self.encoder(
40
+ input_ids=text_ids, attention_mask=text_mask.long()
41
+ ).last_hidden_state[:, 2:]
fusealign_hub/vad.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Vectorized Silero VAD v5 (16 kHz) front-end for long-form cut points."""
2
+
3
+ from functools import lru_cache
4
+
5
+ import torch
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+
9
+ SAMPLE_RATE = 16000
10
+ VAD_BLOCK_FRAMES = 4096 # 512-sample frames per front-end call (~131 s); bounds memory on long recordings
11
+
12
+
13
+ @lru_cache(maxsize=1)
14
+ def _silero():
15
+ """Silero VAD v5 16 kHz weights from the ``silero-vad`` package's JIT model:
16
+ ``(weights, lstm, get_speech_timestamps_from_probs)``.
17
+
18
+ Importing ``silero_vad`` runs ``torch.set_num_threads(1)`` (``silero_vad/model.py``), which
19
+ would silently single-thread the rest of the process; the caller's count is put back.
20
+ """
21
+ threads = torch.get_num_threads()
22
+ try:
23
+ import silero_vad
24
+
25
+ model = silero_vad.load_silero_vad()
26
+ finally:
27
+ torch.set_num_threads(threads)
28
+ from_probs = getattr(silero_vad, "get_speech_timestamps_from_probs", None)
29
+ if from_probs is None:
30
+ raise RuntimeError(
31
+ "silero-vad lacks get_speech_timestamps_from_probs; install silero-vad>=6.2.3"
32
+ )
33
+ weights = {
34
+ key.removeprefix("_model."): value.detach().clone()
35
+ for key, value in model.state_dict().items()
36
+ if key.startswith("_model.") # not "_model_8k."
37
+ }
38
+ lstm = nn.LSTM(128, 128)
39
+ with torch.no_grad():
40
+ for name in ("weight_ih", "weight_hh", "bias_ih", "bias_hh"):
41
+ getattr(lstm, f"{name}_l0").copy_(weights[f"decoder.rnn.{name}"])
42
+ lstm.requires_grad_(False)
43
+ return weights, lstm.eval(), from_probs
44
+
45
+
46
+ @torch.inference_mode()
47
+ def silero_probs(wav: torch.Tensor) -> torch.Tensor:
48
+ """Per-512-sample-frame speech probabilities of a 16 kHz CPU waveform.
49
+
50
+ The JIT model's streaming loop (``get_speech_timestamps``) runs the whole network once per
51
+ frame. Only its LSTM carries state: the STFT and encoder see one frame plus the previous
52
+ frame's last 64 samples, so they run over every frame of a block at once and the LSTM steps
53
+ through the sequence. Same weights and inputs (zero context first, zero-padded last frame);
54
+ agrees with the JIT model to ~2e-6 on CPU, not bit for bit. ~20x faster on CPU; on CUDA it
55
+ drifts to 2e-3, so it always runs on CPU.
56
+ """
57
+ weights, lstm, _ = _silero()
58
+ n_frames = -(-wav.numel() // 512)
59
+ features = []
60
+ for first in range(0, n_frames, VAD_BLOCK_FRAMES):
61
+ last = min(n_frames, first + VAD_BLOCK_FRAMES)
62
+ lo = first * 512
63
+ block = wav[lo:last * 512]
64
+ frames = F.pad(block, (0, (last - first) * 512 - block.numel())).reshape(-1, 512)
65
+ previous = wav[lo - 64:lo] if first else wav.new_zeros(64)
66
+ context = torch.cat((previous.unsqueeze(0), frames[:-1, -64:]))
67
+ x = F.pad(torch.cat((context, frames), dim=1), (0, 64), mode="reflect").unsqueeze(1)
68
+ x = F.conv1d(x, weights["stft.forward_basis_buffer"], stride=128)
69
+ x = (x[:, :129].square() + x[:, 129:].square()).sqrt()
70
+ for index, stride in enumerate((1, 2, 2, 1)):
71
+ x = F.relu(F.conv1d(
72
+ x, weights[f"encoder.{index}.reparam_conv.weight"],
73
+ weights[f"encoder.{index}.reparam_conv.bias"], stride=stride, padding=1,
74
+ ))
75
+ features.append(x.squeeze(-1))
76
+ hidden, _ = lstm(torch.cat(features).unsqueeze(1))
77
+ logits = F.conv1d(
78
+ F.relu(hidden).permute(1, 2, 0),
79
+ weights["decoder.decoder.2.weight"], weights["decoder.decoder.2.bias"],
80
+ )
81
+ return torch.sigmoid(logits).reshape(-1)
82
+
83
+
84
+ def speech_regions(wav: torch.Tensor) -> list[dict]:
85
+ """``get_speech_timestamps(wav, model, sampling_rate=16000, return_seconds=True)``,
86
+ with the probabilities from ``silero_probs``."""
87
+ _, _, from_probs = _silero()
88
+ return from_probs(
89
+ silero_probs(wav).tolist(), sampling_rate=SAMPLE_RATE, return_seconds=True,
90
+ audio_length_samples=wav.numel(),
91
+ )
requirements.txt CHANGED
@@ -12,3 +12,11 @@ joblib==1.5.3
12
  sacremoses==0.1.1
13
  tqdm==4.67.1
14
  pyyaml==6.0.3
 
 
 
 
 
 
 
 
 
12
  sacremoses==0.1.1
13
  tqdm==4.67.1
14
  pyyaml==6.0.3
15
+ safetensors==0.7.0
16
+ silero-vad==6.2.3
17
+ accelerate==1.12.0
18
+ librosa==1.0.0
19
+ nagisa==0.2.11
20
+ soynlp==0.0.493
21
+ qwen-omni-utils==0.0.9
22
+ sox==1.5.0
zonos3/models/accent_format.py CHANGED
@@ -89,7 +89,9 @@ class AccentAdapter:
89
  ``(x @ down.T) @ up`` on the flat ``[out, in]`` product; ``shapes``: the weight shape each linear shift was trained
90
  on. ``experts``: experts module (``layers.N.feed_forward.experts``) -> weight (``w13`` / ``w2``) -> (up [E, out, r],
91
  down [E, r, in]) float32 in the SonicExperts layout. ``router_bias``: router module (``layers.N.feed_forward.router``)
92
- -> float32 [experts] added to its balancing biases."""
 
 
93
 
94
  name: str
95
  format: str
@@ -97,6 +99,7 @@ class AccentAdapter:
97
  shapes: dict[str, tuple[int, ...]] = field(default_factory=dict)
98
  experts: dict[str, dict[str, tuple[torch.Tensor, torch.Tensor]]] = field(default_factory=dict)
99
  router_bias: dict[str, torch.Tensor] = field(default_factory=dict)
 
100
 
101
  @property
102
  def rank(self) -> int:
@@ -104,18 +107,27 @@ class AccentAdapter:
104
  return max((down.shape[0] for down, _ in self.linear.values()), default=0)
105
 
106
 
107
- def load_adapter(path: str | Path) -> AccentAdapter:
108
- """Parse ``<accent>.pt``; raises ValueError for a file no server can apply."""
 
 
 
 
 
109
  path = Path(path)
110
  adapter = torch.load(path, map_location="cpu", weights_only=True)
111
  fmt = adapter.get("format")
112
  if fmt not in FORMATS:
113
  raise ValueError(f"{path}: not a {' / '.join(FORMATS)} adapter")
114
  router_bias: dict[str, torch.Tensor] = {}
 
115
  for target, shift in adapter["exact"].items():
116
  served, zero_mean = served_exact_name(target)
117
  if served is None:
118
  continue
 
 
 
119
  if not served.endswith(".router" + BALANCING_BIASES):
120
  raise ValueError(
121
  f"{path}: shifts {target}; accent serving applies only linear "
@@ -161,4 +173,4 @@ def load_adapter(path: str | Path) -> AccentAdapter:
161
  )
162
  linear[module] = (pair["down"].float(), pair["up"].float().T)
163
  shapes[module] = tuple(pair["shape"])
164
- return AccentAdapter(path.stem, fmt, linear, shapes, experts, router_bias)
 
89
  ``(x @ down.T) @ up`` on the flat ``[out, in]`` product; ``shapes``: the weight shape each linear shift was trained
90
  on. ``experts``: experts module (``layers.N.feed_forward.experts``) -> weight (``w13`` / ``w2``) -> (up [E, out, r],
91
  down [E, r, in]) float32 in the SonicExperts layout. ``router_bias``: router module (``layers.N.feed_forward.router``)
92
+ -> float32 [experts] added to its balancing biases. ``tables``: embedding / output-head weight
93
+ (``multi_embedder.embedders.<i>.weight``, ``multi_output.weight``) -> float32 shift of its rows, only in adapters
94
+ loaded with ``tables=True`` (an adapter trained with the vocabulary grown, e.g. a speech-edit LoRA)."""
95
 
96
  name: str
97
  format: str
 
99
  shapes: dict[str, tuple[int, ...]] = field(default_factory=dict)
100
  experts: dict[str, dict[str, tuple[torch.Tensor, torch.Tensor]]] = field(default_factory=dict)
101
  router_bias: dict[str, torch.Tensor] = field(default_factory=dict)
102
+ tables: dict[str, torch.Tensor] = field(default_factory=dict)
103
 
104
  @property
105
  def rank(self) -> int:
 
107
  return max((down.shape[0] for down, _ in self.linear.values()), default=0)
108
 
109
 
110
+ TABLES = ("multi_embedder.embedders.", "multi_output.weight")
111
+
112
+
113
+ def load_adapter(path: str | Path, *, tables: bool = False) -> AccentAdapter:
114
+ """Parse ``<accent>.pt``; raises ValueError for a file no server can apply. ``tables``: also take the adapter's
115
+ shifts of the embedding tables and the output head (a reference-only path: the sgl, ggml and MLX servers refuse
116
+ them)."""
117
  path = Path(path)
118
  adapter = torch.load(path, map_location="cpu", weights_only=True)
119
  fmt = adapter.get("format")
120
  if fmt not in FORMATS:
121
  raise ValueError(f"{path}: not a {' / '.join(FORMATS)} adapter")
122
  router_bias: dict[str, torch.Tensor] = {}
123
+ table_shifts: dict[str, torch.Tensor] = {}
124
  for target, shift in adapter["exact"].items():
125
  served, zero_mean = served_exact_name(target)
126
  if served is None:
127
  continue
128
+ if tables and served.startswith(TABLES) and served.endswith(".weight"):
129
+ table_shifts[served] = shift.float()
130
+ continue
131
  if not served.endswith(".router" + BALANCING_BIASES):
132
  raise ValueError(
133
  f"{path}: shifts {target}; accent serving applies only linear "
 
173
  )
174
  linear[module] = (pair["down"].float(), pair["up"].float().T)
175
  shapes[module] = tuple(pair["shape"])
176
+ return AccentAdapter(path.stem, fmt, linear, shapes, experts, router_bias, table_shifts)
zonos3/reference/accents.py CHANGED
@@ -4,6 +4,8 @@ A target linear adds ``strength * ((x @ down.T) @ up)`` to its flat ``[out, in]`
4
  ``strength * shift`` to its balancing biases, and each routed (token, expert) pair adds
5
  ``strength * up[e] @ (down[e] @ row)`` to its gate/up pre-activation (w13, SonicExperts interleaved rows) and its
6
  expert output (w2) -- zonos3_sgl.layers.accent ``accent_shift`` / ``accent_router_bias`` / ``expert_pair_shift``.
 
 
7
  """
8
 
9
  from __future__ import annotations
@@ -11,6 +13,7 @@ from __future__ import annotations
11
  from dataclasses import dataclass
12
 
13
  import torch
 
14
 
15
  from zonos3.models.accent_format import AccentAdapter
16
 
@@ -54,15 +57,28 @@ class AccentState:
54
  if biases is None or biases.shape != shift.shape:
55
  raise ValueError(f"accent {adapter.name!r} shifts {module}.balancing_biases, not a router of the model")
56
  router_bias[module] = shift.to(device, torch.float32)
57
- moved = AccentAdapter(adapter.name, adapter.format, linear, adapter.shapes, experts, router_bias)
 
 
 
 
 
 
 
58
  return cls(moved, float(strength))
59
 
 
 
 
 
 
60
  def linear(self, module: str, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
61
  factors = self.adapter.linear.get(module)
62
- if factors is None:
63
- return y
64
- down, up = factors
65
- return y + ((x @ down.T) * self.strength) @ up
 
66
 
67
  def router_bias(self, module: str, bias: torch.Tensor) -> torch.Tensor:
68
  shift = self.adapter.router_bias.get(module)
 
4
  ``strength * shift`` to its balancing biases, and each routed (token, expert) pair adds
5
  ``strength * up[e] @ (down[e] @ row)`` to its gate/up pre-activation (w13, SonicExperts interleaved rows) and its
6
  expert output (w2) -- zonos3_sgl.layers.accent ``accent_shift`` / ``accent_router_bias`` / ``expert_pair_shift``.
7
+ An adapter loaded with its table shifts (``load_adapter(tables=True)``) also adds ``strength * shift[id]`` to the
8
+ embedding rows a prompt reads and ``strength * normalized @ shift.T`` to the output head's logits.
9
  """
10
 
11
  from __future__ import annotations
 
13
  from dataclasses import dataclass
14
 
15
  import torch
16
+ import torch.nn.functional as F
17
 
18
  from zonos3.models.accent_format import AccentAdapter
19
 
 
57
  if biases is None or biases.shape != shift.shape:
58
  raise ValueError(f"accent {adapter.name!r} shifts {module}.balancing_biases, not a router of the model")
59
  router_bias[module] = shift.to(device, torch.float32)
60
+ tables = {}
61
+ for name, shift in adapter.tables.items():
62
+ table = params.get(name)
63
+ if table is None or table.shape != shift.shape:
64
+ raise ValueError(f"accent {adapter.name!r} shifts {name} {tuple(shift.shape)}, which the model has as "
65
+ f"{None if table is None else tuple(table.shape)} (grow its vocabulary first)")
66
+ tables[name] = shift.to(device, dtype)
67
+ moved = AccentAdapter(adapter.name, adapter.format, linear, adapter.shapes, experts, router_bias, tables)
68
  return cls(moved, float(strength))
69
 
70
+ def embedding(self, index: int, ids: torch.Tensor, rows: torch.Tensor) -> torch.Tensor:
71
+ """Embedder ``index``'s rows of ``ids`` with the adapter's table shift."""
72
+ shift = self.adapter.tables.get(f"multi_embedder.embedders.{index}.weight")
73
+ return rows if shift is None else rows + self.strength * F.embedding(ids, shift)
74
+
75
  def linear(self, module: str, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
76
  factors = self.adapter.linear.get(module)
77
+ if factors is not None:
78
+ down, up = factors
79
+ y = y + ((x @ down.T) * self.strength) @ up
80
+ table = self.adapter.tables.get(module + ".weight")
81
+ return y if table is None else y + self.strength * (x @ table.T)
82
 
83
  def router_bias(self, module: str, bias: torch.Tensor) -> torch.Tensor:
84
  shift = self.adapter.router_bias.get(module)
zonos3/reference/lm.py CHANGED
@@ -14,7 +14,7 @@ from __future__ import annotations
14
  import json
15
  import math
16
  import re
17
- from dataclasses import dataclass, field
18
  from pathlib import Path
19
  from typing import NamedTuple
20
 
@@ -405,6 +405,37 @@ class Zonos3LM(nn.Module):
405
  model.root = root
406
  return model.cast(dtype)
407
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
408
  def cast(self, dtype: torch.dtype) -> "Zonos3LM":
409
  """Weights in ``dtype``; the routers' balancing biases stay float32 (as in the checkpoint)."""
410
  for name, param in self.named_parameters():
@@ -602,7 +633,11 @@ class Zonos3LM(nn.Module):
602
  self._capture, self._accents = capture, accents
603
  try:
604
  embedders = self.multi_embedder.embedders
605
- x = sum(F.embedding(ids[:, cb], embedders[cb].weight) for cb in range(c.n_codebooks + 1))
 
 
 
 
606
  self._save("emb_sum", x)
607
  x = self._replace_rows(x, lo, speaker_rows, condition_rows)
608
  self._save("emb_cond", x)
 
14
  import json
15
  import math
16
  import re
17
+ from dataclasses import dataclass, field, replace
18
  from pathlib import Path
19
  from typing import NamedTuple
20
 
 
405
  model.root = root
406
  return model.cast(dtype)
407
 
408
+ def grow(self, grown: dict[str, torch.Tensor], *, span_end_id: int, text_extra_tokens: int) -> "Zonos3LM":
409
+ """This model with the vocabulary of a checkpoint grown from it (span-end audio id, extra text rows: an edit
410
+ checkpoint's ``tools grow_vocabulary``). ``grown`` holds that checkpoint's new rows: per audio embedder (0 ..
411
+ n_codebooks - 1) its span-end row, for the text embedder its extra rows, for ``multi_output`` the span-end row
412
+ of every codebook block, keyed like the checkpoint (``multi_embedder.embedders.<i>.weight`` [rows, dim],
413
+ ``multi_output.weight`` [n_codebooks, dim]). The existing rows keep their values, so a request that never reads
414
+ or samples the new ids runs exactly as before (the sampler masks every special id but the request's stop id)."""
415
+ c = self.config
416
+ if c.span_end_id is not None or c.text_extra_tokens:
417
+ raise ValueError("grow: the model already has a span-end id or extra text rows")
418
+ new = replace(c, span_end_id=int(span_end_id), text_extra_tokens=int(text_extra_tokens))
419
+ if new.audio_vocab != c.audio_vocab + 1 or new.span_end_id != c.codebook_size + 2:
420
+ raise ValueError("grow: the span-end id must be the one row after the audio pad id")
421
+ embedders = self.multi_embedder.embedders
422
+ for i in range(c.n_codebooks + 1):
423
+ key = f"multi_embedder.embedders.{i}.weight"
424
+ rows, width = (new.audio_vocab, c.audio_vocab) if i < c.n_codebooks else (new.text_rows, c.text_rows)
425
+ extra = grown[key].to(embedders[i].weight)
426
+ if tuple(extra.shape) != (rows - width, c.dim):
427
+ raise ValueError(f"grow: {key} new rows {tuple(extra.shape)} != {(rows - width, c.dim)}")
428
+ embedders[i].weight = nn.Parameter(torch.cat((embedders[i].weight, extra)), requires_grad=False)
429
+ head = self.multi_output.weight
430
+ extra = grown["multi_output.weight"].to(head)
431
+ if tuple(extra.shape) != (c.n_codebooks, c.dim):
432
+ raise ValueError(f"grow: multi_output.weight new rows {tuple(extra.shape)} != {(c.n_codebooks, c.dim)}")
433
+ blocks = head.view(c.n_codebooks, c.audio_vocab, c.dim)
434
+ self.multi_output.weight = nn.Parameter(torch.cat((blocks, extra[:, None]), 1).reshape(-1, c.dim),
435
+ requires_grad=False)
436
+ self.config = new
437
+ return self
438
+
439
  def cast(self, dtype: torch.dtype) -> "Zonos3LM":
440
  """Weights in ``dtype``; the routers' balancing biases stay float32 (as in the checkpoint)."""
441
  for name, param in self.named_parameters():
 
633
  self._capture, self._accents = capture, accents
634
  try:
635
  embedders = self.multi_embedder.embedders
636
+
637
+ def embed(cb):
638
+ rows = F.embedding(ids[:, cb], embedders[cb].weight)
639
+ return rows if accents is None else accents.embedding(cb, ids[:, cb], rows)
640
+ x = sum(embed(cb) for cb in range(c.n_codebooks + 1))
641
  self._save("emb_sum", x)
642
  x = self._replace_rows(x, lo, speaker_rows, condition_rows)
643
  self._save("emb_cond", x)
zonos3/reference/synth.py CHANGED
@@ -289,6 +289,39 @@ def plan_prompt(lm: Zonos3LM, request: dict, *, assets: ReferenceAssets, device=
289
  return P.plan_prompt(ctx, request, lambda req, mode: _resolve_speaker(lm, ctx, req, mode))
290
 
291
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292
  # ----------------------------------------------------------------------------------------------------- generation
293
 
294
 
 
289
  return P.plan_prompt(ctx, request, lambda req, mode: _resolve_speaker(lm, ctx, req, mode))
290
 
291
 
292
+ @dataclass
293
+ class EditLayout:
294
+ """A speech-edit region's prompt inputs (``zonos3.tts.plan.text_rows``): the window's codes, its spans and the fills
295
+ generated so far."""
296
+
297
+ codes: torch.Tensor
298
+ spans: list
299
+ fills: list
300
+
301
+
302
+ @torch.inference_mode()
303
+ def edit_region(lm: Zonos3LM, request: dict, *, assets: ReferenceAssets, layout: EditLayout, min_frames: int,
304
+ speaker_embedding: torch.Tensor | None = None, hidden_delta=None, accents: AccentState | None = None,
305
+ device=None) -> tuple[list[torch.Tensor], int | None]:
306
+ """One speech-edit region (``zonos3.tts.edit_runtime.FillJob``): ``request`` (text, language, normalization,
307
+ sampling, seed, max_tokens, condition buckets) planned over the edit layout behind the speaker row
308
+ (``speaker_embedding``, already steered) and generated until the span-end token, masked for ``min_frames`` rows;
309
+ ``hidden_delta``: the region's steering delta on its generated frames. Returns the generated rows and the aligned
310
+ span-end frame (None: the budget ran out)."""
311
+ c = lm.config
312
+ if c.span_end_id is None:
313
+ raise ValueError("Speech editing needs a checkpoint with a span-end audio token (span_end_id)")
314
+ device = torch.device(device if device is not None else lm.device)
315
+ ctx = ReferenceContext(lm, assets, device)
316
+ plan = P.plan_prompt(ctx, request, lambda req, mode: P.Speaker(mode, speaker_embedding, None),
317
+ hidden_delta=hidden_delta, edit=layout)
318
+ sampling = replace(Sampling.from_request(plan.request), min_frames=int(min_frames))
319
+ attempt = generate_rows(lm, plan.cond, sampling=sampling, seed=plan.seed, max_tokens=plan.max_tokens,
320
+ stop_id=c.span_end_id, twin=plan.twin, cfg_scale=plan.cfg_scale, accents=accents,
321
+ steer=steer_fn(plan, None))
322
+ return attempt.rows, attempt.eos_frame
323
+
324
+
325
  # ----------------------------------------------------------------------------------------------------- generation
326
 
327
 
zonos3/tts/edit_align.py CHANGED
@@ -32,7 +32,6 @@ from .align_text import align_tokens
32
  from .markup import _NONVERBAL_MARKUP, has_nonverbal_markup
33
  from . import textmatch
34
 
35
- REPO_ROOT = Path(__file__).resolve().parents[4]
36
  MODEL_SRC = Path(__file__).resolve().parents[2] # model/src: PYTHONPATH of both workers
37
  ASR_WORKER = MODEL_SRC / 'zonos3' / 'workers' / 'asr.py'
38
  FUSEALIGN_WORKER = MODEL_SRC / 'zonos3' / 'workers' / 'fusealign.py'
@@ -76,8 +75,9 @@ def fusealign_installed() -> bool:
76
 
77
 
78
  def asr_python() -> str:
79
- """The interpreter of the ASR worker and of the dubbing worker: ``ZONOS3_ASR_PYTHON``, else the repo's .venv-asr."""
80
- return os.environ.get('ZONOS3_ASR_PYTHON') or str(REPO_ROOT / '.venv-asr' / 'bin' / 'python')
 
81
 
82
 
83
  class _JsonLinesWorker:
 
32
  from .markup import _NONVERBAL_MARKUP, has_nonverbal_markup
33
  from . import textmatch
34
 
 
35
  MODEL_SRC = Path(__file__).resolve().parents[2] # model/src: PYTHONPATH of both workers
36
  ASR_WORKER = MODEL_SRC / 'zonos3' / 'workers' / 'asr.py'
37
  FUSEALIGN_WORKER = MODEL_SRC / 'zonos3' / 'workers' / 'fusealign.py'
 
75
 
76
 
77
  def asr_python() -> str:
78
+ """The interpreter of the ASR worker and of the dubbing worker: ``ZONOS3_ASR_PYTHON``, else the repo's .venv-asr
79
+ (the checkout's root, three levels above model/src; a package installed elsewhere has none)."""
80
+ return os.environ.get('ZONOS3_ASR_PYTHON') or str(MODEL_SRC.parents[1] / '.venv-asr' / 'bin' / 'python')
81
 
82
 
83
  class _JsonLinesWorker: