duplexjev 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- duplexjev/__init__.py +11 -0
- duplexjev/cli.py +77 -0
- duplexjev/decider.py +439 -0
- duplexjev/question.py +95 -0
- duplexjev/server.py +131 -0
- duplexjev-0.1.0.dist-info/METADATA +68 -0
- duplexjev-0.1.0.dist-info/RECORD +12 -0
- duplexjev-0.1.0.dist-info/WHEEL +5 -0
- duplexjev-0.1.0.dist-info/entry_points.txt +2 -0
- duplexjev-0.1.0.dist-info/licenses/LICENSE +202 -0
- duplexjev-0.1.0.dist-info/licenses/NOTICE +19 -0
- duplexjev-0.1.0.dist-info/top_level.txt +1 -0
duplexjev/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""DuplexJev: batched typed speech decisions without decoding.
|
|
2
|
+
|
|
3
|
+
from duplexjev import Decider, Question
|
|
4
|
+
d = Decider.from_pretrained("Qwen/Qwen3-0.6B") # any causal LM (text), or a speech checkpoint
|
|
5
|
+
d.decide(["I want to turn on the"], [Question("turn", "Has the user finished?", ["finished", "not finished"])])
|
|
6
|
+
"""
|
|
7
|
+
from .decider import Decider, load_audio
|
|
8
|
+
from .question import Question
|
|
9
|
+
|
|
10
|
+
__all__ = ["Decider", "Question", "load_audio"]
|
|
11
|
+
__version__ = "0.1.0"
|
duplexjev/cli.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Command line: ``duplexjev decide`` for one-off runs, ``duplexjev serve`` for the tick-batched HTTP server."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from .question import Question
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _questions(args) -> list[Question]:
|
|
12
|
+
qs = []
|
|
13
|
+
if args.questions:
|
|
14
|
+
with open(args.questions, encoding="utf-8") as f:
|
|
15
|
+
qs += [Question.from_dict(q) for q in json.load(f)]
|
|
16
|
+
for spec in args.q or []:
|
|
17
|
+
# "id|question text|opt1,opt2,..."
|
|
18
|
+
qid, text, opts = spec.split("|", 2)
|
|
19
|
+
qs.append(Question(qid, text, [o.strip() for o in opts.split(",")], lang=args.lang or "en"))
|
|
20
|
+
if not qs:
|
|
21
|
+
sys.exit("give --questions FILE.json or at least one --q 'id|text|opt1,opt2'")
|
|
22
|
+
return qs
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def main(argv=None):
|
|
26
|
+
ap = argparse.ArgumentParser(prog="duplexjev")
|
|
27
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
28
|
+
|
|
29
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
30
|
+
common.add_argument("--model", required=True, help="HF id or path: any causal LM, or an Ultravox/DuplexJev speech checkpoint")
|
|
31
|
+
common.add_argument("--text-model", help="override the LLM a speech checkpoint points to (e.g. a local path)")
|
|
32
|
+
common.add_argument("--audio-model", help="override the encoder a speech checkpoint points to")
|
|
33
|
+
common.add_argument("--device")
|
|
34
|
+
|
|
35
|
+
d = sub.add_parser("decide", parents=[common], help="answer questions about audio files or transcripts")
|
|
36
|
+
d.add_argument("--audio", nargs="*", default=[], help="audio files (one item each)")
|
|
37
|
+
d.add_argument("--text", nargs="*", default=[], help="transcripts (one item each)")
|
|
38
|
+
d.add_argument("--context")
|
|
39
|
+
d.add_argument("--questions", help="JSON list of {id, text, options, lang}")
|
|
40
|
+
d.add_argument("--q", action="append", help="inline question: 'id|text|opt1,opt2,...' (repeatable)")
|
|
41
|
+
d.add_argument("--lang", choices=["en", "zh"])
|
|
42
|
+
d.add_argument("--mode", default="packed", choices=["packed", "batch"])
|
|
43
|
+
d.add_argument("--n-perm", type=int, default=1)
|
|
44
|
+
|
|
45
|
+
s = sub.add_parser("serve", parents=[common], help="HTTP server; batches all requests of each tick")
|
|
46
|
+
s.add_argument("--host", default="0.0.0.0")
|
|
47
|
+
s.add_argument("--port", type=int, default=8000)
|
|
48
|
+
s.add_argument("--tick-ms", type=float, default=160.0)
|
|
49
|
+
s.add_argument("--max-items", type=int, help="max items per forward pass")
|
|
50
|
+
|
|
51
|
+
args = ap.parse_args(argv)
|
|
52
|
+
from .decider import Decider
|
|
53
|
+
|
|
54
|
+
dec = Decider.from_pretrained(args.model, device=args.device, text_model=args.text_model, audio_model=args.audio_model)
|
|
55
|
+
if args.cmd == "decide":
|
|
56
|
+
items = [{"audio": a} for a in args.audio] + [{"text": t} for t in args.text]
|
|
57
|
+
if not items:
|
|
58
|
+
sys.exit("give --audio and/or --text")
|
|
59
|
+
for it in items:
|
|
60
|
+
if args.context:
|
|
61
|
+
it["context"] = args.context
|
|
62
|
+
if args.lang:
|
|
63
|
+
it["lang"] = args.lang
|
|
64
|
+
res = dec.decide(items, _questions(args), mode=args.mode, n_perm=args.n_perm)
|
|
65
|
+
names = args.audio + args.text
|
|
66
|
+
print(json.dumps({"results": [{"input": n, "answers": r} for n, r in zip(names, res)], "pass": dec.last_stats},
|
|
67
|
+
ensure_ascii=False, indent=1))
|
|
68
|
+
else:
|
|
69
|
+
import uvicorn
|
|
70
|
+
|
|
71
|
+
from .server import create_app
|
|
72
|
+
|
|
73
|
+
uvicorn.run(create_app(dec, tick_ms=args.tick_ms, max_items=args.max_items), host=args.host, port=args.port)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
if __name__ == "__main__":
|
|
77
|
+
main()
|
duplexjev/decider.py
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
"""Batched typed decisions from one forward pass, with exact prefix sharing.
|
|
2
|
+
|
|
3
|
+
Two layouts give the same answers (up to floating-point noise):
|
|
4
|
+
|
|
5
|
+
* ``mode="packed"`` (default): for every item, the shared prefix (chat template, context, audio) is encoded once and
|
|
6
|
+
all of that item's question suffixes are packed into one row under a block-diagonal mask, with position ids
|
|
7
|
+
restarting at the prefix length. All items of a call are processed together: one prefill for the prefixes, one
|
|
8
|
+
forward for all suffixes. KV memory grows with ``P + sum(L_i)`` per item instead of ``N * (P + L)``.
|
|
9
|
+
* ``mode="batch"``: every (item, question) pair is its own row. Simpler, slower; kept as a reference.
|
|
10
|
+
|
|
11
|
+
The answer to a question is the next-token softmax restricted to its option letters at the last prompt position.
|
|
12
|
+
No tokens are generated.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import time
|
|
17
|
+
from typing import Any, Iterable, Sequence
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
import torch
|
|
21
|
+
|
|
22
|
+
from .question import Question, as_questions
|
|
23
|
+
|
|
24
|
+
SAMPLE_RATE = 16000
|
|
25
|
+
_SENTINEL = "QUESTION"
|
|
26
|
+
|
|
27
|
+
PROMPTS = {
|
|
28
|
+
"en": {"context": "Context:\n{c}", "transcript": "The user said: {t}", "audio": "The user said: <|audio|>"},
|
|
29
|
+
"zh": {"context": "上下文:\n{c}", "transcript": "用户说:{t}", "audio": "用户说:<|audio|>"},
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# ---------------------------------------------------------------------------------------------------------- inputs
|
|
34
|
+
def load_audio(x: Any) -> np.ndarray:
|
|
35
|
+
"""Accept a 16 kHz float array, a (array, sample_rate) tuple or a file path; return 16 kHz mono float32."""
|
|
36
|
+
sr = SAMPLE_RATE
|
|
37
|
+
if isinstance(x, (str, bytes)) or hasattr(x, "__fspath__"):
|
|
38
|
+
import soundfile as sf
|
|
39
|
+
|
|
40
|
+
x, sr = sf.read(x, dtype="float32")
|
|
41
|
+
elif isinstance(x, tuple):
|
|
42
|
+
x, sr = x
|
|
43
|
+
a = np.asarray(x, dtype=np.float32)
|
|
44
|
+
if a.ndim > 1:
|
|
45
|
+
a = a.mean(axis=1) if a.shape[1] <= 8 else a.mean(axis=0)
|
|
46
|
+
if sr != SAMPLE_RATE: # polyphase resampling: fast and without a one-off JIT warm-up
|
|
47
|
+
from math import gcd
|
|
48
|
+
|
|
49
|
+
from scipy.signal import resample_poly
|
|
50
|
+
|
|
51
|
+
g = gcd(int(sr), SAMPLE_RATE)
|
|
52
|
+
a = resample_poly(a, SAMPLE_RATE // g, int(sr) // g).astype(np.float32)
|
|
53
|
+
return a
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def as_item(x: Any) -> dict:
|
|
57
|
+
"""An item is a dict with any of: ``audio``, ``text`` (transcript), ``context``, ``questions``, ``lang``."""
|
|
58
|
+
if isinstance(x, dict):
|
|
59
|
+
return x
|
|
60
|
+
if isinstance(x, str):
|
|
61
|
+
return {"text": x}
|
|
62
|
+
return {"audio": x}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# ---------------------------------------------------------------------------------------------------------- engine
|
|
66
|
+
class Decider:
|
|
67
|
+
"""Answer typed closed-set questions about speech (or text) with zero decode steps.
|
|
68
|
+
|
|
69
|
+
Create with :meth:`from_pretrained`. The same object serves text-only LLMs (inputs are transcripts) and
|
|
70
|
+
Ultravox-format speech checkpoints, including the DuplexJev adapters.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
def __init__(self, model, tokenizer, processor=None, *, device=None, is_audio: bool = False):
|
|
74
|
+
self.model = model.eval()
|
|
75
|
+
self.tok = tokenizer
|
|
76
|
+
self.processor = processor
|
|
77
|
+
self.is_audio = is_audio
|
|
78
|
+
if device is None or str(device) == "auto": # sharded model: inputs go where the embeddings live
|
|
79
|
+
device = model.get_input_embeddings().weight.device if not is_audio else model.language_model.get_input_embeddings().weight.device
|
|
80
|
+
self.device = torch.device(device)
|
|
81
|
+
self.lm = model.language_model if is_audio else model
|
|
82
|
+
self.base = getattr(self.lm, self.lm.base_model_prefix)
|
|
83
|
+
self.head = self.lm.get_output_embeddings()
|
|
84
|
+
self.pad_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id
|
|
85
|
+
self._letter_ids: dict[str, int] = {}
|
|
86
|
+
self._tail_cache: dict[tuple, tuple[str, str]] = {}
|
|
87
|
+
self.last_stats: dict = {}
|
|
88
|
+
|
|
89
|
+
# ------------------------------------------------------------------ loading
|
|
90
|
+
@classmethod
|
|
91
|
+
def from_pretrained(
|
|
92
|
+
cls,
|
|
93
|
+
name_or_path: str,
|
|
94
|
+
*,
|
|
95
|
+
device: str | None = None,
|
|
96
|
+
dtype: torch.dtype | None = None,
|
|
97
|
+
text_model: str | None = None,
|
|
98
|
+
audio_model: str | None = None,
|
|
99
|
+
**kwargs,
|
|
100
|
+
) -> "Decider":
|
|
101
|
+
"""Load a text LLM (any causal LM on the Hugging Face hub) or an Ultravox-format speech checkpoint.
|
|
102
|
+
|
|
103
|
+
``device="auto"`` shards the model over all visible GPUs (needs ``accelerate``).
|
|
104
|
+
``text_model`` / ``audio_model`` override the LLM and encoder a speech checkpoint points to (e.g. a local
|
|
105
|
+
copy of Qwen3-32B). Remaining kwargs go to ``from_pretrained`` of the model.
|
|
106
|
+
"""
|
|
107
|
+
import transformers
|
|
108
|
+
|
|
109
|
+
dkw = "dtype" if tuple(int(x) for x in transformers.__version__.split(".")[:2]) >= (4, 56) else "torch_dtype"
|
|
110
|
+
if device is None:
|
|
111
|
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
112
|
+
if dtype is None:
|
|
113
|
+
dtype = torch.bfloat16 if str(device).startswith("cuda") or device == "auto" else torch.float32
|
|
114
|
+
dmap = "auto" if device == "auto" else {"": device}
|
|
115
|
+
cfg = transformers.AutoConfig.from_pretrained(name_or_path, trust_remote_code=True)
|
|
116
|
+
if getattr(cfg, "model_type", "") == "ultravox":
|
|
117
|
+
if dkw == "dtype":
|
|
118
|
+
import warnings
|
|
119
|
+
|
|
120
|
+
warnings.warn(
|
|
121
|
+
"Ultravox-format checkpoints ship remote code written for transformers 4.51-4.55; with "
|
|
122
|
+
f"transformers {transformers.__version__} loading can be extremely slow (weights built on CPU). "
|
|
123
|
+
'Install with `pip install "duplexjev[speech]"` to get a compatible version.'
|
|
124
|
+
)
|
|
125
|
+
if text_model:
|
|
126
|
+
cfg.text_model_id = text_model
|
|
127
|
+
if audio_model:
|
|
128
|
+
cfg.audio_model_id = audio_model
|
|
129
|
+
model = transformers.AutoModel.from_pretrained(
|
|
130
|
+
name_or_path, config=cfg, trust_remote_code=True, device_map=dmap, **{dkw: dtype}, **kwargs
|
|
131
|
+
)
|
|
132
|
+
processor = transformers.AutoProcessor.from_pretrained(name_or_path, trust_remote_code=True)
|
|
133
|
+
if not hasattr(processor, "audio_processor"): # e.g. a stray preprocessor_config.json took precedence
|
|
134
|
+
from transformers.dynamic_module_utils import get_class_from_dynamic_module
|
|
135
|
+
|
|
136
|
+
cls_ = get_class_from_dynamic_module(cfg.auto_map["AutoProcessor"], name_or_path)
|
|
137
|
+
processor = cls_.from_pretrained(name_or_path)
|
|
138
|
+
ap = processor.audio_processor
|
|
139
|
+
if isinstance(ap, transformers.WhisperFeatureExtractor) and not hasattr(ap, "feature_extractor"):
|
|
140
|
+
processor.audio_processor = transformers.WhisperProcessor(
|
|
141
|
+
feature_extractor=ap, tokenizer=processor.tokenizer
|
|
142
|
+
)
|
|
143
|
+
return cls(model, processor.tokenizer, processor, device=None if device == "auto" else device, is_audio=True)
|
|
144
|
+
tok = transformers.AutoTokenizer.from_pretrained(name_or_path, **{k: v for k, v in kwargs.items() if k == "revision"})
|
|
145
|
+
if device == "auto":
|
|
146
|
+
model = transformers.AutoModelForCausalLM.from_pretrained(name_or_path, device_map="auto", **{dkw: dtype}, **kwargs)
|
|
147
|
+
else:
|
|
148
|
+
model = transformers.AutoModelForCausalLM.from_pretrained(name_or_path, **{dkw: dtype}, **kwargs).to(device)
|
|
149
|
+
return cls(model, tok, device=None if device == "auto" else device, is_audio=False)
|
|
150
|
+
|
|
151
|
+
# ------------------------------------------------------------------ prompt pieces
|
|
152
|
+
def _head_tail(self, context: str | None, content: str, lang: str) -> tuple[str, str]:
|
|
153
|
+
"""Split the chat-formatted prompt into the shared head (up to the question) and the fixed tail."""
|
|
154
|
+
key = (context, content, lang)
|
|
155
|
+
if key in self._tail_cache:
|
|
156
|
+
return self._tail_cache[key]
|
|
157
|
+
parts = []
|
|
158
|
+
if context:
|
|
159
|
+
parts.append(PROMPTS[lang]["context"].format(c=context))
|
|
160
|
+
parts.append(content)
|
|
161
|
+
parts.append(_SENTINEL)
|
|
162
|
+
user = "\n\n".join(parts)
|
|
163
|
+
if getattr(self.tok, "chat_template", None):
|
|
164
|
+
full = self.tok.apply_chat_template(
|
|
165
|
+
[{"role": "user", "content": user}], add_generation_prompt=True, tokenize=False, enable_thinking=False
|
|
166
|
+
)
|
|
167
|
+
else:
|
|
168
|
+
full = user + "\n\nAnswer: "
|
|
169
|
+
head, tail = full.split(_SENTINEL)
|
|
170
|
+
if len(self._tail_cache) < 4096:
|
|
171
|
+
self._tail_cache[key] = (head, tail)
|
|
172
|
+
return head, tail
|
|
173
|
+
|
|
174
|
+
def _letter_id(self, letter: str) -> int:
|
|
175
|
+
if letter not in self._letter_ids:
|
|
176
|
+
ids = self.tok.encode(letter, add_special_tokens=False)
|
|
177
|
+
if len(ids) != 1:
|
|
178
|
+
raise RuntimeError(f"option letter {letter!r} is not a single token for this tokenizer: {ids}")
|
|
179
|
+
self._letter_ids[letter] = ids[0]
|
|
180
|
+
return self._letter_ids[letter]
|
|
181
|
+
|
|
182
|
+
def _align(self, a: np.ndarray) -> np.ndarray:
|
|
183
|
+
"""Left-pad with silence to a whole number of audio tokens.
|
|
184
|
+
|
|
185
|
+
The projector stacks ``stack_factor`` encoder frames per LLM token. If the last group is partial, it is filled
|
|
186
|
+
with whatever follows in the padded batch tensor, so the same clip would read differently depending on its
|
|
187
|
+
batch neighbours. Aligning every clip to full groups (160 ms for Whisper and Qwen3-ASR encoders at stack 8
|
|
188
|
+
and 2) makes every answer independent of batch composition.
|
|
189
|
+
"""
|
|
190
|
+
hop = 160 * int(getattr(self.processor, "encoder_ds_factor", 2)) * int(getattr(self.processor, "stack_factor", 8))
|
|
191
|
+
r = (-len(a)) % hop
|
|
192
|
+
return np.concatenate([np.zeros(r, dtype=np.float32), a]) if r else a
|
|
193
|
+
|
|
194
|
+
def _encode_prefix(self, item: dict, lang: str) -> dict:
|
|
195
|
+
audio = item.get("audio")
|
|
196
|
+
text = item.get("text")
|
|
197
|
+
if audio is not None and not self.is_audio:
|
|
198
|
+
raise ValueError("this model is text-only; pass `text` (a transcript) instead of `audio`")
|
|
199
|
+
if audio is not None:
|
|
200
|
+
content = PROMPTS[lang]["audio"]
|
|
201
|
+
if text:
|
|
202
|
+
content = PROMPTS[lang]["transcript"].format(t=text) + "\n" + content
|
|
203
|
+
elif text is not None:
|
|
204
|
+
content = PROMPTS[lang]["transcript"].format(t=text)
|
|
205
|
+
else:
|
|
206
|
+
raise ValueError("each item needs `audio` or `text`")
|
|
207
|
+
head, tail = self._head_tail(item.get("context"), content, lang)
|
|
208
|
+
if audio is not None:
|
|
209
|
+
p = self.processor(text=head, audio=self._align(load_audio(audio)), sampling_rate=SAMPLE_RATE, return_tensors="pt")
|
|
210
|
+
ids = p["input_ids"][0].tolist()
|
|
211
|
+
aud = {k: p[k] for k in ("audio_values", "audio_lens", "audio_token_len", "audio_token_start_idx", "audio_batch_size") if k in p}
|
|
212
|
+
if "audio_batch_size" not in aud:
|
|
213
|
+
aud["audio_batch_size"] = torch.tensor([p["audio_values"].shape[0]])
|
|
214
|
+
else:
|
|
215
|
+
ids = self.tok(head, add_special_tokens=False)["input_ids"]
|
|
216
|
+
aud = None
|
|
217
|
+
return {"ids": ids, "audio": aud, "tail": tail}
|
|
218
|
+
|
|
219
|
+
def _suffixes(self, qs: list[Question], tail: str, n_perm: int, seed: int):
|
|
220
|
+
"""Token ids of every (question, permutation) suffix, with the letter ids to read."""
|
|
221
|
+
out = []
|
|
222
|
+
for qi, q in enumerate(qs):
|
|
223
|
+
for k in range(n_perm):
|
|
224
|
+
perm = q.permutation(seed + k)
|
|
225
|
+
ids = self.tok(q.render(perm) + tail, add_special_tokens=False)["input_ids"]
|
|
226
|
+
letters = [self._letter_id(c) for c in q.letters()]
|
|
227
|
+
out.append({"q": qi, "perm": perm, "ids": ids, "letters": letters})
|
|
228
|
+
return out
|
|
229
|
+
|
|
230
|
+
# ------------------------------------------------------------------ collation
|
|
231
|
+
def _collate(self, rows: list[tuple[list[int], dict | None]]) -> dict:
|
|
232
|
+
"""Left-pad token rows; stack audio (right-padded) and shift audio start indices by the left padding."""
|
|
233
|
+
L = max(len(r[0]) for r in rows)
|
|
234
|
+
ids = torch.full((len(rows), L), self.pad_id, dtype=torch.long)
|
|
235
|
+
mask = torch.zeros((len(rows), L), dtype=torch.long)
|
|
236
|
+
for i, (r, _) in enumerate(rows):
|
|
237
|
+
ids[i, L - len(r):] = torch.tensor(r)
|
|
238
|
+
mask[i, L - len(r):] = 1
|
|
239
|
+
batch = {"input_ids": ids, "attention_mask": mask}
|
|
240
|
+
if any(a is not None for _, a in rows):
|
|
241
|
+
vals, lens, tlen, start, bs = [], [], [], [], []
|
|
242
|
+
for r, a in rows:
|
|
243
|
+
if a is None:
|
|
244
|
+
raise ValueError("cannot mix items with and without audio in one call")
|
|
245
|
+
shift = L - len(r)
|
|
246
|
+
vals += list(a["audio_values"])
|
|
247
|
+
lens.append(a["audio_lens"])
|
|
248
|
+
tlen.append(a["audio_token_len"])
|
|
249
|
+
start.append(a["audio_token_start_idx"] + shift)
|
|
250
|
+
bs.append(a["audio_batch_size"].view(-1))
|
|
251
|
+
T = max(v.shape[-1] for v in vals)
|
|
252
|
+
batch["audio_values"] = torch.stack([torch.nn.functional.pad(v, (0, T - v.shape[-1])) for v in vals])
|
|
253
|
+
batch["audio_lens"] = torch.cat(lens)
|
|
254
|
+
batch["audio_token_len"] = torch.cat(tlen)
|
|
255
|
+
batch["audio_token_start_idx"] = torch.cat(start)
|
|
256
|
+
batch["audio_batch_size"] = torch.cat(bs)
|
|
257
|
+
out = {k: v.to(self.device) for k, v in batch.items()}
|
|
258
|
+
if "audio_values" in out:
|
|
259
|
+
out["audio_values"] = out["audio_values"].to(self.model.dtype)
|
|
260
|
+
return out
|
|
261
|
+
|
|
262
|
+
def _letter_logits(self, h: torch.Tensor, letters: Sequence[int]) -> torch.Tensor:
|
|
263
|
+
"""Logits of the option letters only, from final hidden states ``h`` [..., d]."""
|
|
264
|
+
W = self.head.weight[list(letters)]
|
|
265
|
+
z = h.to(W.dtype) @ W.T
|
|
266
|
+
if getattr(self.head, "bias", None) is not None:
|
|
267
|
+
z = z + self.head.bias[list(letters)]
|
|
268
|
+
return z.float()
|
|
269
|
+
|
|
270
|
+
# ------------------------------------------------------------------ public API
|
|
271
|
+
@torch.no_grad()
|
|
272
|
+
def decide(
|
|
273
|
+
self,
|
|
274
|
+
items: Iterable[Any],
|
|
275
|
+
questions: Sequence[Question | dict] | None = None,
|
|
276
|
+
*,
|
|
277
|
+
mode: str = "packed",
|
|
278
|
+
n_perm: int = 1,
|
|
279
|
+
seed: int = 0,
|
|
280
|
+
lang: str | None = None,
|
|
281
|
+
max_items: int | None = None,
|
|
282
|
+
max_tokens: int | None = None,
|
|
283
|
+
) -> list[dict]:
|
|
284
|
+
"""Answer every question about every item in one batched pass.
|
|
285
|
+
|
|
286
|
+
Args:
|
|
287
|
+
items: audio arrays / file paths, transcript strings, or dicts with ``audio`` and/or ``text``, optional
|
|
288
|
+
``context`` and optional per-item ``questions``.
|
|
289
|
+
questions: questions asked of every item (unless an item brings its own).
|
|
290
|
+
mode: ``"packed"`` (prefix sharing, default) or ``"batch"`` (one row per question; reference).
|
|
291
|
+
n_perm: average over this many option orders (reduces position bias; costs more suffix tokens).
|
|
292
|
+
seed: selects the option orders.
|
|
293
|
+
lang: language of the fixed prompt words; defaults to each item's ``lang`` or the first question's.
|
|
294
|
+
max_items: split into forward passes of at most this many items.
|
|
295
|
+
max_tokens: split so that each pass holds at most this many prompt tokens (prefixes + all suffixes).
|
|
296
|
+
Bounds activation memory; an item larger than the budget still runs, alone.
|
|
297
|
+
|
|
298
|
+
Returns:
|
|
299
|
+
one dict per item: ``{question_id: {"answer": option, "confidence": p, "probs": {option: p}}}``.
|
|
300
|
+
"""
|
|
301
|
+
items = [as_item(x) for x in items]
|
|
302
|
+
if not items:
|
|
303
|
+
return []
|
|
304
|
+
t0 = time.perf_counter()
|
|
305
|
+
plans = []
|
|
306
|
+
for it in items:
|
|
307
|
+
qs = as_questions(it.get("questions") or questions or [])
|
|
308
|
+
if not qs:
|
|
309
|
+
raise ValueError("no questions given")
|
|
310
|
+
lg = lang or it.get("lang") or qs[0].lang
|
|
311
|
+
pre = self._encode_prefix(it, lg)
|
|
312
|
+
plans.append({"qs": qs, "pre": pre, "sufs": self._suffixes(qs, pre["tail"], n_perm, seed)})
|
|
313
|
+
t_enc = time.perf_counter()
|
|
314
|
+
if mode not in ("packed", "batch"):
|
|
315
|
+
raise ValueError("mode must be 'packed' or 'batch'")
|
|
316
|
+
run = self._run_packed if mode == "packed" else self._run_batch
|
|
317
|
+
n_pass = 0
|
|
318
|
+
for with_audio in (True, False): # speech and text-only items go in separate passes
|
|
319
|
+
group = [p for p in plans if (p["pre"]["audio"] is not None) == with_audio]
|
|
320
|
+
for chunk in _chunks(group, max_items, max_tokens, packed=mode == "packed"):
|
|
321
|
+
run(chunk)
|
|
322
|
+
n_pass += 1
|
|
323
|
+
if self.device.type == "cuda":
|
|
324
|
+
torch.cuda.synchronize(self.device)
|
|
325
|
+
t_fwd = time.perf_counter()
|
|
326
|
+
results = [self._collect(p) for p in plans]
|
|
327
|
+
self.last_stats = {
|
|
328
|
+
"mode": mode,
|
|
329
|
+
"items": len(items),
|
|
330
|
+
"questions": sum(len(p["qs"]) for p in plans),
|
|
331
|
+
"prefix_tokens": sum(len(p["pre"]["ids"]) for p in plans),
|
|
332
|
+
"suffix_tokens": sum(len(s["ids"]) for p in plans for s in p["sufs"]),
|
|
333
|
+
"prepare_ms": round((t_enc - t0) * 1000, 2),
|
|
334
|
+
"forward_ms": round((t_fwd - t_enc) * 1000, 2),
|
|
335
|
+
"batches": n_pass,
|
|
336
|
+
"decode_steps": 0,
|
|
337
|
+
}
|
|
338
|
+
return results
|
|
339
|
+
|
|
340
|
+
def _run_batch(self, plans):
|
|
341
|
+
rows, where = [], []
|
|
342
|
+
for pi, p in enumerate(plans):
|
|
343
|
+
for si, s in enumerate(p["sufs"]):
|
|
344
|
+
rows.append((p["pre"]["ids"] + s["ids"], p["pre"]["audio"]))
|
|
345
|
+
where.append((pi, si))
|
|
346
|
+
batch = self._collate(rows)
|
|
347
|
+
if self.is_audio: # Ultravox merges audio inside its own forward; read last-position logits
|
|
348
|
+
last = self.model(**batch, use_cache=False, logits_to_keep=1).logits[:, -1].float()
|
|
349
|
+
for r, (pi, si) in enumerate(where):
|
|
350
|
+
s = plans[pi]["sufs"][si]
|
|
351
|
+
s["z"] = last[r, torch.tensor(s["letters"], device=last.device)]
|
|
352
|
+
return
|
|
353
|
+
h = self.base(input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], use_cache=False)
|
|
354
|
+
h = h.last_hidden_state[:, -1]
|
|
355
|
+
for r, (pi, si) in enumerate(where):
|
|
356
|
+
s = plans[pi]["sufs"][si]
|
|
357
|
+
s["z"] = self._letter_logits(h[r], s["letters"])
|
|
358
|
+
|
|
359
|
+
def _run_packed(self, plans):
|
|
360
|
+
# 1) prefill all prefixes together (left-padded); keep the KV cache
|
|
361
|
+
batch = self._collate([(p["pre"]["ids"], p["pre"]["audio"]) for p in plans])
|
|
362
|
+
P = batch["input_ids"].shape[1]
|
|
363
|
+
if self.is_audio:
|
|
364
|
+
out = self.model(**batch, use_cache=True, logits_to_keep=1)
|
|
365
|
+
else:
|
|
366
|
+
out = self.base(input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], use_cache=True)
|
|
367
|
+
cache = out.past_key_values
|
|
368
|
+
# 2) all suffixes of an item in one row; block-diagonal causal mask over the suffix part
|
|
369
|
+
B = len(plans)
|
|
370
|
+
lens = [[len(s["ids"]) for s in p["sufs"]] for p in plans]
|
|
371
|
+
T = max(sum(l) for l in lens)
|
|
372
|
+
dt = self.model.dtype
|
|
373
|
+
neg = torch.finfo(dt).min
|
|
374
|
+
ids = torch.full((B, T), self.pad_id, dtype=torch.long)
|
|
375
|
+
pos = torch.full((B, T), P, dtype=torch.long)
|
|
376
|
+
mask = torch.full((B, 1, T, P + T), neg, dtype=dt)
|
|
377
|
+
mask[:, 0, :, :P] = torch.where(batch["attention_mask"].cpu()[:, None, :].bool(), 0.0, neg).to(dt)
|
|
378
|
+
last = []
|
|
379
|
+
for b, p in enumerate(plans):
|
|
380
|
+
o, lb = 0, []
|
|
381
|
+
for s in p["sufs"]:
|
|
382
|
+
n = len(s["ids"])
|
|
383
|
+
ids[b, o:o + n] = torch.tensor(s["ids"])
|
|
384
|
+
pos[b, o:o + n] = P + torch.arange(n)
|
|
385
|
+
mask[b, 0, o:o + n, P + o:P + o + n] = torch.triu(torch.full((n, n), neg, dtype=dt), 1)
|
|
386
|
+
lb.append(o + n - 1)
|
|
387
|
+
o += n
|
|
388
|
+
for t in range(o, T): # padding rows: attend to themselves only (never read)
|
|
389
|
+
mask[b, 0, t, P + t] = 0
|
|
390
|
+
last.append(lb)
|
|
391
|
+
out2 = self.base(
|
|
392
|
+
input_ids=ids.to(self.device),
|
|
393
|
+
attention_mask=mask.to(self.device),
|
|
394
|
+
position_ids=pos.to(self.device),
|
|
395
|
+
past_key_values=cache,
|
|
396
|
+
use_cache=False,
|
|
397
|
+
)
|
|
398
|
+
h = out2.last_hidden_state
|
|
399
|
+
for b, p in enumerate(plans):
|
|
400
|
+
hb = h[b, torch.tensor(last[b], device=h.device)]
|
|
401
|
+
for s, hv in zip(p["sufs"], hb):
|
|
402
|
+
s["z"] = self._letter_logits(hv, s["letters"])
|
|
403
|
+
|
|
404
|
+
def _collect(self, plan) -> dict:
|
|
405
|
+
res = {}
|
|
406
|
+
for qi, q in enumerate(plan["qs"]):
|
|
407
|
+
acc = np.zeros(len(q.options))
|
|
408
|
+
sufs = [s for s in plan["sufs"] if s["q"] == qi]
|
|
409
|
+
for s in sufs:
|
|
410
|
+
z = s["z"]
|
|
411
|
+
p = torch.softmax(z.float(), -1).cpu().numpy()
|
|
412
|
+
for i, j in enumerate(s["perm"]):
|
|
413
|
+
acc[j] += p[i]
|
|
414
|
+
acc /= len(sufs)
|
|
415
|
+
k = int(acc.argmax())
|
|
416
|
+
res[q.id] = {
|
|
417
|
+
"answer": q.options[k],
|
|
418
|
+
"confidence": round(float(acc[k]), 6),
|
|
419
|
+
"probs": {o: round(float(v), 6) for o, v in zip(q.options, acc)},
|
|
420
|
+
}
|
|
421
|
+
return res
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def _chunks(plans, max_items, max_tokens, packed=True):
|
|
425
|
+
"""Split plans into passes bounded by item count and by prompt tokens."""
|
|
426
|
+
def cost(p):
|
|
427
|
+
pre, suf = len(p["pre"]["ids"]), [len(s["ids"]) for s in p["sufs"]]
|
|
428
|
+
return pre + sum(suf) if packed else len(suf) * pre + sum(suf)
|
|
429
|
+
|
|
430
|
+
cur, tok = [], 0
|
|
431
|
+
for p in plans:
|
|
432
|
+
c = cost(p)
|
|
433
|
+
if cur and ((max_items and len(cur) >= max_items) or (max_tokens and tok + c > max_tokens)):
|
|
434
|
+
yield cur
|
|
435
|
+
cur, tok = [], 0
|
|
436
|
+
cur.append(p)
|
|
437
|
+
tok += c
|
|
438
|
+
if cur:
|
|
439
|
+
yield cur
|
duplexjev/question.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Typed closed-set questions and how they are rendered into a prompt suffix."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import random
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Sequence
|
|
8
|
+
|
|
9
|
+
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
10
|
+
|
|
11
|
+
TEMPLATES = {
|
|
12
|
+
"en": {
|
|
13
|
+
"question": "Question: {q}",
|
|
14
|
+
"options": "Options:",
|
|
15
|
+
"instruction": "Answer with only the letter of the correct option.",
|
|
16
|
+
},
|
|
17
|
+
"zh": {
|
|
18
|
+
"question": "问题:{q}",
|
|
19
|
+
"options": "选项:",
|
|
20
|
+
"instruction": "请只回答正确选项的字母。",
|
|
21
|
+
},
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class Question:
|
|
27
|
+
"""One runtime-declared decision.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
id: key used in the result (e.g. ``"turn"``).
|
|
31
|
+
text: the question as the model should read it.
|
|
32
|
+
options: 2–26 answer options; the result is a probability for each.
|
|
33
|
+
lang: prompt language for the fixed words (``"en"`` or ``"zh"``).
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
id: str
|
|
37
|
+
text: str
|
|
38
|
+
options: Sequence[str]
|
|
39
|
+
lang: str = "en"
|
|
40
|
+
_options: tuple = field(init=False, repr=False, compare=False)
|
|
41
|
+
|
|
42
|
+
def __post_init__(self):
|
|
43
|
+
opts = tuple(str(o) for o in self.options)
|
|
44
|
+
if not self.id:
|
|
45
|
+
raise ValueError("Question.id must be non-empty")
|
|
46
|
+
if not self.text:
|
|
47
|
+
raise ValueError(f"Question {self.id!r}: text must be non-empty")
|
|
48
|
+
if not 2 <= len(opts) <= len(LETTERS):
|
|
49
|
+
raise ValueError(f"Question {self.id!r}: needs 2..{len(LETTERS)} options, got {len(opts)}")
|
|
50
|
+
if len(set(opts)) != len(opts):
|
|
51
|
+
raise ValueError(f"Question {self.id!r}: options must be distinct")
|
|
52
|
+
if self.lang not in TEMPLATES:
|
|
53
|
+
raise ValueError(f"Question {self.id!r}: lang must be one of {sorted(TEMPLATES)}")
|
|
54
|
+
object.__setattr__(self, "_options", opts)
|
|
55
|
+
object.__setattr__(self, "options", opts)
|
|
56
|
+
|
|
57
|
+
@classmethod
|
|
58
|
+
def from_dict(cls, d: dict) -> "Question":
|
|
59
|
+
return cls(id=d["id"], text=d["text"], options=d["options"], lang=d.get("lang", "en"))
|
|
60
|
+
|
|
61
|
+
def to_dict(self) -> dict:
|
|
62
|
+
return {"id": self.id, "text": self.text, "options": list(self.options), "lang": self.lang}
|
|
63
|
+
|
|
64
|
+
# ------------------------------------------------------------------ rendering
|
|
65
|
+
def permutation(self, seed: int = 0) -> list[int]:
|
|
66
|
+
"""Deterministic option order for this question: letter i shows option perm[i].
|
|
67
|
+
|
|
68
|
+
Options are shown under permuted letters so that no option is tied to a fixed position. The order depends
|
|
69
|
+
only on (question id, options, seed), so results are reproducible and identical across batch layouts.
|
|
70
|
+
"""
|
|
71
|
+
key = "\x1f".join([self.id, "\x1e".join(self.options), str(seed)]).encode()
|
|
72
|
+
rng = random.Random(int.from_bytes(hashlib.blake2b(key, digest_size=8).digest(), "big"))
|
|
73
|
+
perm = list(range(len(self.options)))
|
|
74
|
+
rng.shuffle(perm)
|
|
75
|
+
return perm
|
|
76
|
+
|
|
77
|
+
def render(self, perm: Sequence[int]) -> str:
|
|
78
|
+
t = TEMPLATES[self.lang]
|
|
79
|
+
lines = [t["question"].format(q=self.text), "", t["options"]]
|
|
80
|
+
lines += [f"{LETTERS[i]}. {self.options[j]}" for i, j in enumerate(perm)]
|
|
81
|
+
lines += ["", t["instruction"]]
|
|
82
|
+
return "\n".join(lines)
|
|
83
|
+
|
|
84
|
+
def letters(self) -> str:
|
|
85
|
+
return LETTERS[: len(self.options)]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def as_questions(qs) -> list[Question]:
|
|
89
|
+
out = []
|
|
90
|
+
for q in qs:
|
|
91
|
+
out.append(q if isinstance(q, Question) else Question.from_dict(q))
|
|
92
|
+
ids = [q.id for q in out]
|
|
93
|
+
if len(set(ids)) != len(ids):
|
|
94
|
+
raise ValueError(f"duplicate question ids: {ids}")
|
|
95
|
+
return out
|
duplexjev/server.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""HTTP server that batches every request arriving within one tick into a single decision pass.
|
|
2
|
+
|
|
3
|
+
duplexjev serve --model Qwen/Qwen3-8B --tick-ms 160
|
|
4
|
+
|
|
5
|
+
Clients POST to ``/v1/decide``; the server collects all pending requests every ``tick_ms`` milliseconds (e.g. the
|
|
6
|
+
latest audio window of every live call), answers all of their questions in one batched pass, and returns each
|
|
7
|
+
request's own answers. Latency per request is at most one tick of waiting plus one pass.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import base64
|
|
13
|
+
import io
|
|
14
|
+
import time
|
|
15
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
16
|
+
from typing import Any, List, Optional
|
|
17
|
+
|
|
18
|
+
from .decider import Decider
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _decode_audio(b64: str):
|
|
22
|
+
import soundfile as sf
|
|
23
|
+
|
|
24
|
+
a, sr = sf.read(io.BytesIO(base64.b64decode(b64)), dtype="float32")
|
|
25
|
+
return (a, sr)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class TickBatcher:
|
|
29
|
+
"""Collect requests and run them together once per tick on a single worker thread."""
|
|
30
|
+
|
|
31
|
+
def __init__(self, decider: Decider, tick_ms: float = 160.0, max_items: Optional[int] = None, mode: str = "packed"):
|
|
32
|
+
self.d = decider
|
|
33
|
+
self.tick = tick_ms / 1000.0
|
|
34
|
+
self.max_items = max_items
|
|
35
|
+
self.mode = mode
|
|
36
|
+
self.pending: list[tuple[dict, asyncio.Future, float]] = []
|
|
37
|
+
self.pool = ThreadPoolExecutor(max_workers=1)
|
|
38
|
+
self.ticks = 0
|
|
39
|
+
self._task: Optional[asyncio.Task] = None
|
|
40
|
+
|
|
41
|
+
def start(self):
|
|
42
|
+
self._task = asyncio.get_running_loop().create_task(self._loop())
|
|
43
|
+
|
|
44
|
+
async def submit(self, item: dict) -> dict:
|
|
45
|
+
fut = asyncio.get_running_loop().create_future()
|
|
46
|
+
self.pending.append((item, fut, time.perf_counter()))
|
|
47
|
+
return await fut
|
|
48
|
+
|
|
49
|
+
async def _loop(self):
|
|
50
|
+
loop = asyncio.get_running_loop()
|
|
51
|
+
nxt = loop.time()
|
|
52
|
+
while True:
|
|
53
|
+
nxt += self.tick
|
|
54
|
+
await asyncio.sleep(max(0.0, nxt - loop.time()))
|
|
55
|
+
if not self.pending:
|
|
56
|
+
continue
|
|
57
|
+
batch, self.pending = self.pending, []
|
|
58
|
+
self.ticks += 1
|
|
59
|
+
tick_id, t0 = self.ticks, time.perf_counter()
|
|
60
|
+
try:
|
|
61
|
+
res = await loop.run_in_executor(
|
|
62
|
+
self.pool, lambda: self.d.decide([b[0] for b in batch], mode=self.mode, max_items=self.max_items)
|
|
63
|
+
)
|
|
64
|
+
stats = dict(self.d.last_stats)
|
|
65
|
+
for (item, fut, t_in), r in zip(batch, res):
|
|
66
|
+
if not fut.done():
|
|
67
|
+
fut.set_result({
|
|
68
|
+
"answers": r,
|
|
69
|
+
"tick": tick_id,
|
|
70
|
+
"batch_items": len(batch),
|
|
71
|
+
"wait_ms": round((t0 - t_in) * 1000, 1),
|
|
72
|
+
"pass_ms": round((time.perf_counter() - t0) * 1000, 1),
|
|
73
|
+
"pass": stats,
|
|
74
|
+
})
|
|
75
|
+
except Exception as e: # report the error to every request of this tick
|
|
76
|
+
for _, fut, _ in batch:
|
|
77
|
+
if not fut.done():
|
|
78
|
+
fut.set_exception(e)
|
|
79
|
+
if loop.time() > nxt: # a long pass: start the next tick now instead of catching up
|
|
80
|
+
nxt = loop.time()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def create_app(decider: Decider, tick_ms: float = 160.0, max_items: Optional[int] = None):
|
|
84
|
+
from fastapi import FastAPI, HTTPException
|
|
85
|
+
from pydantic import BaseModel
|
|
86
|
+
|
|
87
|
+
class QuestionIn(BaseModel):
|
|
88
|
+
id: str
|
|
89
|
+
text: str
|
|
90
|
+
options: List[str]
|
|
91
|
+
lang: str = "en"
|
|
92
|
+
|
|
93
|
+
class DecideIn(BaseModel):
|
|
94
|
+
questions: List[QuestionIn]
|
|
95
|
+
audio_b64: Optional[str] = None # WAV/FLAC bytes, base64
|
|
96
|
+
text: Optional[str] = None # transcript (text-only models, or extra context for speech models)
|
|
97
|
+
context: Optional[str] = None
|
|
98
|
+
lang: Optional[str] = None
|
|
99
|
+
|
|
100
|
+
app = FastAPI(title="DuplexJev decider", version="0.1.0")
|
|
101
|
+
batcher = TickBatcher(decider, tick_ms=tick_ms, max_items=max_items)
|
|
102
|
+
|
|
103
|
+
@app.on_event("startup")
|
|
104
|
+
async def _start():
|
|
105
|
+
batcher.start()
|
|
106
|
+
|
|
107
|
+
@app.get("/health")
|
|
108
|
+
async def health() -> dict[str, Any]:
|
|
109
|
+
return {"ok": True, "speech": decider.is_audio, "tick_ms": tick_ms, "ticks": batcher.ticks}
|
|
110
|
+
|
|
111
|
+
@app.post("/v1/decide")
|
|
112
|
+
async def decide(req: DecideIn) -> dict[str, Any]:
|
|
113
|
+
item: dict[str, Any] = {"questions": [q.model_dump() for q in req.questions]}
|
|
114
|
+
if req.audio_b64:
|
|
115
|
+
if not decider.is_audio:
|
|
116
|
+
raise HTTPException(400, "this server runs a text-only model; send `text`")
|
|
117
|
+
item["audio"] = _decode_audio(req.audio_b64)
|
|
118
|
+
if req.text is not None:
|
|
119
|
+
item["text"] = req.text
|
|
120
|
+
if "audio" not in item and "text" not in item:
|
|
121
|
+
raise HTTPException(400, "send `audio_b64` or `text`")
|
|
122
|
+
if req.context:
|
|
123
|
+
item["context"] = req.context
|
|
124
|
+
if req.lang:
|
|
125
|
+
item["lang"] = req.lang
|
|
126
|
+
try:
|
|
127
|
+
return await batcher.submit(item)
|
|
128
|
+
except ValueError as e:
|
|
129
|
+
raise HTTPException(400, str(e))
|
|
130
|
+
|
|
131
|
+
return app
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: duplexjev
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Batched typed speech decisions without decoding: one forward pass answers many closed-set questions about many calls.
|
|
5
|
+
Author: Adventists.ai
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://adventists-ai.github.io/duplexjev/
|
|
8
|
+
Project-URL: Repository, https://github.com/adventists-ai/duplexjev
|
|
9
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
License-File: NOTICE
|
|
17
|
+
Requires-Dist: torch>=2.1
|
|
18
|
+
Requires-Dist: transformers<4.58,>=4.51
|
|
19
|
+
Requires-Dist: numpy
|
|
20
|
+
Requires-Dist: soundfile
|
|
21
|
+
Requires-Dist: scipy
|
|
22
|
+
Provides-Extra: speech
|
|
23
|
+
Requires-Dist: accelerate; extra == "speech"
|
|
24
|
+
Requires-Dist: peft; extra == "speech"
|
|
25
|
+
Requires-Dist: transformers<4.56,>=4.51; extra == "speech"
|
|
26
|
+
Provides-Extra: server
|
|
27
|
+
Requires-Dist: fastapi; extra == "server"
|
|
28
|
+
Requires-Dist: uvicorn; extra == "server"
|
|
29
|
+
Requires-Dist: pydantic>=2; extra == "server"
|
|
30
|
+
Provides-Extra: all
|
|
31
|
+
Requires-Dist: accelerate; extra == "all"
|
|
32
|
+
Requires-Dist: peft; extra == "all"
|
|
33
|
+
Requires-Dist: transformers<4.56,>=4.51; extra == "all"
|
|
34
|
+
Requires-Dist: fastapi; extra == "all"
|
|
35
|
+
Requires-Dist: uvicorn; extra == "all"
|
|
36
|
+
Requires-Dist: pydantic>=2; extra == "all"
|
|
37
|
+
Provides-Extra: dev
|
|
38
|
+
Requires-Dist: pytest; extra == "dev"
|
|
39
|
+
Requires-Dist: httpx; extra == "dev"
|
|
40
|
+
Dynamic: license-file
|
|
41
|
+
|
|
42
|
+
# duplexjev
|
|
43
|
+
|
|
44
|
+
Batched typed speech decisions without decoding. Every question — *has the user finished? which filler? which intent?*
|
|
45
|
+
— is answered as a probability over its options from a **single forward pass**, with no ASR or text decoding. Many
|
|
46
|
+
questions about many calls share one pass, with exact prefix sharing.
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pip install duplexjev # text models
|
|
50
|
+
pip install "duplexjev[all]" # + speech checkpoints and the HTTP server
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from duplexjev import Decider, Question
|
|
55
|
+
|
|
56
|
+
d = Decider.from_pretrained("Qwen/Qwen3-8B") # any causal LM; or a speech checkpoint (see below)
|
|
57
|
+
qs = [Question("turn", "Has the user finished the turn?", ["finished", "not finished"]),
|
|
58
|
+
Question("intent", "What does the user want?", ["climate", "media", "navigation", "phone"])]
|
|
59
|
+
d.decide(["Turn on the air conditioning", "Navigate to the"], qs)
|
|
60
|
+
# [{'turn': {'answer': 'finished', 'confidence': 0.97, 'probs': {...}}, 'intent': {...}}, {...}]
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Speech checkpoints (Ultravox format, including the DuplexJev adapters) take audio directly:
|
|
64
|
+
`Decider.from_pretrained("fixie-ai/ultravox-v0_6-qwen-3-32b").decide(["call1.wav", "call2.wav"], qs)`.
|
|
65
|
+
|
|
66
|
+
Serve with tick batching: `duplexjev serve --model <id> --tick-ms 160`.
|
|
67
|
+
|
|
68
|
+
Project: https://github.com/adventists-ai/duplexjev · License: Apache-2.0
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
duplexjev/__init__.py,sha256=0DMWmoPp6gCKLW7LvhcKx2MLgio773IWERWkKXKUyG0,478
|
|
2
|
+
duplexjev/cli.py,sha256=7UuUTP4xRQtFM5Z3OdK7CI2DiCJ5ON05dd2Odw2yblU,3422
|
|
3
|
+
duplexjev/decider.py,sha256=n0NGL7PZ9FGKZYYYxcEZxMkicDFW-HUE4HPVu8xVE7g,21449
|
|
4
|
+
duplexjev/question.py,sha256=UGpAt0iRVRD0ktAYJ81t9ZMzNhkrvJX6gI7oRhiOqcI,3564
|
|
5
|
+
duplexjev/server.py,sha256=YeKTbTfdqb-pd9-LiRkp4DsxBoFqFW3rFCbwUVoYyVQ,5004
|
|
6
|
+
duplexjev-0.1.0.dist-info/licenses/LICENSE,sha256=gy3Z4Apo3YOzw_ufVYja19zzN6DbUPfZSD8xDNKS6S4,11343
|
|
7
|
+
duplexjev-0.1.0.dist-info/licenses/NOTICE,sha256=76RaOn2q4eZLBnS3RPnh9yBNJzvvq97TOQwsZRUAKxA,1331
|
|
8
|
+
duplexjev-0.1.0.dist-info/METADATA,sha256=YoVUD5hiHaILdEedrdjhriUAsQy28sRqKn4bQPImdQI,2859
|
|
9
|
+
duplexjev-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
10
|
+
duplexjev-0.1.0.dist-info/entry_points.txt,sha256=2A-uIDgP-5sswzVt1vRmsiUP5DTsdYkgt2VdfrbwR78,49
|
|
11
|
+
duplexjev-0.1.0.dist-info/top_level.txt,sha256=uEOPsH-VnHYzHmQT4-TiPMeUEbC40Tm-AGmZAA68RDI,10
|
|
12
|
+
duplexjev-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2024 Alibaba Cloud
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
DuplexJev
|
|
2
|
+
Copyright 2026 Adventists.ai and the DuplexJev authors.
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0 (see LICENSE), except where noted below.
|
|
5
|
+
|
|
6
|
+
Third-party components
|
|
7
|
+
- Ultravox (https://github.com/fixie-ai/ultravox), MIT License, Copyright (c) 2023 Fixie.ai.
|
|
8
|
+
Training code in training/ patches and extends Ultravox; the projector design follows Ultravox.
|
|
9
|
+
- Qwen3 / Qwen3-ASR (https://github.com/QwenLM), Apache License 2.0. duplexjev/encoder/ is derived from the
|
|
10
|
+
Qwen3-ASR encoder implementation.
|
|
11
|
+
- Model weights released with this project contain only the trained fusion and projector parameters; the frozen
|
|
12
|
+
Qwen3-ASR-0.6B encoder and Qwen3-32B LLM must be obtained from their original sources under their licenses.
|
|
13
|
+
|
|
14
|
+
Datasets
|
|
15
|
+
- qa100 (https://huggingface.co/datasets/adventists-ai/qa100): created by the authors, released under CC-BY-4.0. Audio synthesised with VoxCPM2.
|
|
16
|
+
- Training data (Ultravox v0.6 mixture: WenetSpeech, GigaSpeech, Common Voice 17, People's Speech, LibriSpeech,
|
|
17
|
+
Multilingual LibriSpeech, CoVoST 2, MUSAN) is NOT redistributed; see each dataset's license.
|
|
18
|
+
- ZJU audio-gender-benchmark (https://github.com/Vsky-morigen/audio-gender-benchmark) is used for evaluation only and
|
|
19
|
+
is NOT redistributed here. Its main-language subset includes ODSQA audio whose redistribution terms are unclear.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
duplexjev
|