Skip to content

Commit 0ce601f

Browse files
committed
Voxtral TTS: decode audio in 375-frame chunks, device-robust integration tests
- `generate` decodes the codec in independent chunks of 375 frames (30 s), as the vllm-omni reference does. This bounds the dense ALiBi/sliding-window attention mask: decoding 80 s of audio goes from 4.2 GB to 1.8 GB peak RSS. - Integration tests check teacher-forced semantic codes, acoustic codes from fixed noise and a codec waveform slice against the reference, instead of free-running bf16 codes that are not reproducible across devices.
1 parent d749d83 commit 0ce601f

3 files changed

Lines changed: 123 additions & 20 deletions

File tree

‎docs/source/en/model_doc/voxtral_tts.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,10 @@ for i, audio in enumerate(outputs.audio):
7373
frames of each sample (`outputs.audio_lengths`). The classifier-free guidance scale of the flow matching can be set
7474
with `cfg_alpha` (defaults to 1.2), and `generator` makes the generation reproducible.
7575

76+
As in the reference implementation, the codec decodes the audio in independent chunks of 375 frames (30 s), which
77+
bounds the memory of its attention for long generations (`codec_chunk_size`, set it to `None` to decode all frames at
78+
once).
79+
7680
## VoxtralTtsConfig
7781

7882
[[autodoc]] VoxtralTtsConfig

