sshtel Claude Sonnet 4.6 commited on
Commit
4798cd4
·
1 Parent(s): 3cfd932

perf: improve LFM2.5-Audio inference quality and reliability

Browse files

Applies fixes from inference_lfm_fix.py based on demo testing:

- Fix system prompt: use official "Respond with interleaved text and audio."
instead of custom storyteller prompt; move story context to user turn
so the model processes it correctly for interleaved speech-to-speech
- Fix audio decode: switch from Mimi streaming decode to post-generation
processor.decode(audio_codes) which is more stable and avoids Mimi
streaming state corruption between calls
- Remove torch.compile and _reset_mimi_streaming_state (caused silent
audio / Mimi state bugs); replace with eager Mimi warmup on CUDA
- Raise max_new_tokens 100 -> 512 across inference_lfm, qa_flow, app.py
(100 was insufficient for complete audio generation at 12.5 Hz/frame)
- Add get_model_status() for GPU memory diagnostics
- Add text_to_audio_lfm() for LFM-based TTS mode
- Add _assemble_waveform() helper shared by TTS and Q&A paths

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

Files changed (3) hide show
  1. app.py +1 -1
  2. inference_lfm.py +151 -74
  3. qa_flow.py +1 -1
app.py CHANGED
@@ -1078,7 +1078,7 @@ with gr.Blocks(title="MomsVoice", css=css_code) as demo:
1078
  paragraphs=paragraphs,
1079
  output_dir=SAMPLE_SOUNDS_DIR,
1080
  answer_fn=answer_question_audio,
1081
- max_new_tokens=100,
1082
  )
1083
 
1084
  if not result["ok"]:
 
1078
  paragraphs=paragraphs,
1079
  output_dir=SAMPLE_SOUNDS_DIR,
1080
  answer_fn=answer_question_audio,
1081
+ max_new_tokens=512,
1082
  )
1083
 
1084
  if not result["ok"]:
inference_lfm.py CHANGED
@@ -9,6 +9,7 @@ from __future__ import annotations
9
  import logging
10
  import os
11
  import threading
 
12
 
13
  if os.name == "nt":
14
  os.environ.setdefault("TORCHDYNAMO_DISABLE", "1") # Windows typically lacks Triton for torch.compile
@@ -70,14 +71,55 @@ def _module_device(module, fallback: torch.device) -> torch.device:
70
  return getattr(module, "device", fallback)
71
 
72
 
73
- def _reset_mimi_streaming_state(mimi) -> None:
74
- """Best-effort reset of Mimi's internal streaming buffers."""
75
- for attr in ("_streaming_state", "_states"):
76
- if hasattr(mimi, attr):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  try:
78
- setattr(mimi, attr, None)
 
 
79
  except Exception:
80
  pass
 
81
 
82
 
83
  def get_lfm_model():
@@ -108,50 +150,43 @@ def get_lfm_model():
108
  if moved_model is not None:
109
  _model = moved_model
110
  _model = _model.eval()
111
- # torch.compile for inference speedup on Linux/CUDA (skip on Windows)
112
- if device.type == "cuda" and os.name != "nt":
113
- try:
114
- _model = torch.compile(_model, mode="reduce-overhead", dynamic=True)
115
- logger.info("torch.compile applied to LFM model (reduce-overhead, dynamic).")
116
- except Exception as exc:
117
- logger.warning("torch.compile failed, using eager mode: %s", exc)
118
  # Force lazy Mimi construction after the processor is on the target device,
119
  # and fail early if the streaming decoder cannot run there.
120
  mimi = _processor.mimi.eval()
121
- _reset_mimi_streaming_state(mimi)
 
 
122
  logger.info("LFM2.5-Audio loaded on %s.", _module_device(_model, device))
123
  return _processor, _model
124
 
125
 
126
  def warmup_lfm():
127
- """Run a dummy generation to trigger torch.compile and warm CUDA graphs.
128
  Call once at startup after get_lfm_model() to eliminate first-query latency.
129
  """
130
  try:
131
- processor, model = get_lfm_model()
132
  from liquid_audio import ChatState
 
 
133
  device = _module_device(model, _select_device())
134
  dtype = next(model.parameters()).dtype
135
- mimi = processor.mimi.eval()
136
 
137
- _reset_mimi_streaming_state(mimi)
138
  with GPU_INFERENCE_LOCK, torch.no_grad():
139
  chat = ChatState(processor, dtype=dtype)
140
  chat.new_turn("system")
141
- chat.add_text("You are a helpful assistant.")
142
  chat.end_turn()
143
  chat.new_turn("user")
144
  chat.add_text("Hi")
145
  chat.end_turn()
146
  chat.new_turn("assistant")
147
 
