Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -521,7 +521,7 @@ With these settings, `auto` selects CoreML for SCRFD at 640 px and ArcFace `w600

To run an individual model on CPU, add its label from the `inference` section of `/api/status` to `acceleration.cpu_models`, for example `["face:w600k_r50"]`. The environment equivalent is the comma-separated `KEYSTONE_ACCEL_CPU_MODELS`.

On macOS, `keystone macos setup` starts with `ffmpeg_hwaccel: none` (software decode); set `ffmpeg_hwaccel: auto` to check for VideoToolbox in the configured FFmpeg. On Linux it probes the VA-API device. VideoToolbox samples frames on hardware surfaces, then downloads the selected frames in NV12 or P010 before scaling and JPEG encoding. A camera with a decoder failure falls back to software decode. The dashboard shows each camera's decode backend and the active inference provider for loaded models. Set `ffmpeg_hwaccel: none` to use software decode everywhere.
AI Port decode defaults to `ffmpeg_hwaccel: auto`. On Linux it checks that the configured FFmpeg can initialize VA-API on the render device. If the default `/dev/dri/renderD128` is missing, it checks other accessible render nodes. On macOS, `auto` checks for VideoToolbox in the configured FFmpeg. `keystone macos setup` writes `ffmpeg_hwaccel: none` for new setups. Change it to `auto` to opt in. VideoToolbox samples frames on hardware surfaces, then downloads the selected frames in NV12 or P010 before scaling and JPEG encoding. A camera with a decoder failure falls back to software decode. The dashboard shows each camera's decode backend. Its Acceleration popover shows detected devices, decode readiness, loaded inference providers, and CPU fallbacks. Run `keystone doctor` for local device permissions and driver diagnostics. Set `ffmpeg_hwaccel: none` to use software decode everywhere.

Use the [Apple Silicon inference benchmark](docs/macos-inference-benchmark.md) to compare CLIP, detection and caption latency, CPU use and memory on your Mac.

Expand Down
2 changes: 1 addition & 1 deletion config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ acceleration:
# coreml_cache_dir: /state/coreml_cache # Persistent .mlmodelc cache, defaults to <state_dir>/coreml_cache
migraphx_precision: FP32 # FP32 | FP16 (AMD MIGraphX)
# migraphx_cache_dir: /state/migraphx_cache # Compiled MIGraphX programs, defaults to <state_dir>/migraphx_cache
ffmpeg_hwaccel: none # none | auto | vaapi | videotoolbox (AI Port analyzer decode)
ffmpeg_hwaccel: auto # none | auto | vaapi | videotoolbox (AI Port analyzer decode)
ffmpeg_device: /dev/dri/renderD128 # VA-API only
# If the GPU context is lost (e.g. an Intel xe engine reset), every GPU model keeps failing until
# Keystone restarts. With this on, Keystone exits (code 75) so systemd Restart=on-failure or the
Expand Down
96 changes: 96 additions & 0 deletions src/keystone/acceleration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"""Shared hardware diagnostics for the daemon and doctor."""

from __future__ import annotations

import os
import sys
from typing import TYPE_CHECKING, Any

from .hw_probe import (
probe_gpu_device_files,
probe_render_nodes,
probe_vaapi_device,
probe_video_decode,
vaapi_candidates,
)
from .ort_runtime import (
OPENVINO_EP,
available_providers,
openvino_targets_gpu,
probe_openvino_devices,
)

if TYPE_CHECKING:
from .config import AccelerationConfig


def acceleration_diagnostics(accel: AccelerationConfig, ffmpeg_path: str) -> dict[str, Any]:
nodes = probe_render_nodes()
gpu_nodes = probe_gpu_device_files()
devices = probe_openvino_devices()
providers = available_providers()
mode = accel.ffmpeg_hwaccel
backend, device = probe_video_decode(ffmpeg_path, mode, accel.ffmpeg_device)
hints = []

spec = accel.openvino_device.upper()
wants_openvino = accel.provider == "openvino" or (accel.provider == "auto" and OPENVINO_EP in providers)
wants_openvino_gpu = wants_openvino and (spec == "AUTO" or openvino_targets_gpu(spec))
if accel.provider == "openvino" and OPENVINO_EP not in providers:
hints.append("Install Keystone's OpenVINO extra in the runtime environment to enable the ONNX Runtime provider.")
elif wants_openvino and devices is None:
hints.append("Keystone could not enumerate OpenVINO devices. Check that the OpenVINO Python package can load in the runtime environment.")

if sys.platform == "linux":
needs_dri = mode == "vaapi" or (accel.provider == "openvino" and wants_openvino_gpu)
if needs_dri and not nodes and not probe_vaapi_device(accel.ffmpeg_device):
hints.append("No /dev/dri render nodes found. Check the host GPU driver and pass the render device through to the container or VM.")

candidates = vaapi_candidates(mode, accel.ffmpeg_device)
for node in nodes:
decode_needs_node = not backend and (node.path in candidates or (mode == "auto" and not candidates))
if not node.accessible and (wants_openvino_gpu or decode_needs_node):
hints.append(
f"{node.path} requires read/write access. Give the Keystone process access via "
f"the render node's owning group (GID {node.gid})."
)

if (
wants_openvino_gpu and devices and all(device_id == "CPU" for device_id, _ in devices)
and any(node.accessible and node.vendor == "Intel" for node in nodes)
):
hints.append(
"OpenVINO sees only CPU despite an accessible Intel render node. "
"Check for intel-opencl-icd or libze-intel-gpu1 in Keystone's runtime environment."
)

if not backend:
if any(probe_vaapi_device(path) for path in candidates):
hints.append(
"FFmpeg could not initialize VA-API on an accessible render node. "
"Check FFmpeg's VA-API support and install the matching userspace driver "
"(intel-media-va-driver for recent Intel GPUs or mesa-va-drivers for AMD)."
)
elif candidates and nodes and not os.path.exists(accel.ffmpeg_device):
hints.append(f"{accel.ffmpeg_device} is missing. Set acceleration.ffmpeg_device to an accessible render node.")
elif mode == "vaapi":
hints.append("Keystone's VA-API decode requires Linux. Set acceleration.ffmpeg_hwaccel to auto to select the platform backend.")

if (mode == "videotoolbox" or (mode == "auto" and sys.platform == "darwin")) and not backend:
hints.append("VideoToolbox requires macOS and an FFmpeg build that lists videotoolbox in ffmpeg -hwaccels.")

return {
"openvinoDevices": [{"id": device_id, "name": name} for device_id, name in devices or ()],
"hardware": {
"renderNodes": [
{
"path": node.path, "accessible": node.accessible, "gid": node.gid,
"vendor": node.vendor, "vendorId": node.vendor_id, "deviceId": node.device_id,
}
for node in nodes
],
"gpuDeviceFiles": list(gpu_nodes),
"videoDecode": {"ready": backend is not None, "backend": backend or "software", "device": device},
},
"diagnostics": hints,
}
23 changes: 9 additions & 14 deletions src/keystone/aiport.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,10 @@
from .embedder import Embedder
from .face import DetectedFace, FaceRecognizer
from .history import HistoryStore
from .hw_probe import probe_vaapi_device as probe_vaapi_device
from .hw_probe import probe_video_decode
from .launchd import AIPORT_SOCKET, activated_sockets
from .lpr import LPR_LOCK_CONFIDENCE, LicensePlateRecognizer, PlateDetection, PlateVoteTracker
from .ort_runtime import probe_vaapi_device, probe_videotoolbox
from .tls import (
PinnedTCPConnector,
build_client_ssl_context,
Expand Down Expand Up @@ -2293,19 +2294,13 @@ async def _record_plate(self, cam: PairedCameraState, plate: PlateDetection) ->
plate.confidence,
)

async def _analyzer_hwaccel(self, cam: PairedCameraState) -> str | None:
async def _analyzer_hwaccel(self, cam: PairedCameraState) -> tuple[str | None, str | None]:
if cam.hwaccel_disabled:
return None
return None, None
accel = self.config.acceleration
if accel.ffmpeg_hwaccel == "vaapi":
return "vaapi"
if accel.ffmpeg_hwaccel in {"auto", "videotoolbox"} and sys.platform == "darwin":
if await asyncio.to_thread(probe_videotoolbox, self.config.ffmpeg_path):
return "videotoolbox"
elif accel.ffmpeg_hwaccel == "auto" and sys.platform == "linux":
if probe_vaapi_device(accel.ffmpeg_device):
return "vaapi"
return None
return await asyncio.to_thread(
probe_video_decode, self.config.ffmpeg_path, accel.ffmpeg_hwaccel, accel.ffmpeg_device
)

def _package_enabled_for(self, cam: PairedCameraState) -> bool:
return bool(
Expand Down Expand Up @@ -2457,7 +2452,7 @@ async def _analyze_camera_loop(self, cam: PairedCameraState) -> None:

while self._cameras.get(cam.device_id) is cam:
proc: asyncio.subprocess.Process | None = None
hwaccel = await self._analyzer_hwaccel(cam)
hwaccel, vaapi_device = await self._analyzer_hwaccel(cam)
frames_this_run = 0
stderr_task = None
failure = ""
Expand All @@ -2469,7 +2464,7 @@ async def _analyze_camera_loop(self, cam: PairedCameraState) -> None:
stream_url=cam.stream_url,
detect_fps=self.config.aiport.detect_fps,
analyze_max_width=self.config.aiport.analyze_max_width,
vaapi_device=self.config.acceleration.ffmpeg_device if hwaccel == "vaapi" else None,
vaapi_device=vaapi_device,
hwaccel_backend=hwaccel,
videotoolbox_format=videotoolbox_format,
)
Expand Down
21 changes: 18 additions & 3 deletions src/keystone/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from aiohttp import web

from .acceleration import acceleration_diagnostics
from .aiport import AiPortService
from .brand import APP_NAME, APP_VERSION
from .config import Config
Expand All @@ -23,6 +24,7 @@
from .ort_runtime import (
GPU_WATCHDOG,
coreml_available,
cuda_available,
inference_health,
migraphx_available,
openvino_available,
Expand Down Expand Up @@ -115,6 +117,7 @@ def get_status(self) -> dict[str, Any]:
vision_auth_error = getattr(self.vision, "auth_error", None) if ai_key else None
emb_enabled = ai_key and self.config.embeddings.enabled and self.embedder is not None
protect_ai = self.control.protect_ai_settings if self.control else {}
inference = inference_health()
return {
"app": APP_NAME,
"version": APP_VERSION,
Expand Down Expand Up @@ -165,8 +168,8 @@ def get_status(self) -> dict[str, Any]:
"cameras": {
cid: cam.name for cid, cam in self.config.cameras.items() if cam.name
},
"acceleration": self._acceleration_status(),
"inference": inference_health(),
"acceleration": self._acceleration_status(inference),
"inference": inference,
"faces": self.faces.status() if self.faces else {"enabled": False},
"enhance": self.enhancer.status() if self.enhancer else {"enabled": False},
"stt": self._stt_status(protect_ai),
Expand All @@ -188,7 +191,7 @@ def get_status(self) -> dict[str, Any]:
),
}

def _acceleration_status(self) -> dict[str, Any]:
def _acceleration_status(self, inference: dict[str, dict[str, Any]]) -> dict[str, Any]:
accel = self.config.acceleration
active: dict[str, str] = {}
if self.config.device.enabled and self.config.embeddings.enabled and self.embedder is not None:
Expand Down Expand Up @@ -230,12 +233,21 @@ def _acceleration_status(self) -> dict[str, Any]:
"coremlComputeUnits": accel.coreml_compute_units,
"coremlModelFormat": accel.coreml_model_format,
"coremlCacheDir": accel.coreml_cache_dir,
"cudaAvailable": cuda_available(),
"migraphxAvailable": migraphx_available(),
"migraphxPrecision": accel.migraphx_precision,
"migraphxCacheDir": accel.migraphx_cache_dir,
"ffmpegHwaccel": accel.ffmpeg_hwaccel,
"ffmpegDevice": accel.ffmpeg_device,
"activeProviders": active,
"fallbacks": {
label: {
"requestedProvider": model["requestedProvider"],
"reason": model["fallbackReason"],
}
for label, model in inference.items() if model["fellBack"]
},
**acceleration_diagnostics(accel, self.config.ffmpeg_path),
"gpuWatchdog": GPU_WATCHDOG.status(),
}

Expand Down Expand Up @@ -445,6 +457,9 @@ async def _on_adopted() -> None:

# 2. Start optional status web UI
if self.config.web.enabled:
await asyncio.to_thread(
acceleration_diagnostics, self.config.acceleration, self.config.ffmpeg_path,
)
ui_app = create_status_app(
self.get_status,
lambda: list(self.worker.recent_events) if self.worker else [],
Expand Down
7 changes: 4 additions & 3 deletions src/keystone/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

from .brand import DEFAULT_HOSTNAME, env_var
from .homebrew import resolve_tool
from .hw_probe import DEFAULT_VAAPI_DEVICE
from .peer_networks import normalize_trusted_peers


Expand Down Expand Up @@ -144,8 +145,8 @@ class AccelerationConfig:
coreml_cache_dir: str = "" # Defaults to <state_dir>/coreml_cache
migraphx_precision: str = "FP32" # "FP16" | "FP32"
migraphx_cache_dir: str = "" # Defaults to <state_dir>/migraphx_cache
ffmpeg_hwaccel: str = "none" # "none" | "auto" | "vaapi" | "videotoolbox"
ffmpeg_device: str = "/dev/dri/renderD128"
ffmpeg_hwaccel: str = "auto" # "none" | "auto" | "vaapi" | "videotoolbox"
ffmpeg_device: str = DEFAULT_VAAPI_DEVICE
# When the GPU context is lost (e.g. an Intel xe engine reset), exit so systemd/Docker
# restart Keystone with a fresh one. After gpu_loss_max_restarts such restarts within
# gpu_loss_window_minutes, start on the CPU instead to avoid a restart loop.
Expand Down Expand Up @@ -697,7 +698,7 @@ def validate_acceleration(self) -> None:
str(Path(cache_dir).expanduser().resolve() if cache_dir else self.state_dir / default_dir),
)
acc.ffmpeg_hwaccel = normalize_ffmpeg_hwaccel(acc.ffmpeg_hwaccel)
acc.ffmpeg_device = (acc.ffmpeg_device or "/dev/dri/renderD128").strip() or "/dev/dri/renderD128"
acc.ffmpeg_device = (acc.ffmpeg_device or "").strip() or DEFAULT_VAAPI_DEVICE
acc.restart_on_gpu_loss = (
_as_bool(acc.restart_on_gpu_loss)
if isinstance(acc.restart_on_gpu_loss, str)
Expand Down
30 changes: 30 additions & 0 deletions src/keystone/doctor.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,13 @@

import yaml

from .acceleration import acceleration_diagnostics
from .config import Config, load_config
from .control import ControlService
from .homebrew import resolve_tool
from .macos_cli import default_config_path
from .macos_postgres import PG_ADMIN_URL, PG_EXTENSIONS, PG_PORT, PG_SOCKET
from .ort_runtime import available_providers


def _tcp_open(host: str, port: int) -> bool:
Expand Down Expand Up @@ -256,6 +258,33 @@ def _report_discovery(cfg: Config) -> None:
"system services with sudo keystone macos install-daemons.")


def _report_acceleration(cfg: Config) -> None:
report = acceleration_diagnostics(cfg.acceleration, cfg.ffmpeg_path)
hardware = report["hardware"]
print("INFO Hardware acceleration")
if sys.platform == "linux" and not hardware["renderNodes"]:
print("INFO No /dev/dri render nodes detected")
for node in hardware["renderNodes"]:
gpu = " ".join(filter(None, (node["vendor"], node["deviceId"]))) or "unknown GPU"
access = "read/write" if node["accessible"] else "read/write unavailable"
print(f"INFO {gpu} at {node['path']} ({access}, GID {node['gid']})")
for path in hardware["gpuDeviceFiles"]:
vendor = "AMD ROCm" if path == "/dev/kfd" else "NVIDIA"
print(f"INFO {vendor} device detected at {path}")
video = hardware["videoDecode"]
if video["ready"]:
backend = "VA-API" if video["backend"] == "vaapi" else "VideoToolbox"
target = f" on {video['device']}" if video["device"] else ""
print(f"INFO Video decode: {backend} available{target}")
else:
print(f"INFO Video decode: software (ffmpeg_hwaccel={cfg.acceleration.ffmpeg_hwaccel})")
print(f"INFO ONNX Runtime providers: {', '.join(available_providers()) or 'unavailable'}")
devices = ", ".join(f"{dev['id']} ({dev['name']})" for dev in report["openvinoDevices"])
print(f"INFO OpenVINO devices: {devices or 'none detected'}")
for hint in report["diagnostics"]:
print(f"WARN {hint}")


def command(path: str | None) -> int:
try:
cfg = load_config(default_config_path(path))
Expand All @@ -270,6 +299,7 @@ def check(label: str, ok: bool) -> None:
results.append(ok)

check("FFmpeg executable", _probe_process([cfg.ffmpeg_path, "-version"]) is not None)
_report_acceleration(cfg)
if cfg.device.enabled:
if cfg.device.sync_postgres_password:
psql = cfg.device.psql_path or resolve_tool("psql") or "psql"
Expand Down
17 changes: 12 additions & 5 deletions src/keystone/embedder.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,10 @@ def __init__(
self._unload_task: asyncio.Task[None] | None = None
self.text_model_loads = 0
self.text_model_unloads = 0
self._openvino_device: str | None = None

@property
def _openvino_device(self) -> str | None:
return extract_openvino_device(self.active_provider)

@property
def ready(self) -> bool:
Expand Down Expand Up @@ -322,16 +325,20 @@ def _load_clip_session(self, path: Path, *, encoder: str) -> tuple[GuardedSessio
feed = {inp.name: mask if "mask" in inp.name.lower() else ids for inp in inputs}
if outputs_are_finite(sess.run(None, feed)):
return sess, session_provider_label(sess)
reason = "CLIP sanity check produced non-finite output."
LOG.warning("CLIP %s on %s produced non-finite output", encoder, provider)
except Exception as exc:
reason = f"CLIP sanity check failed: {exc}"
LOG.warning("CLIP %s sanity check failed on %s: %s", encoder, provider, exc)
return create_onnx_session(
cpu, active = create_onnx_session(
path,
threads=self.config.threads,
acceleration=self.acceleration,
allow_openvino=False,
label=f"clip:{encoder}",
)
cpu.record_cpu_fallback(sess.requested_provider or provider, reason)
return cpu, active

def _load_vision_session(self) -> GuardedSession:
if not self.config.coreai_vision_model or (
Expand All @@ -353,7 +360,9 @@ def load_cpu() -> GuardedSession:
session = CoreAIVisionSession(Path(self.config.coreai_vision_model), self.config.coreai_python)
except Exception as exc:
LOG.warning("Could not start Core AI CLIP vision: %s; using CPU", exc)
return load_cpu()
cpu = load_cpu()
cpu.record_cpu_fallback(COREAI_PROVIDER, f"Core AI initialization failed: {exc}")
return cpu

return GuardedSession(
session, label="clip:vision", provider=COREAI_PROVIDER, cpu_fallback=lambda: load_cpu().wrapped
Expand All @@ -376,7 +385,6 @@ def _ensure_and_load_sync(self) -> None:
vision.close()
raise
self._vision_sess = vision
self._openvino_device = extract_openvino_device(self.active_provider)
LOG.info(
"Loaded CLIP ViT-L/14 (ONNX cache=%s, quantization=%s, vision=%s, text=%s, "
"provider=%s, threads=%d)",
Expand Down Expand Up @@ -564,7 +572,6 @@ async def close(self) -> None:
self._vision_sess = None
self._tokenizer = None
self._ready = False
self._openvino_device = None


class OllamaTextEmbedder:
Expand Down
Loading
Loading