Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## Unreleased — 2026-10-18 context tune

- Context sweep on the production launch line (32K/40K/48K/56K, short and 80%-full requests): speed holds to 48K (43.6 tok/s with 39K tokens in context) and falls off at 56K (22.4 tok/s, about 1 GiB moved to system memory). New `bench/ctx-sweep.py`, raw results in `data/ctx-sweep-20261018.jsonl`, tuning-log rows 24-27.
- Governor margin 2.5 -> 1.2 GiB and host-RAM prompt cache 6144 MiB (MAX and BALANCED): the live load is now 45,056 tokens (49,152 when the desktop is light) at 45-50 tok/s on the warm check, instead of 32,768.
- `agents/codex-qwen.cmd`: the 32,768 client cap is now 65,536, so Codex uses the server's real window minus 8K, and it compacts at 90% of the window instead of 85%.
- Recorded the 17-18 Oct slowdown (28 vs 47 tok/s) and its fix (a Windows restart; ECC was off, clocks and temperature normal).

## Unreleased — 2026-10-17 field report

- README front page refresh: hero banner, a four-step "recipe" for Qwen3.8-27B at 50+ tok/s on a B60 (copy-paste server line), the per-request decode headline (mean 53.3, 47-58 tok/s, from the existing `tune.txt` run) with its context caveats stated up front, and a project-scale card.
Expand Down
4 changes: 2 additions & 2 deletions agents/codex-qwen.cmd
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ set "TMP=%LOCALAPPDATA%\Temp"
if "%LOCAL_QWEN_KEY%"=="" for /f "usebackq delims=" %%k in (`powershell -NoProfile -Command "[Environment]::GetEnvironmentVariable('LOCAL_QWEN_KEY','User')"`) do set "LOCAL_QWEN_KEY=%%k"
set "QWEN_WIN=100000"
for /f "usebackq delims=" %%w in (`powershell -NoProfile -ExecutionPolicy Bypass -File C:\AI\governor\qwen.ps1 window`) do set "QWEN_WIN=%%w"
if "%QWEN_CLIENT_CAP%"=="" set "QWEN_CLIENT_CAP=32768"
if "%QWEN_CLIENT_CAP%"=="" set "QWEN_CLIENT_CAP=65536"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve a safe fallback when window discovery fails

If the PowerShell invocation produces no output—for example because C:\AI\governor\qwen.ps1 is missing or fails before printing—the initial QWEN_WIN=100000 remains in effect, and this increased cap now tells Codex it has 65,536 tokens even when the server may have only a 32K–49K context. Codex then waits until roughly 59K to compact and receives an explicit context-overflow error; initialize the wrapper to the same conservative fallback used by qwen.ps1 or only raise the cap after successful discovery.

Useful? React with 👍 / 👎.

if %QWEN_WIN% GTR %QWEN_CLIENT_CAP% set "QWEN_WIN=%QWEN_CLIENT_CAP%"
if "%QWEN_COMPACT%"=="" set "QWEN_COMPACT=200000"
set /a QWEN_CAP=QWEN_WIN*85/100
set /a QWEN_CAP=QWEN_WIN*90/100
if %QWEN_COMPACT% GTR %QWEN_CAP% set "QWEN_COMPACT=%QWEN_CAP%"
rem Lean MCP set for the local model: disable any heavy/cloud MCP servers from your main Codex config here, e.g.
rem -c mcp_servers.<name>.enabled=false
Expand Down
119 changes: 119 additions & 0 deletions bench/ctx-sweep.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# Context sweep for one llama-server launch line (arc-llm-lab, 2026-10-18).
# Starts llama-server on a spare port at each context size, then measures short-prompt speed,
# speed with the context 80% full, and the process's dedicated/shared VRAM (Windows PDH counters).
# Run it with the production model UNLOADED (qwen mode off) so the card is not shared.
# Edit EXE and the paths in BASE_ARGS for your layout. Usage: python ctx-sweep.py 32768 40960 49152 57344
# Writes results.jsonl and server-<ctx>.log next to this file. Results from the B60: data/ctx-sweep-20261018.jsonl

