Files
frigate/frigate/stats/hardware.py
T
91e91c68ef Add Axelera Metis NPU detector plugin v.0.19 (#24270)
* Add Axelera Metis NPU object detector plugin

Runs Frigate inference on the Axelera Metis NPU through the vendor's
low-level axelera.runtime API with pip-installed, sha256-pinned wheels
from Axelera's public artifactory (self-contained: auditwheel-repaired
libs + bundled firmware).

- async send_input/receive_output contract (FIFO pairing, overload emits
  zero rows instead of raising, frames are copied out of camera shm)
- generic YOLO-family decoder driven by the compiled model's manifest.json
  (padded input geometry, dequant params, baked postprocess graph via onnx)
- labels come from the compiled model's model_info.json; empty labelmaps
  fail loudly at init

* object_detection: async runner path for the axelera detector

* detectors: detect_axelera probe (/dev/metis*) + device node init

* stats: Axelera Metis board temperature poller

The card exposes no utilization counter usable next to a live detector, so
the poller reports the board-controller temperature read via axcmd (cached
5s; the read must not race detector init).

* docs: Axelera Metis detector (install, config, model catalog, downloads)

* axelera: expose Metis colon-name device node and image deps for runtime enumeration

The Axelera runtime enumerates Metis cards via the colon-separated node
name created by the vendor udev rule on the host (e.g. /dev/metis-0:1:0)
and probes kernel state with lsmod/lspci. Containers only receive the
raw /dev/metis-0-1-0 node, so the detector never found the card.

- init-devices: create /dev/metis-BB:DD:F aliases for each Metis node
- install_deps: add kmod and pciutils so the runtime's driver check works

* axelera: review round 2 (downloader, stop release, pixel format, docs size, per-class NMS)

- download model zips through ModelDownloader (atomic .part rename; a
  truncated download no longer poisons the cache)
- stop(): release the Context (releases connection/model/instance); the
  previous instance.free() call never existed in the runtime API and was
  silently swallowed
- honor input_pixel_format: flip to RGB planes only when Frigate delivers
  BGR (input_pixel_format: bgr); with rgb the frame passes through as-is
- docs/catalog: width/height = compiled 640x640 input (square regions no
  longer get squashed twice), document input_pixel_format: bgr
- NMS via xyxy_to_xywh_for_nms + per-class cv2.dnn.NMSBoxes, matching the
  other detector plugins instead of a hand-rolled class-agnostic pass

* axelera: report Metis temperature only on the NPU card

The same board readout was surfaced twice on the System page: once as
the detector temperature (get_hardware_temperatures) and once on the
NPU card (npu_usages). Keep the NPU card, where the value belongs.

* axelera: report AIPU utilization as the detector run duty cycle

The runtime exposes no device-side usage counter (mvm_utilisation is a
configuration limit, not a readout), so the NPU card rendered empty.
ModelInstance.run blocks until the AIPU completes: the detector process
now times each run and publishes busy/wall over a 2s window through a
small file under the tmp cache dir; the stats poller reads it and sets
the npu key. A stale file (detector idle/restarting) reports nothing
rather than a stale number.

* axelera: cut hot-path allocations in preprocess and dequantise

Preprocess reused three fresh arrays per frame (resize output, quantised
copy, strided channel flip at write time) and refilled the whole padded
input buffer. Now resize writes into a scratch with cv2 dst=, the BGR->RGB
swap is a cvtColor into scratch (no strided copy), the int8 quantise runs
with out=, and only the border strips the content rect does not cover get
memset. Measured 39% faster on the 704x576 -> 640x640 path.

Dequantise allocated two fp32 temporaries per head (astype then the
dequant expression) before the transpose copy. copyto now casts int8->fp32
while transposing straight into a reused fp32 feed buffer, and the zp/scale
math runs in place. Measured 78% faster for the YOLOX-S head set, outputs
bit-identical (int8->fp32 cast is lossless).

Argmax+gather replaces max+argmax (one class-axis reduction instead of
two), and the postprocess session pins intra_op_num_threads=1: one frame
is in flight through the decoder, extra ORT threads only add context
switches.

* axelera: publish the run duty cycle through a shared Value

