Upload audact-final
Browse files- README.md +35 -10
- audact/__init__.py +16 -2
- audact/decode.py +4 -68
- audact/onnx_caller.py +84 -0
- audact/render.py +80 -0
- inference_onnx.py +9 -0
- onnx/audio_encoder.onnx +3 -0
- onnx/decoder_step.onnx +3 -0
- onnx/tool_encoder.onnx +3 -0
- onnx_fp32/audio_encoder.onnx +3 -0
- onnx_fp32/decoder_step.onnx +3 -0
- onnx_fp32/tool_encoder.onnx +3 -0
- requirements-onnx.txt +4 -0
README.md
CHANGED
|
@@ -17,7 +17,8 @@ base_model:
|
|
| 17 |
# Audact (draft)
|
| 18 |
|
| 19 |
**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**.
|
| 20 |
-
About 52.6M parameters
|
|
|
|
| 21 |
numbers or short strings. Built to work on **tools it never saw in training**.
|
| 22 |
|
| 23 |
> Draft release. Scored once on three frozen test sets (below) and on our validation sets. Not for
|
|
@@ -41,10 +42,25 @@ model can only answer with a tool from the list, then writes the arguments greed
|
|
| 41 |
|
| 42 |
## Usage
|
| 43 |
|
|
|
|
|
|
|
| 44 |
```bash
|
| 45 |
hf download KishaanG/audact --local-dir audact-model && cd audact-model
|
| 46 |
-
pip install -r requirements.txt
|
| 47 |
-
python
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
```
|
| 49 |
|
| 50 |
Or from Python, inside that folder:
|
|
@@ -113,15 +129,24 @@ Notes:
|
|
| 113 |
descriptions, tool lists that don't fit) were found by looking at (d)'s inputs, not its answers.
|
| 114 |
Two of its 12 tool names also appear in public datasets we trained on; those examples are now excluded.
|
| 115 |
|
| 116 |
-
### Speed (one CPU thread)
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|---|---|---|
|
| 120 |
-
| Mean / median / slowest 5% | 1.49 s / 1.41 s / 2.35 s | **0.76 s / 0.75 s / 1.02 s** |
|
| 121 |
-
| Runs as | PyTorch, 32-bit weights (this release) | ONNX, 4-bit weights (its release) |
|
| 122 |
|
| 123 |
-
This model
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
### Validation sets (every clip; used for every decision)
|
| 127 |
|
|
|
|
| 17 |
# Audact (draft)
|
| 18 |
|
| 19 |
**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**.
|
| 20 |
+
About 52.6M parameters; runs on one CPU thread with ONNX Runtime in about half a second per command (int8,
|
| 21 |
+
72 MB). English, up to 10 tools per request, one call or none, arguments that are enums,
|
| 22 |
numbers or short strings. Built to work on **tools it never saw in training**.
|
| 23 |
|
| 24 |
> Draft release. Scored once on three frozen test sets (below) and on our validation sets. Not for
|
|
|
|
| 42 |
|
| 43 |
## Usage
|
| 44 |
|
| 45 |
+
Fastest and lightest, with ONNX Runtime (no PyTorch needed):
|
| 46 |
+
|
| 47 |
```bash
|
| 48 |
hf download KishaanG/audact --local-dir audact-model && cd audact-model
|
| 49 |
+
pip install -r requirements-onnx.txt
|
| 50 |
+
python inference_onnx.py command.wav tools.json # 16 kHz mono audio; a JSON list of tools
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
```python
|
| 54 |
+
from audact.onnx_caller import AudactONNX
|
| 55 |
+
|
| 56 |
+
caller = AudactONNX(".", threads=1) # int8 graphs in onnx/; onnx_dir="onnx_fp32" for 32-bit
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
With PyTorch (needs NeMo for FastConformer's architecture; base weights download once):
|
| 60 |
+
|
| 61 |
+
```bash
|
| 62 |
+
pip install -r requirements.txt
|
| 63 |
+
python inference.py command.wav tools.json
|
| 64 |
```
|
| 65 |
|
| 66 |
Or from Python, inside that folder:
|
|
|
|
| 129 |
descriptions, tool lists that don't fit) were found by looking at (d)'s inputs, not its answers.
|
| 130 |
Two of its 12 tool names also appear in public datasets we trained on; those examples are now excluded.
|
| 131 |
|
| 132 |
+
### Speed and memory (one CPU thread)
|
| 133 |
|
| 134 |
+
Same laptop CPU, same 100 SLURP validation clips, one thread, each model as released:
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
+
| | This model, ONNX int8 (default) | This model, ONNX 32-bit | NeuDecide, ONNX 4-bit |
|
| 137 |
+
|---|---|---|---|
|
| 138 |
+
| Time per command, mean / slowest 5% | **0.55 s / 0.74 s** | 0.67 s / 0.83 s | 0.74 s / 1.01 s |
|
| 139 |
+
| Peak memory | **380 MB** | 774 MB | 567 MB |
|
| 140 |
+
| Model files | 72 MB | 245 MB | **43 MB** |
|
| 141 |
+
|
| 142 |
+
The 32-bit ONNX graphs give the same answers as the PyTorch model (150 of 150 validation clips); the
|
| 143 |
+
test results above are theirs. int8 costs a little accuracy, measured on validation:
|
| 144 |
+
|
| 145 |
+
| Validation, clips needing a call: right tool / exact match / false triggers | 32-bit | int8 |
|
| 146 |
+
|---|---|---|
|
| 147 |
+
| SLURP (real voices) | 51.4% / 26.1% / 36.8% | 49.2% / 24.9% / 32.9% |
|
| 148 |
+
| Synthetic, unseen tools | 86.5% / 41.9% / 18.8% | 85.1% / 40.0% / 14.5% |
|
| 149 |
+
| Chatty synthetic, unseen tools | 87.1% / 41.8% / 14.7% | 86.4% / 40.9% / 13.3% |
|
| 150 |
|
| 151 |
### Validation sets (every clip; used for every decision)
|
| 152 |
|
audact/__init__.py
CHANGED
|
@@ -1,3 +1,17 @@
|
|
| 1 |
-
|
| 2 |
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Audact: speech + a tool list in, one tool call (or none) out.
|
| 2 |
|
| 3 |
+
Audact PyTorch caller (needs torch and NeMo)
|
| 4 |
+
AudactONNX ONNX Runtime caller (needs only onnxruntime, sentencepiece, numpy, soundfile)
|
| 5 |
+
Both are imported only when first used, so the ONNX caller never loads PyTorch.
|
| 6 |
+
"""
|
| 7 |
+
__all__ = ["Audact", "AudactONNX"]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def __getattr__(name):
|
| 11 |
+
if name == "Audact":
|
| 12 |
+
from .caller import Audact
|
| 13 |
+
return Audact
|
| 14 |
+
if name == "AudactONNX":
|
| 15 |
+
from .onnx_caller import AudactONNX
|
| 16 |
+
return AudactONNX
|
| 17 |
+
raise AttributeError(name)
|
audact/decode.py
CHANGED
|
@@ -8,61 +8,13 @@ Decoding (whole-name scoring): no call and every listed tool's name are scored a
|
|
| 8 |
"""
|
| 9 |
from __future__ import annotations
|
| 10 |
|
| 11 |
-
import json
|
| 12 |
-
import re
|
| 13 |
-
|
| 14 |
import torch
|
| 15 |
|
| 16 |
-
from .
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
def tools_json(obj) -> str:
|
| 20 |
-
return json.dumps(obj, separators=(",", ":")) # no spaces: the only form Needle reads well
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
def compact_tools(tools: list[dict]) -> list[dict]:
|
| 24 |
-
"""Drop each argument's description, keep type, enum and required."""
|
| 25 |
-
out = []
|
| 26 |
-
for tool in tools:
|
| 27 |
-
params = tool.get("parameters", {})
|
| 28 |
-
props = {a: {k: v for k, v in spec.items() if k != "description"} for a, spec in params.get("properties", {}).items()}
|
| 29 |
-
out.append({**tool, "parameters": {**params, "properties": props}})
|
| 30 |
-
return out
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
SHORTEN_WORDS = (20, 10, 4)
|
| 34 |
|
| 35 |
-
|
| 36 |
-
def shorten_tools(tools: list[dict], max_words: int) -> list[dict]:
|
| 37 |
-
"""Each tool's description cut to its first sentence and at most max_words words."""
|
| 38 |
-
out = []
|
| 39 |
-
for t in tools:
|
| 40 |
-
first = re.split(r"(?<=[.!?])\s", t.get("description", "").strip(), maxsplit=1)[0]
|
| 41 |
-
out.append({**t, "description": " ".join(first.split()[:max_words])})
|
| 42 |
-
return out
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
def render_tools(tools: list[dict], prefix_len: int, sp) -> tuple[list[int], list[str]]:
|
| 46 |
-
"""<tools> + JSON token ids that fit next to prefix_len audio frames, and the names kept."""
|
| 47 |
-
room = MAX_INPUT_TOKENS - prefix_len
|
| 48 |
-
compact = compact_tools(tools)
|
| 49 |
-
for rendered in [tools, compact] + [shorten_tools(compact, n) for n in SHORTEN_WORDS]:
|
| 50 |
-
ids = [TOOLS] + sp.encode(tools_json(rendered))
|
| 51 |
-
if len(ids) <= room:
|
| 52 |
-
return ids, [t["name"] for t in tools]
|
| 53 |
-
kept = shorten_tools(compact, SHORTEN_WORDS[-1])
|
| 54 |
-
while kept:
|
| 55 |
-
kept = kept[:-1]
|
| 56 |
-
ids = [TOOLS] + sp.encode(tools_json(kept))
|
| 57 |
-
if len(ids) <= room:
|
| 58 |
-
return ids, [t["name"] for t in kept]
|
| 59 |
-
raise ValueError("the audio is too long to leave room for any tool")
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
def allowed_starts(names: list[str], sp) -> list[list[int]]:
|
| 63 |
-
starts = [[TOOL_CALL] + sp.encode("[]") + [EOS]] # no call
|
| 64 |
-
starts += [[TOOL_CALL] + sp.encode(f'[{{"name":"{n}","arguments') for n in names]
|
| 65 |
-
return starts
|
| 66 |
|
| 67 |
|
| 68 |
@torch.inference_mode()
|
|
@@ -90,19 +42,3 @@ def whole_name_decode(needle, memory, mask, starts: list[list[int]], max_new_tok
|
|
| 90 |
out.append(token)
|
| 91 |
ids = torch.cat([ids, torch.tensor([[token]], device=memory.device)], dim=1)
|
| 92 |
return out
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
def parse_answer(ids: list[int], sp) -> dict | None:
|
| 96 |
-
"""Answer ids -> {"name": ..., "arguments": {...}}, None for no call, or {"invalid": text}."""
|
| 97 |
-
text = sp.decode([i for i in ids if i > TOOLS])
|
| 98 |
-
try:
|
| 99 |
-
calls = json.loads(text)
|
| 100 |
-
except json.JSONDecodeError:
|
| 101 |
-
return {"invalid": text}
|
| 102 |
-
if calls == []:
|
| 103 |
-
return None
|
| 104 |
-
if isinstance(calls, list) and isinstance(calls[0], dict) and isinstance(calls[0].get("name"), str):
|
| 105 |
-
args = calls[0].get("arguments") or {}
|
| 106 |
-
if isinstance(args, dict):
|
| 107 |
-
return {"name": calls[0]["name"], "arguments": args}
|
| 108 |
-
return {"invalid": text}
|
|
|
|
| 8 |
"""
|
| 9 |
from __future__ import annotations
|
| 10 |
|
|
|
|
|
|
|
|
|
|
| 11 |
import torch
|
| 12 |
|
| 13 |
+
from . import needle as _needle
|
| 14 |
+
from .render import (EOS, MAX_INPUT_TOKENS, SHORTEN_WORDS, TOOL_CALL, TOOLS, allowed_starts, compact_tools, # noqa: F401
|
| 15 |
+
parse_answer, render_tools, shorten_tools, tools_json)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
assert (EOS, TOOL_CALL, TOOLS, MAX_INPUT_TOKENS) == (_needle.EOS, _needle.TOOL_CALL, _needle.TOOLS, _needle.MAX_INPUT_TOKENS)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
|
| 20 |
@torch.inference_mode()
|
|
|
|
| 42 |
out.append(token)
|
| 43 |
ids = torch.cat([ids, torch.tensor([[token]], device=memory.device)], dim=1)
|
| 44 |
return out
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audact/onnx_caller.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Audact on ONNX Runtime: speech + a tool list in, one call (or none) out, with no PyTorch or NeMo.
|
| 2 |
+
|
| 3 |
+
Three graphs (Phase 6), each run only as often as it must:
|
| 4 |
+
audio_encoder.onnx once per clip waveform (1, S) -> audio vectors (1, T_a, 512)
|
| 5 |
+
tool_encoder.onnx once per clip + tools audio vectors + tool ids -> cross-attention keys/values
|
| 6 |
+
decoder_step.onnx once per token chunk new tokens + cache -> next-token scores + longer cache
|
| 7 |
+
|
| 8 |
+
Decoding is the same whole-name scoring as the PyTorch caller: "no call" and every listed tool's name are
|
| 9 |
+
each fed to the decoder as one chunk and scored by the sum of their tokens' log-probabilities; the best
|
| 10 |
+
one wins, and the arguments are then written greedily, one token at a time, reusing the cache.
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
from .render import EOS, allowed_starts, parse_answer, render_tools
|
| 19 |
+
|
| 20 |
+
RATE = 16_000
|
| 21 |
+
LAYERS, KV_HEADS, HEAD_DIM = 8, 4, 64
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _log_softmax(x: np.ndarray) -> np.ndarray:
|
| 25 |
+
m = x.max(axis=-1, keepdims=True)
|
| 26 |
+
return x - m - np.log(np.exp(x - m).sum(axis=-1, keepdims=True))
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class AudactONNX:
|
| 30 |
+
def __init__(self, folder: str | Path, threads: int = 1, onnx_dir: str | Path | None = None,
|
| 31 |
+
low_memory: bool = True) -> None:
|
| 32 |
+
"""folder: a downloaded copy of the model (tokenizer.model); onnx_dir: where the three graphs are
|
| 33 |
+
(default folder/onnx: int8; folder/onnx_fp32 is the unquantized set). threads: CPU threads for ONNX
|
| 34 |
+
Runtime (1 = the phone-class setting). low_memory: no memory pool (int8, 1 thread: peak 380 MB
|
| 35 |
+
instead of 491 MB, about 5% slower)."""
|
| 36 |
+
import onnxruntime as ort
|
| 37 |
+
import sentencepiece as spm
|
| 38 |
+
|
| 39 |
+
folder = Path(folder)
|
| 40 |
+
graphs = Path(onnx_dir) if onnx_dir else folder / "onnx"
|
| 41 |
+
opts = ort.SessionOptions()
|
| 42 |
+
opts.intra_op_num_threads, opts.inter_op_num_threads = threads, 1
|
| 43 |
+
if low_memory:
|
| 44 |
+
opts.enable_cpu_mem_arena, opts.enable_mem_pattern = False, False
|
| 45 |
+
load = lambda name: ort.InferenceSession(str(graphs / name), opts, providers=["CPUExecutionProvider"])
|
| 46 |
+
self.audio, self.tools, self.step = load("audio_encoder.onnx"), load("tool_encoder.onnx"), load("decoder_step.onnx")
|
| 47 |
+
self.sp = spm.SentencePieceProcessor(model_file=str(folder / "tokenizer.model"))
|
| 48 |
+
|
| 49 |
+
def _step(self, ids: list[int], cache, cross):
|
| 50 |
+
logits, k, v = self.step.run(None, {"ids": np.array([ids], dtype=np.int64), "past_k": cache[0],
|
| 51 |
+
"past_v": cache[1], "cross_k": cross[0], "cross_v": cross[1]})
|
| 52 |
+
return logits[0], (k, v) # (n, 8192), cache extended by n
|
| 53 |
+
|
| 54 |
+
def __call__(self, audio, tools: list[dict], max_new_tokens: int = 96) -> dict | None:
|
| 55 |
+
"""audio: a path to a 16 kHz mono file, or float samples in [-1, 1]. tools: up to 10 JSON-Schema
|
| 56 |
+
functions. Returns {"name", "arguments"}, None for no call, or {"invalid": text}."""
|
| 57 |
+
if isinstance(audio, (str, Path)):
|
| 58 |
+
import soundfile as sf
|
| 59 |
+
audio, rate = sf.read(audio, dtype="float32", always_2d=True)
|
| 60 |
+
assert rate == RATE, f"expected {RATE} Hz audio, got {rate}"
|
| 61 |
+
audio = audio[:, 0]
|
| 62 |
+
wave = np.asarray(audio, dtype=np.float32)[None] # (1, S)
|
| 63 |
+
vectors = self.audio.run(None, {"waveform": wave})[0] # (1, T_a, 512)
|
| 64 |
+
tool_ids, kept = render_tools(tools, vectors.shape[1], self.sp)
|
| 65 |
+
cross = self.tools.run(None, {"audio_vectors": vectors, "tool_ids": np.array([tool_ids], dtype=np.int64)})
|
| 66 |
+
empty = np.zeros((LAYERS, 1, KV_HEADS, 0, HEAD_DIM), dtype=np.float32)
|
| 67 |
+
|
| 68 |
+
best, best_score, best_cache = None, -np.inf, None
|
| 69 |
+
for start in allowed_starts(kept, self.sp): # no call first, then each listed tool's name
|
| 70 |
+
logits, cache = self._step([EOS] + start[:-1], (empty, empty), cross)
|
| 71 |
+
logp = _log_softmax(logits.astype(np.float64)) # (n, 8192)
|
| 72 |
+
score = float(logp[np.arange(len(start)), start].sum())
|
| 73 |
+
if score > best_score: # strict: on a tie the earlier start wins, like argmax
|
| 74 |
+
best, best_score, best_cache = start, score, cache
|
| 75 |
+
if best[-1] == EOS:
|
| 76 |
+
return parse_answer(best[:-1], self.sp) # no call
|
| 77 |
+
out, cache, token = list(best), best_cache, best[-1]
|
| 78 |
+
for _ in range(max_new_tokens): # the arguments, greedily
|
| 79 |
+
logits, cache = self._step([token], cache, cross)
|
| 80 |
+
token = int(logits[-1].argmax())
|
| 81 |
+
if token == EOS:
|
| 82 |
+
break
|
| 83 |
+
out.append(token)
|
| 84 |
+
return parse_answer(out, self.sp)
|
audact/render.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tool-list rendering, decoding starts and answer parsing: pure Python (no PyTorch), shared by the
|
| 2 |
+
PyTorch caller (decode.py) and the ONNX caller (onnx_caller.py), so both read tool lists the same way
|
| 3 |
+
training did (tests/test_render_match.py).
|
| 4 |
+
|
| 5 |
+
Rendering: full tool definitions if audio frames + <tools> + JSON fit in 1,024 positions, else compact
|
| 6 |
+
(argument descriptions dropped), else each tool description shortened (first sentence, at most 20, then
|
| 7 |
+
10, then 4 words), and only then whole tools are dropped from the end of the list until it fits.
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
import re
|
| 13 |
+
|
| 14 |
+
PAD, EOS, TOOL_CALL, TOOLS = 0, 1, 4, 5 # Needle's special token ids (tokenizer.model)
|
| 15 |
+
MAX_INPUT_TOKENS = 1024 # Needle's encoder reads at most this many positions
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def tools_json(obj) -> str:
|
| 19 |
+
return json.dumps(obj, separators=(",", ":")) # no spaces: the only form Needle reads well
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def compact_tools(tools: list[dict]) -> list[dict]:
|
| 23 |
+
"""Drop each argument's description, keep type, enum and required."""
|
| 24 |
+
out = []
|
| 25 |
+
for tool in tools:
|
| 26 |
+
params = tool.get("parameters", {})
|
| 27 |
+
props = {a: {k: v for k, v in spec.items() if k != "description"} for a, spec in params.get("properties", {}).items()}
|
| 28 |
+
out.append({**tool, "parameters": {**params, "properties": props}})
|
| 29 |
+
return out
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
SHORTEN_WORDS = (20, 10, 4)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def shorten_tools(tools: list[dict], max_words: int) -> list[dict]:
|
| 36 |
+
"""Each tool's description cut to its first sentence and at most max_words words."""
|
| 37 |
+
out = []
|
| 38 |
+
for t in tools:
|
| 39 |
+
first = re.split(r"(?<=[.!?])\s", t.get("description", "").strip(), maxsplit=1)[0]
|
| 40 |
+
out.append({**t, "description": " ".join(first.split()[:max_words])})
|
| 41 |
+
return out
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def render_tools(tools: list[dict], prefix_len: int, sp) -> tuple[list[int], list[str]]:
|
| 45 |
+
"""<tools> + JSON token ids that fit next to prefix_len audio frames, and the names kept."""
|
| 46 |
+
room = MAX_INPUT_TOKENS - prefix_len
|
| 47 |
+
compact = compact_tools(tools)
|
| 48 |
+
for rendered in [tools, compact] + [shorten_tools(compact, n) for n in SHORTEN_WORDS]:
|
| 49 |
+
ids = [TOOLS] + sp.encode(tools_json(rendered))
|
| 50 |
+
if len(ids) <= room:
|
| 51 |
+
return ids, [t["name"] for t in tools]
|
| 52 |
+
kept = shorten_tools(compact, SHORTEN_WORDS[-1])
|
| 53 |
+
while kept:
|
| 54 |
+
kept = kept[:-1]
|
| 55 |
+
ids = [TOOLS] + sp.encode(tools_json(kept))
|
| 56 |
+
if len(ids) <= room:
|
| 57 |
+
return ids, [t["name"] for t in kept]
|
| 58 |
+
raise ValueError("the audio is too long to leave room for any tool")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def allowed_starts(names: list[str], sp) -> list[list[int]]:
|
| 62 |
+
starts = [[TOOL_CALL] + sp.encode("[]") + [EOS]] # no call
|
| 63 |
+
starts += [[TOOL_CALL] + sp.encode(f'[{{"name":"{n}","arguments') for n in names]
|
| 64 |
+
return starts
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def parse_answer(ids: list[int], sp) -> dict | None:
|
| 68 |
+
"""Answer ids -> {"name": ..., "arguments": {...}}, None for no call, or {"invalid": text}."""
|
| 69 |
+
text = sp.decode([i for i in ids if i > TOOLS])
|
| 70 |
+
try:
|
| 71 |
+
calls = json.loads(text)
|
| 72 |
+
except json.JSONDecodeError:
|
| 73 |
+
return {"invalid": text}
|
| 74 |
+
if calls == []:
|
| 75 |
+
return None
|
| 76 |
+
if isinstance(calls, list) and isinstance(calls[0], dict) and isinstance(calls[0].get("name"), str):
|
| 77 |
+
args = calls[0].get("arguments") or {}
|
| 78 |
+
if isinstance(args, dict):
|
| 79 |
+
return {"name": calls[0]["name"], "arguments": args}
|
| 80 |
+
return {"invalid": text}
|
inference_onnx.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Example without PyTorch: python inference_onnx.py clip.wav tools.json (16 kHz mono audio; a JSON list of tools)
|
| 2 |
+
Needs only requirements-onnx.txt. Uses the int8 graphs in onnx/ on one CPU thread."""
|
| 3 |
+
import json
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
from audact.onnx_caller import AudactONNX
|
| 7 |
+
|
| 8 |
+
caller = AudactONNX(".", threads=1)
|
| 9 |
+
print(json.dumps(caller(sys.argv[1], json.load(open(sys.argv[2])))))
|
onnx/audio_encoder.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:dca0233a5f68385bdc65662d737573f463951ee9211849fe7487c81c293767a8
|
| 3 |
+
size 38866822
|
onnx/decoder_step.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b186bb1aaa541314d286d7fb6bc39d91404ee114bab79cca62f950a27c42357b
|
| 3 |
+
size 19437874
|
onnx/tool_encoder.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:641a1f50c9644f154f5ca06fdf1c4cfbe3b2bddd9ac0e50408775e5b603b9184
|
| 3 |
+
size 16253660
|
onnx_fp32/audio_encoder.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:61c4ba1223495a5028fceb51e6c4991bb96d2b637a10fe637916bf58fe7654f8
|
| 3 |
+
size 117369766
|
onnx_fp32/decoder_step.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b12c684ac44f0888214ecdefb82d79e5135bfdb8b3854f88e032391fa1500443
|
| 3 |
+
size 75760667
|
onnx_fp32/tool_encoder.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:56b96bab5893ab714bc91ba7210e65ac9c011ba0df996a1410a22bfe9e91fd61
|
| 3 |
+
size 63162688
|
requirements-onnx.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
onnxruntime>=1.20
|
| 2 |
+
sentencepiece
|
| 3 |
+
numpy
|
| 4 |
+
soundfile
|