feat(m0): measure the LLM next to the STT, the STT on the CPU and a real game

gamemode now also starts the 2 GB expert placement with a 16K context and
drops the --kv q4_0 and --mtp off rows the Strata 0.1.59 qwen36 engine
ignores; the normal placement answers one request at a time.

gamemode_stt loads the STT worker (stt.py mode=load) before the LLM picks its
placement and keeps it transcribing ten speakers at once while the LLM is
measured, so the VRAM left is the real game share. The game placements run
with the STT on the GPU and on the CPU. gamemode_live repeats the game rows
while the user runs a real game; it only runs when asked for
(run_m0_game_live.bat) and is skipped when nobody is at the PC.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-10 19:12:53 +09:00
parent d0ffa7f55e
commit 3794bb7149
7 changed files with 499 additions and 59 deletions

View File

@@ -7,6 +7,10 @@ Options (--opt key=value):
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)
only=together the same with the STT loaded next to it and transcribing ten
speakers at once, on the GPU and on the CPU (needs stt_python=)
only=live game placements and the STT while the user runs a real game
stt_python=PATH the Python of the stt venv (m0.py passes it)
"""
from __future__ import annotations
@@ -22,8 +26,8 @@ import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from m0lib.common import (IS_WINDOWS, GpuSampler, StageResult, gpu_memory_mib, run_logged, say, # noqa: E402
scrub, stage_args)
from m0lib.common import (IS_WINDOWS, GpuSampler, StageResult, ask, gpu_memory_mib, interactive, # noqa: E402
read_json, run_logged, say, scrub, stage_args, wait_enter)
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
@@ -59,28 +63,40 @@ PORT = 8080
# routed experts; the rest stay in RAM) and a matching prompt chunk. A game
# placement also reads pictures on the CPU, answers one request at a time and
# leaves the game half the CPU (8 engine workers cost nothing on the 9950X3D).
# The first game PC run (2026-11-10) showed that the expert budget is not the
# floor: at 2 GB the model still held 10.8 GB and a 16 GB card kept only
# 4.3 GB free. The rest is 4.4 GiB of weights that never leave the card, the
# conversation memory (1.43 GiB per 32K in int8; q4_0 is half), the MTP
# drafter (about 1 GB) and buffers, so the smaller placements also shrink those.
# The game PC runs (2026-11-10) showed that the expert budget is not the floor:
# 4.4 GiB of weights never leave the card, the conversation memory scales with
# the context, and Strata 0.1.59's qwen36 engine takes no --kv and always loads
# the MTP block, so the smaller placements shrink the context instead.
# The normal placement answers one request at a time (faster on a 16 GB card);
# two only when a chat channel answers every message.
# The last row starts the normal placement again: what returning after a game costs.
GAME_RESERVE_MIB = 8000
_GAME = {"parallel": 1, "vision": "cpu"}
_W8 = "pool-workers=8"
_EXP2 = ["expert-vram=2", "prefill=2048", _W8]
_EXP0 = ["expert-vram=0", "prefill=2048", _W8]
LEVELS = [
{"key": "normal", "parallel": 2, "vision": "gpu", "sets": []},
{"key": "game_experts_2g", **_GAME, "sets": ["expert-vram=2", "prefill=2048", _W8]},
{"key": "game_experts_1g_kv_q4_16k", **_GAME, "context": 16384, "kv": "q4_0",
"sets": ["expert-vram=1", "prefill=2048", _W8]},
{"key": "game_experts_1g_kv_q4_16k_no_mtp", **_GAME, "context": 16384, "kv": "q4_0", "mtp": "off",
"sets": ["expert-vram=1", "prefill=2048", _W8]},
{"key": "game_experts_0g_kv_q4_16k_no_mtp", **_GAME, "context": 16384, "kv": "q4_0", "mtp": "off",
"sets": ["expert-vram=0", "prefill=2048", _W8]},
{"key": "game_experts_0g_kv_q4_8k_no_mtp", **_GAME, "context": 8192, "kv": "q4_0", "mtp": "off",
"sets": ["expert-vram=0", "prefill=2048", _W8]},
{"key": "normal_again", "parallel": 2, "vision": "gpu", "sets": []},
{"key": "normal", "parallel": 1, "vision": "gpu", "sets": []},
{"key": "game_experts_2g", **_GAME, "sets": _EXP2},
{"key": "game_experts_2g_16k", **_GAME, "context": 16384, "sets": _EXP2},
{"key": "game_experts_0g_16k", **_GAME, "context": 16384, "sets": _EXP0},
{"key": "normal_again", "parallel": 1, "vision": "gpu", "sets": []},
]
# The same with the STT worker loaded first (as the app starts it) and transcribing
# ten speakers at once while the LLM is measured: the VRAM left is then the real
# game share. "stt" is where the STT runs; on the CPU it takes no VRAM but shares
# the cores with the LLM's CPU experts.
TOGETHER = [
{"key": "normal_stt_gpu", "parallel": 1, "vision": "gpu", "sets": [], "stt": "cuda"},
{"key": "normal_parallel2_stt_gpu", "parallel": 2, "vision": "gpu", "sets": [], "stt": "cuda"},
{"key": "game_experts_2g_16k_stt_gpu", **_GAME, "context": 16384, "sets": _EXP2, "stt": "cuda"},
{"key": "game_experts_2g_16k_stt_cpu", **_GAME, "context": 16384, "sets": _EXP2, "stt": "cpu"},
{"key": "game_experts_0g_16k_stt_gpu", **_GAME, "context": 16384, "sets": _EXP0, "stt": "cuda"},
{"key": "game_experts_0g_16k_stt_cpu", **_GAME, "context": 16384, "sets": _EXP0, "stt": "cpu"},
]
# With a real game running: only game placements (the normal one would take the game's VRAM).
LIVE = [lv for lv in TOGETHER if lv["key"].startswith("game_")]
LEVEL_SETS = {"levels": LEVELS, "together": TOGETHER, "live": LIVE}
INSTALL_URL = "https://github.com/Niko1221/Strata/releases/latest/download/install.ps1"
@@ -236,6 +252,60 @@ class Strata:
return scrub(p.stdout[-2000:])
class SttLoad:
"""The STT worker (stt.py mode=load in the stt venv) as a separate process next to the LLM."""
def __init__(self, python: str, work: Path, device: str, log: Path):
d = work / "cache" / f"stt_load_{device}"
shutil.rmtree(d, ignore_errors=True)
d.mkdir(parents=True)
self.out, self.go_file, self.stop_file = d / "result.json", d / "go", d / "stop"
self.log = log
self.cmd = [python, str(Path(__file__).resolve().parent / "stt.py"), "--out", str(self.out),
"--work", str(work), "--opt", "mode=load", "--opt", f"device={device}",
"--opt", f"go={self.go_file}", "--opt", f"stop={self.stop_file}"]
self.proc: subprocess.Popen | None = None
def _read(self) -> dict:
try:
return read_json(self.out)
except (OSError, ValueError):
return {}
def start(self, timeout: float = 900) -> dict:
"""Load the model; returns the worker's result ("loaded", or "failed" with the reason)."""
self._logf = open(self.log, "a", encoding="utf-8")
self.proc = subprocess.Popen(self.cmd, stdout=self._logf, stderr=subprocess.STDOUT)
t0 = time.monotonic()
while time.monotonic() - t0 < timeout:
got = self._read()
if got.get("status") in ("loaded", "failed"):
return got
if self.proc.poll() is not None:
return got or {"status": "failed", "errors": [f"stt worker exited with {self.proc.returncode}"]}
time.sleep(0.5)
return {"status": "failed", "errors": ["stt model did not load in time"]}
def go(self) -> None:
self.go_file.write_text("", encoding="utf-8")
def finish(self, timeout: float = 300) -> dict:
"""Stop the loop; the CPU can be in the middle of a long ten-speaker batch."""
self.stop_file.write_text("", encoding="utf-8")
try:
self.proc.wait(timeout=timeout)
except subprocess.TimeoutExpired:
pass
return self._read()
def close(self) -> None:
if self.proc and self.proc.poll() is None:
self.proc.kill()
self.proc.wait(timeout=30)
if getattr(self, "_logf", None):
self._logf.close()
def port_in_use(port: int) -> bool:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.settimeout(2)
@@ -313,8 +383,11 @@ 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."""
def measure_levels(r: StageResult, s: Strata, preset: dict, context: int, levels: list[dict] = LEVELS,
stt_python: str = "", choose: bool = True) -> None:
"""Start the model in each placement and measure what the switch and the placement cost.
A level with "stt" first loads the STT worker there and keeps it transcribing during the
measurement, so the VRAM left is what a game really gets."""
base = f"http://127.0.0.1:{PORT}/v1"
rows: list[dict] = []
r["levels"] = rows
@@ -327,26 +400,45 @@ def measure_levels(r: StageResult, s: Strata, preset: dict, context: int, levels
s.stop()
idle = gpu_memory_mib()
row["vram_idle_mib"] = idle[0] if idle else None
stt = None
with GpuSampler(interval=1) as g:
row["launch"] = s.launch(preset, row["context"], parallel=lv["parallel"], vision=lv["vision"],
extra_sets=lv["sets"], kv=lv.get("kv"), mtp=lv.get("mtp"), 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))
for err in row["errors"]:
r.error(f"level {lv['key']}", err)
except Exception as e:
r.error(f"level {lv['key']}", e)
else:
r.error(f"level {lv['key']}", "the placement did not start")
now = gpu_memory_mib() if ready else None # the sampler can miss a short run
try:
if lv.get("stt"):
stt = SttLoad(stt_python, s.log.parent.parent, lv["stt"], s.log.with_name("stt_load.log"))
row["stt"] = {"device": lv["stt"], "load": stt.start()}
if row["stt"]["load"].get("status") != "loaded":
r.error(f"level {lv['key']}", "; ".join(row["stt"]["load"].get("errors") or [])
or "the STT did not load")
continue
row["launch"] = s.launch(preset, row["context"], parallel=lv["parallel"], vision=lv["vision"],
extra_sets=lv["sets"], kv=lv.get("kv"), mtp=lv.get("mtp"), 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
if stt:
stt.go()
row.update(quick_bench(c))
for err in row["errors"]:
r.error(f"level {lv['key']}", err)
except Exception as e:
r.error(f"level {lv['key']}", e)
if stt:
busy = stt.finish()
row["stt"].update({k: busy.get(k) for k in ("batch10_s", "single_s", "errors", "seconds")})
for err in busy.get("errors") or []:
r.error(f"level {lv['key']} stt", err)
else:
r.error(f"level {lv['key']}", "the placement did not start")
now = gpu_memory_mib() if ready else None # the sampler can miss a short run
finally:
if stt:
stt.close()
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:
@@ -354,10 +446,12 @@ def measure_levels(r: StageResult, s: Strata, preset: dict, context: int, levels
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, "
say(f" 전환 {row.get('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()
if not choose:
return
r["game_choice"] = pick_game_level(rows)
measured = [x for x in rows if x["key"].startswith("game_") and x.get("vram_free_mib") is not None]
if r["game_choice"] is None and measured:
@@ -366,6 +460,19 @@ def measure_levels(r: StageResult, s: Strata, preset: dict, context: int, levels
f"{most['key']}: {most['vram_free_mib']} MiB")
def ask_for_a_game() -> bool:
"""The live stage needs someone to start a game first. False when nobody is there or they say no."""
if not interactive():
return False
say(" 게임을 켠 상태로 LLM과 음성 인식을 잽니다. 배치 4개를 재고 10~15분 걸립니다.")
if ask(" 지금 게임을 켜고 재시겠습니까?") != "y":
return False
wait_enter(" 게임을 창 모드(테두리 없는 창이면 가장 좋음)로 켜고 플레이 화면까지 들어간 뒤 Enter를 누르고, "
"15초 안에 게임으로 돌아가 주세요. 끝나면 알림음이 울립니다:")
time.sleep(15)
return True
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."""
@@ -385,7 +492,7 @@ def measure_external(r: StageResult, url: str, context: int, only: str = "") ->
if only == "tools":
tools_only(r, c)
return
if only == "levels":
if only in LEVEL_SETS:
r.note("placements need Strata; not measured against an external server")
return
with GpuSampler() as g:
@@ -394,7 +501,8 @@ def measure_external(r: StageResult, url: str, context: int, only: str = "") ->
r["gpu"] = g.summary()
def measure_strata(r: StageResult, work: Path, which: str, context: int, only: str = "") -> None:
def measure_strata(r: StageResult, work: Path, which: str, context: int, only: str = "",
stt_python: str = "") -> None:
preset = PRESETS[which]
r["preset"] = dict(preset, key=which, context=context)
s = Strata(work, work / "logs" / f"strata_{which}.log")
@@ -403,12 +511,27 @@ 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":
if only in LEVEL_SETS:
s.stop()
if port_in_use(PORT):
r.error("port", f"다른 프로그램이 {PORT} 포트를 쓰고 있습니다. 그 프로그램을 끄고 다시 실행해 주세요.")
return
measure_levels(r, s, preset, context)
if only != "levels" and not stt_python:
r.error("stt", "STT 환경을 찾지 못했습니다")
return
if only == "live":
if not ask_for_a_game():
r["skipped"] = "no game started"
return
r.note("measured while the user's game was running")
measure_levels(r, s, preset, context, LEVEL_SETS[only], stt_python=stt_python, choose=only != "live")
if only == "live":
say("\a 게임 중 측정이 끝났습니다. 게임을 꺼도 됩니다.")
try:
import winsound
winsound.MessageBeep()
except Exception:
pass
return
# 1) Start (the first start downloads the model and engine).
@@ -478,15 +601,19 @@ def main() -> int:
which = opts.get("model", "fast")
context = int(opts.get("context", "32768"))
only = opts.get("only", "")
name = {"tools": f"tools_{which}", "levels": "gamemode"}.get(only, f"llm_{which}")
name = {"tools": f"tools_{which}", "levels": "gamemode", "together": "gamemode_stt",
"live": "gamemode_live"}.get(only, f"llm_{which}")
r = StageResult(name, out)
try:
if opts.get("url"):
measure_external(r, opts["url"], context, only)
else:
measure_strata(r, work, which, context, only)
measure_strata(r, work, which, context, only, opts.get("stt_python", ""))
except Exception as e:
r.error("llm", e)
if r.get("skipped"):
r.save("skipped")
return 0
# No server reached means nothing was measured: "failed" so the next run retries it.
if "server" not in r.data:
r.save("failed")