import json, os, subprocess, sys, time, urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
EXE = r"C:\AI\llama.cpp\vulkan-intelfa\llama-server.exe"
PORT = 10011
CTXS = [int(x) for x in (sys.argv[1:] or ["32768", "40960", "49152", "57344", "65536"])]

BASE_ARGS = [
"-m", "C:/AI/models/thinkingcap/ThinkingCap-Qwen3.8-27B-Q4_K_M.gguf",
"--mmproj", "C:/AI/models/thinkingcap/mmproj-ThinkingCap-Qwen3.8-27B-f16.gguf",
"-a", "qwen3.8-27b", "--host", "127.0.0.1", "--port", str(PORT),
"-ctk", "f16", "-ctv", "f16", "-t", "14", "-tb", "14", "-cram", "2048", "--prio", "0",
"-ngl", "99", "-fa", "on", "-lm", "dio", "--jinja", "-np", "1", "--cache-reuse", "256", "--metrics",
"--reasoning-budget", "16384", "--reasoning-budget-message", "Thinking budget reached. Give the final answer now.",
"--no-mmproj-offload", "-fit", "off", "--chat-template-file", "C:/AI/governor/qwen38-template.jinja",
"--no-context-shift",
"-ngld", "99", "-md", "C:/AI/models/qwen3.8-27b/Qwen3.8-27B-DFlash2-Q4_K_M.gguf",
"--spec-type", "draft-dflash", "--spec-draft-n-max", "7", "-ub", "256",
"-ctkd", "q8_0", "-ctvd", "q8_0", "--spec-draft-p-min", "0.4",
]

SHORT = "Write a Python class implementing an LRU cache with get and put, type hints and a docstring. Code only."
URL = f"http://127.0.0.1:{PORT}"


def post(path, body, timeout=900):
r = urllib.request.urlopen(urllib.request.Request(URL + path, data=json.dumps(body).encode(),
headers={"Content-Type": "application/json"}), timeout=timeout)
return json.loads(r.read())


def health():
try:
return json.loads(urllib.request.urlopen(URL + "/health", timeout=3).read()).get("status") == "ok"
except Exception:
return False


def vram(pid):
ps = ("$s=(Get-Counter '\\GPU Process Memory(*)\\Dedicated Usage','\\GPU Process Memory(*)\\Shared Usage').CounterSamples | "
f"? {{ $_.InstanceName -like 'pid_{pid}_*' }}; $d=($s | ? Path -like '*dedicated*' | measure CookedValue -Sum).Sum; "
"$h=($s | ? Path -like '*shared*' | measure CookedValue -Sum).Sum; "
"$a=(Get-Counter '\\GPU Adapter Memory(*)\\Dedicated Usage').CounterSamples | measure CookedValue -Sum; "
"'{0} {1} {2}' -f $d,$h,$a.Sum")
out = subprocess.run(["powershell", "-NoProfile", "-Command", ps], capture_output=True, text=True,
creationflags=0x08000000).stdout.split()
d, h, a = (float(x) / 2**30 for x in out[:3])
return {"dedicated": round(d, 2), "shared": round(h, 2), "others": round(a - d, 2)}


def chat(content, max_tokens):
body = {"messages": [{"role": "user", "content": content}], "max_tokens": max_tokens, "temperature": 0.2,
"chat_template_kwargs": {"enable_thinking": False}}
t0 = time.time(); d = post("/v1/chat/completions", body); dt = time.time() - t0
tm = d.get("timings", {})
return {"wall_s": round(dt, 1), "prompt_n": tm.get("prompt_n"), "prompt_tps": round(tm.get("prompt_per_second", 0), 1),
"gen_n": tm.get("predicted_n"), "gen_tps": round(tm.get("predicted_per_second", 0), 1),
"draft": tm.get("draft_n"), "acc": tm.get("draft_n_accepted")}


