fix(m0): measure smaller game placements and read only the latest engine start

The first game PC run showed that a 2 GB expert budget still left a 16 GB
card only 4.3 GB free: the weights, the 32K int8 conversation memory, the
MTP drafter and buffers take about 8.7 GB on their own. The game placements
now also shrink the memory format (q4_0), the context (16K, 8K) and the
drafter, with half the CPU workers (no speed cost measured). The engine log
is appended across starts, so each placement now reads only its own lines;
when no placement leaves the reserve the result names the most free one.
The gamemode runner skips the desktop stage, which is already measured.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-10 18:23:28 +09:00
parent 8dfab3ab6e
commit 165142be9a
5 changed files with 161 additions and 47 deletions

View File

@@ -26,7 +26,7 @@
| 단계 | 언제 | LLM 배치 (다시 시작 필요) | 다시 시작 없이 바꾸는 것 |
|---|---|---|---|
| 평소 | 게임이 없고 VRAM이 넉넉함 | 전문가 층을 VRAM에 들어가는 만큼 올림(Strata 자동 배치), 동시 요청 2개, 이미지는 GPU로 읽기 | 화면 캡처 미리 준비(말하는 중), 화질 보통, 지난 대화 약 8천 토큰 |
| 게임 중 | 게임을 감지했거나, 다른 프로그램이 VRAM을 써서 남은 VRAM이 "게임용으로 비울 VRAM"보다 적음 | 전문가 층의 VRAM 몫(`--expert-vram`)을 줄여 "게임용으로 비울 VRAM"(기본 8GB)을 비움. 나머지 전문가 층은 RAM에서 CPU로 계산. 동시 요청 1개, 이미지는 CPU로 읽기. CPU 작업자 수를 줄일지는 M0 `gamemode` 결과로 정함 | 캡처 미리 준비 끔, 화질 빠름(긴 변 768px), 지난 대화 약 4천 토큰 |
| 게임 중 | 게임을 감지했거나, 다른 프로그램이 VRAM을 써서 남은 VRAM이 "게임용으로 비울 VRAM"보다 적음 | 전문가 층의 VRAM 몫(`--expert-vram`)을 줄여 "게임용으로 비울 VRAM"(기본 8GB)을 비움. 나머지 전문가 층은 RAM에서 CPU로 계산. 동시 요청 1개, 이미지는 CPU로 읽기, 엔진 CPU 작업자는 절반(16코어 PC에서 8개). 전문가 층만으로 모자라면 대화 메모리 형식(`--kv q4_0`), 맥락 길이, MTP 보조 층도 줄임(아래 측정 결과) | 캡처 미리 준비 끔, 화질 빠름(긴 변 768px), 지난 대화 약 4천 토큰 |
| 일시정지 | 사용자가 켠 경우(기본 꺼짐), 또는 이 PC에서 최소 배치로도 게임 몫을 비울 수 없을 때 | LLM을 멈춤 | 게임 중에는 대답하지 않음 |
### PC마다 값을 계산
@@ -38,12 +38,28 @@
### 전환 규칙
- **게임 시작**: 지금 하던 답이 끝나면 바로 게임 중 배치로 다시 시작합니다. 다시 시작하는 동안(이전 측정 약 52초, 배치별 시간은 M0 `gamemode`에서 잼) 들어온 요청은 대기열에 두고, 한 번만 "잠깐만요, 게임 모드로 바꾸는 중이에요"라고 말한 뒤 준비되면 답합니다.
- **게임 시작**: 지금 하던 답이 끝나면 바로 게임 중 배치로 다시 시작합니다. 다시 시작하는 동안(게임PC 측정 31~36초, 컴퓨터를 켠 뒤 첫 시작은 47초) 들어온 요청은 대기열에 두고, 한 번만 "잠깐만요, 게임 모드로 바꾸는 중이에요"라고 말한 뒤 준비되면 답합니다.
- **되돌리기**: 게임이 끝나고 30초 뒤(설정에서 조절), VRAM 부족은 해소된 상태가 60초 이어진 뒤 평소 배치로 돌아갑니다. 게임을 껐다 바로 다시 켤 때 모델을 반복해서 옮기지 않기 위해서입니다.
- **표시**: 대시보드에 "성능 단계: 게임 중 (발로란트 감지)", 전환 중에는 "모델 배치 바꾸는 중"을 표시합니다.
- **설정**: GUI에서 바꾸는 것은 게임 감지 켜기/끄기, 게임용으로 비울 VRAM, 되돌리기 대기 시간, 게임 중 일시정지 켜기/끄기뿐입니다.
- **엔진이 실행 중 VRAM 줄이기를 지원하면**: Strata 0.1.59의 qwen36 엔진은 실행 중 VRAM 줄이기(`POST /v1/vram`)를 지원하지 않아 다시 시작합니다. 지원하는 버전이 나오면 다시 시작 없이 바로 줄이는 방식으로 바꾸고 다시 잽니다.
### 측정 결과 (M0 `gamemode`, 2026-11-10, RTX 5070 Ti 16GB, Ryzen 9 9950X3D)
| 배치 | 출력 tok/s | 음성 첫 문장 | 맥락 4.8천 토큰 첫 토큰 | 모델 VRAM | 게임에 남는 VRAM |
|---|---|---|---|---|---|
| 평소(동시 2개, 이미지 GPU) | 69.6 / 다시 켠 뒤 75.8 | 0.52초 / 0.47초 | 1.1초 | 13.6GB | 1.1GB |
| 전문가 6GB | 97.1 | 0.39초 | 1.4초 | 14.3GB | 0.4GB |
| 전문가 4GB | 90.0 | 0.40초 | 1.1초 | 12.8GB | 2.3GB |
| 전문가 2GB | 73.8 | 0.48초 | 1.1초 | 10.8GB | 4.3GB |
| 전문가 2GB, CPU 작업자 8개 | 75.8 | 0.51초 | 1.1초 | 10.8GB | 4.3GB |
- 전문가 층 VRAM 몫을 2GB까지 줄여도 게임에 8GB를 남기지 못했습니다. 전문가 층 말고도 카드에 남는 몫이 약 8.7GB입니다: 늘 카드에 있는 가중치 4.4GiB, 32K 대화 메모리(int8) 1.43GiB, 긴 프롬프트용 버퍼 1.1GiB, MTP 보조 층(약 1GB), 그 밖의 버퍼.
- 그래서 게임 중 배치는 전문가 층과 함께 대화 메모리 형식(q4_0, 절반), 맥락(16K 또는 8K), MTP 보조 층(끄면 약 1GB)도 줄이는 후보로 다시 잽니다. 게임 중에는 지난 대화를 약 4천 토큰만 쓰므로 맥락 8K로도 충분합니다.
- CPU 작업자를 16개에서 8개로 줄여도 출력 속도가 줄지 않았습니다(73.8 대 75.8 tok/s). 게임 중에는 8개로 둡니다.
- 전문가 층을 줄이는 비용은 작습니다. 2GB에서도 출력 73.8 tok/s, 음성 첫 문장 0.48초로 기준(30 tok/s, 0.7초)보다 훨씬 빠릅니다. 다만 게임이 GPU를 함께 쓸 때 속도는 아직 재지 않았습니다.
- 평소 배치(동시 요청 2개)는 Strata가 "16GB 카드에는 1개가 맞음"이라고 경고하고, 전문가 층을 덜 올려서 동시 1개 배치(전문가 6GB)보다 출력이 느렸습니다(69.6 대 97.1 tok/s). 16GB 카드에서 평소 동시 요청 수를 1개로 바꿀지는 따로 정합니다.
## 화면 보기: 전체 화면, 모니터별, 프로그램(창)별
- Windows Graphics Capture API로 다음을 볼 수 있습니다.

