[Refactor] Standardize data entry key names to {type}.{qualifier} format (#1829)

Signed-off-by: Divyansh Singhvi <divyanshsinghvi@gmail.com>
Signed-off-by: dsinghvi <divyanshsinghvi@gmail.com>
Signed-off-by: tzhouam <tzhouam@connect.ust.hk>
Co-authored-by: Zhou Taichang <tzhouam@connect.ust.hk>
Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
authored and GitHub committed 2026-04-25 18:15:38 +08:00
1 parent 755a2d9d96
commit 2390350533
41 files changed
+1192 -569

No files matched your search

@@ -230,8 +230,9 @@ class FishSpeechDACDecoder(nn.Module):
for i, info in enumerate(runtime_additional_information):
if i >= len(left_context_size):
break
if "left_context_size" in info:
left_context_size[i] = info["left_context_size"]
meta = info.get("meta", {}) if isinstance(info, dict) else {}
if "left_context_size" in meta:
left_context_size[i] = meta["left_context_size"]
for i, req_ids in enumerate(request_ids_list):
if req_ids.numel() < 1:
@@ -193,9 +193,9 @@ class FishSpeechSlowARForConditionalGeneration(nn.Module):
self.has_preprocess = True
self.has_postprocess = True
self.mtp_hidden_size = int(self.text_config.hidden_size)
self.talker_mtp_output_key = "audio_codes"
self.talker_mtp_output_key = ("codes", "audio")
self.gpu_resident_buffer_keys: set[tuple[str, str]] = {("hidden_states", "last")}
self.talker_mtp_graph_safe = True
self.gpu_resident_buffer_keys: set[str] = {"last_slow_ar_hidden"}
# Qwen3 transformer backbone.
self.model = Qwen3Model(vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model"))
@@ -330,7 +330,7 @@ class FishSpeechSlowARForConditionalGeneration(nn.Module):
for info in info_dicts:
if not isinstance(info, dict):
continue
ac = info.get("audio_codes")
ac = info.get("codes", {}).get("audio")
if isinstance(ac, torch.Tensor):
audio_codes_list.append(ac)
@@ -365,7 +365,8 @@ class FishSpeechSlowARForConditionalGeneration(nn.Module):
if span_len > 1:
# --- Prefill ---
prompt_embeds_buf = info_dict.get("slow_ar_prompt_embeds")
embed = info_dict.get("embed", {})
prompt_embeds_buf = embed.get("prefill")
is_first_prefill = not isinstance(prompt_embeds_buf, torch.Tensor) or prompt_embeds_buf.ndim != 2
dev = input_ids.device
@@ -381,8 +382,8 @@ class FishSpeechSlowARForConditionalGeneration(nn.Module):
next_offset = min(span_len, total_prompt_len)
info_update: dict[str, Any] = {
"slow_ar_prompt_embeds": prompt_embeds_buf if next_offset < total_prompt_len else None,
"prefill_offset": next_offset,
"embed": {"prefill": prompt_embeds_buf if next_offset < total_prompt_len else None},
"meta": {"prefill_offset": next_offset},
}
take = prompt_embeds_buf[:span_len]
@@ -399,7 +400,7 @@ class FishSpeechSlowARForConditionalGeneration(nn.Module):
device=dev,
dtype=torch.long,
)
info_update["audio_codes"] = zeros
info_update["codes"] = {"audio": zeros}
input_ids_out = input_ids.clone()
input_ids_out[:] = self._audio_pad_token_id
@@ -407,7 +408,8 @@ class FishSpeechSlowARForConditionalGeneration(nn.Module):
else:
# Subsequent prefill chunk.
offset = int(info_dict.get("prefill_offset", 0) or 0)
meta = info_dict.get("meta", {})
offset = int(meta.get("prefill_offset", 0) or 0)
total_prompt_len = int(prompt_embeds_buf.shape[0])
s = max(0, min(offset, total_prompt_len))
e = max(0, min(offset + span_len, total_prompt_len))
@@ -426,20 +428,21 @@ class FishSpeechSlowARForConditionalGeneration(nn.Module):
input_ids.clone().fill_(self._audio_pad_token_id),
prompt_embeds,
{
"slow_ar_prompt_embeds": prompt_embeds_buf if next_offset < total_prompt_len else None,
"prefill_offset": next_offset,
"audio_codes": zeros,
"embed": {"prefill": prompt_embeds_buf if next_offset < total_prompt_len else None},
"meta": {"prefill_offset": next_offset},
"codes": {"audio": zeros},
},
)
# --- Decode: span_len == 1 ---
dev = input_ids.device
last_hidden = info_dict.get("last_slow_ar_hidden")
hs = info_dict.get("hidden_states", {})
last_hidden = hs.get("last")
if not isinstance(last_hidden, torch.Tensor):
# First decode step after prefill -- just embed the token directly.
logger.warning(
"preprocess decode: last_slow_ar_hidden not found (keys=%s), "
"preprocess decode: hidden_states.last not found (keys=%s), "
"returning plain embed (mtp_inputs will NOT be set)",
list(info_dict.keys()),
)
@@ -468,8 +471,8 @@ class FishSpeechSlowARForConditionalGeneration(nn.Module):
logger.debug("postprocess: empty hidden_states")
return {}
last = hidden_states[-1, :].detach().contiguous()
logger.debug("postprocess: saved last_slow_ar_hidden shape=%s", tuple(last.shape))
return {"last_slow_ar_hidden": last}
logger.debug("postprocess: saved hidden_states.last shape=%s", tuple(last.shape))
return {"hidden_states": {"last": last}}
# -------------------- prompt construction --------------------
@@ -2321,7 +2321,7 @@ class GlmImageModel(nn.Module):
upsampled_token_ids.append(tokens_upsampled.view(-1))
prior_token_image_ids_info = {
"prior_token_image_ids": upsampled_token_ids,
"ids": {"prior_image": upsampled_token_ids},
"image_grid_thw": image_grid_thw.tolist(),
}
@@ -2533,9 +2533,7 @@ class GlmImageForConditionalGeneration(nn.Module, SupportsMultiModal, SupportsPP
# image_grid_thw is NOT included because:
# 1. vLLM's pooling_output expects dict[str, torch.Tensor], not mixed types
# 2. ar2diffusion doesn't need it - the grid info is already encoded in tensor shape
prior_token_info = {
"prior_token_image_ids": upsampled_token_ids,
}
prior_token_info = {"ids": {"prior_image": upsampled_token_ids}}
# Debug: log prior_token_info
shapes = [t.shape for t in upsampled_token_ids]
@@ -608,16 +608,17 @@ class MammothModa2ARForConditionalGeneration(Qwen2_5_VLForConditionalGeneration)
num_reqs = int(logits.shape[0])
for i in range(num_reqs):
runtime_info = runtime_infos[i] if isinstance(runtime_infos[i], dict) else {}
omni_task = runtime_info.get("omni_task")
meta = runtime_info.get("meta", {})
omni_task = meta.get("omni_task")
if not isinstance(omni_task, list) or not omni_task or omni_task[0] != "t2i":
# Text/understanding/chat: forbid sampling from the extra gen vocab.
logits[i, self.language_model.base_vocab_size :] = neg_inf
continue
ar_width = runtime_info["ar_width"][0]
eol_token_id = runtime_info["eol_token_id"][0]
visual_start = runtime_info["visual_token_start_id"][0]
visual_end = runtime_info["visual_token_end_id"][0]
ar_width = meta["ar_width"][0]
eol_token_id = meta["eol_token_id"][0]
visual_start = meta["visual_token_start_id"][0]
visual_end = meta["visual_token_end_id"][0]
generated_len = runtime_info["generated_len"]
row = logits[i]
@@ -799,7 +799,7 @@ class MiMoAudioForConditionalGeneration(
return OmniOutput(
text_hidden_states=text_hidden_states.reshape(-1, text_hidden_states.shape[-1]),
multimodal_outputs={"code_predictor_codes": next_speech_tokens},
multimodal_outputs={"codes": {"audio": next_speech_tokens}},
)
if self.model_stage == "code2wav":
@@ -486,10 +486,10 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP):
return [ids]
if runtime_additional_information and all(
isinstance(info.get("code_flat_numel"), int) and int(info["code_flat_numel"]) > 0
isinstance(info.get("meta", {}).get("code_flat_numel"), int) and int(info["meta"]["code_flat_numel"]) > 0
for info in runtime_additional_information
):
sizes = [int(info["code_flat_numel"]) for info in runtime_additional_information]
sizes = [int(info["meta"]["code_flat_numel"]) for info in runtime_additional_information]
if sum(sizes) == n:
parts: list[torch.Tensor] = []
offset = 0
@@ -517,11 +517,11 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP):
if not runtime_additional_information:
return left_frames, chunk_frames
for i in range(min(num_req, len(runtime_additional_information))):
info = runtime_additional_information[i]
if "left_context_size" in info:
left_frames[i] = int(info["left_context_size"])
if "codec_chunk_frames" in info:
chunk_frames[i] = int(info["codec_chunk_frames"])
meta = runtime_additional_information[i].get("meta", {})
if "left_context_size" in meta:
left_frames[i] = int(meta["left_context_size"])
if "codec_chunk_frames" in meta:
chunk_frames[i] = int(meta["codec_chunk_frames"])
return left_frames, chunk_frames
def chunked_decode_streaming(
@@ -3,11 +3,13 @@ from typing import NamedTuple
import torch
from vllm.sequence import IntermediateTensors
from vllm_omni.data_entry_keys import OmniPayload
class OmniOutput(NamedTuple):
"""Output from the merged Omni model containing both text and audio."""
text_hidden_states: torch.Tensor
multimodal_outputs: dict | None = None
multimodal_outputs: OmniPayload | None = None
intermediate_tensors: IntermediateTensors | None = None
next_token_id: torch.Tensor | None = None
@@ -32,6 +32,7 @@ from vllm.v1.outputs import SamplerOutput
from vllm.v1.sample.metadata import SamplingMetadata
from vllm.v1.sample.sampler import Sampler
from vllm_omni.data_entry_keys import OmniPayload
from vllm_omni.model_executor.custom_process_mixin import CustomProcessMixin
from vllm_omni.model_executor.model_loader.weight_utils import download_weights_from_hf_specific
from vllm_omni.model_executor.models.output_templates import OmniOutput
@@ -666,6 +667,8 @@ class Qwen2_5OmniForConditionalGeneration(
# - For Decode segments, if per-request auxiliary decode embeddings are provided (optional),
# add them; otherwise, keep the original embedding.
payload: OmniPayload = info_dict
# Ensure we have base embeddings when only ids are provided
if input_embeds is None and input_ids is not None:
input_embeds = self.talker.embed_input_ids(input_ids)
@@ -673,23 +676,27 @@ class Qwen2_5OmniForConditionalGeneration(
span_len = input_ids.shape[0]
if span_len > 1:
# prefill
return self.thinker_to_talker_process(input_ids, input_embeds, **info_dict)
return self.thinker_to_talker_process(input_ids, input_embeds, payload)
else:
# decode
return self.thinker_to_talker_decode_one_step(input_ids, input_embeds, **info_dict)
return self.thinker_to_talker_decode_one_step(input_ids, input_embeds, payload)
def thinker_to_talker_process(
self,
input_ids: torch.Tensor,
input_embeds: torch.Tensor,
**info_dict: object,
payload: OmniPayload,
):
embed = payload.get("embed", {})
hs = payload.get("hidden_states", {})
ids = payload.get("ids", {})
update_dict = {}
prompt_embeds = info_dict.get("prompt_embeds") # Tensor [P,H]
thinker_result = info_dict.get("thinker_result") # Tensor [K,H]
prompt_token_ids = info_dict.get("prompt_token_ids") # list[int]
thinker_output_token_ids = info_dict.get("thinker_output_token_ids") # list[int]
prompt_embeds = embed.get("prefill") # Tensor [P,H]
thinker_result = hs.get("output") # Tensor [K,H]
prompt_token_ids = ids.get("prompt") # list[int]
thinker_output_token_ids = ids.get("output") # list[int]
if not isinstance(prompt_embeds, torch.Tensor):
prompt_embeds = torch.zeros(
@@ -714,7 +721,7 @@ class Qwen2_5OmniForConditionalGeneration(
)
if thinker_result.ndim == 2 and thinker_result.shape[0] > 0:
update_dict["thinker_reply_part"] = thinker_result[1:].detach().to("cpu").contiguous()
update_dict.setdefault("embed", {})["thinker_reply"] = thinker_result[1:].detach().to("cpu").contiguous()
return req_input_ids, req_embeds, update_dict
@@ -763,18 +770,20 @@ class Qwen2_5OmniForConditionalGeneration(
)
return prompt_token_ids_processed, prompt_embeds
def thinker_to_talker_decode_one_step(self, input_ids, input_embeds, **info_dict):
def thinker_to_talker_decode_one_step(self, input_ids, input_embeds, payload: OmniPayload):
embed = payload.get("embed", {})
update_dict = {}
# choose step vector in priority order
step_vec = None
q = info_dict.get("thinker_reply_part", None)
q = embed.get("thinker_reply", None)
if isinstance(q, torch.Tensor) and q.numel() > 0:
step_vec = q[0:1]
new_q = q[1:].detach().to("cpu").contiguous()
update_dict["thinker_reply_part"] = new_q
update_dict.setdefault("embed", {})["thinker_reply"] = new_q
else:
# B) per-request provided decode vector (optional)
dv = info_dict.get("decode_output_prompt_embeds") if isinstance(info_dict, dict) else None
dv = embed.get("decode")
if isinstance(dv, torch.Tensor) and dv.numel() > 0:
step_vec = dv[0:1] if dv.ndim == 2 else dv.view(1, -1)
elif (
@@ -36,6 +36,7 @@ from vllm.v1.outputs import SamplerOutput
from vllm.v1.sample.metadata import SamplingMetadata
from vllm.v1.sample.sampler import Sampler
from vllm_omni.data_entry_keys import Embeddings, HiddenStates, Ids, OmniPayload, OmniPayloadMeta
from vllm_omni.model_executor.custom_process_mixin import CustomProcessMixin
from vllm_omni.model_executor.models.output_templates import OmniOutput
from vllm_omni.model_executor.models.qwen3_omni.qwen3_omni_moe_thinker import (
@@ -175,15 +176,15 @@ class Qwen3OmniMoeForConditionalGeneration(
self.suppressed_tokens = self._get_talker_suppressed_tokens()
self.requires_raw_input_tokens = True
# Keys that should stay on GPU in model_intermediate_buffer to avoid CPU↔GPU round-trips
self.gpu_resident_buffer_keys: set[str] = {
"last_talker_hidden",
"trailing_text_hidden",
"tts_pad_embed_projected",
self.gpu_resident_buffer_keys: set[tuple[str, str]] = {
("hidden_states", "last"),
("hidden_states", "trailing_text"),
("embed", "tts_pad_projected"),
}
# Keys that need to be accumulated across streaming inputs
self.streaming_accumulated_keys: set[str] = {
"thinker_prefill_embeddings",
"thinker_hidden_states",
self.streaming_accumulated_keys: set[tuple[str, str]] = {
("embed", "prefill"),
("hidden_states", "output"),
}
elif self.model_stage == "code2wav":
@@ -429,8 +430,9 @@ class Qwen3OmniMoeForConditionalGeneration(
left_context_size = []
if runtime_additional_information is not None:
for info in runtime_additional_information:
if "left_context_size" in info:
left_context_size.append(info["left_context_size"])
meta = info.get("meta", {})
if "left_context_size" in meta:
left_context_size.append(meta["left_context_size"])
else:
logger.debug("No additional_information provided to code2wav stage.")
audio_tensors = self.generate_audio(codes, left_context_size, seq_token_counts)
@@ -459,7 +461,7 @@ class Qwen3OmniMoeForConditionalGeneration(
text_hidden_states, captured_layer_dict = model_outputs
# Compute thinker-side TTS token embeddings for BOS/EOS/PAD and expose via multimodal outputs.
# These will later be projected into talker text space by the talker stage.
multimodal_outputs = captured_layer_dict if captured_layer_dict is not None else {}
multimodal_outputs: OmniPayload = captured_layer_dict if captured_layer_dict is not None else {}
try:
thinker_tts_embeds = self.thinker.embed_input_ids(self.tts_tokens) # [1,3,thinker_hidden]
if (
@@ -468,9 +470,10 @@ class Qwen3OmniMoeForConditionalGeneration(
and thinker_tts_embeds.shape[1] == 3
):
bos_eos_pad = thinker_tts_embeds.to(text_hidden_states.device).chunk(3, dim=1) # 3 * [1,1,H]
multimodal_outputs["tts_bos_embed"] = [bos_eos_pad[0]]
multimodal_outputs["tts_eos_embed"] = [bos_eos_pad[1]]
multimodal_outputs["tts_pad_embed"] = [bos_eos_pad[2]]
embed = multimodal_outputs.setdefault("embed", {})
embed["tts_bos"] = [bos_eos_pad[0]]
embed["tts_eos"] = [bos_eos_pad[1]]
embed["tts_pad"] = [bos_eos_pad[2]]
except Exception:
# Best-effort; absence will be handled by talker with fallbacks
pass
@@ -494,9 +497,10 @@ class Qwen3OmniMoeForConditionalGeneration(
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")
code_predictor_codes = [info.get("code_predictor_codes") for info in info_dicts]
multimodal_outputs = {"code_predictor_codes": torch.cat(code_predictor_codes, dim=0)}
span_len = multimodal_outputs["code_predictor_codes"].shape[0]
code_predictor_codes = [info.get("codes", {}).get("audio") for info in info_dicts]
audio_codes = torch.cat(code_predictor_codes, dim=0)
multimodal_outputs: OmniPayload = {"codes": {"audio": audio_codes}}
span_len = audio_codes.shape[0]
talker_hidden = talker_hidden[:span_len]
return OmniOutput(text_hidden_states=talker_hidden, multimodal_outputs=multimodal_outputs)
elif self.model_stage == "code2wav":
@@ -640,47 +644,48 @@ class Qwen3OmniMoeForConditionalGeneration(
"""
Postprocess the talker hidden states.
"""
update_dict = {}
update_dict["last_talker_hidden"] = hidden_states[-1, :].detach()
return update_dict
return {"hidden_states": {"last": hidden_states[-1, :].detach()}}
def talker_preprocess(self, input_ids: torch.Tensor, input_embeds: torch.Tensor, **info_dict: dict):
"""
Preprocess talker embeds. Noted that we set the MTP here.
"""
payload: OmniPayload = info_dict
meta = payload.setdefault("meta", {})
# Ensure we have base embeddings when only ids are provided
if input_embeds is None and input_ids is not None:
input_embeds = self.talker.embed_input_ids(input_ids)
span_len = input_ids.shape[0]
update_dict = {}
update_dict: OmniPayload = {}
if span_len > 1:
# prefill
input_ids, input_embeds, update_dict = self.talker_preprocess_prefill(input_ids, input_embeds, **info_dict)
input_ids, input_embeds, update_dict = self.talker_preprocess_prefill(input_ids, input_embeds, payload)
code_predictor_codes = torch.zeros(
(input_embeds.shape[0], self.talker.num_code_groups),
device=self._module_device(self.talker),
dtype=torch.long,
)
update_dict["code_predictor_codes"] = code_predictor_codes
update_dict.setdefault("codes", {})["audio"] = code_predictor_codes
else:
# decode
if not info_dict.get("decode_flag", False):
if not meta.get("decode_flag", False):
# Prefill already consumed the first text token via the
# assistant bootstrap path, so decode starts from the
# remaining-text boundary rather than cumulative index 0.
prefill_consumed_text_tokens = info_dict.get("prefill_consumed_text_tokens")
prefill_consumed_text_tokens = meta.get("prefill_consumed_text_tokens")
if prefill_consumed_text_tokens is None:
raise RuntimeError("Missing prefill_consumed_text_tokens for talker decode handoff.")
info_dict["num_processed_tokens"] = prefill_consumed_text_tokens
update_dict["decode_flag"] = True
meta["num_processed_tokens"] = prefill_consumed_text_tokens
update_dict.setdefault("meta", {})["decode_flag"] = True
last_talker_hidden, text_step, update_dict = self.talker_preprocess_decode(
input_ids, input_embeds, update_dict, **info_dict
input_ids, input_embeds, update_dict, payload
)
update_dict["mtp_inputs"] = last_talker_hidden, text_step
update_dict["num_processed_tokens"] = info_dict.get("num_processed_tokens", 0) + span_len
update_dict.setdefault("meta", {})["num_processed_tokens"] = meta.get("num_processed_tokens", 0) + span_len
return input_ids, input_embeds, update_dict
def talker_mtp(
@@ -737,11 +742,16 @@ class Qwen3OmniMoeForConditionalGeneration(
self.tts_pad_embed = _proj_from_thinker(tts_pad_thinker)
return self.tts_bos_embed, self.tts_eos_embed, self.tts_pad_embed
def talker_preprocess_prefill(self, input_ids: torch.Tensor, input_embeds: torch.Tensor, **info_dict: dict):
# Containers to return per-request updates (e.g., code_predictor_hidden_per_request)
update_dict: dict[str, dict] = {}
def talker_preprocess_prefill(self, input_ids: torch.Tensor, input_embeds: torch.Tensor, payload: OmniPayload):
hs: HiddenStates = payload.get("hidden_states", {})
embed: Embeddings = payload.get("embed", {})
ids: Ids = payload.get("ids", {})
meta: OmniPayloadMeta = payload.get("meta", {})
voice_type = info_dict.get("speaker")
# Containers to return per-request updates (e.g., code_predictor_hidden_per_request)
update_dict: OmniPayload = {}
voice_type = payload.get("speaker")
if voice_type is not None and isinstance(voice_type, (list, tuple)) and len(voice_type) > 0:
voice_type = voice_type[0]
if not isinstance(voice_type, str) or not voice_type.strip():
@@ -749,40 +759,34 @@ class Qwen3OmniMoeForConditionalGeneration(
voice_type = self.default_tts_text_spk_type
else:
voice_type = str(voice_type).lower().strip()
start_index = info_dict.get("num_processed_tokens", 0)
start_index = meta.get("num_processed_tokens", 0)
end_index = start_index + input_embeds.shape[0]
# Read thinker outputs for prefill
thinker_sequence_embeds = info_dict.get("thinker_prefill_embeddings").to(
thinker_sequence_embeds = embed["prefill"].to(
device=self._module_device(self.talker), dtype=torch.bfloat16
) # Tensor [P,H]
thinker_hidden_states = info_dict.get("thinker_hidden_states").to(
thinker_hidden_states = hs["output"].to(
device=self._module_device(self.talker), dtype=torch.bfloat16
) # Tensor [K,H]
thinker_sequences = (
info_dict.get("thinker_sequences")
if info_dict.get("thinker_sequences") is None
else torch.as_tensor(info_dict.get("thinker_sequences"), device=self._module_device(self.talker))
ids.get("all")
if ids.get("all") is None
else torch.as_tensor(ids["all"], device=self._module_device(self.talker))
)
thinker_chatml_ids = (
info_dict.get("thinker_input_ids")
if info_dict.get("thinker_input_ids") is None
else torch.as_tensor(info_dict.get("thinker_input_ids"), device=self._module_device(self.talker))
ids.get("prompt")
if ids.get("prompt") is None
else torch.as_tensor(ids["prompt"], device=self._module_device(self.talker))
)
tts_bos_thinker = info_dict.get("tts_bos_embed").to(
device=self._module_device(self.talker), dtype=torch.bfloat16
)
tts_eos_thinker = info_dict.get("tts_eos_embed").to(
device=self._module_device(self.talker), dtype=torch.bfloat16
)
tts_pad_thinker = info_dict.get("tts_pad_embed").to(
device=self._module_device(self.talker), dtype=torch.bfloat16
)
tts_bos_thinker = embed["tts_bos"].to(device=self._module_device(self.talker), dtype=torch.bfloat16)
tts_eos_thinker = embed["tts_eos"].to(device=self._module_device(self.talker), dtype=torch.bfloat16)
tts_pad_thinker = embed["tts_pad"].to(device=self._module_device(self.talker), dtype=torch.bfloat16)
if thinker_sequence_embeds is None or thinker_hidden_states is None:
raise ValueError(
"additional_information_by_req_id must include "
"'thinker_prefill_embeddings' and 'thinker_hidden_states' for talker prefill."
"'embed.prefill' and 'hidden_states.output' for talker prefill."
)
# Normalize to tensors
@@ -837,7 +841,7 @@ class Qwen3OmniMoeForConditionalGeneration(
# compatible with old shape [1,S,D]
rem_tail = trailing_text_hidden.squeeze(0)
if rem_tail.shape[0] > 0:
update_dict["trailing_text_hidden"] = rem_tail.detach()
update_dict.setdefault("hidden_states", {})["trailing_text"] = rem_tail.detach()
# Also persist projected tts_pad for decode fallback if needed
if isinstance(tts_pad_thinker, torch.Tensor):
pad_in = tts_pad_thinker
@@ -846,27 +850,27 @@ class Qwen3OmniMoeForConditionalGeneration(
if pad_in.ndim == 1:
pad_in = pad_in.view(1, 1, -1)
pad_proj = self.talker.text_projection(pad_in.to(self._module_device(self.talker)))
update_dict["tts_pad_embed_projected"] = pad_proj.detach()
update_dict.setdefault("embed", {})["tts_pad_projected"] = pad_proj.detach()
except Exception:
pass
update_dict["prefill_consumed_text_tokens"] = 1
self._talker_cache_thinker_decode_embeds(info_dict, update_dict)
update_dict.setdefault("meta", {})["prefill_consumed_text_tokens"] = 1
self._talker_cache_thinker_decode_embeds(embed, update_dict)
return req_input_ids[start_index:end_index], req_embeds[start_index:end_index], update_dict
def _talker_cache_thinker_decode_embeds(
self,
info_dict: dict[str, Any],
update_dict: dict[str, Any],
embed: Embeddings,
update_dict: OmniPayload,
) -> None:
"""
Cache thinker embeds for decode stage.
"""
thinker_decode_embeds = info_dict.get("thinker_decode_embeddings", None)
thinker_decode_embeds = embed.get("decode", None)
if thinker_decode_embeds is not None:
cached_thinker_decode_embeds = info_dict.get("cached_thinker_decode_embeddings", None)
cached_thinker_decode_embeds = embed.get("cached_decode", None)
if cached_thinker_decode_embeds is None:
update_dict["cached_thinker_decode_embeddings"] = thinker_decode_embeds
update_dict.setdefault("embed", {})["cached_decode"] = thinker_decode_embeds
else:
cached_thinker_decode_embeds = cached_thinker_decode_embeds.to(
device=self._module_device(self.talker), dtype=torch.bfloat16
@@ -874,10 +878,10 @@ class Qwen3OmniMoeForConditionalGeneration(
thinker_decode_embeds = thinker_decode_embeds.to(
device=self._module_device(self.talker), dtype=torch.bfloat16
)
update_dict["cached_thinker_decode_embeddings"] = torch.cat(
update_dict.setdefault("embed", {})["cached_decode"] = torch.cat(
[cached_thinker_decode_embeds, thinker_decode_embeds], dim=0
)
update_dict["thinker_decode_embeddings"] = None
update_dict.setdefault("embed", {})["decode"] = None
def _thinker_to_talker_prefill(
self,
@@ -964,23 +968,27 @@ class Qwen3OmniMoeForConditionalGeneration(
def _thinker_decode_to_talker_decode(
self,
info_dict: dict,
payload: OmniPayload,
device: torch.device,
update_dict,
):
"""
Project thinker outputs to talker inputs during prefill stage.
Project thinker outputs to talker inputs during decode stage.
Returns:
(input_ids, input_embeds) for talker
text_step embedding for talker
"""
cached_thinker_decode_embeds = info_dict.get("cached_thinker_decode_embeddings", None)
thinker_decode_embed = info_dict.get("thinker_decode_embeddings", None)
start_index = info_dict.get("num_processed_tokens", 0)
thinker_output_token_ids = info_dict.get("thinker_output_token_ids", [])
embed = payload.get("embed", {})
meta = payload.get("meta", {})
ids = payload.get("ids", {})
cached_thinker_decode_embeds = embed.get("cached_decode", None)
thinker_decode_embed = embed.get("decode", None)
start_index = meta.get("num_processed_tokens", 0)
thinker_output_token_ids = ids.get("output", [])
if start_index >= len(thinker_output_token_ids) - 1:
if info_dict.get("finished_flag"):
if meta.get("finished"):
return self.tts_pad_embed.to(device)
update_dict["finished_flag"] = True
update_dict.setdefault("meta", {})["finished"] = True
return self.tts_eos_embed.to(device)
if cached_thinker_decode_embeds is not None and start_index < cached_thinker_decode_embeds.shape[0]:
@@ -989,25 +997,26 @@ class Qwen3OmniMoeForConditionalGeneration(
if thinker_decode_embed is not None:
thinker_decode_embed = thinker_decode_embed.to(device)
cached_thinker_decode_embeds = torch.cat([cached_thinker_decode_embeds, thinker_decode_embed], dim=0)
update_dict["cached_thinker_decode_embeddings"] = cached_thinker_decode_embeds
update_dict.setdefault("embed", {})["cached_decode"] = cached_thinker_decode_embeds
else:
thinker_embed = thinker_decode_embed
if thinker_embed.device != device:
thinker_embed = thinker_embed.to(device)
update_dict["thinker_decode_embeddings"] = None
update_dict.setdefault("embed", {})["decode"] = None
return self.talker.text_projection(thinker_embed).to(device)
def talker_preprocess_decode(
self, input_ids: torch.Tensor, input_embeds: torch.Tensor, update_dict: dict, **info_dict: dict
self, input_ids: torch.Tensor, input_embeds: torch.Tensor, update_dict: OmniPayload, payload: OmniPayload
):
hs = payload.get("hidden_states", {})
last_talker_hidden = None
text_step = None
try:
if self.vllm_config.model_config.async_chunk:
text_step = self._thinker_decode_to_talker_decode(info_dict, input_ids.device, update_dict)
text_step = self._thinker_decode_to_talker_decode(payload, input_ids.device, update_dict)
else:
q_tail = info_dict.get("trailing_text_hidden", None)
q_tail = hs.get("trailing_text", None)
if isinstance(q_tail, torch.Tensor) and q_tail.numel() > 0:
use_vec = q_tail[0:1, :]
new_q_tail = (
@@ -1016,11 +1025,11 @@ class Qwen3OmniMoeForConditionalGeneration(
else self.tts_pad_embed.to(input_embeds.device, dtype=input_embeds.dtype)
)
text_step = use_vec.to(input_embeds.device, dtype=input_embeds.dtype)
update_dict["trailing_text_hidden"] = new_q_tail
update_dict.setdefault("hidden_states", {})["trailing_text"] = new_q_tail
else:
text_step = self.tts_pad_embed.to(input_embeds.device, dtype=input_embeds.dtype)
last_talker_hidden_tensor = info_dict.get("last_talker_hidden")
last_talker_hidden_tensor = hs.get("last")
if last_talker_hidden_tensor is not None:
last_talker_hidden = last_talker_hidden_tensor.to(input_embeds.device, dtype=input_embeds.dtype)
last_talker_hidden = last_talker_hidden.reshape(*last_talker_hidden.shape[-2:]) # [1, hidden_size]
@@ -545,7 +545,9 @@ class Qwen3MoeLLMModel(_Qwen3MoeLLMModel):
if captured_hidden_states is not None and capture_set is not None:
if layer_idx in capture_set:
captured_hidden_states[str(layer_idx)] = hidden_states.clone().view(-1, hidden_states.shape[-1])
hs = captured_hidden_states.setdefault("hidden_states", {})
layers = hs.setdefault("layers", {})
layers[layer_idx] = hidden_states.clone().view(-1, hidden_states.shape[-1])
hidden_states, residual = layer(
positions,
@@ -234,9 +234,10 @@ class Qwen3TTSCode2Wav(nn.Module):
for i, info in enumerate(runtime_additional_information):
if i >= len(left_context_size):
break
if "left_context_size" in info:
meta = info.get("meta", {})
if "left_context_size" in meta:
# left_context_size may come through serialization as an int, [int], or tensor([int]).
value = info["left_context_size"]
value = meta["left_context_size"]
if isinstance(value, list):
value = value[0] if value else 0
if isinstance(value, torch.Tensor):
@@ -26,6 +26,7 @@ from vllm.model_executor.models.utils import AutoWeightsLoader, PPMissingLayer,
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.utils.audio import mel_filter_bank
from vllm_omni.utils.voice_cache import VoiceEmbeddingCache
@@ -343,7 +344,7 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
self.mtp_hidden_size = int(self.talker_config.hidden_size)
# OmniGPUModelRunner will store talker_mtp output under this key in
# per-request additional_information.
self.talker_mtp_output_key = "audio_codes"
self.talker_mtp_output_key = ("codes", "audio")
self.model = Qwen3Model(vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model"))
@@ -402,11 +403,11 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
# 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[str] = {
"audio_codes",
"last_talker_hidden",
"tts_pad_embed",
"tailing_text_hidden",
self.gpu_resident_buffer_keys: set[tuple[str, str]] = {
("codes", "audio"),
("hidden_states", "last"),
("embed", "tts_pad"),
("hidden_states", "trailing_text"),
}
# Tokenizer for prompt building.
@@ -475,18 +476,20 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
for info in info_dicts:
if not isinstance(info, dict):
continue
ac = info.get("audio_codes")
codes = info.get("codes", {})
meta = info.get("meta", {})
ac = codes.get("audio")
if isinstance(ac, torch.Tensor):
audio_codes_list.append(ac)
cs = info.get("codec_streaming")
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)
)
ref_code = info.get("ref_code")
ref_code = codes.get("ref")
if isinstance(ref_code, torch.Tensor) and ref_code.numel() > 0:
ref_code_tensor = ref_code
ref_len = info.get("ref_code_len")
ref_len = meta.get("ref_code_len")
if ref_len is None:
continue
if isinstance(ref_len, torch.Tensor):
@@ -511,13 +514,13 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
audio_codes = torch.cat(audio_codes_list, dim=0)
span_len = int(audio_codes.shape[0])
hidden = hidden[:span_len]
mm: dict[str, torch.Tensor] = {"audio_codes": audio_codes}
mm: OmniPayload = {"codes": {"audio": audio_codes}}
if ref_code_len_list:
mm["ref_code_len"] = torch.cat(ref_code_len_list, dim=0)[:span_len]
mm.setdefault("meta", {})["ref_code_len"] = torch.cat(ref_code_len_list, dim=0)[:span_len]
if ref_code_tensor is not None:
mm["ref_code"] = [ref_code_tensor]
mm.setdefault("codes", {})["ref"] = [ref_code_tensor]
if codec_streaming_list:
mm["codec_streaming"] = torch.cat(codec_streaming_list, dim=0)[:span_len]
mm.setdefault("meta", {})["codec_streaming"] = torch.cat(codec_streaming_list, dim=0)[:span_len]
return OmniOutput(text_hidden_states=hidden, multimodal_outputs=mm)
# -------------------- preprocess / postprocess --------------------
@@ -536,6 +539,11 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
merged.setdefault(k, v)
info_dict = merged
payload: OmniPayload = info_dict
embed = payload.get("embed", {})
hs = payload.get("hidden_states", {})
meta = payload.get("meta", {})
span_len = int(input_ids.shape[0])
if span_len <= 0:
return input_ids, input_embeds if input_embeds is not None else self.embed_input_ids(input_ids), {}
@@ -545,7 +553,7 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
raise ValueError("Missing additional_information.text for Qwen3-TTS AR talker.")
task_type = (info_dict.get("task_type") or ["CustomVoice"])[0]
codec_streaming_val = info_dict.get("codec_streaming")
codec_streaming_val = meta.get("codec_streaming")
if isinstance(codec_streaming_val, list):
codec_streaming_raw = codec_streaming_val[0] if codec_streaming_val else None
else:
@@ -557,8 +565,8 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
if span_len > 1:
# Prefill (prompt embeddings)
prompt_embeds_cpu = info_dict.get("talker_prompt_embeds")
tts_pad_embed_cpu = info_dict.get("tts_pad_embed")
prompt_embeds_cpu = embed.get("prefill")
tts_pad_embed_cpu = embed.get("tts_pad")
tts_pad_embed = None
if isinstance(tts_pad_embed_cpu, torch.Tensor) and tts_pad_embed_cpu.numel() > 0:
tts_pad_embed = tts_pad_embed_cpu.to(device=input_ids.device, dtype=torch.bfloat16).reshape(1, -1)
@@ -573,17 +581,18 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
# Store full prompt embeddings on CPU (large, prefill-only).
# tailing_text_hidden and tts_pad_embed stay on GPU (gpu_resident_buffer_keys).
prompt_embeds_cpu = full_prompt_embeds.detach().to("cpu").contiguous()
info_update: dict[str, Any] = {
"talker_prompt_embeds": prompt_embeds_cpu,
"tailing_text_hidden": tailing_text_hidden.detach(),
"tts_pad_embed": tts_pad_embed.detach(),
"talker_prefill_offset": 0,
"codec_streaming": codec_streaming,
info_update: OmniPayload = {
"embed": {
"prefill": prompt_embeds_cpu,
"tts_pad": tts_pad_embed.detach(),
},
"hidden_states": {"trailing_text": tailing_text_hidden.detach()},
"meta": {"talker_prefill_offset": 0, "codec_streaming": codec_streaming},
}
if isinstance(ref_code, torch.Tensor) and ref_code.numel() > 0:
info_update["ref_code"] = ref_code.detach().to("cpu").contiguous()
info_update.setdefault("codes", {})["ref"] = ref_code.detach().to("cpu").contiguous()
if ref_code_len is not None:
info_update["ref_code_len"] = int(ref_code_len)
info_update["meta"]["ref_code_len"] = int(ref_code_len)
# Always return a span_len slice; if the scheduled placeholder is longer, pad with tts_pad_embed.
# This preserves placeholder/embedding alignment.
offset = 0
@@ -595,12 +604,12 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
pad_rows = tts_pad_embed.reshape(1, -1).to("cpu").expand(pad_n, -1)
take = torch.cat([take, pad_rows], dim=0)
prompt_embeds = take.to(device=input_ids.device, dtype=torch.bfloat16)
info_update["talker_prefill_offset"] = int(offset + span_len)
info_update["meta"]["talker_prefill_offset"] = int(offset + span_len)
else:
# Subsequent prefill chunk: slice from stored embeddings at running offset.
if tts_pad_embed is None:
raise RuntimeError("Missing `tts_pad_embed` in additional_information; prefill must initialize it.")
offset = int(info_dict.get("talker_prefill_offset", 0) or 0)
offset = int(meta.get("talker_prefill_offset", 0) or 0)
if offset < 0:
offset = 0
s = max(0, min(offset, int(prompt_embeds_cpu.shape[0])))
@@ -611,8 +620,9 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
pad_rows = tts_pad_embed.reshape(1, -1).to("cpu").expand(pad_n, -1)
take = torch.cat([take, pad_rows], dim=0)
prompt_embeds = take.to(device=input_ids.device, dtype=torch.bfloat16)
info_update = {"talker_prefill_offset": int(offset + span_len)}
info_update["codec_streaming"] = codec_streaming
info_update = {
"meta": {"talker_prefill_offset": int(offset + span_len), "codec_streaming": codec_streaming}
}
# When inputs_embeds is set, token ids are ignored by the model but must stay in-vocab for vLLM bookkeeping.
input_ids_out = input_ids.clone()
@@ -623,18 +633,18 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
device=input_ids.device,
dtype=torch.long,
)
info_update["audio_codes"] = zeros
info_update.setdefault("codes", {})["audio"] = zeros
return input_ids_out, prompt_embeds, info_update
# Decode: span_len == 1
# Pop one text-step vector from tailing_text_hidden queue.
# These tensors stay on GPU via gpu_resident_buffer_keys - .to() is a no-op.
tts_pad_embed_buf = info_dict.get("tts_pad_embed")
tts_pad_embed_buf = embed.get("tts_pad")
if not isinstance(tts_pad_embed_buf, torch.Tensor):
raise RuntimeError("Missing `tts_pad_embed` in additional_information; prefill must run first.")
tts_pad_embed = tts_pad_embed_buf.to(device=input_ids.device, dtype=torch.bfloat16).reshape(1, -1)
tail = info_dict.get("tailing_text_hidden")
tail = hs.get("trailing_text")
if isinstance(tail, torch.Tensor) and tail.ndim == 2 and tail.shape[0] > 0:
text_step = tail[:1].to(device=input_ids.device, dtype=torch.bfloat16).reshape(1, -1)
new_tail = tail[1:] if tail.shape[0] > 1 else tail[:0]
@@ -642,9 +652,9 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
text_step = tts_pad_embed
new_tail = tail if isinstance(tail, torch.Tensor) else torch.empty((0, tts_pad_embed.shape[-1]))
last_hidden = info_dict.get("last_talker_hidden")
last_hidden = hs.get("last")
if not isinstance(last_hidden, torch.Tensor):
raise RuntimeError("Missing `last_talker_hidden` in additional_information; postprocess must run.")
raise RuntimeError("Missing hidden_states['last'] in additional_information; postprocess must run.")
past_hidden = last_hidden.to(device=input_ids.device, dtype=torch.bfloat16).reshape(1, -1)
# Use OmniGPUModelRunner talker_mtp fast-path for residual codebooks and per-step inputs_embeds update.
@@ -654,9 +664,9 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
inputs_embeds_out = last_id_hidden.reshape(1, -1)
info_update = {
"tailing_text_hidden": new_tail,
"hidden_states": {"trailing_text": new_tail},
"mtp_inputs": (past_hidden, text_step),
"codec_streaming": codec_streaming,
"meta": {"codec_streaming": codec_streaming},
}
return input_ids, inputs_embeds_out, info_update
@@ -666,7 +676,7 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
if hidden_states.numel() == 0:
return {}
last = hidden_states[-1, :].detach()
return {"last_talker_hidden": last}
return {"hidden_states": {"last": last}}
# -------------------- prompt construction helpers --------------------