def filler(target_tokens):
# varied, code-like text so the drafter behaves like a real agent context
blocks, i = [], 0
while True:
i += 1
blocks.append(f"def handler_{i}(order_id: int, qty: int, region: str = 'nsw') -> dict:\n"
f" \"\"\"Process order {i}: validate quantity, apply region surcharge {i % 7}%, log the result.\"\"\"\n"
f" if qty <= 0:\n raise ValueError('qty must be positive for order %d' % order_id)\n"
f" total = qty * {10 + i % 13}.{i % 100:02d} * (1 + {i % 7} / 100)\n"
f" return {{'id': order_id, 'qty': qty, 'region': region, 'total': round(total, 2), 'step': {i}}}\n\n")
if i % 200 == 0:
text = "".join(blocks)
n = len(post("/tokenize", {"content": text})["tokens"])
if n >= target_tokens:
keep = int(len(blocks) * target_tokens / n)
return "".join(blocks[:keep])


def main():
env = dict(os.environ, GGML_VK_FORCE_MMVQ="1")
out = open(os.path.join(HERE, "results.jsonl"), "a", encoding="utf-8")
for ctx in CTXS:
log = open(os.path.join(HERE, f"server-{ctx}.log"), "w", encoding="utf-8", errors="replace")
p = subprocess.Popen([EXE] + BASE_ARGS + ["-c", str(ctx)], stdout=log, stderr=subprocess.STDOUT, env=env,
creationflags=0x08000000) # CREATE_NO_WINDOW
rec = {"ctx": ctx, "t": time.strftime("%H:%M:%S")}
try:
t0 = time.time()
while not health():
if p.poll() is not None:
raise RuntimeError(f"server exited rc={p.returncode}")
Comment on lines +96 to +98

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject an already-occupied benchmark port

If another llama server or compatible service is already listening on port 10011, health() succeeds immediately and this loop never checks whether the newly spawned process exited because it could not bind. The subsequent requests then benchmark the pre-existing server while recording the requested ctx and the failed child's PID, silently corrupting the sweep; perform a preflight port check or verify p.poll() and that the responding server is the process just launched before collecting results.

Useful? React with 👍 / 👎.

if time.time() - t0 > 240:
raise RuntimeError("load timeout")
time.sleep(2)
rec["load_s"] = round(time.time() - t0, 1)
chat("hi", 4) # warm
rec["vram_after_load"] = vram(p.pid)
rec["short"] = [chat(SHORT + " " * k, 300) for k in range(3)]
text = filler(int(ctx * 0.80))
rec["deep"] = chat(text + "\n\nNow write one new function handler_final that sums the 'total' of a list of the dicts above, with type hints, a docstring and two doctests. Code only.", 300)
rec["vram_after_deep"] = vram(p.pid)
except Exception as e:
rec["error"] = repr(e)
finally:
p.kill(); p.wait(); log.close()
time.sleep(6)
print(json.dumps(rec), flush=True); out.write(json.dumps(rec) + "\n"); out.flush()
out.close()


