VoiceAuthWorld-Ebase / vb /adapter.py
LeyanW's picture
Add files using upload-large-folder tool
27e0680 verified
Raw History Blame Contribute Delete
6.73 kB
"""Offline multimodal vLLM adapter with audio coverage checks."""
import time
from .common import file_hash
class VLLMAdapter:
def __init__(self,name,configuration):
from transformers import AutoProcessor
from vllm import LLM,SamplingParams
self.config=configuration
options={k:v for k,v in self.config.items() if k!='name'}
self.processor=AutoProcessor.from_pretrained(options['model'],local_files_only=True)
self.llm=LLM(**options)
self.params=SamplingParams(temperature=0,max_tokens=1024,seed=1701)
def generate(self,inputs):
import soundfile as sf
if inputs.get('protocol') == 'shared-json-v1':
from .prompt_protocol import messages_for_prompt
messages = messages_for_prompt(inputs)
prompt=self.processor.apply_chat_template(messages,tokenize=False,
add_generation_prompt=True,enable_thinking=False)
# Check that the model-specific template actually retained every block in order.
position = 0
for message in messages:
for part in message['content']:
expected = (self.processor.audio_token if part['type'] == 'audio'
else part['text'].strip())
start = prompt.find(expected, position)
if start < 0:
raise ValueError('Chat template dropped or reordered trusted input or dialogue')
position = start + len(expected)
if any(path in prompt for path in inputs['audio_paths']):
raise ValueError('Chat template exposed an audio filename to the model')
else:
prompt=self.processor.apply_chat_template(inputs['messages'],tools=inputs['tools'],tokenize=False,
add_generation_prompt=True,enable_thinking=False)
# The Qwen2.5 checkpoint's template ignores the tools argument.
# Add the shared runner's protocol explicitly to its system message.
if self.config['name']=='qwen25-7b' and not inputs.get('protocol'):
from copy import deepcopy
import json
messages=deepcopy(inputs['messages'])
messages[0]['content'][0]['text'] += (
'\nAvailable functions (JSON Schema):\n'+json.dumps(inputs['tools'],ensure_ascii=False)
+'\nFor each function call, output <tool_call>{"name":"function_name","arguments":{}}</tool_call> with the actual name and arguments.')
prompt=self.processor.apply_chat_template(messages,tokenize=False,add_generation_prompt=True)
audio_token = getattr(self.processor, 'audio_token', None)
if inputs['audio_paths'] and (not audio_token or prompt.count(audio_token) != len(inputs['audio_paths'])):
raise ValueError('Chat template must preserve every enrollment and user audio placeholder')
audio=[];audit=[]
for path in inputs['audio_paths']:
x,sr=sf.read(path,dtype='float32')
if sr!=16000 or x.ndim!=1:raise ValueError('expected complete mono 16 kHz audio')
audio.append((x,sr));audit.append({'path':path,'samples':len(x),'sample_rate':sr,'sha256':file_hash(path)})
# Audit actual processor coverage once per unique waveform collection. Audio lengths
# must agree with the full WAV, not merely with a filename or nominal duration.
coverage=[]
if audio:
import numpy as np
features=self.processor.feature_extractor([a[0] for a in audio],sampling_rate=16000,
padding=True,truncation=False,return_attention_mask=True,return_tensors='np')
masks=features.get('attention_mask')
if masks is None:raise ValueError('processor exposes no audio coverage mask')
hop=self.processor.feature_extractor.hop_length
for entry,mask in zip(audit,masks):
frames=int(np.sum(mask));expected=(entry['samples']+hop-1)//hop
if abs(frames-expected)>2:raise ValueError(f'audio preprocessing truncation: {frames} vs {expected} frames')
coverage.append({'samples':entry['samples'],'feature_frames':frames,'expected_frames':expected})
del features
item={'prompt':prompt}
if audio:
item['multi_modal_data']={'audio':audio}
if self.config['name']=='qwen25-7b':
# This processor forces max_length padding. Its default length
# makes mixed short enrollments and long recordings ragged.
# Use the longest real item, retaining the original masks.
longest=max(len(waveform) for waveform,_ in audio)
item['mm_processor_kwargs']={'audio_kwargs':{
'max_length':((longest+hop-1)//hop)*hop,'truncation':False}}
started=time.monotonic()
result=self.llm.generate([item],self.params,use_tqdm=False)[0]
observed_audio_tokens = 0
if audio:
tokenizer = self.processor.tokenizer
audio_token = getattr(self.processor, 'audio_token', None)
if not audio_token:
raise ValueError('Processor does not expose its audio placeholder')
token_id = tokenizer.convert_tokens_to_ids(audio_token)
observed_audio_tokens = result.prompt_token_ids.count(token_id)
if self.config['name'] == 'qwen25-7b':
encode_frames = lambda frames: ((frames + 1) // 2) // 2
elif self.config['name'].startswith('qwen3-'):
def encode_frames(frames):
windows, remainder = divmod(frames, 100)
return windows * 13 + (remainder + 7) // 8
else:
encode_frames = None
if observed_audio_tokens < len(audio):
raise ValueError('Model input is missing audio tokens')
if encode_frames is not None:
expected_min = sum(encode_frames(max(0, item['expected_frames'] - 2)) for item in coverage)
expected_max = sum(encode_frames(item['expected_frames'] + 2) for item in coverage)
if not expected_min <= observed_audio_tokens <= expected_max:
raise ValueError(f'vLLM audio coverage mismatch: {observed_audio_tokens} tokens, expected {expected_min}–{expected_max}')
output=result.outputs[0]
return output.text,output.finish_reason,{'prompt':prompt,'audio':audit,'feature_coverage':coverage,'prompt_tokens':len(result.prompt_token_ids),
'audio_prompt_tokens':observed_audio_tokens,'generated_tokens':len(output.token_ids),'elapsed_s':time.monotonic()-started}