Replace the tmp-file duty-cycle handoff (and the FRIGATE_TMP env var
nothing else reads) with a third multiprocessing.Value alongside
avg_inference_speed and detection_start: ObjectDetectProcess creates it,
AsyncDetectorRunner passes it to the detector, and the plugin publishes
busy/wall of the blocking ModelInstance.run over a 2s window, mirroring
how memryx receives its shared state. No filesystem path, no staleness
window, no atomic rename, and stats/hardware.py no longer imports the
plugin module to find the file.

The producer also ticks the window while the queue is empty, so the duty
cycle falls to 0 when the card idles instead of sticking at its last
value.

Name it what it is: host-side occupancy of the run call, including DMA
and driver time, not an AIPU core counter (the runtime exposes no
device-side one). The NPU entry now reads temperature from the board
controller plus the detector-reported run duty cycle folded in where
the detector processes are in reach.

* axelera: enumerate devices explicitly and fail with an actionable error

Context.list_devices() keys off the lspci BDF and needs the colon-form
node to be present, so surface an empty enumeration at init with the
fix-it hint instead of a bare device_connect(None) ConnectionError
several frames deeper. Uses the DeviceInfo the runtime enumerated
rather than relying on the pick-first implicit path.

* axelera: deliver every accepted result under backpressure, reset duty cycle on restart

Greptile P1: _push_result dropped a completion when the result queue was
full, stranding the runner's send_times entry and the input SHM mapping
(1 submission : 1 result contract). Replace the drop with a stop-aware
blocking put so an accepted submission always produces exactly one
delivered completion.

Greptile P2: start_or_restart did not clear run_duty_cycle when starting
a replacement process, so stats could show the previous process's duty
cycle while the new detector was still initializing. Reset it to the
-1.0 sentinel alongside detection_start, inside the async branch.

Greptile P2 (offline docs): list axelera among the detector types whose
pre-seeded runtime files live under /config/model_cache/runtimes/<type>.

* axelera: reviewer round 3 (plugin-owned enumeration tools, generic DEVICE_ALIASES, generic duty-cycle fold)

install_deps.sh: drop kmod/pciutils from the base image. The runtime's
list_devices() only greps popen'd lspci/lsmod output over /sys and /proc,
so the plugin now installs shell stand-ins in its own
/config/model_cache/axelera/bin and prepends it to PATH when the real
tools are missing (hardware-verified: the stand-in lspci prints the
Device 1f9d:<id> line the runtime matches, the lsmod shape matches
/proc/modules).

init-devices: replace the Metis-keyed alias block with a generic
DEVICE_ALIASES env var (comma separated alias=target pairs, next to
DEVICE_ACL_PATHS). Docker rejects colon-named nodes in --device AND in
bind mounts (probed: 'too many colons' on both the long volume form and
the mount form), so the in-container symlink stays necessary; docs carry
the pair users must set.

stats/util.py: fold any detector's published run_duty_cycle into the
matching npu_usages entry generically; _axelera_run_duty_cycle and the
per-vendor branch are gone.

plugin: the no-device RuntimeError now names the raw dash-form node
(--device rejects colons, users can only pass the raw node) and points
at DEVICE_ALIASES for the colon alias.

* axelera: reviewer round 4 (aggregate shared-type duty cycles, american spellings)

stats/util.py: several detector processes can share one hardware type (e.g.
two axelera cards on one host). Iterating and assigning made the displayed
NPU usage depend on dict order, last writer wins. Collect the published
windows per type and write the busiest one, matching what the removed
per-vendor helper did with max().

plugin: the remaining British spellings (dequantise family) corrected to
the American forms the repo requires.

plugin: model path resolution follows hailo8l's single-string pattern (URL
or local path or preset name in one value), the download uses urllib
directly like memryx, and _find_model_json now raises on an ambiguous
multi-model directory instead of returning whichever sorts first.

plugin: AxeleraDetector exposes shutdown() (the async contract hook base.py
calls) instead of close(); __del__ guards a partially initialised instance.

* axelera: download URL models through the atomic ModelDownloader

* axelera: bring the detector unit tests in tree

* init-devices: create DEVICE_ALIASES before the ACL-mode exits

An alias is not an ACL grant: users running with FRIGATE_RUN_AS_ROOT or
FRIGATE_DEVICE_ACLS=false still need the colon-form node the runtime
enumerates, so create the aliases right after the euid check. Document
DEVICE_ALIASES next to DEVICE_ACL_PATHS and note it cannot work under
docker's user: mode (the container cannot write to /dev).

* detectors: cover the Axelera Metis probe in test_detector_hardware