if __name__ == "__main__":
main()
4 changes: 4 additions & 0 deletions data/ctx-sweep-20261018.jsonl
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{"ctx": 32768, "t": "03:51:43", "load_s": 16.6, "vram_after_load": {"dedicated": 20.11, "shared": 0.95, "others": 1.64}, "short": [{"wall_s": 6.1, "prompt_n": 36, "prompt_tps": 85.4, "gen_n": 300, "gen_tps": 53.7, "draft": 305, "acc": 254}, {"wall_s": 5.7, "prompt_n": 4, "prompt_tps": 23.1, "gen_n": 300, "gen_tps": 54.8, "draft": 309, "acc": 254}, {"wall_s": 5.5, "prompt_n": 4, "prompt_tps": 23.9, "gen_n": 300, "gen_tps": 57.0, "draft": 292, "acc": 256}], "deep": {"wall_s": 61.2, "prompt_n": 26166, "prompt_tps": 456.2, "gen_n": 179, "gen_tps": 48.2, "draft": 178, "acc": 152}, "vram_after_deep": {"dedicated": 20.15, "shared": 0.98, "others": 1.55}}
{"ctx": 40960, "t": "03:53:31", "load_s": 16.5, "vram_after_load": {"dedicated": 20.61, "shared": 0.96, "others": 1.55}, "short": [{"wall_s": 6.4, "prompt_n": 36, "prompt_tps": 79.7, "gen_n": 300, "gen_tps": 51.0, "draft": 316, "acc": 252}, {"wall_s": 5.5, "prompt_n": 4, "prompt_tps": 23.4, "gen_n": 300, "gen_tps": 57.3, "draft": 296, "acc": 256}, {"wall_s": 5.8, "prompt_n": 4, "prompt_tps": 24.3, "gen_n": 300, "gen_tps": 54.6, "draft": 309, "acc": 254}], "deep": {"wall_s": 78.3, "prompt_n": 32605, "prompt_tps": 438.7, "gen_n": 176, "gen_tps": 46.3, "draft": 175, "acc": 150}, "vram_after_deep": {"dedicated": 20.68, "shared": 0.98, "others": 1.59}}
{"ctx": 49152, "t": "03:55:37", "load_s": 16.5, "vram_after_load": {"dedicated": 21.12, "shared": 0.96, "others": 1.59}, "short": [{"wall_s": 6.3, "prompt_n": 36, "prompt_tps": 86.2, "gen_n": 300, "gen_tps": 52.2, "draft": 319, "acc": 253}, {"wall_s": 5.8, "prompt_n": 4, "prompt_tps": 24.7, "gen_n": 300, "gen_tps": 54.4, "draft": 309, "acc": 254}, {"wall_s": 6.3, "prompt_n": 4, "prompt_tps": 24.1, "gen_n": 300, "gen_tps": 49.9, "draft": 342, "acc": 250}], "deep": {"wall_s": 97.4, "prompt_n": 39181, "prompt_tps": 420.8, "gen_n": 179, "gen_tps": 43.6, "draft": 182, "acc": 151}, "vram_after_deep": {"dedicated": 21.17, "shared": 0.98, "others": 1.66}}
{"ctx": 57344, "t": "03:58:03", "load_s": 16.5, "vram_after_load": {"dedicated": 20.69, "shared": 1.9, "others": 1.66}, "short": [{"wall_s": 10.1, "prompt_n": 36, "prompt_tps": 84.2, "gen_n": 300, "gen_tps": 31.2, "draft": 321, "acc": 252}, {"wall_s": 9.7, "prompt_n": 4, "prompt_tps": 24.8, "gen_n": 300, "gen_tps": 31.6, "draft": 320, "acc": 252}, {"wall_s": 9.3, "prompt_n": 4, "prompt_tps": 24.4, "gen_n": 300, "gen_tps": 33.1, "draft": 309, "acc": 254}], "deep": {"wall_s": 124.6, "prompt_n": 45757, "prompt_tps": 393.3, "gen_n": 183, "gen_tps": 22.4, "draft": 232, "acc": 148}, "vram_after_deep": {"dedicated": 20.76, "shared": 1.92, "others": 1.57}}
6 changes: 5 additions & 1 deletion docs/TUNING-LOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ Every change, in order, with the number it produced. Each **Data** entry names a
| 21 | Qwen's template only accepts `reasoning_effort` of xhigh / medium / low | other values give HTTP 500; "high" maps to xhigh | v3 bench |
| 22 | Windows audit: dwm.exe VRAM with two 3440x1440 monitors | dwm holds 2.6 GB of the 24 GB. Dropping both monitors to 1920x1080 did **not** shrink it (2.6 -> 3.3 GB right after the change, 2.8 GB a minute later). See [DISPLAY-POLICY.md](DISPLAY-POLICY.md) | observed on the PC |
| 23 | Intel graphics services | Graphics Software Service 15 MB RAM, shader distributor 3 MB, PROSet monitoring small; no overlay process was running and none held VRAM. Switching them off is a tidy-up, not a speed-up | observed on the PC |
| 24 | Throughput regression, 17-18 Oct: warm 300-token check fell to 28 tok/s (47 on 15 Oct) with no config change. Checked: ECC **off**, GPU at 2400 MHz and 65 °C under load, no GPU/VRAM/fan tuning, driver unchanged, power plan High performance | a **Windows restart** (uptime was 2 d 13 h) restored it: 42.1 / 44.8 / 46.2 tok/s on the same check. Cause INFERRED: graphics memory manager state after a long uptime | observed on the PC (2026-10-18) |
| 25 | Context sweep: the exact production command line on a spare port, governor off, other apps holding 1.55-1.66 GiB of VRAM. Per size: 3 short code requests, then one request with the context 80% full (code-like filler) | 32K: 54-57 short, **48.2** deep (26K tokens, prompt 456 tok/s). 40K: 51-57 / **46.3** (32.6K, 439). 48K: 50-54 / **43.6** (39K, 421), 1.05 GiB left free. 56K: **31-33 / 22.4**, 1.9 GiB in shared memory. The cliff is between 48K and 56K: 56K would have needed to leave about 0.6 GiB free, and the driver moved about 1 GiB to system memory instead. The 0.96 GiB of "shared" seen at every size is the vision projector held in system memory (`--no-mmproj-offload`, 0.87 GiB file), not a spill | [data/ctx-sweep-20261018.jsonl](../data/ctx-sweep-20261018.jsonl), [bench/ctx-sweep.py](../bench/ctx-sweep.py) |
| 26 | Governor free-VRAM margin 2.5 -> **1.2 GiB** (MAX and BALANCED), host-RAM prompt cache `-cram` 2048 (MAX) / 4096 (BALANCED) -> **6144 MiB** for both, so a 40K agent prompt (about 2.5 GiB of KV) fits in the cache when two agents take turns on the one slot | the governor now loads **45,056** with other apps at 1.64 GiB (1.35 GiB left free), 49,152 when the desktop is light, and steps down when other apps grow. Warm check after the change: 45.1 / 50.1 / 47.2 tok/s | governor.log (2026-10-18 04:04) |

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Commit the advertised governor tune

