From 457b8636fae2d9ac108d5f927ad3b1699a8a211a Mon Sep 17 00:00:00 2001 From: javis-bot Date: Wed, 11 Nov 2026 00:55:26 +0900 Subject: [PATCH] feat(m0): measure a YouTube video's dropped frames next to Jarvis User decision (2026-11-11): the 95 % GPU cap is off by default because gamemode_tune showed it did not lower nvidia-smi's utilisation and cost 6 to 10 % of the LLM's output. The worry behind it was a video stuttering next to Jarvis, so the new on-demand stage video_drops measures that: - A public Blender upload plays at 1080p60 in a throwaway Chrome/Edge profile (removed afterwards), driven over DevTools with a small standard-library WebSocket client, so no package is added to the already built venvs. - Each window counts the video's dropped frames (the player's own counter) and the gaps over 50/100 ms between shown frames (requestVideoFrameCallback); windows with an ad, a pause, the end or a new video are kept but not counted. - Rows: video alone, Jarvis idle (normal placement with the STT room and 1 GB for other programs), Jarvis busy (LLM answering, STT transcribing ten speakers back to back) without and with the cap in A B B A order, then the video alone again. The cap pauses the engine and the STT worker only, never the browser. - run_m0_video.bat runs just this stage. Co-Authored-By: Claude Opus 5.5 --- scripts/m0/README.md | 6 +- scripts/m0/m0.py | 10 +- scripts/m0/m0lib/gpucap.py | 4 +- scripts/m0/m0lib/llm.py | 12 +- scripts/m0/m0lib/video.py | 512 ++++++++++++++++++++++++++++++++++++ scripts/m0/run_m0_video.bat | 5 + tests/test_m0_kit.py | 205 +++++++++++++++ 7 files changed, 746 insertions(+), 8 deletions(-) create mode 100644 scripts/m0/m0lib/video.py create mode 100644 scripts/m0/run_m0_video.bat diff --git a/scripts/m0/README.md b/scripts/m0/README.md index 22cc384..9ecfd24 100644 --- a/scripts/m0/README.md +++ b/scripts/m0/README.md @@ -37,6 +37,7 @@ LLM 단계는 8080 포트를 씁니다. 다른 프로그램이 이 포트를 쓰 | PC 제어 도구 | agent-desktop으로 계산기 버튼을 눌러 12+3=15가 나오는지, 테스트용 브라우저 창(새 임시 프로필)의 입력칸에 글자를 넣고 다시 읽히는지, 디스코드·탐색기 화면을 읽는 시간, 계속 켜 두는 방식(MCP)과 매번 실행하는 방식의 명령 한 번 시간 | | 게임 중 자동 조절 | 이미 받은 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% 제한 없이와 있을 때)의 끊긴 프레임 수와 긴 멈춤 횟수 | | STT 자리와 부분 전사 간격 | 평소 배치를 STT 자리를 남긴 전문가 층 몫으로 켜고 STT를 쉬지 않고 돌리며 잽니다. 게임 중 배치(전문가 2GB)는 STT를 쉬지 않고 돌릴 때, 부분 전사를 2초마다 할 때, 부분 전사 없이 최종 전사만 할 때를 잽니다(게임은 켜지 않음). 배치마다 남는 VRAM, LLM 속도, 최종 전사 시간과 기다린 시간, STT가 GPU를 쓴 비율을 적습니다 | ## 개인정보 @@ -46,6 +47,7 @@ LLM 단계는 8080 포트를 씁니다. 다른 프로그램이 이 포트를 쓰 - 다른 프로그램의 창 제목은 저장하지 않습니다. 디스코드 분리 창 제목은 저장해도 되는지 물어본 뒤에만 넣습니다. - 게임 감지는 실행 중인 프로그램 이름과 창 모양만 봅니다. 게임 화면은 저장하지 않습니다. 설치된 게임은 이름과 안티치트 유무만 기록합니다. - 음성 테스트는 키트에 들어 있는 합성 음성만 씁니다. 마이크는 쓰지 않습니다. +- 영상 끊김 단계(`video_drops`)는 유튜브에 공개된 Blender 영상을 새 임시 브라우저 프로필로 엽니다. 로그인하지 않고, 평소 쓰시는 프로필은 건드리지 않으며, 끝나면 그 임시 프로필을 지웁니다. 저장하는 것은 영상의 프레임 수, 끊긴 프레임 수, 화질, 광고가 나왔는지뿐입니다. - PC 제어 도구 단계는 다른 프로그램의 창 제목과 화면 글자를 저장하지 않습니다. 개수, 걸린 시간, 오류 코드, 계산기 결과 숫자만 저장합니다. 이미 켜 둔 계산기가 있으면 건드리지 않고 그 확인을 건너뛰며, 브라우저는 평소 쓰시는 프로필이 아닌 새 임시 프로필로 엽니다. ## 옵션 (PowerShell에서 직접 실행할 때) @@ -56,7 +58,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`(이 단계는 `-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`(마지막 두 단계는 `-Only`로 고를 때만 돕니다) `tools_fast`, `tools_recommended`는 도구 호출만 다시 잽니다. 처음과 같은 방식(고치기 전)과, 자비스의 수정(지시문 규칙, 계획 단계, 건너뛴 도구 직접 실행)을 넣은 방식을 같은 모델로 비교합니다. 이미 받은 모델을 쓰므로 모델 하나에 몇 분이면 끝납니다. @@ -72,4 +74,6 @@ LLM 단계는 8080 포트를 씁니다. 다른 프로그램이 이 포트를 쓰 `run_m0_game_live.bat`을 더블클릭하면 실제 게임을 켠 상태로 잽니다(`gamemode_live`). 게임을 창 모드로 켜고 플레이 화면까지 들어간 뒤 Enter를 누르고 15초 안에 게임으로 돌아가면 됩니다. 게임 중 배치 4개(전문가 2GB·0GB, 음성 인식 GPU·CPU)를 차례로 재고 10~15분 걸리며, 끝나면 알림음이 울립니다. 게임 화면이나 게임 이름은 저장하지 않고 VRAM 사용량과 속도만 적습니다. 그래픽 메모리를 많이 쓰는 게임이면 배치가 켜지지 않을 수 있는데, 그것도 결과로 적습니다. +`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에 손대지 않으시면 됩니다. 인터넷으로 영상을 받으므로 네트워크가 느리면 버퍼링도 따로 적습니다. + 다 끝나고 필요 없으면 작업 폴더(`\JarvisM0`)를 통째로 지우면 됩니다. Python, 모델, Strata(엔진과 설정 포함)는 모두 그 안에 설치하도록 지정해 두었습니다. diff --git a/scripts/m0/m0.py b/scripts/m0/m0.py index 7c944af..2c1af3b 100644 --- a/scripts/m0/m0.py +++ b/scripts/m0/m0.py @@ -51,14 +51,18 @@ STAGES = [ # STT partial passes while the LLM answers (normal and the 2 GB game placement). ("gamemode_tune", "자동 조절: STT 자리와 VRAM 여유 1GB, 부분 전사 간격, GPU 95% 제한", "base", "llm.py", ["model=fast", "only=tune"], 0), + # Does Jarvis make a YouTube video stutter, and does the 95 % GPU cap help (user decision 2026-11-11: + # 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), # 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. -ON_DEMAND = {"gamemode_live"} +# 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"} # 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"} +NEEDS_STT = {"gamemode_stt", "gamemode_tune", "gamemode_live", "video_drops"} def free_gb(path: Path) -> float: diff --git a/scripts/m0/m0lib/gpucap.py b/scripts/m0/m0lib/gpucap.py index 0d8418a..75ca925 100644 --- a/scripts/m0/m0lib/gpucap.py +++ b/scripts/m0/m0lib/gpucap.py @@ -1,4 +1,6 @@ -"""The GPU share cap the app would put on Jarvis (user decision, 2026-11-10: 95 %). +"""The GPU share cap the app can put on Jarvis (user decision, 2026-11-10: 95 %; 2026-11-11: off by +default, because gamemode_tune showed it did not lower the utilisation; video_drops measures whether +it keeps a video from stuttering). Jarvis's GPU work runs in two processes: the Strata engine and the voice worker (here the STT load worker). A GPU cannot be told to give one process only part of its time, so the cap pauses diff --git a/scripts/m0/m0lib/llm.py b/scripts/m0/m0lib/llm.py index e8d87fb..322200a 100644 --- a/scripts/m0/m0lib/llm.py +++ b/scripts/m0/m0lib/llm.py @@ -13,6 +13,8 @@ Options (--opt key=value): only=tune the normal placement with room left for the STT and 1 GB for other programs, the game placement with the STT doing fewer partial passes 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) stt_python=PATH the Python of the stt venv (m0.py passes it) """ @@ -661,7 +663,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: + if only in LEVEL_SETS or only == "video": r.note("placements need Strata; not measured against an external server") return with GpuSampler() as g: @@ -680,7 +682,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: + if only in LEVEL_SETS or only == "video": s.stop() if port_in_use(PORT): r.error("port", f"다른 프로그램이 {PORT} 포트를 쓰고 있습니다. 그 프로그램을 끄고 다시 실행해 주세요.") @@ -688,6 +690,10 @@ def measure_strata(r: StageResult, work: Path, which: str, context: int, only: s if only != "levels" and not stt_python: r.error("stt", "STT 환경을 찾지 못했습니다") return + if only == "video": + from m0lib import video + video.measure(r, s, preset, context, stt_python) + return if only == "live": if not ask_for_a_game(): r["skipped"] = "no game started" @@ -772,7 +778,7 @@ 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"}.get(only, f"llm_{which}") + "live": "gamemode_live", "tune": "gamemode_tune", "video": "video_drops"}.get(only, f"llm_{which}") r = StageResult(name, out) try: if opts.get("url"): diff --git a/scripts/m0/m0lib/video.py b/scripts/m0/m0lib/video.py new file mode 100644 index 0000000..1f5b35b --- /dev/null +++ b/scripts/m0/m0lib/video.py @@ -0,0 +1,512 @@ +"""Stage part: does Jarvis make a video stutter, and does the 95 % GPU cap help? + +User decision (2026-11-11): the cap's default is off, because gamemode_tune showed it did not lower +nvidia-smi's utilisation and cost 6 to 10 % of the LLM's output. What the user cared about is a +video next to Jarvis, so that is measured directly: a YouTube video plays in a throwaway Chrome/Edge +profile (never the user's) and the kit counts its dropped frames and long gaps between shown frames +with Jarvis off, Jarvis loaded and idle, and Jarvis busy (the LLM answering, the STT transcribing ten +speakers back to back) without and with the cap. The busy rows run in the order A B B A (no cap, +cap, cap, no cap) so a slow drift does not count for one side. + +The browser is driven through the Chrome DevTools Protocol with a small standard-library WebSocket +client (the kit's venvs are already built, so no package is added). Nothing from the page is saved +except the video's own counters, its quality and whether an ad was showing. +""" + +from __future__ import annotations + +import base64 +import json +import os +import shutil +import socket +import struct +import subprocess +import time +import urllib.parse +from pathlib import Path +from typing import Any, Callable + +from m0lib import gpucap, llm +from m0lib.common import IS_WINDOWS, StageResult, gpu_memory_mib, say +from m0lib.llm_client import ChatClient, http_json + +# Blender's own upload (CC BY 3.0, 10:34, 4K and 1080p at 60 fps): no music claim, rarely ads. +VIDEO_URL = "https://www.youtube.com/watch?v=aqz-KE-bpKQ" +QUALITY = "hd1080" +QUIET_S = 60 # the video alone, and Jarvis loaded but idle +SETTLE_S = 5 # after a quality change or a seek, before a window starts +MIN_LEFT_S = 240 # a window that could reach the end starts the video again first +GAP_MS = (50, 100) # a gap between shown frames this long is a visible hitch at 60 fps +ROUNDS = ("busy", "busy_cap95", "busy_cap95_2", "busy_2") + + +# -------------------------------------------------------------------------- +# A minimal WebSocket client (RFC 6455) for one DevTools page. + +def encode_frame(payload: bytes, opcode: int = 1, mask: bytes | None = None) -> bytes: + """One final client frame; a client must mask what it sends.""" + mask = mask or os.urandom(4) + n = len(payload) + if n < 126: + head = bytes([0x80 | opcode, 0x80 | n]) + elif n < 1 << 16: + head = bytes([0x80 | opcode, 0x80 | 126]) + struct.pack(">H", n) + else: + head = bytes([0x80 | opcode, 0x80 | 127]) + struct.pack(">Q", n) + return head + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(payload)) + + +class Cdp: + """One DevTools WebSocket: ``call`` sends a command and returns its result, skipping events.""" + + def __init__(self, ws_url: str, timeout: float = 60, sock: socket.socket | None = None): + self._buf = b"" + self._id = 0 + if sock is not None: # tests hand in one end of a socket pair, already "upgraded" + self.sock = sock + return + u = urllib.parse.urlparse(ws_url) + self.sock = socket.create_connection((u.hostname, u.port), timeout=timeout) + key = base64.b64encode(os.urandom(16)).decode() + # No Origin header: Chrome only checks --remote-allow-origins when one is sent. + self.sock.sendall((f"GET {u.path} HTTP/1.1\r\nHost: {u.hostname}:{u.port}\r\nUpgrade: websocket\r\n" + f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n" + ).encode()) + while b"\r\n\r\n" not in self._buf: + self._more() + head, self._buf = self._buf.split(b"\r\n\r\n", 1) + if b" 101 " not in head.split(b"\r\n", 1)[0]: + raise ConnectionError(f"DevTools refused the WebSocket: {head[:200]!r}") + + def _more(self) -> None: + got = self.sock.recv(65536) + if not got: + raise ConnectionError("DevTools closed the connection") + self._buf += got + + def _take(self, n: int) -> bytes: + while len(self._buf) < n: + self._more() + out, self._buf = self._buf[:n], self._buf[n:] + return out + + def _frame(self) -> tuple[bool, int, bytes]: + b0, b1 = self._take(2) + n = b1 & 0x7F + if n == 126: + n = struct.unpack(">H", self._take(2))[0] + elif n == 127: + n = struct.unpack(">Q", self._take(8))[0] + mask = self._take(4) if b1 & 0x80 else None + data = self._take(n) + if mask: + data = bytes(b ^ mask[i % 4] for i, b in enumerate(data)) + return bool(b0 & 0x80), b0 & 0x0F, data + + def recv(self) -> str: + """The next whole text message; answers pings, raises on close.""" + parts: list[bytes] = [] + while True: + fin, op, data = self._frame() + if op == 8: + raise ConnectionError("DevTools closed the WebSocket") + if op == 9: + self.sock.sendall(encode_frame(data, opcode=10)) + continue + if op == 10: + continue + parts.append(data) + if fin: + return b"".join(parts).decode("utf-8", "replace") + + def call(self, method: str, params: dict | None = None) -> dict: + self._id += 1 + mine = self._id + self.sock.sendall(encode_frame(json.dumps({"id": mine, "method": method, "params": params or {}}).encode())) + while True: + msg = json.loads(self.recv()) + if msg.get("id") != mine: + continue # an event, or the answer to a command that timed out earlier + if "error" in msg: + raise RuntimeError(f"{method}: {msg['error']}") + return msg.get("result") or {} + + def evaluate(self, expression: str) -> Any: + res = self.call("Runtime.evaluate", {"expression": expression, "returnByValue": True}) + if res.get("exceptionDetails"): + d = res["exceptionDetails"] + raise RuntimeError(f"page script failed: {(d.get('exception') or {}).get('description') or d.get('text')}") + return (res.get("result") or {}).get("value") + + def close(self) -> None: + try: + self.sock.close() + except OSError: + pass + + +# -------------------------------------------------------------------------- +# The page: what runs inside YouTube's watch page. + +# Counts shown frames (requestVideoFrameCallback runs once per frame put on screen), the long gaps +# between them, buffering and ads; installed again if YouTube swaps the