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 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-11 00:55:26 +09:00
parent a4f77c3261
commit 457b8636fa
7 changed files with 746 additions and 8 deletions

View File

@@ -1206,3 +1206,208 @@ def test_a_suspend_or_resume_that_raises_does_not_end_the_cap_with_processes_pau
with gpucap.DutyCap([1], 0.9, period=0.02, suspend=procs.suspend, resume=resume) as d:
_time.sleep(0.2)
assert procs.count[1] == 0 and d.summary()["left_paused"] == 0
# --- video_drops: a YouTube video's dropped frames next to Jarvis, with and without the cap --
def _server_frame(payload: bytes, opcode: int = 1, fin: bool = True) -> bytes:
"""A frame as Chrome sends it (servers do not mask)."""
import struct
n = len(payload)
head = bytes([(0x80 if fin else 0) | opcode])
if n < 126:
head += bytes([n])
elif n < 1 << 16:
head += bytes([126]) + struct.pack(">H", n)
else:
head += bytes([127]) + struct.pack(">Q", n)
return head + payload
def _read_client_frame(sock) -> tuple[int, bytes]:
"""Unmask one frame the client sent (clients must mask)."""
import struct
b0, b1 = sock.recv(2)
n = b1 & 0x7F
if n == 126:
n = struct.unpack(">H", sock.recv(2))[0]
elif n == 127:
n = struct.unpack(">Q", sock.recv(8))[0]
assert b1 & 0x80, "a client frame must be masked"
mask = sock.recv(4)
data = b""
while len(data) < n:
data += sock.recv(n - len(data))
return b0 & 0x0F, bytes(b ^ mask[i % 4] for i, b in enumerate(data))
def test_devtools_call_returns_its_own_answer_across_events_pings_and_fragments():
import socket
from m0lib import video
ours, chrome = socket.socketpair()
cdp = video.Cdp("", sock=ours)
big = json.dumps({"id": 1, "result": {"result": {"value": "x" * 70000}}}).encode()
chrome.sendall(_server_frame(json.dumps({"method": "Page.frameNavigated"}).encode()) # an event
+ _server_frame(b"are you there", opcode=9) # a ping
+ _server_frame(big[:300], fin=False) + _server_frame(big[300:], opcode=0))
got = {}
t = threading.Thread(target=lambda: got.update(v=cdp.evaluate("1")))
t.start()
op, sent = _read_client_frame(chrome)
assert op == 1 and json.loads(sent)["method"] == "Runtime.evaluate"
op, pong = _read_client_frame(chrome)
assert (op, pong) == (10, b"are you there")
t.join(timeout=10)
assert got["v"] == "x" * 70000
cdp.close()
chrome.close()
def test_devtools_errors_and_a_closed_socket_are_raised_not_hidden():
import socket
from m0lib import video
ours, chrome = socket.socketpair()
cdp = video.Cdp("", sock=ours)
chrome.sendall(_server_frame(json.dumps({"id": 1, "error": {"message": "no such method"}}).encode()))
with pytest.raises(RuntimeError, match="no such method"):
cdp.call("Nope.nothing")
chrome.sendall(_server_frame(json.dumps({"id": 2, "result": {
"exceptionDetails": {"text": "Uncaught", "exception": {"description": "TypeError: m is undefined"}}}}).encode()))
with pytest.raises(RuntimeError, match="m is undefined"):
cdp.evaluate("m.v")
chrome.sendall(_server_frame(b"", opcode=8))
with pytest.raises(ConnectionError):
cdp.call("Runtime.evaluate")
cdp.close()
chrome.close()
def _snap(total, dropped, **kw):
return {"total": total, "dropped": dropped, "shown": kw.pop("shown", total), "gaps": kw.pop("gaps", [0, 0]),
"max_gap_ms": kw.pop("max_gap_ms", 17.0), "waits": 0, "quality": "hd1080", "height": 1080, **kw}
def test_a_window_counts_the_frames_the_video_dropped_meanwhile():
from m0lib import video
w = video.window_stats(_snap(1000, 5), _snap(4600, 23, gaps=[4, 1], max_gap_ms=140.0), 60.0)
assert w["valid"] and w["frames"] == 3600 and w["dropped"] == 18
assert w["fps"] == 60.0 and w["dropped_per_min"] == 18.0 and w["dropped_share"] == 0.005
assert w["gaps_over_ms"] == {str(video.GAP_MS[0]): 4, str(video.GAP_MS[1]): 1} and w["max_gap_ms"] == 140.0
@pytest.mark.parametrize("after", [_snap(4600, 9, ad=True), _snap(4600, 9, paused=True), _snap(4600, 9, ended=True),
_snap(300, 0), _snap(1000, 5)])
def test_a_window_with_an_ad_a_pause_the_end_a_new_video_or_no_frames_is_kept_but_not_counted(after):
from m0lib import video
w = video.window_stats(_snap(1000, 5), after, 60.0)
assert not w["valid"] and w["invalid_because"]
def test_the_comparison_adds_up_only_valid_busy_windows_on_each_side_of_the_cap():
from m0lib import video
def row(jarvis, cap, frames, dropped, valid=True):
return {"jarvis": jarvis, "gpu_cap": {"cap": 0.95} if cap else None,
"video": {"valid": valid, "frames": frames, "dropped": dropped, "seconds": 60.0,
"gaps_over_ms": {str(g): dropped for g in video.GAP_MS}}}
rows = [row("off", False, 3600, 0), row("busy", False, 3600, 36), row("busy", True, 3600, 6),
row("busy", True, 3600, 1000, valid=False), row("busy", False, 3600, 18)]
c = video.compare(rows)
assert c["no_cap"]["windows"] == 2 and c["no_cap"]["dropped"] == 54 and c["no_cap"]["dropped_per_min"] == 27.0
assert c["cap95"]["windows"] == 1 and c["cap95"]["dropped"] == 6 and c["cap95"]["dropped_share"] == round(6 / 3600, 4)
class _FakePage:
"""The watch page: 60 frames shown per snapshot step, a few dropped; records what the stage did."""
def __init__(self, starts=True):
self.starts = starts
self.total = self.dropped = 0
self.events: list[str] = []
self.closed = False
def start(self, quality="hd1080", timeout=180):
self.events.append("video_start")
return {"started": self.starts, "quality": quality if self.starts else None, "ad_seen": False}
def keep_room(self):
pass
def reset(self):
pass
def snapshot(self):
self.total += 3600
self.dropped += 2
return _snap(self.total, self.dropped)
def close(self):
self.closed = True
def _run_video_stage(tmp_path, monkeypatch, fake_server, page, stt=None):
from m0lib import video
monkeypatch.setattr(video, "QUIET_S", 0.01)
monkeypatch.setattr(video, "open_video_page", lambda work, *a, **k: page)
stt = _FakeStt() if stt is None else stt
r, started, running = _run_levels_stage(tmp_path, monkeypatch, fake_server, _vram, only="video",
extra_opts=["stt_python=py"], stt=stt)
return r, started, running, stt
def test_video_stage_compares_the_video_alone_jarvis_idle_and_busy_with_and_without_the_cap(
tmp_path, monkeypatch, fake_server):
from m0lib import video
page = _FakePage()
r, started, running, stt = _run_video_stage(tmp_path, monkeypatch, fake_server, page)
assert r["stage"] == "video_drops" and r["status"] == "ok"
rows = r["video_rows"]
# Alone first and last; idle before busy; the busy rows alternate A B B A around the cap.
assert [x["jarvis"] for x in rows] == ["off", "idle"] + ["busy"] * len(video.ROUNDS) + ["off"]
busy = [x for x in rows if x["jarvis"] == "busy"]
capped = [bool(x["gpu_cap"]) for x in busy]
assert capped == [False, True, True, False]
assert all(x["video"]["valid"] and x["video"]["frames"] > 0 for x in rows)
for x in busy:
assert x["llm"]["decode_tok_s"]["n"] > 0 # the LLM answered during the window
if x["gpu_cap"]:
assert x["gpu_cap"]["cap"] == llm.GPU_CAP and x["gpu_cap"]["cycles"] > 0
assert x["gpu_cap"]["left_paused"] == 0
# Jarvis is the normal placement: the STT room probe, then one start with the experts it leaves.
assert len(started) == 2 and _expert_vram(started[0]) == 0 and _expert_vram(started[1]) > 0
assert r["placement"]["sets"] == started[1]["sets"]
# The STT is loaded before the LLM and transcribes only once Jarvis is busy.
assert stt.events[:4] == ["stt_loaded", "llm_start", "llm_start", "stt_go"]
assert set(r["comparison"]) == {"no_cap", "cap95"} and r["comparison"]["cap95"]["windows"] == 2
# Nothing is left behind: the browser closed, the model stopped, the STT gone, nothing paused.
assert page.closed and running["now"] is None and stt.loaded is None and not running["held"]
def test_the_cap_in_the_video_stage_pauses_jarvis_and_never_the_browser(tmp_path, monkeypatch, fake_server):
paused = set()
from m0lib import video
page = _FakePage()
monkeypatch.setattr(video, "QUIET_S", 0.01)
monkeypatch.setattr(video, "open_video_page", lambda work, *a, **k: page)
_run_levels_stage(tmp_path, monkeypatch, fake_server, _vram, only="video", extra_opts=["stt_python=py"],
stt=_FakeStt(), paused=paused)
browser = next(p["pid"] for p in _procs(tmp_path / "strata") if "chrome" in p["exe"])
assert paused == {20, 21, STT_LAUNCHER_PID, STT_LAUNCHER_PID + 1} and browser not in paused
def test_video_stage_without_a_browser_or_a_playing_video_starts_no_jarvis(tmp_path, monkeypatch, fake_server):
r, started, _, stt = _run_video_stage(tmp_path, monkeypatch, fake_server, None)
assert r["status"] == "failed" and not started and not stt.events
page = _FakePage(starts=False)
r, started, _, stt = _run_video_stage(tmp_path, monkeypatch, fake_server, page)
assert r["status"] == "failed" and not started and not stt.events and page.closed
def test_video_stage_is_on_demand_with_the_stt_python_and_a_one_click_runner():
import m0
assert "video_drops" in m0.ON_DEMAND and "video_drops" in m0.NEEDS_STT
bat = (Path(m0.KIT) / "run_m0_video.bat").read_text(encoding="utf-8")
assert "-Only video_drops" in bat and "-Redo" in bat