A high-throughput and memory-efficient inference and serving engine for LLMs
Mirrored from https://github.com/tduncan-lum/Nvidia-Optimization-Stack---VLLM.git
Synced Nov 9, 12:30 UTC
Adds FunAudioChat multimodal audio model support (#2) (#33058)
Signed-off-by: ramos <49182011+nemoramo@users.noreply.github.com> Signed-off-by: mayufeng <mayufeng@example.com> Co-authored-by: mayufeng <mayufeng@example.com>
ramos committed
Jan 28, 2026 at 13:18 UTC
36d450e3b88476c07e2dde9297692386f7174175
8 files changed
+1264
examples/offline_inference/audio_language.py
+37
@@ -117,6 +117,31 @@ def run_glmasr(question: str, audio_count: int) -> ModelRequestData:
117
)
118
119
120
+# FunAudioChat
121
+def run_funaudiochat(question: str, audio_count: int) -> ModelRequestData:
122
+ # NOTE: FunAudioChat is not available on the HuggingFace Hub at the time of
123
+ # writing. Pass a local model path via `--model`.
124
+ model_name = "funaudiochat"
125
+
126
+ engine_args = EngineArgs(
127
+ model=model_name,
128
+ max_model_len=4096,
129
+ max_num_seqs=2,
130
+ limit_mm_per_prompt={"audio": audio_count},
131
+ enforce_eager=True,
132
+ )
133
+
134
+ audio_in_prompt = "".join(
135
+ ["<|audio_bos|><|AUDIO|><|audio_eos|>\n" for _ in range(audio_count)]
136
+ )
137
+ prompt = f"{audio_in_prompt}{question}"
138
+
139
+ return ModelRequestData(
140
+ engine_args=engine_args,
141
+ prompt=prompt,
142
+ )
143
+
144
+
145
# Granite Speech
146
def run_granite_speech(question: str, audio_count: int) -> ModelRequestData:
147
# NOTE - the setting in this example are somewhat different from what is
@@ -410,6 +435,7 @@ model_example_map = {
435
"audioflamingo3": run_audioflamingo3,
436
"gemma3n": run_gemma3n,
437
"glmasr": run_glmasr,
438
+ "funaudiochat": run_funaudiochat,
439
"granite_speech": run_granite_speech,
440
"midashenglm": run_midashenglm,
441
"minicpmo": run_minicpmo,
@@ -435,6 +461,12 @@ def parse_args():
461
choices=model_example_map.keys(),
462
help='Huggingface "model_type".',
463
)
464
+ parser.add_argument(
465
+ "--model",
466
+ type=str,
467
+ default=None,
468
+ help="Model ID or local path override. Required for funaudiochat.",
469
+ )
470
parser.add_argument(
471
"--num-prompts", type=int, default=1, help="Number of prompts to run."
472
)
@@ -467,6 +499,9 @@ def main(args):
499
if model not in model_example_map:
500
raise ValueError(f"Model type {model} is not supported.")
501
502
+ if model == "funaudiochat" and not args.model:
503
+ raise ValueError("--model is required when --model-type=funaudiochat")
504
+
505
if args.tensor_parallel_size is not None and args.tensor_parallel_size < 1:
506
raise ValueError(
507
f"tensor_parallel_size must be a positive integer, "
@@ -477,6 +512,8 @@ def main(args):
512
req_data = model_example_map[model](
513
question_per_audio_count[audio_count], audio_count
514
)
515
+ if model == "funaudiochat":
516
+ req_data.engine_args.model = args.model
517
518
# Disable other modalities to save memory
519
default_limits = {"image": 0, "video": 0, "audio": 0}
tests/models/registry.py
+3
@@ -692,6 +692,9 @@ _MULTIMODAL_EXAMPLE_MODELS = {
692
"baidu/ERNIE-4.5-VL-28B-A3B-PT",
693
trust_remote_code=True,
694
),
695
+ "FunAudioChatForConditionalGeneration": _HfExamplesInfo(
696
+ "funaudiochat", is_available_online=False
697
+ ),
698
"FuyuForCausalLM": _HfExamplesInfo("adept/fuyu-8b"),
699
"Gemma3ForConditionalGeneration": _HfExamplesInfo("google/gemma-3-4b-it"),
700
"Gemma3nForConditionalGeneration": _HfExamplesInfo("google/gemma-3n-E2B-it"),
vllm/model_executor/models/funaudiochat.py
new
+1083
@@ -0,0 +1,1083 @@
1
+# SPDX-License-Identifier: Apache-2.0
2
+# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+
4
+"""Inference-only FunAudioChat model compatible with HuggingFace weights.
5
+
6
+FunAudioChat is a Qwen3 text model augmented with:
7
+ - a continuous audio encoder (Whisper-mel frontend + transformer)
8
+ - a discrete audio encoder (speech tokenizer + projector)
9
+
10
+In the HF implementation, audio features are scattered into `<|AUDIO|>` token
11
+positions via `inputs_embeds`, while `position_ids` (RoPE) remains standard 1D.
12
+"""
13
+
14
+from __future__ import annotations
15
+
16
+import os
17
+from collections.abc import Iterable, Mapping, Sequence
18
+from functools import cached_property
19
+from typing import Any
20
+
21
+import numpy as np
22
+import torch
23
+import torch.nn as nn
24
+from transformers import PreTrainedTokenizerFast, WhisperFeatureExtractor
25
+from transformers.activations import get_activation
26
+from transformers.feature_extraction_utils import BatchFeature
27
+from transformers.modeling_outputs import BaseModelOutput
28
+
29
+from vllm.config import VllmConfig
30
+from vllm.config.multimodal import BaseDummyOptions
31
+from vllm.model_executor.layers.attention.mm_encoder_attention import MMEncoderAttention
32
+from vllm.model_executor.layers.linear import QKVParallelLinear, RowParallelLinear
33
+from vllm.model_executor.model_loader.weight_utils import default_weight_loader
34
+from vllm.multimodal import MULTIMODAL_REGISTRY
35
+from vllm.multimodal.inputs import (
36
+ MultiModalDataDict,
37
+ MultiModalFieldConfig,
38
+ MultiModalKwargsItems,
39
+)
40
+from vllm.multimodal.parse import (
41
+ AudioProcessorItems,
42
+ MultiModalDataItems,
43
+ MultiModalDataParser,
44
+)
45
+from vllm.multimodal.processing import (
46
+ BaseDummyInputsBuilder,
47
+ BaseMultiModalProcessor,
48
+ BaseProcessingInfo,
49
+ PromptReplacement,
50
+ PromptUpdate,
51
+ PromptUpdateDetails,
52
+)
53
+from vllm.sequence import IntermediateTensors
54
+from vllm.utils.import_utils import _has_module
55
+
56
+from .interfaces import MultiModalEmbeddings, SupportsMultiModal, SupportsPP
57
+from .utils import AutoWeightsLoader, init_vllm_registered_model, maybe_prefix
58
+
59
+
60
+class _SinusoidsPositionEmbedding(nn.Module):
61
+ def __init__(self, length: int, channels: int, max_timescale: float = 10000.0):
62
+ super().__init__()
63
+ if channels % 2 != 0:
64
+ raise ValueError("SinusoidsPositionEmbedding needs even channels input")
65
+
66
+ log_timescale_increment = np.log(max_timescale) / (channels // 2 - 1)
67
+ inv_timescales = torch.exp(
68
+ -log_timescale_increment * torch.arange(channels // 2).float()
69
+ )
70
+ scaled_time = (
71
+ torch.arange(length)[:, np.newaxis] * inv_timescales[np.newaxis, :]
72
+ )
73
+ self.register_buffer(
74
+ "positional_embedding",
75
+ torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim=1),
76
+ persistent=False,
77
+ )
78
+
79
+
80
+class FunAudioChatAudioAttention(nn.Module):
81
+ """Multi-headed attention used inside the continuous audio tower."""
82
+
83
+ def __init__(self, config: Any):
84
+ super().__init__()
85
+ self.embed_dim = int(config.d_model)
86
+ self.total_num_heads = int(config.encoder_attention_heads)
87
+ self.dropout = float(getattr(config, "attention_dropout", 0.0))
88
+ self.head_dim = self.embed_dim // self.total_num_heads
89
+ self.num_key_value_groups = 1 # needed for eager attention
90
+ self.config = config
91
+
92
+ if self.head_dim * self.total_num_heads != self.embed_dim:
93
+ raise ValueError(
94
+ "embed_dim must be divisible by num_heads "
95
+ f"(got embed_dim={self.embed_dim}, "
96
+ f"num_heads={self.total_num_heads})."
97
+ )
98
+ self.scaling = self.head_dim**-0.5
99
+ self.attention_dropout = 0.0
100
+ self.is_decoder = False
101
+ self.is_causal = False
102
+
103
+ self.qkv_proj = QKVParallelLinear(
104
+ self.embed_dim,
105
+ self.head_dim,
106
+ self.total_num_heads,
107
+ bias=True,
108
+ )
109
+ self.num_heads = self.qkv_proj.num_heads
110
+ self.num_kv_heads = self.qkv_proj.num_kv_heads
111
+ self.q_size = self.num_heads * self.head_dim
112
+ self.kv_size = self.num_kv_heads * self.head_dim
113
+
114
+ self.attn = MMEncoderAttention(
115
+ num_heads=self.num_heads,
116
+ head_size=self.head_dim,
117
+ scale=self.scaling,
118
+ num_kv_heads=self.num_kv_heads,
119
+ prefix="funaudiochat_audio_tower.attn",
120
+ )
121
+ self.out_proj = RowParallelLinear(
122
+ self.embed_dim,
123
+ self.embed_dim,
124
+ bias=True,
125
+ )
126
+
127
+ def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
128
+ stacked_params_mapping = [
129
+ ("qkv_proj", "q_proj", "q"),
130
+ ("qkv_proj", "k_proj", "k"),
131
+ ("qkv_proj", "v_proj", "v"),
132
+ ]
133
+
134
+ params_dict = dict(self.named_parameters())
135
+ with torch.no_grad():
136
+ if self.qkv_proj.bias is not None:
137
+ # HF FunAudioChat uses bias=False for k_proj. Ensure the missing
138
+ # shard starts as zeros, while allowing q/v shards to load.
139
+ self.qkv_proj.bias.zero_()
140
+
141
+ loaded_params: set[str] = set()
142
+ for name, loaded_weight in weights:
143
+ for param_name, shard_name, shard_id in stacked_params_mapping:
144
+ if shard_name not in name:
145
+ continue
146
+ name = name.replace(shard_name, param_name)
147
+ param = params_dict[name]
148
+ weight_loader = getattr(param, "weight_loader", default_weight_loader)
149
+ weight_loader(param, loaded_weight, shard_id)
150
+ break
151
+ else:
152
+ # Skip loading extra bias for GPTQ models.
153
+ if name.endswith(".bias") and name not in params_dict:
154
+ continue
155
+
156
+ param = params_dict[name]
157
+ weight_loader = getattr(param, "weight_loader", default_weight_loader)
158
+ weight_loader(param, loaded_weight)
159
+
160
+ loaded_params.add(name)
161
+
162
+ return loaded_params
163
+
164
+ def forward(
165
+ self,
166
+ hidden_states: torch.Tensor,
167
+ cu_seqlens: torch.Tensor | None = None,
168
+ attention_mask: torch.Tensor | None = None,
169
+ **kwargs: object,
170
+ ) -> torch.Tensor:
171
+ del kwargs
172
+ del attention_mask
173
+ seq_length, _ = hidden_states.size()
174
+
175
+ qkv, _ = self.qkv_proj(hidden_states)
176
+ query_states, key_states, value_states = qkv.split(
177
+ [self.q_size, self.kv_size, self.kv_size], dim=-1
178
+ )
179
+
180
+ max_seqlen: torch.Tensor | None = None
181
+ if cu_seqlens is not None:
182
+ max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max()
183
+
184
+ attn_output = self.attn(
185
+ query_states.reshape(1, seq_length, self.q_size),
186
+ key_states.reshape(1, seq_length, self.kv_size),
187
+ value_states.reshape(1, seq_length, self.kv_size),
188
+ cu_seqlens=cu_seqlens,
189
+ max_seqlen=max_seqlen,
190
+ ).reshape(seq_length, -1)
191
+
192
+ output, _ = self.out_proj(attn_output)
193
+ return output
194
+
195
+
196
+class FunAudioChatAudioEncoderLayer(nn.Module):
197
+ def __init__(self, config: Any):
198
+ super().__init__()
199
+ self.embed_dim = int(config.d_model)
200
+ self.self_attn = FunAudioChatAudioAttention(config)
201
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
202
+ self.dropout = float(config.dropout)
203
+ self.activation_fn = get_activation(str(config.activation_function))
204
+ self.activation_dropout = float(config.activation_dropout)
205
+ self.fc1 = nn.Linear(self.embed_dim, int(config.encoder_ffn_dim))
206
+ self.fc2 = nn.Linear(int(config.encoder_ffn_dim), self.embed_dim)
207
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
208
+
209
+ def forward(
210
+ self,
211
+ hidden_states: torch.Tensor,
212
+ cu_seqlens: torch.Tensor,
213
+ attention_mask: torch.Tensor | None = None,
214
+ **kwargs: object,
215
+ ) -> tuple[torch.Tensor]:
216
+ residual = hidden_states
217
+ hidden_states = self.self_attn_layer_norm(hidden_states)
218
+ hidden_states = self.self_attn(
219
+ hidden_states=hidden_states,
220
+ cu_seqlens=cu_seqlens,
221
+ attention_mask=attention_mask,
222
+ **kwargs,
223
+ )
224
+ hidden_states = residual + hidden_states
225
+
226
+ residual = hidden_states
227
+ hidden_states = self.final_layer_norm(hidden_states)
228
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
229
+ hidden_states = nn.functional.dropout(
230
+ hidden_states, p=self.activation_dropout, training=self.training
231
+ )
232
+ hidden_states = self.fc2(hidden_states)
233
+ hidden_states = nn.functional.dropout(
234
+ hidden_states, p=self.dropout, training=self.training
235
+ )
236
+ hidden_states = residual + hidden_states
237
+
238
+ return (hidden_states,)
239
+
240
+
241
+class FunAudioChatAudioEncoder(nn.Module):
242
+ """Continuous audio tower."""
243
+
244
+ def __init__(self, config: Any):
245
+ super().__init__()
246
+ self.config = config
247
+
248
+ embed_dim = int(config.d_model)
249
+ self.num_mel_bins = int(config.num_mel_bins)
250
+ self.max_source_positions = int(config.max_source_positions)
251
+ self.embed_scale = (embed_dim**0.5) if bool(config.scale_embedding) else 1.0
252
+ self.n_window = int(config.n_window)
253
+
254
+ self.conv1 = nn.Conv1d(self.num_mel_bins, embed_dim, kernel_size=3, padding=1)
255
+ self.conv2 = nn.Conv1d(embed_dim, embed_dim, kernel_size=3, stride=2, padding=1)
256
+ self.layers = nn.ModuleList(
257
+ [
258
+ FunAudioChatAudioEncoderLayer(config)
259
+ for _ in range(int(config.encoder_layers))
260
+ ]
261
+ )
262
+ self.ln_post = nn.LayerNorm(embed_dim)
263
+ self.avg_pooler = nn.AvgPool1d(2, stride=2)
264
+ self.proj = nn.Linear(embed_dim, int(config.output_dim))
265
+ self.positional_embedding = _SinusoidsPositionEmbedding(
266
+ self.max_source_positions, embed_dim
267
+ )
268
+
269
+ # Present in HF weights even if unused during S2T.
270
+ self.audio_bos_eos_token = nn.Embedding(2, int(config.output_dim))
271
+
272
+ @property
273
+ def dtype(self) -> torch.dtype:
274
+ return self.conv1.weight.dtype
275
+
276
+ def _prepare_attention_mask(
277
+ self, inputs_tensor: torch.Tensor, cu_seqlens: torch.Tensor
278
+ ) -> torch.Tensor | None:
279
+ if getattr(self.config, "_attn_implementation", "eager") == "flash_attention_2":
280
+ return None
281
+
282
+ seq_length = inputs_tensor.shape[0]
283
+ attention_mask = torch.full(
284
+ (1, 1, seq_length, seq_length),
285
+ torch.finfo(inputs_tensor.dtype).min,
286
+ device=inputs_tensor.device,
287
+ dtype=inputs_tensor.dtype,
288
+ )
289
+ for i in range(1, len(cu_seqlens)):
290
+ start = int(cu_seqlens[i - 1].item())
291
+ end = int(cu_seqlens[i].item())
292
+ attention_mask[..., start:end, start:end] = 0
293
+ return attention_mask
294
+
295
+ def forward(
296
+ self,
297
+ input_features: torch.Tensor,
298
+ feature_lens: torch.Tensor,
299
+ aftercnn_lens: torch.Tensor,
300
+ speech_maxlen: int,
301
+ **kwargs: object,
302
+ ) -> BaseModelOutput:
303
+ # For max-length audio (300s => ~7500 speech frames at 25Hz), the
304
+ # Torch SDPA path can be prohibitively memory hungry (~O(n^2) inside the
305
+ # longest chunks). Require FlashAttention for such inputs to avoid OOM
306
+ # and performance cliffs.
307
+ if int(speech_maxlen) >= 7500:
308
+ if not _has_module("flash_attn"):
309
+ raise RuntimeError(
310
+ "FunAudioChat long audio (~300s) requires FlashAttention-2 "
311
+ "for the continuous audio tower, but `flash_attn` is not "
312
+ "installed in the runtime environment."
313
+ )
314
+ if not getattr(
315
+ self.layers[0].self_attn.attn, "is_flash_attn_backend", False
316
+ ):
317
+ raise RuntimeError(
318
+ "FunAudioChat long audio (~300s) requires FlashAttention for the "
319
+ "continuous audio tower, but the selected MM encoder attention "
320
+ "backend is not FlashAttention."
321
+ )
322
+
323
+ # Handle empty / invalid items (feature_lens == 0) without crashing.
324
+ original_batch_size = int(feature_lens.size(0))
325
+ device = input_features.device
326
+
327
+ valid_mask = feature_lens > 0
328
+ valid_indices = torch.where(valid_mask)[0]
329
+
330
+ if valid_indices.numel() == 0:
331
+ output_dim = int(self.proj.out_features)
332
+ return BaseModelOutput(
333
+ last_hidden_state=torch.zeros(
334
+ (original_batch_size, speech_maxlen, output_dim),
335
+ device=device,
336
+ dtype=self.proj.weight.dtype,
337
+ )
338
+ )
339
+
340
+ input_features_list = input_features.split(feature_lens.tolist(), dim=1)
341
+ valid_input_features_list = [input_features_list[int(i)] for i in valid_indices]
342
+ valid_input_features = torch.cat(valid_input_features_list, dim=1)
343
+
344
+ valid_feature_lens = feature_lens[valid_mask]
345
+ valid_aftercnn_lens = aftercnn_lens[valid_mask]
346
+
347
+ chunk_num = torch.ceil(valid_feature_lens / (self.n_window * 2)).long()
348
+
349
+ chunk_lengths_list: list[int] = []
350
+ full_chunk_len = self.n_window * 2
351
+ for i, length in enumerate(valid_feature_lens):
352
+ num_chunks_for_sample = int(chunk_num[i].item())
353
+ if num_chunks_for_sample == 0:
354
+ continue
355
+ chunk_lengths_list.extend([full_chunk_len] * (num_chunks_for_sample - 1))
356
+ last_chunk_len = int(length.item()) % full_chunk_len
357
+ if last_chunk_len == 0:
358
+ last_chunk_len = full_chunk_len
359
+ chunk_lengths_list.append(last_chunk_len)
360
+
361
+ chunk_lengths = torch.tensor(
362
+ chunk_lengths_list, dtype=torch.long, device=device
363
+ )
364
+
365
+ chunk_list = valid_input_features.split(chunk_lengths.tolist(), dim=1)
366
+ padded_feature, padded_mask, padded_mask_after_cnn = (
367
+ self.padded_and_mask_function(
368
+ chunk_list, chunk_lengths, padding_value=0, padding_side="right"
369
+ )
370
+ )
371
+
372
+ padded_embed = nn.functional.gelu(self.conv1(padded_feature)) * padded_mask
373
+ padded_embed = nn.functional.gelu(self.conv2(padded_embed)).transpose(1, 2)
374
+
375
+ padded_embed = padded_embed + self.positional_embedding.positional_embedding[
376
+ : padded_embed.shape[1], :
377
+ ].unsqueeze(0).to(padded_embed.dtype)
378
+
379
+ hidden_states = padded_embed[padded_mask_after_cnn]
380
+ cu_seqlens = torch.cat(
381
+ (
382
+ torch.zeros(1, device=padded_mask_after_cnn.device, dtype=torch.int32),
383
+ padded_mask_after_cnn.sum(1).cumsum(0),
384
+ )
385
+ ).to(torch.int32)
386
+
387
+ for encoder_layer in self.layers:
388
+ (hidden_states,) = encoder_layer(
389
+ hidden_states,
390
+ cu_seqlens=cu_seqlens,
391
+ **kwargs,
392
+ )
393
+
394
+ hidden_states_list = hidden_states.split(valid_aftercnn_lens.tolist(), dim=0)
395
+
396
+ pooled_list: list[torch.Tensor] = []
397
+ pooled_lengths: list[int] = []
398
+ for each_audio_states in hidden_states_list:
399
+ seq_len = int(each_audio_states.shape[0])
400
+ if seq_len >= 2:
401
+ pooled = nn.functional.avg_pool1d(
402
+ each_audio_states.transpose(0, 1), kernel_size=2, stride=2
403
+ ).transpose(0, 1)
404
+ else:
405
+ pooled = each_audio_states
406
+ pooled_list.append(pooled)
407
+ pooled_lengths.append(int(pooled.shape[0]))
408
+
409
+ pooled_concat = torch.cat(pooled_list, dim=0)
410
+ processed_concat = self.proj(self.ln_post(pooled_concat))
411
+ processed_audio_list = list(processed_concat.split(pooled_lengths, dim=0))
412
+
413
+ output_dim = (
414
+ int(processed_audio_list[0].shape[-1])
415
+ if processed_audio_list
416
+ else int(self.proj.out_features)
417
+ )
418
+ output_hidden_states = torch.zeros(
419
+ (original_batch_size, speech_maxlen, output_dim),
420
+ dtype=processed_audio_list[0].dtype
421
+ if processed_audio_list
422
+ else self.proj.weight.dtype,
423
+ device=device,
424
+ )
425
+
426
+ for valid_idx, processed in zip(valid_indices, processed_audio_list):
427
+ seq_len = min(int(processed.shape[0]), int(speech_maxlen))
428
+ output_hidden_states[int(valid_idx), :seq_len] = processed[:seq_len]
429
+
430
+ return BaseModelOutput(last_hidden_state=output_hidden_states)
431
+
432
+ def padded_and_mask_function(
433
+ self,
434
+ tensor_list: Sequence[torch.Tensor],
435
+ tensor_len: torch.Tensor,
436
+ padding_value: float = 0.0,
437
+ padding_side: str = "right",
438
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
439
+ max_len = int(tensor_len.max().item())
440
+ dim = int(tensor_list[0].shape[0])
441
+ padded_tensor = torch.full(
442
+ size=(len(tensor_list), dim, max_len),
443
+ fill_value=padding_value,
444
+ dtype=self.dtype,
445
+ device=tensor_list[0].device,
446
+ )
447
+
448
+ batch_mask = torch.zeros(
449
+ (len(tensor_len), max_len), dtype=torch.long, device=padded_tensor.device
450
+ )
451
+ for i, length in enumerate(tensor_len):
452
+ length_val = int(length.item())
453
+ batch_mask[i, :length_val] = 1
454
+ padded_tensor[i, :, :length_val] = tensor_list[i]
455
+
456
+ feature_lens_after_cnn = (tensor_len - 1) // 2 + 1
457
+ max_len_after_cnn = int(feature_lens_after_cnn.max().item())
458
+ batch_mask_after_cnn = torch.zeros(
459
+ (len(tensor_len), max_len_after_cnn),
460
+ dtype=torch.long,
461
+ device=padded_tensor.device,
462
+ )
463
+ for i, length in enumerate(feature_lens_after_cnn):
464
+ batch_mask_after_cnn[i, : int(length.item())] = 1
465
+
466
+ if padding_side != "right":
467
+ raise NotImplementedError("Only right padding is supported.")
468
+
469
+ return (
470
+ padded_tensor,
471
+ batch_mask.unsqueeze(1).to(padded_tensor.dtype),
472
+ batch_mask_after_cnn.bool(),
473
+ )
474
+
475
+ # From the HF FunAudioChat implementation.
476
+ def _get_feat_extract_output_lengths(
477
+ self, input_lengths: torch.LongTensor
478
+ ) -> tuple[torch.LongTensor, torch.LongTensor]:
479
+ input_lengths = (input_lengths - 1) // 2 + 1
480
+ output_lengths = (input_lengths - 2) // 2 + 1
481
+ return input_lengths, output_lengths
482
+
483
+
484
+class FunAudioChatDiscreteEncoder(nn.Module):
485
+ """Discrete audio encoder (speech tokenizer -> grouped embeddings)."""
486
+
487
+ def __init__(self, config: Any):
488
+ super().__init__()
489
+ self.padding_idx = int(config.pad_token_id)
490
+ self.group_size = int(config.group_size)
491
+ self.hidden_size = int(config.output_dim)
492
+ self.continuous_features_mode = getattr(
493
+ config, "continuous_features_mode", "add"
494
+ )
495
+ self.embed_tokens = nn.Embedding(
496
+ int(config.codebook_size), self.hidden_size, self.padding_idx
497
+ )
498
+ self.output_matching = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
499
+ self.continual_output_matching = nn.Linear(
500
+ self.hidden_size, self.hidden_size, bias=False
501
+ )
502
+
503
+ def forward(
504
+ self,
505
+ audio_ids: torch.Tensor,
506
+ continuous_audio_features: torch.Tensor | None = None,
507
+ continuous_audio_output_lengths: torch.Tensor | None = None,
508
+ feature_exist_mask: torch.Tensor | None = None,
509
+ ) -> torch.Tensor:
510
+ del continuous_audio_output_lengths
511
+
512
+ inputs_embeds = self.embed_tokens(audio_ids)
513
+ hidden_states = inputs_embeds.reshape(
514
+ inputs_embeds.shape[0], -1, self.group_size * self.hidden_size
515
+ )
516
+ hidden_states = hidden_states.reshape(
517
+ hidden_states.shape[0], -1, self.group_size, self.hidden_size
518
+ ).mean(dim=2)
519
+ hidden_states = self.output_matching(hidden_states)
520
+
521
+ if continuous_audio_features is not None:
522
+ continuous_audio_features = continuous_audio_features.reshape(
523
+ continuous_audio_features.shape[0],
524
+ -1,
525
+ self.group_size,
526
+ self.hidden_size,
527
+ ).mean(dim=2)
528
+ continuous_audio_hidden_states = self.continual_output_matching(
529
+ continuous_audio_features
530
+ )
531
+
532
+ if feature_exist_mask is None:
533
+ feature_exist_mask = torch.ones(
534
+ (hidden_states.shape[0],),
535
+ dtype=torch.bool,
536
+ device=hidden_states.device,
537
+ )
538
+ if self.continuous_features_mode == "add":
539
+ hidden_states[feature_exist_mask] += continuous_audio_hidden_states
540
+ else:
541
+ hidden_states[feature_exist_mask] = continuous_audio_hidden_states
542
+
543
+ return hidden_states
544
+
545
+ def _get_feat_extract_output_lengths(
546
+ self, input_lengths: torch.LongTensor
547
+ ) -> tuple[torch.LongTensor, torch.LongTensor]:
548
+ output_lengths = (input_lengths + self.group_size - 1) // self.group_size
549
+ return input_lengths, output_lengths
550
+
551
+
552
+class FunAudioChatProcessingInfo(BaseProcessingInfo):
553
+ token_fps: int = 25
554
+
555
+ def get_supported_mm_limits(self) -> Mapping[str, int | None]:
556
+ return {"audio": None}
557
+
558
+ def get_target_channels(self) -> int:
559
+ return 1
560
+
561
+ def get_mm_max_tokens_per_item(
562
+ self,
563
+ seq_len: int,
564
+ mm_counts: Mapping[str, int],
565
+ ) -> Mapping[str, int] | None:
566
+ # The discrete audio encoder downsamples 25Hz frames with group_size=5,
567
+ # so for a 300s clip the max number of `<|AUDIO|>` placeholders is 1500.
568
+ cfg = self.get_hf_config()
569
+ audio_cfg = getattr(cfg, "audio_config", None)
570
+ max_audio_tokens = int(getattr(audio_cfg, "max_source_positions", 1500))
571
+ return {"audio": max_audio_tokens}
572
+
573
+ @cached_property
574
+ def feature_extractor(self) -> WhisperFeatureExtractor:
575
+ return WhisperFeatureExtractor.from_pretrained(self.model_id)
576
+
577
+ @cached_property
578
+ def speech_tokenizer(self) -> PreTrainedTokenizerFast:
579
+ return PreTrainedTokenizerFast.from_pretrained(
580
+ self.model_id, subfolder="speech_tokenizer"
581
+ )
582
+
583
+ def get_feature_extractor(self) -> WhisperFeatureExtractor:
584
+ return self.feature_extractor
585
+
586
+ def get_speech_tokenizer(self) -> PreTrainedTokenizerFast:
587
+ return self.speech_tokenizer
588
+
589
+ def get_audio_group_size(self) -> int:
590
+ cfg = self.get_hf_config()
591
+ audio_cfg = getattr(cfg, "audio_config", None)
592
+ return int(getattr(audio_cfg, "group_size", 5))
593
+
594
+
595
+class FunAudioChatDummyInputsBuilder(
596
+ BaseDummyInputsBuilder[FunAudioChatProcessingInfo]
597
+):
598
+ def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str:
599
+ num_audios = mm_counts.get("audio", 0)
600
+ return "<|audio_bos|><|AUDIO|><|audio_eos|>" * int(num_audios)
601
+
602
+ def get_dummy_mm_data(
603
+ self,
604
+ seq_len: int,
605
+ mm_counts: Mapping[str, int],
606
+ mm_options: Mapping[str, BaseDummyOptions] | None = None,
607
+ ) -> MultiModalDataDict:
608
+ feature_extractor = self.info.get_feature_extractor()
609
+ sampling_rate = int(feature_extractor.sampling_rate)
610
+
611
+ # Dummy inputs are used for profiling; construct the worst-case audio
612
+ # length that maximizes the number of encoder tokens.
613
+ cfg = self.info.get_hf_config()
614
+ audio_cfg = getattr(cfg, "audio_config", None)
615
+ max_audio_tokens = int(getattr(audio_cfg, "max_source_positions", 1500))
616
+ group_size = self.info.get_audio_group_size()
617
+ token_fps = int(getattr(self.info, "token_fps", 25))
618
+ target_num_frames = max(1, max_audio_tokens) * max(1, group_size)
619
+ audio_len = max(
620
+ 1,
621
+ (target_num_frames * sampling_rate + token_fps - 1) // token_fps,
622
+ )
623
+ num_audios = int(mm_counts.get("audio", 0))
624
+
625
+ audio_overrides = mm_options.get("audio") if mm_options else None
626
+ return {
627
+ "audio": self._get_dummy_audios(
628
+ length=audio_len,
629
+ num_audios=num_audios,
630
+ overrides=audio_overrides,
631
+ )
632
+ }
633
+
634
+
635
+class FunAudioChatMultiModalProcessor(
636
+ BaseMultiModalProcessor[FunAudioChatProcessingInfo]
637
+):
638
+ def _get_data_parser(self) -> MultiModalDataParser:
639
+ feature_extractor = self.info.get_feature_extractor()
640
+ return MultiModalDataParser(
641
+ target_sr=int(feature_extractor.sampling_rate),
642
+ target_channels=self.info.get_target_channels(),
643
+ )
644
+
645
+ def _call_hf_processor(
646
+ self,
647
+ prompt: str,
648
+ mm_data: Mapping[str, object],
649
+ mm_kwargs: Mapping[str, object],
650
+ tok_kwargs: Mapping[str, object],
651
+ ) -> BatchFeature:
652
+ tokenizer = self.info.get_tokenizer()
653
+ input_ids = torch.tensor([tokenizer.encode(prompt, **tok_kwargs)])
654
+
655
+ audios = mm_data.get("audios", [])
656
+ if not audios:
657
+ return BatchFeature({"input_ids": input_ids})
658
+
659
+ feature_extractor = self.info.get_feature_extractor()
660
+ sr = int(feature_extractor.sampling_rate)
661
+ min_samples = int(getattr(feature_extractor, "n_fft", 400) or 400)
662
+
663
+ wavs: list[np.ndarray] = []
664
+ speech_strs: list[str] = []
665
+
666
+ speech_tokenizer = self.info.get_speech_tokenizer()
667
+ pad_token = speech_tokenizer.pad_token or "<|audio_pad|>"
668
+ for audio in audios:
669
+ if isinstance(audio, torch.Tensor):
670
+ audio = audio.detach().cpu().numpy()
671
+ audio_np = np.asarray(audio, dtype=np.float32)
672
+
673
+ if min_samples > 0 and audio_np.shape[0] < min_samples:
674
+ audio_np = np.pad(
675
+ audio_np, (0, min_samples - audio_np.shape[0]), mode="constant"
676
+ )
677
+
678
+ wavs.append(audio_np)
679
+ num_frames = int(
680
+ (float(audio_np.shape[0]) / float(sr)) * float(self.info.token_fps)
681
+ )
682
+ speech_strs.append(pad_token * max(1, int(num_frames)))
683
+
684
+ audio_group_size = self.info.get_audio_group_size()
685
+ speech_inputs = speech_tokenizer(
686
+ speech_strs,
687
+ return_attention_mask=True,
688
+ return_token_type_ids=False,
689
+ padding=True,
690
+ pad_to_multiple_of=audio_group_size,
691
+ return_tensors="pt",
692
+ )
693
+
694
+ wav_inputs = feature_extractor(
695
+ wavs,
696
+ sampling_rate=sr,
697
+ return_attention_mask=True,
698
+ padding="max_length",
699
+ return_tensors="pt",
700
+ )
701
+
702
+ mm_inputs: dict[str, torch.Tensor] = {
703
+ "speech_ids": speech_inputs["input_ids"],
704
+ "speech_attention_mask": speech_inputs["attention_mask"],
705
+ "input_features": wav_inputs["input_features"],
706
+ "feature_attention_mask": wav_inputs["attention_mask"],
707
+ "feature_exist_mask": torch.ones((len(wavs),), dtype=torch.bool),
708
+ }
709
+
710
+ return BatchFeature({"input_ids": input_ids, **mm_inputs})
711
+
712
+ def _hf_processor_applies_updates(
713
+ self,
714
+ prompt_text: str,
715
+ mm_items: MultiModalDataItems,
716
+ hf_processor_mm_kwargs: Mapping[str, object],
717
+ tokenization_kwargs: Mapping[str, object],
718
+ ) -> bool:
719
+ return False
720
+
721
+ def _get_mm_fields_config(
722
+ self,
723
+ hf_inputs: BatchFeature,
724
+ hf_processor_mm_kwargs: Mapping[str, object],
725
+ ) -> Mapping[str, MultiModalFieldConfig]:
726
+ return {
727
+ "speech_ids": MultiModalFieldConfig.batched("audio"),
728
+ "speech_attention_mask": MultiModalFieldConfig.batched("audio"),
729
+ "input_features": MultiModalFieldConfig.batched("audio"),
730
+ "feature_attention_mask": MultiModalFieldConfig.batched("audio"),
731
+ "feature_exist_mask": MultiModalFieldConfig.batched("audio"),
732
+ }
733
+
734
+ def _get_prompt_updates(
735
+ self,
736
+ mm_items: MultiModalDataItems,
737
+ hf_processor_mm_kwargs: Mapping[str, object],
738
+ out_mm_kwargs: MultiModalKwargsItems,
739
+ ) -> Sequence[PromptUpdate]:
740
+ tokenizer = self.info.get_tokenizer()
741
+ vocab = tokenizer.get_vocab()
742
+
743
+ audio_token = "<|AUDIO|>"
744
+ audio_token_id = vocab[audio_token]
745
+
746
+ out_mm_data = out_mm_kwargs.get_data()
747
+ speech_attention_mask = out_mm_data.get("speech_attention_mask")
748
+ if speech_attention_mask is None:
749
+ audio_output_lengths: list[int] = []
750
+ else:
751
+ assert isinstance(speech_attention_mask, torch.Tensor)
752
+ speech_lengths = speech_attention_mask.sum(-1)
753
+ group_size = self.info.get_audio_group_size()
754
+ audio_output_lengths = (
755
+ (speech_lengths + group_size - 1) // group_size
756
+ ).tolist()
757
+
758
+ def get_replacement_funaudiochat(item_idx: int):
759
+ num_features = (
760
+ int(audio_output_lengths[item_idx]) if audio_output_lengths else 1
761
+ )
762
+ if num_features <= 0:
763
+ audios = mm_items.get_items("audio", AudioProcessorItems)
764
+ audio_len = audios.get_audio_length(item_idx)
765
+ raise ValueError(
766
+ f"The audio (len={audio_len}) is too short to be "
767
+ "represented inside the model"
768
+ )
769
+
770
+ audio_tokens = [audio_token_id] * num_features
771
+ return PromptUpdateDetails.select_token_id(
772
+ audio_tokens,
773
+ embed_token_id=audio_token_id,
774
+ )
775
+
776
+ return [
777
+ PromptReplacement(
778
+ modality="audio",
779
+ target=audio_token,
780
+ replacement=get_replacement_funaudiochat,
781
+ )
782
+ ]
783
+
784
+
785
+@MULTIMODAL_REGISTRY.register_processor(
786
+ FunAudioChatMultiModalProcessor,
787
+ info=FunAudioChatProcessingInfo,
788
+ dummy_inputs=FunAudioChatDummyInputsBuilder,
789
+)
790
+class FunAudioChatForConditionalGeneration(nn.Module, SupportsMultiModal, SupportsPP):
791
+ @classmethod
792
+ def get_placeholder_str(cls, modality: str, i: int) -> str | None:
793
+ if modality.startswith("audio"):
794
+ return "<|audio_bos|><|AUDIO|><|audio_eos|>"
795
+
796
+ raise ValueError("Only audio modality is supported")
797
+
798
+ def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
799
+ super().__init__()
800
+ config = vllm_config.model_config.hf_config
801
+ quant_config = vllm_config.quant_config
802
+ multimodal_config = vllm_config.model_config.multimodal_config
803
+ self.config = config
804
+ self.multimodal_config = multimodal_config
805
+ self.quant_config = quant_config
806
+
807
+ with self._mark_tower_model(vllm_config, "audio"):
808
+ self.continuous_audio_tower = FunAudioChatAudioEncoder(config.audio_config)
809
+ self.audio_tower = FunAudioChatDiscreteEncoder(config.audio_config)
810
+
811
+ with self._mark_language_model(vllm_config):
812
+ self.language_model = init_vllm_registered_model(
813
+ vllm_config=vllm_config,
814
+ hf_config=config.text_config,
815
+ prefix=maybe_prefix(prefix, "language_model"),
816
+ architectures=["Qwen3ForCausalLM"],
817
+ )
818
+
819
+ self.make_empty_intermediate_tensors = (
820
+ self.language_model.make_empty_intermediate_tensors
821
+ )
822
+
823
+ def get_language_model(self) -> torch.nn.Module:
824
+ return self.language_model
825
+
826
+ def _get_continuous_audio_features(
827
+ self,
828
+ input_features: torch.Tensor,
829
+ feature_attention_mask: torch.Tensor,
830
+ speech_maxlen: int,
831
+ ) -> tuple[torch.Tensor, torch.Tensor]:
832
+ # Align mask and features to avoid indexing errors when padding differs.
833
+ if (
834
+ input_features.dim() == 3
835
+ and feature_attention_mask.shape[1] != input_features.shape[-1]
836
+ ):
837
+ min_len = min(
838
+ int(feature_attention_mask.shape[1]), int(input_features.shape[-1])
839
+ )
840
+ feature_attention_mask = feature_attention_mask[:, :min_len]
841
+ input_features = input_features[:, :, :min_len]
842
+
843
+ feature_lens = torch.sum(feature_attention_mask, dim=1)
844
+
845
+ flat_features = input_features.permute(0, 2, 1)[
846
+ feature_attention_mask.bool()
847
+ ].permute(1, 0)
848
+
849
+ audio_feat_lengths, audio_output_lengths = (
850
+ self.continuous_audio_tower._get_feat_extract_output_lengths(feature_lens)
851
+ )
852
+
853
+ audio_outputs = self.continuous_audio_tower(
854
+ flat_features,
855
+ feature_lens=feature_lens,
856
+ aftercnn_lens=audio_feat_lengths,
857
+ speech_maxlen=speech_maxlen,
858
+ )
859
+ return audio_outputs.last_hidden_state, audio_output_lengths
860
+
861
+ def embed_multimodal(self, **kwargs: object) -> MultiModalEmbeddings:
862
+ speech_ids = kwargs.get("speech_ids")
863
+ speech_attention_mask = kwargs.get("speech_attention_mask")
864
+ input_features = kwargs.get("input_features")
865
+ feature_attention_mask = kwargs.get("feature_attention_mask")
866
+ feature_exist_mask = kwargs.get("feature_exist_mask")
867
+
868
+ if speech_ids is None:
869
+ return []
870
+
871
+ pad_id = int(getattr(self.audio_tower, "padding_idx", 0))
872
+
873
+ if not isinstance(speech_ids, torch.Tensor):
874
+ if (
875
+ isinstance(speech_ids, (list, tuple))
876
+ and len(speech_ids) > 0
877
+ and all(isinstance(t, torch.Tensor) for t in speech_ids)
878
+ ):
879
+ speech_ids_tensors = []
880
+ for t in speech_ids:
881
+ if t.dim() == 2 and t.shape[0] == 1:
882
+ t = t.squeeze(0)
883
+ if t.dim() != 1:
884
+ raise TypeError(
885
+ "FunAudioChat speech_ids must be a 1D tensor per item "
886
+ f"(got shape={tuple(t.shape)})"
887
+ )
888
+ speech_ids_tensors.append(t)
889
+ speech_ids = nn.utils.rnn.pad_sequence(
890
+ speech_ids_tensors,
891
+ batch_first=True,
892
+ padding_value=pad_id,
893
+ )
894
+ else:
895
+ raise TypeError(
896
+ "FunAudioChat speech_ids must be a Tensor or a sequence of Tensors "
897
+ f"(got {type(speech_ids)})"
898
+ )
899
+
900
+ if speech_attention_mask is None:
901
+ speech_attention_mask = speech_ids.ne(pad_id).to(dtype=torch.int64)
902
+
903
+ if not isinstance(speech_attention_mask, torch.Tensor):
904
+ if (
905
+ isinstance(speech_attention_mask, (list, tuple))
906
+ and len(speech_attention_mask) > 0
907
+ and all(isinstance(t, torch.Tensor) for t in speech_attention_mask)
908
+ ):
909
+ mask_tensors = []
910
+ for t in speech_attention_mask:
911
+ if t.dim() == 2 and t.shape[0] == 1:
912
+ t = t.squeeze(0)
913
+ if t.dim() != 1:
914
+ raise TypeError(
915
+ "FunAudioChat speech_attention_mask must be a 1D tensor "
916
+ f"per item (got shape={tuple(t.shape)})"
917
+ )
918
+ mask_tensors.append(t)
919
+ speech_attention_mask = nn.utils.rnn.pad_sequence(
920
+ mask_tensors,
921
+ batch_first=True,
922
+ padding_value=0,
923
+ )
924
+ else:
925
+ raise TypeError(
926
+ "FunAudioChat speech_attention_mask must be a Tensor or a "
927
+ f"sequence of Tensors (got {type(speech_attention_mask)})"
928
+ )
929
+
930
+ debug = os.getenv("VLLM_FUN_AUDIOCHAT_DEBUG", "") == "1"
931
+ if debug:
932
+ print(
933
+ f"[FunAudioChat] embed_multimodal speech_ids={tuple(speech_ids.shape)} "
934
+ f"speech_attention_mask={tuple(speech_attention_mask.shape)}",
935
+ flush=True,
936
+ )
937
+ attn_impl = getattr(
938
+ self.continuous_audio_tower.config, "_attn_implementation", None
939
+ )
940
+ print(
941
+ f"[FunAudioChat] audio_attn_impl={attn_impl}",
942
+ flush=True,
943
+ )
944
+ if hasattr(self.continuous_audio_tower, "conv1"):
945
+ conv1_w = self.continuous_audio_tower.conv1.weight
946
+ print(
947
+ f"[FunAudioChat] conv1_w_norm={float(conv1_w.norm().item()):.6g}",
948
+ flush=True,
949
+ )
950
+ try:
951
+ attn0 = self.continuous_audio_tower.layers[0].self_attn
952
+ q_norm = float(attn0.q_proj.weight.norm().item())
953
+ k_norm = float(attn0.k_proj.weight.norm().item())
954
+ v_norm = float(attn0.v_proj.weight.norm().item())
955
+ o_norm = float(attn0.out_proj.weight.norm().item())
956
+ print(
957
+ f"[FunAudioChat] attn0_q_norm={q_norm:.6g} "
958
+ f"k_norm={k_norm:.6g} "
959
+ f"v_norm={v_norm:.6g} "
960
+ f"o_norm={o_norm:.6g}",
961
+ flush=True,
962
+ )
963
+ except Exception:
964
+ pass
965
+ if isinstance(input_features, torch.Tensor):
966
+ print(
967
+ f"[FunAudioChat] input_features={tuple(input_features.shape)}",
968
+ flush=True,
969
+ )
970
+ if isinstance(feature_attention_mask, torch.Tensor):
971
+ print(
972
+ "[FunAudioChat] feature_attention_mask="
973
+ f"{tuple(feature_attention_mask.shape)}",
974
+ flush=True,
975
+ )
976
+
977
+ group_size = int(self.audio_tower.group_size)
978
+ speech_maxlen = int(speech_ids.shape[-1])
979
+
980
+ # Ensure token length is divisible by group_size.
981
+ target_len = ((speech_maxlen + group_size - 1) // group_size) * group_size
982
+ if target_len > speech_maxlen:
983
+ pad_id = int(self.audio_tower.padding_idx)
984
+ pad_len = target_len - speech_maxlen
985
+ speech_ids = nn.functional.pad(speech_ids, (0, pad_len), value=pad_id)
986
+ speech_attention_mask = nn.functional.pad(
987
+ speech_attention_mask, (0, pad_len), value=0
988
+ )
989
+ speech_maxlen = int(speech_ids.shape[-1])
990
+
991
+ continuous_audio_features = None
992
+ continuous_audio_output_lengths = None
993
+ if input_features is not None and feature_attention_mask is not None:
994
+ assert isinstance(input_features, torch.Tensor)
995
+ assert isinstance(feature_attention_mask, torch.Tensor)
996
+ continuous_audio_features, continuous_audio_output_lengths = (
997
+ self._get_continuous_audio_features(
998
+ input_features=input_features,
999
+ feature_attention_mask=feature_attention_mask,
1000
+ speech_maxlen=speech_maxlen,
1001
+ )
1002
+ )
1003
+
1004
+ if feature_exist_mask is None:
1005
+ feature_exist_mask = torch.ones(
1006
+ (speech_ids.shape[0],), dtype=torch.bool, device=speech_ids.device
1007
+ )
1008
+ assert isinstance(feature_exist_mask, torch.Tensor)
1009
+
1010
+ audio_features = self.audio_tower(
1011
+ speech_ids,
1012
+ continuous_audio_features=continuous_audio_features,
1013
+ continuous_audio_output_lengths=continuous_audio_output_lengths,
1014
+ feature_exist_mask=feature_exist_mask,
1015
+ )
1016
+
1017
+ _, audio_output_lengths = self.audio_tower._get_feat_extract_output_lengths(
1018
+ speech_attention_mask.sum(-1)
1019
+ )
1020
+ lengths = audio_output_lengths.tolist()
1021
+
1022
+ embeds = tuple(
1023
+ audio_features[i, : int(length)] for i, length in enumerate(lengths)
1024
+ )
1025
+ if debug:
1026
+ embed_lens = [int(t.shape[0]) for t in embeds]
1027
+ print(f"[FunAudioChat] embed_multimodal out_lens={embed_lens}", flush=True)
1028
+ if embeds:
1029
+ t0 = embeds[0]
1030
+ print(
1031
+ f"[FunAudioChat] embed0 dtype={t0.dtype} device={t0.device} "
1032
+ f"nan={bool(torch.isnan(t0).any())} "
1033
+ f"norm={float(t0.norm().item()):.6g}",
1034
+ flush=True,
1035
+ )
1036
+ dump_path = os.getenv("VLLM_FUN_AUDIOCHAT_DUMP_PATH", "")
1037
+ if (
1038
+ dump_path
1039
+ and speech_ids.shape[0] == 1
1040
+ and len(embeds) == 1
1041
+ and embed_lens[0] > 10
1042
+ ):
1043
+ if not os.path.exists(dump_path):
1044
+ np.save(dump_path, embeds[0].detach().float().cpu().numpy())
1045
+ print(f"[FunAudioChat] dumped embeds to {dump_path}", flush=True)
1046
+ cont_path = dump_path.replace(".npy", "_cont.npy")
1047
+ if continuous_audio_features is not None and not os.path.exists(
1048
+ cont_path
1049
+ ):
1050
+ np.save(
1051
+ cont_path,
1052
+ continuous_audio_features.detach().float().cpu().numpy(),
1053
+ )
1054
+ print(
1055
+ f"[FunAudioChat] dumped continuous to {cont_path}", flush=True
1056
+ )
1057
+ return embeds
1058
+
1059
+ def forward(
1060
+ self,
1061
+ input_ids: torch.Tensor,
1062
+ positions: torch.Tensor,
1063
+ intermediate_tensors: IntermediateTensors | None = None,
1064
+ inputs_embeds: torch.Tensor | None = None,
1065
+ **kwargs: object,
1066
+ ) -> torch.Tensor | IntermediateTensors:
1067
+ del kwargs
1068
+ if intermediate_tensors is not None:
1069
+ inputs_embeds = None
1070
+
1071
+ return self.language_model.model(
1072
+ input_ids,
1073
+ positions,
1074
+ intermediate_tensors,
1075
+ inputs_embeds=inputs_embeds,
1076
+ )
1077
+
1078
+ def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor | None:
1079
+ return self.language_model.compute_logits(hidden_states)
1080
+
1081
+ def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
1082
+ loader = AutoWeightsLoader(self, skip_prefixes=["audio_invert_tower."])
1083
+ return loader.load_weights(weights)
vllm/model_executor/models/registry.py
+4
@@ -312,6 +312,10 @@ _MULTIMODAL_MODELS = {
312
"ernie45_vl",
313
"Ernie4_5_VLMoeForConditionalGeneration",
314
),
315
+ "FunAudioChatForConditionalGeneration": (
316
+ "funaudiochat",
317
+ "FunAudioChatForConditionalGeneration",
318
+ ),
319
"FuyuForCausalLM": ("fuyu", "FuyuForCausalLM"),
320
"Gemma3ForConditionalGeneration": ("gemma3_mm", "Gemma3ForConditionalGeneration"), # noqa: E501
321
"Gemma3nForConditionalGeneration": (
vllm/multimodal/audio.py
+8
@@ -1,5 +1,6 @@
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+import math
4
from dataclasses import dataclass
5
from enum import Enum
6
from typing import Literal
@@ -195,6 +196,13 @@ class AudioResampler:
196
raise RuntimeError(
197
"Audio resampling is not supported when `target_sr` is not provided"
198
)
199
+ if math.isclose(
200
+ float(orig_sr),
201
+ float(self.target_sr),
202
+ rel_tol=0.0,
203
+ abs_tol=1e-6,
204
+ ):
205
+ return audio
206
if self.method == "librosa":
207
return resample_audio_librosa(
208
audio, orig_sr=orig_sr, target_sr=self.target_sr
vllm/transformers_utils/config.py
+1
@@ -77,6 +77,7 @@ _CONFIG_REGISTRY: dict[str, type[PretrainedConfig]] = LazyConfigDict(
77
deepseek_vl_v2="DeepseekVLV2Config",
78
deepseek_v32="DeepseekV3Config",
79
flex_olmo="FlexOlmoConfig",
80
+ funaudiochat="FunAudioChatConfig",
81
hunyuan_vl="HunYuanVLConfig",
82
isaac="IsaacConfig",
83
kimi_linear="KimiLinearConfig",
vllm/transformers_utils/configs/__init__.py
+4
@@ -22,6 +22,8 @@ _CLASS_TO_MODULE: dict[str, str] = {
22
"DotsOCRConfig": "vllm.transformers_utils.configs.dotsocr",
23
"EAGLEConfig": "vllm.transformers_utils.configs.eagle",
24
"FlexOlmoConfig": "vllm.transformers_utils.configs.flex_olmo",
25
+ "FunAudioChatConfig": "vllm.transformers_utils.configs.funaudiochat",
26
+ "FunAudioChatAudioEncoderConfig": "vllm.transformers_utils.configs.funaudiochat",
27
"HunYuanVLConfig": "vllm.transformers_utils.configs.hunyuan_vl",
28
"HunYuanVLTextConfig": "vllm.transformers_utils.configs.hunyuan_vl",
29
"HunYuanVLVisionConfig": "vllm.transformers_utils.configs.hunyuan_vl",
@@ -65,6 +67,8 @@ __all__ = [
67
"DotsOCRConfig",
68
"EAGLEConfig",
69
"FlexOlmoConfig",
70
+ "FunAudioChatConfig",
71
+ "FunAudioChatAudioEncoderConfig",
72
"HunYuanVLConfig",
73
"HunYuanVLTextConfig",
74
"HunYuanVLVisionConfig",
vllm/transformers_utils/configs/funaudiochat.py
new
+124
@@ -0,0 +1,124 @@
1
+# SPDX-License-Identifier: Apache-2.0
2
+# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+
4
+from __future__ import annotations
5
+
6
+from transformers import PretrainedConfig
7
+
8
+# NOTE: Temporary shim for FunAudioChat checkpoints.
9
+# These checkpoints use `model_type="funaudiochat"`, which is not currently
10
+# recognized by released Transformers, and the public checkpoint does not
11
+# provide an `auto_map` to enable `trust_remote_code=True`.
12
+# Remove this file once Transformers adds native support (or the checkpoint
13
+# provides an `auto_map`) and vLLM can rely on `AutoConfig.from_pretrained()`.
14
+
15
+
16
+class FunAudioChatAudioEncoderConfig(PretrainedConfig):
17
+ model_type = "funaudiochat_audio_encoder"
18
+
19
+ def __init__(
20
+ self,
21
+ _attn_implementation: str | None = None,
22
+ num_mel_bins: int = 128,
23
+ encoder_layers: int = 32,
24
+ encoder_attention_heads: int = 20,
25
+ encoder_ffn_dim: int = 5120,
26
+ d_model: int = 1280,
27
+ dropout: float = 0.0,
28
+ attention_dropout: float = 0.0,
29
+ activation_function: str = "gelu",
30
+ activation_dropout: float = 0.0,
31
+ scale_embedding: bool = False,
32
+ initializer_range: float = 0.02,
33
+ max_source_positions: int = 1500,
34
+ n_window: int = 100,
35
+ output_dim: int = 3584,
36
+ bos_token_id: int | None = None,
37
+ codebook_size: int | None = None,
38
+ continuous_features_mode: str = "replace",
39
+ crq_transformer_config: dict | None = None,
40
+ eos_token_id: int | None = None,
41
+ group_size: int = 5,
42
+ enable_audio_invert_tower: bool = True,
43
+ pad_token_id: int | None = None,
44
+ **kwargs,
45
+ ) -> None:
46
+ attn_impl = kwargs.pop("_attn_implementation", None) or _attn_implementation
47
+ super().__init__(**kwargs)
48
+ # Match HF default for attention implementation selection.
49
+ self._attn_implementation = attn_impl or "sdpa"
50
+
51
+ self.num_mel_bins = num_mel_bins
52
+ self.d_model = d_model
53
+ self.encoder_layers = encoder_layers
54
+ self.encoder_attention_heads = encoder_attention_heads
55
+ self.encoder_ffn_dim = encoder_ffn_dim
56
+ self.dropout = dropout
57
+ self.attention_dropout = attention_dropout
58
+ self.activation_function = activation_function
59
+ self.activation_dropout = activation_dropout
60
+ self.num_hidden_layers = encoder_layers
61
+ self.initializer_range = initializer_range
62
+ self.scale_embedding = scale_embedding
63
+ self.max_source_positions = max_source_positions
64
+ self.n_window = n_window
65
+ self.output_dim = output_dim
66
+
67
+ self.bos_token_id = bos_token_id
68
+ self.codebook_size = codebook_size
69
+ self.continuous_features_mode = continuous_features_mode
70
+ self.crq_transformer_config = crq_transformer_config
71
+ self.eos_token_id = eos_token_id
72
+ self.group_size = group_size
73
+ self.enable_audio_invert_tower = enable_audio_invert_tower
74
+ self.pad_token_id = pad_token_id
75
+
76
+
77
+class FunAudioChatConfig(PretrainedConfig):
78
+ model_type = "funaudiochat"
79
+ attribute_map = {
80
+ "audio_token_id": "audio_token_index",
81
+ }
82
+
83
+ def __init__(
84
+ self,
85
+ audio_config: PretrainedConfig | dict | None = None,
86
+ text_config: PretrainedConfig | dict | None = None,
87
+ audio_token_index: int = 151646,
88
+ ignore_index: int = -100,
89
+ hidden_size: int | None = None,
90
+ **kwargs,
91
+ ) -> None:
92
+ self.audio_token_index = audio_token_index
93
+ self.ignore_index = ignore_index
94
+
95
+ if isinstance(audio_config, dict):
96
+ audio_config.setdefault(
97
+ "model_type", FunAudioChatAudioEncoderConfig.model_type
98
+ )
99
+ audio_config = FunAudioChatAudioEncoderConfig(**audio_config)
100
+ elif audio_config is None:
101
+ audio_config = FunAudioChatAudioEncoderConfig()
102
+ self.audio_config = audio_config
103
+
104
+ if isinstance(text_config, dict):
105
+ # Default to qwen2 for backwards compatibility; FunAudioChat uses
106
+ # qwen3 in practice for recent checkpoints.
107
+ text_config.setdefault("model_type", "qwen2")
108
+ import transformers
109
+
110
+ text_cls = transformers.CONFIG_MAPPING[text_config["model_type"]]
111
+ text_config = text_cls(**text_config)
112
+ elif text_config is None:
113
+ import transformers
114
+
115
+ text_config = transformers.CONFIG_MAPPING["qwen2"]()
116
+ self.text_config = text_config
117
+
118
+ self.hidden_size = (
119
+ int(self.text_config.hidden_size)
120
+ if hidden_size is None
121
+ else int(hidden_size)
122
+ )
123
+
124
+ super().__init__(**kwargs)