duplexjev-vllm 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- duplexjev_vllm/__init__.py +24 -0
- duplexjev_vllm/configuration_qwen3_asr_encoder.py +51 -0
- duplexjev_vllm/model.py +63 -0
- duplexjev_vllm/modeling_qwen3_asr_encoder.py +294 -0
- duplexjev_vllm/processing.py +98 -0
- duplexjev_vllm-0.1.0.dist-info/METADATA +34 -0
- duplexjev_vllm-0.1.0.dist-info/RECORD +10 -0
- duplexjev_vllm-0.1.0.dist-info/WHEEL +5 -0
- duplexjev_vllm-0.1.0.dist-info/entry_points.txt +2 -0
- duplexjev_vllm-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""vLLM plugin for DuplexJev speech-decision models (https://github.com/adventists-ai/duplexjev).
|
|
2
|
+
|
|
3
|
+
Registered as a `vllm.general_plugins` entry point: `pip install duplexjev-vllm`, then
|
|
4
|
+
`vllm serve adventists-ai/DuplexJev-4B`.
|
|
5
|
+
"""
|
|
6
|
+
__version__ = "0.1.0"
|
|
7
|
+
|
|
8
|
+
ARCH = "DuplexJevForConditionalGeneration"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def register():
|
|
12
|
+
from transformers import AutoConfig
|
|
13
|
+
|
|
14
|
+
from .configuration_qwen3_asr_encoder import Qwen3ASREncoderConfig
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
AutoConfig.register(Qwen3ASREncoderConfig.model_type, Qwen3ASREncoderConfig)
|
|
18
|
+
except ValueError:
|
|
19
|
+
pass # already registered in this process
|
|
20
|
+
|
|
21
|
+
from vllm import ModelRegistry
|
|
22
|
+
|
|
23
|
+
if ARCH not in ModelRegistry.get_supported_archs():
|
|
24
|
+
ModelRegistry.register_model(ARCH, "duplexjev_vllm.model:DuplexJevForConditionalGeneration")
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
from transformers import PretrainedConfig
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class Qwen3ASREncoderConfig(PretrainedConfig):
|
|
5
|
+
model_type = "qwen3_asr_encoder_portable"
|
|
6
|
+
|
|
7
|
+
def __init__(
|
|
8
|
+
self,
|
|
9
|
+
d_model=896,
|
|
10
|
+
downsample_hidden_size=480,
|
|
11
|
+
encoder_attention_heads=14,
|
|
12
|
+
encoder_ffn_dim=3584,
|
|
13
|
+
encoder_layers=18,
|
|
14
|
+
num_mel_bins=128,
|
|
15
|
+
n_window=50,
|
|
16
|
+
n_window_infer=800,
|
|
17
|
+
max_position_embeddings=13,
|
|
18
|
+
activation_function="gelu",
|
|
19
|
+
activation_dropout=0.0,
|
|
20
|
+
attention_dropout=0.0,
|
|
21
|
+
dropout=0.0,
|
|
22
|
+
scale_embedding=False,
|
|
23
|
+
initializer_range=0.02,
|
|
24
|
+
**kwargs,
|
|
25
|
+
):
|
|
26
|
+
self.d_model = d_model
|
|
27
|
+
self.downsample_hidden_size = downsample_hidden_size
|
|
28
|
+
self.encoder_attention_heads = encoder_attention_heads
|
|
29
|
+
self.encoder_ffn_dim = encoder_ffn_dim
|
|
30
|
+
self.encoder_layers = encoder_layers
|
|
31
|
+
self.num_mel_bins = num_mel_bins
|
|
32
|
+
self.n_window = n_window
|
|
33
|
+
self.n_window_infer = n_window_infer
|
|
34
|
+
self.max_position_embeddings = max_position_embeddings
|
|
35
|
+
self.activation_function = activation_function
|
|
36
|
+
self.activation_dropout = activation_dropout
|
|
37
|
+
self.attention_dropout = attention_dropout
|
|
38
|
+
self.dropout = dropout
|
|
39
|
+
self.scale_embedding = scale_embedding
|
|
40
|
+
self.initializer_range = initializer_range
|
|
41
|
+
super().__init__(**kwargs)
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def hidden_size(self):
|
|
45
|
+
return self.d_model
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def encoder_ds_factor(self):
|
|
49
|
+
# Three stride-2 convs in the frontend -> 2*2*2 = 8x downsampling from
|
|
50
|
+
# mel frames to encoder output frames (vs. Whisper's single 2x conv).
|
|
51
|
+
return 8
|
duplexjev_vllm/model.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""vLLM model for DuplexJev checkpoints: Qwen3-ASR audio encoder + Ultravox-style projector + a vLLM text model.
|
|
2
|
+
|
|
3
|
+
Everything except the audio tower and the preprocessing is vLLM's own Ultravox implementation.
|
|
4
|
+
"""
|
|
5
|
+
from functools import lru_cache
|
|
6
|
+
|
|
7
|
+
from transformers import AutoTokenizer, WhisperFeatureExtractor
|
|
8
|
+
|
|
9
|
+
import vllm.model_executor.models.ultravox as U
|
|
10
|
+
from vllm.multimodal import MULTIMODAL_REGISTRY
|
|
11
|
+
|
|
12
|
+
import torch
|
|
13
|
+
import torch.nn.functional as F
|
|
14
|
+
|
|
15
|
+
from .modeling_qwen3_asr_encoder import Qwen3ASREncoder, _get_feat_extract_output_lengths
|
|
16
|
+
from .processing import DuplexJevProcessor
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class DuplexJevAudioTower(Qwen3ASREncoder):
|
|
20
|
+
"""Qwen3-ASR encoder with the (features, lens) -> hidden_states call used by vLLM's Ultravox."""
|
|
21
|
+
|
|
22
|
+
def forward(self, input_features, audio_lens=None):
|
|
23
|
+
h = super().forward(input_features, audio_len=audio_lens).last_hidden_state
|
|
24
|
+
# The encoder pads its output to the longest valid clip in the call; vLLM concatenates several calls, so
|
|
25
|
+
# pad every call to the length implied by the (shared) padded mel length instead.
|
|
26
|
+
n = int(_get_feat_extract_output_lengths(torch.tensor(input_features.shape[-1]), self.n_window))
|
|
27
|
+
if h.shape[1] < n:
|
|
28
|
+
h = F.pad(h, (0, 0, 0, n - h.shape[1]))
|
|
29
|
+
return h[:, :n]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _make_tower(*, vllm_config, prefix: str = "", enable_pp: bool = False):
|
|
33
|
+
return DuplexJevAudioTower(vllm_config.model_config.hf_config)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@lru_cache(maxsize=8)
|
|
37
|
+
def _processor(model: str, revision, trust_remote_code: bool, stack_factor: int, ds: int):
|
|
38
|
+
fe = WhisperFeatureExtractor.from_pretrained(model, revision=revision)
|
|
39
|
+
tok = AutoTokenizer.from_pretrained(model, revision=revision, trust_remote_code=trust_remote_code)
|
|
40
|
+
return DuplexJevProcessor(fe, tok, stack_factor=stack_factor, encoder_ds_factor=ds)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class DuplexJevProcessingInfo(U.UltravoxProcessingInfo):
|
|
44
|
+
def get_hf_processor(self, **kwargs):
|
|
45
|
+
mc = self.ctx.model_config
|
|
46
|
+
cfg = mc.hf_config
|
|
47
|
+
p = _processor(mc.model, mc.revision, mc.trust_remote_code,
|
|
48
|
+
cfg.stack_factor, int(getattr(cfg.audio_config, "encoder_ds_factor", 8)))
|
|
49
|
+
p.audio_token_replacement = U._AUDIO_PLACEHOLDER_OVERRIDE
|
|
50
|
+
p.audio_replacement_token_id = cfg.audio_token_index
|
|
51
|
+
return p
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@MULTIMODAL_REGISTRY.register_processor(U.UltravoxMultiModalProcessor, info=DuplexJevProcessingInfo,
|
|
55
|
+
dummy_inputs=U.UltravoxDummyInputsBuilder)
|
|
56
|
+
class DuplexJevForConditionalGeneration(U.UltravoxModel):
|
|
57
|
+
def __init__(self, *, vllm_config, prefix: str = ""):
|
|
58
|
+
orig = U.UltravoxWhisperEncoder
|
|
59
|
+
U.UltravoxWhisperEncoder = _make_tower
|
|
60
|
+
try:
|
|
61
|
+
super().__init__(vllm_config=vllm_config, prefix=prefix)
|
|
62
|
+
finally:
|
|
63
|
+
U.UltravoxWhisperEncoder = orig
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Portable, standalone reimplementation of the Qwen3-ASR audio encoder
|
|
3
|
+
(transformers.models.qwen3_asr.modeling_qwen3_asr.Qwen3ASREncoder), rewritten to avoid
|
|
4
|
+
any transformers-5.x-only internal utilities (ALL_ATTENTION_FUNCTIONS, capture_outputs,
|
|
5
|
+
torch_compilable_check, GradientCheckpointingLayer, etc.) so it loads cleanly via
|
|
6
|
+
trust_remote_code on older transformers installs (verified against 4.51.3).
|
|
7
|
+
|
|
8
|
+
Forward-pass math is unchanged from the original: same conv frontend, same windowed
|
|
9
|
+
(non-causal, block-local) attention via cu_seqlens chunk splitting, same sinusoidal
|
|
10
|
+
position embedding. Only the plumbing around attention-backend selection and
|
|
11
|
+
gradient-checkpointing wrappers was stripped out (this encoder is used frozen /
|
|
12
|
+
fine-tuned without gradient checkpointing here).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import math
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
import torch
|
|
19
|
+
import torch.nn.functional as F
|
|
20
|
+
from torch import nn
|
|
21
|
+
from transformers import PreTrainedModel
|
|
22
|
+
from transformers.activations import ACT2FN
|
|
23
|
+
from transformers.modeling_outputs import BaseModelOutputWithPooling
|
|
24
|
+
|
|
25
|
+
from .configuration_qwen3_asr_encoder import Qwen3ASREncoderConfig
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _get_feat_extract_output_lengths(input_lengths, n_window=50):
|
|
29
|
+
chunk_len = n_window * 2
|
|
30
|
+
input_lengths_leave = input_lengths % chunk_len
|
|
31
|
+
feat_lengths = (input_lengths_leave - 1) // 2 + 1
|
|
32
|
+
return ((feat_lengths - 1) // 2 + 1 - 1) // 2 + 1 + (input_lengths // chunk_len) * 13
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def get_audio_cu_seqlens(chunk_lengths, feature_lens, n_window_infer, n_window):
|
|
36
|
+
aftercnn_lens = _get_feat_extract_output_lengths(feature_lens, n_window)
|
|
37
|
+
feature_lens_after_cnn = _get_feat_extract_output_lengths(chunk_lengths, n_window)
|
|
38
|
+
max_len_after_cnn = feature_lens_after_cnn.max().item()
|
|
39
|
+
|
|
40
|
+
n_window_ratio = n_window_infer // (n_window * 2)
|
|
41
|
+
window_aftercnn = max_len_after_cnn * n_window_ratio
|
|
42
|
+
|
|
43
|
+
cu_chunk_lens = [0]
|
|
44
|
+
for cnn_len in aftercnn_lens:
|
|
45
|
+
cnn_len = int(cnn_len)
|
|
46
|
+
cu_chunk_lens += [window_aftercnn] * (cnn_len // window_aftercnn)
|
|
47
|
+
remainder = cnn_len % window_aftercnn
|
|
48
|
+
if remainder != 0:
|
|
49
|
+
cu_chunk_lens += [remainder]
|
|
50
|
+
|
|
51
|
+
return torch.tensor(cu_chunk_lens, device=feature_lens.device).cumsum(-1, dtype=torch.int32)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class SinusoidsPositionEmbedding(nn.Module):
|
|
55
|
+
def __init__(self, length, channels, max_timescale=10000):
|
|
56
|
+
super().__init__()
|
|
57
|
+
self.length = length
|
|
58
|
+
self.channels = channels
|
|
59
|
+
self.max_timescale = max_timescale
|
|
60
|
+
if channels % 2 != 0:
|
|
61
|
+
raise ValueError("SinusoidsPositionEmbedding needs even channels input")
|
|
62
|
+
position_embedding = self.compute_default_singular_positional_embedding()
|
|
63
|
+
self.register_buffer("positional_embedding", position_embedding, persistent=False)
|
|
64
|
+
|
|
65
|
+
def compute_default_singular_positional_embedding(self):
|
|
66
|
+
log_timescale_increment = np.log(self.max_timescale) / (self.channels // 2 - 1)
|
|
67
|
+
inv_timescales = torch.exp(-log_timescale_increment * torch.arange(self.channels // 2).float())
|
|
68
|
+
scaled_time = torch.arange(self.length)[:, np.newaxis] * inv_timescales[np.newaxis, :]
|
|
69
|
+
return torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim=1)
|
|
70
|
+
|
|
71
|
+
def forward(self, seqlen: int):
|
|
72
|
+
return self.positional_embedding[:seqlen, :]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class Qwen3ASRAudioAttention(nn.Module):
|
|
76
|
+
"""Multi-headed attention, block-local (non-causal within each cu_seqlens chunk)."""
|
|
77
|
+
|
|
78
|
+
def __init__(self, config: Qwen3ASREncoderConfig, *args, **kwargs):
|
|
79
|
+
super().__init__()
|
|
80
|
+
self.embed_dim = config.d_model
|
|
81
|
+
self.num_heads = config.encoder_attention_heads
|
|
82
|
+
self.head_dim = self.embed_dim // self.num_heads
|
|
83
|
+
if (self.head_dim * self.num_heads) != self.embed_dim:
|
|
84
|
+
raise ValueError("embed_dim must be divisible by num_heads")
|
|
85
|
+
self.scaling = self.head_dim**-0.5
|
|
86
|
+
self.attention_dropout = config.attention_dropout
|
|
87
|
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=True)
|
|
88
|
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=True)
|
|
89
|
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=True)
|
|
90
|
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=True)
|
|
91
|
+
|
|
92
|
+
def forward(self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor) -> torch.Tensor:
|
|
93
|
+
"""hidden_states: (seq_length, embed_dim) -- a single packed sequence."""
|
|
94
|
+
seq_length, _ = hidden_states.size()
|
|
95
|
+
|
|
96
|
+
query_states = self.q_proj(hidden_states).reshape(seq_length, self.num_heads, -1)
|
|
97
|
+
key_states = self.k_proj(hidden_states).reshape(seq_length, self.num_heads, -1)
|
|
98
|
+
value_states = self.v_proj(hidden_states).reshape(seq_length, self.num_heads, -1)
|
|
99
|
+
|
|
100
|
+
# (seq, heads, head_dim) -> (1, heads, seq, head_dim)
|
|
101
|
+
query_states = query_states.transpose(0, 1).unsqueeze(0)
|
|
102
|
+
key_states = key_states.transpose(0, 1).unsqueeze(0)
|
|
103
|
+
value_states = value_states.transpose(0, 1).unsqueeze(0)
|
|
104
|
+
|
|
105
|
+
lengths = (cu_seqlens[1:] - cu_seqlens[:-1]).tolist()
|
|
106
|
+
q_chunks = torch.split(query_states, lengths, dim=2)
|
|
107
|
+
k_chunks = torch.split(key_states, lengths, dim=2)
|
|
108
|
+
v_chunks = torch.split(value_states, lengths, dim=2)
|
|
109
|
+
|
|
110
|
+
attn_outputs = []
|
|
111
|
+
for q, k, v in zip(q_chunks, k_chunks, v_chunks):
|
|
112
|
+
out = F.scaled_dot_product_attention(
|
|
113
|
+
q, k, v,
|
|
114
|
+
attn_mask=None,
|
|
115
|
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
|
116
|
+
scale=self.scaling,
|
|
117
|
+
is_causal=False,
|
|
118
|
+
)
|
|
119
|
+
attn_outputs.append(out)
|
|
120
|
+
attn_output = torch.cat(attn_outputs, dim=2)
|
|
121
|
+
|
|
122
|
+
attn_output = attn_output.transpose(1, 2).reshape(seq_length, -1).contiguous()
|
|
123
|
+
attn_output = self.out_proj(attn_output)
|
|
124
|
+
return attn_output
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class Qwen3ASRAudioEncoderLayer(nn.Module):
|
|
128
|
+
def __init__(self, config: Qwen3ASREncoderConfig, *args, **kwargs):
|
|
129
|
+
super().__init__()
|
|
130
|
+
self.embed_dim = config.d_model
|
|
131
|
+
self.self_attn = Qwen3ASRAudioAttention(config)
|
|
132
|
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
|
133
|
+
self.activation_fn = ACT2FN[config.activation_function]
|
|
134
|
+
self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
|
|
135
|
+
self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
|
|
136
|
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
|
137
|
+
|
|
138
|
+
def forward(self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor) -> torch.Tensor:
|
|
139
|
+
residual = hidden_states
|
|
140
|
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
|
141
|
+
hidden_states = self.self_attn(hidden_states=hidden_states, cu_seqlens=cu_seqlens)
|
|
142
|
+
hidden_states = residual + hidden_states
|
|
143
|
+
|
|
144
|
+
residual = hidden_states
|
|
145
|
+
hidden_states = self.final_layer_norm(hidden_states)
|
|
146
|
+
hidden_states = self.fc1(hidden_states)
|
|
147
|
+
hidden_states = self.activation_fn(hidden_states)
|
|
148
|
+
hidden_states = self.fc2(hidden_states)
|
|
149
|
+
hidden_states = residual + hidden_states
|
|
150
|
+
|
|
151
|
+
if hidden_states.dtype == torch.float16:
|
|
152
|
+
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
|
|
153
|
+
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
|
154
|
+
return hidden_states
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class Qwen3ASREncoder(PreTrainedModel):
|
|
158
|
+
config_class = Qwen3ASREncoderConfig
|
|
159
|
+
base_model_prefix = "qwen3_asr_encoder"
|
|
160
|
+
main_input_name = "input_features"
|
|
161
|
+
_no_split_modules = ["Qwen3ASRAudioEncoderLayer"]
|
|
162
|
+
|
|
163
|
+
def __init__(self, config: Qwen3ASREncoderConfig, *args, **kwargs):
|
|
164
|
+
super().__init__(config)
|
|
165
|
+
embed_dim = config.d_model
|
|
166
|
+
self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
|
|
167
|
+
self.n_window = config.n_window
|
|
168
|
+
self.n_window_infer = config.n_window_infer
|
|
169
|
+
self.positional_embedding = SinusoidsPositionEmbedding(config.max_position_embeddings, embed_dim)
|
|
170
|
+
self.layers = nn.ModuleList([Qwen3ASRAudioEncoderLayer(config) for _ in range(config.encoder_layers)])
|
|
171
|
+
self.ln_post = nn.LayerNorm(config.d_model)
|
|
172
|
+
self.conv2d1 = nn.Conv2d(1, config.downsample_hidden_size, 3, 2, padding=1)
|
|
173
|
+
self.conv2d2 = nn.Conv2d(config.downsample_hidden_size, config.downsample_hidden_size, 3, 2, padding=1)
|
|
174
|
+
self.conv2d3 = nn.Conv2d(config.downsample_hidden_size, config.downsample_hidden_size, 3, 2, padding=1)
|
|
175
|
+
self.conv_out = nn.Linear(
|
|
176
|
+
config.downsample_hidden_size * ((((config.num_mel_bins + 1) // 2 + 1) // 2 + 1) // 2),
|
|
177
|
+
config.d_model,
|
|
178
|
+
bias=False,
|
|
179
|
+
)
|
|
180
|
+
self.post_init()
|
|
181
|
+
|
|
182
|
+
@property
|
|
183
|
+
def max_context_length(self) -> int:
|
|
184
|
+
# Matches the WhisperFeatureExtractor-compatible preprocessor_config.json
|
|
185
|
+
# (chunk_length=30s -> nb_max_frames=3000) used alongside this encoder.
|
|
186
|
+
return 3000
|
|
187
|
+
|
|
188
|
+
@staticmethod
|
|
189
|
+
def _post_cnn_length(lengths: torch.Tensor) -> torch.Tensor:
|
|
190
|
+
for _ in range(3):
|
|
191
|
+
lengths = torch.where(lengths > 0, (lengths - 1) // 2 + 1, torch.zeros_like(lengths))
|
|
192
|
+
return lengths
|
|
193
|
+
|
|
194
|
+
def forward(self, input_features: torch.Tensor, input_features_mask: torch.Tensor = None, attention_mask: torch.Tensor = None, audio_len: torch.Tensor = None, **kwargs):
|
|
195
|
+
if input_features_mask is None:
|
|
196
|
+
input_features_mask = attention_mask
|
|
197
|
+
if input_features_mask is None and audio_len is not None:
|
|
198
|
+
# Ultravox's real call site (UltravoxModel.forward -> audio_tower.forward)
|
|
199
|
+
# passes audio_len: a per-sample valid length in mel-FRAME units (matching
|
|
200
|
+
# UltravoxProcessor's audio_lens output), not a full mask and not a raw
|
|
201
|
+
# waveform-sample count. This mirrors ModifiedWhisperEncoder's own
|
|
202
|
+
# audio_len handling so this encoder is a drop-in replacement.
|
|
203
|
+
max_seq_len = input_features.shape[-1]
|
|
204
|
+
positions = torch.arange(max_seq_len, device=input_features.device)[None, :]
|
|
205
|
+
input_features_mask = positions.lt(audio_len.to(input_features.device).view(-1, 1)).to(torch.int32)
|
|
206
|
+
if input_features_mask is None:
|
|
207
|
+
input_features_mask = torch.ones(input_features.shape[0], input_features.shape[-1], dtype=torch.int32, device=input_features.device)
|
|
208
|
+
batch_size = input_features.shape[0]
|
|
209
|
+
if batch_size > 1:
|
|
210
|
+
# The chunked local-attention grouping (get_audio_cu_seqlens) and the
|
|
211
|
+
# conv2d batch-folding below are numerically batch-shape-sensitive: with
|
|
212
|
+
# true multi-sample batching, different per-sample padding amounts change
|
|
213
|
+
# how chunks/attention blocks are grouped and measurably leak between
|
|
214
|
+
# samples (verified empirically: batched vs per-sample outputs diverged
|
|
215
|
+
# by up to ~4 on a LayerNorm-scaled hidden state, far beyond bf16 noise).
|
|
216
|
+
# Looping per-sample reuses the single-sample path unchanged, which is
|
|
217
|
+
# the one verified to match a standalone (batch_size=1) call exactly.
|
|
218
|
+
outs = []
|
|
219
|
+
for i in range(batch_size):
|
|
220
|
+
len_i = int(input_features_mask[i].sum().item())
|
|
221
|
+
feat_i = input_features[i : i + 1, :, :len_i]
|
|
222
|
+
mask_i = input_features_mask[i : i + 1, :len_i]
|
|
223
|
+
out_i = self._forward_single(feat_i, mask_i).last_hidden_state[0]
|
|
224
|
+
outs.append(out_i)
|
|
225
|
+
max_len = max(o.shape[0] for o in outs)
|
|
226
|
+
out = input_features.new_zeros(batch_size, max_len, outs[0].shape[-1])
|
|
227
|
+
for i, o in enumerate(outs):
|
|
228
|
+
out[i, : o.shape[0]] = o
|
|
229
|
+
return BaseModelOutputWithPooling(last_hidden_state=out)
|
|
230
|
+
return self._forward_single(input_features, input_features_mask)
|
|
231
|
+
|
|
232
|
+
def _forward_single(self, input_features: torch.Tensor, input_features_mask: torch.Tensor):
|
|
233
|
+
batch_size, num_mel_bins, padded_feature_length = input_features.shape
|
|
234
|
+
chunk_len = self.n_window * 2
|
|
235
|
+
|
|
236
|
+
if padded_feature_length % chunk_len != 0:
|
|
237
|
+
# Callers (e.g. a generic batch collator) may not know about this
|
|
238
|
+
# encoder's chunk-alignment requirement. Pad defensively to the next
|
|
239
|
+
# chunk boundary instead of erroring out; the extra frames are marked
|
|
240
|
+
# invalid via input_features_mask and dropped before the transformer
|
|
241
|
+
# layers, so they do not affect the output.
|
|
242
|
+
pad_amount = chunk_len - (padded_feature_length % chunk_len)
|
|
243
|
+
input_features = torch.nn.functional.pad(input_features, (0, pad_amount))
|
|
244
|
+
input_features_mask = torch.nn.functional.pad(input_features_mask, (0, pad_amount))
|
|
245
|
+
padded_feature_length = input_features.shape[-1]
|
|
246
|
+
|
|
247
|
+
num_chunks = padded_feature_length // chunk_len
|
|
248
|
+
feature_lens = input_features_mask.sum(-1).to(torch.long)
|
|
249
|
+
chunk_lengths = (
|
|
250
|
+
input_features_mask.view(batch_size, num_chunks, chunk_len).sum(dim=-1).reshape(-1).to(torch.long)
|
|
251
|
+
)
|
|
252
|
+
cu_seqlens = get_audio_cu_seqlens(chunk_lengths, feature_lens, self.n_window_infer, self.n_window)
|
|
253
|
+
|
|
254
|
+
chunked = (
|
|
255
|
+
input_features.view(batch_size, num_mel_bins, num_chunks, chunk_len)
|
|
256
|
+
.permute(0, 2, 1, 3)
|
|
257
|
+
.reshape(batch_size * num_chunks, 1, num_mel_bins, chunk_len)
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
conv_out = F.gelu(self.conv2d1(chunked))
|
|
261
|
+
conv_out = F.gelu(self.conv2d2(conv_out))
|
|
262
|
+
conv_out = F.gelu(self.conv2d3(conv_out))
|
|
263
|
+
total_chunks, conv_channels, freq_bins, time_steps = conv_out.size()
|
|
264
|
+
conv_out = self.conv_out(
|
|
265
|
+
conv_out.permute(0, 3, 1, 2).contiguous().view(total_chunks, time_steps, conv_channels * freq_bins)
|
|
266
|
+
)
|
|
267
|
+
conv_out = conv_out + self.positional_embedding.positional_embedding[:time_steps].to(conv_out.dtype)
|
|
268
|
+
|
|
269
|
+
chunk_post_cnn_lens = self._post_cnn_length(
|
|
270
|
+
input_features_mask.view(batch_size, num_chunks, chunk_len).sum(dim=-1).reshape(-1).to(torch.long)
|
|
271
|
+
)
|
|
272
|
+
valid_mask = torch.arange(time_steps, device=input_features.device) < chunk_post_cnn_lens.unsqueeze(1)
|
|
273
|
+
valid_indices = valid_mask.flatten().nonzero().squeeze(-1)
|
|
274
|
+
hidden_states = torch.index_select(conv_out.reshape(-1, conv_out.shape[-1]), 0, valid_indices)
|
|
275
|
+
|
|
276
|
+
for encoder_layer in self.layers:
|
|
277
|
+
hidden_states = encoder_layer(hidden_states, cu_seqlens)
|
|
278
|
+
|
|
279
|
+
hidden_states = self.ln_post(hidden_states)
|
|
280
|
+
|
|
281
|
+
# hidden_states is a packed (total_valid_frames, C) sequence (no batch dim).
|
|
282
|
+
# Downstream code (UltravoxProjector etc.) expects a standard padded batch
|
|
283
|
+
# tensor (B, T, C), matching what a Whisper-style encoder would return.
|
|
284
|
+
# Unpack using each sample's own post-CNN frame count.
|
|
285
|
+
per_sample_len = _get_feat_extract_output_lengths(feature_lens, self.n_window)
|
|
286
|
+
max_len = int(per_sample_len.max().item()) if batch_size > 0 else 0
|
|
287
|
+
out = hidden_states.new_zeros(batch_size, max_len, hidden_states.shape[-1])
|
|
288
|
+
offset = 0
|
|
289
|
+
for i in range(batch_size):
|
|
290
|
+
n = int(per_sample_len[i].item())
|
|
291
|
+
out[i, :n] = hidden_states[offset : offset + n]
|
|
292
|
+
offset += n
|
|
293
|
+
|
|
294
|
+
return BaseModelOutputWithPooling(last_hidden_state=out)
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Audio + text preprocessing for DuplexJev checkpoints inside vLLM.
|
|
2
|
+
|
|
3
|
+
Same maths as the Ultravox processor the connectors were trained with (Whisper-style 128-bin log-mel, 30 s chunks,
|
|
4
|
+
audio_token_len = ceil(mel_frames / (encoder_ds_factor * stack_factor))), plus the right-padding the duplexjev
|
|
5
|
+
package applies: every clip is padded with silence to a whole number of audio tokens, so a clip reads the same
|
|
6
|
+
whatever it is batched with.
|
|
7
|
+
"""
|
|
8
|
+
from typing import List, Optional
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
import torch
|
|
12
|
+
import torch.nn.functional as F
|
|
13
|
+
import transformers
|
|
14
|
+
|
|
15
|
+
HOP = 160
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class DuplexJevProcessor:
|
|
19
|
+
def __init__(self, feature_extractor, tokenizer, *, stack_factor: int = 2, encoder_ds_factor: int = 8,
|
|
20
|
+
audio_context_size: int = 3000, audio_placeholder: str = "<|audio|>"):
|
|
21
|
+
self.audio_processor = feature_extractor # vLLM reads the WhisperFeatureExtractor from here
|
|
22
|
+
self.tokenizer = tokenizer
|
|
23
|
+
self.stack_factor = stack_factor
|
|
24
|
+
self.encoder_ds_factor = encoder_ds_factor
|
|
25
|
+
self.audio_context_size = audio_context_size
|
|
26
|
+
self.audio_placeholder = audio_placeholder
|
|
27
|
+
self.vocab = tokenizer.get_vocab()
|
|
28
|
+
self.audio_token_replacement = tokenizer.eos_token # vLLM overrides this and audio_replacement_token_id
|
|
29
|
+
self.audio_replacement_token_id = None
|
|
30
|
+
|
|
31
|
+
def _align(self, a: np.ndarray) -> np.ndarray:
|
|
32
|
+
step = HOP * self.encoder_ds_factor * self.stack_factor
|
|
33
|
+
n = max(len(a), 2 * HOP)
|
|
34
|
+
n = -(-n // step) * step
|
|
35
|
+
return np.pad(a, (0, n - len(a))) if n > len(a) else a
|
|
36
|
+
|
|
37
|
+
def _chunk(self, values: torch.Tensor, lens: torch.Tensor, include_audio_num_chunks: bool) -> dict:
|
|
38
|
+
ctx = self.audio_context_size or values.shape[-1]
|
|
39
|
+
chunks: List[torch.Tensor] = []
|
|
40
|
+
clens: List[int] = []
|
|
41
|
+
cont: List[bool] = []
|
|
42
|
+
nch: List[int] = []
|
|
43
|
+
for i in range(values.shape[0]):
|
|
44
|
+
L = int(lens[i])
|
|
45
|
+
nch.append(int(np.ceil(L / ctx)))
|
|
46
|
+
for off in range(0, L, ctx):
|
|
47
|
+
c = values[i, :, off:off + ctx]
|
|
48
|
+
if off > 0 and c.shape[-1] < ctx:
|
|
49
|
+
c = F.pad(c, (0, ctx - c.shape[-1]))
|
|
50
|
+
chunks.append(c)
|
|
51
|
+
clens.append(min(L - off, ctx))
|
|
52
|
+
cont.append(off > 0)
|
|
53
|
+
d = {"audio_values": torch.stack(chunks, 0), "audio_lens": torch.tensor(clens, dtype=torch.int64),
|
|
54
|
+
"audio_is_continuation": torch.tensor(cont, dtype=torch.bool),
|
|
55
|
+
"audio_batch_size": torch.tensor([len(chunks)])}
|
|
56
|
+
if include_audio_num_chunks:
|
|
57
|
+
d["audio_num_chunks"] = torch.tensor(nch, dtype=torch.int64)
|
|
58
|
+
return d
|
|
59
|
+
|
|
60
|
+
def __call__(self, text: Optional[str] = None, audio=None, audios=None, sampling_rate: Optional[int] = None,
|
|
61
|
+
return_tensors="pt", include_audio_num_chunks: bool = False, **kwargs) -> transformers.BatchFeature:
|
|
62
|
+
if audio is not None:
|
|
63
|
+
audios = audio if isinstance(audio, list) else [audio]
|
|
64
|
+
audios = [a.numpy() if isinstance(a, torch.Tensor) else np.asarray(a) for a in (audios or [])]
|
|
65
|
+
data, is_cont = {}, []
|
|
66
|
+
if audios:
|
|
67
|
+
audios = [self._align(a.astype(np.float32)) for a in audios]
|
|
68
|
+
x = self.audio_processor(audios, sampling_rate=sampling_rate or self.audio_processor.sampling_rate,
|
|
69
|
+
padding="longest", pad_to_multiple_of=HOP, truncation=False,
|
|
70
|
+
return_attention_mask=True, return_tensors="pt")
|
|
71
|
+
data.update(self._chunk(torch.as_tensor(x.input_features), torch.as_tensor(x.attention_mask).sum(-1),
|
|
72
|
+
include_audio_num_chunks))
|
|
73
|
+
is_cont = data.pop("audio_is_continuation")
|
|
74
|
+
data["audio_token_len"] = torch.ceil(
|
|
75
|
+
data["audio_lens"] / (self.encoder_ds_factor * self.stack_factor)).to(torch.int)
|
|
76
|
+
if text is not None:
|
|
77
|
+
parts = self.tokenizer(text.split(self.audio_placeholder), add_special_tokens=False)["input_ids"]
|
|
78
|
+
rep = self.vocab[self.audio_token_replacement]
|
|
79
|
+
ids: List[int] = []
|
|
80
|
+
starts: List[int] = []
|
|
81
|
+
p = -1
|
|
82
|
+
for i, n in enumerate(data.get("audio_token_len", [])):
|
|
83
|
+
if not is_cont[i]:
|
|
84
|
+
p += 1
|
|
85
|
+
if p >= len(parts):
|
|
86
|
+
raise ValueError("Text contains too few audio placeholders.")
|
|
87
|
+
ids.extend(parts[p])
|
|
88
|
+
starts.append(len(ids))
|
|
89
|
+
ids.extend([rep] * int(n))
|
|
90
|
+
p += 1
|
|
91
|
+
if p != len(parts) - 1:
|
|
92
|
+
raise ValueError("Text contains too many audio placeholders.")
|
|
93
|
+
ids.extend(parts[p])
|
|
94
|
+
if "audio_token_len" in data:
|
|
95
|
+
data["audio_token_start_idx"] = torch.as_tensor(starts)
|
|
96
|
+
data["input_ids"] = [ids]
|
|
97
|
+
data["attention_mask"] = [[1] * len(ids)]
|
|
98
|
+
return transformers.BatchFeature(data=data, tensor_type=return_tensors)
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: duplexjev-vllm
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: vLLM plugin for DuplexJev speech-decision models (Qwen3-ASR encoder + Ultravox-style projector).
|
|
5
|
+
Author: Adventists.ai
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/adventists-ai/duplexjev
|
|
8
|
+
Project-URL: Repository, https://github.com/adventists-ai/duplexjev
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
Requires-Dist: vllm>=0.29
|
|
12
|
+
|
|
13
|
+
# duplexjev-vllm
|
|
14
|
+
|
|
15
|
+
vLLM plugin for [DuplexJev](https://github.com/adventists-ai/duplexjev) speech-decision models, such as
|
|
16
|
+
[`adventists-ai/DuplexJev-4B`](https://huggingface.co/adventists-ai/DuplexJev-4B).
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pip install "vllm[audio]>=0.29" duplexjev-vllm
|
|
20
|
+
vllm serve adventists-ai/DuplexJev-4B --max-model-len 4096
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
The plugin registers the architecture `DuplexJevForConditionalGeneration` through vLLM's `vllm.general_plugins`
|
|
24
|
+
entry point, so nothing needs to be imported by hand. It adds the Qwen3-ASR audio encoder and the matching
|
|
25
|
+
preprocessing (128-bin log-mel, clips padded to whole audio tokens) to vLLM's Ultravox implementation; the connector
|
|
26
|
+
and the LLM run on vLLM's own code.
|
|
27
|
+
|
|
28
|
+
Each question is one request with `max_tokens=1`; the answer is the next-token distribution over the option letters.
|
|
29
|
+
A client that asks several questions about one clip concurrently is in
|
|
30
|
+
[`examples/vllm_client.py`](https://github.com/adventists-ai/duplexjev/blob/main/examples/vllm_client.py).
|
|
31
|
+
|
|
32
|
+
`modeling_qwen3_asr_encoder.py` is a standalone port of the Qwen3-ASR audio encoder from Hugging Face `transformers`
|
|
33
|
+
(Apache-2.0, Copyright the Qwen team, Alibaba Cloud, and the HuggingFace team). The rest of this package is
|
|
34
|
+
Apache-2.0, Copyright Adventists.ai.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
duplexjev_vllm/__init__.py,sha256=szsotecloC-nC3A78KOFyiqflDliOH2oZFIH1CAzlG8,790
|
|
2
|
+
duplexjev_vllm/configuration_qwen3_asr_encoder.py,sha256=vxkXCz7dfeoVAX1oTtQDIfh70EIgyKX2uuQTCoS8sLo,1683
|
|
3
|
+
duplexjev_vllm/model.py,sha256=OwdJRMh-GT5go8nLbleLTusfv9x8ggVmWgnQWkwa2Qc,2816
|
|
4
|
+
duplexjev_vllm/modeling_qwen3_asr_encoder.py,sha256=GZwu_bZXHV5I_VbuIZsaSOUBpPYsZ6x4w-1Sdzbgrn4,15136
|
|
5
|
+
duplexjev_vllm/processing.py,sha256=78n1wiO22ktc4Y2S6eP34mLOFkxp5JPrzKr2f3NYiiU,5014
|
|
6
|
+
duplexjev_vllm-0.1.0.dist-info/METADATA,sha256=XcHYduBdik9uPHgrxfg_3gsV0i6yNviFcKtRw1TOA8Q,1687
|
|
7
|
+
duplexjev_vllm-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
8
|
+
duplexjev_vllm-0.1.0.dist-info/entry_points.txt,sha256=buXebEK3ICwJvzJkEAKg28x9rUv6F1NoriMy0JkUYjc,59
|
|
9
|
+
duplexjev_vllm-0.1.0.dist-info/top_level.txt,sha256=tHjl9aBlqXt8hAC6iLbyxVIQdnA8wUmuwv58S9s9WUM,15
|
|
10
|
+
duplexjev_vllm-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
duplexjev_vllm
|