[Perf] VoxCPM2: streaming VAE + compile optimization (45% RTF reduction) (#2758)

Signed-off-by: Yueqian Lin <linyueqian@outlook.com>
This commit is contained in:
Yueqian Lin authored and GitHub committed 2026-04-15 09:58:25 +08:00
1 parent 9e46a79c17
commit 02e5dc747d
6 files changed
+716 -79

No files matched your search

@@ -308,31 +308,28 @@ class MiniCPM4PagedForVoxCPM2(nn.Module):
return hidden_states
def compile_selective(self) -> list[str]:
"""Compile MLP + o_proj; keep RMSNorm/RoPE eager for precision."""
compiled: list[str] = []
for i, layer in enumerate(self.layers):
if i in self._compiled_layers:
continue
try:
layer.mlp = torch.compile(
layer.mlp,
mode="default",
fullgraph=True,
)
layer.self_attn.o_proj = torch.compile(
layer.self_attn.o_proj,
mode="default",
fullgraph=True,
)
layer.self_attn._fused_qkv_weight = None
self._compiled_layers.add(i)
if i == 0:
compiled.append(f"layers.*.mlp (×{len(self.layers)})")
compiled.append(f"layers.*.self_attn.o_proj (×{len(self.layers)})")
except Exception as e:
logger.warning("compile_selective: layer %d failed: %s", i, e)
break
return compiled
"""Compile the full model forward as one graph.
Earlier versions compiled ``layer.mlp`` + ``layer.self_attn.o_proj``
(PR #2690) and then the whole ``layer`` (perf/voxcpm2-streaming-vae).
Both still paid one Dynamo dispatch per layer per decode step.
V3 profiling showed 1,332 per-layer dispatches (~28 layers × ~47
decode steps) costing ~726 ms of CPU self-time for a long prompt.
Compiling ``forward`` at the model level lets Dynamo unroll the
28-layer Python loop inside the graph. Graph breaks at
PagedAttention produce sub-graphs but Dynamo memoises the whole
trace once, so the per-step dispatch drops from 28 to just a few.
"""
if self._compiled_layers:
return []
# Null the fused-qkv caches so the compile sees the real weight layout.
for layer in self.layers:
layer.self_attn._fused_qkv_weight = None
self.forward = torch.compile(self.forward, mode="default", fullgraph=False)
# Mark every layer as compiled so idempotent callers don't double-wrap.
self._compiled_layers.update(range(len(self.layers)))
return ["forward (whole model)"]
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
"""Load weights from native checkpoint (base_lm. prefix pre-stripped)."""
@@ -415,22 +412,14 @@ class MiniCPM4PagedResidualLM(nn.Module):
return hidden_states
def compile_selective(self) -> list[str]:
"""Compile MLP + o_proj (same as base_lm)."""
compiled: list[str] = []
for i, layer in enumerate(self.layers):
if i in self._compiled_layers:
continue
try:
layer.mlp = torch.compile(layer.mlp, mode="default", fullgraph=True)
layer.self_attn.o_proj = torch.compile(layer.self_attn.o_proj, mode="default", fullgraph=True)
layer.self_attn._fused_qkv_weight = None
self._compiled_layers.add(i)
if i == 0:
compiled.append(f"layers.*.mlp (×{len(self.layers)})")
compiled.append(f"layers.*.self_attn.o_proj (×{len(self.layers)})")
except Exception as e:
logger.warning("compile_selective: residual layer %d failed: %s", i, e)
return compiled
"""Compile the full residual model forward as one graph (same strategy as base_lm)."""
if self._compiled_layers:
return []
for layer in self.layers:
layer.self_attn._fused_qkv_weight = None
self.forward = torch.compile(self.forward, mode="default", fullgraph=False)
self._compiled_layers.update(range(len(self.layers)))
return ["forward (whole residual)"]
def load_weights_from_native(self, native_residual_lm: nn.Module) -> int:
"""Load weights from native residual_lm. Returns param count."""
@@ -11,6 +11,7 @@ Architecture:
from __future__ import annotations
import dataclasses
import logging
import os
import time
from collections.abc import Iterable
@@ -19,7 +20,6 @@ from typing import Any
import librosa
import torch
import torch.nn as nn
from einops import rearrange
from vllm.config import VllmConfig
from vllm.logger import init_logger
from vllm.model_executor.models.utils import (
@@ -86,7 +86,11 @@ class _RequestState:
curr_prefix_feat_cond: torch.Tensor | None = None
last_audio_patch_gpu: torch.Tensor | None = None
precomputed_stop_logits: torch.Tensor | None = None
accumulated_patches: list[torch.Tensor] = dataclasses.field(default_factory=list)
# Rolling tail of previously-decoded latents used as VAE receptive-field context.
# Shape (n_pad_frames, feat_dim) on GPU. None before first decode.
decode_pad: torch.Tensor | None = None
# Audio chunks already emitted (CPU float32), concatenated for cumulative output.
audio_chunks: list[torch.Tensor] = dataclasses.field(default_factory=list)
decode_step_count: int = 0
request_start_time: float = 0.0
prefill_completed: bool = False
@@ -229,11 +233,11 @@ def _optimized_solve_euler(
buffers.x_in[b : 2 * b].copy_(x)
buffers.mu_in[:b].copy_(mu)
buffers.mu_in[b : 2 * b].zero_()
buffers.t_in[:b].fill_(t.item())
buffers.t_in[b : 2 * b].fill_(t.item())
# Broadcast the 0-dim GPU scalar directly instead of
# ``.fill_(t.item())`` — ``.item()`` forces a GPU->CPU sync.
buffers.t_in[: 2 * b].copy_(t)
if mean_mode:
buffers.dt_in[:b].fill_(dt.item())
buffers.dt_in[b : 2 * b].fill_(dt.item())
buffers.dt_in[: 2 * b].copy_(dt)
else:
buffers.dt_in.zero_()
buffers.cond_in[:b].copy_(cond[:b])
@@ -263,9 +267,10 @@ def _optimized_solve_euler(
else:
buffers.x_in[:b].copy_(x)
buffers.mu_in[:b].copy_(mu)
buffers.t_in[:b].fill_(t.item())
# Broadcast the 0-dim GPU scalar; ``.fill_(t.item())`` would sync.
buffers.t_in[:b].copy_(t)
if mean_mode:
buffers.dt_in[:b].fill_(dt.item())
buffers.dt_in[:b].copy_(dt)
else:
buffers.dt_in[:b].zero_()
buffers.cond_in[:b].copy_(cond[:b])
@@ -320,7 +325,10 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
self._inference_timesteps = 10
self._cfg_value = 2.0
self._cfg_cutoff_ratio = 1.0
self._vae_decode_interval = 5
# Number of trailing latent frames to keep as VAE receptive-field context
# for sliding-window streaming decode. 12 matches the nanovllm reference
# implementation and covers the longest VAE decoder receptive field.
self._n_decode_pad_frames = 12
self._enable_torch_compile = True
self._compile_vae = True
self._max_decode_steps = 2000
@@ -686,7 +694,9 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
state.request_start_time = time.perf_counter()
state.prefill_completed = True
logger.info("PREFILL[%s]: patch norm=%.4f", state.request_id, pred_feat.norm().item())
if logger.isEnabledFor(logging.DEBUG):
# Only compute the norm (which forces a GPU->CPU sync) if we will log it.
logger.debug("PREFILL[%s]: patch norm=%.4f", state.request_id, pred_feat.norm().item())
self._perf.reset()
def _finish_decode(self, state: _RequestState, meta: dict, res_out: torch.Tensor, dev: Any):
@@ -720,26 +730,54 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
# -------------------- audio collection --------------------
def _collect_audio(self, state: _RequestState) -> torch.Tensor | None:
"""Per-step sliding-window VAE decode (nanovllm pattern).
Each decode step feeds ``[decode_pad, new_patch]`` through the VAE
and slices out only the audio region corresponding to the new patch.
The pad buffer (last ``_n_decode_pad_frames`` latent frames) provides
the receptive-field context needed by the VAE's transposed convolutions,
eliminating boundary artifacts between chunks.
Returns the delta audio chunk (not cumulative) so the output processor
can stream each chunk to the client independently.
"""
patch = state.last_audio_patch_gpu
if patch is not None:
state.last_audio_patch_gpu = None
state.accumulated_patches.append(patch.reshape(1, -1).float())
if not state.accumulated_patches:
if patch is None:
return None
state.last_audio_patch_gpu = None
n = len(state.accumulated_patches)
if n <= 1 or n % self._vae_decode_interval == 0 or state.is_stopping:
self._perf.start("vae_decode")
all_p = torch.cat(state.accumulated_patches, dim=0)
state.accumulated_patches = [all_p]
feat = rearrange(all_p.reshape(1, -1, self._feat_dim), "b t d -> b d t")
with torch.no_grad():
audio = self.tts.audio_vae.decode(feat.to(self._device)).reshape(-1).cpu().float()
self._perf.stop("vae_decode")
state.last_decoded_audio = audio
return audio
return state.last_decoded_audio
# patch shape: (patch_size, feat_dim) or (1, patch_size, feat_dim)
new_latent = patch.reshape(-1, self._feat_dim).to(torch.float32)
n_new = new_latent.shape[0] # = patch_size (typically 4)
self._perf.start("vae_decode")
# Build VAE input: [pad_frames | new_latent]
if state.decode_pad is not None:
vae_input = torch.cat([state.decode_pad, new_latent], dim=0)
pad_frames = state.decode_pad.shape[0]
else:
vae_input = new_latent
pad_frames = 0
# VAE decode: (1, feat_dim, T_frames) -> (1, 1, T_samples)
feat = vae_input.unsqueeze(0).transpose(1, 2).contiguous()
with torch.no_grad():
audio = self.tts.audio_vae.decode(feat.to(self._device)).reshape(-1)
# Slice out only the new audio (after the pad region).
# Each latent frame maps to decoder_chunk_size audio samples.
dcs = int(getattr(self.tts.audio_vae, "decode_chunk_size", audio.numel() // vae_input.shape[0]))
new_audio = audio[pad_frames * dcs : (pad_frames + n_new) * dcs].detach().cpu().float()
# Roll the pad buffer: keep last N latent frames as context for next step.
all_latents = vae_input # [pad + new]
state.decode_pad = all_latents[-self._n_decode_pad_frames :].detach()
state.audio_chunks.append(new_audio)
state.last_decoded_audio = new_audio
self._perf.stop("vae_decode")
return new_audio
# -------------------- compute_logits --------------------
@@ -830,7 +868,8 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
state = self._get_or_create_state(req_id)
state.prefill_text = ""
state.accumulated_patches = []
state.decode_pad = None
state.audio_chunks = []
state.prefill_completed = False
state.decode_step_count = 0
state.precomputed_stop_logits = None