feat(m0): measure the one model's game placements and fix desktop app matching

Add a gamemode stage that restarts Qwen3.6-35B-A3B with a smaller routed
expert VRAM budget (6, 4, 2 GiB, and 2 GiB with half the CPU workers), then
the normal placement again, and records switch time, free VRAM, output speed,
first spoken sentence and 8K-context first token for each. It names the
fastest placement that leaves the game its 8 GB reserve. Strata 0.1.59's
qwen36 engine cannot shrink VRAM while running, so each placement is a restart.

The desktop stage now matches running apps by the process image name Windows
lists (Discord.exe) and closes the calculator it launched by image name when
close-app cannot find a UWP app.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-10 17:39:42 +09:00
parent c63a859ced
commit 13de978cf9
8 changed files with 302 additions and 17 deletions

View File

@@ -5,6 +5,8 @@ Options (--opt key=value):
url=http://.../v1 measure an already running server instead (no Strata management)
context=32768 context size to start Strata with
only=tools only re-measure tool calling, before and after the Jarvis fix
only=levels the fast model in each placement the app's automatic
tuning switches between (normal, and less VRAM for a game)
"""
from __future__ import annotations
@@ -20,9 +22,10 @@ import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from m0lib.common import IS_WINDOWS, GpuSampler, StageResult, run_logged, say, scrub, stage_args # noqa: E402
from m0lib.llm_bench import (bench_single, test_decode, test_images, test_parallel, test_tools, # noqa: E402
test_vram_shrink, warmup)
from m0lib.common import (IS_WINDOWS, GpuSampler, StageResult, gpu_memory_mib, run_logged, say, # noqa: E402
scrub, stage_args)
from m0lib.llm_bench import (bench_single, quick_bench, test_decode, test_images, test_parallel, # noqa: E402
test_tools, test_vram_shrink, warmup)
from m0lib.tool_fix import test_tools_fixed, tools_passed # noqa: E402
from m0lib.llm_client import ChatClient, http_json # noqa: E402
@@ -49,6 +52,24 @@ CANDIDATES = {
],
}
PORT = 8080
# The placements the app's automatic tuning moves the one model between.
# Strata's qwen36 engine cannot give VRAM back while it runs (POST /v1/vram
# answers 400), so each placement is a restart with --expert-vram (GiB for the
# routed experts; the rest stay in RAM) and a matching prompt chunk. A game
# placement also reads pictures on the CPU and answers one request at a time.
# The last row starts the normal placement again: what returning after a game costs.
GAME_RESERVE_MIB = 8000
_GAME = {"parallel": 1, "vision": "cpu"}
LEVELS = [
{"key": "normal", "parallel": 2, "vision": "gpu", "sets": []},
{"key": "game_experts_6g", **_GAME, "sets": ["expert-vram=6", "prefill=2048"]},
{"key": "game_experts_4g", **_GAME, "sets": ["expert-vram=4", "prefill=2048"]},
{"key": "game_experts_2g", **_GAME, "sets": ["expert-vram=2", "prefill=2048"]},
# A game also wants CPU cores: the same placement with half the engine's CPU workers.
{"key": "game_experts_2g_8_workers", **_GAME, "sets": ["expert-vram=2", "prefill=2048", "pool-workers=8"]},
{"key": "normal_again", "parallel": 2, "vision": "gpu", "sets": []},
]
INSTALL_URL = "https://github.com/Niko1221/Strata/releases/latest/download/install.ps1"
@@ -166,6 +187,14 @@ class Strata:
dest = self.log.with_name(f"{self.log.stem}_engine_{src.name.removesuffix('.engine.log')}.log")
dest.write_text(scrub(text), encoding="utf-8")
def engine_lines(self, prefix: str = "strata-q36:", limit: int = 20) -> list[str]:
"""The newest engine log's placement lines (how much went to VRAM and RAM), scrubbed."""
found = sorted(self.home.rglob("*.engine.log"), key=lambda p: p.stat().st_mtime)
if not found:
return []
text = found[-1].read_text(encoding="utf-8", errors="replace")[-400_000:]
return [scrub(x.strip())[:400] for x in text.splitlines() if x.lstrip().startswith(prefix)][:limit]
def stop(self) -> None:
run_logged(self.cmd("launch", "--stop"), self.log, timeout=300, env=self.env)
time.sleep(3)
@@ -256,12 +285,71 @@ def try_candidates(r: StageResult, which: str, default_summary: dict | None, mea
return
def measure_levels(r: StageResult, s: Strata, preset: dict, context: int, levels: list[dict] = LEVELS) -> None:
"""Start the model in each placement and measure what the switch and the placement cost."""
base = f"http://127.0.0.1:{PORT}/v1"
rows: list[dict] = []
r["levels"] = rows
for lv in levels:
row: dict = {"key": lv["key"], "parallel": lv["parallel"], "vision": lv["vision"], "sets": lv["sets"]}
rows.append(row)
say(f" - 배치 {lv['key']}: 다시 시작해서 재는 중")
t0 = time.perf_counter()
s.stop()
idle = gpu_memory_mib()
row["vram_idle_mib"] = idle[0] if idle else None
with GpuSampler(interval=1) as g:
row["launch"] = s.launch(preset, context, parallel=lv["parallel"], vision=lv["vision"],
extra_sets=lv["sets"], timeout=3600)
ready = row["launch"].get("ready")
row["switch_s"] = round(time.perf_counter() - t0, 1) if ready else None
row["engine"] = s.engine_lines()
if ready:
try:
c = ChatClient(base)
if "server" not in r.data:
r["server"] = {"model": c.model, "info": server_info(base)}
c.chat([{"role": "user", "content": "안녕"}], max_tokens=8) # loading is not answer time
row.update(quick_bench(c))
except Exception as e:
r.error(f"level {lv['key']}", e)
now = gpu_memory_mib() if ready else None # the sampler can miss a short run
peak = max(x for x in (g.peak, now[0] if now else None) if x is not None) \
if g.peak is not None or now else None
if now:
row["vram_after_mib"] = now[0] # settled; the peak (during the start) is what a running game must survive
if peak is not None and idle:
row["vram_peak_mib"] = peak
row["vram_free_mib"] = idle[1] - peak
say(f" 전환 {row['switch_s']}s, 출력 {(row.get('decode_tok_s') or {}).get('median')} tok/s, "
f"남는 VRAM {row.get('vram_free_mib')} MiB")
r.save()
s.stop()
r["game_choice"] = pick_game_level(rows)
def pick_game_level(rows: list[dict], reserve_mib: int = GAME_RESERVE_MIB) -> dict | None:
"""The game placement the app would pick on this PC: the fastest one that
leaves the game its reserve of VRAM. None when no game placement does."""
fits = [x for x in rows if x["key"].startswith("game_") and (x.get("vram_free_mib") or 0) >= reserve_mib
and (x.get("decode_tok_s") or {}).get("median")]
if not fits:
return None
best = max(fits, key=lambda x: x["decode_tok_s"]["median"])
return {"key": best["key"], "reserve_mib": reserve_mib, "vram_free_mib": best["vram_free_mib"],
"decode_tok_s": best["decode_tok_s"]["median"], "switch_s": best.get("switch_s"),
"voice_first_sentence": (best.get("voice_first_sentence") or {}).get("median")}
def measure_external(r: StageResult, url: str, context: int, only: str = "") -> None:
c = ChatClient(url)
r["server"] = {"url": url, "model": c.model, "info": server_info(c.base)}
if only == "tools":
tools_only(r, c)
return
if only == "levels":
r.note("placements need Strata; not measured against an external server")
return
with GpuSampler() as g:
bench_single(r, c, context)
test_parallel(r, c)
@@ -277,6 +365,13 @@ def measure_strata(r: StageResult, work: Path, which: str, context: int, only: s
return
r["plan"] = s.plan(preset, context)
r.save()
if only == "levels":
s.stop()
if port_in_use(PORT):
r.error("port", f"다른 프로그램이 {PORT} 포트를 쓰고 있습니다. 그 프로그램을 끄고 다시 실행해 주세요.")
return
measure_levels(r, s, preset, context)
return
# 1) Start (the first start downloads the model and engine).
say(f" {preset['label']} 시작 중. 처음에는 모델을 내려받으므로 오래 걸립니다.")
@@ -345,7 +440,8 @@ def main() -> int:
which = opts.get("model", "fast")
context = int(opts.get("context", "32768"))
only = opts.get("only", "")
r = StageResult(f"{'tools' if only == 'tools' else 'llm'}_{which}", out)
name = {"tools": f"tools_{which}", "levels": "gamemode"}.get(only, f"llm_{which}")
r = StageResult(name, out)
try:
if opts.get("url"):
measure_external(r, opts["url"], context, only)