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(cli): make core's length grouping reachable from the CLI, laya-evals and /predict/batch
Aashish14b9218963e7
diff --git a/README.md b/README.mdindex 4aadb0c4..9ec3b1aa 100644--- a/README.md+++ b/README.md@@ -227,7 +227,20 @@ laya "Where is my card" --questions intents.json # answer your own questionslaya # interactive mode```-Routing alone never downloads a checkpoint, so it returns in milliseconds. `--predict` loads the routed checkpoint, which needs network access to the Hugging Face hub the first time; if a checkpoint cannot be downloaded, the CLI says so instead of crashing. `--batch` (with or without `--predict`) sends the whole file through `Router.predict_batch` in one process, so the requests share checkpoint loads and forward passes — measured 2.6x on 20 tickets vs looping `predict` one by one, with `--batch-size N` to bound the forward pass and `--json` for JSONL output. Batch routing (`laya --batch FILE`, no `--predict`) likewise answers with `route_batch` in one pass, still without loading anything.+Routing alone never downloads a checkpoint, so it returns in milliseconds. `--predict` loads the routed checkpoint, which needs network access to the Hugging Face hub the first time; if a checkpoint cannot be downloaded, the CLI says so instead of crashing. `--batch` (with or without `--predict`) sends the whole file through `Router.predict_batch` in one process, so the requests share checkpoint loads and forward passes — measured 2.6x on 20 tickets vs looping `predict` one by one, with `--batch-size N` to bound the forward pass, `--sort-by-length` to group similarly sized requests inside it, and `--json` for JSONL output. Batch routing (`laya --batch FILE`, no `--predict`) likewise answers with `route_batch` in one pass, still without loading anything.++`--sort-by-length` reaches the length grouping `Agent.predict_batch` has done since #294, which+until now only the library call in [Batch Mode](#batch-mode-score-many-states-in-one-forward-pass)+could ask for. A forward pass pads every state in it to the longest one, so a two-line request+sharing a pass with a two-paragraph one spends most of its compute on padding; grouping by length+first puts comparable sizes together. Measured on 128 real Yelp reviews of 69-2,293 characters,+run as `laya --batch FILE --predict --model laya --batch-size 8` with and without the flag, four+interleaved rounds on an Apple-silicon Mac at the CLI's own device pick: 41.25 s median unsorted+against 29.23 s sorted, a **paired median of 1.42x** (1.39-1.44x across the four pairs), with all+128 decisions identical and still in input order. `research/` measures the same knob at 2.15x over+10,000 synthetic multilingual tickets. It needs `--batch-size N` with 1 < N < the number of+requests — a single pass over the whole file has no group to reorder — and the CLI says so on+stderr rather than printing a same-speed result and leaving you to notice.`--questions` takes the same question dict the SDK takes, as JSON: either the mapping itself, or`{"state_key": "body", "questions": {...}}` when the question's instructions name a field other than@@ -271,6 +284,16 @@ curl -s localhost:8000/predict -H 'content-type: application/json' -d '{`--no-preload` loads checkpoints lazily instead of all three up front; `--device cuda|cpu|mps`pins the device. See `python examples/server.py --help` for the rest.+`/predict/batch` accepts two optional body fields that control the shape of the forward passes+without changing any answer: `batch_size` (states per pass; omit it and the whole batch is one+pass) and `sort_by_length` (group similarly sized states so each pass pads to a shorter maximum —+it needs a `batch_size` below the number of states, since one pass has nothing to reorder).+Measured on the running server: 64 real reviews of 91–2,293 characters, one choice question,+`batch_size: 8`, three interleaved rounds on MPS — the default one-pass shape 5.35s median against+3.04s sorted, a paired median of **1.77x** (min 1.76x), and 64/64 labels identical in input order.+`batch_size: 8` on its own was 4.95s, so the length grouping is what earns the second factor:+1.66x over the sized batch.+---## Quickstart: Route Mode (Recommended)diff --git a/docs/evals.md b/docs/evals.mdindex 57bf788e..c182dc90 100644--- a/docs/evals.md+++ b/docs/evals.md@@ -45,7 +45,8 @@ short name like `english`, since there is no Router on this path (default`convaiinnovations/laya`). Its config and tokenizer are loaded from there. The agent serves one checkpoint, so a dataset rowwhose `model` field names a different one fails with a clear error rather than being silentlyanswered by the wrong model; `--device` does not apply. `--batch-size` uses the agent's batch-API when it has one and falls back to one call per state otherwise. The report's `config` block+API when it has one and falls back to one call per state otherwise; `--sort-by-length` is forwarded+to that batch API, which the per-state fallback has no group to reorder. The report's `config` blockrecords the `onnx` path.Measured on `research/evals/fixture.jsonl` (12 labelled rows, English checkpoint, CPU):@@ -117,6 +118,20 @@ raised still counts in `rows_grouped` and `max_chunk`, next to its entries in `ctwo `*_ms` metrics count only the calls that returned, so a failed call never contributes a latencyit did not measure.+### Grouping the rows inside a batch++`--sort-by-length` groups similarly sized rows into the same forward pass, so each pass pads to a+shorter maximum instead of to the longest row in it. It is the shape of the calls, not their+answers: results come back in the same order and score identically, which is why `research/` can+report 2.15x over 10,000 tickets with no decision changing.++There has to be more than one pass to reorder, so it takes effect only with a `--batch-size N`+below the number of rows the run groups. `config.timing` keeps the two claims apart:+`sort_by_length` is what the command line said, `sort_by_length_sent` is what reached the runner.+A run with no `--batch-size` asks for something that cannot happen, and says so with+`sent: false`; a runner whose `predict_batch` predates the knob is scored unsorted rather than+raising `TypeError` halfway through a long run.+## Slices`compare` and `run` report overall numbers and, for `--slice language|model|qid|tag`, the samediff --git a/examples/server.py b/examples/server.pyindex aab5d01a..0ce466e2 100644--- a/examples/server.py+++ b/examples/server.py@@ -154,6 +154,16 @@ class BatchRequest(BaseModel):model: Optional[str] = Nonetask: Optional[str] = Nonelang: Optional[str] = None+ # The batch shape, not a per-state control: these size and group the forward passes rather+ # than saying what a state means. `sort_by_length` only reorders a batch that is split into+ # more than one pass, so it needs a `batch_size` strictly between 1 and the state count.+ batch_size: Optional[int] = Field(+ default=None, ge=1,+ description="states per forward pass; the default sends the whole batch in one pass")+ sort_by_length: bool = Field(+ default=False,+ description="group similarly sized states in the same pass so each pads to a shorter "+ "maximum; needs a batch_size below the state count, never changes an answer")_v_model = field_validator("model")(classmethod(lambda cls, v: _check_model(v)))@@ -361,11 +371,19 @@ def predict_batch(req: BatchRequest) -> Dict[str, Any]:controls = {key: value for key, value in (("model", req.model), ("task", req.task),("lang", req.lang)) if value is not None}requests = [{"state": state, "questions": questions, **controls} for state in req.states]+ # The batch shape is an argument of the batch call, not a control that travels per request: the+ # fallback below answers one state at a time, where there is no group to size or reorder. Sent+ # only when set, so a request that asks for neither keeps making the call it always made.+ shape = {}+ if req.batch_size is not None:+ shape["batch_size"] = req.batch_size+ if req.sort_by_length:+ shape["sort_by_length"] = Truetry:# One call, not one per state: `Router.predict_batch` routes the whole batch, groups it by# checkpoint and shares a forward pass across states that carry the same question schema --# which is exactly this endpoint, since `BatchRequest` holds one `questions` map.- results: List[Dict[str, Any]] = list(_router().predict_batch(requests))+ results: List[Dict[str, Any]] = list(_router().predict_batch(requests, **shape))except Exception:# The batch fails as a unit, so a single bad state would otherwise cost every other state# its answer. Fall back to the per-state path to keep the documented envelope: N results,diff --git a/laya/cli.py b/laya/cli.pyindex 2a5e846f..6b5a7955 100644--- a/laya/cli.py+++ b/laya/cli.py@@ -103,6 +103,10 @@ def build_parser():parser.add_argument("--batch-size", type=int, default=None, metavar="N",help="states per forward pass in --batch mode; the default sends each ""routed group in one pass")+ parser.add_argument("--sort-by-length", action="store_true", dest="sort_by_length",+ help="with --batch-size N where 1 < N < the number of requests, group "+ "similarly sized states into the same forward pass so each pads to a "+ "shorter maximum; fewer padded tokens, same answers in input order")return parser@@ -259,7 +263,20 @@ def run_batch(lines, args, router=None):overrides.update(budget_overrides(args))requests = [{"state": {key: line}, "questions": questions, **overrides}for line in lines]- results = router.predict_batch(requests, batch_size=args.batch_size)+ kwargs = {"batch_size": args.batch_size}+ if args.sort_by_length:+ # Sent only when asked for, as Router.predict_batch itself forwards it: a stub or+ # an attached agent that predates the knob keeps working for every run that does+ # not request it.+ kwargs["sort_by_length"] = True+ chunk = args.batch_size if args.batch_size and args.batch_size > 0 else len(lines)+ if not 1 < chunk < len(lines):+ # Core documents this as a no-op rather than an error, so the shell says why+ # the run was not reordered instead of printing a silent same-speed result.+ print("note: --sort-by-length only takes effect with --batch-size N where "+ "1 < N < %d; the states still go in one forward pass" % len(lines),+ file=sys.stderr)+ results = router.predict_batch(requests, **kwargs)for line, result in zip(lines, results):if args.json:print(json.dumps(result, ensure_ascii=False, default=str))diff --git a/laya/evals.py b/laya/evals.pyindex 050d8c8f..8732a507 100644--- a/laya/evals.py+++ b/laya/evals.py@@ -345,9 +345,27 @@ def _batch_form(runner: Any) -> Optional[str]:return None+def _takes_sort_by_length(runner: Any) -> bool:+ """Whether `runner`'s batch entry point can be given the length-grouping knob.++ The same signature check `_batch_form` makes, for the one optional argument this harness+ forwards: `sort_by_length` is an optimisation, so a runner whose ``predict_batch`` predates it+ (#294) is scored unsorted rather than raising ``TypeError`` at the first chunk of a long run.+ A ``**kwargs`` forwarder counts, because whatever it wraps is a real runner.+ """+ fn = getattr(runner, "predict_batch", None)+ if fn is None:+ return False+ try:+ params = inspect.signature(fn).parameters.values()+ except (TypeError, ValueError):+ return False+ return any(p.name == "sort_by_length" or p.kind is p.VAR_KEYWORD for p in params)++def evaluate(runner: Any, dataset: Dataset, evaluators: Optional[Sequence[Evaluator]] = None,batch_size: Optional[int] = None, on_error: str = "fail",- config: Optional[Dict[str, Any]] = None) -> EvalReport:+ config: Optional[Dict[str, Any]] = None, sort_by_length: bool = False) -> EvalReport:"""Run `runner` over `dataset`, aggregating per-answer metrics overall and per slice.`runner` needs a ``predict(state, questions, model=...)`` method, and for `batch_size` above 1@@ -357,6 +375,12 @@ def evaluate(runner: Any, dataset: Dataset, evaluators: Optional[Sequence[Evalua"model": ...}, ...], batch_size=...)``. A runner that offers neither is scored one ``predict``at a time, which is slower but not wrong.+ `sort_by_length` is forwarded to a chunked runner so similarly sized examples share a forward+ pass and pad to a shorter maximum. It reaches the checkpoint's own batching only when the+ runner's ``predict_batch`` takes it, and only when it is on: an unset control is not sent, so a+ runner that predates the knob is unaffected by a run that does not ask. Nothing about the+ scored answers changes -- the results come back in chunk order either way.+`on_error` is ``"fail"`` (re-raise a runner error) or ``"skip"`` (record it and continue),the latter for evaluating a flaky fleet without aborting the whole run.@@ -379,6 +403,10 @@ def evaluate(runner: Any, dataset: Dataset, evaluators: Optional[Sequence[Evaluaexamples = dataset.examples# Only worth grouping if the runner can be handed the group in one call at all.batch_form = _batch_form(runner) if batch_size is not None and batch_size > 1 else None+ # The chunk shape travels with the calls that have one: a chunk of a single example is a plain+ # `predict`, which has no batch to reorder, and an off control is not sent at all.+ shape = ({"sort_by_length": True}+ if sort_by_length and batch_form and _takes_sort_by_length(runner) else {})index = 0while index < len(examples):@@ -413,10 +441,11 @@ def evaluate(runner: Any, dataset: Dataset, evaluators: Optional[Sequence[Evalua# per-request dicts carry exactly what the positional call would pass.results = runner.predict_batch([{"state": e.state, "questions": e.questions, "model": e.model}- for e in chunk], batch_size=batch_size)+ for e in chunk], batch_size=batch_size, **shape)else:results = runner.predict_batch([e.state for e in chunk], chunk[0].questions,- model=chunk[0].model, batch_size=batch_size)+ model=chunk[0].model, batch_size=batch_size,+ **shape)else:results = [runner.predict(chunk[0].state, chunk[0].questions, model=chunk[0].model)]except Exception as exc: # noqa: BLE001 -- honoured by on_error@@ -466,6 +495,10 @@ def evaluate(runner: Any, dataset: Dataset, evaluators: Optional[Sequence[Evalua"cost_metric": "per decision: that call divided by its own chunk size","batch_size": batch_size,"batch_form": batch_form,+ "sort_by_length": sort_by_length,+ # Requested and sent are different claims: `sort_by_length` needs a chunk to reorder, so a+ # run with no batch form asked for something this harness cannot do.+ "sort_by_length_sent": bool(shape),"chunks": chunks,"rows_grouped": rows_grouped,"rows_alone": rows_alone,diff --git a/laya/evals_cli.py b/laya/evals_cli.pyindex d2a3a8ff..e4067295 100644--- a/laya/evals_cli.py+++ b/laya/evals_cli.py@@ -31,9 +31,11 @@ class RouterRunner:return self.router.predict(state, questions, model=model)def predict_batch(self, states: Sequence[Any], questions: Dict[str, Any],- model: Optional[str] = None, batch_size: Optional[int] = None) -> List[Dict[str, Any]]:+ model: Optional[str] = None, batch_size: Optional[int] = None,+ sort_by_length: bool = False) -> List[Dict[str, Any]]:requests = [{"state": state, "questions": questions, "model": model} for state in states]- return self.router.predict_batch(requests, batch_size=batch_size)+ return self.router.predict_batch(requests, batch_size=batch_size,+ sort_by_length=sort_by_length)class OnnxRunner:@@ -59,10 +61,16 @@ class OnnxRunner:return self.agent.predict(state, questions)def predict_batch(self, states: Sequence[Any], questions: Dict[str, Any],- model: Optional[str] = None, batch_size: Optional[int] = None) -> List[Dict[str, Any]]:+ model: Optional[str] = None, batch_size: Optional[int] = None,+ sort_by_length: bool = False) -> List[Dict[str, Any]]:self._check_model(model)agent_batch = getattr(self.agent, "predict_batch", None)if agent_batch is not None:+ if sort_by_length:+ # Asked for, so it has to reach the agent's own grouping. The per-state fallback+ # below cannot honour it: there is no batch to reorder.+ return agent_batch(list(states), questions, batch_size=batch_size,+ sort_by_length=True)return agent_batch(list(states), questions, batch_size=batch_size)return [self.agent.predict(state, questions) for state in states]@@ -143,6 +151,10 @@ def _build_parser() -> argparse.ArgumentParser:"checkpoint's default branch; the report records the commit that answered ""either way")run.add_argument("--batch-size", type=int, help="examples per forward pass when questions match")+ run.add_argument("--sort-by-length", action="store_true", dest="sort_by_length",+ help="with --batch-size N where 1 < N < the run, group similarly sized "+ "examples into the same forward pass so each pads to a shorter maximum; "+ "scores the same answers, in the same order")run.add_argument("--on-error", choices=("fail", "skip"), default="fail")run.add_argument("--baseline", help="a baseline report JSON to compare against")run.add_argument("--tolerance", action="append", metavar="METRIC=VALUE",@@ -268,7 +280,8 @@ def _cmd_run(args) -> int:if extra:config["score_within"] = [evaluator.tolerance for evaluator in extra]report = evals.evaluate(runner, dataset, evaluators=evals.default_evaluators() + extra,- batch_size=args.batch_size, on_error=args.on_error, config=config)+ batch_size=args.batch_size, on_error=args.on_error, config=config,+ sort_by_length=args.sort_by_length)# Which commit answered belongs in the artifact a baseline is, and it can only be read after# the run: `preload=False` means no checkpoint is resident before the first row.# `loaded_revisions` reports the commit each resident agent came from -- the pin when there isdiff --git a/tests/test_cli.py b/tests/test_cli.pyindex e6125ac7..b895e3c7 100644--- a/tests/test_cli.py+++ b/tests/test_cli.py@@ -231,8 +231,8 @@ class BatchRouter:self.predict_batch_calls = []self.route_batch_calls = []- def predict_batch(self, requests, batch_size=None):- self.predict_batch_calls.append((requests, batch_size))+ def predict_batch(self, requests, batch_size=None, **extra):+ self.predict_batch_calls.append((requests, batch_size, extra))return [{"model": "laya-rl", "answers": {"difficulty": {"score": float(i)}}, "usage": {}}for i in range(len(requests))]@@ -267,12 +267,13 @@ with open(path, "w", encoding="utf-8") as handle:code, out, err, stub = run_batch_cli(["--batch", path, "--predict", "--batch-size", "8"])check("batch predict: exit code", code == 0, "got %r %s" % (code, err))-requests, batch_size = stub.predict_batch_calls[0]+requests, batch_size, extra = stub.predict_batch_calls[0]check("batch predict: exactly one predict_batch call", len(stub.predict_batch_calls) == 1)check("batch predict: blank lines skipped, lines stripped",[r["state"]["request"] for r in requests] == ["first ticket", "second ticket"],str([r["state"] for r in requests]))check("batch predict: --batch-size forwarded", batch_size == 8, str(batch_size))+check("batch predict: no grouping key is sent unless asked for", extra == {}, str(extra))check("batch predict: router questions on every request",sorted(requests[0]["questions"]) == sorted(cli.PRESETS["router"]()),str(sorted(requests[0]["questions"])))@@ -324,6 +325,79 @@ check("batch -: reads stdin", code == 0and len(stub.predict_batch_calls[0][0]) == 2and len([l for l in out.splitlines() if l.strip()]) == 2, "code %r err %r" % (code, err))+# ------------------------------------------------------------- --sort-by-length (#294 knob)+#+# `Agent.predict_batch` and `Router.predict_batch` have grouped similarly sized states into one+# forward pass since #294, README teaches it as the library call, and `research/` reports 2.15x on+# 10,000 tickets from it. `laya --batch` could set `--batch-size` but not the grouping that makes a+# bounded pass cheap, so the one knob with a measurable effect on the other knob was reachable only+# by writing Python. These run the real parser and the real `run_batch` over a recording router.+import inspect as _inspect # noqa: E402++from laya.router import Router as _CoreRouter # noqa: E402++many = os.path.join(tmp, "four.txt")+with open(many, "w", encoding="utf-8") as handle:+ handle.write("one\ntwo\nthree\nfour\n")++check("sort: --sort-by-length reaches the parser",+ cli.build_parser().parse_args(["t", "--sort-by-length"]).sort_by_length is True)+check("sort: it is off by default",+ cli.build_parser().parse_args(["t"]).sort_by_length is False)+# The flag is named after the parameter it drives, and core is the only place that decides the+# name: a rename there has to fail here instead of silently dropping the grouping again.+check("sort: the flag names a real Router.predict_batch parameter",+ "sort_by_length" in _inspect.signature(_CoreRouter.predict_batch).parameters,+ str(list(_inspect.signature(_CoreRouter.predict_batch).parameters)))++code, out, err, stub = run_batch_cli(["--batch", many, "--predict", "--batch-size", "2",+ "--sort-by-length"])+requests, batch_size, extra = stub.predict_batch_calls[0]+check("sort: batch size and grouping both reach predict_batch",+ code == 0 and batch_size == 2 and extra == {"sort_by_length": True},+ "code %r batch_size %r extra %r" % (code, batch_size, extra))+check("sort: a grouping that can take effect is not annotated", err == "", err)+check("sort: answers still print once per state", out.count("difficulty") == 4, out)++code, out, err, stub = run_batch_cli(["--batch", many, "--predict", "--sort-by-length"])+check("sort: asked for without --batch-size, it is still forwarded as core takes it",+ code == 0 and stub.predict_batch_calls[0][2] == {"sort_by_length": True},+ str(stub.predict_batch_calls[0][2]))+check("sort: and the shell says a single pass cannot reorder",+ "1 < N < 4" in err, "err %r" % err)++code, out, err, stub = run_batch_cli(["--batch", many, "--predict", "--batch-size", "4",+ "--sort-by-length"])+check("sort: a pass as wide as the batch cannot reorder either",+ code == 0 and "1 < N < 4" in err and stub.predict_batch_calls[0][2] == {+ "sort_by_length": True}, "err %r" % err)++code, out, err, stub = run_batch_cli(["--batch", many, "--sort-by-length"])+check("sort: batch routing is untouched by a forward-pass knob",+ code == 0 and stub.predict_batch_calls == [] and len(stub.route_batch_calls) == 1,+ "predict=%r route=%r" % (stub.predict_batch_calls, len(stub.route_batch_calls)))++# A flag nobody can find is a flag nobody uses. README is where `laya --batch` and `/predict/batch`+# are taught, so the same pages that teach `--batch-size` have to teach the grouping that makes a+# bounded pass cheap -- including the condition it needs, since a run without it changes nothing.+_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+with open(os.path.join(_ROOT, "README.md"), encoding="utf-8") as handle:+ readme = handle.read()+++def section(heading):+ return readme.split(heading, 1)[1].split("\n## ", 1)[0]+++cli_page = section("### Command line")+check("sort: the page that teaches `laya --batch` teaches the grouping and its condition",+ "--batch-size" in cli_page and "--sort-by-length" in cli_page and "1 < N <" in cli_page,+ repr(cli_page[:120]))+server_page = section("## Try it locally: web GUI + JSON API")+check("sort: the server page teaches both body fields",+ "/predict/batch" in server_page and "batch_size" in server_page+ and "sort_by_length" in server_page, repr(server_page[:120]))+# --------------------------------------------------------------------- --questions FILE# The CLI could only ever answer the five built-in presets, while the library's whole input is a# user-written question dict. A file is the only way to get one onto the command line, so thediff --git a/tests/test_evals.py b/tests/test_evals.pyindex ce0db32a..cd01ae59 100644--- a/tests/test_evals.py+++ b/tests/test_evals.py@@ -310,6 +310,110 @@ def test_evaluate_batches_a_pass_through_wrapper_positionally():assert report.overall["choice_accuracy"] == 1.0+# ------------------------------------------------------- batch grouping (#294 knob)+#+# `Agent.predict_batch` and `Router.predict_batch` group similarly sized states inside a bounded+# `batch_size` since #294, and `research/` reports 2.15x over 10,000 tickets from it with no answer+# changing. `laya-evals run --batch-size` could bound a pass but not group one, so the harness that+# exists to measure cost could not ask for the cheaper shape of the same pass.++UNSENT = object() # a value no caller can send, so a default distinguishes "absent" from False+++class GroupingRunner(RequestsRunner):+ """A `Router`-shaped runner that has the knob and records exactly what the call carried."""++ def __init__(self, by_state):+ super().__init__(by_state)+ self.shapes = []++ def predict_batch(self, requests, batch_size=None, sort_by_length=UNSENT):+ self.shapes.append({"batch_size": batch_size, "sort_by_length": sort_by_length})+ return [{"model": r.get("model") or "m", "answers": self.by_state[r["state"]]}+ for r in requests]+++def _three():+ return Dataset([Example("s1", Q, {"intent": "a"}), Example("s2", Q, {"intent": "a"}),+ Example("s3", Q, {"intent": "b"})])+++ANSWERS3 = {"s1": {"intent": choice_answer("a")}, "s2": {"intent": choice_answer("a")},+ "s3": {"intent": choice_answer("b")}}+++def test_grouping_reaches_a_requests_shaped_runner_when_asked():+ runner = GroupingRunner(ANSWERS3)+ report = evaluate(runner, _three(), evaluators=[ChoiceAccuracy()], batch_size=2,+ sort_by_length=True)+ assert runner.shapes == [{"batch_size": 2, "sort_by_length": True}], runner.shapes+ assert report.overall["choice_accuracy"] == 1.0+++def test_grouping_is_not_invented_for_a_run_that_did_not_ask():+ """The control is dropped when unset, so an older runner sees the call it always saw."""+ runner = GroupingRunner(ANSWERS3)+ evaluate(runner, _three(), evaluators=[ChoiceAccuracy()], batch_size=2)+ assert runner.shapes == [{"batch_size": 2, "sort_by_length": UNSENT}], runner.shapes+++def test_grouping_reaches_a_states_shaped_runner_too():+ """Both batch call shapes the harness promises carry the knob; neither drops it silently."""+ class PassThrough(StubRunner):+ def __init__(self, by_state):+ super().__init__(by_state)+ self.calls = []++ def predict_batch(self, *args, **kwargs):+ self.calls.append(kwargs)+ return [{"model": "m", "answers": self.by_state[s]} for s in args[0]]++ runner = PassThrough(ANSWERS3)+ evaluate(runner, _three(), evaluators=[ChoiceAccuracy()], batch_size=2, sort_by_length=True)+ assert runner.calls == [{"model": None, "batch_size": 2, "sort_by_length": True}], runner.calls+++def test_grouping_changes_the_call_not_the_score():+ asked = GroupingRunner(ANSWERS3)+ sorted_report = evaluate(asked, _three(), evaluators=[ChoiceAccuracy()], batch_size=2,+ sort_by_length=True)+ plain = GroupingRunner(ANSWERS3)+ unsorted_report = evaluate(plain, _three(), evaluators=[ChoiceAccuracy()], batch_size=2)+ assert _labels(sorted_report) == _labels(unsorted_report)+ assert asked.shapes != plain.shapes, "the knob really reached the runner"+++def test_grouping_without_a_batch_to_reorder_is_recorded_as_not_sent():+ """A single-example chunk has nothing to group, and the report says so rather than agreeing."""+ runner = GroupingRunner(ANSWERS3)+ report = evaluate(runner, _three(), evaluators=[ChoiceAccuracy()], sort_by_length=True)+ assert runner.shapes == [], "no batch call was made at all"+ assert report.config["timing"]["sort_by_length"] is True+ assert report.config["timing"]["sort_by_length_sent"] is False+++def test_a_runner_without_the_knob_is_scored_unsorted():+ """`sort_by_length` is an optimisation: it must not end a run over a runner that predates it."""+ runner = RequestsRunner(ANSWERS3) # `predict_batch(requests, batch_size=None)`+ report = evaluate(runner, _three(), evaluators=[ChoiceAccuracy()], batch_size=2,+ sort_by_length=True)+ assert runner.batch_sizes == [2], "the run still batched"+ assert report.overall["choice_accuracy"] == 1.0+ assert not report.config.get("errored")+ assert report.config["timing"]["sort_by_length_sent"] is False+++def test_a_pass_through_wrapper_is_given_the_knob():+ """A runner that forwards `**kwargs` is a real runner behind it, so the grouping goes through."""+ class PassThrough(StubRunner):+ def predict_batch(self, *args, **kwargs):+ return [{"model": "m", "answers": self.by_state[s]} for s in args[0]]++ report = evaluate(PassThrough(ANSWERS3), _three(), evaluators=[ChoiceAccuracy()],+ batch_size=2, sort_by_length=True)+ assert report.config["timing"]["sort_by_length_sent"] is True++# --------------------------------------------------------------- timing (#585)FORWARD_MS = 100.0SHARED = 0.6 # a batch of n costs SHARED * n * FORWARD_MS, as one call@@ -774,10 +878,17 @@ def test_docs_and_the_cli_name_the_same_flags():taught = set(re.findall(r"(?<![\w-])(--[a-z][a-z-]*)", evals_lines))assert taught <= registered, "the page teaches %s, which no subcommand registers" % sorted(taught - registered)+ # The other half of parity: a registered flag nobody documents is unreachable in practice. The+ # page that teaches `--batch-size` has to teach the grouping that makes a bounded pass cheaper.+ assert {"--batch-size", "--sort-by-length"} <= taught, \+ "the evals page teaches the batch size but not the grouping knob"assert "--score-within" in quickstart, "the tolerance metric has to be reachable from the quickstart"metrics = page.split("## Metrics", 1)[1].split("\n## ", 1)[0]assert "score_within" in metrics and "--score-within" in metrics, \"the section that publishes the metric has to carry the flag that reaches it"+ grouping = page.split("### Grouping the rows inside a batch", 1)[1].split("\n#", 1)[0]+ assert "--sort-by-length" in grouping and "sort_by_length_sent" in grouping, \+ "the subsection that explains the grouping has to name the flag and what it reports"# --------------------------------------------------------------- --revision pinningdiff --git a/tests/test_evals_api.py b/tests/test_evals_api.pyindex 84337f91..f20eb2a8 100644--- a/tests/test_evals_api.py+++ b/tests/test_evals_api.py@@ -3,6 +3,7 @@Run: python tests/test_evals_api.py"""import dataclasses+import inspectimport osimport subprocessimport sys@@ -42,6 +43,50 @@ check_true("ScoreWithin names its tolerance", evals.ScoreWithin(0.25).name == "sfor name in ("Dataset", "Example", "EvalError", "EvalReport", "evaluate", "ece", "assert_regression"):check_true("laya.evals.%s exists" % name, hasattr(evals, name))+# --------------------------------------------------------------- evaluate's call signature+# `evaluate` is the harness entry point callers extend from their own scripts, so its parameter+# names and order are the contract. `sort_by_length` is core's #294 forward-pass grouping knob+# reaching a scored run through `laya-evals run --sort-by-length`; it is appended, never inserted,+# because a caller that passed `on_error` or `config` positionally must still mean the same thing.+_sig = inspect.signature(evals.evaluate)+check("evaluate signature", [p.name for p in _sig.parameters.values()],+ ["runner", "dataset", "evaluators", "batch_size", "on_error", "config", "sort_by_length"])+check("evaluate: grouping defaults to off", _sig.parameters["sort_by_length"].default, False)+check_true("evaluate: the knob sits after the batch size it groups inside",+ list(_sig.parameters).index("batch_size")+ < list(_sig.parameters).index("sort_by_length"))++# The two batch entry points the CLI wires up: both have to take the knob by the same name, or a+# `--sort-by-length` run reports `sort_by_length_sent: false` for the surface it ships.+from laya import evals_cli # noqa: E402++for label, fn in (("RouterRunner.predict_batch", evals_cli.RouterRunner.predict_batch),+ ("OnnxRunner.predict_batch", evals_cli.OnnxRunner.predict_batch)):+ params = inspect.signature(fn).parameters+ check_true("%s takes the grouping knob" % label, "sort_by_length" in params)+ check("%s defaults it to off" % label, params["sort_by_length"].default, False)++# A signature is not a wiring: a runner that declares the knob and drops it on the way through+# would pass both checks above. `OnnxRunner`'s call is gated in test_evals_onnx.py against a+# recording agent; this is the same witness for the router-shaped runner the CLI uses by default.+class _RecordingRouter:+ def __init__(self):+ self.calls = []++ def predict_batch(self, requests, batch_size=None, sort_by_length=False):+ self.calls.append({"batch_size": batch_size, "sort_by_length": sort_by_length})+ return [{"model": "m", "answers": {}} for _ in requests]+++_router = _RecordingRouter()+_runner = evals_cli.RouterRunner(_router)+_runner.predict_batch(["s1", "s2"], {"intent": {"type": "choice"}}, batch_size=2, sort_by_length=True)+check("RouterRunner hands the grouping to the router it wraps",+ _router.calls[-1], {"batch_size": 2, "sort_by_length": True})+_runner.predict_batch(["s1", "s2"], {"intent": {"type": "choice"}}, batch_size=2)+check("RouterRunner does not invent it for a run that did not ask",+ _router.calls[-1], {"batch_size": 2, "sort_by_length": False})+# --------------------------------------------------------------- torch stays out of importprobe = subprocess.run([sys.executable, "-c",diff --git a/tests/test_evals_onnx.py b/tests/test_evals_onnx.pyindex d3b25684..af30e1c8 100644--- a/tests/test_evals_onnx.py+++ b/tests/test_evals_onnx.py@@ -57,8 +57,8 @@ class _FakeAgent:class _BatchAgent(_FakeAgent):- def predict_batch(self, states, questions, batch_size=None):- self.calls.append(("predict_batch", tuple(states), batch_size))+ def predict_batch(self, states, questions, batch_size=None, sort_by_length=False):+ self.calls.append(("predict_batch", tuple(states), batch_size, sort_by_length))return [self._answer(questions) for _ in states]@@ -90,8 +90,27 @@ check("predict_batch/falls back to one predict per state",bagent = _BatchAgent("ckpt")out = OnnxRunner(bagent).predict_batch(["a", "b"], Q, batch_size=2)check("predict_batch/delegates once when the agent can batch",- bagent.calls, [("predict_batch", ("a", "b"), 2)])+ bagent.calls, [("predict_batch", ("a", "b"), 2, False)])check("predict_batch/delegated result passes through", len(out), 2)++# The #294 grouping knob: core pads each pass to its longest state, so a batch of mixed lengths+# feeds the model mostly padding. `laya-evals run --sort-by-length` is how a scored run asks for+# the cheaper shape of the same pass.+grouped = _BatchAgent("ckpt")+OnnxRunner(grouped).predict_batch(["a", "b"], Q, batch_size=2, sort_by_length=True)+check("predict_batch/sort_by_length is forwarded to the agent that has it",+ grouped.calls, [("predict_batch", ("a", "b"), 2, True)])++untouched = _BatchAgent("ckpt")+OnnxRunner(untouched).predict_batch(["a", "b"], Q, batch_size=2)+check("predict_batch/an unsorted run does not invent the key",+ untouched.calls, [("predict_batch", ("a", "b"), 2, False)])++# An agent that cannot batch has no group to reorder, and asking must not break the run.+nofile = _FakeAgent("ckpt")+OnnxRunner(nofile).predict_batch(["a", "b", "c"], Q, batch_size=2, sort_by_length=True)+check("predict_batch/a no-batch agent still answers when grouping is asked",+ [c[1] for c in nofile.calls], ["a", "b", "c"])try:OnnxRunner(bagent).predict_batch(["a"], Q, model="other")check_true("predict_batch/foreign model raises too", False, "no exception")@@ -139,6 +158,22 @@ try:"--batch-size", "2"])check("cli/--batch-size runs the ONNX batch path", rc, 0)+ # ... and so does the grouping knob, all the way from the flag to the agent's own call. The+ # report is the witness: `sort_by_length_sent` is what the harness put on the wire, not what+ # the command line said, so a flag that parsed and was dropped fails here by name.+ grouped_path = os.path.join(tmp, "grouped.json")+ rc = evals_cli.main(["run", dataset, "--onnx", "laya.onnx", "--model", "ckpt",+ "--batch-size", "2", "--sort-by-length", "--json", grouped_path])+ check("cli/--sort-by-length scores the same dataset", rc, 0)+ with open(grouped_path) as f:+ grouped_report = json.load(f)+ check("cli/--sort-by-length is sent to the runner",+ grouped_report["config"]["timing"]["sort_by_length_sent"], True)+ check("cli/an ungrouped run says it sent nothing",+ report["config"]["timing"]["sort_by_length_sent"], False)+ check("cli/grouping changes the shape of the run, not its score",+ grouped_report["overall"]["choice_accuracy"], report["overall"]["choice_accuracy"])+# a per-example model the single-checkpoint agent does not serve is an error, not a no-op# (no --model here: --model would authoritatively rewrite every row and mask the mismatch)mismatch = os.path.join(tmp, "mismatch.jsonl")diff --git a/tests/test_example_server_limits.py b/tests/test_example_server_limits.pyindex 59781e6c..66cdcce5 100644--- a/tests/test_example_server_limits.py+++ b/tests/test_example_server_limits.py@@ -473,6 +473,80 @@ def main():and not any("task" in r for r in sent),json.dumps(sent[:1])[:200])+ # --- how the batch is packed is askable ---------------------------------------------+ #+ # `Router.predict_batch` has taken `batch_size` and `sort_by_length` since #294, and the README+ # teaches `router.predict_batch(requests, batch_size=8, sort_by_length=True)`. The endpoint that+ # answers up to 64 states in one call forwarded neither, so every batch was one forward pass+ # padded to its longest state: a caller who wanted smaller passes had no way to ask, in code or+ # over HTTP. These drive the real request model, so a body that named the keys and had them+ # dropped by validation fails here rather than returning a silently slower 200.+ shape_params = set(inspect.signature(CoreRouter.predict_batch).parameters) - {"self", "requests"}+ ok("core still takes the shape keys this endpoint forwards",+ {"batch_size", "sort_by_length"} <= shape_params, str(sorted(shape_params)))++ shaped = RecordingRouter()+ demo.ROUTER = shaped+ body = TestClient(demo.app, raise_server_exceptions=False).post(+ "/predict/batch", json={"states": states, "questions": one,+ "batch_size": 4, "sort_by_length": True})+ ok("a shape request is still one batch call, in order",+ len(shaped.batch_calls) == 1 and not shaped.predict_calls+ and body.json().get("count") == 8+ and [r.get("state") for r in body.json()["results"]] == states,+ "predict_batch=%d predict=%d" % (len(shaped.batch_calls), len(shaped.predict_calls)))+ ok("batch_size and sort_by_length reach predict_batch",+ shaped.batch_calls[0][1] == {"batch_size": 4, "sort_by_length": True},+ str(shaped.batch_calls[0][1]))++ sized = RecordingRouter()+ demo.ROUTER = sized+ TestClient(demo.app, raise_server_exceptions=False).post(+ "/predict/batch", json={"states": states, "questions": one, "batch_size": 2})+ ok("batch_size alone does not invent a sort request",+ sized.batch_calls[0][1] == {"batch_size": 2}, str(sized.batch_calls[0][1]))++ # Core documents `sort_by_length` without a split batch as a no-op, not an error; the endpoint+ # must not be the surface that turns a valid call into a 422.+ unsized = RecordingRouter()+ demo.ROUTER = unsized+ no_split = TestClient(demo.app, raise_server_exceptions=False).post(+ "/predict/batch", json={"states": states, "questions": one, "sort_by_length": True})+ ok("sort_by_length alone is accepted and forwarded, as core takes it",+ no_split.status_code == 200 and unsized.batch_calls[0][1] == {"sort_by_length": True},+ "%s %s" % (no_split.status_code, str(unsized.batch_calls[0][1])))++ junk = TestClient(demo.app, raise_server_exceptions=False).post(+ "/predict/batch", json={"states": states, "questions": one, "batch_size": 0})+ ok("a zero-size forward pass is a 422 before any router call",+ junk.status_code == 422, "%s %s" % (junk.status_code, str(junk.json())[:120]))++ # The shape belongs to the batch call only. When a state fails, the endpoint retries per state+ # through `Router.predict`, which takes neither key: leaking them there would turn one bad+ # state into 8 TypeErrors and an empty batch.+ leaked = RecordingRouter(fail_on="ticket 3")+ demo.ROUTER = leaked+ retried = TestClient(demo.app, raise_server_exceptions=False).post(+ "/predict/batch", json={"states": states, "questions": one,+ "batch_size": 4, "sort_by_length": True})+ ok("the per-state fallback carries no batch shape",+ leaked.batch_calls[0][1] == {"batch_size": 4, "sort_by_length": True}+ and len(leaked.predict_calls) == 8+ and not any("batch_size" in kw or "sort_by_length" in kw+ for _, kw in leaked.predict_calls)+ and [r for r in retried.json()["results"] if "error" in r][0]["index"] == 3,+ str([kw for _, kw in leaked.predict_calls][:1])[:200])++ legacy_shaped = LegacyRouter()+ demo.ROUTER = legacy_shaped+ old = TestClient(demo.app, raise_server_exceptions=False).post(+ "/predict/batch", json={"states": states, "questions": one,+ "batch_size": 4, "sort_by_length": True})+ ok("a router without predict_batch still answers a shaped request",+ old.status_code == 200 and len(old.json()["results"]) == 8+ and not [r for r in old.json()["results"] if "error" in r],+ "%s %s" % (old.status_code, json.dumps(old.json())[:200]))+# One state failing must not cost its neighbours their answer: the endpoint's published# contract is per-item errors inside a 200.partial = RecordingRouter(fail_on="ticket 3")