Upload audact-final
Browse filesFiles changed (13)
- README.md+35-10
- audact/__init__.py+16-2
- audact/decode.py+4-68
- audact/onnx_caller.pyAdded+84
- audact/render.pyAdded+80
- inference_onnx.pyAdded+9
- onnx/audio_encoder.onnxAdded+3
- onnx/decoder_step.onnxAdded+3
- onnx/tool_encoder.onnxAdded+3
- onnx_fp32/audio_encoder.onnxAdded+3
- onnx_fp32/decoder_step.onnxAdded+3
- onnx_fp32/tool_encoder.onnxAdded+3
- requirements-onnx.txtAdded+4
16 unmodified lines1718192021222317 unmodified lines4142434445464748495062 unmodified lines11311411511611711811912012112212312412512612716 unmodified lines# Audact (draft)**Audact** (audio + act): speak a command, get a tool call. Speech plus a list of tools in, one tool call (or no call) out, with **no transcript in between**.About 52.6M parameters (211 MB in fp32). English, up to 10 tools per request, one call or none, arguments that are enums,numbers or short strings. Built to work on **tools it never saw in training**.> Draft release. Scored once on three frozen test sets (below) and on our validation sets. Not for17 unmodified lines## Usage```bashhf download KishaanG/audact --local-dir audact-model && cd audact-modelpip install -r requirements.txt # needs NeMo for FastConformer's architecture (base weights download once)python inference.py command.wav tools.json # 16 kHz mono audio; a JSON list of tools```Or from Python, inside that folder:62 unmodified linesdescriptions, tool lists that don't fit) were found by looking at (d)'s inputs, not its answers.Two of its 12 tool names also appear in public datasets we trained on; those examples are now excluded.### Speed (one CPU thread)| 100 SLURP validation clips, per clip | This model | NeuDecide ||---|---|---|| Mean / median / slowest 5% | 1.49 s / 1.41 s / 2.35 s | **0.76 s / 0.75 s / 1.02 s** || Runs as | PyTorch, 32-bit weights (this release) | ONNX, 4-bit weights (its release) |This model is about 2x slower for now. An ONNX version with smaller weights is in progress; its speechencoder already runs at 11 ms per second of audio on one CPU thread.### Validation sets (every clip; used for every decision)16 unmodified lines171819202122232417 unmodified lines4243444546474849505152535455565758596061626364656662 unmodified lines12913013113213313413513613713813914014114214314414514614714814915015115216 unmodified lines# Audact (draft)**Audact** (audio + act): speak a command, get a tool call. Speech plus a list of tools in, one tool call (or no call) out, with **no transcript in between**.About 52.6M parameters; runs on one CPU thread with ONNX Runtime in about half a second per command (int8,72 MB). English, up to 10 tools per request, one call or none, arguments that are enums,numbers or short strings. Built to work on **tools it never saw in training**.> Draft release. Scored once on three frozen test sets (below) and on our validation sets. Not for17 unmodified lines## UsageFastest and lightest, with ONNX Runtime (no PyTorch needed):```bashhf download KishaanG/audact --local-dir audact-model && cd audact-modelpip install -r requirements-onnx.txtpython inference_onnx.py command.wav tools.json # 16 kHz mono audio; a JSON list of tools``````pythonfrom audact.onnx_caller import AudactONNXcaller = AudactONNX(".", threads=1) # int8 graphs in onnx/; onnx_dir="onnx_fp32" for 32-bit```With PyTorch (needs NeMo for FastConformer's architecture; base weights download once):```bashpip install -r requirements.txtpython inference.py command.wav tools.json```Or from Python, inside that folder:62 unmodified linesdescriptions, tool lists that don't fit) were found by looking at (d)'s inputs, not its answers.Two of its 12 tool names also appear in public datasets we trained on; those examples are now excluded.### Speed and memory (one CPU thread)Same laptop CPU, same 100 SLURP validation clips, one thread, each model as released:| | This model, ONNX int8 (default) | This model, ONNX 32-bit | NeuDecide, ONNX 4-bit ||---|---|---|---|| Time per command, mean / slowest 5% | **0.55 s / 0.74 s** | 0.67 s / 0.83 s | 0.74 s / 1.01 s || Peak memory | **380 MB** | 774 MB | 567 MB || Model files | 72 MB | 245 MB | **43 MB** |The 32-bit ONNX graphs give the same answers as the PyTorch model (150 of 150 validation clips); thetest results above are theirs. int8 costs a little accuracy, measured on validation:| Validation, clips needing a call: right tool / exact match / false triggers | 32-bit | int8 ||---|---|---|| SLURP (real voices) | 51.4% / 26.1% / 36.8% | 49.2% / 24.9% / 32.9% || Synthetic, unseen tools | 86.5% / 41.9% / 18.8% | 85.1% / 40.0% / 14.5% || Chatty synthetic, unseen tools | 87.1% / 41.8% / 14.7% | 86.4% / 40.9% / 13.3% |### Validation sets (every clip; used for every decision)
123from .caller import Audact__all__ = ["Audact"]1234567891011121314151617"""Audact: speech + a tool list in, one tool call (or none) out.Audact PyTorch caller (needs torch and NeMo)AudactONNX ONNX Runtime caller (needs only onnxruntime, sentencepiece, numpy, soundfile)Both are imported only when first used, so the ONNX caller never loads PyTorch."""__all__ = ["Audact", "AudactONNX"]def __getattr__(name):if name == "Audact":from .caller import Audactreturn Audactif name == "AudactONNX":from .onnx_caller import AudactONNXreturn AudactONNXraise AttributeError(name)
7 unmodified lines89101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676821 unmodified lines909192939495969798991001011021031041051061071087 unmodified lines"""from __future__ import annotationsimport jsonimport reimport torchfrom .needle import EOS, MAX_INPUT_TOKENS, TOOL_CALL, TOOLSdef tools_json(obj) -> str:return json.dumps(obj, separators=(",", ":")) # no spaces: the only form Needle reads welldef compact_tools(tools: list[dict]) -> list[dict]:"""Drop each argument's description, keep type, enum and required."""out = []for tool in tools:params = tool.get("parameters", {})props = {a: {k: v for k, v in spec.items() if k != "description"} for a, spec in params.get("properties", {}).items()}out.append({**tool, "parameters": {**params, "properties": props}})return outSHORTEN_WORDS = (20, 10, 4)def shorten_tools(tools: list[dict], max_words: int) -> list[dict]:"""Each tool's description cut to its first sentence and at most max_words words."""out = []for t in tools:first = re.split(r"(?<=[.!?])\s", t.get("description", "").strip(), maxsplit=1)[0]out.append({**t, "description": " ".join(first.split()[:max_words])})return outdef render_tools(tools: list[dict], prefix_len: int, sp) -> tuple[list[int], list[str]]:"""<tools> + JSON token ids that fit next to prefix_len audio frames, and the names kept."""room = MAX_INPUT_TOKENS - prefix_lencompact = compact_tools(tools)for rendered in [tools, compact] + [shorten_tools(compact, n) for n in SHORTEN_WORDS]:ids = [TOOLS] + sp.encode(tools_json(rendered))if len(ids) <= room:return ids, [t["name"] for t in tools]kept = shorten_tools(compact, SHORTEN_WORDS[-1])while kept:kept = kept[:-1]ids = [TOOLS] + sp.encode(tools_json(kept))if len(ids) <= room:return ids, [t["name"] for t in kept]raise ValueError("the audio is too long to leave room for any tool")def allowed_starts(names: list[str], sp) -> list[list[int]]:starts = [[TOOL_CALL] + sp.encode("[]") + [EOS]] # no callstarts += [[TOOL_CALL] + sp.encode(f'[{{"name":"{n}","arguments') for n in names]return starts@torch.inference_mode()21 unmodified linesout.append(token)ids = torch.cat([ids, torch.tensor([[token]], device=memory.device)], dim=1)return outdef parse_answer(ids: list[int], sp) -> dict | None:"""Answer ids -> {"name": ..., "arguments": {...}}, None for no call, or {"invalid": text}."""text = sp.decode([i for i in ids if i > TOOLS])try:calls = json.loads(text)except json.JSONDecodeError:return {"invalid": text}if calls == []:return Noneif isinstance(calls, list) and isinstance(calls[0], dict) and isinstance(calls[0].get("name"), str):args = calls[0].get("arguments") or {}if isinstance(args, dict):return {"name": calls[0]["name"], "arguments": args}return {"invalid": text}7 unmodified lines89101112131415161718192021 unmodified lines4243447 unmodified lines"""from __future__ import annotationsimport torchfrom . import needle as _needlefrom .render import (EOS, MAX_INPUT_TOKENS, SHORTEN_WORDS, TOOL_CALL, TOOLS, allowed_starts, compact_tools, # noqa: F401parse_answer, render_tools, shorten_tools, tools_json)assert (EOS, TOOL_CALL, TOOLS, MAX_INPUT_TOKENS) == (_needle.EOS, _needle.TOOL_CALL, _needle.TOOLS, _needle.MAX_INPUT_TOKENS)@torch.inference_mode()21 unmodified linesout.append(token)ids = torch.cat([ids, torch.tensor([[token]], device=memory.device)], dim=1)return out
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384"""Audact on ONNX Runtime: speech + a tool list in, one call (or none) out, with no PyTorch or NeMo.
Three graphs (Phase 6), each run only as often as it must: audio_encoder.onnx once per clip waveform (1, S) -> audio vectors (1, T_a, 512) tool_encoder.onnx once per clip + tools audio vectors + tool ids -> cross-attention keys/values decoder_step.onnx once per token chunk new tokens + cache -> next-token scores + longer cache
Decoding is the same whole-name scoring as the PyTorch caller: "no call" and every listed tool's name areeach fed to the decoder as one chunk and scored by the sum of their tokens' log-probabilities; the bestone wins, and the arguments are then written greedily, one token at a time, reusing the cache."""from __future__ import annotations
from pathlib import Path
import numpy as np
from .render import EOS, allowed_starts, parse_answer, render_tools
RATE = 16_000LAYERS, KV_HEADS, HEAD_DIM = 8, 4, 64
def _log_softmax(x: np.ndarray) -> np.ndarray: m = x.max(axis=-1, keepdims=True) return x - m - np.log(np.exp(x - m).sum(axis=-1, keepdims=True))
class AudactONNX: def __init__(self, folder: str | Path, threads: int = 1, onnx_dir: str | Path | None = None, low_memory: bool = True) -> None: """folder: a downloaded copy of the model (tokenizer.model); onnx_dir: where the three graphs are (default folder/onnx: int8; folder/onnx_fp32 is the unquantized set). threads: CPU threads for ONNX Runtime (1 = the phone-class setting). low_memory: no memory pool (int8, 1 thread: peak 380 MB instead of 491 MB, about 5% slower).""" import onnxruntime as ort import sentencepiece as spm
folder = Path(folder) graphs = Path(onnx_dir) if onnx_dir else folder / "onnx" opts = ort.SessionOptions() opts.intra_op_num_threads, opts.inter_op_num_threads = threads, 1 if low_memory: opts.enable_cpu_mem_arena, opts.enable_mem_pattern = False, False load = lambda name: ort.InferenceSession(str(graphs / name), opts, providers=["CPUExecutionProvider"]) self.audio, self.tools, self.step = load("audio_encoder.onnx"), load("tool_encoder.onnx"), load("decoder_step.onnx") self.sp = spm.SentencePieceProcessor(model_file=str(folder / "tokenizer.model"))
def _step(self, ids: list[int], cache, cross): logits, k, v = self.step.run(None, {"ids": np.array([ids], dtype=np.int64), "past_k": cache[0], "past_v": cache[1], "cross_k": cross[0], "cross_v": cross[1]}) return logits[0], (k, v) # (n, 8192), cache extended by n
def __call__(self, audio, tools: list[dict], max_new_tokens: int = 96) -> dict | None: """audio: a path to a 16 kHz mono file, or float samples in [-1, 1]. tools: up to 10 JSON-Schema functions. Returns {"name", "arguments"}, None for no call, or {"invalid": text}.""" if isinstance(audio, (str, Path)): import soundfile as sf audio, rate = sf.read(audio, dtype="float32", always_2d=True) assert rate == RATE, f"expected {RATE} Hz audio, got {rate}" audio = audio[:, 0] wave = np.asarray(audio, dtype=np.float32)[None] # (1, S) vectors = self.audio.run(None, {"waveform": wave})[0] # (1, T_a, 512) tool_ids, kept = render_tools(tools, vectors.shape[1], self.sp) cross = self.tools.run(None, {"audio_vectors": vectors, "tool_ids": np.array([tool_ids], dtype=np.int64)}) empty = np.zeros((LAYERS, 1, KV_HEADS, 0, HEAD_DIM), dtype=np.float32)
best, best_score, best_cache = None, -np.inf, None for start in allowed_starts(kept, self.sp): # no call first, then each listed tool's name logits, cache = self._step([EOS] + start[:-1], (empty, empty), cross) logp = _log_softmax(logits.astype(np.float64)) # (n, 8192) score = float(logp[np.arange(len(start)), start].sum()) if score > best_score: # strict: on a tie the earlier start wins, like argmax best, best_score, best_cache = start, score, cache if best[-1] == EOS: return parse_answer(best[:-1], self.sp) # no call out, cache, token = list(best), best_cache, best[-1] for _ in range(max_new_tokens): # the arguments, greedily logits, cache = self._step([token], cache, cross) token = int(logits[-1].argmax()) if token == EOS: break out.append(token) return parse_answer(out, self.sp)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980"""Tool-list rendering, decoding starts and answer parsing: pure Python (no PyTorch), shared by thePyTorch caller (decode.py) and the ONNX caller (onnx_caller.py), so both read tool lists the same waytraining did (tests/test_render_match.py).
Rendering: full tool definitions if audio frames + <tools> + JSON fit in 1,024 positions, else compact(argument descriptions dropped), else each tool description shortened (first sentence, at most 20, then10, then 4 words), and only then whole tools are dropped from the end of the list until it fits."""from __future__ import annotations
import jsonimport re
PAD, EOS, TOOL_CALL, TOOLS = 0, 1, 4, 5 # Needle's special token ids (tokenizer.model)MAX_INPUT_TOKENS = 1024 # Needle's encoder reads at most this many positions
def tools_json(obj) -> str: return json.dumps(obj, separators=(",", ":")) # no spaces: the only form Needle reads well
def compact_tools(tools: list[dict]) -> list[dict]: """Drop each argument's description, keep type, enum and required.""" out = [] for tool in tools: params = tool.get("parameters", {}) props = {a: {k: v for k, v in spec.items() if k != "description"} for a, spec in params.get("properties", {}).items()} out.append({**tool, "parameters": {**params, "properties": props}}) return out
SHORTEN_WORDS = (20, 10, 4)
def shorten_tools(tools: list[dict], max_words: int) -> list[dict]: """Each tool's description cut to its first sentence and at most max_words words.""" out = [] for t in tools: first = re.split(r"(?<=[.!?])\s", t.get("description", "").strip(), maxsplit=1)[0] out.append({**t, "description": " ".join(first.split()[:max_words])}) return out
def render_tools(tools: list[dict], prefix_len: int, sp) -> tuple[list[int], list[str]]: """<tools> + JSON token ids that fit next to prefix_len audio frames, and the names kept.""" room = MAX_INPUT_TOKENS - prefix_len compact = compact_tools(tools) for rendered in [tools, compact] + [shorten_tools(compact, n) for n in SHORTEN_WORDS]: ids = [TOOLS] + sp.encode(tools_json(rendered)) if len(ids) <= room: return ids, [t["name"] for t in tools] kept = shorten_tools(compact, SHORTEN_WORDS[-1]) while kept: kept = kept[:-1] ids = [TOOLS] + sp.encode(tools_json(kept)) if len(ids) <= room: return ids, [t["name"] for t in kept] raise ValueError("the audio is too long to leave room for any tool")
def allowed_starts(names: list[str], sp) -> list[list[int]]: starts = [[TOOL_CALL] + sp.encode("[]") + [EOS]] # no call starts += [[TOOL_CALL] + sp.encode(f'[{{"name":"{n}","arguments') for n in names] return starts
def parse_answer(ids: list[int], sp) -> dict | None: """Answer ids -> {"name": ..., "arguments": {...}}, None for no call, or {"invalid": text}.""" text = sp.decode([i for i in ids if i > TOOLS]) try: calls = json.loads(text) except json.JSONDecodeError: return {"invalid": text} if calls == []: return None if isinstance(calls, list) and isinstance(calls[0], dict) and isinstance(calls[0].get("name"), str): args = calls[0].get("arguments") or {} if isinstance(args, dict): return {"name": calls[0]["name"], "arguments": args} return {"invalid": text}123456789"""Example without PyTorch: python inference_onnx.py clip.wav tools.json (16 kHz mono audio; a JSON list of tools)Needs only requirements-onnx.txt. Uses the int8 graphs in onnx/ on one CPU thread."""import jsonimport sys
from audact.onnx_caller import AudactONNX
caller = AudactONNX(".", threads=1)print(json.dumps(caller(sys.argv[1], json.load(open(sys.argv[2])))))123version https://git-lfs.github.com/spec/v1oid sha256:dca0233a5f68385bdc65662d737573f463951ee9211849fe7487c81c293767a8size 38866822123version https://git-lfs.github.com/spec/v1oid sha256:b186bb1aaa541314d286d7fb6bc39d91404ee114bab79cca62f950a27c42357bsize 19437874123version https://git-lfs.github.com/spec/v1oid sha256:641a1f50c9644f154f5ca06fdf1c4cfbe3b2bddd9ac0e50408775e5b603b9184size 16253660123version https://git-lfs.github.com/spec/v1oid sha256:61c4ba1223495a5028fceb51e6c4991bb96d2b637a10fe637916bf58fe7654f8size 117369766123version https://git-lfs.github.com/spec/v1oid sha256:b12c684ac44f0888214ecdefb82d79e5135bfdb8b3854f88e032391fa1500443size 75760667123version https://git-lfs.github.com/spec/v1oid sha256:56b96bab5893ab714bc91ba7210e65ac9c011ba0df996a1410a22bfe9e91fd61size 631626881234onnxruntime>=1.20sentencepiecenumpysoundfileREADME.md+35-10
audact/__init__.py+16-2
audact/decode.py+4-68
audact/onnx_caller.pyAdded+84
audact/render.pyAdded+80
inference_onnx.pyAdded+9
onnx/audio_encoder.onnxAdded+3
onnx/decoder_step.onnxAdded+3
onnx/tool_encoder.onnxAdded+3
onnx_fp32/audio_encoder.onnxAdded+3
onnx_fp32/decoder_step.onnxAdded+3
onnx_fp32/tool_encoder.onnxAdded+3
requirements-onnx.txtAdded+4