[Misc] Remove Dynin-Omni and dots.tts support (#7655)
Signed-off-by: wangyu <410167048@qq.com> Signed-off-by: Yueqian Lin <linyueqian@outlook.com> Co-authored-by: Yueqian Lin <linyueqian@outlook.com>
This commit is contained in:
1 parent
3f94c417be
commit
6a03e45c34
56 files changed
+133
-12749
No files matched your search
@@ -1,8 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
# NOTE: Do not import model classes in this file. Importing any
|
||||
# submodule in this package triggers __init__.py execution, and
|
||||
# both the model registry and pipeline registry import submodules
|
||||
# directly — heavy imports here would be loaded as a side effect
|
||||
# even though nothing depends on these re-exports.
|
||||
@@ -1,457 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# Copyright 2026 The vLLM-Omni team.
|
||||
# Copyright (c) rednote-hilab. All rights reserved.
|
||||
# Adapted from:
|
||||
# https://github.com/rednote-hilab/dots.tts/tree/a393d2e/src/dots_tts/modules/backbone
|
||||
#
|
||||
# Merged from two upstream files (preserved as-is, inference behaviour
|
||||
# unchanged; only internal imports were folded inline):
|
||||
# - modules/backbone/layers.py -> Dropout, Mlp, rotate_half,
|
||||
# apply_rotary_pos_emb, RotaryEmbedding,
|
||||
# MultiHeadAttention
|
||||
# (Conv1d / ConvTranspose1d are NOT
|
||||
# re-vendored here — they already live in
|
||||
# dots_tts_vocoder.py)
|
||||
# - modules/backbone/dit.py -> modulate, TimestepEmbedder, FinalLayer,
|
||||
# DiTBlock, DiT
|
||||
#
|
||||
# Per-section upstream attributions are preserved at each section header.
|
||||
# Nothing in this file diverges from upstream behaviour.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from einops import rearrange
|
||||
|
||||
# ============================================================================
|
||||
# Building blocks (adapted from modules/backbone/layers.py)
|
||||
# ----------------------------------------------------------------------------
|
||||
# Conv1d / ConvTranspose1d from layers.py are already vendored in
|
||||
# dots_tts_vocoder.py (they are used by the BigVGAN-style AudioVAE). The
|
||||
# pieces below are the ones consumed by the DiT flow-matching head.
|
||||
# ============================================================================
|
||||
|
||||
|
||||
class Dropout(nn.Module):
|
||||
def __init__(self, p: float = 0.5, inplace: bool = False, force_drop: bool = False, **_kwargs):
|
||||
super().__init__()
|
||||
if p < 0.0 or p > 1.0:
|
||||
raise ValueError(f"dropout probability has to be between 0 and 1, but got {p}")
|
||||
self.p = p
|
||||
self.inplace = inplace
|
||||
self.force_drop = force_drop
|
||||
|
||||
def forward(self, x, **_kwargs):
|
||||
return F.dropout(
|
||||
x,
|
||||
p=self.p,
|
||||
training=True if self.force_drop else self.training,
|
||||
inplace=self.inplace,
|
||||
)
|
||||
|
||||
|
||||
class Mlp(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
hidden_size,
|
||||
ffn_hidden_size=4096,
|
||||
act_layer=nn.GELU,
|
||||
dropout=0.0,
|
||||
**_kwargs,
|
||||
):
|
||||
super().__init__()
|
||||
self.fc1 = nn.Linear(hidden_size, ffn_hidden_size)
|
||||
self.act = act_layer()
|
||||
self.fc2 = nn.Linear(ffn_hidden_size, hidden_size)
|
||||
self.drop = Dropout(dropout)
|
||||
|
||||
def forward(self, x, _mask=None):
|
||||
x = self.fc1(x)
|
||||
x = self.act(x)
|
||||
x = self.drop(x)
|
||||
x = self.fc2(x)
|
||||
return self.drop(x)
|
||||
|
||||
|
||||
def rotate_half(x):
|
||||
x1, x2 = x.chunk(2, dim=-1)
|
||||
return torch.cat((-x2, x1), dim=-1)
|
||||
|
||||
|
||||
@torch.autocast(enabled=False, device_type="cuda")
|
||||
def apply_rotary_pos_emb(pos, t):
|
||||
if pos.dim() == 3:
|
||||
pos = pos.unsqueeze(1)
|
||||
return t * pos.cos() + rotate_half(t) * pos.sin()
|
||||
|
||||
|
||||
class RotaryEmbedding(nn.Module):
|
||||
def __init__(self, dim, theta=50000):
|
||||
super().__init__()
|
||||
self.register_buffer(
|
||||
"inv_freq",
|
||||
1.0 / (theta ** (torch.arange(0, dim, 2).float() / dim)),
|
||||
persistent=False,
|
||||
)
|
||||
self._theta = float(theta)
|
||||
|
||||
def _apply(self, fn):
|
||||
inv_freq = self.inv_freq
|
||||
super()._apply(fn)
|
||||
self.inv_freq = inv_freq.to(device=self.inv_freq.device, dtype=torch.float32)
|
||||
return self
|
||||
|
||||
@torch.autocast(enabled=False, device_type="cuda")
|
||||
def forward(self, t):
|
||||
inv_freq = self.inv_freq
|
||||
if inv_freq.device != t.device:
|
||||
raise RuntimeError(f"RotaryEmbedding buffer device mismatch: inv_freq={inv_freq.device} input={t.device}.")
|
||||
t = t.to(dtype=inv_freq.dtype)
|
||||
if t.dim() == 1:
|
||||
freqs = torch.einsum("i , j -> i j", t, inv_freq)
|
||||
else:
|
||||
freqs = torch.einsum("bi, j -> bij", t, inv_freq)
|
||||
return torch.cat((freqs, freqs), dim=-1)
|
||||
|
||||
|
||||
class MultiHeadAttention(nn.Module):
|
||||
"""Multi-head attention"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hidden_size: int,
|
||||
num_heads: int = 8,
|
||||
qkv_bias: bool = False,
|
||||
qk_norm: bool = False,
|
||||
attn_drop: float = 0.0,
|
||||
dropout: float = 0.0,
|
||||
norm_layer: str = "LayerNorm",
|
||||
rotary_bias: bool = False,
|
||||
rotary_theta: float | None = 50000,
|
||||
**_kwargs,
|
||||
):
|
||||
super().__init__()
|
||||
assert hidden_size % num_heads == 0, "hidden_size should be divisible by num_heads"
|
||||
self.num_heads = num_heads
|
||||
self.head_dim = hidden_size // num_heads
|
||||
self.scale = self.head_dim**-0.5
|
||||
self.rotary_bias = rotary_bias
|
||||
|
||||
self.q_proj = nn.Linear(hidden_size, hidden_size, bias=qkv_bias)
|
||||
self.k_proj = nn.Linear(hidden_size, hidden_size, bias=qkv_bias)
|
||||
self.v_proj = nn.Linear(hidden_size, hidden_size, bias=qkv_bias)
|
||||
|
||||
norm_layer = getattr(nn, norm_layer)
|
||||
self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
|
||||
self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
|
||||
|
||||
self.attn_drop = Dropout(attn_drop)
|
||||
self.o_proj = nn.Linear(hidden_size, hidden_size)
|
||||
self.o_dropout = Dropout(dropout)
|
||||
|
||||
if self.rotary_bias:
|
||||
self.rotary = RotaryEmbedding(self.head_dim, theta=rotary_theta)
|
||||
|
||||
def forward(self, q, k=None, v=None, mask=None, pos_ids=None, **_kwargs):
|
||||
k = k or q
|
||||
v = v or q
|
||||
B, L, _ = q.shape
|
||||
_, S, _ = v.shape
|
||||
if mask is not None:
|
||||
if mask.ndim == 2: # [B, L]
|
||||
assert L == S
|
||||
mask = rearrange(mask, "b j -> b 1 1 j")
|
||||
mask = mask.expand(-1, self.num_heads, L, -1)
|
||||
elif mask.ndim == 3: # [B, L, S]
|
||||
assert mask.size(1) == L and mask.size(2) == S
|
||||
mask = mask.unsqueeze(1).expand(-1, self.num_heads, -1, -1)
|
||||
|
||||
q, k, v = self.q_proj(q), self.k_proj(k), self.v_proj(v)
|
||||
q = rearrange(q, "b n (h d) -> b h n d", h=self.num_heads)
|
||||
k = rearrange(k, "b n (h d) -> b h n d", h=self.num_heads)
|
||||
v = rearrange(v, "b n (h d) -> b h n d", h=self.num_heads)
|
||||
q, k = self.q_norm(q), self.k_norm(k)
|
||||
|
||||
# Apply rotary
|
||||
if self.rotary_bias:
|
||||
if L == S:
|
||||
if pos_ids is None:
|
||||
rotary_emb = self.rotary(torch.arange(L, device=q.device))
|
||||
else:
|
||||
rotary_emb = self.rotary(pos_ids)
|
||||
q, k = (apply_rotary_pos_emb(rotary_emb, tensor) for tensor in (q, k))
|
||||
else:
|
||||
q_rotary_emb = self.rotary(torch.arange(L, device=q.device))
|
||||
k_rotary_emb = self.rotary(torch.arange(S, device=k.device))
|
||||
q = apply_rotary_pos_emb(q_rotary_emb, q)
|
||||
k = apply_rotary_pos_emb(k_rotary_emb, k)
|
||||
|
||||
attn_bias = torch.zeros(B, self.num_heads, L, S, dtype=q.dtype, device=q.device)
|
||||
|
||||
if mask is not None:
|
||||
attn_bias.masked_fill_(mask.logical_not(), float("-inf"))
|
||||
|
||||
out = F.scaled_dot_product_attention(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
attn_mask=attn_bias,
|
||||
dropout_p=self.attn_drop.p if self.training else 0.0,
|
||||
)
|
||||
|
||||
out = rearrange(out, "b h n d -> b n (h d)")
|
||||
return self.o_dropout(self.o_proj(out))
|
||||
|
||||
def decode_step(self, x, *, cache, positions: torch.Tensor):
|
||||
if x.size(1) <= 0:
|
||||
raise ValueError("MultiHeadAttention.decode_step expects a non-empty input.")
|
||||
if positions.ndim != 1 or positions.size(0) != x.size(1):
|
||||
raise ValueError("MultiHeadAttention.decode_step positions must match the decode block length.")
|
||||
|
||||
q = self.q_proj(x)
|
||||
k = self.k_proj(x)
|
||||
v = self.v_proj(x)
|
||||
|
||||
q = rearrange(q, "b n (h d) -> b h n d", h=self.num_heads)
|
||||
k = rearrange(k, "b n (h d) -> b h n d", h=self.num_heads)
|
||||
v = rearrange(v, "b n (h d) -> b h n d", h=self.num_heads)
|
||||
q, k = self.q_norm(q), self.k_norm(k)
|
||||
block_len = q.size(2)
|
||||
|
||||
if self.rotary_bias:
|
||||
rotary_emb = self.rotary(positions)
|
||||
q = apply_rotary_pos_emb(rotary_emb, q)
|
||||
k = apply_rotary_pos_emb(rotary_emb, k)
|
||||
|
||||
cached_k, cached_v = cache
|
||||
cached_k.index_copy_(2, positions, k)
|
||||
cached_v.index_copy_(2, positions, v)
|
||||
|
||||
cache_capacity = cached_k.size(2)
|
||||
key_positions = torch.arange(
|
||||
cache_capacity,
|
||||
device=x.device,
|
||||
dtype=torch.long,
|
||||
).unsqueeze(0)
|
||||
query_positions = positions.unsqueeze(1)
|
||||
causal_mask = key_positions <= query_positions
|
||||
valid_mask = key_positions <= positions[-1]
|
||||
attn_bias = torch.zeros(
|
||||
q.size(0),
|
||||
self.num_heads,
|
||||
block_len,
|
||||
cache_capacity,
|
||||
dtype=q.dtype,
|
||||
device=q.device,
|
||||
)
|
||||
attn_bias.masked_fill_(
|
||||
(causal_mask & valid_mask).unsqueeze(0).unsqueeze(0).logical_not(),
|
||||
float("-inf"),
|
||||
)
|
||||
|
||||
out = F.scaled_dot_product_attention(
|
||||
q,
|
||||
cached_k,
|
||||
cached_v,
|
||||
attn_mask=attn_bias,
|
||||
dropout_p=self.attn_drop.p if self.training else 0.0,
|
||||
)
|
||||
out = rearrange(out, "b h n d -> b n (h d)")
|
||||
return self.o_dropout(self.o_proj(out)), cache
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# DiT flow-matching head (adapted from modules/backbone/dit.py)
|
||||
# ----------------------------------------------------------------------------
|
||||
# DiT.__init__ takes a ``transformer_config`` object exposing ``.to_dict()``,
|
||||
# ``.hidden_size`` and ``.num_layers``. Upstream constructs it from a pydantic
|
||||
# config class higher up the stack; vLLM-Omni callers can pass anything that
|
||||
# satisfies the same minimal interface (e.g. a stdlib @dataclass with a
|
||||
# ``to_dict`` method or SimpleNamespace). See dots_tts_talker.py for the
|
||||
# concrete soar-checkpoint config factory.
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def modulate(x, shift, scale, **_kwargs):
|
||||
return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
|
||||
|
||||
|
||||
class TimestepEmbedder(nn.Module):
|
||||
def __init__(self, hidden_size, frequency_embedding_size=256):
|
||||
super().__init__()
|
||||
self.mlp = nn.Sequential(
|
||||
nn.Linear(frequency_embedding_size, hidden_size, bias=True),
|
||||
nn.SiLU(),
|
||||
nn.Linear(hidden_size, hidden_size, bias=True),
|
||||
)
|
||||
self.frequency_embedding_size = frequency_embedding_size
|
||||
|
||||
@staticmethod
|
||||
def timestep_embedding(t, dim, max_period=10000):
|
||||
half = dim // 2
|
||||
freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(
|
||||
device=t.device
|
||||
)
|
||||
args = t[:, None].float() * freqs[None]
|
||||
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
||||
if dim % 2:
|
||||
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
||||
return embedding
|
||||
|
||||
def forward(self, t):
|
||||
t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
|
||||
return self.mlp(t_freq)
|
||||
|
||||
|
||||
class FinalLayer(nn.Module):
|
||||
def __init__(self, hidden_size, output_size):
|
||||
super().__init__()
|
||||
self.adaLN_modulation = nn.Sequential(
|
||||
nn.SiLU(),
|
||||
nn.Linear(hidden_size, 2 * hidden_size, bias=True),
|
||||
)
|
||||
self.norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-5)
|
||||
self.linear = nn.Linear(hidden_size, output_size, bias=True)
|
||||
|
||||
def forward(self, x, c, **_kwargs):
|
||||
shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
|
||||
x = modulate(self.norm(x), shift, scale)
|
||||
return self.linear(x)
|
||||
|
||||
|
||||
class DiTBlock(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
attention: nn.Module,
|
||||
ffn: nn.Module,
|
||||
hidden_size: int = 1024,
|
||||
modulation: bool = False,
|
||||
eps: float = 1e-5,
|
||||
**_kwargs,
|
||||
):
|
||||
super().__init__()
|
||||
self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=not modulation, eps=eps)
|
||||
self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=not modulation, eps=eps)
|
||||
self.attn = attention
|
||||
self.ffn = ffn
|
||||
self.modulation = modulation
|
||||
if modulation:
|
||||
self.adaLN_modulation = nn.Sequential(
|
||||
nn.SiLU(),
|
||||
nn.Linear(hidden_size, 6 * hidden_size, bias=True),
|
||||
)
|
||||
|
||||
def forward(self, x, condition=None, mask=None, **kwargs):
|
||||
if condition is None:
|
||||
assert not self.modulation, "Without global condition, must set modulation to False"
|
||||
else:
|
||||
assert self.modulation, "With global condition, must set modulation to True"
|
||||
shift_attn, scale_attn, gate_attn, shift_ffn, scale_ffn, gate_ffn = self.adaLN_modulation(condition).chunk(
|
||||
6, dim=1
|
||||
)
|
||||
|
||||
if condition is not None:
|
||||
pack_indices = kwargs.get("pack_indices")
|
||||
if pack_indices is not None:
|
||||
gate_attn = gate_attn[pack_indices]
|
||||
gate_ffn = gate_ffn[pack_indices]
|
||||
else:
|
||||
gate_attn = gate_attn.unsqueeze(1)
|
||||
gate_ffn = gate_ffn.unsqueeze(1)
|
||||
|
||||
if condition is not None:
|
||||
x = x + gate_attn * self.attn(
|
||||
modulate(self.norm1(x), shift_attn, scale_attn, **kwargs),
|
||||
mask=mask,
|
||||
**kwargs,
|
||||
)
|
||||
else:
|
||||
x = x + self.attn(self.norm1(x), mask=mask, **kwargs)
|
||||
|
||||
if condition is not None:
|
||||
x = x + gate_ffn * self.ffn(modulate(self.norm2(x), shift_ffn, scale_ffn, **kwargs))
|
||||
else:
|
||||
x = x + self.ffn(self.norm2(x), mask=mask)
|
||||
return x
|
||||
|
||||
|
||||
class DiT(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
in_dim,
|
||||
out_dim,
|
||||
transformer_config,
|
||||
*,
|
||||
mode: str = "flow_matching",
|
||||
):
|
||||
super().__init__()
|
||||
if mode not in {"flow_matching", "meanflow"}:
|
||||
raise ValueError(f"DiT mode must be 'flow_matching' or 'meanflow', got {mode!r}.")
|
||||
|
||||
transformer_kwargs = transformer_config.to_dict()
|
||||
model_dim = transformer_config.hidden_size
|
||||
self.mode = mode
|
||||
self.num_layers = transformer_config.num_layers
|
||||
|
||||
self.input_layer = nn.Linear(in_dim, model_dim)
|
||||
self.time_embedder = TimestepEmbedder(model_dim)
|
||||
if mode == "meanflow":
|
||||
self.duration_embedder = TimestepEmbedder(model_dim)
|
||||
|
||||
self.blocks = nn.ModuleList()
|
||||
for i in range(self.num_layers):
|
||||
attn_block = MultiHeadAttention(**transformer_kwargs, name=f"layer_{i}")
|
||||
ffn_block = Mlp(act_layer=lambda: nn.GELU(approximate="tanh"), **transformer_kwargs)
|
||||
self.blocks.append(DiTBlock(attention=attn_block, ffn=ffn_block, **transformer_kwargs))
|
||||
|
||||
self.output_layer = FinalLayer(model_dim, out_dim)
|
||||
self.initialize_weights()
|
||||
|
||||
def initialize_weights(self):
|
||||
def _basic_init(module):
|
||||
if isinstance(module, nn.Linear):
|
||||
torch.nn.init.xavier_uniform_(module.weight)
|
||||
if module.bias is not None:
|
||||
nn.init.constant_(module.bias, 0)
|
||||
|
||||
self.apply(_basic_init)
|
||||
|
||||
nn.init.normal_(self.time_embedder.mlp[0].weight, std=0.02)
|
||||
nn.init.normal_(self.time_embedder.mlp[2].weight, std=0.02)
|
||||
|
||||
for block in self.blocks:
|
||||
if hasattr(block, "adaLN_modulation"):
|
||||
nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
|
||||
nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
|
||||
|
||||
nn.init.constant_(self.output_layer.adaLN_modulation[-1].weight, 0)
|
||||
nn.init.constant_(self.output_layer.adaLN_modulation[-1].bias, 0)
|
||||
nn.init.constant_(self.output_layer.linear.weight, 0)
|
||||
nn.init.constant_(self.output_layer.linear.bias, 0)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
x,
|
||||
timesteps,
|
||||
duration: torch.Tensor | None = None,
|
||||
mask=None,
|
||||
attn_mask=None,
|
||||
g_cond: torch.Tensor | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
t = self.time_embedder(timesteps)
|
||||
c = t
|
||||
duration_embedder = getattr(self, "duration_embedder", None)
|
||||
if duration_embedder is not None and duration is not None:
|
||||
c = c + duration_embedder(duration)
|
||||
if g_cond is not None:
|
||||
c = c + g_cond
|
||||
|
||||
x = self.input_layer(x)
|
||||
for block in self.blocks:
|
||||
x = block(x, c, mask=attn_mask, **kwargs)
|
||||
return self.output_layer(x, c, **kwargs)
|
||||
@@ -1,355 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# Copyright 2026 The vLLM-Omni team.
|
||||
# Copyright (c) rednote-hilab. All rights reserved.
|
||||
# Adapted from:
|
||||
# https://github.com/rednote-hilab/dots.tts/tree/a393d2e/src/dots_tts/modules/backbone
|
||||
#
|
||||
# Single upstream source (preserved as-is, inference behaviour unchanged;
|
||||
# only the internal `from dots_tts.modules.backbone.layers import ...` line
|
||||
# was folded to point at our sibling vendor files):
|
||||
# - modules/backbone/semantic_encoder.py -> SemanticEncoderDecodeState,
|
||||
# TransformerEncoderLayer,
|
||||
# SuperviseEncoder,
|
||||
# VAESemanticEncoder
|
||||
#
|
||||
# Building blocks (Conv1d / Mlp / MultiHeadAttention) are imported from the
|
||||
# sibling vendor files where they already live:
|
||||
# - Conv1d <- dots_tts_vocoder.py
|
||||
# - Mlp <- dots_tts_dit.py
|
||||
# - MultiHeadAttention <- dots_tts_dit.py
|
||||
#
|
||||
# Nothing else in this file diverges from upstream behaviour.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from einops import rearrange
|
||||
|
||||
from vllm_omni.model_executor.models.dots_tts.dots_tts_dit import (
|
||||
Mlp,
|
||||
MultiHeadAttention,
|
||||
)
|
||||
from vllm_omni.model_executor.models.dots_tts.dots_tts_vocoder import Conv1d
|
||||
|
||||
|
||||
@dataclass
|
||||
class SemanticEncoderDecodeState:
|
||||
conv_tail: torch.Tensor
|
||||
layer_caches: tuple[tuple[torch.Tensor, torch.Tensor], ...]
|
||||
seq_len: int
|
||||
|
||||
|
||||
class TransformerEncoderLayer(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
hidden_size,
|
||||
num_heads=16,
|
||||
ffn_hidden_size=4096,
|
||||
attn_dropout=0.0,
|
||||
ffn_dropout=0.0,
|
||||
norm_layer="LayerNorm",
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__()
|
||||
self.attn = MultiHeadAttention(
|
||||
hidden_size,
|
||||
num_heads,
|
||||
attn_drop=attn_dropout,
|
||||
norm_layer=norm_layer,
|
||||
**kwargs,
|
||||
)
|
||||
norm_cls = getattr(nn, norm_layer)
|
||||
self.attn_norm = norm_cls(hidden_size)
|
||||
self.ffn = Mlp(hidden_size, ffn_hidden_size, dropout=ffn_dropout, act_layer=nn.SiLU)
|
||||
self.ffn_norm = norm_cls(hidden_size)
|
||||
self.hidden_size = hidden_size
|
||||
|
||||
def _build_causal_mask(self, T: int, device): # noqa: N803
|
||||
return torch.tril(torch.ones(T, T, dtype=torch.bool, device=device))
|
||||
|
||||
def _build_padding_mask(self, x_lens, max_len: int, device):
|
||||
B = x_lens.size(0)
|
||||
positions = torch.arange(max_len, device=device).unsqueeze(0).expand(B, -1)
|
||||
return positions < x_lens.unsqueeze(1)
|
||||
|
||||
def _fuse_attn_mask(self, causal_mask, padding_mask):
|
||||
if causal_mask is None and padding_mask is None:
|
||||
return None
|
||||
if causal_mask is None:
|
||||
row = padding_mask.unsqueeze(2)
|
||||
col = padding_mask.unsqueeze(1)
|
||||
return row & col
|
||||
if padding_mask is None:
|
||||
return causal_mask.unsqueeze(0)
|
||||
|
||||
_B, _T = padding_mask.shape
|
||||
causal = causal_mask.unsqueeze(0)
|
||||
row = padding_mask.unsqueeze(2)
|
||||
col = padding_mask.unsqueeze(1)
|
||||
pad_2d = row & col
|
||||
return causal & pad_2d
|
||||
|
||||
def forward(
|
||||
self,
|
||||
x,
|
||||
x_lens=None,
|
||||
causal=True,
|
||||
):
|
||||
_B, T, C = x.shape
|
||||
assert self.hidden_size == C
|
||||
device = x.device
|
||||
|
||||
causal_mask = self._build_causal_mask(T, device) if causal else None
|
||||
if x_lens is not None:
|
||||
padding_mask = self._build_padding_mask(x_lens, T, device)
|
||||
else:
|
||||
padding_mask = None
|
||||
fused_mask = self._fuse_attn_mask(causal_mask, padding_mask)
|
||||
|
||||
h = self.attn_norm(x)
|
||||
h = self.attn(
|
||||
q=h,
|
||||
mask=fused_mask,
|
||||
)
|
||||
x = x + h
|
||||
|
||||
h = self.ffn_norm(x)
|
||||
h = self.ffn(h)
|
||||
return x + h
|
||||
|
||||
def decode_step(
|
||||
self,
|
||||
x,
|
||||
*,
|
||||
cache: tuple[torch.Tensor, torch.Tensor],
|
||||
positions: torch.Tensor,
|
||||
):
|
||||
if x.size(1) <= 0:
|
||||
raise ValueError("TransformerEncoderLayer.decode_step expects a non-empty input.")
|
||||
|
||||
h = self.attn_norm(x)
|
||||
h, cache = self.attn.decode_step(h, cache=cache, positions=positions)
|
||||
x = x + h
|
||||
|
||||
h = self.ffn_norm(x)
|
||||
h = self.ffn(h)
|
||||
return x + h, cache
|
||||
|
||||
|
||||
class SuperviseEncoder(nn.Module):
|
||||
def __init__(self, config):
|
||||
super().__init__()
|
||||
self.hidden_size = config.get("hidden_size", 1024)
|
||||
self.layers = nn.ModuleList(
|
||||
[
|
||||
TransformerEncoderLayer(
|
||||
hidden_size=self.hidden_size,
|
||||
num_heads=config.get("num_heads", 16),
|
||||
ffn_hidden_size=config.get("ffn_hidden_size", 4096),
|
||||
norm_layer=config.get("norm_layer", "LayerNorm"),
|
||||
)
|
||||
for _ in range(config.get("num_layers", 6))
|
||||
]
|
||||
)
|
||||
self.causal = config.get("causal", False)
|
||||
|
||||
def forward(self, x, x_lens=None):
|
||||
batch_size, seq_len, _ = x.shape
|
||||
if x_lens is None:
|
||||
x_lens = torch.full((batch_size,), seq_len, device=x.device, dtype=torch.long)
|
||||
for layer in self.layers:
|
||||
x = layer(x, x_lens=x_lens, causal=self.causal)
|
||||
return x
|
||||
|
||||
def init_decode_state(
|
||||
self,
|
||||
*,
|
||||
batch_size: int,
|
||||
max_seq_len: int,
|
||||
device: torch.device,
|
||||
dtype: torch.dtype,
|
||||
):
|
||||
layer_caches = []
|
||||
for layer in self.layers:
|
||||
cache_shape = (
|
||||
batch_size,
|
||||
layer.attn.num_heads,
|
||||
max_seq_len,
|
||||
layer.attn.head_dim,
|
||||
)
|
||||
layer_caches.append(
|
||||
(
|
||||
torch.zeros(cache_shape, dtype=dtype, device=device),
|
||||
torch.zeros(cache_shape, dtype=dtype, device=device),
|
||||
)
|
||||
)
|
||||
return tuple(layer_caches)
|
||||
|
||||
def reset_decode_state(
|
||||
self,
|
||||
layer_caches: tuple[tuple[torch.Tensor, torch.Tensor], ...],
|
||||
) -> None:
|
||||
if len(layer_caches) != len(self.layers):
|
||||
raise ValueError("Layer cache count does not match encoder depth.")
|
||||
for key_cache, value_cache in layer_caches:
|
||||
key_cache.zero_()
|
||||
value_cache.zero_()
|
||||
|
||||
def decode_step(self, x, *, layer_caches, positions: torch.Tensor):
|
||||
if len(layer_caches) != len(self.layers):
|
||||
raise ValueError("Layer cache count does not match encoder depth.")
|
||||
|
||||
for layer, cache in zip(self.layers, layer_caches, strict=True):
|
||||
x, _ = layer.decode_step(x, cache=cache, positions=positions)
|
||||
return x
|
||||
|
||||
|
||||
class VAESemanticEncoder(nn.Module):
|
||||
def __init__(self, in_dim, out_dim, config):
|
||||
super().__init__()
|
||||
in_ds_rate = 2
|
||||
self.patch_size = int(config.patch_size)
|
||||
self.in_ds_rate = in_ds_rate
|
||||
self.ds_proj = Conv1d(in_dim, in_dim, kernel_size=in_ds_rate, stride=in_ds_rate, causal=True)
|
||||
self.in_proj = nn.Linear(in_dim, config.PatchEncoder.hidden_size)
|
||||
self.encoder = SuperviseEncoder(config.PatchEncoder)
|
||||
self.out_ds_rate = self.patch_size // in_ds_rate
|
||||
self.out_proj = nn.Linear(config.PatchEncoder.hidden_size * self.out_ds_rate, out_dim)
|
||||
|
||||
def forward(self, x, x_lens=None):
|
||||
x = self._downsample(x)
|
||||
x = self.in_proj(x)
|
||||
z = self.encoder(x, x_lens=x_lens)
|
||||
return self._project_embeddings(z)
|
||||
|
||||
def init_decode_state(
|
||||
self,
|
||||
*,
|
||||
max_audio_patch_count: int,
|
||||
batch_size: int,
|
||||
device: torch.device,
|
||||
dtype: torch.dtype,
|
||||
) -> SemanticEncoderDecodeState:
|
||||
return SemanticEncoderDecodeState(
|
||||
conv_tail=torch.zeros(
|
||||
(batch_size, self.ds_proj.in_channels, self.ds_proj.left_padding),
|
||||
dtype=dtype,
|
||||
device=device,
|
||||
),
|
||||
layer_caches=self.encoder.init_decode_state(
|
||||
batch_size=batch_size,
|
||||
max_seq_len=max_audio_patch_count * self.out_ds_rate,
|
||||
device=device,
|
||||
dtype=dtype,
|
||||
),
|
||||
seq_len=0,
|
||||
)
|
||||
|
||||
def reset_decode_state(self, state: SemanticEncoderDecodeState) -> None:
|
||||
state.conv_tail.zero_()
|
||||
self.encoder.reset_decode_state(state.layer_caches)
|
||||
state.seq_len = 0
|
||||
|
||||
def prefill(
|
||||
self,
|
||||
x,
|
||||
state: SemanticEncoderDecodeState,
|
||||
) -> tuple[torch.Tensor, SemanticEncoderDecodeState]:
|
||||
if x.ndim != 3:
|
||||
raise ValueError(f"VAESemanticEncoder.prefill expects rank-3 input, got {tuple(x.shape)}.")
|
||||
if x.size(1) % self.patch_size != 0:
|
||||
raise ValueError(f"Prompt latent length {x.size(1)} must be divisible by patch_size={self.patch_size}.")
|
||||
|
||||
if x.size(1) == 0:
|
||||
return (
|
||||
x.new_zeros((x.size(0), 0, self.out_proj.out_features)),
|
||||
state,
|
||||
)
|
||||
if state.conv_tail.size(0) != x.size(0):
|
||||
raise ValueError("VAESemanticEncoder.prefill batch size does not match decode state.")
|
||||
|
||||
step_inputs = self.in_proj(self._downsample(x))
|
||||
expected_token_count = (x.size(1) // self.patch_size) * self.out_ds_rate
|
||||
if step_inputs.size(1) != expected_token_count:
|
||||
raise RuntimeError(
|
||||
"Patch encoder prefill produced an unexpected token count: "
|
||||
f"expected={expected_token_count} actual={step_inputs.size(1)}."
|
||||
)
|
||||
|
||||
current_seq_len = state.seq_len
|
||||
next_seq_len = current_seq_len + step_inputs.size(1)
|
||||
cache_capacity = state.layer_caches[0][0].size(2)
|
||||
if next_seq_len > cache_capacity:
|
||||
raise ValueError(
|
||||
"Patch encoder prefill exceeds decode-state capacity: "
|
||||
f"required={next_seq_len} capacity={cache_capacity}."
|
||||
)
|
||||
|
||||
positions = torch.arange(step_inputs.size(1), device=x.device, dtype=torch.long) + current_seq_len
|
||||
encoded = self.encoder.decode_step(
|
||||
step_inputs,
|
||||
layer_caches=state.layer_caches,
|
||||
positions=positions,
|
||||
)
|
||||
embedding = self._project_embeddings(encoded)
|
||||
raw = x.transpose(1, 2)
|
||||
state.conv_tail.copy_(raw[..., -self.ds_proj.left_padding :])
|
||||
state.seq_len = next_seq_len
|
||||
return embedding, state
|
||||
|
||||
def decode_patch(
|
||||
self,
|
||||
latent_patch,
|
||||
conv_tail: torch.Tensor,
|
||||
layer_caches: tuple[tuple[torch.Tensor, torch.Tensor], ...],
|
||||
positions: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
if latent_patch.ndim != 3:
|
||||
raise ValueError(f"VAESemanticEncoder.decode_patch expects rank-3 input, got {tuple(latent_patch.shape)}.")
|
||||
if latent_patch.size(1) != self.patch_size:
|
||||
raise ValueError(f"decode_patch expects patch length {self.patch_size}, got {latent_patch.size(1)}.")
|
||||
if positions.ndim != 1 or positions.size(0) != self.out_ds_rate:
|
||||
raise ValueError("decode_patch positions must be a rank-1 tensor matching out_ds_rate.")
|
||||
|
||||
step_inputs, conv_tail = self._downsample_step(
|
||||
latent_patch,
|
||||
conv_tail=conv_tail,
|
||||
)
|
||||
if step_inputs.size(1) != self.out_ds_rate:
|
||||
raise RuntimeError(f"Downsample step produced {step_inputs.size(1)} tokens, expected {self.out_ds_rate}.")
|
||||
|
||||
encoded = self.encoder.decode_step(
|
||||
step_inputs,
|
||||
layer_caches=layer_caches,
|
||||
positions=positions,
|
||||
)
|
||||
embedding = self._project_embeddings(encoded)
|
||||
return embedding, conv_tail
|
||||
|
||||
def _downsample(self, x):
|
||||
return self.ds_proj(x.transpose(1, 2)).transpose(1, 2)
|
||||
|
||||
def _project_embeddings(self, z):
|
||||
if self.out_ds_rate > 1:
|
||||
z = rearrange(z, "b (s d) h -> b s (d h)", d=self.out_ds_rate)
|
||||
return self.out_proj(z)
|
||||
|
||||
def _downsample_step(self, latent_patch, *, conv_tail):
|
||||
raw = latent_patch.transpose(1, 2)
|
||||
conv_input = torch.cat([conv_tail, raw], dim=-1)
|
||||
|
||||
projected = F.conv1d(
|
||||
conv_input,
|
||||
self.ds_proj.weight,
|
||||
self.ds_proj.bias,
|
||||
stride=self.ds_proj.stride[0],
|
||||
padding=0,
|
||||
dilation=self.ds_proj.dilation[0],
|
||||
groups=self.ds_proj.groups,
|
||||
).transpose(1, 2)
|
||||
new_conv_tail = raw[..., -self.ds_proj.left_padding :]
|
||||
return self.in_proj(projected), new_conv_tail
|
||||
@@ -1,70 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""dots.tts prompt builder for vllm-omni's Omni engine + serving layer.
|
||||
|
||||
Mirrors upstream ``build_generation_schedule`` (rednote-hilab/dots.tts @
|
||||
a393d2e data/pipelines/tokenizing.py:169) for the
|
||||
no-prompt-audio + audio-placeholder path — text-only zero-shot TTS.
|
||||
|
||||
V1 returns real Qwen2 token IDs (not placeholders ``[1] * N`` like
|
||||
voxcpm2's builder). Reason: our talker's preprocess() runs
|
||||
``self.model.embed_tokens(input_ids)`` directly, so real IDs flow
|
||||
through naturally. voxcpm2 uses placeholders because its prefill mixes
|
||||
reference-audio embeddings (no token IDs); dots.tts V1 zero-shot is
|
||||
purely text + audio_gen_start, all real IDs.
|
||||
|
||||
Voice clone (reference audio + speaker x-vector) is intentionally not
|
||||
wired here — V1 is zero-shot only. Add reference_audio /
|
||||
voice_profile / prompt_text branches in a follow-up (mirror voxcpm2
|
||||
``build_voxcpm2_prompt``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from vllm.inputs import tokens_input
|
||||
|
||||
# Upstream rednote-hilab/dots.tts @ a393d2e
|
||||
# data/pipelines/tts_pipeline.py:17-18
|
||||
_TTS_TEXT_PREFIX = "[文本]"
|
||||
_TTS_AUDIO_PREFIX = "[文本对应语音]"
|
||||
_AUDIO_GEN_START_TOKEN = "<|audio_gen_start|>"
|
||||
|
||||
|
||||
def build_dots_tts_prompt(
|
||||
tokenizer: Any,
|
||||
text: str,
|
||||
) -> dict[str, Any]:
|
||||
"""Build a dots.tts prefill prompt dict for ``Omni.generate()``.
|
||||
|
||||
Returns ``{"prompt_token_ids": [...], "additional_information": {...}}``
|
||||
where ``prompt_token_ids`` is the real Qwen2 token sequence:
|
||||
|
||||
[text_tokens of "[文本]<text>[文本对应语音]", audio_gen_start_id]
|
||||
|
||||
talker's preprocess() embeds these into ``hidden_states`` for the AR
|
||||
base LM. Decode then drives via ``state.curr_embed_for_next`` (DiT
|
||||
→ patch_encoder AR loopback).
|
||||
"""
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
raise ValueError(f"text must be a non-empty string, got {text!r}")
|
||||
|
||||
prompt_text = f"{_TTS_TEXT_PREFIX}{text}{_TTS_AUDIO_PREFIX}"
|
||||
text_ids = tokenizer.encode(prompt_text, add_special_tokens=False)
|
||||
|
||||
audio_gen_start_id = tokenizer.convert_tokens_to_ids(_AUDIO_GEN_START_TOKEN)
|
||||
if not isinstance(audio_gen_start_id, int) or audio_gen_start_id == tokenizer.unk_token_id:
|
||||
raise ValueError(
|
||||
f"Tokenizer does not know {_AUDIO_GEN_START_TOKEN!r} "
|
||||
f"(got id={audio_gen_start_id!r}). Did you load the "
|
||||
f"dots.tts tokenizer (with added_tokens.json)?"
|
||||
)
|
||||
prompt_token_ids = list(text_ids) + [audio_gen_start_id]
|
||||
|
||||
prompt = tokens_input(prompt_token_ids=prompt_token_ids)
|
||||
prompt["additional_information"] = {
|
||||
# Reserved for future voice clone (ref_audio / speaker x-vector).
|
||||
# V1 zero-shot leaves this empty; preprocess() ignores it.
|
||||
}
|
||||
return prompt
|
||||
@@ -1,732 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# Copyright 2026 The vLLM-Omni team.
|
||||
# Copyright (c) rednote-hilab. All rights reserved.
|
||||
# Portions Copyright 3D-Speaker
|
||||
# (https://github.com/alibaba-damo-academy/3D-Speaker), Apache-2.0.
|
||||
# Adapted from:
|
||||
# https://github.com/rednote-hilab/dots.tts/tree/a393d2e/src/dots_tts/modules/speaker
|
||||
# (whose CAM++ implementation is itself adapted from 3D-Speaker).
|
||||
#
|
||||
# Merged from four upstream files (preserved as-is, inference behaviour
|
||||
# unchanged; only internal cross-module imports were folded inline):
|
||||
# - modules/speaker/encoder.py -> SpeakerXVectorFeatures
|
||||
# - modules/speaker/fbank.py -> fbank constants + extract_speaker_fbank
|
||||
# - modules/speaker/campplus.py -> FCM, CAMPPlus
|
||||
# - modules/speaker/campplus_layers.py -> get_nonlinear, statistics_pooling,
|
||||
# StatsPool, TDNNLayer, CAMLayer,
|
||||
# CAMDenseTDNNLayer, CAMDenseTDNNBlock,
|
||||
# TransitLayer, DenseLayer, BasicResBlock
|
||||
#
|
||||
# Plus two tiny helpers folded from utils/audio.py (used by
|
||||
# extract_speaker_fbank):
|
||||
# - high_quality_resample, extract_fbank
|
||||
#
|
||||
# Nothing in this file diverges from upstream behaviour.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import random
|
||||
from collections import OrderedDict
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
import torch.utils.checkpoint as cp
|
||||
import torchaudio
|
||||
import torchaudio.compliance.kaldi as Kaldi
|
||||
import torchaudio.functional as AF
|
||||
from torch.nn.utils.rnn import pad_sequence
|
||||
|
||||
# ============================================================================
|
||||
# Constants (from modules/speaker/fbank.py)
|
||||
# ============================================================================
|
||||
|
||||
_SPEAKER_FBANK_SAMPLE_RATE = 16000
|
||||
_SPEAKER_FBANK_N_MELS = 80
|
||||
_SPEAKER_FBANK_MEAN_NORM = True
|
||||
_SPEAKER_FBANK_DITHER = 0.0
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Audio helpers (folded from utils/audio.py — used by extract_speaker_fbank)
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def high_quality_resample(x, orig_sr, target_sr):
|
||||
return AF.resample(
|
||||
x,
|
||||
orig_freq=orig_sr,
|
||||
new_freq=target_sr,
|
||||
lowpass_filter_width=64,
|
||||
rolloff=0.95,
|
||||
resampling_method="sinc_interp_kaiser",
|
||||
)
|
||||
|
||||
|
||||
def extract_fbank(
|
||||
waveform: torch.Tensor,
|
||||
*,
|
||||
sample_rate: int,
|
||||
n_mels: int,
|
||||
dither: float = 0.0,
|
||||
mean_norm: bool = False,
|
||||
) -> torch.Tensor:
|
||||
if waveform.ndim == 1:
|
||||
feature_input = waveform.unsqueeze(0)
|
||||
elif waveform.ndim == 2:
|
||||
feature_input = waveform if waveform.size(0) == 1 else waveform[0:1, :]
|
||||
else:
|
||||
raise ValueError(f"FBank expects a 1D or 2D waveform, got shape {tuple(waveform.shape)}.")
|
||||
features = Kaldi.fbank(
|
||||
feature_input,
|
||||
num_mel_bins=n_mels,
|
||||
sample_frequency=sample_rate,
|
||||
dither=dither,
|
||||
)
|
||||
if mean_norm:
|
||||
features = features - features.mean(dim=0, keepdim=True)
|
||||
return features
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Speaker fbank entry (from modules/speaker/fbank.py)
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def extract_speaker_fbank(
|
||||
waveform: torch.Tensor,
|
||||
*,
|
||||
sample_rate: int,
|
||||
) -> torch.Tensor:
|
||||
feature_input = waveform
|
||||
if sample_rate != _SPEAKER_FBANK_SAMPLE_RATE:
|
||||
feature_input = high_quality_resample(
|
||||
waveform,
|
||||
orig_sr=sample_rate,
|
||||
target_sr=_SPEAKER_FBANK_SAMPLE_RATE,
|
||||
)
|
||||
return extract_fbank(
|
||||
feature_input,
|
||||
sample_rate=_SPEAKER_FBANK_SAMPLE_RATE,
|
||||
n_mels=_SPEAKER_FBANK_N_MELS,
|
||||
dither=_SPEAKER_FBANK_DITHER,
|
||||
mean_norm=_SPEAKER_FBANK_MEAN_NORM,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# CAM++ building blocks (from modules/speaker/campplus_layers.py)
|
||||
# ----------------------------------------------------------------------------
|
||||
# 3D-Speaker, Apache-2.0.
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def get_nonlinear(config_str, channels):
|
||||
nonlinear = nn.Sequential()
|
||||
for name in config_str.split("-"):
|
||||
if name == "relu":
|
||||
nonlinear.add_module("relu", nn.ReLU(inplace=True))
|
||||
elif name == "prelu":
|
||||
nonlinear.add_module("prelu", nn.PReLU(channels))
|
||||
elif name == "batchnorm":
|
||||
nonlinear.add_module("batchnorm", nn.BatchNorm1d(channels))
|
||||
elif name == "batchnorm_":
|
||||
nonlinear.add_module("batchnorm", nn.BatchNorm1d(channels, affine=False))
|
||||
else:
|
||||
raise ValueError(f"Unexpected module ({name}).")
|
||||
return nonlinear
|
||||
|
||||
|
||||
def statistics_pooling(x, dim=-1, keepdim=False, unbiased=True, _eps=1e-2):
|
||||
mean = x.mean(dim=dim)
|
||||
std = x.std(dim=dim, unbiased=unbiased)
|
||||
stats = torch.cat([mean, std], dim=-1)
|
||||
if keepdim:
|
||||
stats = stats.unsqueeze(dim=dim)
|
||||
return stats
|
||||
|
||||
|
||||
class StatsPool(nn.Module):
|
||||
def forward(self, x):
|
||||
return statistics_pooling(x)
|
||||
|
||||
|
||||
class TDNNLayer(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
in_channels,
|
||||
out_channels,
|
||||
kernel_size,
|
||||
stride=1,
|
||||
padding=0,
|
||||
dilation=1,
|
||||
bias=False,
|
||||
config_str="batchnorm-relu",
|
||||
):
|
||||
super().__init__()
|
||||
if padding < 0:
|
||||
assert kernel_size % 2 == 1, f"Expect equal paddings, but got even kernel size ({kernel_size})"
|
||||
padding = (kernel_size - 1) // 2 * dilation
|
||||
self.linear = nn.Conv1d(
|
||||
in_channels,
|
||||
out_channels,
|
||||
kernel_size,
|
||||
stride=stride,
|
||||
padding=padding,
|
||||
dilation=dilation,
|
||||
bias=bias,
|
||||
)
|
||||
self.nonlinear = get_nonlinear(config_str, out_channels)
|
||||
|
||||
def forward(self, x):
|
||||
x = self.linear(x)
|
||||
return self.nonlinear(x)
|
||||
|
||||
|
||||
class CAMLayer(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
bn_channels,
|
||||
out_channels,
|
||||
kernel_size,
|
||||
stride,
|
||||
padding,
|
||||
dilation,
|
||||
bias,
|
||||
reduction=2,
|
||||
):
|
||||
super().__init__()
|
||||
self.linear_local = nn.Conv1d(
|
||||
bn_channels,
|
||||
out_channels,
|
||||
kernel_size,
|
||||
stride=stride,
|
||||
padding=padding,
|
||||
dilation=dilation,
|
||||
bias=bias,
|
||||
)
|
||||
self.linear1 = nn.Conv1d(bn_channels, bn_channels // reduction, 1)
|
||||
self.relu = nn.ReLU(inplace=True)
|
||||
self.linear2 = nn.Conv1d(bn_channels // reduction, out_channels, 1)
|
||||
self.sigmoid = nn.Sigmoid()
|
||||
|
||||
def forward(self, x):
|
||||
y = self.linear_local(x)
|
||||
context = x.mean(-1, keepdim=True) + self.seg_pooling(x)
|
||||
context = self.relu(self.linear1(context))
|
||||
m = self.sigmoid(self.linear2(context))
|
||||
return y * m
|
||||
|
||||
def seg_pooling(self, x, seg_len=100, stype="avg"):
|
||||
if stype == "avg":
|
||||
seg = F.avg_pool1d(x, kernel_size=seg_len, stride=seg_len, ceil_mode=True)
|
||||
elif stype == "max":
|
||||
seg = F.max_pool1d(x, kernel_size=seg_len, stride=seg_len, ceil_mode=True)
|
||||
else:
|
||||
raise ValueError("Wrong segment pooling type.")
|
||||
shape = seg.shape
|
||||
seg = seg.unsqueeze(-1).expand(*shape, seg_len).reshape(*shape[:-1], -1)
|
||||
return seg[..., : x.shape[-1]]
|
||||
|
||||
|
||||
class CAMDenseTDNNLayer(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
in_channels,
|
||||
out_channels,
|
||||
bn_channels,
|
||||
kernel_size,
|
||||
stride=1,
|
||||
dilation=1,
|
||||
bias=False,
|
||||
config_str="batchnorm-relu",
|
||||
memory_efficient=False,
|
||||
):
|
||||
super().__init__()
|
||||
assert kernel_size % 2 == 1, f"Expect equal paddings, but got even kernel size ({kernel_size})"
|
||||
padding = (kernel_size - 1) // 2 * dilation
|
||||
self.memory_efficient = memory_efficient
|
||||
self.nonlinear1 = get_nonlinear(config_str, in_channels)
|
||||
self.linear1 = nn.Conv1d(in_channels, bn_channels, 1, bias=False)
|
||||
self.nonlinear2 = get_nonlinear(config_str, bn_channels)
|
||||
self.cam_layer = CAMLayer(
|
||||
bn_channels,
|
||||
out_channels,
|
||||
kernel_size,
|
||||
stride=stride,
|
||||
padding=padding,
|
||||
dilation=dilation,
|
||||
bias=bias,
|
||||
)
|
||||
|
||||
def bn_function(self, x):
|
||||
return self.linear1(self.nonlinear1(x))
|
||||
|
||||
def forward(self, x):
|
||||
if self.training and self.memory_efficient:
|
||||
x = cp.checkpoint(self.bn_function, x)
|
||||
else:
|
||||
x = self.bn_function(x)
|
||||
return self.cam_layer(self.nonlinear2(x))
|
||||
|
||||
|
||||
class CAMDenseTDNNBlock(nn.ModuleList):
|
||||
def __init__(
|
||||
self,
|
||||
num_layers,
|
||||
in_channels,
|
||||
out_channels,
|
||||
bn_channels,
|
||||
kernel_size,
|
||||
stride=1,
|
||||
dilation=1,
|
||||
bias=False,
|
||||
config_str="batchnorm-relu",
|
||||
memory_efficient=False,
|
||||
):
|
||||
super().__init__()
|
||||
for i in range(num_layers):
|
||||
layer = CAMDenseTDNNLayer(
|
||||
in_channels=in_channels + i * out_channels,
|
||||
out_channels=out_channels,
|
||||
bn_channels=bn_channels,
|
||||
kernel_size=kernel_size,
|
||||
stride=stride,
|
||||
dilation=dilation,
|
||||
bias=bias,
|
||||
config_str=config_str,
|
||||
memory_efficient=memory_efficient,
|
||||
)
|
||||
self.add_module(f"tdnnd{i + 1}", layer)
|
||||
|
||||
def forward(self, x):
|
||||
for layer in self:
|
||||
x = torch.cat([x, layer(x)], dim=1)
|
||||
return x
|
||||
|
||||
|
||||
class TransitLayer(nn.Module):
|
||||
def __init__(self, in_channels, out_channels, bias=True, config_str="batchnorm-relu"):
|
||||
super().__init__()
|
||||
self.nonlinear = get_nonlinear(config_str, in_channels)
|
||||
self.linear = nn.Conv1d(in_channels, out_channels, 1, bias=bias)
|
||||
|
||||
def forward(self, x):
|
||||
x = self.nonlinear(x)
|
||||
return self.linear(x)
|
||||
|
||||
|
||||
class DenseLayer(nn.Module):
|
||||
def __init__(self, in_channels, out_channels, bias=False, config_str="batchnorm-relu"):
|
||||
super().__init__()
|
||||
self.linear = nn.Conv1d(in_channels, out_channels, 1, bias=bias)
|
||||
self.nonlinear = get_nonlinear(config_str, out_channels)
|
||||
|
||||
def forward(self, x):
|
||||
if len(x.shape) == 2:
|
||||
x = self.linear(x.unsqueeze(dim=-1)).squeeze(dim=-1)
|
||||
else:
|
||||
x = self.linear(x)
|
||||
return self.nonlinear(x)
|
||||
|
||||
|
||||
class BasicResBlock(nn.Module):
|
||||
expansion = 1
|
||||
|
||||
def __init__(self, in_planes, planes, stride=1):
|
||||
super().__init__()
|
||||
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=(stride, 1), padding=1, bias=False)
|
||||
self.bn1 = nn.BatchNorm2d(planes)
|
||||
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)
|
||||
self.bn2 = nn.BatchNorm2d(planes)
|
||||
|
||||
self.shortcut = nn.Sequential()
|
||||
if stride != 1 or in_planes != self.expansion * planes:
|
||||
self.shortcut = nn.Sequential(
|
||||
nn.Conv2d(
|
||||
in_planes,
|
||||
self.expansion * planes,
|
||||
kernel_size=1,
|
||||
stride=(stride, 1),
|
||||
bias=False,
|
||||
),
|
||||
nn.BatchNorm2d(self.expansion * planes),
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
out = F.relu(self.bn1(self.conv1(x)))
|
||||
out = self.bn2(self.conv2(out))
|
||||
out += self.shortcut(x)
|
||||
return F.relu(out)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# CAM++ model (from modules/speaker/campplus.py)
|
||||
# ----------------------------------------------------------------------------
|
||||
# 3D-Speaker, Apache-2.0.
|
||||
# ============================================================================
|
||||
|
||||
|
||||
class FCM(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
block=BasicResBlock,
|
||||
num_blocks=(2, 2),
|
||||
m_channels=32,
|
||||
feat_dim=_SPEAKER_FBANK_N_MELS,
|
||||
):
|
||||
super().__init__()
|
||||
self.in_planes = m_channels
|
||||
self.conv1 = nn.Conv2d(1, m_channels, kernel_size=3, stride=1, padding=1, bias=False)
|
||||
self.bn1 = nn.BatchNorm2d(m_channels)
|
||||
|
||||
self.layer1 = self._make_layer(block, m_channels, num_blocks[0], stride=2)
|
||||
self.layer2 = self._make_layer(block, m_channels, num_blocks[1], stride=2)
|
||||
|
||||
self.conv2 = nn.Conv2d(m_channels, m_channels, kernel_size=3, stride=(2, 1), padding=1, bias=False)
|
||||
self.bn2 = nn.BatchNorm2d(m_channels)
|
||||
self.out_channels = m_channels * (feat_dim // 8)
|
||||
|
||||
def _make_layer(self, block, planes, num_blocks, stride):
|
||||
strides = [stride] + [1] * (num_blocks - 1)
|
||||
layers = []
|
||||
for stride in strides:
|
||||
layers.append(block(self.in_planes, planes, stride))
|
||||
self.in_planes = planes * block.expansion
|
||||
return nn.Sequential(*layers)
|
||||
|
||||
def forward(self, x):
|
||||
x = x.unsqueeze(1)
|
||||
out = F.relu(self.bn1(self.conv1(x)))
|
||||
out = self.layer1(out)
|
||||
out = self.layer2(out)
|
||||
out = F.relu(self.bn2(self.conv2(out)))
|
||||
|
||||
shape = out.shape
|
||||
return out.reshape(shape[0], shape[1] * shape[2], shape[3])
|
||||
|
||||
|
||||
class CAMPPlus(nn.Module):
|
||||
_TDNN_KERNEL_SIZE = 5
|
||||
_TDNN_STRIDE = 2
|
||||
_TDNN_PADDING = 2
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
feat_dim=_SPEAKER_FBANK_N_MELS,
|
||||
embedding_size=512,
|
||||
growth_rate=32,
|
||||
bn_size=4,
|
||||
init_channels=128,
|
||||
config_str="batchnorm-relu",
|
||||
memory_efficient=True,
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
self.head = FCM(feat_dim=feat_dim)
|
||||
channels = self.head.out_channels
|
||||
|
||||
self.xvector = nn.Sequential(
|
||||
OrderedDict(
|
||||
[
|
||||
(
|
||||
"tdnn",
|
||||
TDNNLayer(
|
||||
channels,
|
||||
init_channels,
|
||||
self._TDNN_KERNEL_SIZE,
|
||||
stride=self._TDNN_STRIDE,
|
||||
dilation=1,
|
||||
padding=-1,
|
||||
config_str=config_str,
|
||||
),
|
||||
),
|
||||
]
|
||||
)
|
||||
)
|
||||
channels = init_channels
|
||||
for i, (num_layers, kernel_size, dilation) in enumerate(zip((12, 24, 16), (3, 3, 3), (1, 2, 2), strict=True)):
|
||||
block = CAMDenseTDNNBlock(
|
||||
num_layers=num_layers,
|
||||
in_channels=channels,
|
||||
out_channels=growth_rate,
|
||||
bn_channels=bn_size * growth_rate,
|
||||
kernel_size=kernel_size,
|
||||
dilation=dilation,
|
||||
config_str=config_str,
|
||||
memory_efficient=memory_efficient,
|
||||
)
|
||||
self.xvector.add_module(f"block{i + 1}", block)
|
||||
channels = channels + num_layers * growth_rate
|
||||
self.xvector.add_module(
|
||||
f"transit{i + 1}",
|
||||
TransitLayer(channels, channels // 2, bias=False, config_str=config_str),
|
||||
)
|
||||
channels //= 2
|
||||
|
||||
self.xvector.add_module("out_nonlinear", get_nonlinear(config_str, channels))
|
||||
|
||||
self.xvector.add_module("stats", StatsPool())
|
||||
self.xvector.add_module("dense", DenseLayer(channels * 2, embedding_size, config_str="batchnorm_"))
|
||||
|
||||
for m in self.modules():
|
||||
if isinstance(m, (nn.Conv1d, nn.Linear)):
|
||||
nn.init.kaiming_normal_(m.weight.data)
|
||||
if m.bias is not None:
|
||||
nn.init.zeros_(m.bias)
|
||||
|
||||
@staticmethod
|
||||
def _conv_output_lengths(lengths, kernel_size, stride=1, padding=0, dilation=1):
|
||||
return (
|
||||
torch.div(
|
||||
lengths + 2 * padding - dilation * (kernel_size - 1) - 1,
|
||||
stride,
|
||||
rounding_mode="floor",
|
||||
)
|
||||
+ 1
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _make_length_mask(lengths, max_len, device):
|
||||
lengths = lengths.to(device=device, dtype=torch.long).clamp(min=0, max=max_len)
|
||||
return torch.arange(max_len, device=device).unsqueeze(0) < lengths.unsqueeze(1)
|
||||
|
||||
def _masked_stats_pooling(self, x, lengths, unbiased=True, eps=1e-2):
|
||||
lengths = lengths.to(device=x.device, dtype=torch.long).clamp(min=1, max=x.size(-1))
|
||||
mask = self._make_length_mask(lengths, x.size(-1), x.device).unsqueeze(1)
|
||||
mask = mask.to(dtype=x.dtype)
|
||||
|
||||
denom = lengths.to(dtype=x.dtype).view(-1, 1).clamp_min(1.0)
|
||||
mean = (x * mask).sum(dim=-1) / denom
|
||||
|
||||
centered = (x - mean.unsqueeze(-1)) * mask
|
||||
var_denom = (lengths - 1).clamp_min(1).to(dtype=x.dtype).view(-1, 1) if unbiased else denom
|
||||
var = centered.pow(2).sum(dim=-1) / var_denom
|
||||
std = torch.sqrt(var.clamp_min(eps))
|
||||
return torch.cat([mean, std], dim=1)
|
||||
|
||||
def forward(self, x, lengths=None):
|
||||
x = x.permute(0, 2, 1) # (B,T,F) => (B,F,T)
|
||||
x = self.head(x)
|
||||
if lengths is not None:
|
||||
lengths = lengths.to(device=x.device, dtype=torch.long).clamp(min=1)
|
||||
|
||||
for name, module in self.xvector.named_children():
|
||||
if name == "stats":
|
||||
x = self._masked_stats_pooling(x, lengths) if lengths is not None else module(x)
|
||||
continue
|
||||
|
||||
x = module(x)
|
||||
if name == "tdnn" and lengths is not None:
|
||||
lengths = self._conv_output_lengths(
|
||||
lengths,
|
||||
kernel_size=self._TDNN_KERNEL_SIZE,
|
||||
stride=self._TDNN_STRIDE,
|
||||
padding=self._TDNN_PADDING,
|
||||
)
|
||||
|
||||
return x
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# SpeakerXVectorFeatures wrapper (from modules/speaker/encoder.py)
|
||||
# ============================================================================
|
||||
|
||||
|
||||
class SpeakerXVectorFeatures(nn.Module):
|
||||
"""Speaker embedding extractor based on 3D-Speaker CAM++."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
sample_rate=_SPEAKER_FBANK_SAMPLE_RATE,
|
||||
campplus_embedding_size=512,
|
||||
max_audio_seconds=10.0,
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
self.sample_rate = sample_rate
|
||||
self.max_audio_seconds = float(max_audio_seconds)
|
||||
self.model = CAMPPlus(
|
||||
feat_dim=_SPEAKER_FBANK_N_MELS,
|
||||
embedding_size=campplus_embedding_size,
|
||||
)
|
||||
self.resample = None
|
||||
if self.sample_rate != _SPEAKER_FBANK_SAMPLE_RATE:
|
||||
self.resample = torchaudio.transforms.Resample(
|
||||
orig_freq=sample_rate,
|
||||
new_freq=_SPEAKER_FBANK_SAMPLE_RATE,
|
||||
)
|
||||
|
||||
for param in self.model.parameters():
|
||||
param.requires_grad = False
|
||||
|
||||
@staticmethod
|
||||
def _normalize_lengths(lengths, batch_size, max_length, device, *, min_length):
|
||||
if lengths is None:
|
||||
return torch.full(
|
||||
(batch_size,),
|
||||
max_length,
|
||||
device=device,
|
||||
dtype=torch.long,
|
||||
)
|
||||
return lengths.to(device=device, dtype=torch.long).clamp(
|
||||
min=min_length,
|
||||
max=max_length,
|
||||
)
|
||||
|
||||
def _crop_audio(self, audio, audio_lengths=None):
|
||||
original_lengths = self._normalize_lengths(
|
||||
audio_lengths,
|
||||
audio.size(0),
|
||||
audio.size(-1),
|
||||
audio.device,
|
||||
min_length=0,
|
||||
)
|
||||
if self.max_audio_seconds <= 0:
|
||||
return audio, original_lengths, original_lengths, torch.zeros_like(original_lengths)
|
||||
|
||||
max_input_length = round(self.sample_rate * self.max_audio_seconds)
|
||||
cropped_audio = []
|
||||
cropped_lengths = []
|
||||
starts = []
|
||||
|
||||
for index, total_length_tensor in enumerate(original_lengths):
|
||||
total_length = int(total_length_tensor.item())
|
||||
cropped_length = min(total_length, max_input_length)
|
||||
start = random.randint(0, total_length - cropped_length) if total_length > cropped_length else 0
|
||||
cropped_audio.append(audio[index, start : start + cropped_length])
|
||||
cropped_lengths.append(cropped_length)
|
||||
starts.append(start)
|
||||
|
||||
return (
|
||||
pad_sequence(
|
||||
cropped_audio,
|
||||
batch_first=True,
|
||||
padding_value=0.0,
|
||||
),
|
||||
original_lengths,
|
||||
torch.tensor(
|
||||
cropped_lengths,
|
||||
device=audio.device,
|
||||
dtype=torch.long,
|
||||
),
|
||||
torch.tensor(starts, device=audio.device, dtype=torch.long),
|
||||
)
|
||||
|
||||
def _crop_fbank(
|
||||
self,
|
||||
fbank,
|
||||
fbank_lengths,
|
||||
original_audio_lengths,
|
||||
cropped_audio_lengths,
|
||||
starts,
|
||||
):
|
||||
original_fbank_lengths = self._normalize_lengths(
|
||||
fbank_lengths,
|
||||
fbank.size(0),
|
||||
fbank.size(1),
|
||||
fbank.device,
|
||||
min_length=1,
|
||||
)
|
||||
cropped_fbank = []
|
||||
cropped_fbank_lengths = []
|
||||
|
||||
for index, total_feat_length_tensor in enumerate(original_fbank_lengths):
|
||||
total_audio_length = int(original_audio_lengths[index].item())
|
||||
total_feat_length = int(total_feat_length_tensor.item())
|
||||
start_audio = int(starts[index].item())
|
||||
end_audio = start_audio + int(cropped_audio_lengths[index].item())
|
||||
|
||||
if total_audio_length > 0:
|
||||
start_feat = math.floor(start_audio * total_feat_length / total_audio_length)
|
||||
end_feat = math.ceil(end_audio * total_feat_length / total_audio_length)
|
||||
else:
|
||||
start_feat = 0
|
||||
end_feat = 1
|
||||
|
||||
start_feat = min(start_feat, total_feat_length - 1)
|
||||
end_feat = min(max(end_feat, start_feat + 1), total_feat_length)
|
||||
cropped_fbank.append(fbank[index, start_feat:end_feat])
|
||||
cropped_fbank_lengths.append(end_feat - start_feat)
|
||||
|
||||
return pad_sequence(
|
||||
cropped_fbank,
|
||||
batch_first=True,
|
||||
padding_value=0.0,
|
||||
), torch.tensor(
|
||||
cropped_fbank_lengths,
|
||||
device=fbank.device,
|
||||
dtype=torch.long,
|
||||
)
|
||||
|
||||
def _extract_fbank_batch(self, audio, audio_lengths):
|
||||
if self.resample is not None:
|
||||
audio = self.resample(audio)
|
||||
audio_lengths = torch.ceil(audio_lengths.float() * (_SPEAKER_FBANK_SAMPLE_RATE / self.sample_rate)).long()
|
||||
|
||||
audio_cpu = audio.detach().cpu()
|
||||
features = []
|
||||
|
||||
for index, valid_length_tensor in enumerate(audio_lengths):
|
||||
valid_length = int(valid_length_tensor.item())
|
||||
waveform = audio_cpu[index, :valid_length]
|
||||
if waveform.numel() == 0:
|
||||
waveform = audio_cpu.new_zeros(1)
|
||||
features.append(
|
||||
extract_speaker_fbank(
|
||||
waveform,
|
||||
sample_rate=_SPEAKER_FBANK_SAMPLE_RATE,
|
||||
)
|
||||
)
|
||||
|
||||
fbank_lengths = torch.tensor(
|
||||
[feature.size(0) for feature in features],
|
||||
device=audio.device,
|
||||
dtype=torch.long,
|
||||
)
|
||||
fbank = pad_sequence(
|
||||
features,
|
||||
batch_first=True,
|
||||
padding_value=0.0,
|
||||
).to(device=audio.device, dtype=audio.dtype)
|
||||
return fbank, fbank_lengths
|
||||
|
||||
@torch.no_grad()
|
||||
@torch.autocast(enabled=False, device_type="cuda")
|
||||
def forward(self, audio, audio_lengths=None, fbank=None, fbank_lengths=None, **_kwargs):
|
||||
self.model.eval()
|
||||
audio = audio.float()
|
||||
if audio.dim() == 3:
|
||||
if audio.size(1) != 1:
|
||||
raise ValueError(f"Speaker encoder expects mono audio, got shape {tuple(audio.shape)}.")
|
||||
audio = audio[:, 0]
|
||||
elif audio.dim() != 2:
|
||||
raise ValueError(f"Speaker encoder expects a 2D or 3D audio tensor, got shape {tuple(audio.shape)}.")
|
||||
|
||||
audio, original_audio_lengths, cropped_audio_lengths, starts = self._crop_audio(
|
||||
audio,
|
||||
audio_lengths=audio_lengths,
|
||||
)
|
||||
|
||||
if fbank is None:
|
||||
fbank, fbank_lengths = self._extract_fbank_batch(
|
||||
audio,
|
||||
cropped_audio_lengths,
|
||||
)
|
||||
else:
|
||||
if not isinstance(fbank, torch.Tensor):
|
||||
raise TypeError("Speaker encoder expects `fbank` to be a torch.Tensor.")
|
||||
if fbank.dim() != 3 or fbank.size(0) != audio.size(0):
|
||||
raise ValueError(
|
||||
f"Speaker encoder expects `fbank` with shape (B, T, F) and matching batch size, got {tuple(fbank.shape)}." # noqa: E501
|
||||
)
|
||||
fbank, fbank_lengths = self._crop_fbank(
|
||||
fbank.to(device=audio.device, dtype=torch.float32),
|
||||
fbank_lengths,
|
||||
original_audio_lengths,
|
||||
cropped_audio_lengths,
|
||||
starts,
|
||||
)
|
||||
|
||||
return self.model(fbank, lengths=fbank_lengths)
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,46 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""dots.tts pipeline topology (frozen).
|
||||
|
||||
Single-stage AR TTS: text → 48 kHz waveform in one pass.
|
||||
Architecture: Qwen2.5-1.5B base LM (vLLM-native) → DiTAR / MeanFlow head
|
||||
→ AudioVAE.decode → BigVGAN → 48 kHz mono.
|
||||
|
||||
Speaker conditioning via CAM++ x-vector injected in preprocess().
|
||||
|
||||
Modeled after voxcpm2's single-stage pipeline (same "vLLM-native base LM
|
||||
+ side-path computation" pattern), but simplified: no residual LM, no FSQ.
|
||||
"""
|
||||
|
||||
from vllm_omni.config.stage_config import (
|
||||
PipelineConfig,
|
||||
StageExecutionType,
|
||||
StagePipelineConfig,
|
||||
)
|
||||
|
||||
DOTS_TTS_PIPELINE = PipelineConfig(
|
||||
model_type="dots_tts",
|
||||
model_arch="DotsTTSForConditionalGeneration",
|
||||
default_deploy_config_name="dots_tts.yaml",
|
||||
stages=(
|
||||
StagePipelineConfig(
|
||||
stage_id=0,
|
||||
model_stage="latent_generator",
|
||||
execution_type=StageExecutionType.LLM_AR,
|
||||
input_sources=(),
|
||||
final_output=True,
|
||||
final_output_type="audio",
|
||||
owns_tokenizer=True,
|
||||
engine_output_type="audio",
|
||||
sampling_constraints={
|
||||
"detokenize": False,
|
||||
# Stop signal slot in compute_logits (voxcpm2 convention —
|
||||
# talker emits logits[i, 1] = 1.0 when prob_stop > 0.8, vLLM
|
||||
# matches against this list to terminate the request). Not
|
||||
# Qwen2.5 EOS (151643) — that ID would never come out of the
|
||||
# 2-slot continue/stop softmax our compute_logits builds.
|
||||
"stop_token_ids": [1],
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
@@ -1,8 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
# NOTE: Do not import model classes in this file. Importing any
|
||||
# submodule in this package triggers __init__.py execution, and
|
||||
# both the model registry and pipeline registry import submodules
|
||||
# directly — heavy imports here would be loaded as a side effect
|
||||
# even though nothing depends on these re-exports.
|
||||
@@ -1,747 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable, Mapping, Sequence
|
||||
from functools import cached_property
|
||||
from importlib import import_module
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.multimodal import BaseDummyOptions
|
||||
from vllm.inputs import MultiModalDataDict
|
||||
from vllm.inputs import MultiModalInput as MultiModalInputs
|
||||
from vllm.model_executor.models.interfaces import SupportsMultiModal
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItems,
|
||||
PlaceholderRange,
|
||||
)
|
||||
from vllm.multimodal.parse import MultiModalDataItems, MultiModalDataParser
|
||||
from vllm.multimodal.processing import (
|
||||
BaseDummyInputsBuilder,
|
||||
BaseMultiModalProcessor,
|
||||
BaseProcessingInfo,
|
||||
ProcessorInputs,
|
||||
PromptUpdate,
|
||||
TimingContext,
|
||||
)
|
||||
from vllm.sequence import IntermediateTensors
|
||||
from vllm.v1.outputs import SamplerOutput
|
||||
from vllm.v1.sample.metadata import SamplingMetadata
|
||||
from vllm.v1.sample.sampler import Sampler
|
||||
|
||||
from vllm_omni.model_executor.models.output_templates import OmniOutput
|
||||
|
||||
from .dynin_omni_common import build_zero_input_embeddings
|
||||
|
||||
try:
|
||||
from PIL import Image as PILImage
|
||||
except Exception: # pragma: no cover
|
||||
PILImage = None
|
||||
|
||||
|
||||
_MODALITY_ORDER = ("image", "video", "audio")
|
||||
|
||||
_MODALITY_ALIASES = {
|
||||
"img2img": "image",
|
||||
}
|
||||
|
||||
_MODALITY_INPUT_KEY_BY_NAME = {
|
||||
"image": "pixel_values",
|
||||
"video": "pixel_values_videos",
|
||||
"audio": "input_audio_features",
|
||||
}
|
||||
|
||||
_MODALITY_PLACEHOLDER_BY_NAME = {
|
||||
"image": "<|soi|><|image|><|eoi|>",
|
||||
"video": "<|sov|><|video|><|eov|>",
|
||||
"audio": "<|soa|><|audio|><|eoa|>",
|
||||
}
|
||||
|
||||
_MODALITY_INPUT_ALIASES = {
|
||||
"image": ("pixel_values", "image_embeds", "img2img"),
|
||||
"video": ("pixel_values_videos", "video_embeds"),
|
||||
"audio": ("input_audio_features", "audio_embeds"),
|
||||
}
|
||||
|
||||
|
||||
def _normalize_modality_name(modality: str) -> str:
|
||||
return _MODALITY_ALIASES.get(modality, modality)
|
||||
|
||||
|
||||
def _get_modality_count(mm_counts: Mapping[str, int], modality: str) -> int:
|
||||
canonical = _normalize_modality_name(modality)
|
||||
count = mm_counts.get(canonical, 0)
|
||||
for alias, target in _MODALITY_ALIASES.items():
|
||||
if target == canonical:
|
||||
count += mm_counts.get(alias, 0)
|
||||
return count
|
||||
|
||||
|
||||
def _normalize_mm_data_aliases(mm_data: MultiModalDataDict) -> MultiModalDataDict:
|
||||
normalized: dict[str, Any] = {}
|
||||
for modality, value in mm_data.items():
|
||||
canonical = _normalize_modality_name(modality)
|
||||
if canonical in normalized and normalized[canonical] is not None and value is not None:
|
||||
raise ValueError(
|
||||
"Dynin received duplicate multimodal inputs for "
|
||||
f"{canonical!r} via {modality!r}. "
|
||||
"Provide either the canonical modality or its alias, not both."
|
||||
)
|
||||
if canonical not in normalized or normalized[canonical] is None:
|
||||
normalized[canonical] = value
|
||||
return normalized
|
||||
|
||||
|
||||
def _get_placeholder_text(modality: str) -> str | None:
|
||||
modality = _normalize_modality_name(modality)
|
||||
for base_modality, placeholder in _MODALITY_PLACEHOLDER_BY_NAME.items():
|
||||
if modality.startswith(base_modality):
|
||||
return placeholder
|
||||
return None
|
||||
|
||||
|
||||
class DyninOmniProcessingInfo(BaseProcessingInfo):
|
||||
def get_data_parser(self) -> MultiModalDataParser:
|
||||
return DyninOmniMultiModalDataParser(
|
||||
expected_hidden_size=self._get_expected_hidden_size(),
|
||||
)
|
||||
|
||||
def get_supported_mm_limits(self) -> Mapping[str, int | None]:
|
||||
limits = {modality: 1 for modality in _MODALITY_ORDER}
|
||||
for alias, target in _MODALITY_ALIASES.items():
|
||||
if target in limits:
|
||||
limits[alias] = limits[target]
|
||||
return limits
|
||||
|
||||
def get_mm_max_tokens_per_item(
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
) -> Mapping[str, int] | None:
|
||||
del seq_len, mm_counts
|
||||
limits = {modality: 1 for modality in _MODALITY_ORDER}
|
||||
for alias, target in _MODALITY_ALIASES.items():
|
||||
if target in limits:
|
||||
limits[alias] = limits[target]
|
||||
return limits
|
||||
|
||||
|
||||
class DyninOmniDummyInputsBuilder(BaseDummyInputsBuilder[DyninOmniProcessingInfo]):
|
||||
def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str:
|
||||
chunks: list[str] = []
|
||||
for modality in _MODALITY_ORDER:
|
||||
placeholder = _get_placeholder_text(modality)
|
||||
if placeholder is None:
|
||||
continue
|
||||
chunks.extend([placeholder] * _get_modality_count(mm_counts, modality))
|
||||
return " ".join(chunks)
|
||||
|
||||
def get_dummy_mm_data(
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
mm_options: Mapping[str, BaseDummyOptions] | None = None,
|
||||
) -> MultiModalDataDict:
|
||||
del seq_len
|
||||
|
||||
mm_data: dict[str, Any] = {}
|
||||
|
||||
num_images = _get_modality_count(mm_counts, "image")
|
||||
if num_images > 0:
|
||||
mm_data["image"] = self._get_dummy_images(
|
||||
width=224,
|
||||
height=224,
|
||||
num_images=num_images,
|
||||
overrides=mm_options.get("image") if mm_options else None,
|
||||
)
|
||||
|
||||
num_videos = _get_modality_count(mm_counts, "video")
|
||||
if num_videos > 0:
|
||||
mm_data["video"] = self._get_dummy_videos(
|
||||
width=224,
|
||||
height=224,
|
||||
num_frames=8,
|
||||
num_videos=num_videos,
|
||||
overrides=mm_options.get("video") if mm_options else None,
|
||||
)
|
||||
|
||||
num_audios = _get_modality_count(mm_counts, "audio")
|
||||
if num_audios > 0:
|
||||
mm_data["audio"] = self._get_dummy_audios(
|
||||
length=16000,
|
||||
num_audios=num_audios,
|
||||
overrides=mm_options.get("audio") if mm_options else None,
|
||||
)
|
||||
|
||||
return mm_data
|
||||
|
||||
|
||||
class DyninOmniMultiModalDataParser(MultiModalDataParser):
|
||||
def parse_mm_data(self, mm_data: MultiModalDataDict) -> MultiModalDataItems:
|
||||
normalized = _normalize_mm_data_aliases(mm_data)
|
||||
mm_items = super().parse_mm_data(normalized)
|
||||
|
||||
for alias, canonical in _MODALITY_ALIASES.items():
|
||||
if alias in mm_data and canonical in mm_items and alias not in mm_items:
|
||||
mm_items[alias] = mm_items[canonical]
|
||||
|
||||
return mm_items
|
||||
|
||||
def _get_audio_with_sr(self, audio: Any) -> tuple[np.ndarray, float | None]:
|
||||
audio_array, orig_sr = super()._get_audio_with_sr(audio)
|
||||
if self.audio_resampler.target_sr is None:
|
||||
return audio_array, None
|
||||
return audio_array, orig_sr
|
||||
|
||||
|
||||
class DyninOmniMultiModalProcessor(BaseMultiModalProcessor[DyninOmniProcessingInfo]):
|
||||
@staticmethod
|
||||
def _find_subsequence(
|
||||
haystack: list[int],
|
||||
needle: list[int],
|
||||
start: int,
|
||||
) -> int | None:
|
||||
if not needle:
|
||||
return None
|
||||
|
||||
max_start = len(haystack) - len(needle)
|
||||
if max_start < start:
|
||||
return None
|
||||
|
||||
for idx in range(start, max_start + 1):
|
||||
if haystack[idx : idx + len(needle)] == needle:
|
||||
return idx
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _make_disabled_embed_mask(length: int) -> torch.Tensor:
|
||||
return torch.zeros(length, dtype=torch.bool)
|
||||
|
||||
@staticmethod
|
||||
def _encode_prompt_to_token_ids(
|
||||
prompt: str | list[int],
|
||||
tokenizer: Any | None,
|
||||
) -> list[int]:
|
||||
if isinstance(prompt, str):
|
||||
if tokenizer is None:
|
||||
raise ValueError("Tokenizer is required to process string prompts for Dynin multimodal inputs.")
|
||||
return tokenizer.encode(prompt, add_special_tokens=False)
|
||||
return list(prompt)
|
||||
|
||||
@staticmethod
|
||||
def _ensure_non_empty_prompt_ids(
|
||||
prompt_token_ids: list[int],
|
||||
tokenizer: Any | None,
|
||||
) -> list[int]:
|
||||
if prompt_token_ids:
|
||||
return prompt_token_ids
|
||||
|
||||
fallback_id = None
|
||||
if tokenizer is not None:
|
||||
fallback_id = getattr(tokenizer, "bos_token_id", None)
|
||||
if fallback_id is None:
|
||||
fallback_id = getattr(tokenizer, "eos_token_id", None)
|
||||
if fallback_id is None:
|
||||
fallback_id = getattr(tokenizer, "pad_token_id", None)
|
||||
|
||||
return [0 if fallback_id is None else int(fallback_id)]
|
||||
|
||||
@classmethod
|
||||
def _image_to_chw_float_tensor(cls, image: Any) -> torch.Tensor:
|
||||
if isinstance(image, torch.Tensor):
|
||||
tensor = image.detach()
|
||||
elif isinstance(image, np.ndarray):
|
||||
tensor = torch.from_numpy(image)
|
||||
elif PILImage is not None and isinstance(image, PILImage.Image):
|
||||
tensor = torch.from_numpy(np.asarray(image).copy())
|
||||
else:
|
||||
raise TypeError(f"Unsupported image item type: {type(image)!r}")
|
||||
|
||||
if tensor.ndim == 2:
|
||||
tensor = tensor.unsqueeze(-1)
|
||||
if tensor.ndim != 3:
|
||||
raise ValueError(f"Expected 3D image tensor, got shape={tuple(tensor.shape)}")
|
||||
|
||||
if tensor.shape[-1] in (1, 3, 4) and tensor.shape[0] not in (1, 3, 4):
|
||||
tensor = tensor.permute(2, 0, 1)
|
||||
|
||||
if tensor.shape[0] == 1:
|
||||
tensor = tensor.repeat(3, 1, 1)
|
||||
if tensor.shape[0] == 4:
|
||||
tensor = tensor[:3]
|
||||
|
||||
tensor = tensor.to(dtype=torch.float32)
|
||||
if tensor.numel() > 0 and torch.max(tensor) > 1.0:
|
||||
tensor = tensor / 255.0
|
||||
return tensor.contiguous()
|
||||
|
||||
@classmethod
|
||||
def _video_to_tchw_float_tensor(cls, video: Any) -> torch.Tensor:
|
||||
if isinstance(video, (list, tuple)) and not isinstance(video, torch.Tensor):
|
||||
frames = [cls._image_to_chw_float_tensor(frame) for frame in video]
|
||||
if not frames:
|
||||
return torch.zeros((1, 3, 1, 1), dtype=torch.float32)
|
||||
return torch.stack(frames, dim=0).contiguous()
|
||||
|
||||
if isinstance(video, torch.Tensor):
|
||||
tensor = video.detach()
|
||||
elif isinstance(video, np.ndarray):
|
||||
tensor = torch.from_numpy(video)
|
||||
else:
|
||||
raise TypeError(f"Unsupported video item type: {type(video)!r}")
|
||||
|
||||
if tensor.ndim == 3:
|
||||
return cls._image_to_chw_float_tensor(tensor).unsqueeze(0).contiguous()
|
||||
|
||||
if tensor.ndim != 4:
|
||||
raise ValueError(f"Expected 4D video tensor, got shape={tuple(tensor.shape)}")
|
||||
|
||||
if tensor.shape[-1] in (1, 3, 4) and tensor.shape[1] not in (1, 3, 4):
|
||||
tensor = tensor.permute(0, 3, 1, 2)
|
||||
|
||||
if tensor.shape[1] == 1:
|
||||
tensor = tensor.repeat(1, 3, 1, 1)
|
||||
if tensor.shape[1] == 4:
|
||||
tensor = tensor[:, :3]
|
||||
|
||||
tensor = tensor.to(dtype=torch.float32)
|
||||
if tensor.numel() > 0 and torch.max(tensor) > 1.0:
|
||||
tensor = tensor / 255.0
|
||||
return tensor.contiguous()
|
||||
|
||||
@staticmethod
|
||||
def _audio_to_float_tensor(audio: Any) -> torch.Tensor:
|
||||
if isinstance(audio, tuple) and len(audio) == 2:
|
||||
audio = audio[0]
|
||||
|
||||
if isinstance(audio, torch.Tensor):
|
||||
tensor = audio.detach()
|
||||
elif isinstance(audio, np.ndarray):
|
||||
tensor = torch.from_numpy(audio)
|
||||
else:
|
||||
tensor = torch.as_tensor(audio)
|
||||
|
||||
tensor = tensor.to(dtype=torch.float32).contiguous().view(-1)
|
||||
if tensor.numel() == 0:
|
||||
return torch.zeros((16000,), dtype=torch.float32)
|
||||
|
||||
max_abs = torch.max(torch.abs(tensor))
|
||||
if max_abs > 1.0:
|
||||
tensor = tensor / max_abs
|
||||
|
||||
return tensor.contiguous()
|
||||
|
||||
@classmethod
|
||||
def _convert_modality_item(cls, modality: str, item: Any) -> torch.Tensor:
|
||||
if modality == "image":
|
||||
return cls._image_to_chw_float_tensor(item)
|
||||
if modality == "video":
|
||||
return cls._video_to_tchw_float_tensor(item)
|
||||
if modality == "audio":
|
||||
return cls._audio_to_float_tensor(item)
|
||||
raise ValueError(f"Unsupported modality for Dynin processor: {modality}")
|
||||
|
||||
def _build_modality_kwargs(
|
||||
self,
|
||||
modality: str,
|
||||
modality_items: Sequence[Any],
|
||||
) -> Sequence[Any]:
|
||||
modality = _normalize_modality_name(modality)
|
||||
input_key = _MODALITY_INPUT_KEY_BY_NAME[modality]
|
||||
tensor_items = [self._convert_modality_item(modality, item) for item in modality_items]
|
||||
mm_kwargs = MultiModalKwargsItems.from_hf_inputs(
|
||||
{input_key: tensor_items},
|
||||
{input_key: MultiModalFieldConfig.batched(modality)},
|
||||
)
|
||||
return mm_kwargs[modality]
|
||||
|
||||
def _build_placeholder_ranges(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
item_count: int,
|
||||
prompt_token_ids: list[int],
|
||||
tokenizer: Any | None,
|
||||
search_start: int,
|
||||
) -> tuple[list[PlaceholderRange], int]:
|
||||
ranges: list[PlaceholderRange] = []
|
||||
|
||||
for _ in range(item_count):
|
||||
placeholder_text = _get_placeholder_text(modality)
|
||||
placeholder_token_ids: list[int] = []
|
||||
|
||||
if placeholder_text and tokenizer is not None:
|
||||
placeholder_token_ids = tokenizer.encode(
|
||||
placeholder_text,
|
||||
add_special_tokens=False,
|
||||
)
|
||||
|
||||
found_offset = None
|
||||
if placeholder_token_ids:
|
||||
found_offset = self._find_subsequence(
|
||||
prompt_token_ids,
|
||||
placeholder_token_ids,
|
||||
search_start,
|
||||
)
|
||||
|
||||
if found_offset is None:
|
||||
found_offset = min(search_start, len(prompt_token_ids) - 1)
|
||||
placeholder_len = 1
|
||||
else:
|
||||
placeholder_len = len(placeholder_token_ids)
|
||||
|
||||
ranges.append(
|
||||
PlaceholderRange(
|
||||
offset=found_offset,
|
||||
length=placeholder_len,
|
||||
is_embed=self._make_disabled_embed_mask(placeholder_len),
|
||||
)
|
||||
)
|
||||
search_start = found_offset + placeholder_len
|
||||
|
||||
return ranges, search_start
|
||||
|
||||
def _get_mm_fields_config(
|
||||
self,
|
||||
hf_inputs: Any,
|
||||
hf_processor_mm_kwargs: Mapping[str, object],
|
||||
) -> Mapping[str, MultiModalFieldConfig]:
|
||||
del hf_inputs, hf_processor_mm_kwargs
|
||||
return {}
|
||||
|
||||
def _get_prompt_updates(
|
||||
self,
|
||||
mm_items: MultiModalDataItems,
|
||||
hf_processor_mm_kwargs: Mapping[str, object],
|
||||
out_mm_kwargs: MultiModalKwargsItems,
|
||||
) -> Sequence[PromptUpdate]:
|
||||
del mm_items, hf_processor_mm_kwargs, out_mm_kwargs
|
||||
return []
|
||||
|
||||
def apply(
|
||||
self,
|
||||
inputs: ProcessorInputs,
|
||||
timing_ctx: TimingContext,
|
||||
) -> MultiModalInputs:
|
||||
prompt = inputs.prompt
|
||||
mm_items = inputs.mm_data_items
|
||||
|
||||
with timing_ctx.record("get_mm_hashes"):
|
||||
mm_hashes = inputs.get_mm_hashes(
|
||||
self.info.model_id,
|
||||
self.info.ctx.get_mm_config().mm_hasher_algorithm,
|
||||
)
|
||||
|
||||
tokenizer = self.info.ctx.tokenizer
|
||||
prompt_token_ids = self._encode_prompt_to_token_ids(prompt, tokenizer)
|
||||
prompt_token_ids = self._ensure_non_empty_prompt_ids(prompt_token_ids, tokenizer)
|
||||
|
||||
mm_kwargs_by_modality: dict[str, Sequence[Any]] = {}
|
||||
mm_placeholders: dict[str, list[PlaceholderRange]] = {}
|
||||
search_start = 0
|
||||
mm_counts = mm_items.get_all_counts()
|
||||
|
||||
for modality in _MODALITY_ORDER:
|
||||
item_count = mm_counts.get(modality, 0)
|
||||
if item_count <= 0:
|
||||
continue
|
||||
|
||||
modality_items = mm_items[modality].get_all()
|
||||
if len(modality_items) != item_count:
|
||||
raise RuntimeError(
|
||||
f"Parsed {len(modality_items)} items but expected {item_count} for modality={modality!r}"
|
||||
)
|
||||
|
||||
mm_kwargs_by_modality[modality] = self._build_modality_kwargs(
|
||||
modality,
|
||||
modality_items,
|
||||
)
|
||||
|
||||
placeholder_ranges, search_start = self._build_placeholder_ranges(
|
||||
modality=modality,
|
||||
item_count=item_count,
|
||||
prompt_token_ids=prompt_token_ids,
|
||||
tokenizer=tokenizer,
|
||||
search_start=search_start,
|
||||
)
|
||||
mm_placeholders[modality] = placeholder_ranges
|
||||
|
||||
return MultiModalInputs(
|
||||
type="multimodal",
|
||||
prompt_token_ids=prompt_token_ids,
|
||||
mm_kwargs=MultiModalKwargsItems(mm_kwargs_by_modality),
|
||||
mm_hashes=mm_hashes,
|
||||
mm_placeholders=mm_placeholders,
|
||||
)
|
||||
|
||||
|
||||
class DyninOmniStageBase(nn.Module):
|
||||
stage_name = "Dynin stage"
|
||||
|
||||
def make_empty_intermediate_tensors(
|
||||
self,
|
||||
batch_size: int,
|
||||
dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
) -> IntermediateTensors:
|
||||
del batch_size, dtype, device
|
||||
return IntermediateTensors({})
|
||||
|
||||
def embed_input_ids(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
multimodal_embeddings: Any = None,
|
||||
is_multimodal: torch.Tensor | None = None,
|
||||
**kwargs: Any,
|
||||
) -> torch.Tensor:
|
||||
del multimodal_embeddings, is_multimodal, kwargs
|
||||
return build_zero_input_embeddings(
|
||||
input_ids=input_ids,
|
||||
hidden_size=self.hidden_size,
|
||||
stage_name=self.stage_name,
|
||||
)
|
||||
|
||||
def load_weights(
|
||||
self,
|
||||
weights: Iterable[tuple[str, torch.Tensor]],
|
||||
) -> set[str]:
|
||||
return {name for name, _ in weights}
|
||||
|
||||
def compute_logits(
|
||||
self,
|
||||
hidden_states: torch.Tensor | OmniOutput,
|
||||
sampling_metadata: Any = None,
|
||||
) -> torch.Tensor | None:
|
||||
del hidden_states, sampling_metadata
|
||||
return None
|
||||
|
||||
|
||||
@MULTIMODAL_REGISTRY.register_processor(
|
||||
DyninOmniMultiModalProcessor,
|
||||
info=DyninOmniProcessingInfo,
|
||||
dummy_inputs=DyninOmniDummyInputsBuilder,
|
||||
)
|
||||
class DyninOmniForConditionalGeneration(nn.Module, SupportsMultiModal):
|
||||
supports_multimodal_raw_input_only = True
|
||||
STAGE_ALIAS = {
|
||||
"tokenizer": "token2text",
|
||||
"token2token": "token2text",
|
||||
"detok_text": "token2text",
|
||||
"token2img": "token2image",
|
||||
"token2wav": "token2audio",
|
||||
"token2speech": "token2audio",
|
||||
}
|
||||
|
||||
STAGE_IMPL = {
|
||||
"token2text": (".dynin_omni_token2text", "DyninOmniToken2Text"),
|
||||
"token2image": (".dynin_omni_token2image", "DyninOmniToken2Image"),
|
||||
"token2audio": (".dynin_omni_token2audio", "DyninOmniToken2Audio"),
|
||||
}
|
||||
|
||||
_STAGE_IMPL_CACHE: dict[str, type[nn.Module]] = {}
|
||||
|
||||
@classmethod
|
||||
def get_placeholder_str(cls, modality: str, i: int) -> str | None:
|
||||
del i
|
||||
return _get_placeholder_text(modality)
|
||||
|
||||
@classmethod
|
||||
def _resolve_stage_impl_class(cls, model_stage: str) -> type[nn.Module]:
|
||||
impl = cls._STAGE_IMPL_CACHE.get(model_stage)
|
||||
if impl is not None:
|
||||
return impl
|
||||
|
||||
module_name, class_name = cls.STAGE_IMPL[model_stage]
|
||||
module = import_module(module_name, package=__package__)
|
||||
impl = getattr(module, class_name)
|
||||
cls._STAGE_IMPL_CACHE[model_stage] = impl
|
||||
return impl
|
||||
|
||||
@classmethod
|
||||
def _normalize_stage_name(cls, raw_stage: str) -> str:
|
||||
normalized = cls.STAGE_ALIAS.get(raw_stage, raw_stage)
|
||||
if normalized not in cls.STAGE_IMPL:
|
||||
raise ValueError(
|
||||
"Unsupported DYNIN omni model_stage: "
|
||||
f"{raw_stage} (normalized={normalized}). "
|
||||
f"Supported: {sorted(cls.STAGE_IMPL.keys())}"
|
||||
)
|
||||
return normalized
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
|
||||
super().__init__()
|
||||
|
||||
raw_stage = str(getattr(vllm_config.model_config, "model_stage", "token2text")).lower()
|
||||
self.model_stage = self._normalize_stage_name(raw_stage)
|
||||
|
||||
impl_cls = self._resolve_stage_impl_class(self.model_stage)
|
||||
self.impl = impl_cls(vllm_config=vllm_config, prefix=prefix)
|
||||
self.model = self.impl
|
||||
|
||||
self.has_preprocess = False
|
||||
self.has_postprocess = False
|
||||
self.have_multimodal_outputs = getattr(self.impl, "have_multimodal_outputs", True)
|
||||
self.requires_raw_input_tokens = getattr(self.impl, "requires_raw_input_tokens", True)
|
||||
self.language_model = self._resolve_language_model()
|
||||
|
||||
def _resolve_language_model(self) -> Any | None:
|
||||
if hasattr(self.impl, "get_language_model"):
|
||||
language_model = self.impl.get_language_model()
|
||||
if language_model is not None:
|
||||
return language_model
|
||||
|
||||
if hasattr(self.impl, "language_model"):
|
||||
language_model = getattr(self.impl, "language_model")
|
||||
if language_model is not None:
|
||||
return language_model
|
||||
|
||||
if self.model_stage == "token2text":
|
||||
return getattr(self.impl, "model", None)
|
||||
|
||||
return None
|
||||
|
||||
def get_language_model(self) -> Any | None:
|
||||
return self.language_model
|
||||
|
||||
@cached_property
|
||||
def sampler(self):
|
||||
if hasattr(self.model, "sampler"):
|
||||
return self.model.sampler
|
||||
if self.language_model is not None and hasattr(self.language_model, "sampler"):
|
||||
return self.language_model.sampler
|
||||
return Sampler()
|
||||
|
||||
def init_multi_modal(self, thinker_config: Any = None) -> None:
|
||||
if hasattr(self.model, "init_multi_modal"):
|
||||
self.model.init_multi_modal(thinker_config)
|
||||
|
||||
def _collect_multimodal_inputs(self, **kwargs: Any) -> dict[str, Any]:
|
||||
mm_inputs: dict[str, Any] = {}
|
||||
for modality, aliases in _MODALITY_INPUT_ALIASES.items():
|
||||
for alias in aliases:
|
||||
if alias in kwargs and kwargs[alias] is not None:
|
||||
mm_inputs[modality] = kwargs[alias]
|
||||
break
|
||||
return mm_inputs
|
||||
|
||||
def _normalize_loaded_weight_names(
|
||||
self,
|
||||
loaded: set[str],
|
||||
expected_param_names: set[str],
|
||||
) -> set[str]:
|
||||
if self.model_stage != "token2text":
|
||||
return loaded
|
||||
|
||||
normalized_loaded: set[str] = set()
|
||||
prefixes = ("", "impl.", "impl.model.")
|
||||
|
||||
for name in loaded:
|
||||
for prefix in prefixes:
|
||||
candidate = f"{prefix}{name}" if prefix else name
|
||||
if candidate in expected_param_names:
|
||||
normalized_loaded.add(candidate)
|
||||
break
|
||||
|
||||
if len(normalized_loaded) < len(expected_param_names):
|
||||
normalized_loaded.update(expected_param_names)
|
||||
|
||||
return normalized_loaded
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor | None = None,
|
||||
positions: torch.Tensor | None = None,
|
||||
intermediate_tensors: IntermediateTensors | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
**kwargs: Any,
|
||||
) -> OmniOutput:
|
||||
return self.model(
|
||||
input_ids=input_ids,
|
||||
positions=positions,
|
||||
intermediate_tensors=intermediate_tensors,
|
||||
inputs_embeds=inputs_embeds,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def make_empty_intermediate_tensors(
|
||||
self,
|
||||
batch_size: int,
|
||||
dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
) -> IntermediateTensors:
|
||||
return self.model.make_empty_intermediate_tensors(batch_size, dtype, device)
|
||||
|
||||
def embed_input_ids(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
multimodal_embeddings: Any = None,
|
||||
is_multimodal: torch.Tensor | None = None,
|
||||
**kwargs: Any,
|
||||
) -> torch.Tensor:
|
||||
squeezed_batch = False
|
||||
staged_input_ids = input_ids
|
||||
|
||||
if input_ids.ndim == 0:
|
||||
staged_input_ids = input_ids.view(1, 1)
|
||||
squeezed_batch = True
|
||||
elif input_ids.ndim == 1:
|
||||
staged_input_ids = input_ids.unsqueeze(0)
|
||||
squeezed_batch = True
|
||||
|
||||
embeddings = self.model.embed_input_ids(
|
||||
staged_input_ids,
|
||||
multimodal_embeddings=multimodal_embeddings,
|
||||
is_multimodal=is_multimodal,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
if squeezed_batch and isinstance(embeddings, torch.Tensor):
|
||||
if embeddings.ndim == 3 and embeddings.shape[0] == 1:
|
||||
return embeddings.squeeze(0)
|
||||
if embeddings.ndim == 2 and input_ids.ndim == 0 and embeddings.shape[0] == 1:
|
||||
return embeddings
|
||||
|
||||
return embeddings
|
||||
|
||||
def embed_multimodal(self, **kwargs: Any) -> Any:
|
||||
if hasattr(self.model, "embed_multimodal"):
|
||||
return self.model.embed_multimodal(**kwargs)
|
||||
|
||||
self._collect_multimodal_inputs(**kwargs)
|
||||
return None
|
||||
|
||||
def load_weights(
|
||||
self,
|
||||
weights: Iterable[tuple[str, torch.Tensor]],
|
||||
) -> set[str]:
|
||||
loaded = self.model.load_weights(weights)
|
||||
if loaded is None:
|
||||
loaded = set()
|
||||
|
||||
expected_param_names = {name for name, _ in self.named_parameters()}
|
||||
if not expected_param_names:
|
||||
return loaded
|
||||
|
||||
return self._normalize_loaded_weight_names(loaded, expected_param_names)
|
||||
|
||||
def compute_logits(
|
||||
self,
|
||||
hidden_states: torch.Tensor | OmniOutput,
|
||||
sampling_metadata: Any = None,
|
||||
) -> torch.Tensor | None:
|
||||
return self.model.compute_logits(hidden_states, sampling_metadata=sampling_metadata)
|
||||
|
||||
def sample(
|
||||
self,
|
||||
logits: torch.Tensor,
|
||||
sampling_metadata: SamplingMetadata,
|
||||
) -> SamplerOutput | None:
|
||||
if hasattr(self.model, "sample"):
|
||||
return self.model.sample(logits, sampling_metadata)
|
||||
if self.language_model is not None and hasattr(self.language_model, "sample"):
|
||||
return self.language_model.sample(logits, sampling_metadata)
|
||||
return None
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,313 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
from vllm.sequence import IntermediateTensors
|
||||
|
||||
from vllm_omni.model_executor.models.output_templates import OmniOutput
|
||||
|
||||
from .dynin_omni import DyninOmniStageBase
|
||||
from .dynin_omni_common import (
|
||||
DetokTarget,
|
||||
_looks_like_hf_repo_id,
|
||||
coerce_token_ids_1d,
|
||||
normalize_runtime_info,
|
||||
resolve_dynin_infer_sources,
|
||||
resolve_hidden_size,
|
||||
unwrap_first_value,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _get_hf_token() -> str | None:
|
||||
return os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_HUB_TOKEN")
|
||||
|
||||
|
||||
def _ensure_transformers_tied_weights_compat() -> None:
|
||||
"""Provide the transformers>=5 tied-weight attr expected during loading.
|
||||
|
||||
The DYNIN audio detokenizer uses Hugging Face remote code that still only
|
||||
defines the older ``_tied_weights_keys`` attribute. transformers 5.x now
|
||||
reads ``all_tied_weights_keys`` inside ``from_pretrained`` before the model
|
||||
instance is returned, so patching the loaded object is too late.
|
||||
"""
|
||||
try:
|
||||
from transformers import PreTrainedModel
|
||||
except Exception:
|
||||
return
|
||||
|
||||
if hasattr(PreTrainedModel, "all_tied_weights_keys"):
|
||||
return
|
||||
|
||||
def all_tied_weights_keys(self: Any) -> dict[str, Any]:
|
||||
keys: dict[str, Any] = {}
|
||||
for attr_name in ("_tied_weights_keys", "_dynamic_tied_weights_keys"):
|
||||
raw_keys = getattr(self, attr_name, None)
|
||||
if raw_keys is None:
|
||||
continue
|
||||
if isinstance(raw_keys, dict):
|
||||
keys.update({str(k): v for k, v in raw_keys.items()})
|
||||
continue
|
||||
if isinstance(raw_keys, str):
|
||||
keys[raw_keys] = None
|
||||
continue
|
||||
for key in raw_keys:
|
||||
keys[str(key)] = None
|
||||
return keys
|
||||
|
||||
PreTrainedModel.all_tied_weights_keys = property(all_tied_weights_keys) # type: ignore[attr-defined]
|
||||
|
||||
|
||||
def _ensure_remote_s2u_vendor_root(
|
||||
*,
|
||||
repo_id: str,
|
||||
local_files_only: bool,
|
||||
) -> str | None:
|
||||
if local_files_only or not _looks_like_hf_repo_id(repo_id):
|
||||
return None
|
||||
|
||||
existing = os.environ.get("DYNIN_S2U_VENDOR_ROOT")
|
||||
if existing:
|
||||
existing_path = Path(existing).expanduser().resolve()
|
||||
if existing_path.is_dir():
|
||||
return str(existing_path)
|
||||
|
||||
try:
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
except Exception as e:
|
||||
logger.warning("huggingface_hub unavailable; cannot fetch s2u_vendor from %s: %s", repo_id, e)
|
||||
return None
|
||||
|
||||
token = _get_hf_token()
|
||||
last_error: Exception | None = None
|
||||
revisions: list[str | None] = [None]
|
||||
|
||||
for revision in revisions:
|
||||
try:
|
||||
snapshot_dir = hf_api().snapshot_download(
|
||||
repo_id=repo_id,
|
||||
revision=revision,
|
||||
allow_patterns=["s2u_vendor/**"],
|
||||
token=token,
|
||||
)
|
||||
except TypeError:
|
||||
try:
|
||||
snapshot_dir = hf_api().snapshot_download(
|
||||
repo_id=repo_id,
|
||||
revision=revision,
|
||||
allow_patterns=["s2u_vendor/**"],
|
||||
)
|
||||
except Exception as e:
|
||||
last_error = e
|
||||
continue
|
||||
except Exception as e:
|
||||
last_error = e
|
||||
continue
|
||||
|
||||
vendor_root = (Path(snapshot_dir) / "s2u_vendor").resolve()
|
||||
if vendor_root.is_dir():
|
||||
os.environ["DYNIN_S2U_VENDOR_ROOT"] = str(vendor_root)
|
||||
logger.info("Using remote S2U vendor root: %s", vendor_root)
|
||||
return str(vendor_root)
|
||||
|
||||
if last_error is not None:
|
||||
logger.warning("Failed to download remote s2u_vendor from %s: %s", repo_id, last_error)
|
||||
return None
|
||||
|
||||
|
||||
class DyninOmniToken2Audio(DyninOmniStageBase):
|
||||
"""Stage-3: token detokenization to speech (or pass-through)."""
|
||||
|
||||
stage_name = "Dynin token2audio"
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
|
||||
del prefix
|
||||
super().__init__()
|
||||
self.vllm_config = vllm_config
|
||||
self.have_multimodal_outputs = True
|
||||
self.requires_raw_input_tokens = True
|
||||
self.hidden_size = resolve_hidden_size(vllm_config=vllm_config)
|
||||
self._vq_audio = None
|
||||
self._vq_audio_path: str | None = None
|
||||
self._vq_audio_local_files_only: bool | None = None
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor | None = None,
|
||||
positions: torch.Tensor | None = None,
|
||||
intermediate_tensors: IntermediateTensors | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
**kwargs: Any,
|
||||
) -> OmniOutput:
|
||||
del positions, intermediate_tensors, inputs_embeds
|
||||
if input_ids is None:
|
||||
raise ValueError("token2audio stage requires input_ids")
|
||||
|
||||
runtime_info = normalize_runtime_info(kwargs.get("runtime_additional_information"))
|
||||
detok_id = int(unwrap_first_value(runtime_info.get("detok_id"), 0))
|
||||
tokens = coerce_token_ids_1d(input_ids)
|
||||
|
||||
if detok_id != DetokTarget.AUDIO:
|
||||
return OmniOutput(
|
||||
text_hidden_states=None,
|
||||
multimodal_outputs={
|
||||
"token_ids": tokens,
|
||||
"detok_id": torch.tensor([detok_id], dtype=torch.long, device=tokens.device),
|
||||
},
|
||||
)
|
||||
|
||||
audio, sample_rate = self._decode_audio_tokens(tokens, runtime_info=runtime_info)
|
||||
return OmniOutput(
|
||||
text_hidden_states=None,
|
||||
multimodal_outputs={
|
||||
"speech": audio,
|
||||
"audio": audio,
|
||||
"sr": torch.tensor([sample_rate], dtype=torch.int, device=audio.device),
|
||||
"detok_id": torch.tensor([detok_id], dtype=torch.long, device=audio.device),
|
||||
},
|
||||
)
|
||||
|
||||
def _decode_audio_tokens(self, tokens: torch.Tensor, runtime_info: dict[str, Any]) -> tuple[torch.Tensor, int]:
|
||||
# Follow DYNIN validation path:
|
||||
# token list -> "<|speech_x|>" string -> vq_model_audio.decode(...).
|
||||
vq_audio = self._ensure_vq_audio(runtime_info=runtime_info, ref_device=tokens.device)
|
||||
|
||||
audio_codebook_size = int(unwrap_first_value(runtime_info.get("audio_codebook_size"), 4096))
|
||||
audio_vocab_offset = unwrap_first_value(
|
||||
runtime_info.get("audio_vocab_offset"),
|
||||
unwrap_first_value(runtime_info.get("t2s_vocab_start"), None),
|
||||
)
|
||||
|
||||
token_ids = tokens.to(torch.long)
|
||||
if audio_vocab_offset is not None:
|
||||
off = int(audio_vocab_offset)
|
||||
token_ids = torch.where(token_ids >= off, token_ids - off, token_ids)
|
||||
token_ids = token_ids[(token_ids >= 0) & (token_ids < audio_codebook_size)]
|
||||
if token_ids.numel() == 0:
|
||||
raise RuntimeError("Audio detokenizer got no valid audio token ids.")
|
||||
|
||||
speech_unit_str = " ".join(map(str, token_ids.detach().cpu().tolist()))
|
||||
speech_unit_for_decode = "".join(f"<|speech_{unit}|>" for unit in speech_unit_str.split(" ") if unit != "")
|
||||
|
||||
condition = unwrap_first_value(
|
||||
runtime_info.get("condition"),
|
||||
unwrap_first_value(runtime_info.get("t2s_condition"), None),
|
||||
)
|
||||
output_wav_file = unwrap_first_value(runtime_info.get("output_wav_file"), None)
|
||||
created_tmp = False
|
||||
if output_wav_file is None:
|
||||
fd, tmp_wav = tempfile.mkstemp(prefix="dynin_t2s_", suffix=".wav")
|
||||
os.close(fd)
|
||||
output_wav_file = tmp_wav
|
||||
created_tmp = True
|
||||
|
||||
audio_array = vq_audio.decode(speech_unit_for_decode, condition=condition, output_wav_file=output_wav_file)
|
||||
if created_tmp:
|
||||
try:
|
||||
os.remove(output_wav_file)
|
||||
except Exception:
|
||||
pass
|
||||
if not isinstance(audio_array, torch.Tensor):
|
||||
audio_array = torch.as_tensor(audio_array, dtype=torch.float32, device=tokens.device)
|
||||
else:
|
||||
audio_array = audio_array.to(device=tokens.device, dtype=torch.float32)
|
||||
|
||||
if audio_array.ndim > 1:
|
||||
audio_array = audio_array.reshape(-1)
|
||||
audio_array = audio_array.contiguous()
|
||||
|
||||
sample_rate = int(
|
||||
unwrap_first_value(
|
||||
runtime_info.get("sr"),
|
||||
unwrap_first_value(runtime_info.get("sample_rate"), 24000),
|
||||
)
|
||||
)
|
||||
try:
|
||||
cfg = getattr(vq_audio, "u2s_config", None)
|
||||
cfg_sr = getattr(cfg, "sampling_rate", None)
|
||||
if cfg_sr is None:
|
||||
cfg_sr = getattr(getattr(cfg, "data", None), "sampling_rate", None)
|
||||
if cfg_sr is not None:
|
||||
sample_rate = int(cfg_sr)
|
||||
except Exception:
|
||||
pass
|
||||
return audio_array, sample_rate
|
||||
|
||||
def _ensure_vq_audio(self, runtime_info: dict[str, Any], ref_device: torch.device) -> Any:
|
||||
sources = resolve_dynin_infer_sources(vllm_config=self.vllm_config, runtime_info=runtime_info)
|
||||
model_path = str(sources.vq_audio_source)
|
||||
local_files_only = bool(sources.vq_audio_local_files_only)
|
||||
|
||||
_ensure_remote_s2u_vendor_root(
|
||||
repo_id=model_path,
|
||||
local_files_only=local_files_only,
|
||||
)
|
||||
|
||||
if (
|
||||
self._vq_audio is None
|
||||
or self._vq_audio_path != model_path
|
||||
or self._vq_audio_local_files_only != local_files_only
|
||||
):
|
||||
logger.info(
|
||||
"Loading DYNIN audio detokenizer from %s (local_files_only=%s)",
|
||||
model_path,
|
||||
local_files_only,
|
||||
)
|
||||
try:
|
||||
from transformers import AutoModel
|
||||
except Exception as e:
|
||||
raise RuntimeError(
|
||||
"transformers is required to load EMOVASpeechTokenizer remote code from Hugging Face."
|
||||
) from e
|
||||
|
||||
_ensure_transformers_tied_weights_compat()
|
||||
try:
|
||||
self._vq_audio = AutoModel.from_pretrained(
|
||||
model_path,
|
||||
trust_remote_code=True,
|
||||
local_files_only=local_files_only,
|
||||
low_cpu_mem_usage=False,
|
||||
)
|
||||
except TypeError:
|
||||
try:
|
||||
self._vq_audio = AutoModel.from_pretrained(
|
||||
model_path,
|
||||
trust_remote_code=True,
|
||||
local_files_only=local_files_only,
|
||||
)
|
||||
except TypeError:
|
||||
self._vq_audio = AutoModel.from_pretrained(
|
||||
model_path,
|
||||
trust_remote_code=True,
|
||||
)
|
||||
except Exception as e:
|
||||
raise RuntimeError(
|
||||
f"Failed to load EMOVASpeechTokenizer from Hugging Face remote code for model path '{model_path}'."
|
||||
) from e
|
||||
|
||||
if not hasattr(self._vq_audio, "decode"):
|
||||
raise RuntimeError(
|
||||
"Loaded audio tokenizer does not expose decode(). "
|
||||
"Check HF config.json auto_map/model_type and ensure trust_remote_code=True."
|
||||
)
|
||||
self._vq_audio.eval()
|
||||
self._vq_audio.requires_grad_(False)
|
||||
self._vq_audio_path = model_path
|
||||
self._vq_audio_local_files_only = local_files_only
|
||||
if hasattr(self._vq_audio, "to"):
|
||||
self._vq_audio = self._vq_audio.to(ref_device)
|
||||
return self._vq_audio
|
||||
|
||||
def embed_multimodal(self, **kwargs: Any) -> Any:
|
||||
del kwargs
|
||||
return None
|
||||
@@ -1,150 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
from vllm.sequence import IntermediateTensors
|
||||
|
||||
from vllm_omni.model_executor.models.output_templates import OmniOutput
|
||||
|
||||
from .dynin_omni import DyninOmniStageBase
|
||||
from .dynin_omni_common import (
|
||||
DetokTarget,
|
||||
_to_bool,
|
||||
coerce_token_ids_1d,
|
||||
get_dynin_magvit_attr,
|
||||
normalize_runtime_info,
|
||||
resolve_dynin_infer_sources,
|
||||
resolve_hidden_size,
|
||||
unwrap_first_value,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class DyninOmniToken2Image(DyninOmniStageBase):
|
||||
"""Stage-2: token detokenization to image (or pass-through)."""
|
||||
|
||||
stage_name = "Dynin token2image"
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
|
||||
del prefix
|
||||
super().__init__()
|
||||
|
||||
self.vllm_config = vllm_config
|
||||
self.have_multimodal_outputs = True
|
||||
self.requires_raw_input_tokens = True
|
||||
self.hidden_size = resolve_hidden_size(vllm_config=vllm_config)
|
||||
self._vq_model = None
|
||||
self._vq_model_path: str | None = None
|
||||
self._vq_local_files_only: bool | None = None
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor | None = None,
|
||||
positions: torch.Tensor | None = None,
|
||||
intermediate_tensors: IntermediateTensors | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
**kwargs: Any,
|
||||
) -> OmniOutput:
|
||||
del positions, intermediate_tensors, inputs_embeds
|
||||
if input_ids is None:
|
||||
raise ValueError("token2image stage requires input_ids")
|
||||
runtime_info = normalize_runtime_info(kwargs.get("runtime_additional_information"))
|
||||
detok_id = int(unwrap_first_value(runtime_info.get("detok_id"), 0))
|
||||
tokens = coerce_token_ids_1d(input_ids)
|
||||
|
||||
if detok_id != DetokTarget.IMAGE:
|
||||
return OmniOutput(
|
||||
text_hidden_states=None,
|
||||
multimodal_outputs={
|
||||
"token_ids": tokens,
|
||||
"detok_id": torch.tensor([detok_id], dtype=torch.long, device=tokens.device),
|
||||
},
|
||||
)
|
||||
|
||||
image = self._decode_image_tokens(tokens, runtime_info=runtime_info)
|
||||
return OmniOutput(
|
||||
text_hidden_states=None,
|
||||
multimodal_outputs={
|
||||
"image": image,
|
||||
"detok_id": torch.tensor([detok_id], dtype=torch.long, device=image.device),
|
||||
},
|
||||
)
|
||||
|
||||
def _decode_image_tokens(self, tokens: torch.Tensor, runtime_info: dict[str, Any]) -> torch.Tensor:
|
||||
# Follow DYNIN validation path:
|
||||
# tokens -> clamp -> vq_model.decode_code -> (x+1)/2 -> [0,1].
|
||||
vq_model = self._ensure_vq_model(runtime_info=runtime_info, ref_device=tokens.device)
|
||||
codebook_size = int(unwrap_first_value(runtime_info.get("codebook_size"), 8192))
|
||||
image_vocab_offset = unwrap_first_value(runtime_info.get("image_vocab_offset"), None)
|
||||
if image_vocab_offset is None:
|
||||
text_vocab_size = unwrap_first_value(runtime_info.get("text_vocab_size"), None)
|
||||
num_new_special_tokens = int(unwrap_first_value(runtime_info.get("num_new_special_tokens"), 0))
|
||||
if text_vocab_size is not None:
|
||||
image_vocab_offset = int(text_vocab_size) + num_new_special_tokens
|
||||
|
||||
token_ids = tokens.to(torch.long)
|
||||
if image_vocab_offset is not None:
|
||||
off = int(image_vocab_offset)
|
||||
token_ids = torch.where(token_ids >= off, token_ids - off, token_ids)
|
||||
token_ids = torch.clamp(token_ids, min=0, max=max(0, codebook_size - 1))
|
||||
token_ids = token_ids.unsqueeze(0)
|
||||
|
||||
decoded = vq_model.decode_code(token_ids)
|
||||
decoded = torch.clamp((decoded + 1.0) / 2.0, min=0.0, max=1.0)
|
||||
if decoded.ndim != 4 or decoded.shape[0] == 0:
|
||||
raise RuntimeError(f"Unexpected MAGVIT decode output shape: {tuple(decoded.shape)}")
|
||||
return decoded[0].contiguous()
|
||||
|
||||
def _ensure_vq_model(self, runtime_info: dict[str, Any], ref_device: torch.device) -> Any:
|
||||
sources = resolve_dynin_infer_sources(vllm_config=self.vllm_config, runtime_info=runtime_info)
|
||||
model_path = str(sources.vq_image_source)
|
||||
local_files_only = bool(sources.vq_image_local_files_only)
|
||||
if self._vq_model is None or self._vq_model_path != model_path or self._vq_local_files_only != local_files_only:
|
||||
disable_xet = unwrap_first_value(
|
||||
runtime_info.get("hf_hub_disable_xet"),
|
||||
unwrap_first_value(runtime_info.get("disable_hf_xet"), True),
|
||||
)
|
||||
if _to_bool(disable_xet, default=True):
|
||||
os.environ.setdefault("HF_HUB_DISABLE_XET", "1")
|
||||
logger.info(
|
||||
"Loading DYNIN image detokenizer from %s (local_files_only=%s)",
|
||||
model_path,
|
||||
local_files_only,
|
||||
)
|
||||
try:
|
||||
MAGVITv2 = get_dynin_magvit_attr(
|
||||
"MAGVITv2",
|
||||
source=model_path,
|
||||
local_files_only=local_files_only,
|
||||
)
|
||||
try:
|
||||
self._vq_model = MAGVITv2.from_pretrained(
|
||||
model_path,
|
||||
local_files_only=local_files_only,
|
||||
)
|
||||
except TypeError:
|
||||
self._vq_model = MAGVITv2.from_pretrained(model_path)
|
||||
except Exception as e:
|
||||
raise RuntimeError(
|
||||
"Failed to load MAGVITv2 from local DYNIN submodel implementation "
|
||||
f"for model path '{model_path}'. "
|
||||
"If your environment cannot access huggingface.co, set "
|
||||
"additional_information.vq_model_image_path to a local MAGVITv2 directory "
|
||||
"and set additional_information.vq_model_image_local_files_only=true."
|
||||
) from e
|
||||
self._vq_model.eval()
|
||||
self._vq_model.requires_grad_(False)
|
||||
self._vq_model_path = model_path
|
||||
self._vq_local_files_only = local_files_only
|
||||
if hasattr(self._vq_model, "to"):
|
||||
self._vq_model = self._vq_model.to(ref_device)
|
||||
return self._vq_model
|
||||
|
||||
def embed_multimodal(self, **kwargs: Any) -> Any:
|
||||
del kwargs
|
||||
return None
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,67 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Dynin-Omni pipeline topology (frozen).
|
||||
|
||||
Stage 0: token2text — multimodal understanding / text generation (comprehension)
|
||||
Stage 1: token2image — stage-0 tokens → image latents
|
||||
Stage 2: token2audio — stage-1 tokens → audio latents
|
||||
|
||||
All three stages run on the generation worker (``LLM_GENERATION``); the
|
||||
inter-stage hand-off uses the worker-connector full-payload data plane
|
||||
(``*_full_payload`` producers + ``token2text_to_token2image`` /
|
||||
``token2image_to_token2audio`` consumers). Deploy knobs (devices, GPU memory,
|
||||
batched tokens, connectors) live in ``vllm_omni/deploy/dynin_omni*.yaml``.
|
||||
"""
|
||||
|
||||
from vllm_omni.config.stage_config import (
|
||||
PipelineConfig,
|
||||
StageExecutionType,
|
||||
StagePipelineConfig,
|
||||
)
|
||||
|
||||
_PROC = "vllm_omni.model_executor.stage_input_processors.dynin_omni"
|
||||
|
||||
DYNIN_OMNI_PIPELINE = PipelineConfig(
|
||||
model_type="dynin_omni",
|
||||
default_deploy_config_name="dynin_omni.yaml",
|
||||
model_arch="DyninOmniForConditionalGeneration",
|
||||
# Arch-fallback safety net: route by hf_config.architectures when the
|
||||
# auto-detected model_type does not match the registry key exactly.
|
||||
hf_architectures=("DyninOmniForConditionalGeneration",),
|
||||
stages=(
|
||||
StagePipelineConfig(
|
||||
stage_id=0,
|
||||
model_stage="token2text",
|
||||
execution_type=StageExecutionType.LLM_GENERATION,
|
||||
input_sources=(),
|
||||
final_output=True,
|
||||
final_output_type="text",
|
||||
owns_tokenizer=True,
|
||||
engine_output_type="latent",
|
||||
custom_process_next_stage_input_func=f"{_PROC}.token2text_to_token2image_full_payload",
|
||||
),
|
||||
StagePipelineConfig(
|
||||
stage_id=1,
|
||||
model_stage="token2image",
|
||||
execution_type=StageExecutionType.LLM_GENERATION,
|
||||
input_sources=(0,),
|
||||
final_output=True,
|
||||
final_output_type="image",
|
||||
engine_output_type="latent",
|
||||
custom_process_input_func=f"{_PROC}.token2text_to_token2image",
|
||||
custom_process_next_stage_input_func=f"{_PROC}.token2image_to_token2audio_full_payload",
|
||||
requires_full_payload_input=True,
|
||||
),
|
||||
StagePipelineConfig(
|
||||
stage_id=2,
|
||||
model_stage="token2audio",
|
||||
execution_type=StageExecutionType.LLM_GENERATION,
|
||||
input_sources=(1,),
|
||||
final_output=True,
|
||||
final_output_type="audio",
|
||||
engine_output_type="latent",
|
||||
custom_process_input_func=f"{_PROC}.token2image_to_token2audio",
|
||||
requires_full_payload_input=True,
|
||||
),
|
||||
),
|
||||
)
|
||||
@@ -171,10 +171,9 @@ class Qwen3OmniMoeForConditionalGeneration(
|
||||
# such as the vLLM-text perf benchmark.
|
||||
#
|
||||
# Default to the thinker: it is the text-generation stage, which is what
|
||||
# a non-staged run of this model is asking for. Same shape as
|
||||
# dynin_omni ("token2text") and glm_tts ("glm_tts"). An explicitly wrong
|
||||
# value still reaches the ValueError below rather than being silently
|
||||
# accepted.
|
||||
# a non-staged run of this model is asking for. Same shape as glm_tts
|
||||
# ("glm_tts"). An explicitly wrong value still reaches the ValueError
|
||||
# below rather than being silently accepted.
|
||||
self.model_stage = getattr(vllm_config.model_config, "model_stage", None) or "thinker"
|
||||
# Staged startup always injects model_stage; its absence means a plain
|
||||
# vLLM run with no talker stage downstream, so no one consumes captured
|
||||
|
||||
@@ -321,12 +321,6 @@ _OMNI_MODELS = {
|
||||
"voxcpm2_talker",
|
||||
"VoxCPM2TalkerForConditionalGeneration",
|
||||
),
|
||||
## dots.tts
|
||||
"DotsTTSForConditionalGeneration": (
|
||||
"dots_tts",
|
||||
"dots_tts_talker",
|
||||
"DotsTTSForConditionalGeneration",
|
||||
),
|
||||
## Voxtral TTS
|
||||
"VoxtralTTSForConditionalGeneration": (
|
||||
"voxtral_tts",
|
||||
@@ -396,11 +390,6 @@ _OMNI_MODELS = {
|
||||
"modeling_moss_tts_codec",
|
||||
"MossTTSCodecDecoder",
|
||||
),
|
||||
"DyninOmniForConditionalGeneration": (
|
||||
"dynin_omni",
|
||||
"dynin_omni",
|
||||
"DyninOmniForConditionalGeneration",
|
||||
),
|
||||
## IndexTTS2
|
||||
"IndexTTS2TalkerForConditionalGeneration": (
|
||||
"indextts2",
|
||||
|
||||
Reference in new issue
Block a user