‎src/transformers/models/voxtral_tts/generation_voxtral_tts.py‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ def generate(
5151
cfg_alpha: float = 1.2,
5252
generator: torch.Generator | None = None,
5353
output_audio: bool = True,
54+
codec_chunk_size: int | None = 375,
5455
**kwargs,
5556
) -> VoxtralTtsGenerateOutput:
5657
r"""
@@ -75,6 +76,9 @@ def generate(
7576
Random generator for the flow-matching noise, for reproducible generations.
7677
output_audio (`bool`, *optional*, defaults to `True`):
7778
Whether to decode the generated codes into waveforms with the codec.
79+
codec_chunk_size (`int`, *optional*, defaults to 375):
80+
The codec decodes the audio in independent chunks of this many frames (30 s), as the reference
81+
implementation does, which bounds the memory of its attention. `None` decodes all frames at once.
7882
7983
Returns:
8084
[`VoxtralTtsGenerateOutput`]
@@ -138,7 +142,14 @@ def generate(
138142
num_special = self.config.acoustic_transformer_config.num_special_audio_tokens
139143
codec_codes = (audio_codes - num_special).clamp(min=0)
140144
# The codec is causal, so frames past the end of a sequence do not affect its waveform
141-
audio_values = self.codec_model.decode(codec_codes).audio_values
145+
chunk_size = codec_chunk_size or codec_codes.shape[1]
146+
audio_values = torch.cat(
147+
[
148+
self.codec_model.decode(codec_codes[:, start : start + chunk_size]).audio_values
149+
for start in range(0, codec_codes.shape[1], chunk_size)
150+
],
151+
dim=-1,
152+
)
142153
hop_length = self.config.codec_config.hop_length
143154
audio = [audio_values[i, : int(audio_lengths[i]) * hop_length] for i in range(batch_size)]
144155

‎tests/models/voxtral_tts/test_modeling_voxtral_tts.py‎

Lines changed: 107 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
"""Testing suite for the PyTorch Voxtral TTS model."""
1515

1616
import unittest
17+
from unittest import mock
1718

1819
from transformers import (
1920
VoxtralTtsAcousticTransformerConfig,
@@ -249,6 +250,30 @@ def test_generate(self):
249250
again = model.generate(**inputs, max_new_frames=5, generator=torch.Generator(torch_device).manual_seed(0))
250251
torch.testing.assert_close(again.audio_codes, outputs.audio_codes)
251252

253+
def test_generate_decodes_audio_in_chunks(self):
254+
config, inputs = self.model_tester.prepare_config_and_inputs_with_voice()
255+
model = VoxtralTtsForTextToSpeech(config).to(torch_device).eval()
256+
# Never predict `[END_AUDIO]`, so every frame is decoded
257+
semantic_head = model.acoustic_transformer.get_semantic_logits
258+
259+
def get_semantic_logits(hidden_states):
260+
logits = semantic_head(hidden_states)
261+
logits[..., 1] = logits.min() - 1
262+
return logits
263+
264+
with mock.patch.object(model.acoustic_transformer, "get_semantic_logits", get_semantic_logits):
265+
outputs = model.generate(
266+
**inputs, max_new_frames=5, codec_chunk_size=2, generator=torch.Generator(torch_device).manual_seed(0)
267+
)
268+
self.assertEqual(outputs.audio_lengths.tolist(), [5] * self.model_tester.batch_size)
269+
codec_codes = outputs.audio_codes - config.acoustic_transformer_config.num_special_audio_tokens
270+
with torch.no_grad():
271+
expected = torch.cat(
272+
[model.codec_model.decode(codec_codes[:, i : i + 2]).audio_values for i in range(0, 5, 2)], dim=-1
273+
)
274+
for audio, expected_audio in zip(outputs.audio, expected):
275+
torch.testing.assert_close(audio, expected_audio)
276+
252277
def test_generate_stops_on_end_audio(self):
253278
config, inputs = self.model_tester.prepare_config_and_inputs_with_voice()
254279
model = VoxtralTtsForTextToSpeech(config).to(torch_device).eval()
@@ -296,28 +321,91 @@ def test_codec_is_causal(self):
296321
@require_torch
297322
@require_mistral_common
298323
class VoxtralTtsIntegrationTest(unittest.TestCase):
324+
"""
325+
Expected values come from the original model (a transcription of the vllm-omni reference implementation), which
326+
generates these frames for `"Paris is a beautiful city!"` with the `casual_male` voice (Whisper transcribes the
327+
audio as "Paris is a beautiful city."). The free-running bf16 generation is too sensitive to numerics to compare
328+
across devices, so the model is checked with teacher forcing on the reference frames instead.
329+
"""
330+
299331
# TODO: point to the Transformers-format files once they are on the Hub
300332
checkpoint = "mistralai/Voxtral-4B-TTS-2603"
333+
text = "Paris is a beautiful city!"
334+
voice = "casual_male"
335+
# fmt: off
336+
expected_semantic_codes = [855, 806, 7096, 6114, 1438, 855, 10, 10, 6226, 663, 3950, 2072, 8023, 8023, 8023, 10, 10, 10, 3684, 3684, 7973, 1645, 1]
337+
expected_first_frames = [
338+
[855, 2, 15, 6, 6, 16, 10, 6, 6, 18, 5, 18, 5, 7, 20, 13, 11, 9, 6, 17, 10, 16, 7, 8, 14, 9, 9, 18, 21, 16, 20, 4, 6, 6, 17, 3, 4],
339+
[806, 12, 9, 12, 9, 19, 10, 11, 12, 18, 11, 15, 2, 7, 12, 17, 7, 11, 13, 9, 15, 16, 12, 9, 15, 12, 18, 20, 15, 9, 15, 13, 12, 5, 15, 5, 8],
340+
[7096, 19, 16, 20, 20, 18, 5, 10, 4, 18, 6, 13, 5, 12, 14, 12, 6, 10, 10, 12, 13, 12, 9, 18, 13, 11, 12, 16, 18, 18, 21, 6, 7, 16, 19, 3, 3],
341+
[6114, 8, 6, 15, 4, 10, 18, 10, 11, 17, 7, 9, 13, 18, 18, 14, 4, 4, 8, 21, 3, 15, 7, 19, 15, 7, 20, 15, 19, 15, 5, 7, 9, 20, 14, 4, 2],
342+
[1438, 16, 12, 18, 19, 13, 18, 7, 3, 17, 9, 6, 14, 9, 17, 5, 4, 9, 13, 20, 9, 14, 13, 9, 20, 20, 13, 7, 17, 12, 5, 10, 15, 7, 15, 5, 4],
343+
[855, 16, 4, 6, 16, 21, 10, 7, 14, 8, 8, 20, 14, 8, 10, 17, 13, 10, 9, 15, 9, 16, 9, 16, 14, 10, 14, 22, 20, 10, 10, 18, 9, 10, 13, 10, 10],
344+
]
345+
# fmt: on
346+
347+
@classmethod
348+
def setUpClass(cls):
349+
cls.processor = AutoProcessor.from_pretrained(cls.checkpoint)
350+
cls.model = VoxtralTtsForTextToSpeech.from_pretrained(
351+
cls.checkpoint, dtype=torch.bfloat16, device_map=torch_device
352+
)
301353

302-
def tearDown(self):
354+
@classmethod
355+
def tearDownClass(cls):
356+
del cls.model
303357
cleanup(torch_device, gc_collect=True)
304358

305-
def test_generate_casual_male(self):
306-
"""
307-
Reproducer, values obtained on CPU (bf16): the original model (a transcription of the vllm-omni reference) and
308-
this port generate the same 23 frames for this prompt, which Whisper transcribes as "Paris is a beautiful city."
309-
"""
310-
processor = AutoProcessor.from_pretrained(self.checkpoint)
311-
model = VoxtralTtsForTextToSpeech.from_pretrained(
312-
self.checkpoint, dtype=torch.bfloat16, device_map=torch_device
359+
def test_teacher_forced_semantic_codes(self):
360+
inputs = self.processor(self.text, voice=self.voice).to(torch_device)
361+
frames = torch.tensor(self.expected_first_frames, device=torch_device)
362+
with torch.no_grad():
363+
outputs = self.model(**inputs, audio_codes=frames[None])
364+
prompt_length = inputs["input_ids"].shape[1]
365+
semantic_logits = outputs.semantic_logits[0, prompt_length - 1 :].float().cpu()
366+
367+
# Values obtained on CPU
368+
expected_logits_slice = torch.tensor([-5.38, 1.3, -4.56, 6.56, -4.91, -5.06, 8.94, -7.09])
369+
torch.testing.assert_close(semantic_logits[0, :8], expected_logits_slice, rtol=0, atol=0.15)
370+
371+
# Restricted to the valid semantic codes, as in generation
372+
semantic_logits[:, 0] = -float("inf")
373+
semantic_logits[:, 2 + self.model.config.acoustic_transformer_config.semantic_codebook_size :] = -float("inf")
374+
predicted = semantic_logits.argmax(-1).tolist()
375+
expected = self.expected_semantic_codes[: len(predicted)]
376+
num_matches = sum(p == e for p, e in zip(predicted, expected))
377+
# Near-ties of the bf16 logits may flip a code
378+
self.assertGreaterEqual(num_matches, len(expected) - 1, f"{predicted} != {expected}")
379+
380+
def test_acoustic_codes_from_reference_noise(self):
381+
# Seeded flow-matching noise for the first frame, as drawn by `generate` with a CPU generator seeded at 0
382+
inputs = self.processor(self.text, voice=self.voice).to(torch_device)
383+
with torch.no_grad():
384+
hidden_state = self.model(**inputs).last_hidden_state[:, -1]
385+
noise = torch.randn(1, 36, generator=torch.Generator().manual_seed(0)).to(torch_device)
386+
frame = self.model.acoustic_transformer.generate_frame(hidden_state, noise=noise)[0].tolist()
387+
expected = self.expected_first_frames[0]
388+
self.assertEqual(frame[0], expected[0])
389+
# Acoustic codes are FSQ levels: bf16 differences may move a few of them by one level
390+
self.assertLessEqual(max(abs(a - b) for a, b in zip(frame[1:], expected[1:])), 1)
391+
self.assertGreaterEqual(sum(a == b for a, b in zip(frame[1:], expected[1:])), 30)
392+
393+
def test_codec_decode(self):
394+
codes = torch.tensor(self.expected_first_frames, device=torch_device) - 2
395+
with torch.no_grad():
396+
audio = self.model.codec_model.decode(codes[None]).audio_values[0].float().cpu()
397+
self.assertEqual(audio.shape, (6 * self.model.config.codec_config.hop_length,))
398+
# Values obtained on CPU
399+
expected_slice = torch.tensor(
400+
[0.00134, -0.00433, -0.00812, -0.00854, -0.00485, -0.00123, 0.00084, -0.00067, -0.00409, -0.00568]
313401
)
314-
inputs = processor("Paris is a beautiful city!", voice="casual_male").to(torch_device)
315-
outputs = model.generate(**inputs, generator=torch.Generator(torch_device).manual_seed(0))
316-
317-
# fmt: off
318-
expected_semantic_codes = [855, 7008, 7096, 6071, 1438, 855, 10, 10, 6226, 663, 3950, 2072, 8023, 8023, 8023, 10, 10, 10, 3684, 3684, 7973, 5246, 1]
319-
expected_first_frame = [855, 2, 15, 6, 6, 16, 10, 6, 6, 18, 5, 18, 5, 7, 20, 13, 11, 9, 6, 17, 10, 15, 7, 8, 14, 9, 9, 18, 21, 16, 20, 4, 6, 6, 17, 3, 4]
320-
# fmt: on
321-
self.assertEqual(outputs.audio_codes[0, :, 0].tolist(), expected_semantic_codes)
322-
self.assertEqual(outputs.audio_codes[0, 0].tolist(), expected_first_frame)
323-
self.assertEqual(outputs.audio[0].shape, (22 * model.config.codec_config.hop_length,))
402+
torch.testing.assert_close(audio[4000:4010], expected_slice, rtol=0, atol=1e-3)
403+
404+
def test_generate(self):
405+
inputs = self.processor(self.text, voice=self.voice).to(torch_device)
406+
outputs = self.model.generate(**inputs, generator=torch.Generator(torch_device).manual_seed(0))
407+
# The sentence lasts about 1.8 s (22 frames of 80 ms) and generation stops on `[END_AUDIO]`
408+
num_frames = int(outputs.audio_lengths[0])
409+
self.assertTrue(15 <= num_frames <= 30, num_frames)
410+
self.assertEqual(int(outputs.audio_codes[0, num_frames, 0]), 1)
411+
self.assertEqual(outputs.audio[0].shape, (num_frames * self.model.config.codec_config.hop_length,))

0 commit comments

Comments
 (0)