Spaces:
lolab
/
Paused

Gatozu35 commited on
Commit
eac6ec8
·
verified ·
1 Parent(s): 127a1e8

Deploy ZONOS3 d5c266c

Browse files
app.py CHANGED
@@ -107,7 +107,7 @@ from zonos3.tts.steering import (
107
  disabled_controls,
108
  resolve_controls,
109
  )
110
- from zonos3.utils.release import RELEASE_LM, resolve_dir_or_local, resolve_file
111
  from zonos3.workers import asr as asr_worker
112
  from zonos3.workers import fusealign as fusealign_worker
113
 
@@ -116,6 +116,10 @@ STUDIO = ROOT / "studio"
116
  # One device object everywhere: synthesize() moves the LM when lm.device != device, and ReferenceAssets caches the
117
  # decoder by str(device). On ZeroGPU this process only emulates CUDA; the GPU exists inside @spaces.GPU calls.
118
  DEVICE = torch.device("cuda:0")
 
 
 
 
119
  CPU = torch.device("cpu")
120
 
121
  # The edit LoRA (zonos-accent-lora/3) brings the vocabulary it was trained with: its span-end audio row and edit-marker
@@ -123,10 +127,10 @@ CPU = torch.device("cpu")
123
  # LoRA per request (EDIT_LORA). The phoneme tokens (zonos-text-extra/1, trained on the frozen release LM) follow the
124
  # edit marker rows: pronunciation groups (U+E000 IPA U+E001) read them, text without groups never does. Grown on the
125
  # CPU, then moved: ZeroGPU's emulated CUDA refuses mixing its tensors with CPU ones in this process.
