[Perf][MiniCPM-O-4.5]Add CUDA Graph For HiFTGenerator (#5869)

Signed-off-by: boatman <109857087+sphinxkkkbc@users.noreply.github.com>
This commit is contained in:
boatman authored and GitHub committed 2026-08-09 22:29:49 +08:00
1 parent f01e4bdddc
commit fc8946fcf5
13 files changed
+509 -17

No files matched your search

@@ -4,6 +4,7 @@
from __future__ import annotations
from collections.abc import Mapping
from contextlib import nullcontext
from dataclasses import dataclass
from typing import Any
@@ -11,6 +12,11 @@ from typing import Any
import torch
import torch.nn as nn
import torch.nn.functional as F
from vllm.logger import init_logger
from .cuda_graph_wrapper import HiFTGraphWrapper
logger = init_logger(__name__)
_SILENCE_TOKEN = 4218
@@ -60,7 +66,14 @@ class BatchedToken2Wav(nn.Module):
asset loader and prompt feature extractor.
"""
def __init__(self, token2wav: Any, trt_stepper: Any | None = None):
def __init__(
self,
token2wav: Any,
trt_stepper: Any | None = None,
*,
connector_config: Mapping[str, int] | None = None,
hift_graph_config: Mapping[str, Any] | None = None,
):
super().__init__()
self._token2wav = token2wav
# Optional TrtDiTStepper (step_audio2_dit_trt): replaces only the
@@ -82,7 +95,7 @@ class BatchedToken2Wav(nn.Module):
_autocast_disabled(device),
):
# 50 mel frames match the default first streamed vocoder chunk.
speech, source = self.hift(
speech, source = self.hift.inference(
torch.zeros((1, mel_channels, 50), device=device, dtype=dtype),
torch.zeros((1, 1, 0), device=device, dtype=dtype),
)
@@ -98,8 +111,41 @@ class BatchedToken2Wav(nn.Module):
token2wav.speech_window.detach().clone(),
persistent=False,
)
self.hift_graph_wrapper: HiFTGraphWrapper | None = None
graph_config = dict(hift_graph_config or {})
if bool(graph_config.get("enabled", False)):
if hift_parameter is None:
raise ValueError("MiniCPM-o HiFT Graph requires a parameterized HiFT module")
if hift_parameter.device.type != "cuda":
logger.info("HiFT CUDA Graph is disabled on device type %s", hift_parameter.device.type)
else:
if connector_config is None:
raise ValueError("MiniCPM-o HiFT CUDA Graph requires connector chunk configuration")
if self.mel_cache_len <= 0 or self.source_cache_len % self.mel_cache_len != 0:
raise ValueError(
"MiniCPM-o HiFT CUDA Graph requires source_cache_len to be divisible by mel_cache_len"
)
capture_batch_sizes = graph_config.get("capture_batch_sizes", [1])
logger.info("Enabling HiFT CUDA Graph with batch sizes %s", capture_batch_sizes)
self.hift_graph_wrapper = HiFTGraphWrapper(
token2wav=token2wav,
connector_config=dict(connector_config),
capture_batch_sizes=capture_batch_sizes,
)
with torch.inference_mode(), _autocast_disabled(hift_parameter.device):
self.hift_graph_wrapper.capture()
logger.info("HiFT CUDA Graph captured successfully")
self._prompt_features: dict[tuple[str, str], PromptFeatures] = {}
def _hift_inference(
self,
mel: torch.Tensor,
source_cache: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
if self.hift_graph_wrapper is None:
return self.hift.inference(mel, source_cache)
return self.hift_graph_wrapper.replay(mel, source_cache)
def prepare_prompt(self, prompt_cache_id: str, prompt_wav: str) -> PromptFeatures:
cache_key = (prompt_cache_id, prompt_wav)
cached = self._prompt_features.get(cache_key)
@@ -463,7 +509,7 @@ class BatchedToken2Wav(nn.Module):
old_source = torch.cat([state.hift_cache["source"] for state in states], dim=0)
old_speech = torch.cat([state.hift_cache["speech"] for state in states], dim=0)
mel = torch.cat((old_mel, chunk_mel), dim=2)
speech, source = self.hift(mel, old_source)
speech, source = self._hift_inference(mel, old_source)
if old_speech.shape[-1] > 0:
window = self.speech_window.to(device=speech.device, dtype=speech.dtype)
speech = self._fade_in_out(speech, old_speech, window)
@@ -0,0 +1,135 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
from torch.cuda import CUDAGraph
from vllm.logger import init_logger
from vllm.platforms import current_platform
logger = init_logger(__name__)
class HiFTGraphWrapper:
def __init__(self, token2wav, connector_config, capture_batch_sizes):
self.decode_fn = token2wav.hift.inference
self.graph_fn = token2wav.hift._inference_pre_istft
self.finalize_fn = token2wav.hift._finalize_decode
self.codec_chunk_frames = connector_config["codec_chunk_frames"]
self.codec_left_context_frames = connector_config["codec_left_context_frames"]
lookahead_layer = getattr(token2wav.flow.encoder, "pre_lookahead_layer", None)
pre_lookahead_len = getattr(lookahead_layer, "pre_lookahead_len", None)
self.pre_lookahead_len = int(pre_lookahead_len) if pre_lookahead_len is not None else 3
self.mel_cache_len = int(token2wav.mel_cache_len)
self.source_cache_len = int(token2wav.source_cache_len)
self.mel_frames = int(token2wav.hift.conv_pre.in_channels)
self.flow_upsample_rate = int(getattr(token2wav.flow, "token_mel_ratio", 2))
self.capture_bucket_size, self.capture_source_cache_len = self.derive_capture_bucket_size()
self.capture_batch_sizes = capture_batch_sizes
self.graph: dict[tuple[int, int, int], torch.cuda.CUDAGraph] = {}
self.static_speech_inputs: dict[tuple[int, int, int], torch.Tensor] = {}
self.static_magnitude_outputs: dict[tuple[int, int, int], torch.Tensor] = {}
self.static_phase_outputs: dict[tuple[int, int, int], torch.Tensor] = {}
self.static_cache_source_inputs: dict[tuple[int, int, int], torch.Tensor] = {}
self.static_cache_source_outputs: dict[tuple[int, int, int], torch.Tensor] = {}
parameter = next(token2wav.hift.parameters())
self.device = parameter.device
self.dtype = parameter.dtype
self.max_lazy_graphs = 8
self.lazy_graph_count = 0
def derive_capture_bucket_size(self):
chunk_mel_frames = (
self.codec_chunk_frames + self.codec_left_context_frames - self.pre_lookahead_len
) * self.flow_upsample_rate
return [chunk_mel_frames, chunk_mel_frames + self.mel_cache_len], [
0,
self.source_cache_len,
]
def capture(self):
for batch_size in self.capture_batch_sizes:
for mel_frames, source_cache_len in zip(
self.capture_bucket_size,
self.capture_source_cache_len,
strict=True,
):
self._capture(batch_size, mel_frames, source_cache_len)
def _capture(
self,
batch_size: int,
mel_frames: int,
source_cache_len: int,
):
if torch.cuda.is_current_stream_capturing():
raise RuntimeError("Cannot capture HiFT graph during an active stream capture")
key = (batch_size, mel_frames, source_cache_len)
if key in self.graph:
return
static_mel = torch.zeros(batch_size, self.mel_frames, mel_frames, device=self.device, dtype=self.dtype)
static_source_cache = torch.zeros(batch_size, 1, source_cache_len, device=self.device, dtype=self.dtype)
current_stream = torch.cuda.current_stream(self.device)
warmup_stream = torch.cuda.Stream(device=self.device)
warmup_stream.wait_stream(current_stream)
with torch.cuda.stream(warmup_stream), torch.no_grad():
for _ in range(3):
warmup_outputs = self.graph_fn(static_mel, static_source_cache)
current_stream.wait_stream(warmup_stream)
del warmup_outputs
graph = CUDAGraph()
with torch.cuda.graph(graph, pool=current_platform.get_global_graph_pool()):
static_magnitude_output, static_phase_output, static_cache_source_output = self.graph_fn(
static_mel,
static_source_cache,
)
self.graph[key] = graph
self.static_speech_inputs[key] = static_mel
self.static_cache_source_inputs[key] = static_source_cache
self.static_magnitude_outputs[key] = static_magnitude_output
self.static_phase_outputs[key] = static_phase_output
self.static_cache_source_outputs[key] = static_cache_source_output
logger.info("Captured HiFT CUDA Graph for shape %s", key)
def replay(self, speech_feat, cache_source):
if torch.cuda.is_current_stream_capturing():
logger.info("Falling back to eager HiFT inference during an active stream capture")
return self.decode_fn(speech_feat, cache_source)
batch_size = speech_feat.shape[0]
num_frames = speech_feat.shape[2]
cache_source_len = cache_source.shape[2]
target_b = next((b for b in sorted(self.capture_batch_sizes) if b >= batch_size), None)
if target_b is None:
logger.info("Falling back to eager HiFT inference for unsupported batch size %d", batch_size)
return self.decode_fn(speech_feat, cache_source)
key = (target_b, num_frames, cache_source_len)
if key not in self.graph:
if self.lazy_graph_count >= self.max_lazy_graphs:
logger.info("Falling back to eager HiFT inference after reaching the lazy Graph limit")
return self.decode_fn(speech_feat, cache_source)
logger.info("Lazily capturing HiFT CUDA Graph for shape %s", key)
self._capture(*key)
self.lazy_graph_count += 1
static_speech_inputs = self.static_speech_inputs[key].zero_()
static_speech_inputs[:batch_size].copy_(speech_feat)
static_cache_sources = self.static_cache_source_inputs[key].zero_()
static_cache_sources[:batch_size].copy_(cache_source)
self.graph[key].replay()
static_magnitude_output = self.static_magnitude_outputs[key]
static_phase_output = self.static_phase_outputs[key]
static_cache_source_output = self.static_cache_source_outputs[key]
cache_source = static_cache_source_output[:batch_size].clone()
speech = self.finalize_fn(static_magnitude_output[:batch_size], static_phase_output[:batch_size]).clone()
return speech, cache_source
@@ -150,6 +150,18 @@ class MiniCPMO45Code2Wav(nn.Module):
prefix="minicpmo45-runtime-prompts-",
)
extra = self._extra_config()
self._connector_config = {
"codec_chunk_frames": int(extra.get("codec_chunk_frames", 25)),
"codec_left_context_frames": int(extra.get("codec_left_context_frames", 3)),
}
if self._connector_config["codec_chunk_frames"] <= 0 or self._connector_config["codec_left_context_frames"] < 0:
raise ValueError(f"Invalid MiniCPM-o connector chunk configuration: {self._connector_config}")
raw_capture_batch_sizes = extra.get("hift_graph_capture_batch_sizes")
capture_batch_sizes = [1] if raw_capture_batch_sizes is None else raw_capture_batch_sizes
self._hift_graph_config = {
"enabled": bool(extra.get("enable_hift_graph", False)),
"capture_batch_sizes": capture_batch_sizes,
}
self._min_batch_size = int(extra.get("code2wav_min_batch_size", 1))
if self._min_batch_size < 1:
raise ValueError("MiniCPM-o Code2Wav code2wav_min_batch_size must be >= 1")
@@ -785,4 +797,9 @@ class MiniCPMO45Code2Wav(nn.Module):
logger.info("MiniCPM-o Code2Wav: DiT estimator running on TensorRT (%s)", dtype_name)
token2wav.enable_trt_spk_embedding()
logger.info("MiniCPM-o Code2Wav: campplus speaker embedding running on TensorRT")
self.backend = BatchedToken2Wav(token2wav, trt_stepper=trt_stepper)
self.backend = BatchedToken2Wav(
token2wav,
trt_stepper=trt_stepper,
connector_config=self._connector_config,
hift_graph_config=self._hift_graph_config,
)