feat(m0): measure the 1 GB room for other programs and a 95 % GPU cap

User decision (2026-11-10, room to watch a video next to Jarvis): the
normal placement leaves 1 GB of VRAM for programs opened later, and
Jarvis's GPU work is capped at 95 %.

- gamemode_tune's normal rows take OTHER_ROOM_MIB off the expert budget.
- gpucap.DutyCap pauses the Strata engine (strata.exe --serve under the
  kit) and the STT worker with their children together for 10 ms of
  every 200 ms (NtSuspendProcess), and always resumes them.
- Every row samples nvidia-smi utilization.gpu; capped rows have an
  uncapped twin (normal with and without the STT, game 2 GB with 2 s
  partials) so the run shows the cost and what the GPU really gets back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-10 23:52:57 +09:00
parent 3f0ed4343b
commit 0e50c558d1
5 changed files with 400 additions and 25 deletions

View File

@@ -16,7 +16,7 @@ import pytest
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts" / "m0"))
from m0lib import common, llm, llm_bench # noqa: E402
from m0lib import common, gpucap, llm, llm_bench # noqa: E402
from m0lib.llm_client import ChatClient # noqa: E402
pytestmark = pytest.mark.unit
@@ -455,7 +455,7 @@ def test_a_lying_model_fails_the_stage_and_the_next_model_is_measured(tmp_path):
def _run_levels_stage(tmp_path, monkeypatch, fake_server, gpu, ready=lambda sets: True, only="levels",
extra_opts=(), stt=None):
extra_opts=(), stt=None, procs=None, paused=None):
"""Run the stage with Strata replaced; ``gpu(running)`` is nvidia-smi's (used, total), where
``running`` is the started placement ({"sets", "context", "kv", "mtp"}) or None. ``stt`` is a
_FakeStt whose loaded model adds to the used VRAM."""
@@ -492,6 +492,16 @@ def _run_levels_stage(tmp_path, monkeypatch, fake_server, gpu, ready=lambda sets
monkeypatch.setattr(llm, "port_in_use", lambda p: running["now"] is not None)
monkeypatch.setattr(llm, "gpu_memory_mib", lambda: gpu(running["now"]))
monkeypatch.setattr(common, "gpu_memory_mib", lambda: gpu(running["now"]))
monkeypatch.setattr(gpucap, "gpu_util_pct", lambda: 99)
# The kit's own engine and STT worker; the GPU cap "pauses" them by recording it.
procs = _procs(tmp_path / "strata") if procs is None else procs
monkeypatch.setattr(gpucap, "process_table", lambda: list(procs))
held = set()
paused = set() if paused is None else paused
monkeypatch.setattr(gpucap, "suspend_pid", lambda pid: held.add(pid) or paused.add(pid) or True)
monkeypatch.setattr(gpucap, "resume_pid", lambda pid: held.discard(pid) or True)
monkeypatch.setattr(gpucap, "PERIOD_S", 0.002)
running["held"] = held
out = tmp_path / "results" / "gamemode.json"
out.parent.mkdir(parents=True, exist_ok=True)
opts = ["--opt", "model=fast", "--opt", f"only={only}"]
@@ -659,6 +669,7 @@ def test_normal_placement_answers_one_request_at_a_time(tmp_path, monkeypatch, f
STT_MODEL_MIB = 1300 # M0 stt: the loaded model
STT_GROWTH_MIB = 1440 # M0 stt: what ten speakers at once add over the loaded model
STT_GPU_MIB = STT_MODEL_MIB + STT_GROWTH_MIB
STT_LAUNCHER_PID = 4100 # the venv python.exe; the real interpreter is its child
class _FakeStt:
@@ -687,6 +698,8 @@ class _FakeStt:
fake.paces.append(pace)
class _One:
pid = STT_LAUNCHER_PID
def start(self, timeout=900):
if fake.broken_at_load:
return {"status": "failed", "errors": ["load: RuntimeError: CUDA failed"]}
@@ -977,12 +990,17 @@ def test_tune_stage_leaves_the_stt_room_in_the_normal_placement(tmp_path, monkey
rows = {x["key"]: x for x in r["levels"]}
budgets = {_expert_vram(x) for x in started[1:] if x["vision"] == normal[0]["vision"]}
assert len(budgets) == 1 and budgets.pop() > 0
# With the STT at its ten-speaker peak the card keeps the margin free, and not much more.
continuous = [rows[lv["key"]] for lv in normal if lv.get("stt_pace") is None]
# With the STT at its ten-speaker peak the card keeps the margin and the room for other
# programs free, and not much more.
continuous = [rows[lv["key"]] for lv in normal if lv.get("stt") and lv.get("stt_pace") is None]
assert continuous
keep = llm.STT_ROOM_MARGIN_MIB + llm.OTHER_ROOM_MIB
for row in continuous:
assert llm.STT_ROOM_MARGIN_MIB <= row["vram_free_mib"] < llm.STT_ROOM_MARGIN_MIB + 2 * 103
assert keep <= row["vram_free_mib"] < keep + 2 * 103
assert row["stt_room"]["stt_growth_mib"] == llm.STT_GROWTH_FALLBACK_MIB
assert row["stt_room"]["other_room_mib"] == llm.OTHER_ROOM_MIB
# The same placement is also measured without the STT, so the cap's cost on the LLM alone shows.
assert any(not lv.get("stt") for lv in normal) and any(lv.get("stt") for lv in normal)
# Without a game the STT keeps every partial while the LLM answers (user decision); only the
# 2 GB game placement is measured back to back, with fewer partials and with finals only.
assert all(lv.get("stt_pace") is None for lv in normal)
@@ -990,7 +1008,13 @@ def test_tune_stage_leaves_the_stt_room_in_the_normal_placement(tmp_path, monkey
assert game and all("expert-vram=2" in lv["sets"] for lv in game)
paces = {(lv.get("stt_pace") or {}).get("partial_every", "continuous") for lv in game}
assert paces == {"continuous", 2.0, None}
assert stt.paces == [lv.get("stt_pace") for lv in llm.TUNED]
assert stt.paces == [lv.get("stt_pace") for lv in llm.TUNED if lv.get("stt")]
# Each capped row has its uncapped twin in the same run.
capped = [lv for lv in llm.TUNED if lv.get("gpu_cap")]
assert capped and all(lv["gpu_cap"] == llm.GPU_CAP for lv in capped)
for lv in capped:
twin = {k: v for k, v in lv.items() if k not in ("key", "gpu_cap")}
assert any({k: v for k, v in x.items() if k != "key"} == twin for x in llm.TUNED)
assert stt.loaded is None and running["now"] is None
@@ -1022,3 +1046,108 @@ def test_tune_stage_runs_with_the_stt_python_and_has_a_one_click_runner(tmp_path
assert "gamemode_tune" in m0.NEEDS_STT and "gamemode_tune" not in m0.ON_DEMAND
bat = (Path(m0.KIT) / "run_m0_gamemode_tune.bat").read_text(encoding="utf-8")
assert "-Only gamemode_tune" in bat and "-Redo" in bat
# --- the GPU cap: Jarvis's engine and STT worker paused together for 5 % of the time --------
def _procs(home):
eng = str(home / "components" / "engine" / "0.1.59-windows-x86_64-cuda-cuda13" / "strata.exe")
term = str(home / "terminal" / "current" / "bin" / "strata.exe")
return [
{"pid": 10, "ppid": 1, "exe": term, "cmd": f"{term} launch --yes"},
{"pid": 20, "ppid": 10, "exe": eng, "cmd": f"{eng} --serve --pack x"},
{"pid": 21, "ppid": 20, "exe": "C:\\x\\helper.exe", "cmd": "helper"},
{"pid": 30, "ppid": 1, "exe": eng.replace(str(home), str(home.parent / "other")), "cmd": "strata.exe --serve"},
{"pid": STT_LAUNCHER_PID, "ppid": 1, "exe": "C:\\venv\\python.exe", "cmd": "python stt.py"},
{"pid": STT_LAUNCHER_PID + 1, "ppid": STT_LAUNCHER_PID, "exe": "C:\\py\\python.exe", "cmd": "python stt.py"},
{"pid": 50, "ppid": 1, "exe": "C:\\chrome.exe", "cmd": "chrome"},
]
def test_process_table_lines_are_parsed_with_tabs_in_command_lines():
rows = gpucap.parse_process_table("20\t10\tC:\\e\\strata.exe\tstrata.exe --serve\ta\r\n\nbad line\n4\t\t\t\n")
assert rows[0] == {"pid": 20, "ppid": 10, "exe": "C:\\e\\strata.exe", "cmd": "strata.exe --serve\ta"}
assert rows[1]["pid"] == 4 and rows[1]["ppid"] is None and len(rows) == 2
def test_cap_pauses_the_serving_engine_and_the_stt_worker_with_their_children(tmp_path):
procs = _procs(tmp_path / "strata")
roots = gpucap.engine_roots(procs, tmp_path / "strata")
assert roots == [20] # not the terminal that started it, nor another kit's engine
assert sorted(gpucap.with_children(procs, roots + [STT_LAUNCHER_PID])) == \
[20, 21, STT_LAUNCHER_PID, STT_LAUNCHER_PID + 1]
def test_duty_cap_pauses_for_the_capped_share_and_leaves_nothing_paused():
import time as _time
held, log = set(), []
def suspend(pid):
held.add(pid)
log.append(("s", pid))
return True
def resume(pid):
held.discard(pid)
log.append(("r", pid))
return True
with gpucap.DutyCap([1, 2], 0.9, period=0.05, suspend=suspend, resume=resume) as d:
_time.sleep(0.6)
s = d.summary()
assert not held
assert s["cycles"] >= 5 and s["failed_processes"] == 0
assert 0.05 <= s["paused_share"] <= 0.2 # about 10 % of the time
# Both processes are paused together: each pause holds both before either is resumed.
for i in range(0, len(log), 4):
assert sorted(log[i:i + 4]) == [("r", 1), ("r", 2), ("s", 1), ("s", 2)]
assert {k for k, _ in log[i:i + 2]} == {"s"}
def test_no_cap_pauses_nothing():
calls = []
with gpucap.DutyCap([1], 1.0, period=0.01, suspend=calls.append, resume=calls.append) as d:
import time as _time
_time.sleep(0.05)
assert calls == [] and d.summary()["cycles"] == 0
def test_util_sampler_counts_samples_over_the_cap():
vals = iter([99, 90, 97, 80])
with gpucap.UtilSampler(interval=0.01, read=lambda: next(vals, None)) as u:
import time as _time
_time.sleep(0.1)
s = u.summary(0.95)
assert s["pct"]["n"] == 4 and s["over_cap_share"] == 0.5
def _tune_with_cap(tmp_path, monkeypatch, fake_server, procs):
paused = set()
r, _, running = _run_levels_stage(tmp_path, monkeypatch, fake_server, _vram, only="tune",
extra_opts=["stt_python=py"], stt=_FakeStt(), procs=procs, paused=paused)
return r, running["held"], paused
def test_capped_rows_pause_jarvis_and_record_what_the_gpu_got(tmp_path, monkeypatch, fake_server):
home = tmp_path / "strata"
r, held, paused = _tune_with_cap(tmp_path, monkeypatch, fake_server, _procs(home))
assert r["status"] == "ok"
assert not held # nothing is left paused
assert paused == {20, 21, STT_LAUNCHER_PID, STT_LAUNCHER_PID + 1}
rows = {x["key"]: x for x in r["levels"]}
for lv in llm.TUNED:
row = rows[lv["key"]]
assert row["gpu_util"]["pct"]["n"] > 0 # every row records the GPU's use
if lv.get("gpu_cap"):
assert row["gpu_cap"]["cap"] == llm.GPU_CAP and row["gpu_cap"]["cycles"] > 0
assert row["gpu_util"]["over_cap_share"] == 1.0 # the fake GPU stays at 99 %
else:
assert "gpu_cap" not in row
def test_cap_without_the_engine_process_is_an_error_not_a_quiet_uncapped_row(tmp_path, monkeypatch,
fake_server):
r, _, paused = _tune_with_cap(tmp_path, monkeypatch, fake_server, [])
assert r["status"] == "partial" and not paused
assert any("no engine process" in e["error"] for e in r["errors"])