* Update docs/docs/configuration/non_root.md

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* axelera: address the 2026-10-12 review round

- hash directory models deterministically in compute_model_hash instead of
  raising IsADirectoryError at startup
- keep canonical model labels addressable after user renames in the
  labelmap lookup (two classes can share one renamed name)
- key the URL model cache by source and archive content, extract replaced
  archives into fresh directories, prune superseded variants conservatively
- keep publishing the run duty cycle when the hardware poll has no entry
  (duty-only npu_usages entry instead of a hidden detector)
- document the user: mode device reach instead of host-only alias creation

* axelera: prune only generated cache entries

A fresh download matched user-provided layouts (the docs-recommended
<name>/ directory, <name>.zip archives) and look-alike model names
(yolox.zip vs yolox-s-*) by prefix. Pruning is now gated on the exact
generated identity pattern <name>-<source>-<32 hex digits>, so downloads
never touch user-provided directories, other models, or other sources.

* axelera: narrow the model path design to memryx-style zips

- path is always a .zip of the compiled output (local or http(s) URL),
  extracted fresh on every start under a lock, like the memryx
  custom-model flow
- _decode returns the raw class index and Frigate's labelmap names it;
  _build_label_lookup and _read_model_labels are gone, and the YOLOX
  objectness check keys off model_type
- scheme-less URL support and the quantized/manifest.json fallback are
  dropped
- width/height must equal the compiled input size; init raises otherwise
  instead of letterboxing
- compute_model_hash is back to the unchanged file-only hashing; the
  .extracted marker, source/content cache-name hashes and
  _prune_model_cache are removed

* Update frigate/test/test_axelera_detector.py

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* axelera: drop the run duty cycle, match the hailo temperature flow

- no other accelerator reports NPU usage and the published value was time
  blocked in run(), not device utilization from the vendor API; removing
  it leaves the runner selection as the only core change
- the board temperature moves to a get_hardware_temperatures branch like
  hailo, so it renders on the detector card; _poll_axelera, its POLLERS
  entry and the _scan_detectors line are gone
- axelera_runtime2 is not installed: axelera.runtime imports it only
  inside a try for its separate new-runtime API, and the low-level API
  the plugin uses (Context, load_model, device_connect,
  load_model_instance) lives in axelera.runtime.objects

* axelera: follow-ups from the 2026-10-13 review round

- the offline-setup table no longer lists the axelera_runtime2 wheels,
  which are not installed
- a failed board temperature read starts a 60s cooldown so an
  unresponsive axcmd does not delay every stats update

* axelera: drop the model-hash test, fix the model.json error messages

* axelera: drop DEVICE_ALIASES, document the CDI device spec

* axelera: use ln -sf in the CDI hook example

---------

Co-authored-by: Patryk Watkowski <patrykorwat@users.noreply.github.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-10-20 09:53:28 -05:00

489 lines
15 KiB
Python