148
- with mimi.streaming(1):
149
- for t in model.generate_interleaved(
150
- **chat, max_new_tokens=10, audio_temperature=1.0, audio_top_k=4,
151
- ):
152
- pass # Just trigger compilation, discard output
153
- _reset_mimi_streaming_state(mimi)
154
- logger.info("LFM warmup complete — torch.compile graphs cached.")
155
  except Exception as exc:
156
  logger.warning("LFM warmup failed (non-fatal): %s", exc)
157
 
@@ -160,7 +195,7 @@ def answer_question_audio(
160
  question_audio_path: str | None = None,
161
  question_text: str | None = None,
162
  story_context: str = "",
163
- max_new_tokens: int = 100,
164
  ) -> tuple[str, np.ndarray | None, int]:
165
  """
166
  Answer a question about the story using LFM2.5-Audio end-to-end.
@@ -177,19 +212,18 @@ def answer_question_audio(
177
  with GPU_INFERENCE_LOCK, torch.no_grad():
178
  chat = ChatState(processor, dtype=dtype)
179
 
180
- # System prompt with story context
181
  chat.new_turn("system")
182
- system_prompt = (
183
- "You are a friendly storyteller answering a child's question about a bedtime story. "
184
- "Answer in 1-2 short, simple sentences using warm, age-appropriate language. "
185
- "Only use information from the story context below.\n\n"
186
- f"Story context:\n{story_context[:3000]}"
187
- )
188
- chat.add_text(system_prompt)
189
  chat.end_turn()
190
 
191
- # User turn — audio or text
192
  chat.new_turn("user")
 
 
 
 
 
193
  if question_audio_path:
194
  import librosa
195
  wav_np, sr = librosa.load(question_audio_path, sr=16000, mono=True)
@@ -201,10 +235,83 @@ def answer_question_audio(
201
  return "Please ask a question!", None, SAMPLE_RATE
202
  chat.end_turn()
203
 
204
- # Generate answer using Mimi streaming decode (official approach)
205
  chat.new_turn("assistant")
206
- text_out = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
  wav_chunks = []
 
208
 
209
  mimi = processor.mimi.eval()
210
  mimi_device = _first_parameter_device(mimi, device)
@@ -216,46 +323,16 @@ def answer_question_audio(
216
  audio_temperature=1.0,
217
  audio_top_k=4,
218
  ):
219
- if t.numel() == 1:
220
- text_out.append(t)
221
- elif t.numel() == 8:
222
- # Skip EOS/invalid marker frames before they poison the stream.
223
- if (t >= 2048).any() or (t < 0).any():
224
  continue
225
- codes = t.reshape(1, 8, 1).to(device=mimi_device, dtype=torch.long)
226
  try:
227
- wav_chunk = mimi.decode(codes)
228
  wav_chunks.append(wav_chunk.cpu())
229
  except Exception as exc:
230
- logger.warning(
231
- "Mimi decode skipped frame: %s (codes_device=%s, mimi_device=%s, shape=%s)",
232
- exc,
233
- codes.device,
234
- mimi_device,
235
- tuple(codes.shape),
236
- )
237
 
238
- # Decode text
239
- answer_text = ""
240
- if text_out:
241
- answer_text = "".join(processor.text.decode(t.detach().cpu()) for t in text_out).strip()
242
-
243
- # Assemble waveform from streaming chunks
244
- waveform = None
245
- if wav_chunks:
246
- try:
247
- waveform = torch.cat(wav_chunks, dim=-1).float().numpy().squeeze()
248
- if waveform.ndim == 0 or len(waveform) == 0:
249
- waveform = None
250
- else:
251
- peak = np.abs(waveform).max()
252
- if peak < 0.001:
253
- waveform = None # Silent, likely garbage
254
- else:
255
- # Normalize to target peak (0.9) for consistent volume
256
- waveform = waveform * (0.9 / peak)
257
- except Exception as e:
258
- logger.warning("Audio decode failed: %s", e)
259
- waveform = None
260
 
261
- return answer_text, waveform, SAMPLE_RATE
 
9
  import logging
10
  import os
11
  import threading
12
+ import time
13
 
14
  if os.name == "nt":
15
  os.environ.setdefault("TORCHDYNAMO_DISABLE", "1") # Windows typically lacks Triton for torch.compile
 
71
  return getattr(module, "device", fallback)
72
 
73
 
74
+ def _assemble_waveform(wav_chunks: list) -> np.ndarray | None:
75
+ """Concatenate Mimi output chunks, normalize to peak 0.9, and return float32 array."""
76
+ if not wav_chunks:
77
+ return None
78
+ try:
79
+ waveform = torch.cat(wav_chunks, dim=-1).float().numpy().squeeze()
80
+ except Exception as exc:
81
+ logger.warning("Waveform assembly failed: %s", exc)
82
+ return None
83
+
84
+ if waveform.ndim == 0 or waveform.size == 0:
85
+ return None
86
+
87
+ peak = float(np.abs(waveform).max())
88
+ logger.info("Waveform peak amplitude: %.6f (samples: %d)", peak, waveform.size)
89
+
90
+ if peak == 0.0:
91
+ logger.warning("Waveform is all zeros — model generated silence")
92
+ return None
93
+
94
+ return waveform * (0.9 / peak)
95
+
96
+
97
+ def get_model_status() -> dict:
98
+ """Return current model load state, device, dtype, and GPU memory."""
99
+ status: dict = {
100
+ "model_loaded": _model is not None,
101
+ "repo": HF_REPO,
102
+ "device": None,
103
+ "dtype": None,
104
+ "gpu_name": None,
105
+ "gpu_memory_used_gb": None,
106
+ "gpu_memory_reserved_gb": None,
107
+ }
108
+ if _model is not None:
109
+ device = _module_device(_model, _select_device())
110
+ status["device"] = str(device)
111
+ try:
112
+ status["dtype"] = str(next(_model.parameters()).dtype).replace("torch.", "")
113
+ except Exception:
114
+ pass
115
+ if device.type == "cuda":
116
  try:
117
+ status["gpu_name"] = torch.cuda.get_device_name(device)
118
+ status["gpu_memory_used_gb"] = round(torch.cuda.memory_allocated(device) / 1e9, 2)
119
+ status["gpu_memory_reserved_gb"] = round(torch.cuda.memory_reserved(device) / 1e9, 2)
120
  except Exception:
121
  pass
122
+ return status
123
 
124
 
125
  def get_lfm_model():
 
150
  if moved_model is not None:
151
  _model = moved_model
152
  _model = _model.eval()
 
 
 
 
 
 
 
153
  # Force lazy Mimi construction after the processor is on the target device,
154
  # and fail early if the streaming decoder cannot run there.
155
  mimi = _processor.mimi.eval()
156
+ if device.type == "cuda":
157
+ with torch.no_grad(), mimi.streaming(1):
158
+ mimi.decode(torch.randint(0, 2048, (1, 8, 1), device=device))
159
  logger.info("LFM2.5-Audio loaded on %s.", _module_device(_model, device))
160
  return _processor, _model
161
 
162
 
163
  def warmup_lfm():
164
+ """Run a dummy generation to warm the model after loading.
165
  Call once at startup after get_lfm_model() to eliminate first-query latency.