126
- EDIT_ADAPTER = load_adapter(resolve_file(f"{RELEASE_LM}/edit_lora/z3m_omni3b_edit_lora.pt"))
127
- PHONEME_ROWS = TextExtraRows.load(resolve_file(f"{RELEASE_LM}/phoneme_tokens/phoneme_tokens_s15000.pt"))
128
  LM = (
129
- Zonos3LM.load(RELEASE_LM, device="cpu", dtype=torch.float32)
130
  .grow(EDIT_ADAPTER.grown)
131
  .append_text_rows(PHONEME_ROWS)
132
  .to(DEVICE)
@@ -136,7 +140,7 @@ ASSETS = ReferenceAssets.load(steer_bundle=str(ROOT / "steering" / "studio_bundl
136
  CONTEXT = ReferenceContext(LM, ASSETS, DEVICE) # the request rules' view of the checkpoint (no GPU work)
137
  EDIT_LORA = AccentState.for_model(LM, EDIT_ADAPTER, 1.0)
138
  # The gold pronunciation lexicon behind "Phonemize selection"; espeak-ng (espeakng-loader) guesses the words it lacks.
139
- _LEXICON = "hf://Zyphra/ZONOS3_Mini_release_ckpts/lexicons/gold_phonemes_v1"
140
  resolve_file(f"{_LEXICON}/manifest.json")
141
  LEXICON = PhonemeLexicon(str(Path(resolve_file(f"{_LEXICON}/data.mdb")).parent))
142
  ASSETS.decoder(CONFIG.audio_codec, DEVICE)
@@ -178,7 +182,7 @@ def capabilities() -> dict:
178
  prefix_stream=prefix_stream_supported(c.audio_codec),
179
  silence_hop=dual_codec_hop(c.audio_codec),
180
  tag_cfg_available=True,
181
- tag_cfg_trained=trained_on_tags(resolve_dir_or_local(RELEASE_LM)),
182
  decoder=decoder_capability(c.audio_codec),
183
  condition_tokens=None
184
  if c.condition_count == 0
 
107
  disabled_controls,
108
  resolve_controls,
109
  )
110
+ from zonos3.utils.release import resolve_dir_or_local, resolve_file
111
  from zonos3.workers import asr as asr_worker
112
  from zonos3.workers import fusealign as fusealign_worker
113
 
 
116
  # One device object everywhere: synthesize() moves the LM when lm.device != device, and ReferenceAssets caches the
117
  # decoder by str(device). On ZeroGPU this process only emulates CUDA; the GPU exists inside @spaces.GPU calls.
118
  DEVICE = torch.device("cuda:0")
119
+ # The Space serves speech editing and pronunciation groups, whose edit LoRA, phoneme tokens and lexicon are only in the
120
+ # private release repo (the public Zyphra/ZONOS3-Mini has the plain LM): it keeps loading from there (HF_TOKEN secret).
121
+ SPACE_RELEASE_REPO = "Zyphra/ZONOS3_Mini_release_ckpts"
122
+ SPACE_LM = f"hf://{SPACE_RELEASE_REPO}/lm/rate30_20k_r2grpo"
123
  CPU = torch.device("cpu")
124
 
125
  # The edit LoRA (zonos-accent-lora/3) brings the vocabulary it was trained with: its span-end audio row and edit-marker
 
127
  # LoRA per request (EDIT_LORA). The phoneme tokens (zonos-text-extra/1, trained on the frozen release LM) follow the
128
  # edit marker rows: pronunciation groups (U+E000 IPA U+E001) read them, text without groups never does. Grown on the
129
  # CPU, then moved: ZeroGPU's emulated CUDA refuses mixing its tensors with CPU ones in this process.
130
+ EDIT_ADAPTER = load_adapter(resolve_file(f"{SPACE_LM}/edit_lora/z3m_omni3b_edit_lora.pt"))
131
+ PHONEME_ROWS = TextExtraRows.load(resolve_file(f"{SPACE_LM}/phoneme_tokens/phoneme_tokens_s15000.pt"))
132
  LM = (
133
+ Zonos3LM.load(SPACE_LM, device="cpu", dtype=torch.float32)
134
  .grow(EDIT_ADAPTER.grown)
135
  .append_text_rows(PHONEME_ROWS)
136
  .to(DEVICE)
 
140
  CONTEXT = ReferenceContext(LM, ASSETS, DEVICE) # the request rules' view of the checkpoint (no GPU work)
141
  EDIT_LORA = AccentState.for_model(LM, EDIT_ADAPTER, 1.0)
142
  # The gold pronunciation lexicon behind "Phonemize selection"; espeak-ng (espeakng-loader) guesses the words it lacks.
143
+ _LEXICON = f"hf://{SPACE_RELEASE_REPO}/lexicons/gold_phonemes_v1"
144
  resolve_file(f"{_LEXICON}/manifest.json")
145
  LEXICON = PhonemeLexicon(str(Path(resolve_file(f"{_LEXICON}/data.mdb")).parent))
146
  ASSETS.decoder(CONFIG.audio_codec, DEVICE)
 
182
  prefix_stream=prefix_stream_supported(c.audio_codec),
183
  silence_hop=dual_codec_hop(c.audio_codec),
184
  tag_cfg_available=True,
185
+ tag_cfg_trained=trained_on_tags(resolve_dir_or_local(SPACE_LM)),
186
  decoder=decoder_capability(c.audio_codec),
187
  condition_tokens=None
188
  if c.condition_count == 0
steering/studio_bundle_mect60k_x10.json CHANGED
@@ -1979,7 +1979,6 @@
1979
  "preview_text": "Hello there. It's lovely to finally meet you, how have you been?",
1980
  "request_defaults": {
1981
  "speaker_mode": "embedding",
1982
- "speaker_cfg_scale": 1.5,
1983
  "stream_decode": "prefix"
1984
  },
1985
  "identity_threshold": 0.8
 
1979
  "preview_text": "Hello there. It's lovely to finally meet you, how have you been?",
1980
  "request_defaults": {
1981
  "speaker_mode": "embedding",
 
1982
  "stream_decode": "prefix"
1983
  },
1984
  "identity_threshold": 0.8
studio/assets/studio-BMJfx_9-.js DELETED
The diff for this file is too large to render. See raw diff
 
studio/assets/studio-CUnPlHU1.js ADDED
The diff for this file is too large to render. See raw diff
 
studio/studio.html CHANGED
@@ -10,7 +10,7 @@
10
  <link rel="manifest" href="/manifest.webmanifest" />
11
  <meta name="theme-color" content="#0a0a0a" />
12
  <script src="/theme-boot.js"></script>
13
- <script type="module" crossorigin src="/assets/studio-BMJfx_9-.js"></script>
14
  <link rel="modulepreload" crossorigin href="/assets/web-engine-DLmQsyPj.js">
15
  <link rel="modulepreload" crossorigin href="/assets/latin-500-DPgjq1zP.js">
16
  <link rel="stylesheet" crossorigin href="/assets/web-engine-xKv10YAh.css">
 
10
  <link rel="manifest" href="/manifest.webmanifest" />
11
  <meta name="theme-color" content="#0a0a0a" />
12
  <script src="/theme-boot.js"></script>
13
+ <script type="module" crossorigin src="/assets/studio-CUnPlHU1.js"></script>
14
  <link rel="modulepreload" crossorigin href="/assets/web-engine-DLmQsyPj.js">
15
  <link rel="modulepreload" crossorigin href="/assets/latin-500-DPgjq1zP.js">
16
  <link rel="stylesheet" crossorigin href="/assets/web-engine-xKv10YAh.css">
studio/sw.js CHANGED
@@ -14,7 +14,7 @@
14
  // cache under it). clients.claim on activate only takes over pages nothing controls yet (the first visit), which then
15
  // read this version's cache; a cache miss still falls back to the network.
16
 
17
- const VERSION = "ff661923b5c4";
18
  const PRECACHE = [
19
  "/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2",
20
  "/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2",
@@ -29,7 +29,7 @@ const PRECACHE = [
29
  "/assets/jetbrains-mono-latin-500-normal-CJOVTJB7.woff",
30
  "/assets/latin-500-DKfSw4PI.css",
31
  "/assets/latin-500-DPgjq1zP.js",
32
- "/assets/studio-BMJfx_9-.js",
33
  "/assets/studio-Cxzv5JLi.css",
34
  "/assets/web-engine-DLmQsyPj.js",
35
  "/assets/web-engine-xKv10YAh.css",
 
14
  // cache under it). clients.claim on activate only takes over pages nothing controls yet (the first visit), which then
15
  // read this version's cache; a cache miss still falls back to the network.
16
 
17
+ const VERSION = "a8c24f17068f";
18
  const PRECACHE = [
19
  "/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2",
20
  "/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2",
 
29
  "/assets/jetbrains-mono-latin-500-normal-CJOVTJB7.woff",
30
  "/assets/latin-500-DKfSw4PI.css",
31
  "/assets/latin-500-DPgjq1zP.js",
32
+ "/assets/studio-CUnPlHU1.js",
33
  "/assets/studio-Cxzv5JLi.css",
34
  "/assets/web-engine-DLmQsyPj.js",
35
  "/assets/web-engine-xKv10YAh.css",
zonos3/codec/istft_head_a_20261002/stream.py CHANGED
@@ -2,9 +2,11 @@
2
 
3
  `ISTFTStream.decode(codes)` takes the next undelayed code frames and returns the 44100 Hz samples that are final;
4
  `flush()` returns the rest. The causal trunk keeps its state between calls: one depthwise-conv history per ConvNeXt
5
- block (semantic head and iSTFT head) and a sliding-window KV cache per transformer layer. The host half (overlap-add
6
- iSTFT, FIR mixer, resampler) is `zonos3.codec.stream_host`. Concatenated outputs + flush equal `model(codes)` over the
7
- whole sequence: after F frames exactly 2940*F - 1470 samples are out, flush brings the total to 2940*F.
 
 
8
  """
9
 
10
  import copy
@@ -17,7 +19,7 @@ from torch.nn import functional as F
17
  from zonos3.codec.hybrid10_dual_encoding.base_model import MossStage, Patch
18
  from zonos3.codec.hybrid10_dual_encoding.model import SemanticConvNeXt
19
  from zonos3.codec.istft_head_a_20261002.model import ISTFTCodec, MultiResISTFTHead
20
- from zonos3.codec.stream_host import IstftHeadStream, ResamplerStream
21
 
22
  _CODEBOOK_SIZE = 4096
23
 
@@ -172,15 +174,15 @@ class ISTFTStream:
172
  elif isinstance(stage, MossStage):
173
  keep = max(layer.context for layer in stage.layers) - 1
174
  self.full_frames = max(self.full_frames, -(-keep // cpf))
175
- windows = [getattr(head, f"window_{i}").detach().cpu().numpy() for i in range(len(head.n_ffts))]
 
176
  self.head = IstftHeadStream(
177
- head.n_ffts, head.hop, windows, head.mixer.weight[0].detach().cpu().numpy(), head.max_log_magnitude
178
  )
179
  rs = model.to_external
180
  self.resampler = ResamplerStream(
181
- rs.kernel[:, 0].detach().cpu().numpy(), rs.orig_freq // rs.gcd, rs.new_freq // rs.gcd, rs.width
182
  )
183
- self.device = next(model.parameters()).device
184
  self.graphs = graphs if self.device.type == "cuda" else None
185
 
186
  def decode(self, codes: np.ndarray) -> np.ndarray:
@@ -208,15 +210,17 @@ class ISTFTStream:
208
  return np.concatenate(out)
209
 
210
  def flush(self) -> np.ndarray:
211
- return np.concatenate([self.resampler.push(self.head.flush()), self.resampler.flush()])
 
 
212
 
213
  def fork(self) -> "ISTFTStream":
214
  """An independent stream continuing from this one's state. The trunk state tensors are never written in place
215
- (every chunk makes new ones), so the twins share them; the host overlap-add and resampler state is copied."""
216
  twin = copy.copy(self)
217
  twin.sem_hist, twin.head_hist = list(self.sem_hist), list(self.head_hist)
218
  twin.kv = [None if layers is None else list(layers) for layers in self.kv]
219
- twin.head, twin.resampler = copy.deepcopy(self.head), copy.deepcopy(self.resampler)
220
  return twin
221
 
222
  def _chunk(self, codes):
@@ -229,11 +233,10 @@ class ISTFTStream:
229
  else:
230
  frames = torch.full((), self.frames, dtype=torch.int64, device=self.device)
231
  ys, state = self._trunk(packed.to(self.device), frames, *state)
232
- ys = [y.cpu().numpy() for y in ys]
233
  self.sem_hist, self.kv, self.head_hist = state
234
- out = self.resampler.push(self.head.push(*ys))
235
  self.frames += n
236
- return out
237
 
238
  def _trunk(self, packed, frames, sem_hist, kv, head_hist):
239
  """The GPU half of a chunk, free of side effects (CUDA-graph capturable): codes [1, codebooks, n] int64, the
 
2
 
3
  `ISTFTStream.decode(codes)` takes the next undelayed code frames and returns the 44100 Hz samples that are final;
4
  `flush()` returns the rest. The causal trunk keeps its state between calls: one depthwise-conv history per ConvNeXt
5
+ block (semantic head and iSTFT head) and a sliding-window KV cache per transformer layer. The rest (overlap-add iSTFT,
6
+ FIR mixer, resampler) runs on the same device, `zonos3.codec.stream_device` (the torch twins of the NumPy ports in
7
+ `zonos3.codec.stream_host`), so a chunk's only host copy is its final samples. Concatenated outputs + flush equal
8
+ `model(codes)` over the whole sequence: after F frames exactly 2940*F - 1470 samples are out, flush brings the total
9
+ to 2940*F.
10
  """
11
 
12
  import copy
 
19
  from zonos3.codec.hybrid10_dual_encoding.base_model import MossStage, Patch
20
  from zonos3.codec.hybrid10_dual_encoding.model import SemanticConvNeXt
21
  from zonos3.codec.istft_head_a_20261002.model import ISTFTCodec, MultiResISTFTHead
22
+ from zonos3.codec.stream_device import IstftHeadStream, ResamplerStream
23
 
24
  _CODEBOOK_SIZE = 4096
25
 
 
174
  elif isinstance(stage, MossStage):
175
  keep = max(layer.context for layer in stage.layers) - 1
176
  self.full_frames = max(self.full_frames, -(-keep // cpf))
177
+ self.device = next(model.parameters()).device
178
+ windows = [getattr(head, f"window_{i}").detach() for i in range(len(head.n_ffts))]
179
  self.head = IstftHeadStream(
180
+ head.n_ffts, head.hop, windows, head.mixer.weight[0].detach(), head.max_log_magnitude, self.device
181
  )
182
  rs = model.to_external
183
  self.resampler = ResamplerStream(
184
+ rs.kernel[:, 0].detach(), rs.orig_freq // rs.gcd, rs.new_freq // rs.gcd, rs.width, self.device
185
  )
 
186
  self.graphs = graphs if self.device.type == "cuda" else None
187
 
188
  def decode(self, codes: np.ndarray) -> np.ndarray:
 
210
  return np.concatenate(out)
211
 
212
  def flush(self) -> np.ndarray:
213
+ with torch.inference_mode():
214
+ out = torch.cat([self.resampler.push(self.head.flush()), self.resampler.flush()])
215
+ return out.cpu().numpy()
216
 
217
  def fork(self) -> "ISTFTStream":
218
  """An independent stream continuing from this one's state. The trunk state tensors are never written in place
219
+ (every chunk makes new ones), so the twins share them; the head's overlap-add buffers are copied."""
220
  twin = copy.copy(self)
221
  twin.sem_hist, twin.head_hist = list(self.sem_hist), list(self.head_hist)
222
  twin.kv = [None if layers is None else list(layers) for layers in self.kv]
223
+ twin.head, twin.resampler = self.head.copy(), self.resampler.copy()
224
  return twin
225
 
226
  def _chunk(self, codes):
 
233
  else:
234
  frames = torch.full((), self.frames, dtype=torch.int64, device=self.device)
235
  ys, state = self._trunk(packed.to(self.device), frames, *state)
 
236
  self.sem_hist, self.kv, self.head_hist = state
237
+ out = self.resampler.push(self.head.push(*ys)) # before the next replay overwrites a graph's static ys
238
  self.frames += n
239
+ return out.cpu().numpy()
240
 
241
  def _trunk(self, packed, frames, sem_hist, kv, head_hist):
242
  """The GPU half of a chunk, free of side effects (CUDA-graph capturable): codes [1, codebooks, n] int64, the
zonos3/codec/stream_device.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Streaming iSTFT head + resampler on the codec's device: the torch twins of `zonos3.codec.stream_host`.
2
+
3
+ Same algorithm and float64 arithmetic as the NumPy ports (overlap-add iSTFT of the two head branches, the FIR mixer,
4
+ the 44160 -> 44100 Hz sinc resampler), on the tensors the trunk leaves on its device, so a chunk needs no host round
5
+ trip before its final samples. Positions and lengths are host integers (they follow from the frame counts), so the
6
+ only device sync is the caller's copy of the output. Outputs are float32 like the NumPy ports' (the head's output is
7
+ rounded to float32 before the resampler, as there); the overlap-add sums in another order, so the samples match the
8
+ NumPy path to float32 rounding, not bit for bit.
9
+ """
10
+
11
+ import torch
12
+ from torch.nn import functional as F
13
+
14
+
15
+ class IstftHeadStream:
16
+ """Two-branch centered iSTFT (shared hop) followed by the linear FIR mixer, fed head frames incrementally."""
17
+
18
+ def __init__(self, n_ffts, hop, windows, mixer, max_log_mag, device):
19
+ self.n_ffts = [int(n) for n in n_ffts]
20
+ self.hop = int(hop)
21
+ self.device = torch.device(device)
22
+ f64 = dict(dtype=torch.float64, device=self.device)
23
+ self.windows = [torch.as_tensor(w).to(**f64) for w in windows]
24
+ self.mixer = torch.as_tensor(mixer).to(**f64)
25
+ if self.mixer.ndim != 2 or self.mixer.shape[0] != 2 or self.mixer.shape[1] % 2 != 1:
26
+ raise ValueError("istft: mixer kernel must be odd")
27
+ for n, w in zip(self.n_ffts, self.windows):
28
+ if len(w) != n or n % self.hop:
29
+ raise ValueError(f"istft: window of {len(w)} taps for n_fft {n}, hop {self.hop}")
30
+ self.max_log_mag = float(max_log_mag)
31
+ self.K = self.mixer.shape[1]
32
+ self.h = (self.K - 1) // 2
33
+ self._f64 = f64
34
+ self.ola = [torch.zeros(0, **f64), torch.zeros(0, **f64)]
35
+ self.env = [torch.zeros(0, **f64), torch.zeros(0, **f64)]
36
+ self.ola_base = [0, 0]
37
+ self.mix_in = [torch.zeros(self.h, **f64), torch.zeros(self.h, **f64)] # index 0 sits at absolute mix_base
38
+ self.mix_base = self.mix_next = 0
39
+ self.frames = 0
40
+ self.done = False
41
+ self._env: dict[tuple[int, int], torch.Tensor] = {} # (branch, cols) -> overlap-added squared window
42
+
43
+ def copy(self) -> "IstftHeadStream":
44
+ """An independent twin (the overlap-add buffers are updated in place; everything else is replaced)."""
45
+ twin = object.__new__(IstftHeadStream)
46
+ twin.__dict__.update(self.__dict__)
47
+ twin.ola, twin.env = [t.clone() for t in self.ola], [t.clone() for t in self.env]
48
+ twin.ola_base, twin.mix_in = list(self.ola_base), list(self.mix_in)
49
+ return twin
50
+
51
+ def _overlap_add(self, frames: torch.Tensor, n: int) -> torch.Tensor:
52
+ """Frames [cols, n] placed every hop samples and summed -> [(cols - 1) * hop + n]."""
53
+ cols = frames.shape[0]
54
+ span = (cols - 1) * self.hop + n
55
+ return F.fold(
56
+ frames.T.unsqueeze(0), output_size=(1, span), kernel_size=(1, n), stride=(1, self.hop)
57
+ ).reshape(span)
58
+
59
+ def push(self, y0: torch.Tensor, y1: torch.Tensor) -> torch.Tensor:
60
+ """y_i [cols, n_i + 2]: log-magnitude for n_i//2+1 bins, then phase. Returns the 44160 Hz samples now final."""
61
+ if self.done:
62
+ raise RuntimeError("istft: push after flush")
63
+ cols = None
64
+ for i, y in enumerate((y0, y1)):
65
+ n = self.n_ffts[i]
66
+ bins = n // 2 + 1
67
+ y = y.to(**self._f64)
68
+ if y.ndim != 2 or y.shape[1] != n + 2 or (cols is not None and y.shape[0] != cols):
69
+ raise ValueError(f"istft: branch {i} has shape {tuple(y.shape)}, expected [cols, {n + 2}]")
70
+ cols = y.shape[0]
71
+ if cols == 0:
72
+ return torch.zeros(0, dtype=torch.float32, device=self.device)
73
+ mag = torch.exp(torch.clamp(y[:, :bins], max=self.max_log_mag))
74
+ ph = y[:, bins:]
75
+ imag = mag * torch.sin(ph)
76
+ imag[:, 0] = 0.0
77
+ imag[:, -1] = 0.0
78
+ win = self.windows[i]
79
+ frames = torch.fft.irfft(torch.complex(mag * torch.cos(ph), imag), n, dim=-1) * win
80
+ add = self._overlap_add(frames, n)
81
+ env = self._env.get((i, cols))
82
+ if env is None:
83
+ env = self._env[(i, cols)] = self._overlap_add((win * win).expand(cols, n), n)
84
+ span = add.shape[0]
85
+ o = self.frames * self.hop - self.ola_base[i]
86
+ need = o + span
87
+ if self.ola[i].shape[0] < need:
88
+ grow = torch.zeros(need - self.ola[i].shape[0], **self._f64)
89
+ self.ola[i] = torch.cat([self.ola[i], grow])
90
+ self.env[i] = torch.cat([self.env[i], grow])
91
+ self.ola[i][o:need] += add
92
+ self.env[i][o:need] += env
93
+ self.frames += cols
94
+ for i in range(2):
95
+ self._finalize(i, self.frames * self.hop)
96
+ return self._mix_emit()
97
+
98
+ def flush(self) -> torch.Tensor:
99
+ """End of stream: every sample m < frames*hop is final; the mixer sees h zeros after the last sample."""
100
+ if self.done or self.frames == 0:
101
+ return torch.zeros(0, dtype=torch.float32, device=self.device)
102
+ self.done = True
103
+ L = self.frames * self.hop
104
+ for i in range(2):
105
+ self._finalize(i, self.ola_base[i] + self.ola[i].shape[0])
106
+ keep = self.h + L - self.mix_base
107
+ m = self.mix_in[i]
108
+ m = m[:keep] if m.shape[0] >= keep else torch.cat([m, torch.zeros(keep - m.shape[0], **self._f64)])
109
+ self.mix_in[i] = torch.cat([m, torch.zeros(self.h, **self._f64)])
110
+ return self._mix_emit()
111
+
112
+ def _finalize(self, i, pf):
113
+ """Moves overlap-add positions [ola_base, pf) of branch i into the mixer input, dropping the centre padding."""
114
+ n = pf - self.ola_base[i]
115
+ if n <= 0:
116
+ return
117
+ skip = min(n, max(0, self.n_ffts[i] // 2 - self.ola_base[i]))
118
+ self.mix_in[i] = torch.cat([self.mix_in[i], self.ola[i][skip:n] / self.env[i][skip:n]])
119
+ self.ola[i] = self.ola[i][n:]
120
+ self.env[i] = self.env[i][n:]
121
+ self.ola_base[i] = pf
122
+
123
+ def _mix_emit(self) -> torch.Tensor:
124
+ """y[m] = sum_c sum_k mixer[c][k] * mix_in_c[m + k] for every m whose taps are available."""
125
+ K = self.K
126
+ m1 = min(m.shape[0] for m in self.mix_in) + self.mix_base - K + 1
127
+ if m1 <= self.mix_next:
128
+ return torch.zeros(0, dtype=torch.float32, device=self.device)
129
+ take = m1 - self.mix_base + K - 1
130
+ x = torch.stack([m[:take] for m in self.mix_in]).unsqueeze(0) # [1, 2, take]
131
+ y = F.conv1d(x, self.mixer.unsqueeze(0)).reshape(-1) # cross-correlation summed over both channels
132
+ drop = m1 - self.mix_base
133
+ self.mix_in = [m[drop:] for m in self.mix_in]
134
+ self.mix_base = self.mix_next = m1
135
+ return y.to(torch.float32)
136
+
137
+
138
+ class ResamplerStream:
139
+ """Streaming torchaudio sinc resampler: out[n*new + i] = sum_k kernel[i][k] * x[n*orig + k - width]."""
140
+
141
+ def __init__(self, kernel, orig, new, width, device):
142
+ self.orig, self.new, self.width = int(orig), int(new), int(width)
143
+ self.kl = 2 * self.width + self.orig
144
+ self.device = torch.device(device)
145
+ self._f64 = dict(dtype=torch.float64, device=self.device)
146
+ self.kernel = torch.as_tensor(kernel).to(**self._f64)
147
+ if tuple(self.kernel.shape) != (self.new, self.kl):
148
+ raise ValueError(f"resampler: kernel shape {tuple(self.kernel.shape)}, expected {(self.new, self.kl)}")
149
+ self._weight = self.kernel.unsqueeze(1) # [new, 1, kl]
150
+ self.buf = torch.zeros(0, **self._f64)
151
+ self.base = 0 # absolute index of buf[0]
152
+ self.n_in = 0 # samples pushed
153
+ self.next_block = 0
154
+
155
+ def copy(self) -> "ResamplerStream":
156
+ """An independent twin (the buffer is only ever replaced, never written in place)."""
157
+ twin = object.__new__(ResamplerStream)
158
+ twin.__dict__.update(self.__dict__)
159
+ return twin
160
+
161
+ def push(self, x: torch.Tensor) -> torch.Tensor:
162
+ x = x.to(**self._f64).reshape(-1)
163
+ self.buf = torch.cat([self.buf, x])
164
+ self.n_in += x.shape[0]
165
+ return self._run(False)
166
+
167
+ def flush(self) -> torch.Tensor:
168
+ return self._run(True)
169
+
170
+ def _run(self, flush):
171
+ O, N, W, KL = self.orig, self.new, self.width, self.kl
172
+ if flush:
173
+ total = -(-N * self.n_in // O)
174
+ end = -(-total // N)
175
+ else:
176
+ reach = self.n_in + W - KL
177
+ end = reach // O + 1 if reach >= 0 else 0
178
+ out = torch.zeros(0, dtype=torch.float32, device=self.device)
179
+ if end > self.next_block:
180
+ lo = self.next_block * O - W
181
+ hi = (end - 1) * O - W + KL
182
+ a, b = max(lo, 0), min(hi, self.n_in)
183
+ if b > a:
184
+ seg = F.pad(self.buf[a - self.base : b - self.base], (a - lo, hi - b))
185
+ else:
186
+ seg = torch.zeros(hi - lo, **self._f64)
187
+ # windows of KL samples every O samples, each dotted with the N kernel rows: [N, blocks] -> block-major
188
+ y = F.conv1d(seg.view(1, 1, -1), self._weight, stride=O)[0].T.reshape(-1)
189
+ if flush:
190
+ y = y[: total - self.next_block * N]
191
+ out = y.to(torch.float32)
192
+ self.next_block = end
193
+ keep_from = min(self.n_in, max(0, self.next_block * O - W))
194
+ if keep_from > self.base:
195
+ self.buf = self.buf[keep_from - self.base :]
196
+ self.base = keep_from
197
+ return out
zonos3/generation.py CHANGED
@@ -30,4 +30,6 @@ EDIT_MAX_SECONDS: float = float(_data["audio_max_seconds"]["edit"])
30
  # prefix streams: decode a frame once its first STREAM_CODEBOOKS codebooks arrived, for the "first" chunk or "all"
31
  STREAM_CODEBOOKS: int = int(_data["stream_codebooks"]["default"])
32
  STREAM_CODEBOOKS_SCOPE: str = str(_data["stream_codebooks"]["scope"])
 
 
33
  del _data
 
30
  # prefix streams: decode a frame once its first STREAM_CODEBOOKS codebooks arrived, for the "first" chunk or "all"
31
  STREAM_CODEBOOKS: int = int(_data["stream_codebooks"]["default"])
32
  STREAM_CODEBOOKS_SCOPE: str = str(_data["stream_codebooks"]["scope"])
33
+ # the soft limiter's knee after the decoder's output gain (zonos3.tts.audio.output_pcm)
34
+ OUTPUT_LIMIT_DBFS: float = float(_data["output_limit_dbfs"])
35
  del _data
zonos3/reference/synth.py CHANGED
@@ -29,6 +29,7 @@ from zonos3.reference.lm import LMCache, ProbeSpec, Zonos3LM
29
  from zonos3.speaker_cfg import guided_logits
30
  from zonos3.tokenizer.textnorm import load_normalizer, normalize_request_text
31
  from zonos3.tts import plan as P
 
32
  from zonos3.tts.delay import apply_cold_start_delay
33
  from zonos3.tts.laci import LaciConfig, LaciHeads, LaciSession, RateBuckets
34
  from zonos3.tts.probe import locate_text_span
@@ -622,7 +623,8 @@ def decode_rows(
622
 
623
 
624
  class _Emit:
625
- """Streamed PCM out: gained, the last ``fade_out_ms`` held back and faded at the end of the take."""
 
626
 
627
  def __init__(self, on_audio, gain: float, fade_out_ms: float):
628
  self.on_audio, self.gain, self.fade_out_ms = on_audio, np.float32(gain), fade_out_ms
@@ -631,7 +633,7 @@ class _Emit:
631
  self.parts: list[np.ndarray] = []
632
 
633
  def __call__(self, chunk: np.ndarray, last: bool) -> None:
634
- data = np.concatenate((self.held, chunk * self.gain)).astype(np.float32)
635
  if last:
636
  data, self.held = fade_out(data, self.fade_out_ms), data[:0]
637
  elif self.hold:
@@ -794,7 +796,7 @@ def synthesize(
794
  context_codes=plan.context_codes,
795
  device=device,
796
  )
797
- pcm = fade_out(pcm * np.float32(gain), float(req.fade_out_ms)).astype(np.float32)
798
  if on_audio is not None:
799
  on_audio(pcm)
800
  return SynthResult(pcm, plan.seed, record, rows, eos_frame, plan)
 
29
  from zonos3.speaker_cfg import guided_logits
30
  from zonos3.tokenizer.textnorm import load_normalizer, normalize_request_text
31
  from zonos3.tts import plan as P
32
+ from zonos3.tts.audio import output_pcm
33
  from zonos3.tts.delay import apply_cold_start_delay
34
  from zonos3.tts.laci import LaciConfig, LaciHeads, LaciSession, RateBuckets
35
  from zonos3.tts.probe import locate_text_span
 
623
 
624
 
625
  class _Emit:
626
+ """Streamed PCM out: through the output stage (gain + soft limiter), the last ``fade_out_ms`` held back and faded at
627
+ the end of the take."""
628
 
629
  def __init__(self, on_audio, gain: float, fade_out_ms: float):
630
  self.on_audio, self.gain, self.fade_out_ms = on_audio, np.float32(gain), fade_out_ms
 
633
  self.parts: list[np.ndarray] = []
634
 
635
  def __call__(self, chunk: np.ndarray, last: bool) -> None:
636
+ data = np.concatenate((self.held, output_pcm(chunk, float(self.gain)))).astype(np.float32)
637
  if last:
638
  data, self.held = fade_out(data, self.fade_out_ms), data[:0]
639
  elif self.hold:
 
796
  context_codes=plan.context_codes,
797
  device=device,
798
  )
799
+ pcm = fade_out(output_pcm(pcm, gain), float(req.fade_out_ms)).astype(np.float32)
800
  if on_audio is not None:
801
  on_audio(pcm)
802
  return SynthResult(pcm, plan.seed, record, rows, eos_frame, plan)
zonos3/registries/codec_registry_keep2_plain.json CHANGED
@@ -8,9 +8,9 @@
8
  "frame_rate": 15.0,
9
  "max_tokens": 450,
10
  "codec_step": 600000,
11
- "checkpoint": "hf://Zyphra/ZONOS3_Mini_release_ckpts/autoencoder/generator.pt",
12
- "checkpoint_sha256": "1cedeb12d7d964026c0a16afc32abd1de23dc484533111f24c950775f1941172",
13
- "teacher": "hf://Zyphra/ZONOS3_Mini_release_ckpts/autoencoder/teacher",
14
  "tag": "3n_600k_sched600k_r4096_attnres_800m50k",
15
  "codebook_sizes": [
16
  4096,
@@ -39,7 +39,7 @@
39
  "decoder": {
40
  "kind": "istft_mr",
41
  "label": "Multi-resolution iSTFT head + linear STFT loss, KEEP-2 pruned decoder (istft_head_a_20261002/full-unfreezeall-mr-drop30-4x10-50k, job 73313, final step 50,000: decoder.0 keeps layers 0+31, decoder.2/4/6/8 keep 0+11, cold-crop recipe; release copy = step + trainable state); causal, fp32",
42
- "campaign": "hf://Zyphra/ZONOS3_Mini_release_ckpts/autoencoder/heads/keep2_plain",
43
  "config": "config_full_unfreezeall_mr_drop30_4x10.json",
44
  "checkpoint": "step_0050000.pt",
45
  "expect_step": 50000,
 
8
  "frame_rate": 15.0,
9
  "max_tokens": 450,
10
  "codec_step": 600000,
11
+ "checkpoint": "hf://Zyphra/ZONOS3-Mini/autoencoder/generator.pt",
12
+ "checkpoint_sha256": "75a587a3eda9ca3d345f0c305756a7ff8619b01685c261b08ae243c69c2caf9a",
13
+ "teacher": "hf://Zyphra/ZONOS3-Mini/autoencoder/teacher",
14
  "tag": "3n_600k_sched600k_r4096_attnres_800m50k",
15
  "codebook_sizes": [
16
  4096,
 
39
  "decoder": {
40
  "kind": "istft_mr",
41
  "label": "Multi-resolution iSTFT head + linear STFT loss, KEEP-2 pruned decoder (istft_head_a_20261002/full-unfreezeall-mr-drop30-4x10-50k, job 73313, final step 50,000: decoder.0 keeps layers 0+31, decoder.2/4/6/8 keep 0+11, cold-crop recipe; release copy = step + trainable state); causal, fp32",
42
+ "campaign": "hf://Zyphra/ZONOS3-Mini/autoencoder/heads/keep2_plain",
43
  "config": "config_full_unfreezeall_mr_drop30_4x10.json",
44
  "checkpoint": "step_0050000.pt",
45
  "expect_step": 50000,
zonos3/registries/generation.json CHANGED
@@ -1,10 +1,10 @@
1
  {
2
- "description": "Request defaults and limits of every server and the studio (zonos3.generation). sample_rate: the API's audio rate (Hz). sampling: the v2 sampling defaults (servers/api/openapi.yaml repeats them; model/tests/test_generation.py keeps the two equal). tag_cfg_scale: the tag-CFG scale range. silence_prefill_frames: the server default length (ZONOS3_SILENCE_PREFILL_FRAMES overrides it) and the longest a request may ask for. decode_context_frames: the reference tail decoded ahead of the stream when a request leaves decode_context_frames unset or 0. reference_max_frames: the reference prefix of the GGUF servers (60 s at the dual codec's 2940-sample hop; longer reference codes keep their first frames). max_frames: the GGUF servers' default frame budget (--max). audio_max_seconds: the longest reference clip, upload and speech-edit clip. stream_codebooks: the prefix stream's early partial-frame decode defaults (request fields stream_codebooks / stream_codebooks_scope): a frame is decoded once its first `default` codebooks arrived, for the `scope` chunks (first: the first chunk only; all: every chunk); default = n_codebooks decodes complete frames only.",
3
  "sample_rate": 44100,
4
  "sampling": {
5
- "temperature": 1.0,
6
- "topk": 100,
7
- "top_p": 1.0,
8
  "min_p": 0.0,
9
  "repetition_penalty": 2.4,
10
  "repetition_window": 96,
@@ -16,5 +16,6 @@
16
  "reference_max_frames": 900,
17
  "max_frames": 2000,
18
  "audio_max_seconds": {"reference": 60, "upload": 600, "edit": 150},
19
- "stream_codebooks": {"default": 1, "scope": "first"}
 
20
  }
 
1
  {
2
+ "description": "Request defaults and limits of every server and the studio (zonos3.generation). sample_rate: the API's audio rate (Hz). sampling: the v2 sampling defaults (servers/api/openapi.yaml repeats them; model/tests/test_generation.py keeps the two equal). tag_cfg_scale: the tag-CFG scale range. silence_prefill_frames: the server default length (ZONOS3_SILENCE_PREFILL_FRAMES overrides it) and the longest a request may ask for. decode_context_frames: the reference tail decoded ahead of the stream when a request leaves decode_context_frames unset or 0. reference_max_frames: the reference prefix of the GGUF servers (60 s at the dual codec's 2940-sample hop; longer reference codes keep their first frames). max_frames: the GGUF servers' default frame budget (--max). audio_max_seconds: the longest reference clip, upload and speech-edit clip. stream_codebooks: the prefix stream's early partial-frame decode defaults (request fields stream_codebooks / stream_codebooks_scope): a frame is decoded once its first `default` codebooks arrived, for the `scope` chunks (first: the first chunk only; all: every chunk); default = n_codebooks decodes complete frames only. output_limit_dbfs: the knee k of the soft limiter every server applies after the decoder's output gain: samples at or below it pass unchanged, louder ones bend smoothly into full scale, sign(x) (k + (1 - k) tanh((|x| - k) / (1 - k))).",
3
  "sample_rate": 44100,
4
  "sampling": {
5
+ "temperature": 0.75,
6
+ "topk": 80,
7
+ "top_p": 0.69,
8
  "min_p": 0.0,
9
  "repetition_penalty": 2.4,
10
  "repetition_window": 96,
 
16
  "reference_max_frames": 900,
17
  "max_frames": 2000,
18
  "audio_max_seconds": {"reference": 60, "upload": 600, "edit": 150},
19
+ "stream_codebooks": {"default": 1, "scope": "first"},
20
+ "output_limit_dbfs": -1.0
21
  }
zonos3/registries/speaker_encoder_registry.json CHANGED
@@ -3,7 +3,7 @@
3
  "ownmect_s2": {
4
  "type": "mect_fbank",
5
  "description": "George's own-weights MECT-B2 speaker encoder (arXiv 2609.24061 architecture, trained from scratch at Zyphra on VoxCeleb2 + VoxBlink2, stage-2 large-margin finetune), 192-d; the ownmect_s2 column of data_shards_w2vsv (zv3subsample) and the ZTTS2 prompt vectors in ztts2_mect_prompts_20261015/vectors were extracted with this checkpoint",
6
- "checkpoint": "hf://Zyphra/ZONOS3_Mini_release_ckpts/speaker_encoders/ownmect_s2/ckpt_0037.pth",
7
  "sha256": "3cef65631f3161cbd8eacc6ea40e59a237c79656d85c7232dcbe0c8d07cae88f",
8
  "backbone_type": "MECT_B2",
9
  "backbone_config": {
@@ -30,8 +30,8 @@
30
  "provenance": {
31
  "source_checkpoint": "/data/home/george/repos/w2v-bert-sv-mect-results/checkpoints/ownmect_s2_261009190656/ckpt_0037.pth",
32
  "code": "/data/home/george/repos/w2v-bert-sv-mect (branch own-mect): recipes/DeepASV/local/mect_sv.py MECTFbank + local/third_party/antspeaker",
33
- "infer_config": "hf://Zyphra/ZONOS3_Mini_release_ckpts/speaker_encoders/ownmect_s2/ownmect_b2_infer.yaml",
34
- "train_config": "hf://Zyphra/ZONOS3_Mini_release_ckpts/speaker_encoders/ownmect_s2/train.yaml",
35
  "extractor": "/data/groups/audio/gabriel/ztts2_mect_prompts_20261015/george/embed_prompt_scp.py (whole prompt, fp32, --emb-dim 192)"
36
  }
37
  }
 
3
  "ownmect_s2": {
4
  "type": "mect_fbank",
5
  "description": "George's own-weights MECT-B2 speaker encoder (arXiv 2609.24061 architecture, trained from scratch at Zyphra on VoxCeleb2 + VoxBlink2, stage-2 large-margin finetune), 192-d; the ownmect_s2 column of data_shards_w2vsv (zv3subsample) and the ZTTS2 prompt vectors in ztts2_mect_prompts_20261015/vectors were extracted with this checkpoint",
6
+ "checkpoint": "hf://Zyphra/ZONOS3-Mini/speaker_encoders/ownmect_s2/ckpt_0037.pth",
7
  "sha256": "3cef65631f3161cbd8eacc6ea40e59a237c79656d85c7232dcbe0c8d07cae88f",
8
  "backbone_type": "MECT_B2",
9
  "backbone_config": {
 
30
  "provenance": {
31
  "source_checkpoint": "/data/home/george/repos/w2v-bert-sv-mect-results/checkpoints/ownmect_s2_261009190656/ckpt_0037.pth",
32
  "code": "/data/home/george/repos/w2v-bert-sv-mect (branch own-mect): recipes/DeepASV/local/mect_sv.py MECTFbank + local/third_party/antspeaker",
33
+ "infer_config": "speaker_encoders/ownmect_s2/ownmect_b2_infer.yaml of Zyphra/ZONOS3_Mini_release_ckpts (not in the public repo)",
34
+ "train_config": "speaker_encoders/ownmect_s2/train.yaml of Zyphra/ZONOS3_Mini_release_ckpts (not in the public repo)",
35
  "extractor": "/data/groups/audio/gabriel/ztts2_mect_prompts_20261015/george/embed_prompt_scp.py (whole prompt, fp32, --emb-dim 192)"
36
  }
37
  }
zonos3/tokenizer/textnorm.py CHANGED
@@ -12,6 +12,7 @@ text_normalization flag.
12
 
13
  from __future__ import annotations
14
 
 
15
  import logging
16
  import os
17
  import re
@@ -201,23 +202,29 @@ class TTSTextNormalizer:
201
  cache_dir = os.path.join(self.cache_root, f"{lang}_{input_case}")
202
  os.makedirs(cache_dir, exist_ok=True)
203
 
204
- logger.info("Loading TTS text normalizer for '%s' (%s)...", lang, input_case)
205
- normalizer = Normalizer(
206
- input_case=input_case,
207
- lang=lang,
208
- cache_dir=cache_dir,
209
- overwrite_cache=False,
210
- )
211
-
212
- prefix = _VERBALIZER_FAR_PREFIX.get(lang)
213
- if prefix is not None:
214
- far_path = os.path.join(cache_dir, f"{prefix}_tn_True_deterministic_verbalizer.far")
215
- if not os.path.exists(far_path):
216
- from zonos3.vendor.nemo_text_processing.text_normalization.en.graph_utils import (
217
- generator_main,
 
 
218
  )
 
 
 
 
219
 
220
- generator_main(far_path, {"verbalize": normalizer.verbalizer.fst})
221
  return normalizer
222
 
223
  def get(self, lang: str):
 
12
 
13
  from __future__ import annotations
14
 
15
+ import fcntl
16
  import logging
17
  import os
18
  import re
 
202
  cache_dir = os.path.join(self.cache_root, f"{lang}_{input_case}")
203
  os.makedirs(cache_dir, exist_ok=True)
204
 
205
+ # Several tokenizer processes share this cache: one builds and writes the .far files while the others wait,
206
+ # then load them (an unlocked concurrent build could read another process's half-written .far).
207
+ with open(os.path.join(cache_dir, ".build.lock"), "w") as lock_file:
208
+ fcntl.flock(lock_file, fcntl.LOCK_EX)
209
+ logger.info("Loading TTS text normalizer for '%s' (%s)...", lang, input_case)
210
+ normalizer = Normalizer(
211
+ input_case=input_case,
212
+ lang=lang,
213
+ cache_dir=cache_dir,
214
+ overwrite_cache=False,
215
+ )
216
+
217
+ prefix = _VERBALIZER_FAR_PREFIX.get(lang)
218
+ if prefix is not None:
219
+ far_path = os.path.join(
220
+ cache_dir, f"{prefix}_tn_True_deterministic_verbalizer.far"
221
  )
222
+ if not os.path.exists(far_path):
223
+ from zonos3.vendor.nemo_text_processing.text_normalization.en.graph_utils import (
224
+ generator_main,
225
+ )
226
 
227
+ generator_main(far_path, {"verbalize": normalizer.verbalizer.fst})
228
  return normalizer
229
 
230
  def get(self, lang: str):
zonos3/tts/align_text.py CHANGED
@@ -1,4 +1,10 @@
1
- """The tokens a transcript is force-aligned by (FuseAlign: zonos3/workers/fusealign.py places one interval per token)."""
 
 
 
 
 
 
2
 
3
  from __future__ import annotations
4
 
@@ -7,28 +13,50 @@ import unicodedata
7
 
8
  from zonos3.languages import UNSPACED
9
 
10
- _CJK_BLOCKS = (
11
- (0x3040, 0x30FF),
12
- (0x31F0, 0x31FF),
13
- (0x3400, 0x4DBF),
14
- (0x4E00, 0x9FFF),
15
- (0xF900, 0xFAFF),
16
- (0xFF66, 0xFF9F),
17
- )
18
  _TOKEN = re.compile(r"\S+")
 
 
19
 
20
 
21
  def _wordy(ch: str) -> bool:
22
  return unicodedata.category(ch)[0] in "LN" or ch == "'"
23
 
24
 
25
- def _cjk(ch: str) -> bool:
26
- o = ord(ch)
27
- return any(lo <= o <= hi for lo, hi in _CJK_BLOCKS)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
 
30
  def text_units(text: str, lang: str) -> list[dict]:
31
- """Split the target text into word units ``{"text", "start", "end"}`` (char offsets); trailing punctuation sticks to its unit."""
 
 
32
  spans: list[list[int]] = [] # [start, end)
33
  lead: int | None = None # start of non-wordy chars seen before the first unit
34
 
@@ -40,20 +68,32 @@ def text_units(text: str, lang: str) -> list[dict]:
40
  lead = start
41
 
42
  if lang in UNSPACED:
43
- run_end = -1 # end of the open run of non-CJK wordy chars
 
 
 
 
 
 
 
 
44
  for i, ch in enumerate(text):
45
  if ch.isspace():
46
  continue
47
- if _wordy(ch):
48
- if _cjk(ch):
 
49
  spans.append([i, i + 1])
50
- run_end = -1
51
- elif run_end == i:
 
 
 
 
52
  spans[-1][1] = i + 1
53
- run_end = i + 1
54
  else:
55
  spans.append([i, i + 1])
56
- run_end = i + 1
57
  else:
58
  attach(i, i + 1)
59
  else:
@@ -70,9 +110,9 @@ def text_units(text: str, lang: str) -> list[dict]:
70
  def align_tokens(text: str, lang: str) -> list[str]:
71
  """The words of ``text`` for forced alignment; ``lang`` is a Whisper-style code (``en``, ``ja``, ``zh``, ...).
72
 
73
- Unspaced languages (``UNSPACED``: ja, zh, yue) take the unit texts of ``text_units`` (one unit per CJK character
74
- or Latin/digit run, trailing punctuation attached; whitespace inside a unit removed), every other language the
75
- whitespace words."""
76
  if lang in UNSPACED:
77
  return [token for token in ("".join(u["text"].split()) for u in text_units(text, lang)) if token]
78
  return text.split()
 
1
+ """The tokens a transcript is force-aligned by (FuseAlign: zonos3/workers/fusealign.py places one interval per token).
2
+
3
+ FuseAlign was trained on transcripts whose unspaced scripts were segmented into words (z-speech-alignment's wordseg:
4
+ jieba for Mandarin and Cantonese, MeCab/UniDic for Japanese, each over the maximal runs of Han and kana). Here those
5
+ runs are cut by ICU's word break (root locale): the same dictionaries as the browser's ``Intl.Segmenter``, so the
6
+ in-browser engine and the studio cut CJK text exactly as the servers do. ICU and jieba / MeCab agree on most words
7
+ (東京タワー is one ICU word, two MeCab morphemes)."""
8
 
9
  from __future__ import annotations
10
 
 
13
 
14
  from zonos3.languages import UNSPACED
15
 
16
+ # z-speech-alignment wordseg's _HAN and _KANA: the runs a word segmenter cuts.
17
+ _CJK_RUN = re.compile("[\u3005\u3007\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\u3040-\u30ff\u31f0-\u31ff\uff66-\uff9f]+")
 
 
 
 
 
 
18
  _TOKEN = re.compile(r"\S+")
19
+ # ICU rule statuses at or above UBRK_WORD_NUMBER (100): the segment is a word (Intl.Segmenter isWordLike).
20
+ _ICU_WORD = 100
21
 
22
 
23
  def _wordy(ch: str) -> bool:
24
  return unicodedata.category(ch)[0] in "LN" or ch == "'"
25
 
26
 
27
+ def cjk_words(run: str) -> list[tuple[int, int]]:
28
+ """``[start, end)`` of the words ICU's word break (root locale) finds in a run of Han / kana (``_CJK_RUN``);
29
+ segments that are not words (``・``) are left out."""
30
+ import icu # pyicu-wheels: loaded on the first CJK text
31
+
32
+ breaks = icu.BreakIterator.createWordInstance(icu.Locale.getRoot())
33
+ breaks.setText(run) # BMP-only run: ICU's UTF-16 offsets are str offsets
34
+ words, start = [], breaks.first()
35
+ for end in breaks:
36
+ if breaks.getRuleStatus() >= _ICU_WORD:
37
+ words.append((start, end))
38
+ start = end
39
+ return words
40
+
41
+
42
+ def split_cjk(word: str) -> list[str]:
43
+ """A whitespace-free string cut into the words of its Han / kana runs (``cjk_words``) and the text between them;
44
+ a string without such runs is returned whole."""
45
+ out, pos = [], 0
46
+ for m in _CJK_RUN.finditer(word):
47
+ if m.start() > pos:
48
+ out.append(word[pos : m.start()])
49
+ out += [m.group()[a:b] for a, b in cjk_words(m.group())]
50
+ pos = m.end()
51
+ if pos < len(word):
52
+ out.append(word[pos:])
53
+ return out
54
 
55
 
56
  def text_units(text: str, lang: str) -> list[dict]:
57
+ """Split the target text into word units ``{"text", "start", "end"}`` (char offsets); trailing punctuation sticks
58
+ to its unit. Unspaced languages (``UNSPACED``) take one unit per word of each Han / kana run (``cjk_words``) and
59
+ per run of other letters / digits; every other language its whitespace words."""
60
  spans: list[list[int]] = [] # [start, end)
61
  lead: int | None = None # start of non-wordy chars seen before the first unit
62
 
 
68
  lead = start
69
 
70
  if lang in UNSPACED:
71
+ in_run: set[int] = set() # offsets inside a Han / kana run
72
+ starts: set[int] = set() # first char of each run word
73
+ inside: set[int] = set() # every char of each run word
74
+ for m in _CJK_RUN.finditer(text):
75
+ in_run.update(range(m.start(), m.end()))
76
+ for a, b in cjk_words(m.group()):
77
+ starts.add(m.start() + a)
78
+ inside.update(range(m.start() + a, m.start() + b))
79
+ run_end = -1 # end of the open run of other wordy chars
80
  for i, ch in enumerate(text):
81
  if ch.isspace():
82
  continue
83
+ if i in in_run:
84
+ run_end = -1
85
+ if i in starts:
86
  spans.append([i, i + 1])
87
+ elif i in inside:
88
+ spans[-1][1] = i + 1
89
+ else:
90
+ attach(i, i + 1)
91
+ elif _wordy(ch):
92
+ if run_end == i:
93
  spans[-1][1] = i + 1
 
94
  else:
95
  spans.append([i, i + 1])
96
+ run_end = i + 1
97
  else:
98
  attach(i, i + 1)
99
  else:
 
110
  def align_tokens(text: str, lang: str) -> list[str]:
111
  """The words of ``text`` for forced alignment; ``lang`` is a Whisper-style code (``en``, ``ja``, ``zh``, ...).
112
 
113
+ Unspaced languages (``UNSPACED``: ja, zh, yue) take the unit texts of ``text_units`` (one unit per ICU word of a
114
+ Han / kana run or per Latin/digit run, trailing punctuation attached; whitespace inside a unit removed), every
115
+ other language the whitespace words."""
116
  if lang in UNSPACED:
117
  return [token for token in ("".join(u["text"].split()) for u in text_units(text, lang)) if token]
118
  return text.split()
zonos3/tts/audio.py CHANGED
@@ -1,4 +1,5 @@
1
- """Reference-audio decoding (ffmpeg -> PCM WAV -> mono float tensor) and the one PCM16 WAV encoder.
 
2
 
3
  Shared by the HTTP server and the offline :class:`~zonos3_sgl.tts.llm.TTSLLM`; has no
4
  FastAPI / server dependency.
@@ -15,8 +16,31 @@ import wave
15
  import numpy as np
16
  import torch
17
 
 
 
18
  logger = logging.getLogger(__name__)
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  def pcm16_samples(pcm: np.ndarray) -> np.ndarray:
22
  """Float PCM -> little-endian int16: NaN -> 0, clip to [-1, 1], x 32767, round half to even (libsndfile's
 
1
+ """Reference-audio decoding (ffmpeg -> PCM WAV -> mono float tensor), the served PCM's output stage (gain + soft
2
+ limiter) and the one PCM16 WAV encoder.
3
 
4
  Shared by the HTTP server and the offline :class:`~zonos3_sgl.tts.llm.TTSLLM`; has no
5
  FastAPI / server dependency.
 
16
  import numpy as np
17
  import torch
18
 
19
+ from zonos3.generation import OUTPUT_LIMIT_DBFS
20
+
21
  logger = logging.getLogger(__name__)
22
 
23
+ # The soft limiter's knee (generation registry output_limit_dbfs) as a linear amplitude.
24
+ OUTPUT_LIMIT_KNEE = np.float32(10.0 ** (OUTPUT_LIMIT_DBFS / 20.0))
25
+
26
+
27
+ def output_pcm(samples: np.ndarray, gain: float) -> np.ndarray:
28
+ """Decoder audio -> the served float32 PCM: times the output ``gain`` (the decoder's headroom), then the soft
29
+ limiter. Samples at or below the knee k (OUTPUT_LIMIT_KNEE) pass unchanged; louder ones become
30
+ ``sign(x) * (k + (1 - k) * tanh((|x| - k) / (1 - k)))``: slope 1 at the knee, bounded by full scale (float32 tanh
31
+ reaches it only past |x| ~ 1.9). Per sample, so streamed chunks equal the whole audio."""
32
+ x = np.asarray(samples, dtype=np.float32)
33
+ if gain != 1.0:
34
+ x = x * np.float32(gain)
35
+ over = np.abs(x) > OUTPUT_LIMIT_KNEE
36
+ if not over.any():
37
+ return x
38
+ width = np.float32(1.0) - OUTPUT_LIMIT_KNEE
39
+ y = x.copy()
40
+ peak = x[over]
41
+ y[over] = np.sign(peak) * (OUTPUT_LIMIT_KNEE + width * np.tanh((np.abs(peak) - OUTPUT_LIMIT_KNEE) / width))
42
+ return y
43
+
44
 
45
  def pcm16_samples(pcm: np.ndarray) -> np.ndarray:
46
  """Float PCM -> little-endian int16: NaN -> 0, clip to [-1, 1], x 32767, round half to even (libsndfile's
zonos3/tts/textmatch.py CHANGED
@@ -10,6 +10,8 @@ from __future__ import annotations
10
 
11
  import re
12
 
 
 
13
  # Curly quotes are folded so "don't" and "don’t" are one token. Every letter
14
  # or digit of any script is kept: libriheavy's ``[A-Z0-9']`` rule reduced a
15
  # Mandarin token to the empty string, so a guide in an unspaced script
@@ -59,8 +61,9 @@ def char_error_rate(reference: str, hypothesis: str) -> float:
59
 
60
 
61
  def tokens(text: str) -> list[str]:
62
- """The edit tokens of a text: the whitespace words of its ``normalize``."""
63
- return normalize(text).split()
 
64
 
65
 
66
  def word_errors(reference: list[str], hypothesis: list[str]) -> int:
 
10
 
11
  import re
12
 
13
+ from zonos3.tts.align_text import split_cjk
14
+
15
  # Curly quotes are folded so "don't" and "don’t" are one token. Every letter
16
  # or digit of any script is kept: libriheavy's ``[A-Z0-9']`` rule reduced a
17
  # Mandarin token to the empty string, so a guide in an unspaced script
 
61
 
62
 
63
  def tokens(text: str) -> list[str]:
64
+ """The edit tokens of a text: the whitespace words of its ``normalize``, each Han / kana run cut into its words
65
+ (``zonos3.tts.align_text.split_cjk``: the units FuseAlign aligns unspaced text by)."""
66
+ return [token for word in normalize(text).split() for token in split_cjk(word)]
67
 
68
 
69
  def word_errors(reference: list[str], hypothesis: list[str]) -> int:
zonos3/utils/hf.py CHANGED
@@ -20,7 +20,7 @@ def resolve_model_path(model_path: str) -> str:
20
  """Resolve a model path to a local directory.
21
 
22
  Local paths are returned as-is. A Hugging Face repo id (e.g.
23
- ``hf://Zyphra/ZONOS3_Mini_release_ckpts/lm/rate30_20k_r2grpo``) is downloaded to the local HF cache first.
24
  """
25
  from zonos3.utils.release import is_hf, resolve_dir_or_local
26
 
 
20
  """Resolve a model path to a local directory.
21
 
22
  Local paths are returned as-is. A Hugging Face repo id (e.g.
23
+ ``hf://Zyphra/ZONOS3-Mini/lm/zonos3_mini``) is downloaded to the local HF cache first.
24
  """
25
  from zonos3.utils.release import is_hf, resolve_dir_or_local
26
 
zonos3/utils/release.py CHANGED
@@ -2,10 +2,9 @@
2
 
3
  Registries, configs and the server's default --model-path may name files and folders in a Hugging Face repo as
4
  ``hf://<owner>/<repo>/<path inside the repo>``. ``resolve_file`` / ``resolve_dir_or_local`` fetch them into the local HF cache
5
- (``HF_HOME``; ``HF_TOKEN`` or a stored login is needed while the repo is private) and return local paths; plain local paths pass
6
- through unchanged, so the cluster servers keep running from their local registries. Default repo: ``ZONOS3_RELEASE_REPO``
7
- (Zyphra/ZONOS3_Mini_release_ckpts) and its language model ``lm/rate30_20k_r2grpo`` (was ``lm/mect_60k``,
8
- which was ``lm/fullenc_120k`` before).
9
  """
10
 
11
  from __future__ import annotations
@@ -16,8 +15,8 @@ from functools import lru_cache
16
  from pathlib import Path
17
 
18
  PREFIX = "hf://"
19
- RELEASE_REPO = os.environ.get("ZONOS3_RELEASE_REPO", "Zyphra/ZONOS3_Mini_release_ckpts")
20
- RELEASE_LM = os.environ.get("ZONOS3_RELEASE_LM", f"{PREFIX}{RELEASE_REPO}/lm/rate30_20k_r2grpo")
21
  RELEASE_SPEAKER_REGISTRY = f"{PREFIX}{RELEASE_REPO}/registries/speaker_encoder_registry.json"
22
 
23
 
 
2
 
3
  Registries, configs and the server's default --model-path may name files and folders in a Hugging Face repo as
4
  ``hf://<owner>/<repo>/<path inside the repo>``. ``resolve_file`` / ``resolve_dir_or_local`` fetch them into the local HF cache
5
+ (``HF_HOME``; ``HF_TOKEN`` or a stored login for private repos) and return local paths; plain local paths pass through
6
+ unchanged, so the cluster servers keep running from their local registries. Default repo: ``ZONOS3_RELEASE_REPO``
7
+ (Zyphra/ZONOS3-Mini, public) and its language model ``lm/zonos3_mini``.
 
8
  """
9
 
10
  from __future__ import annotations
 
15
  from pathlib import Path
16
 
17
  PREFIX = "hf://"
18
+ RELEASE_REPO = os.environ.get("ZONOS3_RELEASE_REPO", "Zyphra/ZONOS3-Mini")
19
+ RELEASE_LM = os.environ.get("ZONOS3_RELEASE_LM", f"{PREFIX}{RELEASE_REPO}/lm/zonos3_mini")
20
  RELEASE_SPEAKER_REGISTRY = f"{PREFIX}{RELEASE_REPO}/registries/speaker_encoder_registry.json"
21
 
22