View File

@@ -64,6 +64,6 @@ LLM 단계는 8080 포트를 씁니다. 다른 프로그램이 이 포트를 쓰
`run_m0_desktop.bat`을 더블클릭하면 PC 제어 도구 단계(`desktop`)만 돕니다. agent-desktop(약 2MB)을 작업 폴더에 받아 쓰고, 1~2분이면 끝납니다. 계산기와 테스트용 브라우저 창이 잠깐 떴다가 닫히니 그동안 손대지 않으시면 됩니다. 입력칸이 값 넣기를 지원하지 않으면 키 입력으로 넣는데, 이때는 그 창이 잠깐 앞으로 나옵니다.
`run_m0_gamemode.bat`을 더블클릭하면 PC 제어 도구 단계(`desktop`)를 다시 재고, 이어서 게임 중 자동 조절 단계(`gamemode`)를 돕니다. 모델은 이미 받아 둔 것을 쓰므로 새로 받지 않고, 10~15분 걸립니다. 그동안 게임이나 무거운 프로그램은 꺼 두시고 PC에 손대지 않으시면 됩니다.
`run_m0_gamemode.bat`을 더블클릭하면 게임 중 자동 조절 단계(`gamemode`)만 돕니다. 같은 모델을 배치 7개(평소, 게임 중 후보 5개, 다시 평소)로 차례로 다시 켜서 잽니다. 게임 중 후보는 전문가 층 VRAM 몫(2GB, 1GB, 0GB)과 함께 대화 메모리 형식(q4_0), 맥락(16K, 8K), MTP 보조 층을 줄입니다. 모델은 이미 받아 둔 것을 쓰므로 새로 받지 않고, 10분 안팎 걸립니다. 그동안 게임이나 무거운 프로그램은 꺼 두시고 PC에 손대지 않으시면 됩니다.
다 끝나고 필요 없으면 작업 폴더(`\JarvisM0`)를 통째로 지우면 됩니다. Python, 모델, Strata(엔진과 설정 포함)는 모두 그 안에 설치하도록 지정해 두었습니다.