View File

@@ -2,6 +2,11 @@
Runs inside its own venv (faster-whisper, nvidia-cublas-cu12, nvidia-cudnn-cu12).
Audio: the synthetic Korean samples in assets/ko_samples (MeloTTS voice).
With --opt mode=load it is instead the STT load the gamemode stages put next to
the LLM: load the model on device=cuda|cpu, write {"status": "loaded"} to --out,
wait for the file go=PATH, then transcribe ten speakers at once (and one final
clip) on a loop until the file stop=PATH appears, and write the timings.
"""
from __future__ import annotations
@@ -14,7 +19,8 @@ import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from m0lib.common import GpuSampler, StageResult, cer, gpu_memory_mib, say, stage_args, stats # noqa: E402
from m0lib.common import (GpuSampler, StageResult, cer, gpu_memory_mib, say, stage_args, stats, # noqa: E402
write_json)
SR = 16000
ASSETS = Path(__file__).resolve().parent.parent / "assets" / "ko_samples"
@@ -71,8 +77,60 @@ def batch_transcribe(model, audios: list, beam: int = 1) -> tuple[list[str], flo
return texts, time.perf_counter() - t0
def load_loop(batch, single, go: Path, stop: Path, wait_s: float = 3600, max_s: float = 600) -> dict:
"""Wait for ``go``, then run ``batch()`` (ten speakers) and ``single()`` (one final clip)
in turn until ``stop`` appears. An error (out of memory) ends the loop and is kept."""
t0 = time.monotonic()
while not go.exists():
if stop.exists() or time.monotonic() - t0 > wait_s:
return {"status": "not_started", "batch10_s": stats([]), "single_s": stats([]), "errors": []}
time.sleep(0.2)
b, one, errors = [], [], []
t1 = time.monotonic()
while not stop.exists() and time.monotonic() - t1 < max_s:
try:
for fn, into in ((batch, b), (single, one)):
s0 = time.perf_counter()
fn()
into.append(time.perf_counter() - s0)
except Exception as e:
errors.append(f"{type(e).__name__}: {str(e)[:300]}")
break
return {"status": "done", "batch10_s": stats(b), "single_s": stats(one), "errors": errors,
"seconds": round(time.monotonic() - t1, 1)}
def load_worker(out: Path, work: Path, opts: dict) -> int:
device = opts.get("device", "cuda")
ctype = opts.get("compute", "int8_float16" if device == "cuda" else "int8")
threads = int(opts.get("threads", "8"))
res: dict = {"device": device, "compute_type": ctype, "cpu_threads": threads if device == "cpu" else None}
try:
if device == "cuda":
add_cuda_dll_dirs()
from faster_whisper import WhisperModel
refs = json.loads((ASSETS / "refs.json").read_text(encoding="utf-8"))["samples"]
clips = [read_wav(ASSETS / refs[i % len(refs)]["file"]) for i in range(10)]
t0 = time.perf_counter()
model = WhisperModel(opts.get("model", "large-v3-turbo"), device=device, compute_type=ctype,
cpu_threads=threads if device == "cpu" else 0,
download_root=str(work / "models" / "stt"))
transcribe(model, clips[0], 1) # warm-up
res["load_s"] = round(time.perf_counter() - t0, 2)
except Exception as e:
write_json(out, dict(res, status="failed", errors=[f"load: {type(e).__name__}: {str(e)[:300]}"]))
return 0
write_json(out, dict(res, status="loaded"))
res.update(load_loop(lambda: batch_transcribe(model, clips), lambda: transcribe(model, clips[0], 1),
Path(opts["go"]), Path(opts["stop"])))
write_json(out, res)
return 0
def main() -> int:
out, work, opts = stage_args()
if opts.get("mode") == "load":
return load_worker(out, work, opts)
r = StageResult("stt", out)
r["cuda_dll_dirs"] = len(add_cuda_dll_dirs())
os.environ.setdefault("HF_HOME", str(work / "models" / "hf"))