166
  """
167
  try:
 
168
  from liquid_audio import ChatState
169
+
170
+ processor, model = get_lfm_model()
171
  device = _module_device(model, _select_device())
172
  dtype = next(model.parameters()).dtype
 
173
 
 
174
  with GPU_INFERENCE_LOCK, torch.no_grad():
175
  chat = ChatState(processor, dtype=dtype)
176
  chat.new_turn("system")
177
+ chat.add_text("Respond with interleaved text and audio.")
178
  chat.end_turn()
179
  chat.new_turn("user")
180
  chat.add_text("Hi")
181
  chat.end_turn()
182
  chat.new_turn("assistant")
183
 
184
+ for _ in model.generate_interleaved(
185
+ **chat, max_new_tokens=10, audio_temperature=1.0, audio_top_k=4,
186
+ ):
187
+ pass # Just trigger warmup, discard output
188
+
189
+ logger.info("LFM warmup complete.")
 
190
  except Exception as exc:
191
  logger.warning("LFM warmup failed (non-fatal): %s", exc)
192
 
 
195
  question_audio_path: str | None = None,
196
  question_text: str | None = None,
197
  story_context: str = "",
198
+ max_new_tokens: int = 512,
199
  ) -> tuple[str, np.ndarray | None, int]:
200
  """
201
  Answer a question about the story using LFM2.5-Audio end-to-end.
 
212
  with GPU_INFERENCE_LOCK, torch.no_grad():
213
  chat = ChatState(processor, dtype=dtype)
214
 
215
+ # Official system prompt for interleaved speech-to-speech
216
  chat.new_turn("system")
217
+ chat.add_text("Respond with interleaved text and audio.")
 
 
 
 
 
 
218
  chat.end_turn()
219
 
220
+ # User turn — story context as text prefix, then audio or text question
221
  chat.new_turn("user")
222
+ if story_context:
223
+ chat.add_text(
224
+ f"Story context:\n{story_context[:3000]}\n\n"
225
+ "Answer the question in 1-2 short sentences based only on the story."
226
+ )
227
  if question_audio_path:
228
  import librosa
229
  wav_np, sr = librosa.load(question_audio_path, sr=16000, mono=True)
 
235
  return "Please ask a question!", None, SAMPLE_RATE
236
  chat.end_turn()
237
 
 
238
  chat.new_turn("assistant")
