[Core][Model] Enable Qwen3-TTS MRV2 and optimize the TTS pipeline (#7781)

Signed-off-by: Sy03 <1370724210@qq.com>
This commit is contained in:
Sy03 authored and GitHub committed 2026-09-20 23:03:08 -07:00
1 parent d139c600c7
commit a9e2117f5e
103 files changed
+10232 -661

No files matched your search

@@ -682,14 +682,20 @@ class CodePredictorWrapper(nn.Module):
self._lm_heads_list: list[nn.Module] | None = None
self._codec_embeds_list: list[nn.Module] | None = None
self._device_graphs: dict[int | tuple[int, int], tuple] = {} # (graph, static_output) per bucket
# Outer-runner execution buckets when a model host declares them (MRv2);
# ``None`` keeps the legacy power-of-two bucket derivation.
self._execution_batch_buckets: list[int] | None = None
prefix_graph_cfg = self._stage_connector_extra_config(vllm_config)
prefix_graphs_requested = self._parse_bool_config(prefix_graph_cfg.get("code_predictor_prefix_graphs"))
is_npu = current_omni_platform.is_npu()
self._prefix_graphs_enabled = prefix_graphs_requested and wrapper_config.use_cuda_graphs and not is_npu
if prefix_graphs_requested and not self._prefix_graphs_enabled:
# MRv2 captures the whole Talker MTP call. It can therefore capture
# shorter compiled re-prefill forwards without nesting predictor-owned
# CUDA graphs inside the outer graph.
self._prefix_reprefill_enabled = prefix_graphs_requested and not is_npu
self._prefix_graphs_enabled = self._prefix_reprefill_enabled and wrapper_config.use_cuda_graphs
if prefix_graphs_requested and not self._prefix_reprefill_enabled:
logger.info_once(
"code_predictor: prefix CUDA graphs requested but disabled because use_cuda_graphs=%s is_npu=%s",
wrapper_config.use_cuda_graphs,
"code_predictor: prefix re-prefill requested but disabled because is_npu=%s",
is_npu,
)
self._prefix_graph_buckets = self._parse_positive_int_set(
@@ -698,6 +704,7 @@ class CodePredictorWrapper(nn.Module):
self._prefix_graph_seq_lens = self._parse_positive_int_set(
prefix_graph_cfg.get("code_predictor_prefix_graph_seq_lens")
)
self._prefix_reprefill_seq_lens = tuple(self._prefix_seq_lens(self._num_groups + 1))
def get_input_embeddings(self) -> nn.ModuleList:
return self.model.get_input_embeddings()
@@ -761,7 +768,8 @@ class CodePredictorWrapper(nn.Module):
dynamic=False,
options={"epilogue_fusion": False},
)
self._warmup_buckets()
with torch._dynamo.config.patch(cache_size_limit=self._compile_cache_size_limit()):
self._warmup_buckets()
if self._wrapper_config.use_cuda_graphs:
self._capture_cuda_graphs()
@@ -770,7 +778,7 @@ class CodePredictorWrapper(nn.Module):
logger.info("code_predictor: torch.compile (dynamic=False, no epilogue fusion)")
def _padded_bsz(self, bsz: int) -> int:
"""Round batch size up to nearest power-of-2 bucket."""
"""Round batch size up to the nearest warmed bucket."""
for bucket in self._bucket_sizes:
if bsz <= bucket:
return bucket
@@ -832,15 +840,28 @@ class CodePredictorWrapper(nn.Module):
return row_generators
@classmethod
def _sample_codes_gumbel(cls, logits: torch.Tensor, generator: _GeneratorLike = None) -> torch.Tensor:
"""Sample ``logits`` via Gumbel-max with optional per-row generators."""
row_generators = cls._normalize_generators(generator, int(logits.shape[0]))
u = torch.empty_like(logits, dtype=torch.float32)
if isinstance(row_generators, list):
for row, row_generator in enumerate(row_generators):
u[row : row + 1].uniform_(_UNIFORM_EPS, 1.0 - _UNIFORM_EPS, generator=row_generator)
def _sample_codes_gumbel(
cls,
logits: torch.Tensor,
generator: _GeneratorLike = None,
uniforms: torch.Tensor | None = None,
) -> torch.Tensor:
"""Sample ``logits`` via Gumbel-max with optional precomputed noise."""
if uniforms is None:
row_generators = cls._normalize_generators(generator, int(logits.shape[0]))
u = torch.empty_like(logits, dtype=torch.float32)
if isinstance(row_generators, list):
for row, row_generator in enumerate(row_generators):
u[row : row + 1].uniform_(_UNIFORM_EPS, 1.0 - _UNIFORM_EPS, generator=row_generator)
else:
u.uniform_(_UNIFORM_EPS, 1.0 - _UNIFORM_EPS, generator=row_generators)
else:
u.uniform_(_UNIFORM_EPS, 1.0 - _UNIFORM_EPS, generator=row_generators)
if uniforms.shape != logits.shape:
raise ValueError(
f"precomputed sampling uniforms must match logits: uniforms={tuple(uniforms.shape)} "
f"logits={tuple(logits.shape)}"
)
u = uniforms
return (logits.float() - torch.log(-torch.log(u))).argmax(dim=-1, keepdim=True)
def _prefix_seq_lens(self, max_seq: int) -> list[int]:
@@ -850,13 +871,64 @@ class CodePredictorWrapper(nn.Module):
allowed = set(all_seq_lens)
return sorted(seq_len for seq_len in self._prefix_graph_seq_lens if seq_len in allowed)
def _warmup_buckets(self) -> None:
"""Warmup power-of-2 batch-size buckets to front-load Inductor compilation."""
@staticmethod
def _synchronize_warmup(device: torch.device) -> None:
if device.type != "cpu":
current_omni_platform.synchronize()
def configure_mtp_execution_buckets(self, sizes: Iterable[int]) -> None:
"""Declare the batch buckets the outer runner can actually reach.
Must be called before the first warmup; once buckets are captured the
existing set is only acceptable when it already covers the declaration
(never clear active graphs to rebuild them).
"""
max_bsz = int(self._vllm_config.scheduler_config.max_num_seqs)
cleaned = sorted({int(size) for size in sizes if 0 < int(size) <= max_bsz} | {max_bsz})
if self._bucket_sizes:
missing = [size for size in cleaned if size not in self._bucket_sizes]
if missing:
raise RuntimeError(
"mtp execution buckets must be configured before the first warmup; "
f"missing={missing} existing={self._bucket_sizes}"
)
return
self._execution_batch_buckets = cleaned
def _batch_bucket_sizes(self) -> list[int]:
max_bsz = self._vllm_config.scheduler_config.max_num_seqs
if self._execution_batch_buckets is not None:
# Outer-reachable buckets plus prefix-graph capture buckets and the
# full-size eager fallback row already merged at configure time.
bucket_sizes = list(self._execution_batch_buckets)
bucket_sizes.extend(bucket for bucket in self._prefix_graph_buckets if bucket <= max_bsz)
return sorted(set(bucket_sizes))
bucket_sizes = [1 << i for i in range(max_bsz.bit_length()) if (1 << i) <= max_bsz]
if max_bsz not in bucket_sizes:
bucket_sizes.append(max_bsz)
self._bucket_sizes = sorted(bucket_sizes)
bucket_sizes.extend(bucket for bucket in self._prefix_graph_buckets if bucket <= max_bsz)
bucket_sizes.append(max_bsz)
return sorted(set(bucket_sizes))
def _compile_cache_size_limit(self) -> int:
bucket_sizes = self._batch_bucket_sizes()
if not self._prefix_reprefill_enabled:
required_entries = len(bucket_sizes)
else:
prefix_buckets = (
self._prefix_graph_buckets.intersection(bucket_sizes)
if self._prefix_graph_buckets
else set(bucket_sizes)
)
prefix_seq_lens = self._prefix_reprefill_seq_lens
needs_full_graph = set(prefix_seq_lens) != set(range(2, self._num_groups + 1))
full_graph_entries = len(bucket_sizes) - len(prefix_buckets)
if needs_full_graph:
full_graph_entries += len(prefix_buckets)
required_entries = full_graph_entries + len(prefix_buckets) * len(prefix_seq_lens)
return max(torch._dynamo.config.cache_size_limit, required_entries)
def _warmup_buckets(self) -> None:
"""Warm up batch-size buckets to front-load Inductor compilation."""
self._bucket_sizes = self._batch_bucket_sizes()
max_seq = self._num_groups + 1
device = next(self.model.parameters()).device
@@ -866,8 +938,8 @@ class CodePredictorWrapper(nn.Module):
self._ensure_buffers(device, self._model_dtype, max(self._bucket_sizes))
proj_buf = self._proj_buf
if self._prefix_graphs_enabled:
prefix_seq_lens = self._prefix_seq_lens(max_seq)
if self._prefix_reprefill_enabled:
prefix_seq_lens = self._prefix_reprefill_seq_lens
needs_full_graph = set(prefix_seq_lens) != set(range(2, max_seq))
for bsz in self._bucket_sizes:
capture_prefixes = not self._prefix_graph_buckets or bsz in self._prefix_graph_buckets
@@ -905,6 +977,10 @@ class CodePredictorWrapper(nn.Module):
self._compiled_model_fwd(proj_buf[:bsz, :max_seq, :], pos_ids)
logger.info("code_predictor: warmup done for buckets %s", self._bucket_sizes)
# Compiled attention warmup is asynchronous. Complete it before graph
# capture and serving reuse the same static buffers.
self._synchronize_warmup(device)
def _capture_cuda_graphs(self) -> None:
"""Capture a CUDA graph per bucket using vLLM's global graph pool."""
from vllm.platforms import current_platform
@@ -914,7 +990,7 @@ class CodePredictorWrapper(nn.Module):
proj_buf = self._proj_buf
if self._prefix_graphs_enabled:
prefix_seq_lens = self._prefix_seq_lens(max_seq)
prefix_seq_lens = self._prefix_reprefill_seq_lens
needs_full_graph = set(prefix_seq_lens) != set(range(2, max_seq))
for bsz in self._bucket_sizes:
capture_prefixes = not self._prefix_graph_buckets or bsz in self._prefix_graph_buckets
@@ -1013,13 +1089,20 @@ class CodePredictorWrapper(nn.Module):
top_p: float = 1.0,
generator: torch.Generator | None = None,
generators: Sequence[torch.Generator | None] | None = None,
sample_uniforms: torch.Tensor | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
"""Predict residual codebooks 1..G-1 autoregressively via re-prefill."""
bsz = int(layer0_code.shape[0])
num_groups = self._num_groups
if generators is not None and len(generators) != bsz:
raise ValueError(f"generators must have one entry per row: got {len(generators)} for batch {bsz}")
if sample_uniforms is not None:
expected_shape = (bsz, num_groups - 1, int(self.config.vocab_size))
if tuple(sample_uniforms.shape) != expected_shape:
raise ValueError(
f"sample_uniforms must have shape {expected_shape}, got {tuple(sample_uniforms.shape)}"
)
sample_generator: _GeneratorLike = generators if generators is not None else generator
num_groups = self._num_groups
device = layer0_code.device
# _setup_compile caches _model_dtype on first call; use it for buffers
@@ -1072,11 +1155,16 @@ class CodePredictorWrapper(nn.Module):
for step in range(1, num_groups):
graph_key: int | tuple[int, int] = padded_bsz
seq_len = max_seq
if self._prefix_graphs_enabled:
prefix_key = (padded_bsz, step + 1)
if prefix_key in self._device_graphs:
graph_key = prefix_key
seq_len = step + 1
if self._prefix_reprefill_enabled:
actual_seq_len = step + 1
for prefix_seq_len in self._prefix_reprefill_seq_lens:
if prefix_seq_len < actual_seq_len:
continue
prefix_key = (padded_bsz, prefix_seq_len)
if prefix_key in self._bucket_pos_ids:
graph_key = prefix_key
seq_len = prefix_seq_len
break
pos_ids = self._bucket_pos_ids.get(graph_key)
if pos_ids is None:
pos_ids = (
@@ -1123,7 +1211,8 @@ class CodePredictorWrapper(nn.Module):
remove_mask = (cumulative_probs - sorted_probs) >= s_top_p
sorted_logits[remove_mask] = float("-inf")
logits = sorted_logits.scatter(1, sorted_idx, sorted_logits)
code = self._sample_codes_gumbel(logits, generator=sample_generator)
step_uniforms = sample_uniforms[:, step - 1, :] if sample_uniforms is not None else None
code = self._sample_codes_gumbel(logits, generator=sample_generator, uniforms=step_uniforms)
else:
# "per_call" mode: temperature-scaled + top-k -> Gumbel-max
if use_sampling:
@@ -1131,7 +1220,8 @@ class CodePredictorWrapper(nn.Module):
if top_k > 0:
topk_vals, _ = scaled.topk(top_k, dim=-1)
scaled = scaled.masked_fill(scaled < topk_vals[:, -1:], float("-inf"))
code = self._sample_codes_gumbel(scaled, generator=sample_generator)
step_uniforms = sample_uniforms[:, step - 1, :] if sample_uniforms is not None else None
code = self._sample_codes_gumbel(scaled, generator=sample_generator, uniforms=step_uniforms)
else:
code = logits.argmax(dim=-1, keepdim=True)