View File

@@ -57,17 +57,28 @@ PORT = 8080
# 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.
# 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 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"
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": "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": []},
]
INSTALL_URL = "https://github.com/Niko1221/Strata/releases/latest/download/install.ps1"
@@ -118,13 +129,17 @@ class Strata:
return self._flags
def launch_args(self, preset: dict, context: int, parallel: int, vision: str, extra_sets: list[str],
restart: bool) -> tuple[list[str], list[str]]:
restart: bool, kv: str | None = None, mtp: str | None = None) -> tuple[list[str], list[str]]:
want = [("--family", preset["family"]), ("--model", preset["model"]), ("--data-dir", str(self.models)),
("--context", str(context)), ("--vision", vision), ("--parallel", str(parallel)),
("--access", "local"), ("--port", str(PORT)), ("--no-api-key", None), ("--yes", None),
("--no-tui", None)]
if preset.get("drafting"):
want.append(("--drafting", preset["drafting"]))
if kv:
want.append(("--kv", kv))
if mtp:
want.append(("--mtp", mtp))
if restart:
want.append(("--restart", None))
for s in extra_sets:
@@ -151,8 +166,9 @@ class Strata:
return {"exit": p.returncode, "text": scrub(p.stdout[-3000:] + p.stderr[-2000:])}
def launch(self, preset: dict, context: int, parallel: int, vision: str = "on",
extra_sets: list[str] | None = None, restart: bool = False, timeout: float = 4 * 3600) -> dict:
args, dropped = self.launch_args(preset, context, parallel, vision, extra_sets or [], restart)
extra_sets: list[str] | None = None, restart: bool = False, timeout: float = 4 * 3600,
kv: str | None = None, mtp: str | None = None) -> dict:
args, dropped = self.launch_args(preset, context, parallel, vision, extra_sets or [], restart, kv, mtp)
last = [0.0]
def progress(line: str) -> bool:
@@ -163,6 +179,7 @@ class Strata:
last[0] = time.monotonic()
return True
self.mark_engine_logs()
t0 = time.perf_counter()
rc = run_logged(self.cmd("launch", *args), self.log, timeout=timeout, env=self.env, echo=True,
echo_filter=progress)
@@ -187,12 +204,23 @@ 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 mark_engine_logs(self) -> None:
"""Remember how long each engine log is, so engine_lines() reads only what the next start writes."""
self._log_marks = {p: p.stat().st_size for p in self.home.rglob("*.engine.log")}
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."""
"""The placement lines (how much went to VRAM and RAM) the newest engine log got since the
last start, scrubbed. The log is appended across starts; one written again is read whole."""
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:]
src = found[-1]
start = getattr(self, "_log_marks", {}).get(src, 0)
if src.stat().st_size < start:
start = 0
with open(src, "rb") as f:
f.seek(start)
text = f.read()[-400_000:].decode("utf-8", errors="replace")
return [scrub(x.strip())[:400] for x in text.splitlines() if x.lstrip().startswith(prefix)][:limit]
def stop(self) -> None:
@@ -291,7 +319,8 @@ def measure_levels(r: StageResult, s: Strata, preset: dict, context: int, levels
rows: list[dict] = []
r["levels"] = rows
for lv in levels:
row: dict = {"key": lv["key"], "parallel": lv["parallel"], "vision": lv["vision"], "sets": lv["sets"]}
row: dict = {"key": lv["key"], "parallel": lv["parallel"], "vision": lv["vision"], "sets": lv["sets"],
"context": lv.get("context", context), "kv": lv.get("kv"), "mtp": lv.get("mtp")}
rows.append(row)
say(f" - 배치 {lv['key']}: 다시 시작해서 재는 중")
t0 = time.perf_counter()
@@ -299,8 +328,8 @@ def measure_levels(r: StageResult, s: Strata, preset: dict, context: int, levels
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)
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()
@@ -330,6 +359,11 @@ def measure_levels(r: StageResult, s: Strata, preset: dict, context: int, levels
r.save()
s.stop()
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:
most = max(measured, key=lambda x: x["vram_free_mib"])
r.note(f"no game placement leaves {GAME_RESERVE_MIB} MiB free; the most free is "
f"{most['key']}: {most['vram_free_mib']} MiB")
def pick_game_level(rows: list[dict], reserve_mib: int = GAME_RESERVE_MIB) -> dict | None:

View File

@@ -1,5 +1,5 @@
@echo off
chcp 65001 >nul
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0run_m0.ps1" -Only desktop,gamemode -Redo %*
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0run_m0.ps1" -Only gamemode -Redo %*
echo.
pause

View File

@@ -455,28 +455,31 @@ 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):
"""Run the stage with Strata replaced; ``gpu(launched_sets)`` is nvidia-smi's (used, total)."""
"""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."""
port = int(fake_server.rsplit(":", 1)[1].split("/")[0])
monkeypatch.setattr(llm, "PORT", port)
started = []
running = {"sets": None}
running = {"now": None}
def launch(self, preset, context, parallel, vision="on", extra_sets=None, restart=False, timeout=0):
started.append({"parallel": parallel, "vision": vision, "sets": list(extra_sets or [])})
ok = ready(extra_sets or [])
running["sets"] = list(extra_sets or []) if ok else None
return {"ready": ok}
def launch(self, preset, context, parallel, vision="on", extra_sets=None, restart=False, timeout=0,
kv=None, mtp=None):
spec = {"parallel": parallel, "vision": vision, "sets": list(extra_sets or []), "context": context,
"kv": kv, "mtp": mtp}
started.append(spec)
running["now"] = spec if ready(extra_sets or []) else None
return {"ready": running["now"] is not None}
def stop(self):
running["sets"] = None
running["now"] = None
monkeypatch.setattr(llm.Strata, "install", lambda self: True)
monkeypatch.setattr(llm.Strata, "plan", lambda self, preset, context: {})
monkeypatch.setattr(llm.Strata, "launch", launch)
monkeypatch.setattr(llm.Strata, "stop", stop)
monkeypatch.setattr(llm, "port_in_use", lambda p: running["sets"] is not None)
monkeypatch.setattr(llm, "gpu_memory_mib", lambda: gpu(running["sets"]))
monkeypatch.setattr(common, "gpu_memory_mib", lambda: gpu(running["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"]))
out = tmp_path / "results" / "gamemode.json"
out.parent.mkdir(parents=True)
monkeypatch.setattr(sys, "argv", ["llm.py", "--out", str(out), "--work", str(tmp_path),
@@ -485,37 +488,97 @@ def _run_levels_stage(tmp_path, monkeypatch, fake_server, gpu, ready=lambda sets
return json.loads(out.read_text(encoding="utf-8")), started, running
def _vram(sets):
"""16 GB card, 2 GB used by Windows; the model takes less with a smaller expert budget."""
if sets is None:
return 2000, 16303
experts = next((int(s.split("=")[1]) for s in sets if s.startswith("expert-vram=")), None)
return (2000 + (13400 if experts is None else 1500 + experts * 1024)), 16303
def _model_mib(spec):
"""Roughly what the 2026-11-10 game PC showed: 4.4 GiB of weights that never leave the card, the
expert budget, the conversation memory (int8, 1.43 GiB per 32K; q4_0 half), about 1 GB for the
MTP drafter and 1.5 GB of buffers. With no expert budget Strata fills the card."""
experts = next((int(s.split("=")[1]) for s in spec["sets"] if s.startswith("expert-vram=")), None)
if experts is None:
return 13400
kv = 1464 * spec["context"] / 32768 * (0.5 if spec["kv"] == "q4_0" else 1)
return int(4506 + experts * 1024 + kv + (0 if spec["mtp"] == "off" else 1000) + 1500)
def _vram(running):
"""16 GB card, 2 GB used by Windows."""
return (2000 if running is None else 2000 + _model_mib(running)), 16303
def _vram_big_floor(running):
"""A card where even the smallest placement leaves the game less than its reserve."""
return (2000 if running is None else 2000 + _model_mib(running) + 3000), 16303
def test_gamemode_measures_every_placement_and_returns_to_normal(tmp_path, monkeypatch, fake_server):
r, started, running = _run_levels_stage(tmp_path, monkeypatch, fake_server, _vram)
assert r["stage"] == "gamemode" and r["status"] == "ok"
assert [x["sets"] for x in started] == [lv["sets"] for lv in llm.LEVELS]
# Each placement starts with its own context, conversation memory format and drafter.
for spec, lv in zip(started, llm.LEVELS):
assert spec["context"] == lv.get("context", 32768)
assert (spec["kv"], spec["mtp"]) == (lv.get("kv"), lv.get("mtp"))
assert started[-1] == started[0] # the last start is the normal placement again
for lv in llm.LEVELS:
row = next(x for x in r["levels"] if x["key"] == lv["key"])
assert row["switch_s"] is not None
assert row["voice_first_sentence"]["n"] > 0
rows = {x["key"]: x for x in r["levels"]}
assert rows["game_experts_2g"]["vram_free_mib"] > rows["game_experts_6g"]["vram_free_mib"] > rows["normal"]["vram_free_mib"]
assert running["sets"] is None # the model is not left running after the stage
for lv in llm.LEVELS:
assert rows[lv["key"]]["switch_s"] is not None
assert rows[lv["key"]]["voice_first_sentence"]["n"] > 0
# The game placements go below the 2 GB expert budget that still left a 16 GB card only 4 GB.
game = [rows[lv["key"]] for lv in llm.LEVELS if lv["key"].startswith("game_")]
assert max(x["vram_free_mib"] for x in game) > min(x["vram_free_mib"] for x in game)
assert min(x["vram_free_mib"] for x in game) > rows["normal"]["vram_free_mib"]
# On this card a smaller placement does leave the reserve, and the choice is one that does.
assert r["game_choice"]["vram_free_mib"] >= llm.GAME_RESERVE_MIB
assert running["now"] is None # the model is not left running after the stage
def test_when_no_placement_leaves_the_reserve_the_result_says_how_much_is_free(tmp_path, monkeypatch,
fake_server):
r, _, _ = _run_levels_stage(tmp_path, monkeypatch, fake_server, _vram_big_floor)
assert r["game_choice"] is None
assert r["status"] == "ok" # every placement was measured; it is the card that is too small
most = max(x["vram_free_mib"] for x in r["levels"] if x["key"].startswith("game_"))
assert any(str(most) in n for n in r["notes"])
def test_engine_lines_are_only_those_of_the_latest_start(tmp_path):
# The engine log is appended across starts: reading it from the top repeated an old start's
# placement lines for every placement.
s = llm.Strata(tmp_path, tmp_path / "strata.log")
log = tmp_path / "strata" / "localappdata" / "Strata" / "launch" / "ud-q4_k_xl-32k.engine.log"
log.parent.mkdir(parents=True)
log.write_text("strata-q36: hybrid experts: 59 of 256 per layer in VRAM (4.32 GiB)\n", encoding="utf-8")
s.mark_engine_logs()
with open(log, "a", encoding="utf-8") as f:
f.write("strata-q36: hybrid experts: 14 of 256 per layer in VRAM (1.02 GiB)\n")
assert s.engine_lines() == ["strata-q36: hybrid experts: 14 of 256 per layer in VRAM (1.02 GiB)"]
# A log written again from the start (shorter than the mark) is read whole.
log.write_text("strata-q36: context 8192 cells\n", encoding="utf-8")
assert s.engine_lines() == ["strata-q36: context 8192 cells"]
def test_placement_memory_format_and_drafter_reach_the_launch_command(tmp_path, monkeypatch):
ran = []
monkeypatch.setattr(llm, "run_logged", lambda cmd, *a, **k: ran.append(cmd) or 1)
s = llm.Strata(tmp_path, tmp_path / "strata.log")
monkeypatch.setattr(s, "supported_flags", lambda: {"--family", "--model", "--context", "--kv", "--mtp"})
s.launch(llm.PRESETS["fast"], 8192, parallel=1, kv="q4_0", mtp="off")
s.launch(llm.PRESETS["fast"], 32768, parallel=1)
with_opts, plain = ran
assert with_opts[with_opts.index("--kv") + 1] == "q4_0" and with_opts[with_opts.index("--mtp") + 1] == "off"
assert with_opts[with_opts.index("--context") + 1] == "8192"
assert "--kv" not in plain and "--mtp" not in plain
def test_a_placement_that_does_not_start_is_recorded_and_the_rest_still_run(tmp_path, monkeypatch, fake_server):
r, started, _ = _run_levels_stage(tmp_path, monkeypatch, fake_server, _vram,
ready=lambda sets: "expert-vram=4" not in sets)
ready=lambda sets: "expert-vram=1" not in sets)
assert len(started) == len(llm.LEVELS)
row = next(x for x in r["levels"] if x["key"] == "game_experts_4g")
failed = [lv["key"] for lv in llm.LEVELS if "expert-vram=1" in lv["sets"]]
row = next(x for x in r["levels"] if x["key"] == failed[0])
assert row["switch_s"] is None and "decode_tok_s" not in row
# A placement that never started is a gap in the measurement, not a pass.
assert r["status"] == "partial"
assert any("game_experts_4g" in e["where"] for e in r["errors"])
assert any(failed[0] in e["where"] for e in r["errors"])
def test_only_the_normal_placement_starting_is_not_ok(tmp_path, monkeypatch, fake_server):
@@ -523,7 +586,8 @@ def test_only_the_normal_placement_starting_is_not_ok(tmp_path, monkeypatch, fak
ready=lambda sets: not any(s.startswith("expert-vram=") for s in sets))
assert r["game_choice"] is None
assert r["status"] == "partial"
assert sum(1 for e in r["errors"] if e["where"].startswith("level game_")) == 4
game = [lv for lv in llm.LEVELS if lv["key"].startswith("game_")]
assert sum(1 for e in r["errors"] if e["where"].startswith("level game_")) == len(game)
def _row(key, free, tok_s):
@@ -542,12 +606,12 @@ def test_no_game_choice_when_no_placement_leaves_the_reserve():
assert llm.pick_game_level(rows, reserve_mib=8000) is None
def test_kit_has_a_one_click_runner_for_desktop_and_gamemode():
def test_kit_has_a_one_click_runner_for_gamemode():
import m0
keys = [s[0] for s in m0.STAGES]
assert "gamemode" in keys
bat = (Path(m0.KIT) / "run_m0_gamemode.bat").read_text(encoding="utf-8")
assert "-Only desktop,gamemode" in bat and "-Redo" in bat
assert "-Only gamemode" in bat and "-Redo" in bat
def test_a_measurement_error_inside_a_placement_marks_the_stage_partial(tmp_path, monkeypatch, fake_server):