audio-layers-live / model_runtime.py
ChristophSchuhmann's picture
Add live audio-only foreground/background proposals and recurrent CLAP2 alignment
2799d65 verified
Raw History Blame Contribute Delete
12.1 kB
"""Audio-only caption proposers. All model code and weights are pinned."""
import gc,json,os,re,shutil,time,threading
from pathlib import Path
import numpy as np
import torch
from scipy.signal import resample_poly
from huggingface_hub import snapshot_download
from runtime_isolation import libraries
from candidate_inventory import deduplicate
ROOT=Path(__file__).parent;SPECS=json.loads((ROOT/'models.json').read_text());PROMPT=(ROOT/'prompt.txt').read_text()
CACHE=Path(os.getenv('LAYER_MODEL_CACHE','/tmp/sound-layer-models'));CACHE.mkdir(parents=True,exist_ok=True)
LOCK=threading.RLock();DEFAULT=None
LABELS={'moss_thinking':'MOSS Audio 8B Thinking','moss_instruct':'MOSS Audio 8B Instruct','minicpm':'MiniCPM-o 4.5','salmonn':'SALMONN 2 Pro 8B','lfm_direct':'LFM3 Audio · direct','lfm_thinking':'LFM3 Audio · bounded thinking'}
def ensure_weights(key):
spec=SPECS[key];name='lfm' if key.startswith('lfm') else key
override=json.loads(os.getenv('LAYER_MODEL_PATHS','{}')).get(name)
if override:return override,0.
begin=time.perf_counter()
# Retain the default plus only one optional checkpoint. Never touch external caches.
optional=CACHE/'optional';optional.mkdir(exist_ok=True)
if key!='moss_thinking':
for other in optional.iterdir():
if other.name!=name and other.is_dir():shutil.rmtree(other)
folder=CACHE/'default' if key=='moss_thinking' else optional/name
path=snapshot_download(spec['repo'],revision=spec['revision'],allow_patterns=['*.safetensors','*.json','*.py','*.jinja','*.txt','*.model'],cache_dir=str(folder),max_workers=4)
return path,time.perf_counter()-begin
def load_model(key,path,device='cuda'):
start=time.perf_counter();spec=SPECS[key]
with libraries(spec['runtime']):
if key.startswith('moss'):
from src.modeling_moss_audio import MossAudioModel
from src.processing_moss_audio import MossAudioProcessor
model=MossAudioModel.from_pretrained(path,dtype=torch.bfloat16,attn_implementation='sdpa').eval().to(device)
processor=MossAudioProcessor.from_pretrained(path,enable_time_marker=True)
elif key=='minicpm':
from transformers import AutoModel
model=AutoModel.from_pretrained(path,trust_remote_code=True,attn_implementation='sdpa',torch_dtype=torch.bfloat16,init_vision=False,init_audio=True,init_tts=False).eval().to(device);processor=None
elif key=='salmonn':
from qwenvl.model.modeling_qwen3_vl import Qwen3VLForConditionalGeneration
from transformers import AutoTokenizer,WhisperFeatureExtractor
model=Qwen3VLForConditionalGeneration.from_pretrained(path,attn_implementation='sdpa',torch_dtype=torch.bfloat16).eval().to(device)
processor=(AutoTokenizer.from_pretrained(path,use_fast=False),WhisperFeatureExtractor(feature_size=128,sampling_rate=16000,hop_length=160,chunk_length=30))
else:
from transformers import AutoModelForMultimodalLM,AutoProcessor
model=AutoModelForMultimodalLM.from_pretrained(path,dtype=torch.bfloat16,device_map=device,trust_remote_code=True,attn_implementation='sdpa').eval()
processor=AutoProcessor.from_pretrained(path,trust_remote_code=True,fix_mistral_regex=False)
return {'model':model,'processor':processor,'load_seconds':time.perf_counter()-start,'device':device}
def preload_default(device='cuda'):
global DEFAULT
path,_=ensure_weights('moss_thinking');DEFAULT=load_model('moss_thinking',path,device);return DEFAULT
class Parsed(dict):
format_repair=False
def parse(text):
decoder=json.JSONDecoder()
for m in re.finditer(r'\{',text):
try:obj,_=decoder.raw_decode(text[m.start():])
except json.JSONDecodeError:continue
if not isinstance(obj,dict) or set(obj)!={'foreground','background'}:continue
if all(isinstance(v,list) and len(v)<=40 and all(isinstance(s,str) and 0<len(s.strip())<=1500 for s in v) for v in obj.values()):return Parsed({k:[' '.join(s.split()) for s in v] for k,v in obj.items()})
# Repair syntax only. Every recovered string must occur literally in the final
# response, and both layer keys must have been explicitly present.
from json_repair import repair_json
try:
objects=[repair_json(text,return_objects=True)]
keys=list(re.finditer(r'"(foreground|background)"\s*:\s*\[',text))
if len(keys)==2 and len({m[1] for m in keys})==2:
# A missing quote at the end of one list must not swallow the next key.
separate={}
for i,m in enumerate(keys):
part=text[m.end()-1:keys[i+1].start() if i+1<len(keys) else len(text)].strip().rstrip(',} \n')
separate[m[1]]=repair_json(part,return_objects=True)
objects.append(separate)
for obj in objects:
if isinstance(obj,dict) and set(obj)=={'foreground','background'} and all(re.search(r'"'+k+r'"\s*:',text) for k in obj) and all(isinstance(v,list) and len(v)<=40 and all(isinstance(s,str) and 0<len(s.strip())<=1500 and s in text for s in v) for v in obj.values()):
result=Parsed({k:[' '.join(s.split()) for s in v] for k,v in obj.items()});result.format_repair=True;return result
except Exception:pass
raise ValueError('The model did not return a complete foreground/background JSON answer. Try generating again or choose another proposer. No invented fallback captions were substituted.')
def propose(key,pcm32,wav_path,path,token_budget=4096):
spec=SPECS[key];start=time.perf_counter();handle=DEFAULT if key=='moss_thinking' else load_model(key,path)
if handle is None:raise RuntimeError('The default model has not loaded yet.')
model=handle['model'];processor=handle['processor'];device=handle['device'];w=resample_poly(pcm32,1,2).astype('float32');meta={}
try:
with libraries(spec['runtime']),torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):
torch.manual_seed(20261114);torch.cuda.synchronize();t=time.perf_counter()
if key.startswith('moss'):
thinking=key=='moss_thinking';text=processor._build_default_prompt(PROMPT,has_audio=True)+('<think>\n' if thinking else '')
inputs=processor(text=text,audios=[w],return_tensors='pt').to(device);inputs['audio_data']=inputs['audio_data'].to(torch.bfloat16);inputs['audio_input_mask']=inputs['input_ids']==processor.audio_token_id
ni=inputs['input_ids'].shape[1]
if ni+token_budget>model.config.language_config.max_position_embeddings:raise ValueError('Audio and output budget exceed this model context.')
ids=model.generate(**inputs,max_new_tokens=token_budget,do_sample=thinking,**({'temperature':.6,'top_p':.95,'top_k':20} if thinking else {}))[0,ni:]
raw=processor.decode(ids,skip_special_tokens=True);final=raw.rsplit('</think>',1)[-1];meta.update(generated_tokens=len(ids),reasoning_completed_naturally=(not thinking or '</think>' in raw))
if len(ids)>=token_budget or not meta['reasoning_completed_naturally']:raise ValueError('Generation reached its token budget before completing the JSON answer. Increase the output budget or try again.')
elif key=='minicpm':
raw=model.chat(msgs=[{'role':'user','content':[PROMPT,w]}],max_new_tokens=token_budget,max_inp_length=16384,do_sample=False,enable_thinking=False,use_tts_template=True,generate_audio=False)
final=raw.rsplit('</think>',1)[-1];meta.update(generated_tokens=len(model.processor.tokenizer.encode(raw,add_special_tokens=False)),token_count_note='retokenized decoded text')
elif key=='salmonn':
tokenizer,fe=processor;chunks=[w[k:k+480000] for k in range(0,len(w),480000)]
features=torch.cat([fe(a,sampling_rate=16000,return_tensors='pt')['input_features'] for a in chunks]).to(device)
ids=tokenizer.apply_chat_template([{'role':'system','content':'You are a helpful assistant.'},{'role':'user','content':'<|audio_pad|>'*(60*len(chunks))+'\n'+PROMPT}],add_generation_prompt=True,return_tensors='pt').to(device)
out=model.generate(input_ids=ids,attention_mask=torch.ones_like(ids),audio_feature=features,max_new_tokens=token_budget,do_sample=False)[0,ids.shape[1]:]
raw=tokenizer.decode(out,skip_special_tokens=True);final=raw.rsplit('</think>',1)[-1];meta.update(generated_tokens=len(out),audio_chunks=len(chunks))
else:
thinking=key=='lfm_thinking';prefix='{"foreground": ['
msgs=[{'role':'system','content':'Describe only audible sounds in English; do not transcribe speech. Return the requested JSON.'},{'role':'user','content':[{'type':'audio','audio':wav_path},{'type':'text','text':PROMPT}]},{'role':'assistant','content':'<think>' if thinking else '<think></think>\n'+prefix}]
inputs=processor.apply_chat_template(msgs,continue_final_message=True,tokenize=True,return_dict=True,return_tensors='pt').to(device);ni=inputs['input_ids'].shape[1]
kwargs=dict(suppress_mixed=True,suppress_audio_out=True,return_dict_in_generate=True,do_sample=True,temperature=.4,top_p=.9,top_k=20,use_cache=True,repetition_penalty=1.1,text_repetition_window=2048)
reasonids=[];reasontext='';bounded=False;reason_budget=min(2048,max(1024,token_budget//2));answer_budget=min(2048,token_budget)
if thinking:
end=processor.tokenizer.encode('</think>',add_special_tokens=False);eos=model.generation_config.eos_token_id;eos=[eos] if isinstance(eos,int) else list(eos or [])
reason=model.generate(**inputs,max_new_tokens=reason_budget,eos_token_id=end+eos,**kwargs)
reasonids=reason.sequences[0,ni:].tolist();reasontext=processor.decode(reasonids,skip_special_tokens=True);natural=reasonids[-len(end):]==end;bounded=not natural
suffix=('' if natural else '</think>')+'\n'+prefix
inputs['input_ids']=torch.cat([reason.sequences,torch.tensor([processor.tokenizer.encode(suffix,add_special_tokens=False)],device=device)],1);inputs['attention_mask']=torch.ones_like(inputs['input_ids'])
nf=inputs['input_ids'].shape[1];answer=model.generate(**inputs,max_new_tokens=answer_budget,**kwargs);ids=answer.sequences[0,nf:]
raw=prefix+processor.decode(ids,skip_special_tokens=True);final=raw
meta.update(generated_tokens=len(reasonids)+len(ids),thinking_tokens=len(reasonids),raw_reasoning=reasontext,reasoning_budget_enforced=bounded,reasoning_budget_tokens=reason_budget if thinking else 0,answer_budget_tokens=answer_budget)
if len(ids)>=answer_budget:raise ValueError('LFM reached the final-answer token limit. Try again or use MOSS Thinking.')
torch.cuda.synchronize();elapsed=time.perf_counter()-t
parsed=parse(final)
result={'model':spec['repo'],'revision':spec['revision'],'variant':key,'label':LABELS[key],'prompt':PROMPT,'raw_output':raw,'final_text':final,'captions':parsed,'format_repair':parsed.format_repair,'elapsed_seconds':elapsed,'load_seconds':handle['load_seconds'] if key!='moss_thinking' else 0.,'total_seconds':time.perf_counter()-start,'output_token_budget':token_budget,'device':torch.cuda.get_device_name(),'input_modality':'audio only','success':True,**meta}
# Explicit absence statements are not audible sound events.
result['original_captions']={k:list(v) for k,v in result['captions'].items()}
for lane in result['captions']:
absent={f'no {lane}',f'no {lane} sounds',f'no distinct {lane} sounds',f'no audible {lane} sounds',f'no discernible {lane} sounds'}
result['captions'][lane]=[c for c in result['captions'][lane] if c.lower().strip().rstrip('.') not in absent]
return deduplicate(result)
finally:
if key!='moss_thinking':del handle,model,processor;gc.collect();torch.cuda.empty_cache()