For anyone deploying the governor from this repository, these settings are not actually applied: governor/profiles.json still gives MAX a 1.35 GiB margin and 8192 MiB cache, and BALANCED a 1.5 GiB margin and 4096 MiB cache. Because launch.ps1 reads those values directly, the shipped governor will not use the documented 1.2 GiB/6144 MiB configuration or reliably produce the claimed 45,056/49,152-token loads; update the profile alongside this documentation or mark the result as local-only.

Useful? React with 👍 / 👎.

| 27 | Codex wrapper: client cap 32,768 -> 65,536 and compaction at 90% of the window (was 85%) | Codex now gets the server's real window minus 8K (36,864 at a 45,056 load) and compacts at about 33K instead of 27.8K | [agents/codex-qwen.cmd](../agents/codex-qwen.cmd) |

## Settings that matter (final)

Expand All @@ -37,7 +41,7 @@ GGML_VK_FORCE_MMVQ=1
llama-server -m Qwen3.8-27B-UD-Q4_K_M.gguf --mmproj mmproj-F16.gguf --no-mmproj-offload -a qwen3.8-27b
--host 127.0.0.1 --port 10001
-c <sized at each load, 32768 to 65536> -ctk f16 -ctv f16
-t <8 BALANCED | 14 MAX | 4 LEAN> -tb <same as -t> -cram <4096 BALANCED | 8192 MAX | 1024 LEAN>
-t <8 BALANCED | 14 MAX | 4 LEAN> -tb <same as -t> -cram <6144 BALANCED | 6144 MAX | 1024 LEAN>
--prio <-1 BELOW-NORMAL | 0 NORMAL>
-ngl 99 -fa on -lm dio -np 1 -fit off --jinja --chat-template-file qwen38-template.jinja
--cache-reuse 256 --metrics --no-context-shift
Expand Down
Loading