"""Config driven hardware usage collection for stats."""
import logging
import os
import time
from collections.abc import Callable
from concurrent.futures import Future, ThreadPoolExecutor, wait
from dataclasses import dataclass, field
from functools import cache, partial
from glob import glob
from typing import Any
from frigate.config import FrigateConfig
from frigate.config.camera.updater import (
CameraConfigUpdateEnum,
CameraConfigUpdateSubscriber,
)
from frigate.config.classification import SemanticSearchModelEnum
from frigate.const import FFMPEG_HWACCEL_AMF, FFMPEG_HWACCEL_VULKAN
from frigate.detectors.hardware import DEV_ROOT, hardware_prober
from frigate.util.services import (
get_amd_gpu_stats,
get_axcl_npu_stats,
get_axelera_board_temp,
get_cpu_stats,
get_hailo_temps,
get_intel_gpu_stats,
get_jetson_stats,
get_nvidia_gpu_stats,
get_openvino_npu_stats,
get_rockchip_gpu_stats,
get_rockchip_npu_stats,
is_vaapi_amd_driver,
)
logger = logging.getLogger(__name__)
HARDWARE_ERROR_COOLDOWN_SECONDS = 3600
POLL_TIMEOUT_SECONDS = 10
# hardware names polled here, in the order used to resolve a generic GPU demand
GPU_HARDWARE_KEYS = {
"onnx:nvidia": "nvidia",
"tensorrt": "jetson",
"onnx:amd": "amd_gpu",
"openvino:GPU": "intel_gpu",
"rknn": "rockchip",
}
@dataclass
class HardwarePollResult:
"""Usage entries from one hardware poll, split by stats bucket."""
gpu: dict[str, dict[str, Any]] = field(default_factory=dict)
npu: dict[str, dict[str, Any]] = field(default_factory=dict)
ok: bool = True
@cache
def _is_amd_vaapi() -> bool:
"""Cached vaapi driver check, the driver cannot change at runtime."""
return is_vaapi_amd_driver()
def _present_hardware() -> set[str]:
return {hardware.key for hardware in hardware_prober.probe()}
def _gpu_device_nodes_exist(name: str) -> bool:
"""Whether the GPU's device nodes are visible to this container.
The prober reads /proc and /sys, which show the host kernel's hardware
even when a device was not passed into the container, so a GPU is only
usable when its device nodes exist too.
"""
if name == "nvidia":
return bool(glob(f"{DEV_ROOT}/nvidia*"))
elif name in ("amd_gpu", "intel_gpu"):
return bool(glob(f"{DEV_ROOT}/dri/*"))
return True
def _present_gpu() -> str | None:
"""The hardware name of the first usable GPU found on this system, if any."""
present = _present_hardware()
for key, name in GPU_HARDWARE_KEYS.items():
if key in present and _gpu_device_nodes_exist(name):
return name
return None
def _poll_nvidia(config: FrigateConfig) -> HardwarePollResult:
nvidia_usage = get_nvidia_gpu_stats()
if not nvidia_usage:
return HardwarePollResult(
gpu={"nvidia-gpu": {"vendor": "nvidia", "gpu": "", "mem": ""}}, ok=False
)
gpu: dict[str, dict[str, Any]] = {}
for entry in nvidia_usage.values():
gpu[entry["name"]] = {
"vendor": "nvidia",
"gpu": str(round(float(entry["gpu"]), 2)) + "%",
"mem": str(round(float(entry["mem"]), 2)) + "%",
"enc": str(round(float(entry["enc"]), 2)) + "%",
"dec": str(round(float(entry["dec"]), 2)) + "%",
"temp": str(entry["temp"]),
}
return HardwarePollResult(gpu=gpu)
def _poll_jetson(config: FrigateConfig) -> HardwarePollResult:
jetson_usage = get_jetson_stats()
if not jetson_usage:
return HardwarePollResult(
gpu={"jetson-gpu": {"vendor": "nvidia", "gpu": "", "mem": ""}}, ok=False
)
return HardwarePollResult(gpu={"jetson-gpu": {"vendor": "nvidia", **jetson_usage}})
def _poll_intel_gpu(config: FrigateConfig) -> HardwarePollResult:
intel_usage = get_intel_gpu_stats(config.telemetry.stats.intel_gpu_device)
if not intel_usage:
return HardwarePollResult(
gpu={"intel-gpu": {"vendor": "intel", "gpu": "", "mem": ""}}, ok=False
)
gpu: dict[str, dict[str, Any]] = {}
for entry in intel_usage.values():
name = entry.pop("name")
gpu[name] = entry
return HardwarePollResult(gpu=gpu)
def _poll_amd_gpu(config: FrigateConfig) -> HardwarePollResult:
amd_usage = get_amd_gpu_stats()
if not amd_usage:
return HardwarePollResult(
gpu={"amd-vaapi": {"vendor": "amd", "gpu": "", "mem": ""}}, ok=False
)
return HardwarePollResult(gpu={"amd-vaapi": {"vendor": "amd", **amd_usage}})
def _poll_rockchip(config: FrigateConfig) -> HardwarePollResult:
result = HardwarePollResult()
rga_usage = get_rockchip_gpu_stats()
if rga_usage:
result.gpu["rockchip"] = {"vendor": "rockchip", **rga_usage}
npu_usage = get_rockchip_npu_stats()
if npu_usage:
result.npu["rockchip"] = npu_usage
result.ok = bool(rga_usage or npu_usage)
return result
def _poll_rpi(config: FrigateConfig) -> HardwarePollResult:
# RPi v4l2m2m is currently not able to get usage stats
return HardwarePollResult(
gpu={"rpi-v4l2m2m": {"vendor": "rpi", "gpu": "", "mem": ""}}
)
def _poll_intel_npu(config: FrigateConfig) -> HardwarePollResult:
npu_usage = get_openvino_npu_stats()
if not npu_usage:
return HardwarePollResult(ok=False)
return HardwarePollResult(npu={"openvino": npu_usage})
def _poll_axengine(config: FrigateConfig) -> HardwarePollResult:
npu_usage = get_axcl_npu_stats()
if not npu_usage:
return HardwarePollResult(ok=False)
return HardwarePollResult(npu={"axengine": npu_usage})
POLLERS: dict[str, Callable[[FrigateConfig], HardwarePollResult]] = {
"nvidia": _poll_nvidia,
"jetson": _poll_jetson,
"intel_gpu": _poll_intel_gpu,
"amd_gpu": _poll_amd_gpu,
"rockchip": _poll_rockchip,
"rpi": _poll_rpi,
"intel_npu": _poll_intel_npu,
"axengine": _poll_axengine,
}
def _hwaccel_hardware(args: str) -> str | None:
"""Map an ffmpeg hwaccel arg string (preset or raw args) to a hardware name."""
if "cuvid" in args or "nvidia" in args:
return "nvidia"
elif "nvmpi" in args or "jetson" in args:
return "jetson"
elif "qsv" in args:
return "intel_gpu"
elif FFMPEG_HWACCEL_AMF in args or "amf" in args:
return "amd_gpu"
elif "vaapi" in args:
return "amd_gpu" if _is_amd_vaapi() else "intel_gpu"
elif "preset-rk" in args or "rkmpp" in args:
return "rockchip"
elif "v4l2m2m" in args or "rpi" in args:
return "rpi"
elif FFMPEG_HWACCEL_VULKAN in args or "vulkan" in args:
# vulkan is vendor neutral, attribute it to whichever GPU is present
return _present_gpu()
return None
class HardwareStats:
"""Catalogs and polls all hardware relevant to the config."""
def __init__(self, config: FrigateConfig) -> None:
self.config = config
# hardware name -> bound poll function; the catalog of what to monitor
self._monitored: dict[str, Callable[[], HardwarePollResult]] = {}
self._errors: dict[str, float] = {}
self._executor = ThreadPoolExecutor(
max_workers=8, thread_name_prefix="hw_stats"
)
self._config_subscriber = CameraConfigUpdateSubscriber(
config,
config.cameras,
[
CameraConfigUpdateEnum.add,
CameraConfigUpdateEnum.remove,
CameraConfigUpdateEnum.ffmpeg,
CameraConfigUpdateEnum.audio_transcription,
CameraConfigUpdateEnum.semantic_search,
CameraConfigUpdateEnum.face_recognition,
CameraConfigUpdateEnum.lpr,
],
)
self.update_config()
def set_config(self, config: FrigateConfig) -> None:
"""Follow a runtime config swap and recalculate the monitored hardware.
The camera update subscriber has to follow too, or later camera updates
would land on the discarded config.
"""
self.config = config
self._config_subscriber.config = config
self._config_subscriber.camera_configs = config.cameras
self.update_config()
def update_config(self) -> None:
"""Recalculate all hardware that needs to be monitored from the config."""
names = self._scan_ffmpeg() | self._scan_detectors() | self._scan_enrichments()
monitored: dict[str, Callable[[], HardwarePollResult]] = {}
for name in sorted(names):
if name == "intel_gpu" and not self.config.telemetry.stats.intel_gpu_stats:
continue
if name == "amd_gpu" and not self.config.telemetry.stats.amd_gpu_stats:
continue
monitored[name] = partial(POLLERS[name], self.config)
self._monitored = monitored
logger.debug("Monitoring hardware for stats: %s", list(monitored))
def update_stats(self, all_stats: dict[str, Any]) -> None:
"""Poll the monitored hardware concurrently and fill usage stats."""
if self._config_subscriber.check_for_updates():
self.update_config()
now = time.monotonic()
hardware_futures: dict[Future[HardwarePollResult], str] = {}
for name, poll in self._monitored.items():
last_error = self._errors.get(name)
if last_error is not None:
if now - last_error < HARDWARE_ERROR_COOLDOWN_SECONDS:
continue
self._errors.pop(name, None)
hardware_futures[self._executor.submit(poll)] = name
cpu_future = self._executor.submit(get_cpu_stats)
futures: list[Future[Any]] = [*hardware_futures, cpu_future]
done, _ = wait(futures, timeout=POLL_TIMEOUT_SECONDS)
gpu_usages: dict[str, dict[str, Any]] = {}
npu_usages: dict[str, dict[str, Any]] = {}
for future, name in hardware_futures.items():
if future not in done:
logger.warning("Timed out collecting %s stats", name)
self._errors[name] = time.monotonic()
continue
try:
result = future.result()
except Exception:
logger.exception("Failed to collect %s stats", name)
self._errors[name] = time.monotonic()
continue
gpu_usages.update(result.gpu)
npu_usages.update(result.npu)
if not result.ok:
self._errors[name] = time.monotonic()
if gpu_usages:
all_stats["gpu_usages"] = gpu_usages
if npu_usages:
all_stats["npu_usages"] = npu_usages
if cpu_future in done:
try:
cpu_stats = cpu_future.result()
except Exception:
logger.exception("Failed to collect cpu stats")
else:
if cpu_stats:
all_stats["cpu_usages"] = cpu_stats
def stop(self) -> None:
self._config_subscriber.stop()
self._executor.shutdown(wait=False, cancel_futures=True)
def _scan_ffmpeg(self) -> set[str]:
"""Hardware used by camera hwaccel args (presets or raw ffmpeg args)."""
hwaccel_args: list[str] = []
for camera in self.config.cameras.values():
args = camera.ffmpeg.hwaccel_args
if isinstance(args, list):
args = " ".join(args)
if args and args not in hwaccel_args:
hwaccel_args.append(args)
for stream_input in camera.ffmpeg.inputs:
args = stream_input.hwaccel_args
if isinstance(args, list):
args = " ".join(args)
if args and args not in hwaccel_args:
hwaccel_args.append(args)
names: set[str] = set()
for args in hwaccel_args:
name = _hwaccel_hardware(args)
if name is not None:
names.add(name)
return names
def _scan_detectors(self) -> set[str]:
"""Hardware used by the configured detection models."""
names: set[str] = set()
for model in self.config.models:
for spec in self.config.devices_for_model(model):
if spec.detector == "rknn":
names.add("rockchip")
elif spec.detector == "axengine":
names.add("axengine")
elif spec.detector == "tensorrt":
names.add("jetson")
elif spec.detector == "openvino":
if spec.device == "NPU":
names.add("intel_npu")
elif spec.device is None or spec.device.startswith("GPU"):
names.add("intel_gpu")
elif spec.detector == "onnx":
gpu = _present_gpu()
if gpu is not None:
names.add(gpu)
return names
def _scan_enrichments(self) -> set[str]:
"""Hardware used by enabled enrichments, resolved to the present GPU."""
config = self.config
names: set[str] = set()
gpu = _present_gpu()
if gpu is not None:
semantic = config.semantic_search
if (
semantic.enabled
# GenAI providers run remotely and use no local hardware
and (
semantic.model is None
or isinstance(semantic.model, SemanticSearchModelEnum)
)
and (
semantic.device
or ("GPU" if semantic.model_size == "large" else "CPU")
)
!= "CPU"
):
names.add(gpu)
if (
config.face_recognition.enabled
and (config.face_recognition.device or "GPU") != "CPU"
):
names.add(gpu)
if config.lpr.enabled and (config.lpr.device or "AUTO") != "CPU":
names.add(gpu)
# audio transcription runs on CUDA only, and the device is global only
transcription = config.audio_transcription
transcription_enabled = transcription.enabled or any(
camera.audio_transcription.enabled for camera in config.cameras.values()
)
if (
transcription_enabled
and transcription.device == "GPU"
and "onnx:nvidia" in _present_hardware()
and _gpu_device_nodes_exist("nvidia")
):
names.add("nvidia")
return names
def read_temperature(path: str) -> float | None:
"""Read a sysfs temperature file, converting millidegrees to degrees.
Returns None when the file does not exist.
"""
if os.path.isfile(path):
with open(path) as f:
line = f.readline().strip()
return int(line) / 1000
return None
def get_hardware_temperatures(detector_type: str) -> list[float | None]:
"""Per unit temperatures for a detector type, in stable device order."""
if detector_type == "edgetpu":
# PCIe Corals expose a temperature through the apex driver
base = "/sys/class/apex/"
if os.path.isdir(base):
return [
read_temperature(os.path.join(base, apex, "temp"))
for apex in sorted(os.listdir(base))
]
elif detector_type == "hailo":
hailo_temps = get_hailo_temps()
return [hailo_temps[name] for name in sorted(hailo_temps.keys())]
elif detector_type == "axelera":
return [get_axelera_board_temp()]
return []