[PR #5516] [Engine] serve: in-place retune (TUNE) and conversation-cache routing by traffic shape #5490

Open
opened 2026-11-08 02:48:05 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Niko1221/Strata/pull/5516
Author: @rwkeyes
Created: 11/7/2026
Status: 🔄 Open

Base: main ← Head: serve/in-place-tune-and-cache-routing


📝 Commits (2)

  • 21a634e engine: retune the running engine between requests (a TUNE line)
  • e929c26 serve: POST /v1/tune, and route the prompt cache by traffic shape

📊 Changes

6 files changed (+677 additions, -0 deletions)

View changed files

➕ serve/conv_router.py (+126 -0)
📝 serve/server.py (+157 -0)
➕ serve/test_conv_router.py (+113 -0)
➕ serve/test_tune.py (+146 -0)
📝 src/program/generate.cpp (+69 -0)
📝 sycl/src/program/generate.cpp (+66 -0)

📄 Description

Problem and result

Two settings live behind an engine restart today, and one of them is worth a lot on the traffic this
server actually sees:

  1. Retuning costs a restart. prompt_cache, prompt_cache_every, short_read, spec_min_p,
    pcie_frac, prefill_chunk and the adapt_* family are read out of the engine's options at the
    moment the engine uses them, yet changing one restarts the engine — and with it a model load
    (93–100 s measured here). Measuring one value costs a start; a sweep costs one per candidate.
  2. The conversation cache is a tax on single-shot traffic. With --prompt-cache 6, a request that
    will never reuse its context still pays the parking cost. Cache off is +10.1 % prefill on 3.5 k
    code and +4.0 % on 4.0 k prose
    , and short single-shot prompts go from 0.522 s to 0.239 s TTFT.
    A context that is reused goes from 5.3 s to 0.3 s with the cache on, so the cache is right for
    chat/agent traffic and wrong for a batch of one-shot prompts — and the message list says which one
    a request is.

Result: a retune line on the serve pipe, POST /v1/tune in front of it, and an opt-in
--conv-route off|shadow|on (default off) that switches prompt_cache per traffic shape.
Measured on this tree (stock 146df3c4 + these two commits), Arc Pro B70, engine 0.1.58 SYCL,
Qwen3.8-Flash-Next IQ1_M, temperature 0, one request at a time:

lane --conv-route off --conv-route on
short single-shot TTFT 0.522 s 0.304 s (−42 %)
short single-shot prefill 143 tok/s 244 tok/s
short single-shot wall 0.73 s 0.50 s
a repeated context (the cache must still pay) 0.190 s / 20 575 tok/s 0.192 s / 20 374 tok/s
a 3.9 k code prompt unchanged unchanged until the run reaches --conv-route-batch-after

POST /v1/tune round trip on the same run:
{"settings":{"prompt_cache":0,"spec_min_p":0.4}} → {"applied":{"prompt_cache":0,"spec_min_p":0.4},"refused":[]};
{"settings":{"spec":4}} → {"applied":{},"refused":["spec=4"]} (a start-up-only key is refused, per key,
not silently ignored).

The empty answers in the extraction lane are expected on this tree: it is stock + these two commits,
without the thinking policy from #5512, so a 24-token budget still goes into the reasoning block. That
is the other PR; nothing here changes answer content, and the lanes above differ only in cache state.

Issue: #5515 — the problem, the proposed shape, and the two questions I would like a maintainer's
answer on before this is anything more than a draft (whether a retune belongs in the serve protocol at
all, and which key set it should accept). This PR is that implementation, kept in draft until the
scope question is answered.

Independent of #5512 (thinking budget by prompt): different regions of serve/server.py, no shared
lines, and either can land without the other — though the two together are what make the short-answer
lanes both fast and non-empty.

Approach

Two commits:

engine: retune the running engine between requests (a TUNE line)
TUNE k=v ... on the serve pipe → TUNED k=v ... with a refused: k=v(why) tail. Same handler in
src/program/generate.cpp (CUDA/HIP) and the DPCT copy in sycl/src/program/generate.cpp. The
dispatch sits after the QUIT check and before the request's busy scope, so nothing is in flight
when a field is written — that is what makes it safe without a lock. The key set is only what is read
out of the options when used: adapt_every, adapt_swaps, adapt_decay, adapt_min_gain (src/ only —
the DPCT copy has no such field), pcie_frac, spec_min_p, prompt_cache, prompt_cache_every,
short_read, and prefill_chunk downward only (its buffers were sized at start-up). Everything
that sizes memory or the session at load is deliberately absent: --spec, --kv*, --max-context,
--expert-cache and the resident tiers, --pcie-mode, graph/native flags.

serve: POST /v1/tune, and route the prompt cache by traffic shape
StrataEngine.tune() writes the line and parses the reply (TUNED → applied/refused, ERR →
ValueError, silence → EngineDied). Service.tune() takes the FIFO and, with --batch, the engine's
control line, exactly as Service.vram() already does, so a retune never lands mid-request.
POST /v1/tune returns 200 applied/refused, 409 while a request holds the engine, 400 for a malformed
body, 503 when the engine is gone.

serve/conv_router.py is the decision, and it is deliberately biased to keeping the cache: more than
one user turn, tools, or a prefix seen recently → on; a run of --conv-route-batch-after (4)
single-shot never-seen prompts → off; one conversational request switches it straight back. A wrong
"off" costs one full re-prefill on the next repeat, a wrong "on" costs the prefill share — that
asymmetry is why the counter is a run and not a single request. A switch needs the FIFO within 1 s, so
a retune that cannot get it is counted as refused and skipped rather than delaying the request.
shadow labels and logs only, so a deployment can measure its own mix first. Counters are reported
under conv_route in GET /v1/status.

Validation

Passed:

  • SYCL (the backend I can run here), full build of this tree at e929c26:
    cmake -S sycl -B build-sycl-aot -DSTRATA_SYCL_AOT=bmg-g31, ninja -j10 → engine 108 MB, --help
    rc=0, AOT device images embedded. 17 m 30 s cold.
  • CUDA: the changed translation unit compiles — cmake -DSTRATA_ENABLE_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=89 (CUDA 12.6) then
    ninja CMakeFiles/strata.dir/src/program/generate.cpp.o → object produced (2.45 MB), warnings only.
  • HIP: the changed translation unit compiles — -DSTRATA_ENABLE_HIP=ON -DCMAKE_HIP_COMPILER=/opt/rocm-7.1.1/llvm/bin/clang++ -DCMAKE_HIP_ARCHITECTURES=gfx1100 -Dhip_DIR=/opt/rocm-7.1.1/lib/cmake/hip -DCMAKE_CXX_FLAGS=-D__HIP_PLATFORM_AMD__=1 then the same
    object target → object produced (2.48 MB). Two notes for the tree, both pre-existing and untouched by
    this PR: the plain-CMake HIP configure needs hip_DIR (via setup.py it is found), and the host
    compile of that TU needs __HIP_PLATFORM_AMD__ (the repo's own setup path defines it). Also
    src/kernels/cuda/iq_kernels.cu has two __shared__ alignas(16) int4 sites that HIP clang rejects
    (#778) — I did not touch them and did not include a fix, since it is a different problem.
  • Hardware run, the numbers in "Problem and result": the engine above, --conv-route off and on,
    same config otherwise, POST /v1/tune exercised in both arms (applied and refused paths).
  • python -m pytest -q serve/test_tune.py serve/test_conv_router.py → 22 passed.
  • python -m unittest discover -s serve -p 'test_*.py' → 1521 tests, 613 s, 17 skipped, 1 failure;
    the failure is test_server.test_hip_ordinal ('0,1' != '1,0'), which fails identically on an
    unpatched 146df3c4 worktree. Log kept.

Failed: none observed beyond the pre-existing test_hip_ordinal.

Not run:

  • No CUDA or HIP hardware run — this host has one Arc Pro B70 and no NVIDIA/AMD dGPU reachable for
    the engine. Both backends' changed translation units compile; neither was executed.
  • No Metal build (the Metal tree has its own window handling and this change does not touch it).
  • No --batch/multi-slot run: Service.tune() takes the engine's control line when --batch is on,
    following Service.vram(), but I did not exercise a batching configuration.
  • No long soak (hours) of repeated switching; the router's own hysteresis is unit-tested, not aged.

Limits

  • The router is a heuristic over the message list. A request with a large, never-reused context
    that arrives right after four single-shot requests loses the cache for that one request and pays it
    back on the next repeat, which is the documented asymmetry; shadow exists to measure that rate on
    real traffic before turning it on.
  • The retune set is intentionally small. Adding a key is easy once it is clear the field is read at
    use time, but a key that sizes memory cannot join it — a future --spec or --kv-resident change is
    still a restart, and the reply now says so per key instead of failing invisibly.
  • One GPU, one model, one pack for the numbers above; the router's shape thresholds (batch_after,
    the repeat window) are defaults from one workload, not universal constants.

AI assistance was used for the implementation and the measurement runs. Every number is from a run on
the hardware named, and the commands are in this body.


🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Niko1221/Strata/pull/5516 **Author:** [@rwkeyes](https://github.com/rwkeyes) **Created:** 11/7/2026 **Status:** 🔄 Open **Base:** `main` ← **Head:** `serve/in-place-tune-and-cache-routing` --- ### 📝 Commits (2) - [`21a634e`](https://github.com/Niko1221/Strata/commit/21a634ea0394fbfd73533154f987ac700b144bf0) engine: retune the running engine between requests (a TUNE line) - [`e929c26`](https://github.com/Niko1221/Strata/commit/e929c26411f573fe3bb409c2a612c237c129be13) serve: POST /v1/tune, and route the prompt cache by traffic shape ### 📊 Changes **6 files changed** (+677 additions, -0 deletions) <details> <summary>View changed files</summary> ➕ `serve/conv_router.py` (+126 -0) 📝 `serve/server.py` (+157 -0) ➕ `serve/test_conv_router.py` (+113 -0) ➕ `serve/test_tune.py` (+146 -0) 📝 `src/program/generate.cpp` (+69 -0) 📝 `sycl/src/program/generate.cpp` (+66 -0) </details> ### 📄 Description ## Problem and result Two settings live behind an engine restart today, and one of them is worth a lot on the traffic this server actually sees: 1. **Retuning costs a restart.** `prompt_cache`, `prompt_cache_every`, `short_read`, `spec_min_p`, `pcie_frac`, `prefill_chunk` and the `adapt_*` family are read out of the engine's options at the moment the engine uses them, yet changing one restarts the engine — and with it a model load (93–100 s measured here). Measuring one value costs a start; a sweep costs one per candidate. 2. **The conversation cache is a tax on single-shot traffic.** With `--prompt-cache 6`, a request that will never reuse its context still pays the parking cost. Cache off is **+10.1 % prefill on 3.5 k code and +4.0 % on 4.0 k prose**, and short single-shot prompts go from **0.522 s to 0.239 s** TTFT. A context that *is* reused goes from 5.3 s to 0.3 s with the cache on, so the cache is right for chat/agent traffic and wrong for a batch of one-shot prompts — and the message list says which one a request is. **Result:** a retune line on the serve pipe, `POST /v1/tune` in front of it, and an opt-in `--conv-route off|shadow|on` (default **off**) that switches `prompt_cache` per traffic shape. Measured on this tree (stock `146df3c4` + these two commits), Arc Pro B70, engine 0.1.58 SYCL, Qwen3.8-Flash-Next IQ1_M, temperature 0, one request at a time: | lane | `--conv-route off` | `--conv-route on` | |---|---:|---:| | short single-shot TTFT | 0.522 s | **0.304 s (−42 %)** | | short single-shot prefill | 143 tok/s | 244 tok/s | | short single-shot wall | 0.73 s | 0.50 s | | a repeated context (the cache must still pay) | 0.190 s / 20 575 tok/s | 0.192 s / 20 374 tok/s | | a 3.9 k code prompt | unchanged | unchanged until the run reaches `--conv-route-batch-after` | `POST /v1/tune` round trip on the same run: `{"settings":{"prompt_cache":0,"spec_min_p":0.4}}` → `{"applied":{"prompt_cache":0,"spec_min_p":0.4},"refused":[]}`; `{"settings":{"spec":4}}` → `{"applied":{},"refused":["spec=4"]}` (a start-up-only key is refused, per key, not silently ignored). The empty answers in the extraction lane are **expected on this tree**: it is stock + these two commits, without the thinking policy from #5512, so a 24-token budget still goes into the reasoning block. That is the other PR; nothing here changes answer content, and the lanes above differ only in cache state. ## Related discussion Issue: #5515 — the problem, the proposed shape, and the two questions I would like a maintainer's answer on before this is anything more than a draft (whether a retune belongs in the serve protocol at all, and which key set it should accept). This PR is that implementation, kept in draft until the scope question is answered. Independent of #5512 (thinking budget by prompt): different regions of `serve/server.py`, no shared lines, and either can land without the other — though the two together are what make the short-answer lanes both fast and non-empty. ## Approach Two commits: **`engine: retune the running engine between requests (a TUNE line)`** `TUNE k=v ...` on the serve pipe → `TUNED k=v ...` with a `refused: k=v(why)` tail. Same handler in `src/program/generate.cpp` (CUDA/HIP) and the DPCT copy in `sycl/src/program/generate.cpp`. The dispatch sits after the QUIT check and **before** the request's busy scope, so nothing is in flight when a field is written — that is what makes it safe without a lock. The key set is only what is read out of the options when used: `adapt_every`, `adapt_swaps`, `adapt_decay`, `adapt_min_gain` (src/ only — the DPCT copy has no such field), `pcie_frac`, `spec_min_p`, `prompt_cache`, `prompt_cache_every`, `short_read`, and `prefill_chunk` **downward only** (its buffers were sized at start-up). Everything that sizes memory or the session at load is deliberately absent: `--spec`, `--kv*`, `--max-context`, `--expert-cache` and the resident tiers, `--pcie-mode`, graph/native flags. **`serve: POST /v1/tune, and route the prompt cache by traffic shape`** `StrataEngine.tune()` writes the line and parses the reply (`TUNED` → applied/refused, `ERR` → `ValueError`, silence → `EngineDied`). `Service.tune()` takes the FIFO and, with `--batch`, the engine's control line, exactly as `Service.vram()` already does, so a retune never lands mid-request. `POST /v1/tune` returns 200 applied/refused, 409 while a request holds the engine, 400 for a malformed body, 503 when the engine is gone. `serve/conv_router.py` is the decision, and it is deliberately biased to keeping the cache: more than one user turn, tools, or a prefix seen recently → **on**; a *run* of `--conv-route-batch-after` (4) single-shot never-seen prompts → **off**; one conversational request switches it straight back. A wrong "off" costs one full re-prefill on the next repeat, a wrong "on" costs the prefill share — that asymmetry is why the counter is a run and not a single request. A switch needs the FIFO within 1 s, so a retune that cannot get it is counted as `refused` and skipped rather than delaying the request. `shadow` labels and logs only, so a deployment can measure its own mix first. Counters are reported under `conv_route` in `GET /v1/status`. ## Validation **Passed:** * **SYCL (the backend I can run here), full build of this tree** at `e929c26`: `cmake -S sycl -B build-sycl-aot -DSTRATA_SYCL_AOT=bmg-g31`, `ninja -j10` → engine 108 MB, `--help` rc=0, AOT device images embedded. 17 m 30 s cold. * **CUDA: the changed translation unit compiles** — `cmake -DSTRATA_ENABLE_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=89` (CUDA 12.6) then `ninja CMakeFiles/strata.dir/src/program/generate.cpp.o` → object produced (2.45 MB), warnings only. * **HIP: the changed translation unit compiles** — `-DSTRATA_ENABLE_HIP=ON -DCMAKE_HIP_COMPILER=/opt/rocm-7.1.1/llvm/bin/clang++ -DCMAKE_HIP_ARCHITECTURES=gfx1100 -Dhip_DIR=/opt/rocm-7.1.1/lib/cmake/hip -DCMAKE_CXX_FLAGS=-D__HIP_PLATFORM_AMD__=1` then the same object target → object produced (2.48 MB). Two notes for the tree, both pre-existing and untouched by this PR: the plain-CMake HIP configure needs `hip_DIR` (via `setup.py` it is found), and the host compile of that TU needs `__HIP_PLATFORM_AMD__` (the repo's own setup path defines it). Also `src/kernels/cuda/iq_kernels.cu` has two `__shared__ alignas(16) int4` sites that HIP clang rejects (#778) — I did not touch them and did not include a fix, since it is a different problem. * **Hardware run**, the numbers in "Problem and result": the engine above, `--conv-route off` and `on`, same config otherwise, `POST /v1/tune` exercised in both arms (applied and refused paths). * `python -m pytest -q serve/test_tune.py serve/test_conv_router.py` → **22 passed**. * `python -m unittest discover -s serve -p 'test_*.py'` → **1521 tests, 613 s, 17 skipped, 1 failure**; the failure is `test_server.test_hip_ordinal` (`'0,1' != '1,0'`), which fails identically on an unpatched `146df3c4` worktree. Log kept. **Failed:** none observed beyond the pre-existing `test_hip_ordinal`. **Not run:** * No CUDA or HIP **hardware** run — this host has one Arc Pro B70 and no NVIDIA/AMD dGPU reachable for the engine. Both backends' changed translation units compile; neither was executed. * No Metal build (the Metal tree has its own window handling and this change does not touch it). * No `--batch`/multi-slot run: `Service.tune()` takes the engine's control line when `--batch` is on, following `Service.vram()`, but I did not exercise a batching configuration. * No long soak (hours) of repeated switching; the router's own hysteresis is unit-tested, not aged. ## Limits * **The router is a heuristic over the message list.** A request with a large, never-reused context that arrives right after four single-shot requests loses the cache for that one request and pays it back on the next repeat, which is the documented asymmetry; `shadow` exists to measure that rate on real traffic before turning it on. * **The retune set is intentionally small.** Adding a key is easy once it is clear the field is read at use time, but a key that sizes memory cannot join it — a future `--spec` or `--kv-resident` change is still a restart, and the reply now says so per key instead of failing invisibly. * One GPU, one model, one pack for the numbers above; the router's shape thresholds (`batch_after`, the repeat window) are defaults from one workload, not universal constants. AI assistance was used for the implementation and the measurement runs. Every number is from a run on the hardware named, and the commands are in this body. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Niko1221/Strata#5490
No description provided.