239
+ text_out: list[torch.Tensor] = []
240
+ audio_out: list[torch.Tensor] = []
241
+ text_token_count = 0
242
+ t0 = time.perf_counter()
243
+
244
+ for t in model.generate_interleaved(
245
+ **chat,
246
+ max_new_tokens=max_new_tokens,
247
+ audio_temperature=1.0,
248
+ audio_top_k=4,
249
+ ):
250
+ if t.numel() == 1:
251
+ text_token_count += 1
252
+ text_out.append(t)
253
+ elif t.numel() == 8:
254
+ audio_out.append(t)
255
+
256
+ gen_time = time.perf_counter() - t0
257
+ audio_frame_count = max(0, len(audio_out) - 1) # last frame is EOS
258
+ logger.info(
259
+ "Generated: %d text tokens, %d audio frames (%.1f sec), %.1f s wall",
260
+ text_token_count, audio_frame_count, audio_frame_count / 12.5, gen_time,
261
+ )
262
+
263
+ # Decode text
264
+ answer_text = ""
265
+ if text_out:
266
+ answer_text = "".join(processor.text.decode(t.detach().cpu()) for t in text_out).strip()
267
+
268
+ # Decode audio via processor.decode (drops EOS frame)
269
+ waveform = None
270
+ if len(audio_out) > 1:
271
+ audio_codes = torch.stack(audio_out[:-1], dim=1).unsqueeze(0) # (1, 8, N)
272
+ raw = processor.decode(audio_codes).cpu().float()
273
+ waveform = raw[0].numpy()
274
+ peak = float(np.abs(waveform).max())
275
+ if peak > 0:
276
+ waveform = waveform * (0.9 / peak)
277
+ logger.info("Decoded audio: %.2f sec, peak %.4f", len(waveform) / SAMPLE_RATE, peak)
278
+
279
+ return answer_text, waveform, SAMPLE_RATE
280
+
281
+
282
+ def text_to_audio_lfm(
283
+ text: str,
284
+ max_new_tokens: int = 1024,
285
+ ) -> tuple[np.ndarray | None, int]:
286
+ """Convert text to audio using LFM2.5-Audio in TTS mode.
287
+
288
+ Feeds the text as a user message with a "read aloud" system prompt,
289
+ then collects only the audio tokens from generate_interleaved.
290
+ Returns (waveform_or_None, sample_rate).
291
+ """
292
+ from liquid_audio import ChatState
293
+
294
+ if not text.strip():
295
+ return None, SAMPLE_RATE
296
+
297
+ processor, model = get_lfm_model()
298
+ device = _module_device(model, _select_device())
299
+ dtype = next(model.parameters()).dtype
300
+
301
+ with GPU_INFERENCE_LOCK, torch.no_grad():
302
+ chat = ChatState(processor, dtype=dtype)
303
+
304
+ chat.new_turn("system")
305
+ chat.add_text("Read the following text aloud clearly and naturally.")
306
+ chat.end_turn()
307
+
308
+ chat.new_turn("user")
309
+ chat.add_text(text)
310
+ chat.end_turn()
311
+
312
+ chat.new_turn("assistant")
313
  wav_chunks = []
314
+ audio_frame_count = 0
315
 
316
  mimi = processor.mimi.eval()
317
  mimi_device = _first_parameter_device(mimi, device)
 
323
  audio_temperature=1.0,
324
  audio_top_k=4,
325
  ):
326
+ if t.numel() == 8:
327
+ if (t == 2048).any():
 
 
 
328
  continue
329
+ audio_frame_count += 1
330
  try:
331
+ wav_chunk = mimi.decode(t[None, :, None].to(device=mimi_device, dtype=torch.long))[0]
332
  wav_chunks.append(wav_chunk.cpu())
333
  except Exception as exc:
334
+ logger.warning("TTS decode skipped frame: %s", exc)
 
 
 
 
 
 
335
 
336
+ logger.info("TTS: %d audio frames (%.1f sec)", audio_frame_count, audio_frame_count / 12.5)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337
 
338
+ return _assemble_waveform(wav_chunks), SAMPLE_RATE
qa_flow.py CHANGED
@@ -101,7 +101,7 @@ def build_qa_response(
101
  output_dir: Path,
102
  answer_fn: Callable[..., tuple[str, object | None, int]],
103
  audio_writer: AudioWriter = _default_audio_writer,
104
- max_new_tokens: int = 100,
105
  ) -> dict[str, object]:
106
  """Run Q&A and return display-ready data without importing Gradio."""
107
  q_txt = (question_text or "").strip()
 
101
  output_dir: Path,
102
  answer_fn: Callable[..., tuple[str, object | None, int]],
103
  audio_writer: AudioWriter = _default_audio_writer,
104
+ max_new_tokens: int = 512,
105
  ) -> dict[str, object]:
106
  """Run Q&A and return display-ready data without importing Gradio."""
107
  q_txt = (question_text or "").strip()