Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.
Python calibrationclassificationdecision-modelhuggingfacejevmodernbertmultilingualnlppythonpytorchroutingtyped-decisionszero-shot
feat(common): report options that collapse into the same token span
AlKor13ac1bc7846898
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 7a9cca5f..c69cd3b6 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -114,6 +114,7 @@ jobs:python tests/test_tokenizer_concurrency.pypython tests/test_lazy_import.pypython tests/test_runtime_fixes.py+ python tests/test_option_collapse.pypython tests/test_lang_guess.pypython tests/test_identifier_complexity.pypython tests/test_lang_stats.pydiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 8344b4ba..2c289a81 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -50,6 +50,7 @@ jobs:python tests/test_packaging.pypython tests/test_doc_tables.pypython tests/test_lang_guess.py+ python tests/test_option_collapse.pypython tests/test_calibration_persistence.pypython tests/test_context_manager.pypython tests/test_criteria_normalization.pydiff --git a/laya/agent.py b/laya/agent.pyindex 1b58de6f..92f56645 100644--- a/laya/agent.py+++ b/laya/agent.py@@ -18,6 +18,7 @@ from .common import (amp_dtype,build_model,build_sequence,+ collapsed_options,clamp_temperature,collate_items,answer_confidence,@@ -670,11 +671,12 @@ class Agent(HookRegistry):items = []for qid in ids:q = internal[qid]- seq, markers = build_sequence(self.tok, state, q, max_len, head_max_len,- truncate_left=truncate_left, state_ids=state_ids)+ seq, markers, stats = build_sequence(self.tok, state, q, max_len, head_max_len,+ truncate_left=truncate_left, state_ids=state_ids,+ return_stats=True)if len(markers) != len(render_options(q)):raise ValueError("question %r options exceed head_max_len=%d" % (qid, head_max_len))- items.append({"ids": seq, "markers": markers, "qtype": QTYPES[q["t"]]})+ items.append({"ids": seq, "markers": markers, "qtype": QTYPES[q["t"]], "options": stats})return itemsdef _amp_enabled_for(self, rows: int) -> bool:@@ -923,10 +925,19 @@ class Agent(HookRegistry):n_tokens = int(att[row:row + nrows].sum())answers = self._decode_answers(logits, act, items, ids, internal, row,**({"lang": lang} if lang else {}))+ usage = {"input_tokens": n_tokens, "output_tokens": 0}+ # Only when a question actually lost options to the head+ # budget: an answer chosen from 42 distinguishable spans of+ # 58 has a ceiling the caller cannot otherwise see, and a+ # key that is always present would be noise on the+ # overwhelming majority of requests that never collapse.+ collapsed = collapsed_options(ids, items)+ if collapsed:+ usage["options"] = collapsedwindow_results[index] = {"model": "laya-rl-agent","answers": answers,- "usage": {"input_tokens": n_tokens, "output_tokens": 0},+ "usage": usage,}row += nrowsresults.extend(window_results)@@ -1082,6 +1093,12 @@ class Agent(HookRegistry):Empty questions return empty answers and zero token usage without tokenizationor a model forward pass.+ When the head budget leaves two options with the same token span, `usage` carries+ an `options` entry for each question it happened to -- `total`, `distinct` and+ `tokens_per_option` -- because an answer chosen among 42 distinguishable spans of+ 58 has a ceiling that is the budget's and not the model's. Questions whose options+ all survive are absent, so a request that collapses nothing is unchanged.+To score many states at once, see `predict_batch`, which shares forward passes across them."""return self.predict_batch([state], questions, lang=lang, hooks=hooks,diff --git a/laya/common.py b/laya/common.pyindex 91f702a5..08b67db3 100644--- a/laya/common.py+++ b/laya/common.py@@ -100,11 +100,16 @@ def build_sequence(option_order: Optional[List[int]] = None,truncate_left: bool = False,state_ids: Optional[List[int]] = None,+ return_stats: bool = False,):"""Format: [CLS] <type> instructions [SEP] [MASK] opt0 [MASK] opt1 ... [SEP] state [SEP].`state_ids` lets a caller tokenize the shared state once and reuse it across every question,instead of re-serializing and re-tokenizing the same document per question.++ `return_stats` adds a third return value describing what the head budget did to the options:+ `options` (how many the question defines), `options_distinct` (how many still have a token+ span of their own) and `tokens_per_option` (the cap applied to each, or None when none was)."""mask_tok = tok.mask_tokenopts = render_options(q)@@ -125,8 +130,10 @@ def build_sequence()["input_ids"]opt_ids.append([tok.mask_token_id] + opt_tokens)opt_budget = head_max_len - sum(len(o) for o in opt_ids)+ per_option = Noneif opt_budget < 16:per = max(4, (head_max_len - 16) // max(1, len(opt_ids)))+ per_option = peropt_ids = [o[:per] for o in opt_ids]opt_budget = head_max_len - sum(len(o) for o in opt_ids)head_ids = head_ids[: max(8, opt_budget)]@@ -143,7 +150,36 @@ def build_sequence(# not state_ids[-room:]: with no room left, state_ids[-0:] is the whole state rather than none of itst = state_ids[max(0, len(state_ids) - room):] if truncate_left else state_ids[:room]ids = ids + st + [tok.sep_token_id]- return ids[:max_len], [m for m in markers if m < max_len]+ ids, markers = ids[:max_len], [m for m in markers if m < max_len]+ if not return_stats:+ return ids, markers+ # Two options that share a prefix can come out of the cut as the same token span: the marker+ # count still matches the option count, so the guard in `Agent._encode_state` passes and+ # nothing downstream can tell that the question lost the ability to name them apart. Counted+ # on the capped option ids, before assembly: re-slicing the finished sequence cannot close+ # the last option's span -- it runs on into the serialized state, which differs per request,+ # so the last option always looks distinguishable however it collided (#538).+ return ids, markers, {+ "options": len(opt_ids),+ "options_distinct": len({tuple(o) for o in opt_ids}),+ "tokens_per_option": per_option,+ }+++def collapsed_options(qids, items) -> Dict[str, Dict[str, Optional[int]]]:+ """The questions whose options no longer have a token span each, from per-item stats.++ `total` is the number of options the question defines, not the number of markers that+ reached the sequence: a report counted from the markers would say "43/58" about a request+ where 28 options never made it into the input at all.+ """+ out = {}+ for qid, item in zip(qids, items):+ stats = item.get("options")+ if stats and stats["options_distinct"] < stats["options"]:+ out[qid] = {"total": stats["options"], "distinct": stats["options_distinct"],+ "tokens_per_option": stats["tokens_per_option"]}+ return outclass DecisionModel(nn.Module):diff --git a/laya/onnx_agent.py b/laya/onnx_agent.pyindex 0f4a19f5..88ef3355 100644--- a/laya/onnx_agent.py+++ b/laya/onnx_agent.py@@ -16,6 +16,7 @@ from laya.common import (QTYPES,answer_confidence,build_sequence,+ collapsed_options,collate_items,confidence_from_probs,encode_text,@@ -299,13 +300,13 @@ class ONNXAgent(HookRegistry):for qid in ids:q = self._to_internal(questions[qid])- seq, markers = build_sequence(+ seq, markers, stats = build_sequence(self.tok, state, q, max_len, head_max_len,- truncate_left=truncate_left, state_ids=state_ids,+ truncate_left=truncate_left, state_ids=state_ids, return_stats=True,)if len(markers) != len(render_options(q)):raise ValueError("question %r options exceed head_max_len=%d" % (qid, head_max_len))- items.append({"ids": seq, "markers": markers, "qtype": QTYPES[q["t"]]})+ items.append({"ids": seq, "markers": markers, "qtype": QTYPES[q["t"]], "options": stats})b = collate_items([items], self.tok.pad_token_id)@@ -379,10 +380,14 @@ class ONNXAgent(HookRegistry):"action": ext,}+ usage = {"input_tokens": n_tokens, "output_tokens": 0}+ collapsed = collapsed_options(ids, items)+ if collapsed:+ usage["options"] = collapsedreturn {"model": "laya-rl-agent-onnx","answers": answers,- "usage": {"input_tokens": n_tokens, "output_tokens": 0},+ "usage": usage,}def decide(self, state: Union[str, dict, list], schema: Any = None, *,diff --git a/tests/test_hooks_api.py b/tests/test_hooks_api.pyindex fa750e30..9d8f0b67 100644--- a/tests/test_hooks_api.py+++ b/tests/test_hooks_api.py@@ -157,6 +157,21 @@ for label, cls in (("Agent", Agent), ("Router", Router), ("ONNXAgent", ONNXAgentfor method in ("add_hook", "remove_hook", "hooks_installed"):check_true("%s/%s exists" % (label, method), callable(getattr(cls, method, None)))+# --------------------------------------------------------------- usage block+# `input_tokens` / `output_tokens` are the fields every client decodes, so they are always+# present. `options` (#538) is additive and conditional: it appears only for a request whose+# options lost their distinct token spans, which is what keeps it out of ordinary responses.+from laya.common import build_sequence, collapsed_options # noqa: E402++check_param("build_sequence", build_sequence, "return_stats", False)+check("collapsed_options/nothing collapsed is empty",+ collapsed_options(["q"], [{"options": {"options": 3, "options_distinct": 3,+ "tokens_per_option": None}}]), {})+check("collapsed_options/a collapsed question is reported",+ collapsed_options(["q"], [{"options": {"options": 58, "options_distinct": 42,+ "tokens_per_option": 4}}]),+ {"q": {"total": 58, "distinct": 42, "tokens_per_option": 4}})+print("\n%d passed, %d failed" % (len(PASS), len(FAIL)))for f in FAIL:diff --git a/tests/test_option_collapse.py b/tests/test_option_collapse.pynew file mode 100644index 00000000..e12fe412--- /dev/null+++ b/tests/test_option_collapse.py@@ -0,0 +1,135 @@+"""Options that collapse into the same token span must be reported (issue #538).++`build_sequence` caps every option at 48 tokens, and re-caps all of them to+`max(4, (head_max_len - 16) // n)` once they overflow the head budget. Two options that share a+prefix can survive that cut as the *same* span: the marker count still equals the option count,+so the guard in `Agent._encode_state` passes and the request is answered normally -- from a+question that can no longer name those options apart. On a 58-label question at the default+budget only 42 of 58 spans differ, which is an accuracy ceiling of 72% that nothing in the+response mentions.++No weights and no network: a character-level stub tokenizer, so a shared prefix behaves the way+a real tokenizer's does.++Run: python tests/test_option_collapse.py+"""+import os+import sys++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from laya.common import build_sequence, collapsed_options # noqa: E402++PASS, FAIL = [], []+++def check(name, got, want):+ if got == want:+ PASS.append(name)+ else:+ FAIL.append("%s:\n got %r\n want %r" % (name, got, want))+++def check_true(name, cond, detail=""):+ if cond:+ PASS.append(name)+ else:+ FAIL.append("%s %s" % (name, detail))+++class PrefixTok:+ """Character-level ids, so options that share a prefix share their leading tokens."""++ mask_token = "[MASK]"+ mask_token_id = 1+ cls_token_id = 2+ sep_token_id = 3+ pad_token_id = 0++ def __call__(self, text, add_special_tokens=False, truncation=False, max_length=None):+ ids = [10 + (ord(c) % 90) for c in text]+ if truncation and max_length is not None:+ ids = ids[:max_length]+ return {"input_ids": ids}+++TOK = PrefixTok()+# Four labels that agree for their first fourteen characters, as MASSIVE's iot_hue_light* do.+HUE = ["iot_hue_lightup", "iot_hue_lightoff", "iot_hue_lightdim", "iot_hue_lightchange"]+++def q_choice(labels):+ return {"t": "choice", "ins": "which one?", "crit": {k: k.replace("_", " ") for k in labels}}+++# ---------------------------------------------------------------- the return shape+ret = build_sequence(TOK, "a state", q_choice(["yes", "no"]), 128, 64)+check("shape/default is unchanged", len(ret), 2)+ret = build_sequence(TOK, "a state", q_choice(["yes", "no"]), 128, 64, return_stats=True)+check("shape/return_stats adds one value", len(ret), 3)+ids_a, markers_a = build_sequence(TOK, "a state", q_choice(["yes", "no"]), 128, 64)+check("shape/ids are identical either way", ret[0], ids_a)+check("shape/markers are identical either way", ret[1], markers_a)+check("shape/stat keys", sorted(ret[2]), ["options", "options_distinct", "tokens_per_option"])++# ---------------------------------------------------------------- nothing collapses+_, _, roomy = build_sequence(TOK, "a state", q_choice(HUE), 512, 256, return_stats=True)+check("roomy/every option is its own span", roomy["options_distinct"], 4)+check("roomy/counts every option", roomy["options"], 4)+check("roomy/no cap was applied", roomy["tokens_per_option"], None)++# ---------------------------------------------------------------- the cut collapses them+_, _, tight = build_sequence(TOK, "a state", q_choice(HUE), 128, 24, return_stats=True)+check("tight/a cap was applied", tight["tokens_per_option"], 4)+check("tight/still one marker per option", tight["options"], 4)+check_true("tight/but not one span per option", tight["options_distinct"] < tight["options"],+ "distinct=%r" % tight["options_distinct"])++# The number is the question's, not the state's: the same question collapses identically+# whatever it is asked about, which is what makes it computable once per question set.+_, _, other_state = build_sequence(TOK, {"body": "a completely different request"} , q_choice(HUE),+ 128, 24, return_stats=True)+check("tight/independent of the state", other_state["options_distinct"], tight["options_distinct"])++# A distinct set of labels under the same budget keeps its spans, so the report is about the+# option texts and not merely about the option count.+_, _, spread = build_sequence(TOK, "a state", q_choice(["alpha", "bravo", "charlie", "delta"]),+ 128, 24, return_stats=True)+check("tight/distinct labels survive the same cap", spread["options_distinct"], 4)++# ---------------------------------------------------------------- `total` is the question's+# Markers past `max_len` are dropped from the sequence; `options` must still count the options+# the question defines, or a report reads "2 of 2 distinct" about a question with 40 of them.+MANY = ["label_%02d" % i for i in range(40)] # distinct keys: a dict would fold repeats+_, dropped_markers, dropped = build_sequence(TOK, "a state", q_choice(MANY), 40, 400,+ return_stats=True)+check_true("markers/some were dropped by max_len", len(dropped_markers) < 40,+ "kept=%d" % len(dropped_markers))+check("markers/total still counts the question's options", dropped["options"], 40)++# ---------------------------------------------------------------- the filter+items = [{"options": {"options": 58, "options_distinct": 42, "tokens_per_option": 4}},+ {"options": {"options": 4, "options_distinct": 4, "tokens_per_option": None}},+ {"qtype": 0}]+out = collapsed_options(["intent", "dept", "legacy"], items)+check("filter/only the collapsed question", sorted(out), ["intent"])+check("filter/reports the question's own numbers", out["intent"],+ {"total": 58, "distinct": 42, "tokens_per_option": 4})+check("filter/an item without stats is skipped", "legacy" in out, False)+check("filter/nothing collapsed is an empty dict", collapsed_options(["dept"], [items[1]]), {})++# ---------------------------------------------------------------- what the agents publish+_agent_src = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "laya", "agent.py"),+ encoding="utf-8").read()+_onnx_src = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "laya", "onnx_agent.py"),+ encoding="utf-8").read()+for name, src in (("agent", _agent_src), ("onnx", _onnx_src)):+ check_true("usage/%s publishes it only when something collapsed" % name,+ 'collapsed = collapsed_options(ids, items)' in src and+ 'if collapsed:' in src and 'usage["options"] = collapsed' in src)+ check_true("usage/%s asks build_sequence for the stats" % name, "return_stats=True" in src)++print("\n%d passed, %d failed" % (len(PASS), len(FAIL)))+for f in FAIL:+ print(" FAIL " + f)+sys.exit(1 if FAIL else 0)diff --git a/tests/test_truncation_direction.py b/tests/test_truncation_direction.pyindex c4de4078..30c72a6e 100644--- a/tests/test_truncation_direction.py+++ b/tests/test_truncation_direction.py@@ -59,13 +59,13 @@ def test_agent_list_vs_string_truncation_direction():list_capture = {}string_capture = {}- def fake_build(tok, state, q, max_len, head_max_len, truncate_left=False, state_ids=None):+ def fake_build(tok, state, q, max_len, head_max_len, truncate_left=False, **kwargs):if isinstance(state, list):list_capture["truncate_left"] = truncate_leftelse:string_capture["truncate_left"] = truncate_leftreturn build_sequence(tok, state, q, max_len, head_max_len,- truncate_left=truncate_left, state_ids=state_ids)+ truncate_left=truncate_left, **kwargs)with patch("laya.agent.build_sequence", side_effect=fake_build):agent.system_one([{"role": "user", "content": "hi"}, {"role": "user", "content": "newest"}], questions)@@ -85,11 +85,11 @@ def test_agent_system_one_passes_truncate_left_for_list():captured = {}- def fake_build(tok, state, q, max_len, head_max_len, truncate_left=False, state_ids=None):+ def fake_build(tok, state, q, max_len, head_max_len, truncate_left=False, **kwargs):captured["truncate_left"] = truncate_leftcaptured["state"] = statereturn build_sequence(tok, state, q, max_len, head_max_len,- truncate_left=truncate_left, state_ids=state_ids)+ truncate_left=truncate_left, **kwargs)with patch("laya.agent.build_sequence", side_effect=fake_build):agent.system_one(conversation, questions)@@ -107,10 +107,10 @@ def test_agent_system_one_string_state_default_truncation():captured = {}- def fake_build(tok, state, q, max_len, head_max_len, truncate_left=False, state_ids=None):+ def fake_build(tok, state, q, max_len, head_max_len, truncate_left=False, **kwargs):captured["truncate_left"] = truncate_leftreturn build_sequence(tok, state, q, max_len, head_max_len,- truncate_left=truncate_left, state_ids=state_ids)+ truncate_left=truncate_left, **kwargs)with patch("laya.agent.build_sequence", side_effect=fake_build):agent.system_one("just a string state", questions)