Skip to content

Commit ce615a0

Browse files
committed
Voxtral TTS: batch-invariant generation, skip finished rows, converter tests
- `generate` accepts one `torch.Generator` per batch element, so the audio of a sequence does not depend on the rest of the batch (on the released model in bf16, batched and single generations give identical codes). - Sequences that emitted `[END_AUDIO]` are dropped from the KV cache and every per-row tensor, instead of running the model until the longest one ends. - Tests for the conversion script on a tiny checkpoint in the original layout: strict loading, tensor-to-parameter mapping, RoPE permutation against the interleaved formulation, and weight-norm folding.
1 parent 0ce601f commit ce615a0

2 files changed

Lines changed: 338 additions & 14 deletions

File tree

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

Lines changed: 45 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def generate(
4949
attention_mask: torch.Tensor | None = None,
5050
max_new_frames: int = 2000,
5151
cfg_alpha: float = 1.2,
52-
generator: torch.Generator | None = None,
52+
generator: torch.Generator | list[torch.Generator] | None = None,
5353
output_audio: bool = True,
5454
codec_chunk_size: int | None = 375,
5555
**kwargs,
@@ -72,8 +72,10 @@ def generate(
7272
Maximum number of audio frames to generate (one frame is 80 ms of audio).
7373
cfg_alpha (`float`, *optional*, defaults to 1.2):
7474
Classifier-free guidance scale of the flow-matching velocity.
75-
generator (`torch.Generator`, *optional*):
76-
Random generator for the flow-matching noise, for reproducible generations.
75+
generator (`torch.Generator` or `list[torch.Generator]`, *optional*):
76+
Random generator(s) for the flow-matching noise, for reproducible generations. With one generator per
77+
batch element, each sequence draws its noise from its own generator, so its audio does not depend on
78+
the other sequences of the batch (up to numerical precision).
7779
output_audio (`bool`, *optional*, defaults to `True`):
7880
Whether to decode the generated codes into waveforms with the codec.
7981
codec_chunk_size (`int`, *optional*, defaults to 375):
@@ -89,6 +91,8 @@ def generate(
8991

9092
batch_size = input_ids.shape[0]
9193
device = input_ids.device
94+
if isinstance(generator, (list, tuple)) and len(generator) != batch_size:
95+
raise ValueError(f"Got {len(generator)} generators for a batch of {batch_size} sequences.")
9296
if attention_mask is None:
9397
attention_mask = torch.ones_like(input_ids)
9498
position_ids = (attention_mask.long().cumsum(-1) - 1).clamp(min=0)
@@ -105,24 +109,34 @@ def generate(
105109
last_hidden_state = outputs.last_hidden_state[:, -1]
106110
next_position_ids = position_ids[:, -1:] + 1
107111

112+
num_codebooks = self.config.num_codebooks
108113
frames = []
109-
finished = torch.zeros(batch_size, dtype=torch.bool, device=device)
110114
audio_lengths = torch.zeros(batch_size, dtype=torch.long, device=device)
115+
# Rows of the batch still generating: finished rows are dropped from the cache and every per-row tensor
116+
active_rows = list(range(batch_size))
111117
for _ in range(max_new_frames):
112-
frame = self.acoustic_transformer.generate_frame(
113-
last_hidden_state, cfg_alpha=cfg_alpha, generator=generator
118+
noise = self._sample_flow_matching_noise(generator, active_rows, device)
119+
active_frame = self.acoustic_transformer.generate_frame(
120+
last_hidden_state, cfg_alpha=cfg_alpha, noise=noise
114121
)
115-
frame[finished] = EMPTY_AUDIO_TOKEN
122+
frame = active_frame.new_full((batch_size, num_codebooks), EMPTY_AUDIO_TOKEN)
123+
frame[active_rows] = active_frame
116124
frames.append(frame)
117-
just_finished = (frame[:, 0] == END_AUDIO_TOKEN) & ~finished
118-
audio_lengths += (~finished & ~just_finished).long()
119-
finished |= just_finished
120-
if finished.all():
121-
break
122125

123-
attention_mask = torch.cat([attention_mask, attention_mask.new_ones((batch_size, 1))], dim=-1)
126+
ended = (active_frame[:, 0] == END_AUDIO_TOKEN).tolist()
127+
audio_lengths[[row for row, row_ended in zip(active_rows, ended) if not row_ended]] += 1
128+
if all(ended):
129+
break
130+
if any(ended):
131+
keep = [i for i, row_ended in enumerate(ended) if not row_ended]
132+
cache.batch_select_indices(torch.tensor(keep, device=device))
133+
active_rows = [active_rows[i] for i in keep]
134+
active_frame, attention_mask = active_frame[keep], attention_mask[keep]
135+
next_position_ids = next_position_ids[keep]
136+
137+
attention_mask = torch.cat([attention_mask, attention_mask.new_ones((len(active_rows), 1))], dim=-1)
124138
outputs = self.model(
125-
audio_codes=frame[:, None],
139+
audio_codes=active_frame[:, None],
126140
attention_mask=attention_mask,
127141
position_ids=next_position_ids,
128142
cache=cache,
@@ -154,3 +168,20 @@ def generate(
154168
audio = [audio_values[i, : int(audio_lengths[i]) * hop_length] for i in range(batch_size)]
155169

156170
return VoxtralTtsGenerateOutput(audio=audio, audio_codes=audio_codes, audio_lengths=audio_lengths)
171+
172+
def _sample_flow_matching_noise(
173+
self,
174+
generator: torch.Generator | list[torch.Generator] | None,
175+
active_rows: list[int],
176+
device: torch.device,
177+
) -> torch.Tensor:
178+
"""Initial acoustic latents (in float32) of the rows still generating."""
179+
num_acoustic_codebooks = self.config.acoustic_transformer_config.num_acoustic_codebooks
180+
if isinstance(generator, (list, tuple)):
181+
noise = [
182+
torch.randn(num_acoustic_codebooks, generator=generator[row], device=generator[row].device)
183+
for row in active_rows
184+
]
185+
return torch.stack([row_noise.to(device) for row_noise in noise])
186+
noise_device = generator.device if generator is not None else device
187+
return torch.randn((len(active_rows), num_acoustic_codebooks), generator=generator, device=noise_device)

0 commit comments

Comments
 (0)