feat(m0): measure the game's own frame times and try yielding by priority instead of a GPU cap

The 95 % GPU cap is gone: it did not lower utilisation, slowed the LLM and
a YouTube video did not stutter without it. What it was meant to protect
is now measured directly in a game. The new on-demand game_frames stage
records the game's frame times with PresentMon (pinned by hash, game
process only, CSV deleted after reading) with Jarvis off, idle and busy in
the game placement, and busy while Jarvis yields: its processes at
below-normal CPU and GPU scheduling priority, read back to confirm, then
restored. Busy rows run A B B A. The design docs record the candidate and
the pre-registered rule for adopting it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-11 09:05:55 +09:00
parent 726fca3377
commit dff18c5c7e
9 changed files with 717 additions and 11 deletions

View File

@@ -34,7 +34,7 @@
| 도구 호출 | Strata에서 동작(빠름 12번 중 9번, 권장 12번 중 8번). 둘 다 도구를 부르지 않고 한 척하는 경우가 있음: 빠름 모델은 "5분 타이머 맞춰 줘"에서 "설정했습니다"라고만 답하고(3번 모두), 권장 모델은 "서울 날씨 어때?"에서 날씨를 지어내 답함(3번 모두). 두뇌 코드에서 고침(2026-11-10): (1) 지시문에 "바뀌는 정보(날씨·뉴스·가격·화면)는 이번 턴 도구 결과로만 말하고, 동작은 도구가 성공했을 때만 했다고 말한다"는 규칙을 넣고, 지시문 끝에 이번 턴에 쓸 수 있는 도구 이름을 다시 적음. (2) 모델이 계획 단계가 고른 도구를 건너뛰고 답하면 그 답을 버리고 계획에 적힌 호출을 직접 실행한 뒤 결과로 다시 답하게 함(인자가 도구 형식에 맞을 때만, 아니면 원래 답 유지). (3) 계획 단계에 도구 인자 이름을 보여 줌. 측정 키트 `tools_fast`/`tools_recommended` 단계로 두 모델에서 다시 확인. 수정 후에도 틀리면 모델을 바꿈(사용자 결정): 키트가 같은 계열의 덜 압축된 모델(빠름: UD-Q6_K_XL, Q8_0 / 권장: IQ3_XXS, IQ3_S)을 차례로 재고, 처음 통과한 모델을 기본값으로 함. 재측정 결과(2026-11-10): 빠름 모델 UD-Q4_K_XL이 27번 모두 통과해 기본값 그대로 둠. 도구를 모두 모델이 직접 불렀고 "건너뛴 도구 직접 실행" 장치는 한 번도 돌지 않음. (처음 채점에서는 "할 수 있는 도구는 없습니다/준비되어 있지 않습니다"를 거절로 읽지 못해 6번을 실패로 잘못 매겼고, 그래서 Q6_K_XL과 Q8_0까지 받아 잼. 채점을 고친 뒤 세 모델 모두 27번 통과.) 권장 모델은 Q2_0, IQ3_XXS, IQ3_S 모두 27번 중 24번: "거실 불 꺼 줘"에서 계획 단계는 도구가 필요 없다고 했는데 상관없는 도구(화면 보기, 날씨, 한 번은 0분 타이머)를 부름. 압축 정도와 상관없는 모델 성질이라 권장 모델은 뺌 |
| 분리된 화면공유 창 | 분리 창은 하나뿐이고 그 안에서 볼 화면공유를 고름. 창 제목에는 음성 채널 이름만 있어 누구 화면인지 모름. 누가 공유 중인지는 음성 채널 상태로 확인. 물어본 사람이 공유 중이 아니면 그렇다고 답함. 공유 중이면 공유자가 여러 명이어도 따로 묻지 않고 분리 창을 바로 캡처(사용자가 이미 그 사람 화면을 보고 있음). 가려져도 영상은 계속 그려짐 |
| 게임 감지 | 발로란트(테두리 없는 창)를 게임으로, 브라우저 전체화면 영상을 게임 아님으로 바르게 판단. 안티치트 Vanguard 실행 감지 |
| 게임 모드 VRAM 비우기 | Strata 0.1.59의 qwen36 엔진은 실행 중 VRAM 줄이기를 지원하지 않음(`POST /v1/vram`이 400). 그래서 게임 중 배치는 전문가 층 VRAM 몫(`--expert-vram`)과 프롬프트 조각(`--prefill 2048`)을 정해 다시 시작함. M0 `gamemode` 두 번 측정 결과(2026-11-10): 16GB 카드에서는 게임에 8GB를 비울 수 없음(가장 많이 비운 배치도 6.3GB, STT 제외). `--kv`와 `--mtp off`는 이 엔진에서 VRAM을 줄이지 않음(엔진 소스와 측정으로 확인). 게임 중 배치는 동시 1개, 이미지 CPU, CPU 작업자 8개, 맥락 16K이고 전문가 몫은 식으로 계산함. 게임 중 최소 배치는 전문가 2GB(사용자 결정, 2026-11-10): 실제 게임 중(`gamemode_live`) 0GB보다 출력이 1.5~2.1배 빨랐음(STT GPU 19.3 대 9.3, STT CPU 38.4 대 25.4 tok/s). 0GB는 2GB로 게임 몫이 0 이하인 PC에서만 일시정지 전에 씀. 이 PC는 기본값 8GB를 못 비우므로 최소 배치로 가고 "게임에 약 2.6GB까지만"을 표시함(LLM과 STT를 함께 켜고 10명 동시 전사를 돌리며 잰 값, `gamemode_stt`). 평소 배치도 Strata 자동 배치 대신 같은 식으로 STT 몫을 남겨 `--expert-vram`을 정함(사용자 결정, 2026-11-10): 자동 배치는 STT와 함께 16.3GB 중 15.9GB까지 채웠고 맥락 첫 토큰이 1.6초에서 7.5초로 늘었음. 게임 중에 LLM이 답하는 동안에는 STT 부분 전사 간격을 늘리고 최종 전사는 바로 처리함. 게임이 없을 때는 LLM이 답하는 동안에도 부분 전사를 줄이지 않고 그대로 함(사용자 결정, 2026-11-10). 10명 동시 전사를 쉬지 않고 돌리면 LLM 출력이 1/2.5~1/3로 줄고 음성 첫 문장이 1.3~1.7초가 됨. 평소 배치는 다른 프로그램용 여유 VRAM 1GB를 더 남김(설정에서 바꿈). Jarvis의 GPU 사용률 제한(LLM 엔진과 음성 워커를 200ms마다 함께 10ms씩 멈춤, 영상을 볼 여유를 위해)을 검토했으나 아래 측정으로 뺌. `gamemode_tune` 측정 결과(2026-11-11): 평소 배치는 식으로 전문가 1.5GB가 나왔고 STT가 VRAM을 가장 많이 쓸 때도 1.8GB가 남았으며 맥락 첫 토큰은 7.5초에서 1.9초로 줄었음(LLM만 64.4 tok/s). 게임 중 LLM이 답하는 동안에는 부분 전사를 멈춤: 2초 간격은 37.5 tok/s에 음성 첫 문장 0.89초로 기준을 넘었고, 멈추면 64.9 tok/s, 0.55초였음. 부분 전사를 멈췄을 때 beam 2~3 최종 전사와 긴 말의 실제 지연은 미검증. GPU 95% 제한은 멈춘 시간 5.2%를 지켰지만 nvidia-smi 사용률이 내려가지 않았고(96→98%, 40→39%) 출력만 6~10% 느려져서 기본값은 100%(끔)로 정함(사용자 결정, 2026-11-11). M0 `video_drops` 측정 결과(2026-11-11): Jarvis가 GPU를 98%까지 쓰는 동안에도 유튜브 1080p 60fps 영상의 끊긴 프레임은 창마다 3~4개로 Jarvis를 끈 때(3개)와 같았고 50ms 넘는 멈춤과 버퍼링은 0번, 95% 제한은 끊김을 줄이지 못함(7 대 7개). 그래서 미리 정한 기준대로 GPU 사용률 제한 설정을 뺌. 게임 화면 프레임에 주는 영향은 재지 않음. 배치 전환 28~36초, 실제 게임 중 43~47초. STT는 게임 중에도 GPU에 둠: CPU로 옮기면 말 한 마디 전사가 3.0~3.8초(GPU 0.11~0.19초)라 부분 전사를 따라가지 못함. 엔진이 실행 중 줄이기를 지원하면 다시 잼 ([pc-features.md](pc-features.md#측정-결과-m0-gamemode-2026-11-10-rtx-5070-ti-16gb-ryzen-9-9950x3d)) |
| 게임 모드 VRAM 비우기 | Strata 0.1.59의 qwen36 엔진은 실행 중 VRAM 줄이기를 지원하지 않음(`POST /v1/vram`이 400). 그래서 게임 중 배치는 전문가 층 VRAM 몫(`--expert-vram`)과 프롬프트 조각(`--prefill 2048`)을 정해 다시 시작함. M0 `gamemode` 두 번 측정 결과(2026-11-10): 16GB 카드에서는 게임에 8GB를 비울 수 없음(가장 많이 비운 배치도 6.3GB, STT 제외). `--kv`와 `--mtp off`는 이 엔진에서 VRAM을 줄이지 않음(엔진 소스와 측정으로 확인). 게임 중 배치는 동시 1개, 이미지 CPU, CPU 작업자 8개, 맥락 16K이고 전문가 몫은 식으로 계산함. 게임 중 최소 배치는 전문가 2GB(사용자 결정, 2026-11-10): 실제 게임 중(`gamemode_live`) 0GB보다 출력이 1.5~2.1배 빨랐음(STT GPU 19.3 대 9.3, STT CPU 38.4 대 25.4 tok/s). 0GB는 2GB로 게임 몫이 0 이하인 PC에서만 일시정지 전에 씀. 이 PC는 기본값 8GB를 못 비우므로 최소 배치로 가고 "게임에 약 2.6GB까지만"을 표시함(LLM과 STT를 함께 켜고 10명 동시 전사를 돌리며 잰 값, `gamemode_stt`). 평소 배치도 Strata 자동 배치 대신 같은 식으로 STT 몫을 남겨 `--expert-vram`을 정함(사용자 결정, 2026-11-10): 자동 배치는 STT와 함께 16.3GB 중 15.9GB까지 채웠고 맥락 첫 토큰이 1.6초에서 7.5초로 늘었음. 게임 중에 LLM이 답하는 동안에는 STT 부분 전사 간격을 늘리고 최종 전사는 바로 처리함. 게임이 없을 때는 LLM이 답하는 동안에도 부분 전사를 줄이지 않고 그대로 함(사용자 결정, 2026-11-10). 10명 동시 전사를 쉬지 않고 돌리면 LLM 출력이 1/2.5~1/3로 줄고 음성 첫 문장이 1.3~1.7초가 됨. 평소 배치는 다른 프로그램용 여유 VRAM 1GB를 더 남김(설정에서 바꿈). Jarvis의 GPU 사용률 제한(LLM 엔진과 음성 워커를 200ms마다 함께 10ms씩 멈춤, 영상을 볼 여유를 위해)을 검토했으나 아래 측정으로 뺌. `gamemode_tune` 측정 결과(2026-11-11): 평소 배치는 식으로 전문가 1.5GB가 나왔고 STT가 VRAM을 가장 많이 쓸 때도 1.8GB가 남았으며 맥락 첫 토큰은 7.5초에서 1.9초로 줄었음(LLM만 64.4 tok/s). 게임 중 LLM이 답하는 동안에는 부분 전사를 멈춤: 2초 간격은 37.5 tok/s에 음성 첫 문장 0.89초로 기준을 넘었고, 멈추면 64.9 tok/s, 0.55초였음. 부분 전사를 멈췄을 때 beam 2~3 최종 전사와 긴 말의 실제 지연은 미검증. GPU 95% 제한은 멈춘 시간 5.2%를 지켰지만 nvidia-smi 사용률이 내려가지 않았고(96→98%, 40→39%) 출력만 6~10% 느려져서 기본값은 100%(끔)로 정함(사용자 결정, 2026-11-11). M0 `video_drops` 측정 결과(2026-11-11): Jarvis가 GPU를 98%까지 쓰는 동안에도 유튜브 1080p 60fps 영상의 끊긴 프레임은 창마다 3~4개로 Jarvis를 끈 때(3개)와 같았고 50ms 넘는 멈춤과 버퍼링은 0번, 95% 제한은 끊김을 줄이지 못함(7 대 7개). 그래서 미리 정한 기준대로 GPU 사용률 제한 설정을 뺌. 대신 게임 화면의 프레임 시간(평균 fps, 1% low, 50ms 넘는 프레임)을 직접 재고(M0 `game_frames`), 게임 중 Jarvis 프로세스의 CPU·GPU 우선순위를 "보통 이하"로 낮추는 양보(멈추지 않음)를 후보로 함께 잼. 미리 정한 기준: 바쁠 때 게임만 켠 때보다 5% 넘게 떨어지지 않으면 아무것도 더하지 않고, 더 떨어지면 양보가 하락을 절반 이상 줄일 때만 게임 중 기본으로 켬(Jarvis 출력이 20% 넘게 느려지면 사용자에게 물음) ([pc-features.md](pc-features.md#pc마다-값을-계산)). 배치 전환 28~36초, 실제 게임 중 43~47초. STT는 게임 중에도 GPU에 둠: CPU로 옮기면 말 한 마디 전사가 3.0~3.8초(GPU 0.11~0.19초)라 부분 전사를 따라가지 못함. 엔진이 실행 중 줄이기를 지원하면 다시 잼 ([pc-features.md](pc-features.md#측정-결과-m0-gamemode-2026-11-10-rtx-5070-ti-16gb-ryzen-9-9950x3d)) |
| PC 프로그램 조작 (agent-desktop) | 게임PC에서 동작 확인: 계산기 12+3=15, 테스트 창 입력칸에 값 넣고 다시 읽기 성공(창을 띄우고 2.9초 뒤 읽힘). 명령 한 번: 찾기 0.18초, 누르기 0.22초, 값 넣기 0.28초. 명령마다 실행 0.10초, 계속 켜 둔 MCP 0.09초라 명령마다 실행 방식으로 정함. 디스코드·탐색기 읽기 시간은 키트가 Windows 프로세스 이름(`Discord.exe`)을 맞추지 못해 재지 못했고, 키트가 띄운 계산기는 `close-app`으로 닫히지 않음(UWP 앱이라 `APP_NOT_FOUND`). 둘 다 고쳐서 `gamemode`와 함께 다시 잼 |
| 봇용 크롬창 | 실제 모니터 어디에도 보이지 않게 가상 모니터에 둠(사용자 선택). M0 `vdisplay` 단계는 돌리지 않고, M6에서 함께 넣을 드라이버로 직접 확인 ([pc-features.md](pc-features.md#봇용-크롬창과-디스코드-화면공유)) |

View File

@@ -35,7 +35,11 @@
- **게임 중 최소 배치는 전문가 2GB입니다**(사용자 결정, 2026-11-10). 전문가 몫에는 긴 프롬프트용 버퍼 1.1GiB가 먼저 들어가므로 2GB는 전문가를 실제로 올리는 가장 작은 값이고, 실제 게임 중에는 0GB보다 출력이 1.5~2.1배 빨랐습니다(아래 측정 결과). 0GB는 2GB로는 게임 몫이 0 이하가 되는 PC에서만 일시정지 전 마지막 단계로 씁니다.
- **몫이 최소 배치보다 작을 때**: 계산한 몫이 최소 배치(전문가 2GB)보다 작으면, 몫을 늘려 게임 몫을 침범하지 않습니다. 대신 게임용으로 비울 VRAM을 "그래픽카드 VRAM − 다른 프로그램 − STT 몫 − 엔진 기본 버퍼 − 최소 배치"까지 줄이고, 대시보드와 게임 모드 설정 화면에 "이 PC에서는 게임에 X GB까지만 비울 수 있음"을 표시합니다. 이렇게 줄인 값이 0 이하이면(예: 8GB 그래픽카드에서 다른 프로그램이 이미 많이 씀) 게임 중에는 LLM을 멈추고 일시정지 단계로 갑니다. 게임 중 일시정지를 꺼 두었어도 마찬가지이고, 그 이유를 대시보드에 표시합니다. 게임이 끝나면 되돌리기 규칙대로 돌아옵니다.
- **첫 실행 자가 점검**: 설치가 끝나면 평소·게임 중 배치로 각각 30초씩 출력 속도와 음성 첫 문장 시간을 잽니다. 평소 배치가 기준(출력 30 tok/s, 음성 첫 문장 0.7초)에 못 미치는 PC는 평소에도 동시 요청 1개, 이미지 CPU 읽기, 지난 대화 약 4천 토큰으로 시작합니다. 게임 중 배치가 기준에 못 미치면 대시보드와 설정 화면에 "게임 중에는 답이 느릴 수 있음"을 표시합니다.
- **GPU 사용률 제한은 두지 않습니다**: Jarvis 옆에서 보는 영상이 끊기지 않도록 LLM 엔진과 음성·두뇌 워커를 200ms마다 함께 10ms씩 멈추는 제한(Windows 프로세스 일시정지)을 검토했지만 뺐습니다(2026-11-11). M0 `gamemode_tune`에서는 멈춘 시간이 정한 대로 5.2%였는데도 nvidia-smi 사용률이 내려가지 않았고(STT를 쉬지 않고 돌릴 때 중앙값 96→98%, LLM만 40→39%) 출력만 6~10% 느려졌습니다([측정 결과](#자동-조절-측정-m0-gamemode_tune-2026-11-11)). M0 `video_drops`에서는 제한이 없어도 Jarvis가 GPU를 98%까지 쓰는 동안 유튜브 1080p 60fps 영상이 끊기지 않았고, 95% 제한은 끊긴 프레임을 줄이지 못했습니다([측정 결과](#영상-끊김-측정-m0-video_drops-2026-11-11)). 미리 정한 기준(제한이 끊김을 줄이지 못하면 설정을 뺌)대로 설정에서 뺐습니다. 게임 화면 프레임에 주는 영향은 재지 않았습니다.
- **GPU 사용률 제한은 두지 않습니다**: Jarvis 옆에서 보는 영상이 끊기지 않도록 LLM 엔진과 음성·두뇌 워커를 200ms마다 함께 10ms씩 멈추는 제한(Windows 프로세스 일시정지)을 검토했지만 뺐습니다(2026-11-11). M0 `gamemode_tune`에서는 멈춘 시간이 정한 대로 5.2%였는데도 nvidia-smi 사용률이 내려가지 않았고(STT를 쉬지 않고 돌릴 때 중앙값 96→98%, LLM만 40→39%) 출력만 6~10% 느려졌습니다([측정 결과](#자동-조절-측정-m0-gamemode_tune-2026-11-11)). M0 `video_drops`에서는 제한이 없어도 Jarvis가 GPU를 98%까지 쓰는 동안 유튜브 1080p 60fps 영상이 끊기지 않았고, 95% 제한은 끊긴 프레임을 줄이지 못했습니다([측정 결과](#영상-끊김-측정-m0-video_drops-2026-11-11)). 미리 정한 기준(제한이 끊김을 줄이지 못하면 설정을 뺌)대로 설정에서 뺐습니다. 게임 화면 프레임에 주는 영향은 아래 `game_frames`로 따로 잽니다.
- **대신 게임 화면의 프레임을 직접 보고, 멈추는 대신 우선순위로 양보합니다(후보, M0 `game_frames`로 정함)**: 사용률 제한은 GPU 전체 사용률을 보고 Jarvis를 일정 시간씩 멈추는 방식이라, 게임이 GPU를 원하지 않을 때도 Jarvis를 느리게 했고 정작 막으려던 것(화면이 끊기는 것)은 보지 않았습니다. 그래서 두 가지를 바꿉니다(2026-11-11).
- **기준은 게임 화면의 프레임 시간입니다**: 평균 fps, 1% low(가장 느린 1% 프레임), 50ms·100ms를 넘는 프레임 수를 봅니다. Windows가 기록하는 "게임이 프레임을 내보낸 시각"만 읽고 게임 화면은 보지 않습니다.
- **양보(후보)**: 게임 중에는 LLM 엔진과 음성·두뇌 워커의 CPU 우선순위와 GPU 스케줄링 우선순위를 "보통 이하"로 둡니다(Windows 프로세스 우선순위, 일시정지 없음). Windows는 게임이 같은 코어나 GPU를 원할 때만 게임에 먼저 내주므로, 게임이 덜 바쁠 때는 Jarvis 속도가 그대로입니다. 게임이 없을 때는 양보하지 않습니다(영상은 양보 없이도 끊기지 않았음). 설정 화면에는 두지 않습니다.
- **미리 정한 기준**: Jarvis가 답하는 동안 게임의 평균 fps와 1% low가 게임만 켠 때보다 5% 넘게 떨어지지 않고 50ms 넘는 프레임도 늘지 않으면, 아무것도 더하지 않습니다(양보도 넣지 않음). 더 떨어지면 양보가 그 하락을 절반 이상 줄일 때 게임 중 기본으로 켭니다. 이때 Jarvis 출력이 20% 넘게 느려지면 켜기 전에 사용자에게 묻습니다. 양보로도 줄지 않으면 넣지 않고, 대시보드에서 게임 중 일시정지를 안내합니다.
- **실행 중 감시**: 대시보드가 이미 재는 단계별 지연을 씁니다. 음성 첫 문장이 최근 5번 중 3번 이상 0.7초를 넘으면 다시 시작 없이 바꿀 수 있는 것부터 낮춥니다: 지난 대화 양 → 화질 → 캡처 미리 준비. 10분 동안 기준 안에 들면 하나씩 되돌립니다. 다시 시작이 필요한 배치 변경은 게임 감지와 VRAM 부족 때만 합니다.
### 전환 규칙
@@ -153,6 +157,10 @@ LLM과 STT를 함께 켠 측정(M0 `gamemode_stt`, 게임 없음). STT를 먼저
- **95% 제한은 끊김을 줄이지 못했습니다**(창 두 개 합계 7개 대 7개). 그래서 설정을 뺐습니다([위](#pc마다-값을-계산)).
- **재지 않은 것**: 게임 중, 게임과 영상을 함께 켠 경우, 이 PC(RTX 5070 Ti 16GB) 말고 다른 그래픽카드. 영상은 GPU의 영상 전용 회로로 풀리므로 LLM·STT 계산과 덜 부딪혔을 수 있습니다(추정).
### 게임 프레임 측정 (M0 `game_frames`, 측정 전)
게임을 켜고 캐릭터를 한자리에 세워 둔 채로 창마다 1분씩 잽니다. 순서는 게임만 → Jarvis를 켜 두고 쉼 → Jarvis 바쁨 → 바쁨+양보 → 바쁨+양보 → 바쁨 → 다시 게임만입니다(바쁨 줄은 A B B A 순서라 천천히 바뀌는 장면 탓이 한쪽에만 쌓이지 않음). Jarvis는 게임 중 배치(전문가 2GB, 맥락 16K, 음성 인식 GPU)이고, "바쁨"은 LLM이 쉬지 않고 답하고 음성 인식이 정한 대로 최종 전사만 하는 상태입니다. 프레임 시간은 PresentMon(인텔의 공개 도구, 버전과 해시 고정)으로 게임 프로세스 하나만 기록하고, 게임 이름이 든 원본 기록은 읽자마자 지웁니다. Windows 이벤트 기록을 쓰므로 관리자 권한이 필요하고, 게임을 켜기 전에 한 번만 묻습니다. 양보 창에서는 우선순위가 실제로 낮아졌는지 다시 읽어서 확인하고, 낮아지지 않았으면 비교에서 뺍니다.
## 화면 보기: 전체 화면, 모니터별, 프로그램(창)별
- Windows Graphics Capture API로 다음을 볼 수 있습니다.

View File

@@ -4,7 +4,7 @@
| 단계 | 내용 | 완료 기준 |
|---|---|---|
| M0 | 게임PC 사전 검증 | 측정 스크립트를 게임PC에서 직접 실행하고 결과 파일을 보내 주시는 방식입니다. 결과로 기본값을 확정합니다. 확인 항목은 아래 목록에 있습니다. 가상 모니터 확인을 뺀 모든 항목 측정 완료(2026-11-10). 가상 모니터 확인은 M6에서 합니다. 2026-11-10에 추가한 `desktop` 단계(agent-desktop)는 측정을 마쳤고, 자동 성능 조절용 `gamemode` 단계는 세 번 쟀고, `gamemode_stt`(LLM과 STT를 함께 켬, STT GPU·CPU)와 `gamemode_live`(실제 게임을 켬) 단계도 측정을 마쳤습니다(2026-11-10). 결과로 게임 중 최소 배치는 전문가 2GB로 정했고, 평소 배치에 STT 자리를 남기는 것과 게임 중 LLM이 답하는 동안 부분 전사 간격을 늘리는 것(게임이 없을 때는 그대로)도 정했습니다(사용자 결정, 2026-11-10). `gamemode_tune` 단계도 측정을 마쳤고(2026-11-11), 게임 중 LLM이 답하는 동안에는 부분 전사를 멈추기로 정했습니다. GPU 95% 제한은 측정에서 사용률을 낮추지 못해 기본값을 끔으로 바꿨고(사용자 결정, 2026-11-11), `video_drops` 단계(Jarvis를 돌리는 동안 유튜브 영상의 끊긴 프레임, 직접 실행)도 측정을 마쳤습니다(2026-11-11). Jarvis가 바쁠 때도 영상이 끊기지 않았고 제한이 끊김을 줄이지 못해 설정을 뺐습니다. 이로써 가상 모니터 확인을 뺀 M0 측정이 모두 끝났습니다. 측정 키트: [scripts/m0/](../../scripts/m0/README.md) |
| M0 | 게임PC 사전 검증 | 측정 스크립트를 게임PC에서 직접 실행하고 결과 파일을 보내 주시는 방식입니다. 결과로 기본값을 확정합니다. 확인 항목은 아래 목록에 있습니다. 가상 모니터 확인을 뺀 모든 항목 측정 완료(2026-11-10). 가상 모니터 확인은 M6에서 합니다. 2026-11-10에 추가한 `desktop` 단계(agent-desktop)는 측정을 마쳤고, 자동 성능 조절용 `gamemode` 단계는 세 번 쟀고, `gamemode_stt`(LLM과 STT를 함께 켬, STT GPU·CPU)와 `gamemode_live`(실제 게임을 켬) 단계도 측정을 마쳤습니다(2026-11-10). 결과로 게임 중 최소 배치는 전문가 2GB로 정했고, 평소 배치에 STT 자리를 남기는 것과 게임 중 LLM이 답하는 동안 부분 전사 간격을 늘리는 것(게임이 없을 때는 그대로)도 정했습니다(사용자 결정, 2026-11-10). `gamemode_tune` 단계도 측정을 마쳤고(2026-11-11), 게임 중 LLM이 답하는 동안에는 부분 전사를 멈추기로 정했습니다. GPU 95% 제한은 측정에서 사용률을 낮추지 못해 기본값을 끔으로 바꿨고(사용자 결정, 2026-11-11), `video_drops` 단계(Jarvis를 돌리는 동안 유튜브 영상의 끊긴 프레임, 직접 실행)도 측정을 마쳤습니다(2026-11-11). Jarvis가 바쁠 때도 영상이 끊기지 않았고 제한이 끊김을 줄이지 못해 설정을 뺐습니다. 대신 게임 화면의 프레임을 직접 재는 `game_frames` 단계(게임을 켠 채로 Jarvis를 끈 때·쉴 때·바쁠 때와 우선순위를 낮춘 양보 상태, 직접 실행, 관리자 권한)를 넣었고(2026-11-11), 남은 M0 측정은 이 단계와 가상 모니터 확인(M6)입니다. 측정 키트: [scripts/m0/](../../scripts/m0/README.md) |
| M1 | 음성 워커 | 화자별 스트리밍 STT(공용 모델, 배치), 문장 단위 TTS를 WebSocket으로 제공. 녹음 파일 10개 동시 입력 테스트 통과 |
| M2 | 디스코드 음성 코어 이전 | v1 봇 코드를 Electron 안으로 이전. 입장/퇴장, 화자별 수신, 재생, 정지 명령 동작. 채팅 채널 연결(읽기·보내기) |
| M3 | 두뇌 연결 | 기존 jarvis를 Ollama 대신 Strata 주소로 연결. 대화 기록 저장소와 지난 대화 전체 검색(본인 기록 + 등록한 채팅 채널 + 같은 음성 채널의 다른 사람 말). 채팅 채널 도구(읽기·검색·보내기·수정·반응·삭제·고정). 메모리, 날씨, 웹 검색, 식단, MCP 기존 테스트와 평가(evals) 통과 |
@@ -21,7 +21,7 @@ M0에서 확인할 항목:
- 화질 단계별 이미지 읽기 시간
- 한국어 품질
- 게임 모드 전환 시간, 모델 배치별 출력 속도·음성 첫 문장·남는 VRAM (`gamemode` 단계)
- LLM과 STT(10명 동시 전사)를 함께 켰을 때 남는 VRAM과 양쪽 속도, 게임 중 STT를 CPU로 옮겼을 때의 전사 시간 (`gamemode_stt` 단계), 실제 게임을 켠 채로 같은 측정 (`gamemode_live` 단계, 직접 실행), 평소 배치에 STT 자리와 다른 프로그램용 여유 1GB를 남겼을 때, 게임 중 배치에서 LLM이 답하는 동안 부분 전사 간격을 늘렸을 때, GPU 사용률을 95%로 제한했을 때의 양쪽 속도와 실제 GPU 사용률 (`gamemode_tune` 단계), Jarvis를 끈 때·쉴 때·바쁠 때(제한 없이와 95%) 유튜브 영상의 끊긴 프레임 수 (`video_drops` 단계, 직접 실행)
- LLM과 STT(10명 동시 전사)를 함께 켰을 때 남는 VRAM과 양쪽 속도, 게임 중 STT를 CPU로 옮겼을 때의 전사 시간 (`gamemode_stt` 단계), 실제 게임을 켠 채로 같은 측정 (`gamemode_live` 단계, 직접 실행), 평소 배치에 STT 자리와 다른 프로그램용 여유 1GB를 남겼을 때, 게임 중 배치에서 LLM이 답하는 동안 부분 전사 간격을 늘렸을 때, GPU 사용률을 95%로 제한했을 때의 양쪽 속도와 실제 GPU 사용률 (`gamemode_tune` 단계), Jarvis를 끈 때·쉴 때·바쁠 때(제한 없이와 95%) 유튜브 영상의 끊긴 프레임 수 (`video_drops` 단계, 직접 실행), 게임을 켠 채로 Jarvis를 끈 때·쉴 때·바쁠 때와 바쁠 때 우선순위를 낮춰 양보했을 때 게임 화면의 평균 fps·1% low·50ms 넘는 프레임 수 (`game_frames` 단계, 직접 실행)
- faster-whisper turbo와 MeloTTS/CosyVoice2 속도
- 봇용 크롬창의 Alt+Tab 숨김과 디스코드 화면공유 목록 표시
- 디스코드 분리 화면공유 창 식별과, 가려졌을 때 영상이 멈추는지
@@ -37,7 +37,7 @@ M7 완료 기준:
- 봇용 크롬창 화면공유 표시
- agent-desktop으로 프로그램 조작, 접근성 정보가 없는 화면만 키보드·마우스 제어, 비상 정지
- 안티치트 감지·차단 안내
- 게임 감지(테두리 없는 창 포함)와 자동 성능 조절(평소·게임 중 배치 전환, 첫 실행 자가 점검, 실행 중 지연 감시), 게임 중 일시정지
- 게임 감지(테두리 없는 창 포함)와 자동 성능 조절(평소·게임 중 배치 전환, 첫 실행 자가 점검, 실행 중 지연 감시), 게임 중 일시정지, 게임에 양보(`game_frames` 결과로 넣을지 정함)
M0~M4는 "더 빠르고 똑똑한 음성 대화"의 핵심이고, M5~M8은 "설치 하나로 끝나는 관리 앱"입니다. 로그 화면은 M5에 넣어서 그 뒤 테스트할 때부터 바로 쓸 수 있게 합니다. M4까지 끝나면 GUI 없이도 새 엔진을 먼저 써 볼 수 있습니다.

View File

@@ -38,6 +38,7 @@ LLM 단계는 8080 포트를 씁니다. 다른 프로그램이 이 포트를 쓰
| 게임 중 자동 조절 | 이미 받은 Qwen3.6-35B-A3B를 평소 배치(동시 1개)와 게임 중 배치 3개(전문가 층 2GB 맥락 32K, 2GB 맥락 16K, 0GB 맥락 16K)로 차례로 다시 시작해서, 배치마다 전환 시간, 남는 VRAM, 출력 속도, 음성 첫 문장, 맥락 8천 토큰 첫 토큰 시간을 잽니다. 마지막에 평소 배치로 한 번 더 켜서 되돌리는 시간도 잽니다 |
| LLM과 음성 인식 함께 | 음성 인식(STT)을 먼저 켜 두고 LLM을 평소 배치(동시 1개, 2개)와 게임 중 배치(전문가 2GB·0GB, 맥락 16K)로 켭니다. LLM을 재는 동안 음성 인식은 10명 동시 전사를 계속 돌립니다. 게임 중 배치는 음성 인식을 GPU에 둔 경우와 CPU에 둔 경우를 둘 다 잽니다. 배치마다 남는 VRAM, LLM 속도, 10명 동시 전사 시간, 한 사람 전사 시간을 적습니다 |
| 영상 끊김 (`run_m0_video.bat`로만) | 유튜브 영상을 틀어 두고 Jarvis를 끈 때, 켜 두고 쉴 때, 바쁠 때(GPU 95% 제한 없이와 있을 때)의 끊긴 프레임 수와 긴 멈춤 횟수 |
| 게임 프레임 (`run_m0_game_frames.bat`로만) | 게임을 켜 두고 Jarvis를 끈 때, 켜 두고 쉴 때, 바쁠 때(우선순위를 낮춰 게임에 양보할 때와 안 할 때)의 게임 화면 평균 fps, 1% low, 50ms·100ms 넘는 프레임 수 |
| STT 자리와 부분 전사 간격 | 평소 배치를 STT 자리를 남긴 전문가 층 몫으로 켜고 STT를 쉬지 않고 돌리며 잽니다. 게임 중 배치(전문가 2GB)는 STT를 쉬지 않고 돌릴 때, 부분 전사를 2초마다 할 때, 부분 전사 없이 최종 전사만 할 때를 잽니다(게임은 켜지 않음). 배치마다 남는 VRAM, LLM 속도, 최종 전사 시간과 기다린 시간, STT가 GPU를 쓴 비율을 적습니다 |
## 개인정보
@@ -48,6 +49,7 @@ LLM 단계는 8080 포트를 씁니다. 다른 프로그램이 이 포트를 쓰
- 게임 감지는 실행 중인 프로그램 이름과 창 모양만 봅니다. 게임 화면은 저장하지 않습니다. 설치된 게임은 이름과 안티치트 유무만 기록합니다.
- 음성 테스트는 키트에 들어 있는 합성 음성만 씁니다. 마이크는 쓰지 않습니다.
- 영상 끊김 단계(`video_drops`)는 유튜브에 공개된 Blender 영상을 새 임시 브라우저 프로필로 엽니다. 로그인하지 않고, 평소 쓰시는 프로필은 건드리지 않으며, 끝나면 그 임시 프로필을 지웁니다. 저장하는 것은 영상의 프레임 수, 끊긴 프레임 수, 화질, 광고가 나왔는지뿐입니다.
- 게임 프레임 단계(`game_frames`)는 PresentMon(인텔의 공개 도구)으로 게임이 프레임을 내보낸 시각만 기록합니다. 게임 화면은 보지 않고, 게임 이름이 든 원본 기록은 읽자마자 지웁니다. 저장하는 것은 fps, 1% low, 긴 프레임 수 같은 숫자뿐입니다.
- PC 제어 도구 단계는 다른 프로그램의 창 제목과 화면 글자를 저장하지 않습니다. 개수, 걸린 시간, 오류 코드, 계산기 결과 숫자만 저장합니다. 이미 켜 둔 계산기가 있으면 건드리지 않고 그 확인을 건너뛰며, 브라우저는 평소 쓰시는 프로필이 아닌 새 임시 프로필로 엽니다.
## 옵션 (PowerShell에서 직접 실행할 때)
@@ -58,7 +60,7 @@ LLM 단계는 8080 포트를 씁니다. 다른 프로그램이 이 포트를 쓰
.\run_m0.ps1 -Only stt,tts_melo -Redo # 특정 단계만 다시
```
단계 이름: `sysinfo`, `winchecks`, `vdisplay`, `tts_melo`, `tts_cosy2`, `tts_cosy3`, `stt`, `llm_fast`, `llm_recommended`, `tools_fast`, `tools_recommended`, `desktop`, `gamemode`, `gamemode_stt`, `gamemode_tune`, `gamemode_live`, `video_drops`(마지막 두 단계는 `-Only`로 고를 때만 돕니다)
단계 이름: `sysinfo`, `winchecks`, `vdisplay`, `tts_melo`, `tts_cosy2`, `tts_cosy3`, `stt`, `llm_fast`, `llm_recommended`, `tools_fast`, `tools_recommended`, `desktop`, `gamemode`, `gamemode_stt`, `gamemode_tune`, `gamemode_live`, `video_drops`, `game_frames`(마지막 세 단계는 `-Only`로 고를 때만 돕니다)
`tools_fast`, `tools_recommended`는 도구 호출만 다시 잽니다. 처음과 같은 방식(고치기 전)과, 자비스의 수정(지시문 규칙, 계획 단계, 건너뛴 도구 직접 실행)을 넣은 방식을 같은 모델로 비교합니다. 이미 받은 모델을 쓰므로 모델 하나에 몇 분이면 끝납니다.
@@ -76,4 +78,6 @@ LLM 단계는 8080 포트를 씁니다. 다른 프로그램이 이 포트를 쓰
`run_m0_video.bat`을 더블클릭하면 Jarvis 옆에서 보는 영상이 끊기는지 잽니다(`video_drops`). 크롬(없으면 엣지)이 새 임시 프로필로 떠서 유튜브의 Blender 영상(Big Buck Bunny, 1080p 60fps, 소리 끔)을 틉니다. 광고가 나오면 건너뛸 수 있을 때 건너뛰고 끝날 때까지 기다립니다. 영상을 틀어 둔 채로 (1) Jarvis를 끈 상태 1분, (2) LLM(평소 배치, STT 자리와 여유 1GB)과 STT를 켜 두고 쉬는 상태 1분, (3) LLM이 답하고 STT가 10명 동시 전사를 쉬지 않고 하는 상태를 GPU 95% 제한 없이 두 번, 제한을 켜고 두 번, (4) 다시 Jarvis를 끈 상태 1분을 잽니다. 각각 끊긴 프레임 수(유튜브 "전문가용 통계"의 Dropped Frames와 같은 값)와, 화면에 프레임이 50ms·100ms 넘게 안 바뀐 횟수를 셉니다. 10~15분 걸립니다. 그동안 브라우저 창을 가리거나 최소화하지 말고 PC에 손대지 않으시면 됩니다. 광고, 일시정지, 버퍼링, 건너뛰기가 끼었거나 화질이 1080p 60fps가 아니었던 구간, 제한을 켰는데 Jarvis를 실제로 멈추지 못한 구간은 기록만 하고 비교에서는 뺍니다. 영상이 멈추거나 유튜브 오류가 뜨거나 페이지가 새로고침되면 키트가 알아서 다시 틀고(재생을 누르고, 안 되면 페이지를 다시 엽니다) 그 구간을 최대 3번까지 다시 잽니다. 직접 새로고침하지 않으셔도 됩니다. 화질이나 프레임 수가 떨어진 구간은 GPU 탓일 수 있어서 다시 재지 않습니다.
`run_m0_game_frames.bat`을 더블클릭하면 Jarvis가 게임 화면을 끊기게 하는지 잽니다(`game_frames`). 게임 프레임은 Windows 이벤트 기록으로 재므로 처음에 관리자 권한을 묻는 창이 한 번 뜹니다. 게임을 켜기 전에 "예"를 눌러 주세요. 그다음 게임을 켜고 플레이 화면까지 들어간 뒤 Enter를 누르고 15초 안에 게임으로 돌아가면 됩니다. 끝날 때까지 캐릭터를 한자리에 세워 두고 마우스·키보드에 손대지 마세요. 창마다 1분씩 (1) 게임만, (2) Jarvis(게임 중 배치)를 켜 두고 쉴 때, (3) LLM이 답하고 음성 인식이 최종 전사를 하는 동안을 그냥 두 번, Jarvis의 CPU·GPU 우선순위를 낮춰 게임에 양보하게 하고 두 번, (4) 다시 게임만 잽니다. 10~15분 걸리고 끝나면 알림음이 울립니다. 게임이 앞에 없었던 구간, 게임이 프레임을 거의 내지 않은 구간, 우선순위가 실제로 낮아지지 않은 양보 구간은 기록만 하고 비교에서 뺍니다. 프레임 제한(수직 동기화나 fps 제한)은 평소 쓰시는 대로 두셔도 됩니다.
다 끝나고 필요 없으면 작업 폴더(`\JarvisM0`)를 통째로 지우면 됩니다. Python, 모델, Strata(엔진과 설정 포함)는 모두 그 안에 설치하도록 지정해 두었습니다.

View File

@@ -55,14 +55,18 @@ STAGES = [
# the cap is off by default until this shows it helps). Opens YouTube, so only when asked for.
("video_drops", "영상 끊김: Jarvis를 돌리는 동안 유튜브 영상의 끊긴 프레임", "base", "llm.py",
["model=fast", "only=video"], 0),
# Does Jarvis make the user's game drop frames, and does yielding by priority help (the cap is gone,
# 2026-11-11). Needs the user's game and administrator rights (event tracing), so only when asked for.
("game_frames", "게임 프레임: Jarvis를 돌리는 동안 게임 화면의 프레임 (직접 게임을 켜 주셔야 합니다)", "base", "llm.py",
["model=fast", "only=frames"], 0),
# With the user's game running. Needs someone at the PC, so only when asked for (--only).
("gamemode_live", "게임을 켠 상태로 재기 (직접 게임을 켜 주셔야 합니다)", "base", "llm.py",
["model=fast", "only=live"], 0),
]
# Stages left out of a full run: they need the user there after the unattended part, or open a website.
ON_DEMAND = {"gamemode_live", "video_drops"}
ON_DEMAND = {"gamemode_live", "video_drops", "game_frames"}
# Stages that start the STT worker next to the LLM and need the stt venv's Python.
NEEDS_STT = {"gamemode_stt", "gamemode_tune", "gamemode_live", "video_drops"}
NEEDS_STT = {"gamemode_stt", "gamemode_tune", "gamemode_live", "video_drops", "game_frames"}
def free_gb(path: Path) -> float:

485
scripts/m0/m0lib/frames.py Normal file
View File

@@ -0,0 +1,485 @@
"""Stage part: does Jarvis make the user's game drop frames, and does yielding to the game help?
The GPU cap is gone (2026-11-11): pausing Jarvis for 5 % of every 200 ms did not lower nvidia-smi's
utilisation, cost 6 to 10 % of the LLM's output, and a YouTube video next to a busy Jarvis did not
stutter with or without it. What is left unmeasured is a game. So this stage measures what the user
would notice, the game's own frame times, instead of a GPU-wide number:
- PresentMon (Intel's open-source tool, pinned by hash) records when the game presents each frame
through Windows' event tracing. It sees no picture; the kit keeps only the frame-time numbers and
deletes its CSV (which names the game) right after reading it. Event tracing needs administrator
rights, so this stage runs elevated (run_m0_game_frames.bat asks once, before the game is started).
- Windows: the game alone, Jarvis loaded and idle, Jarvis busy in the game placement the app uses
(the LLM answering, the STT doing only finals, as decided for a game), and busy while Jarvis yields:
its processes at below-normal CPU priority and below-normal GPU scheduling priority. Unlike the cap
nothing is paused; Windows hands the game the cores and the GPU first only when it wants them. The
busy rows run A B B A (plain, yield, yield, plain) so a slow drift does not count for one side.
"""
from __future__ import annotations
import contextlib
import csv
import hashlib
import io
import subprocess
import threading
import time
import urllib.request
from pathlib import Path
from typing import Any
from m0lib import gpucap, llm
from m0lib.common import IS_WINDOWS, StageResult, gpu_memory_mib, interactive, ask, say, stats, wait_enter
from m0lib.llm_bench import KOREAN_PROMPTS, NO_THINK, VOICE_SYSTEM
from m0lib.llm_client import ChatClient
PRESENTMON_VERSION = "2.6.0"
PRESENTMON_URL = (f"https://github.com/GameTechDev/PresentMon/releases/download/v{PRESENTMON_VERSION}/"
f"PresentMon-{PRESENTMON_VERSION}-x64.exe")
PRESENTMON_SHA256 = "b2a706bc6ad475749e3b7e3409263aa1e6906d45bdcf993f6dbc0f660188f1af"
WINDOW_S = 60
SETTLE_S = 5 # Jarvis busy (or yielding) before a window starts
HITCH_MS = (50, 100) # a frame this long is a visible hitch
MIN_FRAMES = 300 # under this in a minute (5 fps) the game was not really drawing
ROUNDS = ("busy", "busy_yield", "busy_yield_2", "busy_2")
# The foreground window belongs to one of these when the user did not get back to the game.
NOT_A_GAME = {"windowsterminal.exe", "openconsole.exe", "conhost.exe", "cmd.exe", "powershell.exe",
"pwsh.exe", "explorer.exe"}
# Windows' values: process priority classes and D3DKMT_SCHEDULINGPRIORITYCLASS.
CPU_NORMAL, CPU_BELOW_NORMAL = 0x20, 0x4000
GPU_NORMAL, GPU_BELOW_NORMAL = 2, 1
GAME_LEVEL = next(lv for lv in llm.TOGETHER if lv["key"] == "game_experts_2g_16k_stt_gpu")
# --------------------------------------------------------------------------
# Windows: rights, the game's process, priorities.
def is_admin() -> bool:
if not IS_WINDOWS:
return False
import ctypes
try:
return bool(ctypes.windll.shell32.IsUserAnAdmin())
except Exception:
return False
def foreground_process() -> tuple[int, str] | None:
"""(pid, exe file name in lower case) of the window in front, or None."""
if not IS_WINDOWS:
return None
import ctypes
from ctypes import wintypes
user32 = ctypes.WinDLL("user32")
k32 = ctypes.WinDLL("kernel32")
user32.GetForegroundWindow.restype = ctypes.c_void_p
user32.GetWindowThreadProcessId.argtypes = [ctypes.c_void_p, ctypes.POINTER(wintypes.DWORD)]
k32.OpenProcess.restype = ctypes.c_void_p
k32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
k32.QueryFullProcessImageNameW.argtypes = [ctypes.c_void_p, wintypes.DWORD, wintypes.LPWSTR,
ctypes.POINTER(wintypes.DWORD)]
k32.CloseHandle.argtypes = [ctypes.c_void_p]
hwnd = user32.GetForegroundWindow()
if not hwnd:
return None
pid = wintypes.DWORD()
user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
h = k32.OpenProcess(0x1000, False, pid.value) # PROCESS_QUERY_LIMITED_INFORMATION
name = ""
if h:
try:
buf = ctypes.create_unicode_buffer(1024)
n = wintypes.DWORD(len(buf))
if k32.QueryFullProcessImageNameW(h, 0, buf, ctypes.byref(n)):
name = Path(buf.value).name.lower()
finally:
k32.CloseHandle(h)
return pid.value, name
_API: dict = {}
def _api() -> dict:
import ctypes
from ctypes import wintypes
if not _API:
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
gdi = ctypes.WinDLL("gdi32")
k32.OpenProcess.restype = ctypes.c_void_p
k32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
k32.CloseHandle.argtypes = [ctypes.c_void_p]
k32.GetPriorityClass.argtypes = [ctypes.c_void_p]
k32.GetPriorityClass.restype = wintypes.DWORD
k32.SetPriorityClass.argtypes = [ctypes.c_void_p, wintypes.DWORD]
gdi.D3DKMTGetProcessSchedulingPriorityClass.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)]
gdi.D3DKMTGetProcessSchedulingPriorityClass.restype = ctypes.c_long
gdi.D3DKMTSetProcessSchedulingPriorityClass.argtypes = [ctypes.c_void_p, ctypes.c_int]
gdi.D3DKMTSetProcessSchedulingPriorityClass.restype = ctypes.c_long
_API.update(k32=k32, gdi=gdi, ctypes=ctypes)
return _API
def get_priority(pid: int) -> tuple[int | None, int | None]:
"""(CPU priority class, GPU scheduling priority class) of a process; None where unreadable."""
a = _api()
h = a["k32"].OpenProcess(0x0200 | 0x1000, False, pid) # SET_INFORMATION | QUERY_LIMITED
if not h:
return None, None
try:
cpu = a["k32"].GetPriorityClass(h) or None
val = a["ctypes"].c_int()
gpu = val.value if a["gdi"].D3DKMTGetProcessSchedulingPriorityClass(h, a["ctypes"].byref(val)) == 0 else None
return cpu, gpu
finally:
a["k32"].CloseHandle(h)
def set_priority(pid: int, cpu: int | None, gpu: int | None) -> tuple[bool, bool]:
"""Set what is given; (CPU done, GPU done)."""
a = _api()
h = a["k32"].OpenProcess(0x0200 | 0x1000, False, pid)
if not h:
return False, False
try:
ok_cpu = cpu is None or bool(a["k32"].SetPriorityClass(h, cpu))
ok_gpu = gpu is None or a["gdi"].D3DKMTSetProcessSchedulingPriorityClass(h, gpu) == 0
return ok_cpu, ok_gpu
finally:
a["k32"].CloseHandle(h)
class Yield:
"""Jarvis's processes at below-normal CPU and GPU priority while the block runs, put back after.
Each lowering is read back, so a priority Windows ignored does not count as lowered."""
def __init__(self, pids: list[int]):
self.pids = list(pids)
self.before: dict[int, tuple[int | None, int | None]] = {}
self.cpu_lowered = self.gpu_lowered = self.restored = 0
self.not_restored: list[int] = []
def __enter__(self) -> "Yield":
for pid in self.pids:
self.before[pid] = get_priority(pid)
set_priority(pid, CPU_BELOW_NORMAL, GPU_BELOW_NORMAL)
cpu, gpu = get_priority(pid)
self.cpu_lowered += cpu == CPU_BELOW_NORMAL
self.gpu_lowered += gpu == GPU_BELOW_NORMAL
return self
def __exit__(self, *exc) -> None:
for pid, (cpu, gpu) in self.before.items():
ok = set_priority(pid, cpu or CPU_NORMAL, GPU_NORMAL if gpu is None else gpu)
if all(ok):
self.restored += 1
else:
self.not_restored.append(pid)
def summary(self) -> dict:
return {"processes": len(self.pids), "cpu_lowered": self.cpu_lowered, "gpu_lowered": self.gpu_lowered,
"restored": self.restored, "not_restored": len(self.not_restored)}
def yield_problems(summary: dict) -> list[str]:
"""Why a yielding window did not yield: no process, nothing lowered, or a priority not put back."""
out = []
if not summary.get("processes"):
out.append("yield found no Jarvis process")
elif not summary.get("cpu_lowered") and not summary.get("gpu_lowered"):
out.append("yield lowered no priority")
if summary.get("not_restored"):
out.append(f"{summary['not_restored']} process(es) kept the lowered priority")
return out
# --------------------------------------------------------------------------
# PresentMon and the frame times.
def ensure_presentmon(work: Path) -> Path:
exe = work / "tools" / f"PresentMon-{PRESENTMON_VERSION}-x64.exe"
if exe.exists() and hashlib.sha256(exe.read_bytes()).hexdigest() == PRESENTMON_SHA256:
return exe
exe.parent.mkdir(parents=True, exist_ok=True)
part = exe.with_suffix(".part")
with urllib.request.urlopen(PRESENTMON_URL, timeout=120) as resp:
part.write_bytes(resp.read())
got = hashlib.sha256(part.read_bytes()).hexdigest()
if got != PRESENTMON_SHA256:
part.unlink()
raise RuntimeError(f"PresentMon download has the wrong hash ({got[:12]})")
part.replace(exe)
return exe
def presentmon_cmd(exe: Path, pid: int, seconds: int, out_csv: Path) -> list[str]:
return [str(exe), "--process_id", str(pid), "--output_file", str(out_csv), "--timed", str(seconds),
"--terminate_after_timed", "--no_console_stats", "--v1_metrics", "--no_track_input",
"--session_name", "JarvisM0", "--stop_existing_session"]
def capture(exe: Path, pid: int, seconds: int, out_csv: Path, log: Path) -> tuple[list[dict], str | None]:
"""The game's frames over ``seconds`` (rows of PresentMon's CSV) and an error, if any. The CSV
names the game, so it is deleted as soon as it is read."""
out_csv.unlink(missing_ok=True)
with open(log, "a", encoding="utf-8") as f:
try:
p = subprocess.run(presentmon_cmd(exe, pid, seconds, out_csv), stdout=f, stderr=subprocess.STDOUT,
timeout=seconds + 60)
code = p.returncode
except subprocess.TimeoutExpired:
code = "timeout"
try:
text = out_csv.read_text(encoding="utf-8", errors="replace")
except OSError:
return [], f"PresentMon wrote no frames (exit {code})"
finally:
out_csv.unlink(missing_ok=True)
return parse_csv(text), None if code == 0 else f"PresentMon exited with {code}"
def parse_csv(text: str) -> list[dict]:
"""PresentMon's rows with lower-case column names (1.x writes msBetweenPresents, 2.x MsBetweenPresents)."""
return [{(k or "").strip().lower(): (v or "").strip() for k, v in row.items()}
for row in csv.DictReader(io.StringIO(text))]
def _num(value: str) -> float | None:
try:
return float(value)
except (TypeError, ValueError):
return None
def frame_stats(rows: list[dict], seconds: float) -> dict:
"""Frame rate, 1 % low (the 99th-percentile frame time as a rate) and hitches of the game's main
swap chain (the one with the most frames)."""
chains: dict[str, list[dict]] = {}
for x in rows:
chains.setdefault(x.get("swapchainaddress", ""), []).append(x)
main = max(chains.values(), key=len) if chains else []
ms = [v for v in (_num(x.get("msbetweenpresents")) for x in main[1:]) if v is not None and v > 0]
out: dict[str, Any] = {"seconds": round(seconds, 1), "frames": len(ms)}
if not ms:
return {**out, "valid": False, "invalid_because": ["the game drew no frames"]}
srt = sorted(ms)
p99 = srt[min(len(srt) - 1, int(len(srt) * 0.99))]
out.update(fps=round(len(ms) / (sum(ms) / 1000), 1), low1_fps=round(1000 / p99, 1),
p99_ms=round(p99, 2), max_ms=round(srt[-1], 1),
hitches_over_ms={str(h): sum(v > h for v in ms) for h in HITCH_MS},
not_shown=sum(x.get("dropped") == "1" for x in main[1:]))
reasons = []
if len(ms) < MIN_FRAMES * seconds / 60:
reasons.append(f"the game drew only {len(ms)} frames")
out["valid"] = not reasons
if reasons:
out["invalid_because"] = reasons
return out
def compare(rows: list[dict]) -> dict:
"""The game alone, next to busy Jarvis and next to yielding Jarvis, over the valid windows, with
the change against the game alone in per cent."""
def pool(kind: str) -> dict:
valid = [x["game"] for x in rows if x.get("kind") == kind and (x.get("game") or {}).get("valid")]
if not valid:
return {"windows": 0}
n = len(valid)
return {"windows": n, "fps": round(sum(v["fps"] for v in valid) / n, 1),
"low1_fps": round(sum(v["low1_fps"] for v in valid) / n, 1),
**{f"hitches_over_{h}ms": sum(v["hitches_over_ms"][str(h)] for v in valid) for h in HITCH_MS}}
out = {k: pool(k) for k in ("off", "busy", "busy_yield")}
off = out["off"]
for k in ("busy", "busy_yield"):
if off["windows"] and out[k]["windows"]:
out[k]["vs_off_pct"] = {m: round((out[k][m] - off[m]) / off[m] * 100, 1) for m in ("fps", "low1_fps")}
return out
# --------------------------------------------------------------------------
# Jarvis busy for as long as a window lasts.
class BusyLlm:
"""The LLM answering back to back (a long answer, then a voice answer) until the block ends."""
def __init__(self, c: ChatClient):
self.c = c
self.stop = threading.Event()
self.decode: list[float] = []
self.voice: list[float] = []
self.errors: list[str] = []
self.thread = threading.Thread(target=self._loop, daemon=True)
def _loop(self) -> None:
voice = [p for kind, p in KOREAN_PROMPTS if kind == "voice"]
i = 0
while not self.stop.is_set():
try:
a = self.c.chat([{"role": "user", "content": f"({i}) 한국의 사계절을 각각 세 문장씩 자세히 설명해 줘."}],
max_tokens=320, extra=NO_THINK)
if a.get("decode_tok_s"):
self.decode.append(a["decode_tok_s"])
if voice and not self.stop.is_set():
a = self.c.chat([{"role": "system", "content": VOICE_SYSTEM},
{"role": "user", "content": voice[i % len(voice)]}], max_tokens=120, extra=NO_THINK)
if a.get("first_sentence") is not None:
self.voice.append(a["first_sentence"])
except Exception as e:
self.errors.append(f"{type(e).__name__}")
if len(self.errors) > 20:
return
time.sleep(1)
i += 1
def __enter__(self) -> "BusyLlm":
self.thread.start()
return self
def __exit__(self, *exc) -> None:
self.stop.set()
self.thread.join(timeout=120)
def summary(self) -> dict:
return {"decode_tok_s": stats(self.decode), "voice_first_sentence": stats(self.voice),
"errors": sorted(set(self.errors))}
# --------------------------------------------------------------------------
# The stage.
def ask_for_a_game() -> bool:
if not interactive():
return False
say(" 게임을 켠 채로 게임 화면의 프레임을 잽니다. 10~15분 걸립니다.")
if ask(" 지금 게임을 켜고 재시겠습니까?") != "y":
return False
wait_enter(" 게임을 켜고 플레이 화면까지 들어간 뒤 Enter를 누르고, 15초 안에 게임으로 돌아가 주세요. "
"끝날 때까지 캐릭터를 한자리에 세워 두고 마우스·키보드에 손대지 말아 주세요. 끝나면 알림음이 울립니다:")
time.sleep(15)
return True
def measure(r: StageResult, s: "llm.Strata", preset: dict, context: int, stt_python: str) -> None:
work = s.log.parent.parent
pm_log = s.log.with_name("presentmon.log")
rows: list[dict] = []
r["frame_rows"] = rows
if not is_admin():
r.error("admin", "게임 프레임은 관리자 권한이 있어야 잴 수 있습니다. run_m0_game_frames.bat으로 실행해 주세요.")
return
try:
pm = ensure_presentmon(work)
except Exception as e:
r.error("presentmon", e)
return
r["presentmon"] = PRESENTMON_VERSION
if not ask_for_a_game():
r["skipped"] = "no game started"
return
fg = foreground_process()
if fg is None or fg[1] in NOT_A_GAME:
r.error("game", "게임 창이 앞에 없었습니다. 게임으로 돌아간 뒤 다시 실행해 주세요.")
return
game = fg[0]
r.note("measured while the user's game was running (its name is not kept)")
base = f"http://127.0.0.1:{llm.PORT}/v1"
def window(key: str, kind: str) -> dict:
x: dict = {"key": key, "kind": kind}
used = gpu_memory_mib()
if used:
x["vram_free_mib"] = used[1] - used[0]
with gpucap.UtilSampler() as util:
frames, err = capture(pm, game, WINDOW_S, work / "cache" / "frames.csv", pm_log)
g = frame_stats(frames, WINDOW_S)
g["gpu_util"] = util.summary()
now = foreground_process()
if now is not None and now[0] != game:
g["valid"] = False
g["invalid_because"] = g.get("invalid_because", []) + ["the game was not in front at the end"]
if err:
r.error(f"frames {key}", err)
x["game"] = g
rows.append(x)
if not g["valid"]:
r.note(f"{key}: not counted ({'; '.join(g['invalid_because'])})")
say(f" {key}: {g.get('fps')} fps, 1% low {g.get('low1_fps')} fps, "
f"{HITCH_MS[0]}ms 넘는 프레임 {(g.get('hitches_over_ms') or {}).get(str(HITCH_MS[0]))}개")
r.save()
return x
stt = None
try:
say(" - 게임만")
window("game_only", "off")
say(" - Jarvis 켜기 (게임 중 배치: 전문가 2GB, 맥락 16K, 음성 인식 GPU)")
s.stop()
stt = llm.SttLoad(stt_python, work, "cuda", s.log.with_name("stt_load.log"), pace=llm._FINALS_ONLY)
load = stt.start()
r["stt_load"] = load
if load.get("status") != "loaded":
r.error("frames stt", "; ".join(load.get("errors") or []) or "the STT did not load")
return
lv = GAME_LEVEL
r["placement"] = {"key": lv["key"], "sets": lv["sets"], "context": lv["context"], "parallel": lv["parallel"],
"vision": lv["vision"], "stt_pace": llm._FINALS_ONLY}
launch = s.launch(preset, lv["context"], parallel=lv["parallel"], vision=lv["vision"],
extra_sets=list(lv["sets"]), timeout=3600)
if not launch.get("ready"):
r.error("frames llm", "the game placement did not start")
return
c = ChatClient(base)
r["server"] = {"model": c.model}
c.chat([{"role": "user", "content": "안녕"}], max_tokens=8)
say(" - Jarvis 켜 두고 쉬는 중")
window("jarvis_idle", "idle")
stt.go()
for key in ROUNDS:
yielding = "yield" in key
say(f" - Jarvis가 답하고 음성 인식이 최종 전사를 하는 중{' (게임에 양보)' if yielding else ''}")
pids = llm.cap_pids(s, stt) if yielding else []
y = Yield(pids)
with y if yielding else contextlib.nullcontext(), BusyLlm(c) as busy:
time.sleep(SETTLE_S)
x = window(key, "busy_yield" if yielding else "busy")
x["llm"] = busy.summary()
for err in x["llm"]["errors"]:
r.error(f"frames {key} llm", err)
if yielding:
x["yield"] = y.summary()
problems = yield_problems(x["yield"])
for why in problems:
r.error(f"frames {key} yield", why)
if problems:
x["game"]["valid"] = False
x["game"]["invalid_because"] = x["game"].get("invalid_because", []) + problems
r.save()
busy_stt = stt.finish()
r["stt_busy"] = {k: busy_stt.get(k) for k in ("status", "single_s", "errors", "final_wait_s")
if k in busy_stt}
for err in llm.stt_gaps(busy_stt, llm._FINALS_ONLY):
r.error("frames stt", err)
stt.close()
stt = None
s.stop()
say(" - Jarvis 끄고 게임만 다시")
window("game_only_again", "off")
r["comparison"] = compare(rows)
except Exception as e:
r.error("frames", e)
finally:
if stt:
stt.close()
s.stop()
say("\a 게임 프레임 측정이 끝났습니다. 게임을 꺼도 됩니다.")
try:
import winsound
winsound.MessageBeep()
except Exception:
pass

View File

@@ -15,6 +15,8 @@ Options (--opt key=value):
while the LLM answers, and both with Jarvis capped at 95 % of the GPU
only=video a YouTube video's dropped frames with Jarvis off, idle and busy (the
normal placement), busy also with the 95 % GPU cap (video.py)
only=frames the user's game's frame times with Jarvis off, idle and busy (the game
placement), busy also yielding to the game by priority (frames.py)
stt_python=PATH the Python of the stt venv (m0.py passes it)
"""
@@ -663,7 +665,7 @@ def measure_external(r: StageResult, url: str, context: int, only: str = "") ->
if only == "tools":
tools_only(r, c)
return
if only in LEVEL_SETS or only == "video":
if only in LEVEL_SETS or only in ("video", "frames"):
r.note("placements need Strata; not measured against an external server")
return
with GpuSampler() as g:
@@ -682,7 +684,7 @@ def measure_strata(r: StageResult, work: Path, which: str, context: int, only: s
return
r["plan"] = s.plan(preset, context)
r.save()
if only in LEVEL_SETS or only == "video":
if only in LEVEL_SETS or only in ("video", "frames"):
s.stop()
if port_in_use(PORT):
r.error("port", f"다른 프로그램이 {PORT} 포트를 쓰고 있습니다. 그 프로그램을 끄고 다시 실행해 주세요.")
@@ -694,6 +696,10 @@ def measure_strata(r: StageResult, work: Path, which: str, context: int, only: s
from m0lib import video
video.measure(r, s, preset, context, stt_python)
return
if only == "frames":
from m0lib import frames
frames.measure(r, s, preset, context, stt_python)
return
if only == "live":
if not ask_for_a_game():
r["skipped"] = "no game started"
@@ -778,7 +784,8 @@ def main() -> int:
context = int(opts.get("context", "32768"))
only = opts.get("only", "")
name = {"tools": f"tools_{which}", "levels": "gamemode", "together": "gamemode_stt",
"live": "gamemode_live", "tune": "gamemode_tune", "video": "video_drops"}.get(only, f"llm_{which}")
"live": "gamemode_live", "tune": "gamemode_tune", "video": "video_drops",
"frames": "game_frames"}.get(only, f"llm_{which}")
r = StageResult(name, out)
try:
if opts.get("url"):

View File

@@ -0,0 +1,12 @@
@echo off
chcp 65001 >nul
rem The game's frame times come from Windows event tracing, which needs administrator rights.
rem Ask once here, before the game is started, so no prompt pops up over the game.
net session >nul 2>&1
if errorlevel 1 (
powershell -NoProfile -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
exit /b
)
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0run_m0.ps1" -Only game_frames -Redo %*
echo.
pause

View File

@@ -1655,3 +1655,189 @@ def test_a_player_that_never_comes_back_is_tried_again_per_window_and_the_stage_
assert cdp.navigated >= len(rows) * (video.ATTEMPTS - 1)
assert not any("seekTo" in e["error"] for e in r["errors"])
assert closed and running["now"] is None and stt.loaded is None and not running["held"]
# --- game_frames: the user's game's frame times next to Jarvis, plain and yielding by priority --
_PM_HEAD = ("Application,ProcessID,SwapChainAddress,Runtime,SyncInterval,PresentFlags,Dropped,TimeInSeconds,"
"msInPresentAPI,msBetweenPresents\n")
def _pm_csv(frames_ms, chain="0x1", pid=7000, dropped=(), head=_PM_HEAD):
t, lines = 0.0, []
for i, ms in enumerate(frames_ms):
t += ms / 1000
lines.append(f"game.exe,{pid},{chain},DXGI,0,0,{1 if i in dropped else 0},{t:.4f},0.1,{ms}")
return head + "\n".join(lines) + "\n"
def test_frame_stats_read_the_main_swap_chain_with_rate_one_percent_low_and_hitches():
from m0lib import frames
main = [10.0] * 200 + [60.0, 120.0]
text = _pm_csv(main, dropped={5}) + _pm_csv([500.0] * 5, chain="0x2", head="")
g = frames.frame_stats(frames.parse_csv(text), 3.0)
counted = main[1:] # the first row's interval reaches back before the capture
assert g["valid"] and g["frames"] == len(counted)
assert g["fps"] == round(len(counted) / (sum(counted) / 1000), 1)
p99 = sorted(counted)[int(len(counted) * 0.99)]
assert g["low1_fps"] == round(1000 / p99, 1) and g["max_ms"] == 120.0
assert g["hitches_over_ms"] == {"50": 2, "100": 1} and g["not_shown"] == 1
def test_frame_stats_read_presentmon_2_column_names_too():
from m0lib import frames
text = _pm_csv([16.7] * 100).replace("msBetweenPresents", "MsBetweenPresents")
assert frames.frame_stats(frames.parse_csv(text), 1.5)["fps"] == round(1000 / 16.7, 1)
def test_a_window_where_the_game_drew_nothing_or_almost_nothing_is_not_counted():
from m0lib import frames
assert not frames.frame_stats([], 60)["valid"]
few = frames.frame_stats(frames.parse_csv(_pm_csv([1000.0] * 30)), 60)
assert not few["valid"] and "frames" in few["invalid_because"][0]
def test_compare_pools_the_valid_windows_against_the_game_alone():
from m0lib import frames
def row(kind, fps, low, valid=True):
return {"kind": kind, "game": {"valid": valid, "fps": fps, "low1_fps": low,
"hitches_over_ms": {str(h): 1 for h in frames.HITCH_MS}}}
c = frames.compare([row("off", 100, 80), row("idle", 99, 79), row("busy", 90, 60), row("busy_yield", 98, 76),
row("busy_yield", 10, 5, valid=False), row("busy", 90, 60), row("off", 100, 80)])
assert c["off"]["windows"] == 2 and c["busy_yield"]["windows"] == 1
assert c["busy"]["vs_off_pct"] == {"fps": -10.0, "low1_fps": -25.0}
assert c["busy_yield"]["vs_off_pct"] == {"fps": -2.0, "low1_fps": -5.0}
class _FakePriorities:
"""Process priorities as Windows keeps them; ``ignored`` pids accept nothing."""
def __init__(self, ignored=()):
self.now: dict = {}
self.ignored = set(ignored)
self.touched: set = set()
def get(self, pid):
return self.now.get(pid, (0x20, 2))
def set(self, pid, cpu, gpu):
self.touched.add(pid)
if pid in self.ignored:
return False, False
self.now[pid] = (cpu, gpu)
return True, True
def test_yield_lowers_cpu_and_gpu_priority_and_puts_back_what_each_process_had(monkeypatch):
from m0lib import frames
pr = _FakePriorities(ignored={3})
pr.now[2] = (0x8000, 2) # already above normal: it gets that back, not plain normal
monkeypatch.setattr(frames, "get_priority", pr.get)
monkeypatch.setattr(frames, "set_priority", pr.set)
with frames.Yield([1, 2, 3]) as y:
assert pr.now[1] == pr.now[2] == (frames.CPU_BELOW_NORMAL, frames.GPU_BELOW_NORMAL)
assert pr.now[1] == (0x20, 2) and pr.now[2] == (0x8000, 2)
s = y.summary()
assert s == {"processes": 3, "cpu_lowered": 2, "gpu_lowered": 2, "restored": 2, "not_restored": 1}
assert frames.yield_problems(s) == ["1 process(es) kept the lowered priority"]
assert frames.yield_problems(frames.Yield([]).summary()) == ["yield found no Jarvis process"]
def test_presentmon_records_only_the_game_for_a_fixed_time_and_a_bad_download_is_refused(tmp_path, monkeypatch):
from m0lib import frames
cmd = frames.presentmon_cmd(Path("pm.exe"), 7000, 60, Path("f.csv"))
assert cmd[cmd.index("--process_id") + 1] == "7000" and cmd[cmd.index("--timed") + 1] == "60"
assert "--terminate_after_timed" in cmd and "--output_file" in cmd
class _Resp:
def __enter__(self):
return self
def __exit__(self, *a):
return None
def read(self):
return b"not presentmon"
monkeypatch.setattr(frames.urllib.request, "urlopen", lambda url, timeout=0: _Resp())
with pytest.raises(RuntimeError, match="hash"):
frames.ensure_presentmon(tmp_path)
assert not list((tmp_path / "tools").iterdir())
GAME_PID = 7000
def _run_frames_stage(tmp_path, monkeypatch, fake_server, admin=True, front=(GAME_PID, "game.exe"), pr=None):
from m0lib import frames
pr = _FakePriorities() if pr is None else pr
captured = []
monkeypatch.setattr(frames, "is_admin", lambda: admin)
monkeypatch.setattr(frames, "ensure_presentmon", lambda work: Path("pm.exe"))
monkeypatch.setattr(frames, "ask_for_a_game", lambda: True)
monkeypatch.setattr(frames, "foreground_process", lambda: front)
monkeypatch.setattr(frames, "get_priority", pr.get)
monkeypatch.setattr(frames, "set_priority", pr.set)
monkeypatch.setattr(frames, "SETTLE_S", 0)
def capture(exe, pid, seconds, out_csv, log):
captured.append((pid, dict(pr.now)))
return frames.parse_csv(_pm_csv([16.0] * 4000, pid=pid)), None
monkeypatch.setattr(frames, "capture", capture)
stt = _FakeStt()
r, started, running = _run_levels_stage(tmp_path, monkeypatch, fake_server, _vram, only="frames",
extra_opts=["stt_python=py"], stt=stt)
return r, started, running, stt, pr, captured
def test_frames_stage_measures_the_game_alone_next_to_jarvis_idle_busy_and_yielding(
tmp_path, monkeypatch, fake_server):
from m0lib import frames
r, started, running, stt, pr, captured = _run_frames_stage(tmp_path, monkeypatch, fake_server)
assert r["stage"] == "game_frames" and r["status"] == "ok"
rows = r["frame_rows"]
# Alone first and last; idle before busy; plain and yielding rows alternate A B B A.
assert [x["kind"] for x in rows] == ["off", "idle", "busy", "busy_yield", "busy_yield", "busy", "off"]
assert all(x["game"]["valid"] for x in rows) and {pid for pid, _ in captured} == {GAME_PID}
for x in rows:
if x["kind"].startswith("busy"):
assert x["llm"]["decode_tok_s"]["n"] > 0 # the LLM answered during the window
# Jarvis runs the app's game placement, the STT doing finals only (no partials while it answers).
assert len(started) == 1 and started[0]["sets"] == frames.GAME_LEVEL["sets"]
assert stt.paces == [llm._FINALS_ONLY] and stt.events[:3] == ["stt_loaded", "llm_start", "stt_go"]
# Yielding lowers Jarvis's processes during those windows only, never the game, and puts them back.
jarvis = {20, 21, STT_LAUNCHER_PID, STT_LAUNCHER_PID + 1}
low = (frames.CPU_BELOW_NORMAL, frames.GPU_BELOW_NORMAL)
for (pid, prio), x in zip(captured, rows):
lowered = {p for p, v in prio.items() if v == low}
assert lowered == (jarvis if x["kind"] == "busy_yield" else set())
assert GAME_PID not in pr.touched and all(v == (0x20, 2) for v in pr.now.values())
assert set(r["comparison"]) == {"off", "busy", "busy_yield"} and r["comparison"]["busy_yield"]["windows"] == 2
assert running["now"] is None and stt.loaded is None
def test_frames_stage_needs_administrator_rights_and_the_game_in_front_before_starting_jarvis(
tmp_path, monkeypatch, fake_server):
r, started, _, stt, _, captured = _run_frames_stage(tmp_path, monkeypatch, fake_server, admin=False)
assert r["status"] == "failed" and not started and not stt.events and not captured
assert any("관리자" in e["error"] for e in r["errors"])
r, started, _, stt, _, captured = _run_frames_stage(tmp_path, monkeypatch, fake_server,
front=(1234, "windowsterminal.exe"))
assert r["status"] == "failed" and not started and not stt.events and not captured
def test_a_yield_that_lowered_nothing_does_not_count_as_a_yielding_window(tmp_path, monkeypatch, fake_server):
pr = _FakePriorities(ignored={20, 21, STT_LAUNCHER_PID, STT_LAUNCHER_PID + 1})
r, *_ = _run_frames_stage(tmp_path, monkeypatch, fake_server, pr=pr)
assert r["comparison"]["busy_yield"]["windows"] == 0 and r["comparison"]["busy"]["windows"] == 2
assert r["status"] == "partial" and any("lowered no priority" in e["error"] for e in r["errors"])
def test_frames_stage_is_on_demand_with_the_stt_python_and_an_elevating_one_click_runner():
import m0
assert "game_frames" in m0.ON_DEMAND and "game_frames" in m0.NEEDS_STT
bat = (Path(m0.KIT) / "run_m0_game_frames.bat").read_text(encoding="utf-8")
assert "-Only game_frames" in bat and "-Verb RunAs" in bat