[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)
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from typing import NamedTuple
import torch
@@ -6,6 +9,18 @@ from vllm.sequence import IntermediateTensors
from vllm_omni.data_entry_keys import OmniPayload
class OwnedBatchTensor(NamedTuple):
"""A batch tensor whose producer transfers ownership to the buffer.
The producer must have freshly allocated the tensor (e.g. an index_select
result) and must not write it afterwards. The buffer keeps row views
instead of taking a second snapshot. Tensors without this marker are
treated as borrowed (graph output / shared scratch) and still get a clone.
"""
tensor: torch.Tensor
class OmniOutput(NamedTuple):
"""Output from the merged Omni model containing both text and audio."""
@@ -179,6 +179,7 @@ class Qwen3OmniMoeForConditionalGeneration(
# vLLM run with no talker stage downstream, so no one consumes captured
# thinker layers and the forward must return what stock vLLM expects.
self.is_staged_run = getattr(vllm_config.model_config, "model_stage", None) is not None
self._returns_tuple = self.model_stage == "thinker" and self.is_staged_run
if self.model_stage == "thinker":
self.use_async_omni_output = True
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# Copyright 2026 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -533,6 +536,10 @@ class Qwen3TTSConfig(PretrainedConfig):
if any("Code2Wav" in str(a) for a in archs):
if hasattr(config, "rope_parameters"):
delattr(config, "rope_parameters")
# Code2Wav doesn't use position embeddings, but vLLM validates
# max_model_len <= max_position_embeddings. Set a large value
# to allow the pipeline.yaml max_model_len (65536) to pass validation.
config.max_position_embeddings = 131072
return config
@@ -1,5 +1,6 @@
# Copyright 2026 The Alibaba Qwen team.
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""
CUDA Graph wrapper for Qwen3TTSTokenizerV2Decoder.
@@ -8,10 +9,8 @@ reducing kernel launch overhead during inference.
"""
import bisect
import os
import time
from collections import Counter
from collections.abc import Callable, Sequence
from collections.abc import Callable, Collection, Sequence
import torch
from torch.cuda import CUDAGraph
@@ -187,22 +186,6 @@ class CUDAGraphDecoderWrapper:
self._warmed_up = False
self._device = None
self._stats_enabled = os.environ.get("VLLM_OMNI_QWEN3_CODE2WAV_CUDAGRAPH_STATS", "").lower() in (
"1",
"true",
"yes",
"on",
)
self._stats_log_every = int(os.environ.get("VLLM_OMNI_QWEN3_CODE2WAV_CUDAGRAPH_STATS_LOG_EVERY", "0") or 0)
self._stats_total = 0
self._stats_hits = 0
self._stats_compiled_hits = 0
self._stats_fallbacks = 0
self._stats_stream_capture_fallbacks = 0
self._stats_requests: Counter[tuple[int, int]] = Counter()
self._stats_hit_shapes: Counter[tuple[int, int, int]] = Counter()
self._stats_compiled_shapes: Counter[tuple[int, int]] = Counter()
self._stats_fallback_shapes: Counter[tuple[int, int, int]] = Counter()
@staticmethod
def compute_capture_sizes(
@@ -244,57 +227,19 @@ class CUDAGraphDecoderWrapper:
shapes.update(self.extra_capture_shapes)
return sorted(shapes)
def _record_decode_stats(
self,
*,
hit: bool,
batch_size: int,
@staticmethod
def _select_replay_shape(
actual_batch_size: int,
actual_size: int,
padded_size: int | None,
stream_capture: bool = False,
compiled: bool = False,
) -> None:
if not self._stats_enabled:
return
padded_key = int(padded_size) if padded_size is not None else -1
self._stats_total += 1
self._stats_requests[(batch_size, actual_size)] += 1
if hit:
self._stats_hits += 1
if compiled:
self._stats_compiled_hits += 1
self._stats_compiled_shapes[(batch_size, actual_size)] += 1
else:
self._stats_hit_shapes[(batch_size, actual_size, padded_key)] += 1
else:
self._stats_fallbacks += 1
self._stats_fallback_shapes[(batch_size, actual_size, padded_key)] += 1
if stream_capture:
self._stats_stream_capture_fallbacks += 1
if self._stats_log_every > 0 and self._stats_total % self._stats_log_every == 0:
self.log_decode_stats()
def log_decode_stats(self) -> None:
if not self._stats_enabled or self._stats_total == 0:
return
hit_rate = 100.0 * self._stats_hits / self._stats_total
logger.info(
"Code2Wav CUDA Graph stats: total=%d hits=%d fallbacks=%d "
"compiled_hits=%d stream_capture_fallbacks=%d hit_rate=%.2f%% "
"top_requests=%s top_compiled=%s top_hits=%s top_fallbacks=%s",
self._stats_total,
self._stats_hits,
self._stats_fallbacks,
self._stats_compiled_hits,
self._stats_stream_capture_fallbacks,
hit_rate,
self._stats_requests.most_common(12),
self._stats_compiled_shapes.most_common(12),
self._stats_hit_shapes.most_common(12),
self._stats_fallback_shapes.most_common(12),
available_shapes: Collection[tuple[int, int]],
) -> tuple[int, int] | None:
"""Select the lowest-cost captured shape that contains the request."""
candidates = (
(batch_size, size)
for batch_size, size in available_shapes
if batch_size >= actual_batch_size and size >= actual_size
)
return min(candidates, key=lambda shape: (shape[0] * shape[1], shape[0], shape[1]), default=None)
def warmup(
self,
@@ -486,68 +431,42 @@ class CUDAGraphDecoderWrapper:
# outside the startup capture window, so normal inference still hits
# the graph fast path.
if torch.cuda.is_current_stream_capturing():
self._record_decode_stats(
hit=False,
batch_size=int(codes.shape[0]),
actual_size=int(codes.shape[-1]),
padded_size=None,
stream_capture=True,
)
return self.decoder(codes)
batch_size = int(codes.shape[0])
actual_size = int(codes.shape[-1])
padded_size = self._get_padded_size(actual_size)
compile_key = (batch_size, actual_size)
if compile_key not in self._compiled_shapes and padded_size is not None:
compile_key = (batch_size, padded_size)
if compile_key in self._compiled_shapes:
compile_key = self._select_replay_shape(batch_size, actual_size, self._compiled_shapes)
if compile_key is not None:
compiled_size = compile_key[1]
self._record_decode_stats(
hit=True,
batch_size=batch_size,
actual_size=actual_size,
padded_size=compiled_size,
compiled=True,
)
static_input = self._compiled_static_inputs[compile_key]
if actual_size == compiled_size:
if actual_size == compiled_size and batch_size == compile_key[0]:
static_input.copy_(codes)
else:
static_input.zero_()
static_input[:, :, :actual_size] = codes
static_input[:batch_size, :, :actual_size] = codes
self._compiled_graphs[compile_key].replay()
output = self._trim_replay_output(self._compiled_static_outputs[compile_key], actual_size, compiled_size)
output = output[:batch_size]
if clone_graph_output:
return output.clone()
return output
graph_key = (batch_size, padded_size) if padded_size is not None else None
graph_key = self._select_replay_shape(batch_size, actual_size, self.graphs)
if graph_key is None or graph_key not in self.graphs:
self._record_decode_stats(
hit=False,
batch_size=batch_size,
actual_size=actual_size,
padded_size=padded_size,
)
if graph_key is None:
return self.decoder(codes)
self._record_decode_stats(
hit=True,
batch_size=batch_size,
actual_size=actual_size,
padded_size=padded_size,
)
static_input = self.static_inputs[graph_key]
if actual_size == padded_size:
graph_size = graph_key[1]
if actual_size == graph_size and batch_size == graph_key[0]:
static_input.copy_(codes)
else:
static_input.zero_()
static_input[:, :, :actual_size] = codes
static_input[:batch_size, :, :actual_size] = codes
self.graphs[graph_key].replay()
output = self._trim_replay_output(self.static_outputs[graph_key], actual_size, padded_size)
output = self._trim_replay_output(self.static_outputs[graph_key], actual_size, graph_size)
output = output[:batch_size]
if clone_graph_output:
return output.clone()
return output
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Qwen3-TTS pipeline: Talker (text → RVQ codec) → Code2Wav (codec → audio).
Chunked vs end-to-end mode is dispatched from ``deploy.async_chunk``.
@@ -41,6 +41,7 @@ QWEN3_TTS_PIPELINE = PipelineConfig(
owns_tokenizer=True,
engine_output_type="latent",
async_chunk_process_next_stage_input_func=(f"{_PROC}.talker2code2wav_async_chunk"),
supports_native_mrv2_data_plane=True,
custom_process_next_stage_input_func=f"{_PROC}.talker2code2wav_full_payload",
sampling_constraints={
"detokenize": False,
@@ -56,6 +57,7 @@ QWEN3_TTS_PIPELINE = PipelineConfig(
final_output_type="audio",
engine_output_type="audio",
model_arch="Qwen3TTSCode2Wav",
supports_native_mrv2_data_plane=True,
# ``sync_process_input_func`` is the only input-proc override for
# this stage in sync (non-async-chunk) mode: a length-only
# ``_token_only`` placeholder. The bulk codec payload itself
@@ -198,10 +198,6 @@ def mel_spectrogram(
hann_window: torch.Tensor | None = None,
) -> torch.Tensor:
"""Mel spectrogram via torch STFT and a (cached) mel filterbank."""
if torch.min(y) < -1.0:
logger.warning("Min value of input waveform signal is %s", torch.min(y))
if torch.max(y) > 1.0:
logger.warning("Max value of input waveform signal is %s", torch.max(y))
device = y.device
if mel_basis is None:
mel_basis = _cached_mel_filter_bank(sampling_rate, n_fft, num_mels, fmin, fmax).to(device)
@@ -350,7 +346,7 @@ class Qwen3TTSPromptEmbedsBuilder:
tts_pad_embed: torch.Tensor,
encode_ref_audio_batch: Callable[..., list[torch.Tensor]],
speaker_cache: Any | None = None,
ref_audio_artifact_cache_max_entries: int = 256,
ref_audio_artifact_cache_max_entries: int = 1024,
):
self._config = config
self._talker_config = talker_config
@@ -366,9 +362,14 @@ class Qwen3TTSPromptEmbedsBuilder:
self._embedding_dtype = torch.bfloat16
self._text_tokenizer: Any | None = None
# Projected special-token embeddings are immutable model constants.
# Reusing them avoids launching the embedding/projection pair once per
# request during prompt construction.
self._projected_token_cache: dict[tuple[str, tuple[int, ...]], torch.Tensor] = {}
self._ref_audio_artifact_cache_max_entries = int(ref_audio_artifact_cache_max_entries)
self._ref_audio_artifact_cache: OrderedDict[str, dict[str, torch.Tensor | bool]] = OrderedDict()
self._long_tensor_cache: dict[tuple[str, tuple[int, ...]], torch.Tensor] = {}
# Bounded LRU; caller-supplied orig_sr can otherwise grow this without limit.
self._resampler_cache: OrderedDict[tuple[int, int], AudioResampler] = OrderedDict()
@@ -384,6 +385,29 @@ class Qwen3TTSPromptEmbedsBuilder:
"""Return the pad-token embedding on the requested device/dtype, shape ``[1, 1, H]``."""
return self._tts_pad_embed_buffer.to(device=device, dtype=dtype).reshape(1, 1, -1)
def _long_tensor(self, values: Sequence[int], device: torch.device) -> torch.Tensor:
device = torch.device(device)
if device.type == "cuda" and device.index is None:
device = torch.device("cuda", torch.accelerator.current_device_index())
key = (str(device), tuple(int(v) for v in values))
cache = getattr(self, "_long_tensor_cache", None)
if cache is None:
cache = self._long_tensor_cache = {}
cached = cache.get(key)
if cached is None or cached.device != device:
cached = torch.tensor([list(key[1])], device=device, dtype=torch.long)
cache[key] = cached
return cached
def _projected_tokens(self, values: Sequence[int], device: torch.device) -> torch.Tensor:
device = torch.device(device)
key = (str(device), tuple(int(v) for v in values))
cached = self._projected_token_cache.get(key)
if cached is None:
cached = self._text_projection(self._text_embedding(self._long_tensor(values, device)))
self._projected_token_cache[key] = cached
return cached
def _get_resampler(self, orig_sr: int, target_sr: int) -> AudioResampler:
key = (int(orig_sr), int(target_sr))
cache = self._resampler_cache
@@ -631,9 +655,9 @@ class Qwen3TTSPromptEmbedsBuilder:
if entry is None:
entry = {}
if isinstance(ref_code, torch.Tensor):
entry["ref_code"] = ref_code.detach().to("cpu", dtype=torch.long).contiguous()
entry["ref_code"] = ref_code.detach().to(dtype=torch.long).contiguous()
if isinstance(ref_spk_embedding, torch.Tensor):
entry["ref_spk_embedding"] = ref_spk_embedding.detach().to("cpu", dtype=self._embedding_dtype).reshape(-1)
entry["ref_spk_embedding"] = ref_spk_embedding.detach().to(dtype=self._embedding_dtype).reshape(-1)
if not entry:
return
self._ref_audio_artifact_cache[cache_key] = entry
@@ -659,7 +683,6 @@ class Qwen3TTSPromptEmbedsBuilder:
self._speaker_encoder.to(device=dev, dtype=dtype)
except StopIteration:
pass
# Resample to 24kHz for speaker encoder.
target_sr = int(getattr(self._config.speaker_encoder_config, "sample_rate", 24000))
if sr != target_sr:
@@ -761,6 +784,23 @@ class Qwen3TTSPromptEmbedsBuilder:
req_ids: list[str],
model_intermediate_buffer: dict[str, dict[str, Any]],
device: torch.device,
) -> None:
"""MRv1 adapter for the request-info batch implementation."""
self.preprocess_infos_batch(
req_infos=[
info_dict
for req_id in req_ids
if isinstance((info_dict := model_intermediate_buffer.get(req_id)), dict)
],
device=device,
)
@torch.inference_mode()
def preprocess_infos_batch(
self,
*,
req_infos: list[dict[str, Any]],
device: torch.device,
) -> None:
"""Batch Base voice-clone ref-audio codec extraction for current prefill requests.
@@ -775,11 +815,7 @@ class Qwen3TTSPromptEmbedsBuilder:
pending_text: list[tuple[dict[str, Any], str]] = []
pending_ref_text: list[tuple[dict[str, Any], str]] = []
groups: dict[int, list[tuple[dict[str, Any], np.ndarray, int]]] = {}
for req_id in req_ids:
info_dict = model_intermediate_buffer.get(req_id)
if not isinstance(info_dict, dict):
continue
for info_dict in req_infos:
if (
self._needs_initial_prompt_preprocess(info_dict)
and first_value(info_dict.get("task_type"), "CustomVoice") == "Base"
@@ -837,17 +873,31 @@ class Qwen3TTSPromptEmbedsBuilder:
except Exception as exc:
logger.debug("Qwen3-TTS batched text tokenization failed; falling back to serial path: %s", exc)
continue
input_ids = tokenized.get("input_ids") if isinstance(tokenized, dict) else None
input_ids = tokenized.get("input_ids") if isinstance(tokenized, Mapping) else None
if not isinstance(input_ids, list) or len(input_ids) != len(items):
continue
valid_items: list[tuple[dict[str, Any], int]] = []
flat_ids: list[int] = []
for (info_dict, _), ids in zip(items, input_ids, strict=True):
if isinstance(ids, list) and ids:
info_dict[key] = torch.tensor(ids, dtype=torch.long)
if not (
isinstance(ids, list)
and ids
and all(isinstance(token_id, (int, np.integer)) for token_id in ids)
):
continue
valid_items.append((info_dict, len(ids)))
flat_ids.extend(int(token_id) for token_id in ids)
if not valid_items:
continue
use_async_h2d = device.type == "cuda"
packed_ids_cpu = torch.tensor(flat_ids, dtype=torch.long, pin_memory=use_async_h2d)
packed_ids = packed_ids_cpu.to(device=device, non_blocking=use_async_h2d)
offset = 0
for info_dict, num_ids in valid_items:
info_dict[key] = packed_ids.narrow(0, offset, num_ids)
offset += num_ids
groups = {sr: items for sr, items in groups.items() if len(items) >= 2}
if not groups:
return
for sr, items in groups.items():
wavs = [wav for _, wav, _ in items]
try:
@@ -892,9 +942,7 @@ class Qwen3TTSPromptEmbedsBuilder:
codec_embed_sum = torch.cat(codec_embed, dim=1).sum(1).unsqueeze(0) # [1,T,H]
codec_embed_sum = torch.cat(
[
self._codec_embed(
torch.tensor([[self._talker_config.codec_bos_id]], device=codec_embed_sum.device, dtype=torch.long)
),
self._codec_embed(self._long_tensor([self._talker_config.codec_bos_id], codec_embed_sum.device)),
codec_embed_sum,
],
dim=1,
@@ -990,12 +1038,8 @@ class Qwen3TTSPromptEmbedsBuilder:
# tts special token embeds (projected into talker hidden).
# ``tts_pad_embed`` is precomputed (request-independent), so we only
# need bos/eos here.
tts_tokens = torch.tensor(
[[config.tts_bos_token_id, config.tts_eos_token_id]],
device=input_ids.device,
dtype=input_ids.dtype,
)
tts_bos_embed, tts_eos_embed = text_projection(text_embedding(tts_tokens)).chunk(2, dim=1)
projected_tts = self._projected_tokens([config.tts_bos_token_id, config.tts_eos_token_id], input_ids.device)
tts_bos_embed, tts_eos_embed = projected_tts.chunk(2, dim=1)
tts_pad_embed = self._pad_embed(input_ids.device, tts_bos_embed.dtype)
# Codec prefill tags.
@@ -1032,9 +1076,9 @@ class Qwen3TTSPromptEmbedsBuilder:
]
]
codec_input_0 = codec_embed(torch.tensor(codec_prefill_list, device=input_ids.device, dtype=torch.long))
codec_input_0 = codec_embed(self._long_tensor(codec_prefill_list[0], input_ids.device))
codec_input_1 = codec_embed(
torch.tensor([[talker_config.codec_pad_id, talker_config.codec_bos_id]], device=input_ids.device)
self._long_tensor([talker_config.codec_pad_id, talker_config.codec_bos_id], input_ids.device)
)
# Speaker embedding/token (task-dependent)
@@ -1339,7 +1383,7 @@ class Qwen3TTSPromptEmbedsBuilder:
talker_prompt,
text_all + codec_embed(pad_ids),
tts_pad_embed
+ codec_embed(torch.tensor([[talker_config.codec_bos_id]], device=input_ids.device)),
+ codec_embed(self._long_tensor([talker_config.codec_bos_id], input_ids.device)),
],
dim=1,
)
@@ -1392,8 +1436,7 @@ class Qwen3TTSPromptEmbedsBuilder:
[
talker_prompt,
text_all + codec_embed(pad_ids),
tts_pad_embed
+ codec_embed(torch.tensor([[talker_config.codec_bos_id]], device=input_ids.device)),
tts_pad_embed + codec_embed(self._long_tensor([talker_config.codec_bos_id], input_ids.device)),
],
dim=1,
)
@@ -1431,8 +1474,7 @@ class Qwen3TTSPromptEmbedsBuilder:
[
talker_prompt,
text_all + codec_embed(pad_ids),
tts_pad_embed
+ codec_embed(torch.tensor([[talker_config.codec_bos_id]], device=input_ids.device)),
tts_pad_embed + codec_embed(self._long_tensor([talker_config.codec_bos_id], input_ids.device)),
],
dim=1,
)
@@ -46,9 +46,9 @@ def _codec_ids_from_payload_or_input(
if isinstance(codes, dict):
audio = codes.get("audio")
if isinstance(audio, torch.Tensor) and audio.numel() > 0:
return audio.reshape(-1).to(device=input_ids.device, dtype=torch.long)
return audio.reshape(-1).to(dtype=torch.long)
if isinstance(audio, (list, tuple)) and audio:
return torch.as_tensor(audio, device=input_ids.device, dtype=torch.long).reshape(-1)
return torch.as_tensor(audio, dtype=torch.long).reshape(-1)
return input_ids.reshape(-1).to(dtype=torch.long)
@@ -63,6 +63,10 @@ class Qwen3TTSCode2Wav(nn.Module):
# decoder caches must use the same IDs delivered by on_requests_finished;
# payload metadata carries an external ID which may differ.
requires_request_ids = True
# A nonempty native codes.audio payload is authoritative; token IDs may
# serve only as per-request control slots for the generation scheduler.
supports_native_payload_input = True
batched_gpu_staging_keys = {("codes", "audio")}
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
@@ -427,12 +431,9 @@ class Qwen3TTSCode2Wav(nn.Module):
try:
_, c = valid_codes_qf[0]
logger.info(
"Code2Wav codec: frames=%d q=%d uniq=%d range=[%d,%d] batch=%d",
"Code2Wav codec: frames=%d q=%d batch=%d",
c.shape[1],
q,
int(torch.unique(c).numel()),
int(c.min().item()),
int(c.max().item()),
len(valid_codes_qf),
)
except Exception:
@@ -454,9 +455,22 @@ class Qwen3TTSCode2Wav(nn.Module):
request_lengths = [int(codes_qf.shape[-1]) for _, codes_qf in valid_codes_qf]
max_request_length = max(request_lengths)
request_codes = valid_codes_qf[0][1].new_zeros((len(valid_codes_qf), q, max_request_length))
for row, (_, codes_qf) in enumerate(valid_codes_qf):
request_codes[row, :, : codes_qf.shape[-1]].copy_(codes_qf)
request_codes_shape = (len(valid_codes_qf), q, max_request_length)
target_device = ids.device
if target_device.type == "cuda" and all(codes_qf.device.type == "cpu" for _, codes_qf in valid_codes_qf):
staged_codes = torch.zeros(
request_codes_shape,
dtype=torch.long,
device="cpu",
pin_memory=True,
)
for row, (_, codes_qf) in enumerate(valid_codes_qf):
staged_codes[row, :, : codes_qf.shape[-1]].copy_(codes_qf)
request_codes = staged_codes.to(device=target_device, non_blocking=True)
else:
request_codes = torch.zeros(request_codes_shape, dtype=torch.long, device=target_device)
for row, (_, codes_qf) in enumerate(valid_codes_qf):
request_codes[row, :, : codes_qf.shape[-1]].copy_(codes_qf)
self._record_decode_batch_stats(
group_size=len(valid_codes_qf),
@@ -4,7 +4,8 @@
from __future__ import annotations
import copy
from collections.abc import Iterable, Mapping, Sequence
from collections.abc import Iterable, Iterator, Mapping, Sequence
from contextlib import contextmanager
from typing import Any
import numpy as np
@@ -25,13 +26,14 @@ from vllm.multimodal.audio import AudioResampler
from vllm.sequence import IntermediateTensors
from vllm_omni.data_entry_keys import OmniPayload
from vllm_omni.model_executor.models.output_templates import OmniOutput
from vllm_omni.model_executor.models.output_templates import OmniOutput, OwnedBatchTensor
from vllm_omni.utils.speaker_cache import (
get_speaker_cache,
iter_custom_voice_profiles,
load_validated_profile_tensors,
validate_qwen3_tts_profile,
)
from vllm_omni.worker.sampling_utils import get_tts_local_seed
from .configuration_qwen3_tts import Qwen3TTSConfig, Qwen3TTSSpeakerEncoderConfig, Qwen3TTSTalkerConfig
from .prompt_embeds_builder import PRECOMPUTED_TEXT_IDS_KEY, Qwen3TTSPromptEmbedsBuilder, resolve_x_vector_only
@@ -42,6 +44,80 @@ from .tokenizer_12hz.modeling_qwen3_tts_tokenizer_v2 import Qwen3TTSTokenizerV2E
logger = init_logger(__name__)
_TRAILING_TEXT_COMPACT_MIN_FRAMES = 64
_ASYNC_REF_CODES_PUBLISHED_KEY = "_qwen3_tts_ref_codes_published"
def _qwen3_tts_gpu_resident_buffer_keys(
use_v2_model_runner: bool,
) -> set[tuple[str, str]]:
keys = {
("codes", "audio"),
("hidden_states", "last"),
("hidden_states", "trailing_text"),
}
if use_v2_model_runner:
keys.update(
{
("codes", "ref"),
("embed", "prefill"),
("meta", "codec_frame_valid"),
}
)
return keys
def _materialize_span_scalars(
values: Sequence[int],
span_lengths: Sequence[int],
*,
dtype: torch.dtype,
device: torch.device,
) -> torch.Tensor | None:
"""Expand a uniform scalar cohort with one GPU allocation."""
if len(values) != len(span_lengths):
raise ValueError(
f"values and span_lengths must have the same length, got {len(values)} and {len(span_lengths)}"
)
total = sum(int(length) for length in span_lengths)
if not values:
return torch.empty((0,), dtype=dtype, device=device)
first = int(values[0])
if not all(int(value) == first for value in values[1:]):
return None
return torch.full((total,), first, dtype=dtype, device=device)
def _should_publish_async_ref_codes(info: dict[str, Any]) -> bool:
"""Publish ref codes exactly once, including after a KV-resumed prefill."""
meta = info.get("meta")
return not (isinstance(meta, dict) and bool(meta.get(_ASYNC_REF_CODES_PUBLISHED_KEY)))
def _mark_async_ref_codes_published(info: dict[str, Any]) -> None:
meta = info.setdefault("meta", {})
if not isinstance(meta, dict):
raise TypeError("Qwen3-TTS payload meta must be a dict")
meta[_ASYNC_REF_CODES_PUBLISHED_KEY] = True
def _ref_audio_artifact_cache_capacity(vllm_config: VllmConfig) -> int:
model_cfg = getattr(vllm_config, "model_config", None)
connector_cfg = getattr(model_cfg, "stage_connector_config", None)
connector_extra = (
connector_cfg.get("extra", connector_cfg)
if isinstance(connector_cfg, dict)
else getattr(connector_cfg, "extra", None)
)
if not isinstance(connector_extra, dict):
connector_extra = {}
raw_capacity = connector_extra.get("ref_audio_artifact_cache_max_entries", 1024)
try:
capacity = int(raw_capacity)
except (TypeError, ValueError) as exc:
raise ValueError(f"Invalid ref_audio_artifact_cache_max_entries={raw_capacity!r}") from exc
if capacity < 0:
raise ValueError(f"ref_audio_artifact_cache_max_entries must be non-negative, got {capacity}")
return capacity
def _has_tts_text_conditioning(info_dict: dict[str, Any], hidden_states: Any | None = None) -> bool:
@@ -267,8 +343,7 @@ class Qwen3TTSSpeakerEncoder(torch.nn.Module):
class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
"""vLLM-AR talker: step-wise layer-0 codec decoding.
Predicts residual codebooks (1..Q-1) into `audio_codes` and streams text via `tailing_text_hidden`."""
"""vLLM-AR talker with step-wise layer-0 codec decoding."""
hf_to_vllm_mapper = WeightsMapper(
orig_to_new_prefix={
@@ -329,29 +404,13 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
# per-request additional_information.
self.talker_mtp_output_key = ("codes", "audio")
self.talker_mtp_graph_safe = True
# talker_mtp samples with per-row generators, so explicitly-seeded
# requests stay batched instead of one scalar forward per row (#4883).
# This is only valid while talker_mtp receives the *unpadded* active
# batch, i.e. when it is NOT graph-wrapped. The runner wraps talker_mtp
# (padded batches + a single captured RNG stream) whenever full
# cudagraphs are enabled, so disable per-row generators in that case.
# Consequence: under full cudagraphs, per-request ``tts_local_seed`` is
# not reproducible (matching Qwen3-Omni, which has no per-row seeding);
# eager mode keeps the per-row generator fast-path.
# TODO(#4923): the model should not read ``cudagraph_mode`` — it is an
# upstream (runner) concern, and the runner already re-derives the same
# wrap decision in ``_init_talker_mtp``. Once all TTS models declare
# ``talker_mtp_graph_safe`` we should move this gating into the model
# runner (models only expose the static capability flag, and users can
# then configure ``cudagraph_mode`` freely). This also means mtp seeding
# is silently dropped when the decode batch > 1 under full cudagraphs;
# the follow-up should refactor the per-row generator in the runner to
# be cudagraph-safe so seeded batches stay reproducible.
cudagraph_mode = getattr(vllm_config.compilation_config, "cudagraph_mode", None)
talker_mtp_graph_wrapped = (
self.talker_mtp_graph_safe and cudagraph_mode is not None and cudagraph_mode.has_full_cudagraphs()
)
self.talker_mtp_accepts_per_row_generators = not talker_mtp_graph_wrapped
# The runners bypass only the outer whole-MTP graph when explicit
# generators are present, so seeded requests can still share one raw
# batched MTP call with independent per-row streams.
self.talker_mtp_accepts_per_row_generators = True
self.mtp_sample_uniforms = True
self.mtp_sample_steps = max(0, int(self.talker_config.num_code_groups) - 1)
self.mtp_sample_vocab_size = self._codebook_vocab_size
self.use_async_omni_output = True
self.eager_omni_postprocess_before_async_output = True
self.omni_pooler_payload_include_hidden = False
@@ -445,14 +504,24 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
# the same req_id ordering that indexes sampling_metadata.
self._req_x_vector_only: dict[str, bool | None] = {}
self._batch_req_ids: list[str] = []
self._mrv2_silence_ban_mask: torch.Tensor | None = None
# Keys that should stay on GPU in model_intermediate_buffer to avoid
# CPU-to-GPU round-trips on every decode step.
self.gpu_resident_buffer_keys: set[tuple[str, str]] = {
("codes", "audio"),
("hidden_states", "last"),
("hidden_states", "trailing_text"),
}
self._use_v2_model_runner = bool(getattr(vllm_config.model_config, "use_v2_model_runner", False))
self.gpu_resident_buffer_keys = _qwen3_tts_gpu_resident_buffer_keys(self._use_v2_model_runner)
if self._use_v2_model_runner:
# Align predictor warmup/capture buckets with the outer MRv2 MTP
# graph buckets so the compile cache covers every reachable size.
outer_max_bsz = int(vllm_config.scheduler_config.max_num_seqs)
outer_buckets = {
int(size)
for size in vllm_config.compilation_config.cudagraph_capture_sizes
if 0 < int(size) <= outer_max_bsz
}
outer_buckets.update({1, outer_max_bsz}) # eager fallback rows
self.code_predictor.configure_mtp_execution_buckets(sorted(outer_buckets))
# ``text_proj(text_emb(tts_pad_token_id))`` is request-independent —
# it depends only on frozen ``text_embedding`` / ``text_projection``
@@ -492,6 +561,7 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
self._subtalker_sampling_params: dict[str, Any] = (
dict(raw_subtalker_sampling) if isinstance(raw_subtalker_sampling, Mapping) else {}
)
self.mtp_sampling_params = self._subtalker_sampling_params
self._stacked_codec_embed: torch.Tensor | None = None
@@ -514,6 +584,7 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
tts_pad_embed=self._tts_pad_embed,
encode_ref_audio_batch=self._encode_ref_audio_batch,
speaker_cache=self._speaker_cache,
ref_audio_artifact_cache_max_entries=_ref_audio_artifact_cache_capacity(vllm_config),
)
self._load_custom_voice_profiles()
@@ -592,6 +663,10 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
# Suppress silence-region tokens for the first N decode frames (#4966). The
# per-request decode step is the length of its generated-token history.
ban_n = self._silence_ban_frames
if ban_n > 0 and sampling_metadata is None and self._mrv2_silence_ban_mask is not None:
if self._mrv2_silence_ban_mask.shape[0] != logits.shape[0]:
raise ValueError("MRV2 silence-ban batch must match the sampled logits rows")
return logits.masked_fill(self._mrv2_silence_ban_mask & self._silence_mask, float("-inf"))
if ban_n > 0 and sampling_metadata is not None:
output_token_ids = getattr(sampling_metadata, "output_token_ids", None)
if output_token_ids is None or len(output_token_ids) != logits.shape[0]:
@@ -645,11 +720,17 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
info_dicts = kwargs.get("runtime_additional_information") or []
if "runtime_additional_information" in kwargs and "model_intermediate_buffer" not in kwargs:
logger.warning_once("runtime_additional_information is deprecated, use model_intermediate_buffer")
model_config = getattr(getattr(self, "vllm_config", None), "model_config", None)
async_chunk = bool(getattr(model_config, "async_chunk", False))
audio_codes_list: list[torch.Tensor] = []
ref_code_len_list: list[torch.Tensor] = []
ref_code_len_segments: list[tuple[int | torch.Tensor, int, torch.device]] = []
ref_code_list: list[torch.Tensor] = []
has_ref_code = False
codec_streaming_list: list[torch.Tensor] = []
codec_streaming_values: list[int] = []
codec_streaming_span_lengths: list[int] = []
codec_streaming_device: torch.device | None = None
codec_frame_valid_device: torch.device | None = None
codec_frame_valid_parts: list[torch.Tensor] = []
for info in info_dicts:
if not isinstance(info, dict):
ref_code_list.append(torch.empty(0, dtype=torch.long))
@@ -659,17 +740,46 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
ac = codes.get("audio")
if isinstance(ac, torch.Tensor):
audio_codes_list.append(ac)
cs = meta.get("codec_streaming")
if isinstance(cs, bool):
codec_streaming_list.append(
torch.full((int(ac.shape[0]),), int(cs), dtype=torch.int8, device=ac.device)
frame_valid = meta.get("codec_frame_valid")
if isinstance(frame_valid, bool):
codec_frame_valid_device = ac.device
codec_frame_valid_parts.append(
torch.full(
(int(ac.shape[0]),),
int(frame_valid),
dtype=torch.int8,
device=ac.device,
)
)
elif isinstance(frame_valid, torch.Tensor):
if frame_valid.numel() != 1:
raise ValueError("codec_frame_valid must be scalar per request")
codec_frame_valid_device = ac.device
codec_frame_valid_parts.append(
frame_valid.to(device=ac.device, dtype=torch.int8, non_blocking=True)
.reshape(1)
.expand(int(ac.shape[0]))
)
cs = meta.get("codec_streaming")
if not async_chunk and isinstance(cs, bool):
codec_streaming_values.append(int(cs))
codec_streaming_span_lengths.append(int(ac.shape[0]))
codec_streaming_device = ac.device
ref_code = codes.get("ref")
if isinstance(ref_code, torch.Tensor) and ref_code.numel() > 0:
publish_ref_code = not async_chunk or _should_publish_async_ref_codes(info)
if publish_ref_code and isinstance(ref_code, torch.Tensor) and ref_code.numel() > 0:
ref_code_list.append(ref_code)
has_ref_code = True
if async_chunk:
_mark_async_ref_codes_published(info)
else:
ref_code_list.append(torch.empty(0, dtype=torch.long))
if async_chunk:
# The streaming consumer uses codes.ref.shape[0] directly and
# does not read ref_code_len or codec_streaming. Avoid creating
# GPU control tensors that would only be snapshotted and copied
# back to the CPU on every decode step.
continue
ref_len = meta.get("ref_code_len")
if ref_len is None:
continue
@@ -680,7 +790,7 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
if ref_len.numel() == 0:
raise ValueError("ref_code_len is an empty tensor")
ref_len_tail = ref_len.reshape(-1)[-1:].to(dtype=torch.int32, device=ac.device)
ref_code_len_list.append(ref_len_tail.expand(span_len).contiguous())
ref_code_len_segments.append((ref_len_tail, span_len, ac.device))
continue
if isinstance(ref_len, list):
if len(ref_len) != 1:
@@ -688,7 +798,7 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
ref_len_val = int(ref_len[0])
else:
ref_len_val = int(ref_len)
ref_code_len_list.append(torch.full((span_len,), ref_len_val, dtype=torch.int32, device=ac.device))
ref_code_len_segments.append((ref_len_val, span_len, ac.device))
if not audio_codes_list:
return OmniOutput(text_hidden_states=hidden, multimodal_outputs={})
@@ -696,15 +806,61 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
audio_codes = torch.cat(audio_codes_list, dim=0)
span_len = int(audio_codes.shape[0])
mm: OmniPayload = {"codes": {"audio": audio_codes}}
if ref_code_len_list:
mm.setdefault("meta", {})["ref_code_len"] = torch.cat(ref_code_len_list, dim=0)[:span_len]
if ref_code_len_segments:
if all(isinstance(value, int) for value, _length, _device in ref_code_len_segments):
ref_code_len = _materialize_span_scalars(
[int(value) for value, _length, _device in ref_code_len_segments],
[length for _value, length, _device in ref_code_len_segments],
dtype=torch.int32,
device=ref_code_len_segments[0][2],
)
if ref_code_len is None:
ref_code_len = torch.cat(
[
torch.full((length,), int(value), dtype=torch.int32, device=device)
for value, length, device in ref_code_len_segments
],
dim=0,
)
else:
ref_code_len_parts = [
value.expand(length)
if isinstance(value, torch.Tensor)
else torch.full((length,), value, dtype=torch.int32, device=device)
for value, length, device in ref_code_len_segments
]
ref_code_len = torch.cat(ref_code_len_parts, dim=0)
mm.setdefault("meta", {})["ref_code_len"] = ref_code_len[:span_len]
if has_ref_code:
# Batch-aligned, one entry per request: ``to_payload_element``
# indexes ``element[idx]`` per request, and a shorter list would
# silently broadcast one request's reference codes to the others.
mm.setdefault("codes", {})["ref"] = ref_code_list
if codec_streaming_list:
mm.setdefault("meta", {})["codec_streaming"] = torch.cat(codec_streaming_list, dim=0)[:span_len]
if codec_streaming_values:
assert codec_streaming_device is not None
codec_streaming = _materialize_span_scalars(
codec_streaming_values,
codec_streaming_span_lengths,
dtype=torch.int8,
device=codec_streaming_device,
)
if codec_streaming is None:
codec_streaming = torch.cat(
[
torch.full((length,), value, dtype=torch.int8, device=codec_streaming_device)
for value, length in zip(
codec_streaming_values,
codec_streaming_span_lengths,
strict=True,
)
],
dim=0,
)
mm.setdefault("meta", {})["codec_streaming"] = codec_streaming[:span_len]
if codec_frame_valid_parts:
assert codec_frame_valid_device is not None
codec_frame_valid = torch.cat(codec_frame_valid_parts, dim=0)
mm.setdefault("meta", {})["codec_frame_valid"] = codec_frame_valid[:span_len]
return OmniOutput(text_hidden_states=hidden, multimodal_outputs=mm)
# -------------------- preprocess / postprocess --------------------
@@ -763,27 +919,32 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
if is_prefill:
# Prefill (prompt embeddings)
prompt_embeds_cpu = embed.get("prefill")
# First prefill round: prompt_embeds_cpu is not yet populated.
# Subsequent prefill rounds (multi-chunk): prompt_embeds_cpu is a Tensor stored by the first round.
is_first_prefill = not isinstance(prompt_embeds_cpu, torch.Tensor) or prompt_embeds_cpu.ndim != 2
prompt_embeds_buffer = embed.get("prefill")
# First prefill round: the retained prompt buffer is not populated.
# Subsequent chunks slice the buffer stored by the first round.
is_first_prefill = not isinstance(prompt_embeds_buffer, torch.Tensor) or prompt_embeds_buffer.ndim != 2
if is_first_prefill:
full_prompt_embeds, tailing_text_hidden, ref_code_len, ref_code = (
self._prompt_builder.build_prompt_embeds(task_type=task_type, info_dict=info_dict)
)
# Store full prompt embeddings on CPU (large, prefill-only).
# tailing_text_hidden stays on GPU (gpu_resident_buffer_keys).
prompt_embeds_cpu = full_prompt_embeds.detach().to("cpu").contiguous()
prompt_embeds_buffer = full_prompt_embeds.detach()
if not bool(getattr(self, "_use_v2_model_runner", False)):
prompt_embeds_buffer = prompt_embeds_buffer.to("cpu")
prompt_embeds_buffer = prompt_embeds_buffer.contiguous()
info_update: OmniPayload = {
"embed": {"prefill": prompt_embeds_cpu},
"embed": {"prefill": prompt_embeds_buffer},
"hidden_states": {"trailing_text": tailing_text_hidden.detach()},
"meta": {
"talker_text_offset": 0,
"codec_streaming": codec_streaming,
"codec_frame_valid": torch.zeros((), dtype=torch.bool, device=input_ids.device),
},
}
if isinstance(ref_code, torch.Tensor) and ref_code.numel() > 0:
info_update.setdefault("codes", {})["ref"] = ref_code.detach().to("cpu").contiguous()
ref_code_buffer = ref_code.detach()
if not bool(getattr(self, "_use_v2_model_runner", False)):
ref_code_buffer = ref_code_buffer.to("cpu")
info_update.setdefault("codes", {})["ref"] = ref_code_buffer.contiguous()
if ref_code_len is not None:
info_update["meta"]["ref_code_len"] = int(ref_code_len)
# First prefill: source the slice offset from `_omni_num_computed_tokens`
@@ -794,16 +955,21 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
else:
# Subsequent prefill chunk: slice from stored embeddings at running offset.
offset = max(0, int(meta.get("talker_prefill_offset", 0) or 0))
info_update = {"meta": {"codec_streaming": codec_streaming}}
info_update = {
"meta": {
"codec_streaming": codec_streaming,
"codec_frame_valid": torch.zeros((), dtype=torch.bool, device=input_ids.device),
}
}
# Always return a span_len slice; if the scheduled placeholder is longer than what
# the prompt actually fills, pad with tts_pad_embed (preserves placeholder/embedding alignment).
s = max(0, min(offset, int(prompt_embeds_cpu.shape[0])))
e = max(0, min(offset + span_len, int(prompt_embeds_cpu.shape[0])))
take = prompt_embeds_cpu[s:e]
s = max(0, min(offset, int(prompt_embeds_buffer.shape[0])))
e = max(0, min(offset + span_len, int(prompt_embeds_buffer.shape[0])))
take = prompt_embeds_buffer[s:e]
if int(take.shape[0]) < span_len:
pad_n = int(span_len - int(take.shape[0]))
pad_rows = tts_pad_embed.reshape(1, -1).to("cpu").expand(pad_n, -1)
pad_rows = tts_pad_embed.to(device=take.device).reshape(1, -1).expand(pad_n, -1)
take = torch.cat([take, pad_rows], dim=0)
prompt_embeds = take.to(device=input_ids.device, dtype=dtype)
info_update["meta"]["talker_prefill_offset"] = int(offset + span_len)
@@ -826,7 +992,16 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
.to(device=input_ids.device, dtype=dtype)
.reshape(span_len, -1)
)
return input_ids, inputs_embeds_out, {"meta": {"codec_streaming": codec_streaming}}
return (
input_ids,
inputs_embeds_out,
{
"meta": {
"codec_streaming": codec_streaming,
"codec_frame_valid": torch.zeros((), dtype=torch.bool, device=input_ids.device),
}
},
)
# Decode: span_len == 1
# Pop one text-step vector from tailing_text_hidden queue.
@@ -884,6 +1059,9 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
"meta": {
"talker_text_offset": int(next_text_offset),
"codec_streaming": codec_streaming,
"codec_frame_valid": (
(input_ids.reshape(-1)[-1] >= 0) & (input_ids.reshape(-1)[-1] < self._codebook_vocab_size)
).reshape(()),
},
}
if trailing_text_update is not None:
@@ -895,11 +1073,13 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
*,
input_ids: torch.Tensor,
req_infos: list[dict[str, Any]],
input_embeds: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, list[dict[str, Any]]]:
"""Batch the decode-only preprocess path for Qwen3-TTS.
This mirrors the scalar decode branch in ``preprocess()``, but performs
the token embedding lookup once for the whole decode batch.
the token embedding lookup once for the whole decode batch, unless
the runner has already prepared embeddings for these input ids.
"""
input_ids_flat = input_ids.reshape(-1)
if int(input_ids_flat.numel()) != len(req_infos):
@@ -907,6 +1087,7 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
f"preprocess_decode_batch expected {len(req_infos)} input ids, got {int(input_ids_flat.numel())}"
)
codec_frame_valid_batch = (input_ids_flat >= 0) & (input_ids_flat < self._codebook_vocab_size)
device = input_ids_flat.device
dtype = self._embedding_dtype
# Request-independent constant (see :meth:`_init_runtime_buffers`) —
@@ -979,17 +1160,16 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
"meta": {
"talker_text_offset": int(next_text_offset),
"codec_streaming": codec_streaming,
"codec_frame_valid": codec_frame_valid_batch[len(updates)].reshape(()),
},
}
if trailing_text_update is not None:
info_update["hidden_states"] = {"trailing_text": trailing_text_update.detach()}
updates.append(info_update)
inputs_embeds_out = self.embed_input_ids(input_ids_flat.reshape(-1, 1).to(torch.long)).to(
device=device,
dtype=dtype,
)
inputs_embeds_out = inputs_embeds_out.reshape(len(req_infos), -1)
if input_embeds is None:
input_embeds = self.embed_input_ids(input_ids_flat.reshape(-1, 1).to(torch.long))
inputs_embeds_out = input_embeds.to(device=device, dtype=dtype).reshape(len(req_infos), -1)
return (
input_ids_flat,
inputs_embeds_out,
@@ -998,6 +1178,16 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
updates,
)
def preprocess_decode_batch_mrv2(
self,
*,
input_ids: torch.Tensor,
input_embeds: torch.Tensor,
req_infos: list[dict[str, Any]],
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, list[dict[str, Any]]]:
"""Expose the existing TTS decode batcher through the MRv2 contract."""
return self.preprocess_decode_batch(input_ids=input_ids, req_infos=req_infos, input_embeds=input_embeds)
def postprocess(self, hidden_states: torch.Tensor, **_: Any) -> dict[str, Any]:
# Keep the last token hidden for the next decode step's code predictor.
# Stays on GPU - gpu_resident_buffer_keys avoids the CPU round-trip.
@@ -1006,6 +1196,23 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
last = hidden_states[-1, :].detach()
return {"hidden_states": {"last": last}}
def postprocess_batch_mrv2(
self,
*,
hidden_states: torch.Tensor,
last_token_indices: torch.Tensor,
) -> tuple[tuple[str, str], OwnedBatchTensor]:
"""Gather every request's Talker tail in one GPU operation.
``index_select`` freshly allocates the result, so the batch is marked
as owned and the intermediate buffer stores row views without taking
a second snapshot.
"""
return (
("hidden_states", "last"),
OwnedBatchTensor(hidden_states.index_select(0, last_token_indices)),
)
@torch.inference_mode()
def preprocess_batch(
self,
@@ -1026,6 +1233,39 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
device=device,
)
@torch.inference_mode()
def preprocess_batch_mrv2(
self,
*,
req_infos: list[dict[str, Any]],
device: torch.device,
) -> None:
"""Batch new MRv2 prefill slots without rebuilding a req-id map."""
if self._silence_ban_frames > 0:
for info in req_infos:
self._req_x_vector_only[info["req_id"]] = resolve_x_vector_only(info)
self._prompt_builder.preprocess_infos_batch(
req_infos=req_infos,
device=device,
)
@contextmanager
def mrv2_sampling_context(self, *, req_ids: list[str], num_output_tokens: torch.Tensor) -> Iterator[None]:
"""Scope the silence gate to sampling, never prompt-logprob computation."""
self.set_batch_req_ids(req_ids)
self._mrv2_silence_ban_mask = None
if self._silence_ban_frames > 0:
in_scope = torch.tensor(
[self._req_x_vector_only.get(req_id) is True for req_id in req_ids],
device=num_output_tokens.device,
dtype=torch.bool,
)
self._mrv2_silence_ban_mask = (in_scope & (num_output_tokens < self._silence_ban_frames)).unsqueeze(1)
try:
yield
finally:
self._mrv2_silence_ban_mask = None
def set_batch_req_ids(self, req_ids: Sequence[str]) -> None:
"""Record the current batch's req_ids, in the order that indexes logits.
@@ -1051,10 +1291,9 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
sampling_rate=target_sr,
return_tensors="pt",
)
inputs = inputs.to(device).to(torch.bfloat16)
input_values = inputs["input_values"].squeeze(1)
padding_mask = inputs["padding_mask"].squeeze(1)
input_values = inputs["input_values"].squeeze(1).to(device=device, dtype=torch.bfloat16)
downsample = self._encoder_downsample_rate
valid_code_lengths = [(int(wav.size) + downsample - 1) // downsample for wav in wavs]
with torch.inference_mode():
encoded = self.encoder.encode(
@@ -1063,13 +1302,13 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
)
audio_codes = encoded.audio_codes[:, : self._encoder_valid_num_quantizers]
downsample = self._encoder_downsample_rate
return [
code[..., : -(-mask.sum() // downsample)].transpose(0, 1).to(device=device, dtype=torch.long)
for code, mask in zip(audio_codes, padding_mask)
code[:, : int(valid_len)].transpose(0, 1).to(dtype=torch.long).contiguous()
for code, valid_len in zip(audio_codes, valid_code_lengths, strict=True)
]
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
self._prompt_builder._projected_token_cache.clear()
# Consume talker weights, and conditionally consume speaker encoder
# weights only if they are present in the checkpoint.
speaker_weights: list[tuple[str, torch.Tensor]] = []
@@ -1256,6 +1495,7 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
top_p: float | None = None,
generator: torch.Generator | None = None,
generators: Sequence[torch.Generator | None] | None = None,
sample_uniforms: torch.Tensor | None = None,
**kwargs: Any,
) -> tuple[torch.Tensor, torch.Tensor]:
"""GPU fast-path used by OmniGPUModelRunner to predict residual codebooks (1..Q-1).
@@ -1296,6 +1536,7 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
top_p=top_p,
generator=generator,
generators=generators,
sample_uniforms=sample_uniforms,
) # [B, Q]
# Map invalid layer-0 ids (e.g. EOS) to PAD=0 so SpeechTokenizer sees only real codes.
@@ -1313,3 +1554,20 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
summed = (last_id_hidden.squeeze(1) + gathered.sum(dim=1)).unsqueeze(1)
inputs_embeds_out = (summed + text_step).reshape(bsz, -1)
return inputs_embeds_out, audio_codes.to(dtype=torch.long)
# MRV2 capability names read the V1 canonical values so platform patches
# such as the NPU 310P graph-safety override apply to both runners.
mtp = talker_mtp
get_mtp_seed = staticmethod(get_tts_local_seed)
@property
def mtp_output_key(self) -> tuple[str, str]:
return self.talker_mtp_output_key
@property
def mtp_graph_safe(self) -> bool:
return self.talker_mtp_graph_safe
@property
def mtp_accepts_per_row_generators(self) -> bool:
return self.talker_mtp_accepts_per_row_generators
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# Copyright 2026 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -28,7 +31,7 @@ from transformers import MimiConfig, MimiModel
from transformers.activations import ACT2FN
from transformers.cache_utils import Cache, DynamicCache
from transformers.integrations import use_kernel_forward_from_hub
from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
from transformers.masking_utils import create_sliding_window_causal_mask
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.modeling_outputs import BaseModelOutputWithPast
@@ -521,15 +524,63 @@ class Qwen3TTSTokenizerV2DecoderTransformerModel(Qwen3TTSTokenizerV2DecoderPreTr
self.norm = Qwen3TTSTokenizerV2DecoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.rotary_emb = Qwen3TTSTokenizerV2DecoderRotatoryEmbedding(config=config)
self.gradient_checkpointing = False
self.has_sliding_layers = "sliding_attention" in self.config.layer_types
self.window_size = config.sliding_window
self.input_proj = nn.Linear(config.latent_dim, config.hidden_size)
self.output_proj = nn.Linear(config.hidden_size, config.latent_dim)
# Stateless calls with implicit positions share one broadcastable mask
# per warmup shape. Incremental or explicit-position calls build a live mask.
self._sliding_attention_mask_cache: dict[tuple[int, torch.dtype, torch.device, str], torch.Tensor | None] = {}
# Initialize weights and apply final processing
self.post_init()
def _apply(self, fn, recurse=True):
# A placement or dtype change invalidates every cached mask.
self._sliding_attention_mask_cache.clear()
return super()._apply(fn, recurse=recurse)
def _get_sliding_attention_mask(
self,
inputs_embeds: torch.Tensor,
) -> torch.Tensor | None:
sequence_length = int(inputs_embeds.shape[1])
max_position_embeddings = int(self.config.max_position_embeddings)
if sequence_length > max_position_embeddings:
raise ValueError(
f"Input length {sequence_length} exceeds max_position_embeddings {max_position_embeddings}"
)
cache_key = (
sequence_length,
inputs_embeds.dtype,
inputs_embeds.device,
str(self.config._attn_implementation),
)
if cache_key not in self._sliding_attention_mask_cache:
mask_inputs = inputs_embeds[:1]
mask_kwargs = {
"config": self.config,
"attention_mask": None,
"past_key_values": None,
"position_ids": None,
}
sig = inspect.signature(create_sliding_window_causal_mask)
if "input_embeds" in sig.parameters:
mask_kwargs["input_embeds"] = mask_inputs
mask_kwargs["cache_position"] = torch.arange(
sequence_length,
device=inputs_embeds.device,
)
else:
mask_kwargs["inputs_embeds"] = mask_inputs
sliding_attention_mask = create_sliding_window_causal_mask(**mask_kwargs)
if sliding_attention_mask is not None:
sliding_attention_mask = sliding_attention_mask.contiguous()
self._sliding_attention_mask_cache[cache_key] = sliding_attention_mask
return self._sliding_attention_mask_cache[cache_key]
# Note: @check_model_inputs decorator removed for vLLM compatibility
# The decorator causes "unexpected keyword argument 'inputs_embeds'" error
@auto_docstring
@@ -558,6 +609,17 @@ class Qwen3TTSTokenizerV2DecoderTransformerModel(Qwen3TTSTokenizerV2DecoderPreTr
inputs_embeds = self.input_proj(inputs_embeds)
sequence_length = inputs_embeds.shape[1]
# Only internally generated positions are known to be contiguous and
# zero-based without reading CUDA tensor values back to the host.
# Explicit positions use the live mask path, including during capture.
uses_prepared_or_incremental_mask = (
attention_mask is not None
or bool(use_cache)
or past_key_values is not None
or cache_position is not None
or position_ids is not None
)
if use_cache and past_key_values is None:
past_key_values = DynamicCache(config=self.config)
@@ -565,7 +627,7 @@ class Qwen3TTSTokenizerV2DecoderTransformerModel(Qwen3TTSTokenizerV2DecoderPreTr
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
cache_position = torch.arange(
past_seen_tokens,
past_seen_tokens + inputs_embeds.shape[1],
past_seen_tokens + sequence_length,
device=inputs_embeds.device,
)
@@ -574,22 +636,24 @@ class Qwen3TTSTokenizerV2DecoderTransformerModel(Qwen3TTSTokenizerV2DecoderPreTr
hidden_states = inputs_embeds
if not isinstance(causal_mask_mapping := attention_mask, dict):
if isinstance(attention_mask, dict):
sliding_attention_mask = attention_mask["sliding_attention"]
elif uses_prepared_or_incremental_mask:
mask_kwargs = {
"config": self.config,
"attention_mask": attention_mask,
"past_key_values": past_key_values,
"position_ids": position_ids,
}
sig = inspect.signature(create_causal_mask)
sig = inspect.signature(create_sliding_window_causal_mask)
if "input_embeds" in sig.parameters:
mask_kwargs["input_embeds"] = inputs_embeds
mask_kwargs["cache_position"] = cache_position
else:
mask_kwargs["inputs_embeds"] = inputs_embeds
causal_mask_mapping = {"full_attention": create_causal_mask(**mask_kwargs)}
if self.has_sliding_layers:
causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
sliding_attention_mask = create_sliding_window_causal_mask(**mask_kwargs)
else:
sliding_attention_mask = self._get_sliding_attention_mask(inputs_embeds)
# create position embeddings to be shared across the decoder layers
position_embeddings = self.rotary_emb(hidden_states, position_ids)
@@ -597,7 +661,7 @@ class Qwen3TTSTokenizerV2DecoderTransformerModel(Qwen3TTSTokenizerV2DecoderPreTr
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
hidden_states = decoder_layer(
hidden_states,
attention_mask=causal_mask_mapping[decoder_layer.attention_type],
attention_mask=sliding_attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
use_cache=use_cache,
@@ -1400,13 +1464,15 @@ class Qwen3TTSTokenizerV2Decoder(Qwen3TTSTokenizerV2DecoderPreTrainedModel):
@staticmethod
def _slice_dynamic_cache(cache: DynamicCache, row: int) -> DynamicCache:
request_cache = copy.deepcopy(cache)
for layer in request_cache.layers:
if layer.keys is not None:
layer.keys = layer.keys[row : row + 1].clone()
if layer.values is not None:
layer.values = layer.values[row : row + 1].clone()
return request_cache
# Preserve cache metadata and independent ownership without cloning the
# full batch for every request. Seed deepcopy with only the selected KV
# rows; it will copy the remaining cache structure normally.
memo: dict[int, Any] = {}
for layer in cache.layers:
for tensor in (layer.keys, layer.values):
if tensor is not None and id(tensor) not in memo:
memo[id(tensor)] = tensor[row : row + 1].clone()
return copy.deepcopy(cache, memo)
@staticmethod
def _cache_tensors_are_batchable(request_caches: list[dict[str, Any]], keys: tuple[str, ...]) -> bool: