feat(app): log the graphics card's free memory after the LLM starts and while each answer is written

The app logs how much of the card is free once the model answers, and the
voice worker reads the card once a second while an answer or a scheduled task
is written and logs the least free memory seen (no text, llm tab), so a slow
answer can be matched to a full card.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-17 15:40:20 +09:00
parent ce03424ba4
commit f1600f09c2
6 changed files with 129 additions and 7 deletions

View File

@@ -5,6 +5,7 @@ from __future__ import annotations
import argparse
import asyncio
import os
import shutil
import sys
from .log import debug_log
@@ -42,7 +43,7 @@ def main() -> int:
from .brain import take_mcp_env
mcp_env = take_mcp_env()
from .server import VoiceWorker, is_loopback
from .server import VoiceWorker, is_loopback, nvidia_card
from .stt_whisper import WhisperTranscriber
from .vad import SileroVad
@@ -81,7 +82,8 @@ def main() -> int:
recorder = Recorder(os.environ[RECORDINGS_ENV])
async def run() -> None:
worker = VoiceWorker(token, transcriber, vad.stream, tts, history=history, brain=brain, recorder=recorder)
worker = VoiceWorker(token, transcriber, vad.stream, tts, history=history, brain=brain, recorder=recorder,
card=nvidia_card if shutil.which("nvidia-smi") else None)
server = await worker.serve(args.host, args.port)
debug_log(f"voice worker listening on {args.host}:{args.port} tts={'on' if tts else 'off'} "
f"history={'on' if history else 'off'} brain={'on' if brain else 'off'} "

View File

@@ -15,7 +15,7 @@ from typing import Callable
import numpy as np
from .log import debug_log
from .log import debug_log, notice
from .audio import InputConverter, loudness_equalise
from .brain import Brain, MemorySettings
@@ -44,6 +44,19 @@ def is_loopback(host: str) -> bool:
LLM_WAIT_S = 180.0
def nvidia_card() -> tuple[int, int] | None:
"""The first NVIDIA card's used and total memory in MiB (``nvidia-smi``), None when unreadable."""
import subprocess
try:
out = subprocess.run(["nvidia-smi", "--query-gpu=memory.used,memory.total", "--format=csv,noheader,nounits"],
capture_output=True, text=True, timeout=5,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)).stdout
used, total = (int(v) for v in out.splitlines()[0].split(","))
return used, total
except Exception:
return None
class _LlmPaused(Exception):
"""The app paused the LLM (a game runs): nothing is answered until it is ready again."""
@@ -53,6 +66,7 @@ MAX_NOTES = 20
MAX_NOTE_CHARS = 300
# How long answer traces stay (history.spec.md, "Traces"); removed when the worker starts.
TRACE_KEEP_DAYS = 30
CARD_EVERY_S = 1.0 # how often the card's free memory is read while an answer is written
class _LiveTrace(list):
@@ -93,7 +107,8 @@ class VoiceWorker:
def __init__(self, token: str, transcriber: Transcriber | None, vad_factory: Callable[[], VadStream],
tts_engine: TtsEngine | None = None, hello_timeout_s: float = 5.0, tick_s: float = 0.05,
history=None, brain: Brain | None = None, chat_timeout_s: float = 15.0,
delivery_timeout_s: float = 30.0, recorder=None):
delivery_timeout_s: float = 30.0, recorder=None,
card: Callable[[], tuple[int, int] | None] | None = None):
if not token:
raise ValueError("a connection token is required")
self.token = token
@@ -105,6 +120,7 @@ class VoiceWorker:
self.history = history # jarvis.memory.history.HistoryStore or None
self.recorder = recorder # recordings.Recorder (voice.record on) or None
self.brain = brain
self.card = card # (used MiB, total MiB) of the graphics card, or None without one
# One reply at a time per lane: voice answers never wait behind another person's chat answer
# (conversation.md: with an "answer everything" chat channel the LLM takes two or more
# requests at once). One person's replies stay one at a time across lanes, so their dialogue
@@ -687,7 +703,7 @@ class Session:
history = HistoryContext()
try:
trace.append(self._records_step(history, notes))
async with self._llm():
async with self._llm(), self._card_watch(f"task {rid}"):
answer = await asyncio.to_thread(w.brain.reply, user, text, history, task=True,
notes=notes or [], trace=trace)
except Exception as e: # the brain must never take the session down
@@ -752,6 +768,34 @@ class Session:
w.llm_active -= 1
self._llm_check_idle()
@contextlib.asynccontextmanager
async def _card_watch(self, label: str):
"""While an answer is written: the card's free memory, read every `CARD_EVERY_S`; the least
seen is logged once it ends (a slow answer can then be matched to a full card)."""
card = self.worker.card
if card is None:
yield
return
seen: list[tuple[int, int]] = []
async def read():
while True:
got = await asyncio.to_thread(card)
if got:
seen.append(got)
await asyncio.sleep(CARD_EVERY_S)
t0 = time.monotonic()
task = asyncio.get_running_loop().create_task(read())
try:
yield
finally:
task.cancel()
if seen:
total = seen[-1][1]
notice(f"{label} card: least {min(total - u for u, _ in seen)} MiB free of {total} MiB "
f"({len(seen)} readings, {int((time.monotonic() - t0) * 1000)} ms)", "llm")
def _on_prepare(self, msg: dict) -> None:
"""A call still being said: the brain gets ready for it. One prepare per user runs at a time;
while it runs only the newest text waits, and one about the same as the last one prepared
@@ -909,7 +953,7 @@ class Session:
screen = AppBridge(self, asyncio.get_running_loop(), "screen", *origin)
trace.append(self._records_step(history, notes))
try:
async with self._llm(rid if speak else None):
async with self._llm(rid if speak else None), self._card_watch(f"answer {rid}"):
w.answering += 1
try:
answer = await asyncio.to_thread(w.brain.reply, user, text, history, chat=chat,

View File

@@ -531,3 +531,10 @@ cancel, and engine failures. The category names the service, so the app's log sc
in its tab (`app/src/admin.spec.md`, "Logs"): `stt` (utterance ends, STT batches, the Whisper model),
`tts` (sentences, cancels, MeloTTS), `llm` (the brain's replies, prepares and judgements),
`voice_worker` for the rest (connections, sessions, channels).
Without debug logging too, each answer and each scheduled task logs one `llm` line once the LLM is
done with it: the least free graphics memory read while it was written, the card's total, how many
readings and how long it took (`answer <id> card: least N MiB free of T MiB (k readings, ms)`). The
card is read with `nvidia-smi` once a second while the answer is written, in a thread, so the answer
never waits for it; without `nvidia-smi` nothing is read or logged. The line carries no text, so a
slow answer can be matched to a full card (the engine log has the same answer's timings).