Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

feat(examples): expose workflow32 top-k sampling (#686)

svonavaa23013c0dd81
diff --git a/examples/typed-decisions/workflow32/README.md b/examples/typed-decisions/workflow32/README.md
index 96198b50f..a25f56f99 100644
--- a/examples/typed-decisions/workflow32/README.md
+++ b/examples/typed-decisions/workflow32/README.md
@@ -45,10 +45,12 @@ budget covers reasoning as well as the final JSON. `--thinking on` requests
may override that request. The runner records caller settings without claiming
to verify actual server configuration. Use `--thinking off` or
`--thinking server` to record a different configuration; the latter omits the
-template override. `--max-completion-tokens`, `--timeout` and `--temperature`
-are explicit overrides and remain visible in `plan.json`; `--temperature 0`
-reproduces the separately published temperature-0 treatment. Results with
-different settings are different runs.
+template override. `--max-completion-tokens`, `--timeout`, `--temperature` and
+`--top-k` are explicit overrides and remain visible in `plan.json`;
+`--temperature 0` reproduces the separately published temperature-0 treatment.
+`--top-k` accepts integers from 1 to 4,294,967,295 and defaults to 64; for
+example, `--top-k 20` records and sends 20. Results with different settings are
+different runs.
Every case runs once, in source order, with no truncation, tools, retry,
synthetic probe or warmup. The first ordinary case gates continuation on a
diff --git a/examples/typed-decisions/workflow32/run.py b/examples/typed-decisions/workflow32/run.py
index 0b3e6d9f4..4940caaaf 100644
--- a/examples/typed-decisions/workflow32/run.py
+++ b/examples/typed-decisions/workflow32/run.py
@@ -85,7 +85,7 @@ def request_body(case: dict, settings: dict) -> dict:
"max_completion_tokens": settings["max_completion_tokens"],
"temperature": settings["temperature"],
"top_p": 0.95,
- "top_k": 64,
+ "top_k": settings["top_k"],
}
if settings["thinking"] != "server":
body["chat_template_kwargs"] = {"enable_thinking": settings["thinking"] == "on"}
@@ -243,7 +243,7 @@ def case_worker(case: dict, folder: Path, settings: dict, inner: httpx.BaseTrans
max_completion_tokens=settings["max_completion_tokens"],
temperature=settings["temperature"],
top_p=0.95,
- top_k=64,
+ top_k=settings["top_k"],
extra_body=extra,
wait_for_capacity=False,
max_oom_retries=0,
@@ -321,8 +321,11 @@ def run_frame(
max_completion_tokens: int = 32768,
thinking: str = "on",
temperature: float = 1.0,
+ top_k: int = 64,
execute=run_case,
) -> list[dict]:
+ if isinstance(top_k, bool) or not isinstance(top_k, int) or not 1 <= top_k <= 2**32 - 1:
+ raise ValueError("Top-k must be an integer from 1 to 4294967295")
if not math.isfinite(timeout_s) or timeout_s <= 0 or max_completion_tokens <= 0:
raise ValueError("Positive finite case timeout and completion token cap are required")
if (
@@ -352,6 +355,7 @@ def run_frame(
"max_completion_tokens": max_completion_tokens,
"thinking": thinking,
"temperature": float(temperature),
+ "top_k": top_k,
}
out.mkdir(parents=True, exist_ok=False)
sync_directory(out.parent)
@@ -409,7 +413,7 @@ def run_frame(
return rows
-if __name__ == "__main__":
+def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--inputs", type=Path, default=Path("data/inputs.json"))
parser.add_argument("--out", type=Path, default=Path("run-output"))
@@ -419,7 +423,8 @@ if __name__ == "__main__":
parser.add_argument("--max-completion-tokens", type=int, default=32768)
parser.add_argument("--thinking", choices=("on", "off", "server"), default="on")
parser.add_argument("--temperature", type=float, default=1.0)
- args = parser.parse_args()
+ parser.add_argument("--top-k", type=int, default=64)
+ args = parser.parse_args(argv)
if not args.url:
parser.error("Set SIE_URL or pass --url")
outcomes = run_frame(
@@ -431,5 +436,10 @@ if __name__ == "__main__":
max_completion_tokens=args.max_completion_tokens,
thinking=args.thinking,
temperature=args.temperature,
+ top_k=args.top_k,
)
- raise SystemExit(1 if any(row.get("halt") for row in outcomes) or outcomes[0]["status"] != "ok" else 0)
+ return 1 if any(row.get("halt") for row in outcomes) or outcomes[0]["status"] != "ok" else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/examples/typed-decisions/workflow32/tests/test_workflow.py b/examples/typed-decisions/workflow32/tests/test_workflow.py
index 535bc3e95..a64511351 100644
--- a/examples/typed-decisions/workflow32/tests/test_workflow.py
+++ b/examples/typed-decisions/workflow32/tests/test_workflow.py
@@ -57,6 +57,7 @@ def settings(**updates) -> dict:
"max_completion_tokens": 32768,
"thinking": "on",
"temperature": 1.0,
+ "top_k": 64,
**updates,
}
@@ -245,6 +246,76 @@ class SourceAndFrameTests(unittest.TestCase):
self.assertEqual(plan["decoding"]["temperature"], 0.0)
self.assertEqual(execute.call_args.args[2]["temperature"], 0.0)
+ def test_explicit_top_k_is_recorded_and_dispatched(self) -> None:
+ execute = mock.Mock(return_value={"status": "ok", "physical_sends": 1})
+ self.frame(execute, top_k=20)
+ plan = json.loads((self.root / "out" / "plan.json").read_bytes())
+ self.assertEqual(plan["decoding"]["top_k"], 20)
+ self.assertEqual(execute.call_count, 32)
+ self.assertTrue(all(call.args[2]["top_k"] == 20 for call in execute.call_args_list))
+
+ def test_invalid_top_k_rejected_before_inputs_output_or_dispatch(self) -> None:
+ for value in [True, False, 20.0, 1.5, "20", None, 0, -1, 2**32]:
+ with self.subTest(top_k=value), mock.patch.object(run, "load_inputs") as load:
+ execute = mock.Mock()
+ with self.assertRaisesRegex(ValueError, "Top-k must be an integer from 1 to 4294967295"):
+ self.frame(execute, top_k=value)
+ load.assert_not_called()
+ execute.assert_not_called()
+ self.assertFalse((self.root / "out").exists())
+
+ def test_top_k_range_boundaries_are_accepted(self) -> None:
+ for value in [1, 2**32 - 1]:
+ with self.subTest(top_k=value), contextlib.redirect_stdout(io.StringIO()):
+ execute = mock.Mock(return_value={"status": "failed", "physical_sends": 1})
+ out = self.root / f"out-{value}"
+ run.run_frame(
+ self.inputs,
+ out,
+ url="https://example.test/base",
+ model="public/model",
+ top_k=value,
+ execute=execute,
+ )
+ self.assertEqual(execute.call_args.args[2]["top_k"], value)
+ self.assertEqual(json.loads((out / "plan.json").read_bytes())["decoding"]["top_k"], value)
+
+
+class CliTests(unittest.TestCase):
+ def test_explicit_and_default_top_k_are_forwarded(self) -> None:
+ for arguments, expected in [(["--top-k", "20"], 20), ([], 64)]:
+ with (
+ self.subTest(arguments=arguments),
+ mock.patch.object(run, "run_frame", return_value=[{"status": "ok"}]) as frame,
+ ):
+ status = run.main(["--url", "https://example.test/base", "--model", "public/model", *arguments])
+ self.assertEqual(status, 0)
+ frame.assert_called_once_with(
+ Path("data/inputs.json"),
+ Path("run-output"),
+ url="https://example.test/base",
+ model="public/model",
+ timeout_s=1800,
+ max_completion_tokens=32768,
+ thinking="on",
+ temperature=1.0,
+ top_k=expected,
+ )
+
+ def test_noninteger_top_k_is_rejected_without_calling_frame(self) -> None:
+ with mock.patch.object(run, "run_frame") as frame, contextlib.redirect_stderr(io.StringIO()):
+ with self.assertRaises(SystemExit) as caught:
+ run.main(["--url", "https://example.test/base", "--model", "public/model", "--top-k", "1.5"])
+ self.assertEqual(caught.exception.code, 2)
+ frame.assert_not_called()
+
+ def test_nonpositive_top_k_is_rejected_before_input_loading(self) -> None:
+ for value in ["0", "-1"]:
+ with self.subTest(top_k=value), mock.patch.object(run, "load_inputs") as load:
+ with self.assertRaises(ValueError):
+ run.main(["--url", "https://example.test/base", "--model", "public/model", "--top-k", value])
+ load.assert_not_called()
+
class TransportTests(unittest.TestCase):
def setUp(self) -> None:
@@ -268,6 +339,7 @@ class TransportTests(unittest.TestCase):
requests.append(request)
self.assertEqual(request.url.path, "/base/v1/chat/completions")
self.assertEqual(json.loads(request.read()), self.expected)
+ self.assertEqual(json.loads(request.read())["top_k"], 64)
self.assertEqual(request.headers["accept-encoding"], "gzip, identity")
self.assertTrue((self.folder / "sent.json").exists())
return httpx.Response(
@@ -296,6 +368,23 @@ class TransportTests(unittest.TestCase):
self.assertEqual(bodies, [run.request_body(self.case, settings(temperature=0.0))])
self.assertEqual(bodies[0]["temperature"], 0.0)
+ def test_explicit_top_k_reaches_the_wire_once(self) -> None:
+ bodies = []
+
+ def handler(request):
+ self.assertEqual(request.method, "POST")
+ bodies.append(json.loads(request.read()))
+ return httpx.Response(
+ 200, stream=httpx.ByteStream(run.canonical(reply())), headers={"content-type": "application/json"}
+ )
+
+ terminal = self.worker(handler, top_k=20)
+ self.assertEqual(terminal["status"], "ok")
+ self.assertEqual(terminal["finish_reason"], "stop")
+ self.assertEqual(terminal["physical_sends"], 1)
+ self.assertEqual(bodies, [run.request_body(self.case, settings(top_k=20))])
+ self.assertEqual(bodies[0]["top_k"], 20)
+
def test_capacity_rejection_never_retries(self) -> None:
requests = []