Skip to content

A GPU task manager for Windows, Linux, and WSL: per-process VRAM, GPU activity, and LLM model/KV-cache insights (Windows AMD and NVIDIA).

Python

Add macOS (Apple Silicon) backend

Sameh Khamis0a078d836b4e
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index aae2f0d..67a9631 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -13,7 +13,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- os: [windows-latest, ubuntu-latest]
+ os: [windows-latest, ubuntu-latest, macos-latest]
python: ["3.11", "3.13"]
steps:
- uses: actions/checkout@v4
diff --git a/README.md b/README.md
index 595d958..78c485d 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,8 @@
**An `htop` for what's inside your GPU, not just how full it is.**
-Windows + NVIDIA, with Linux and WSL support (see [Linux and WSL](#linux-and-wsl)). A terminal UI
+Windows + NVIDIA, with Linux and WSL support (see [Linux and WSL](#linux-and-wsl)) and macOS on Apple
+Silicon (see [macOS](#macos-apple-silicon)). A terminal UI
that connects per-process GPU memory and engine activity with loaded runtimes, model files, and
LLM buffer breakdowns.
@@ -199,6 +200,34 @@ That is one machine and driver, not a guarantee. A process that started long bef
the GPU can break the start-order guess, and processes started in the same refresh are ordered by
guess unless their sizes match.
+## macOS (Apple Silicon)
+
+Run from a clone (`uv run gputaskman`); there is no portable macOS download yet. Apple GPUs share
+one pool of memory with the CPU, so there is no VRAM to split and no spill/commit counters. What
+macOS exposes without root:
+
+| Column | Source | Who |
+|---|---|---|
+| GPU memory (header) | IOAccelerator `PerformanceStatistics`: `Alloc system memory` (all GPU allocations) out of physical RAM | device |
+| GPU% (header) | `Device Utilization %` | device |
+| GPU% | Each Metal client (`AGXDeviceUserClient`) names its creator PID and keeps a cumulative `accumulatedGPUTime`; the rate between samples | every process |
+| VRAM | `footprint`: the process's memory macOS charges to graphics (the `(graphics)` categories: Metal buffers, textures) | your own processes |
+| Runtime, model files | Mapped files from `proc_pidinfo` region walks (psutil has no memory maps on macOS): `libggml*.dylib`, `libllama*.dylib`, `libmlx*.dylib`, `libtorch_cpu.dylib`, the Metal driver bundle | your own processes |
+
+Other users' processes (WindowServer, system daemons) show GPU% with memory `n/a`: `footprint` needs
+root for them. Idle ones are left out of the table, except WindowServer. `footprint` takes ~70 ms per
+process, so it runs in a background thread, busiest process first; a new process shows `n/a` for a
+second or two until its first measurement. Spill, paged, clocks, power, and temperature are not
+available.
+
+Live check on an M4 Mac mini (macOS 26.3.1): a PyTorch MPS job with a 2 GiB buffer and a matmul loop
+showed `Python AI PyTorch+Metal 3.06 GB 99%`, with device utilization at 99% and allocated GPU
+memory rising by the same amount.
+
+Scans skip other apps' sandbox containers (`~/Library/Containers`, `~/Library/Group Containers`) and
+system files without opening them: opening a file in a protected container blocks while macOS waits
+for a privacy consent prompt.
+
## What you get
- **Device view:** VRAM usage, GPU activity, memory activity, PCIe traffic, temperature, power,
@@ -486,7 +515,7 @@ uv run --locked python -m unittest discover -s tests -v
uv build
```
-CI runs hardware-independent checks on Windows and Ubuntu, Python 3.11 and 3.13. Live GPU behavior
+CI runs hardware-independent checks on Windows, Ubuntu and macOS, Python 3.11 and 3.13. Live GPU behavior
still needs real hardware; the CI does not pretend to validate that. The WSL matching tests replay
context sequences measured on a real WSL2 machine.
@@ -533,6 +562,7 @@ downloads are bundled in this repository.
| `pdh.py` / `dxgi.py` | Windows counters and adapter enumeration |
| `linux.py` | Linux backend: NVML adapters and per-process usage, container PID matching, WSL detection, `/dev/dxg` holders |
| `wslhost.py` | WSL: interop check, Windows host counter stream, adapter pairing, context matching |
+| `macos.py` | macOS backend: IOKit device stats and per-process GPU time, `footprint` GPU memory poller, libproc memory maps |
| `nvml.py` | NVIDIA device readings |
| `procinfo.py` | Runtime, mapped-file, and process discovery |
| `stores.py` | Friendly names from Ollama, LM Studio, and Hugging Face model stores |
@@ -547,6 +577,8 @@ downloads are bundled in this repository.
- Explicit provenance and availability for every counter and estimate.
- Reliable multi-GPU matching and per-device model placement.
- Bare-metal Linux validation on hardware; AMD and Intel GPUs on Linux through DRM fdinfo.
+- macOS: a portable build, Ollama/llama.cpp/MLX validation, and compressed GPU memory (footprint's
+ `swapped`) as the paged column.
- WSL: per-process GPU load for Linux rows, and Ollama's systemd journal as a log source.
- Live throughput deltas, LM Studio validation, and per-model context accounting.
- Opt-in ETW file-open tracing to name models loaded by read-and-close runtimes (any whisper or ONNX
diff --git a/pyproject.toml b/pyproject.toml
index fac3220..7040ea2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -14,6 +14,7 @@ classifiers = [
"Environment :: Console",
"Operating System :: Microsoft :: Windows",
"Operating System :: POSIX :: Linux",
+ "Operating System :: MacOS",
"Programming Language :: Python :: 3",
"Topic :: System :: Monitoring",
]
diff --git a/src/gputaskman/app.py b/src/gputaskman/app.py
index f80f533..570d103 100644
--- a/src/gputaskman/app.py
+++ b/src/gputaskman/app.py
@@ -20,7 +20,7 @@ from textual.worker import get_current_worker
from .collector import Collector, ProcRow, Snapshot
from .llm import gb
from .nvml import NvDevice, format_metric
-from .report import WSL_EMPTY, has_engine_counters, has_wddm_counters, inferred_note, vram_label, wsl_note
+from .report import METAL_NOTE, WSL_EMPTY, has_engine_counters, has_wddm_counters, inferred_note, vram_label, wsl_note
KIND_STYLE = {
"LLM": "bold magenta", "decision": "bold orchid", "decision?": "orchid",
@@ -152,6 +152,9 @@ class HelpScreen(ModalScreen):
yield Markdown(HELP_MD)
+METAL_CHARTS = ("GPU", "VRAM")
+
+
class GpuTaskManager(App):
TITLE = "gputaskman"
CSS = """
@@ -292,8 +295,11 @@ class GpuTaskManager(App):
def render_device(self, s: Snapshot) -> Group:
nv = s.nv
name = s.adapter.name if s.adapter else (nv.name if nv else "GPU")
- head = Text.assemble((name, "bold"), f" driver {s.driver} CUDA {s.cuda} ",
- (nv.driver_model if nv else "", "bold yellow"), f" {nv.pci_bus if nv else ''}")
+ if s.backend == "metal":
+ head = Text.assemble((name, "bold"), f" {s.driver} ", ("Metal", "bold yellow"), " unified memory")
+ else:
+ head = Text.assemble((name, "bold"), f" driver {s.driver} CUDA {s.cuda} ",
+ (nv.driver_model if nv else "", "bold yellow"), f" {nv.pci_bus if nv else ''}")
if self.paused:
head.append(" [PAUSED]", style="bold red")
@@ -309,7 +315,7 @@ class GpuTaskManager(App):
other = max(s.vram_used - attributed * scale, 0)
parts.append((other, "grey35"))
width = max(min(self.size.width - 40, 90), 20)
- vram = Text("VRAM ")
+ vram = Text("GPU mem " if s.backend == "metal" else "VRAM ")
vram.append_text(stacked_bar(parts, s.vram_total, width))
vram.append(f" {gb(s.vram_used)} / {gb(s.vram_total)}", style="bold")
legend = Text(" ")
@@ -326,9 +332,14 @@ class GpuTaskManager(App):
legend.append(" [bar normalized; labels are raw]", style="grey62")
if s.backend == "wsl":
legend.append("\n " + wsl_note(s), style="grey62")
+ if s.backend == "metal":
+ legend.append("\n " + METAL_NOTE, style="grey62")
lines = [head, vram, legend]
- if nv:
+ if nv and s.backend == "metal":
+ lines.append(Text(f"GPU {format_metric(nv.util_gpu, unit='%')}",
+ style=f"bold {self.CHART_COLORS['GPU']}"))
+ elif nv:
rx = nv.pcie_rx_kbs / 1024 if nv.pcie_rx_kbs is not None else None
tx = nv.pcie_tx_kbs / 1024 if nv.pcie_tx_kbs is not None else None
pstate = f"P{nv.pstate}" if nv.pstate is not None else "P N/A"
@@ -380,6 +391,8 @@ class GpuTaskManager(App):
# Reserve the border, padding, and scrollbar even before child resize events arrive.
width = max(1, self.size.width - 6)
indices = list(range(len(self.CHARTS))) if self.chart_idx == -1 else [self.chart_idx]
+ if self.snap.backend == "metal" and self.chart_idx == -1:
+ indices = [i for i in indices if self.CHARTS[i] in METAL_CHARTS] # IOKit has no clocks/power/temp
columns = min(len(indices), 3, max(1, (width + 2) // 46))
cell_width = max(1, (width - 2 * (columns - 1)) // columns)
grid = Table.grid(padding=(0, 2), pad_edge=False, expand=True)
@@ -399,6 +412,7 @@ class GpuTaskManager(App):
_, power_scale, _, _ = self.chart_series(self.CHARTS.index("Power"), self.snap.nv)
_, clock_scale, _, _ = self.chart_series(self.CHARTS.index("SM clock"), self.snap.nv)
self.query_one("#chart-note", Static).update(
+ "Recent samples · blank = no reading" if self.snap.backend == "metal" else
f"Recent samples · blank = no reading · power 0–{power_scale:.0f} W · "
f"SM clock 0–{clock_scale:.0f} MHz"
)
@@ -491,6 +505,10 @@ class GpuTaskManager(App):
out.append(Text(inferred_note(r.gpu), style="grey62"))
elif s.wsl_split:
out.append(Text(f"No per-process VRAM: {s.wsl_split}.", style="grey62"))
+ elif s.backend == "metal":
+ out.append(Text("GPU memory n/a: footprint can't read other users' processes without root "
+ "(or hasn't measured this one yet). GPU% comes from Metal's per-process GPU time.",
+ style="grey62"))
if wddm and r.gpu.paged_out >= 64 << 20:
out.append(Text(f"{gb(r.gpu.paged_out)} of {gb(r.gpu.committed)} committed is not accounted for by local/non-local "
"usage. Estimated non-residency, not proof of eviction or disk paging.",
diff --git a/src/gputaskman/cli.py b/src/gputaskman/cli.py
index 737de75..959d9ca 100644
--- a/src/gputaskman/cli.py
+++ b/src/gputaskman/cli.py
@@ -22,8 +22,8 @@ def main() -> None:
if not math.isfinite(args.interval) or args.interval <= 0:
ap.error("--interval must be a finite number greater than zero")
- if sys.platform != "win32" and not sys.platform.startswith("linux"):
- sys.exit("gputaskman supports Windows (WDDM) and Linux/WSL (NVML) only.")
+ if sys.platform not in ("win32", "darwin") and not sys.platform.startswith("linux"):
+ sys.exit("gputaskman supports Windows (WDDM), Linux/WSL (NVML) and macOS (Apple Silicon) only.")
if args.gpu:
from .collector import enumerate_adapters, select_adapter
@@ -44,6 +44,8 @@ def main() -> None:
try:
if c.host is not None:
c.host.wait(15.0) # WSL: the first Windows counter sample takes several seconds
+ if hasattr(c.counters, "warm_up"):
+ c.counters.warm_up(15.0) # macOS: per-process GPU memory comes from a background footprint pass
time.sleep(1.0) # engine utilization is a rate; needs two samples
print(dump(c.sample(), args.json))
finally:
diff --git a/src/gputaskman/collector.py b/src/gputaskman/collector.py
index 331e935..7589e89 100644
--- a/src/gputaskman/collector.py
+++ b/src/gputaskman/collector.py
@@ -21,6 +21,11 @@ if sys.platform == "win32":
from .pdh import GpuCounters
BACKEND = "wddm"
+elif sys.platform == "darwin":
+ from .macos import MacCounters as GpuCounters
+ from .macos import enumerate_adapters, macos_version
+
+ BACKEND = "metal"
else:
from .linux import LinuxCounters as GpuCounters
from .linux import enumerate_adapters, is_wsl
@@ -103,7 +108,7 @@ class Snapshot:
vram_used: int # adapter-wide dedicated usage (WDDM counters, or NVML on Linux): the ground truth
shared_used: int
procs: list[ProcRow] = field(default_factory=list)
- backend: str = "wddm" # wddm (Windows) | nvml (native Linux) | wsl (device-wide only)
+ backend: str = "wddm" # wddm (Windows) | nvml (native Linux) | wsl (device-wide only) | metal (macOS)
host_status: str = "" # WSL only: Windows host counters via interop -- ok | starting | off (...) | ...
wsl_split: str = "" # WSL only: why Linux rows have no (inferred) VRAM, when they don't
@@ -173,6 +178,13 @@ class Collector:
self._own_start = time.time() # our NVML context is created now, not when the process started
self._host_restarted = time.time()
+ def _driver(self) -> str:
+ if BACKEND == "metal":
+ if not hasattr(self, "_macos"):
+ self._macos = f"macOS {macos_version()}".strip()
+ return self._macos
+ return self.nvml.driver
+
def _parent_ports(self, pid: int, depth: int = 2) -> list[int]:
d = self.inspector.get(pid)
if d.parents is None:
@@ -195,11 +207,13 @@ class Collector:
a = adapters.get(luid)
nvs = self.nvml.sample() if self.nvml.ok else []
nv = select_nv_device(self.adapter, nvs, self.gpu_index)
+ if BACKEND == "metal":
+ nv = self.counters.device # IOKit's device stats in the shape the header renders
total = (nv.mem_total if nv else 0) or (self.adapter.dedicated_vram if self.adapter else 0)
snap = Snapshot(
taken=time.time(), adapter=self.adapter, adapters=self.adapters, nv=nv,
- driver=self.nvml.driver, cuda=self.nvml.cuda_version, vram_total=total,
+ driver=self._driver(), cuda=self.nvml.cuda_version, vram_total=total,
vram_used=int(a.dedicated) if a else (nv.mem_used if nv else 0),
shared_used=int(a.shared) if a else 0, backend=BACKEND,
)
diff --git a/src/gputaskman/handy.py b/src/gputaskman/handy.py
index 4cc4036..737d902 100644
--- a/src/gputaskman/handy.py
+++ b/src/gputaskman/handy.py
@@ -122,6 +122,8 @@ def inspect_handy(
if sys.platform == "win32":
default_data = os.environ.get("APPDATA", "")
default_local = os.environ.get("LOCALAPPDATA", "")
+ elif sys.platform == "darwin": # Tauri's app data dir on macOS (logs/ location unverified)
+ default_data = default_local = os.path.join(os.path.expanduser("~"), "Library", "Application Support")
else: # Tauri keeps both the settings store and logs/ under the XDG data dir on Linux
default_data = default_local = os.environ.get("XDG_DATA_HOME") or os.path.join(
os.path.expanduser("~"), ".local", "share")
diff --git a/src/gputaskman/macos.py b/src/gputaskman/macos.py
new file mode 100644
index 0000000..99f63e1
--- /dev/null
+++ b/src/gputaskman/macos.py
@@ -0,0 +1,332 @@
+"""macOS GPU backend (Apple Silicon): device stats and per-process GPU time from IOKit, GPU memory from footprint.
+
+Apple GPUs share one pool of memory with the CPU (unified memory), so there is no VRAM to divide up and no
+spill/commit counters. What macOS does expose without root:
+
+- Device-wide: the IOAccelerator's PerformanceStatistics -- "Device Utilization %" and "Alloc system memory"
+ (GPU allocations across all processes).
+- Per process, for every user: each Metal client (AGXDeviceUserClient) names its creator PID and keeps a
+ cumulative accumulatedGPUTime in ns. GPU% is the change between two samples.
+- Per process, own processes only: footprint(1) reports the process's memory charged to graphics (Metal
+ buffers and textures) -- the "(graphics)" categories. Other users' processes (WindowServer, daemons) need
+ root, so their GPU memory is unknown, never zero.
+
+Measured on an M4 Mac mini (macOS 26.3): a PyTorch MPS job with a 2 GiB buffer showed 2.06 GiB of graphics
+footprint, GPU time matched Device Utilization (98% vs 99%), and Alloc system memory rose by the same amount.
+"""
+
+from __future__ import annotations
+
+import ctypes
+import json
+import os
+import plistlib
+import re
+import subprocess
+import tempfile
+import threading
+import time
+from collections import defaultdict
+from dataclasses import dataclass
+
+from .dxgi import Adapter
+from .nvml import NvDevice
+from .pdh import AdapterGpu, ProcGpu
+
+VENDOR_APPLE = 0x106B
+ADAPTER_KEY = 1 # one integrated GPU
+_CREATOR = re.compile(r"pid (\d+)")
+# Other users' processes show only GPU time; keep the idle ones out of the table (except the compositor).
+ALWAYS_SHOWN = {"windowserver"}
+
+
+def _ioreg(*args: str) -> list | None:
+ try:
+ out = subprocess.run(["ioreg", "-a", "-w", "0", "-r", *args], capture_output=True, timeout=5).stdout
+ return plistlib.loads(out) if out.strip() else []
+ except (OSError, subprocess.SubprocessError, plistlib.InvalidFileException, ValueError):
+ return None
+
+
+@dataclass
+class DeviceStats:
+ model: str = "Apple GPU"
+ cores: int | None = None
+ utilization: float | None = None # Device Utilization %
+ renderer: float | None = None
+ tiler: float | None = None
+ allocated: int = 0 # Alloc system memory: GPU allocations, all processes
+
+
+def parse_accelerator(entries: list | None) -> DeviceStats | None:
+ for e in entries or []:
+ stats = e.get("PerformanceStatistics")
+ if not isinstance(stats, dict):
+ continue
+ return DeviceStats(model=str(e.get("model", "Apple GPU")), cores=e.get("gpu-core-count"),
+ utilization=stats.get("Device Utilization %"),
+ renderer=stats.get("Renderer Utilization %"), tiler=stats.get("Tiler Utilization %"),
+ allocated=int(stats.get("Alloc system memory", 0)))
+ return None
+
+
+def parse_clients(entries: list | None) -> dict[int, int]:
+ """{pid: accumulated GPU ns} summed over that process's Metal clients."""
+ out: dict[int, int] = defaultdict(int)
+ for e in entries or []:
+ m = _CREATOR.match(str(e.get("IOUserClientCreator", "")))
+ if not m:
+ continue
+ pid = int(m[1])
+ out[pid] += sum(int(u.get("accumulatedGPUTime", 0)) for u in e.get("AppUsage") or [] if isinstance(u, dict))
+ return dict(out)
+
+
+def graphics_bytes(process: dict) -> int:
+ """footprint JSON: dirty bytes of the categories macOS charges to graphics."""
+ return int(sum(v.get("dirty", 0) for k, v in (process.get("categories") or {}).items() if k.endswith("(graphics)")))
+
+
+def physical_memory() -> int:
+ try:
+ return os.sysconf("SC_PHYS_PAGES") * os.sysconf("SC_PAGE_SIZE")
+ except (ValueError, OSError):
+ return 0
+
+
+def macos_version() -> str:
+ try:
+ return subprocess.run(["sw_vers", "-productVersion"], capture_output=True, text=True, timeout=5).stdout.strip()
+ except (OSError, subprocess.SubprocessError):
+ return ""
+
+
+def enumerate_adapters() -> list[Adapter]:
+ dev = parse_accelerator(_ioreg("-d", "1", "-c", "IOAccelerator"))
+ if dev is None:
+ return []
+ return [Adapter(luid=ADAPTER_KEY, name=dev.model, vendor_id=VENDOR_APPLE, dedicated_vram=physical_memory(),
+ shared_system=0, software=False)]
+
+
+def _owner(pid: int) -> int | None:
+ try:
+ import psutil
+ return psutil.Process(pid).uids().real
+ except Exception:
+ return None
+
+
+class FootprintPoller:
+ """footprint(1) takes ~70 ms per process, too slow for the refresh loop: poll the own-user GPU clients in
+ a background thread, busiest first, and keep the latest graphics size per PID."""
+
+ CYCLE = 2.0 # seconds between passes
+ DENIED_RETRY = 60.0
+
+ def __init__(self, run=subprocess.run) -> None:
+ self._run = run
+ self._targets: list[int] = []
+ self._sizes: dict[int, tuple[int, float]] = {}
+ self._denied: dict[int, float] = {}
+ self._lock = threading.Lock()
+ self._wake = threading.Event()
+ self._passed = threading.Event() # set after each completed pass
+ self._stop = False
+ self._thread: threading.Thread | None = None
+
+ def start(self) -> None:
+ if self._thread is None:
+ self._thread = threading.Thread(target=self._loop, name="macos-footprint", daemon=True)
+ self._thread.start()
+
+ def set_targets(self, pids: list[int]) -> None:
+ with self._lock:
+ self._targets = list(pids)
+ self._sizes = {p: v for p, v in self._sizes.items() if p in pids}
+ self._wake.set()
+
+ def get(self, pid: int) -> int | None:
+ with self._lock:
+ hit = self._sizes.get(pid)
+ return hit[0] if hit else None
+
+ def measure(self, pid: int) -> int | None:
+ with tempfile.TemporaryDirectory() as d:
+ path = os.path.join(d, "fp.json")
+ try:
+ self._run(["footprint", "-f", "bytes", "-j", path, "-p", str(pid)],
+ capture_output=True, timeout=10)
+ with open(path, encoding="utf-8") as f:
+ data = json.load(f)
+ except (OSError, subprocess.SubprocessError, ValueError):
+ return None
+ for p in data.get("processes") or []:
+ if p.get("pid") == pid:
+ return graphics_bytes(p)
+ return None
+
+ def poll_once(self) -> None:
+ with self._lock:
+ targets = list(self._targets)
+ now = time.time()
+ for pid in targets:
+ if self._stop:
+ return
+ if now - self._denied.get(pid, -1e9) < self.DENIED_RETRY:
+ continue
+ size = self.measure(pid)
+ with self._lock:
+ if size is None:
+ self._denied[pid] = now
+ self._sizes.pop(pid, None)
+ else:
+ self._sizes[pid] = (size, time.time())
+
+ def wait_pass(self, timeout: float) -> bool:
+ self._passed.clear()
+ return self._passed.wait(timeout)
+
+ def _loop(self) -> None:
+ while not self._stop:
+ start = time.time()
+ self.poll_once()
+ self._passed.set()
+ self._wake.wait(max(self.CYCLE - (time.time() - start), 0.2))
+ self._wake.clear()
+
+ def close(self) -> None:
+ self._stop = True
+ self._wake.set()
+
+
+class MacCounters:
+ """Same interface as pdh.GpuCounters: sample() -> ({adapter key: {pid: ProcGpu}}, {adapter key: AdapterGpu}).
+ `device` carries the device-wide stats in the NvDevice shape the header already renders."""
+
+ def __init__(self, poller: FootprintPoller | None = None, uid: int | None = None) -> None:
+ self.ok = True
+ self.device: NvDevice | None = None
+ self._prev: dict[int, tuple[int, float]] = {} # pid -> (gpu ns, wall time)
+ self._uid = os.getuid() if uid is None else uid
+ self._owners: dict[int, int | None] = {}
+ self.poller = poller or FootprintPoller()
+ self._names: dict[int, str] = {}
+ self.poller.start()
+ self.sample() # baseline: GPU% is a rate, like the WDDM counters' first collection
+
+ def warm_up(self, timeout: float) -> None:
+ """One-shot output: wait for a full footprint pass so own processes have their GPU memory."""
+ self.poller.wait_pass(timeout)
+
+ def _name(self, pid: int) -> str:
+ if pid not in self._names:
+ try:
+ import psutil
+ self._names[pid] = psutil.Process(pid).name()
+ except Exception:
+ self._names[pid] = ""
+ return self._names[pid]
+
+ def sample(self, accel: list | None = None, clients: list | None = None,
+ now: float | None = None) -> tuple[dict[int, dict[int, ProcGpu]], dict[int, AdapterGpu]]:
+ now = time.time() if now is None else now
+ accel = _ioreg("-d", "1", "-c", "IOAccelerator") if accel is None else accel
+ clients = _ioreg("-l", "-c", "AGXDeviceUserClient") if clients is None else clients
+ procs: dict[int, dict[int, ProcGpu]] = defaultdict(dict)
+ adapters: dict[int, AdapterGpu] = defaultdict(AdapterGpu)
+ dev = parse_accelerator(accel)
+ if dev is not None:
+ adapters[ADAPTER_KEY].dedicated = float(dev.allocated)
+ self.device = NvDevice(index=0, name=dev.model, driver_model="Metal", mem_total=physical_memory(),
+ mem_used=dev.allocated, util_gpu=dev.utilization)
+ times = parse_clients(clients)
+ own: list[tuple[float, int]] = []
+ for pid, ns in times.items():
+ prev = self._prev.get(pid)
+ pct = 0.0
+ if prev is not None and now > prev[1] and ns >= prev[0]:
+ pct = min((ns - prev[0]) / 1e9 / (now - prev[1]) * 100.0, 100.0)
+ if pid not in self._owners:
+ self._owners[pid] = _owner(pid)
+ mine = self._owners[pid] == self._uid
+ g = ProcGpu()
+ if pct:
+ g.engines["gpu"] = pct
+ if mine:
+ own.append((pct, pid))
+ size = self.poller.get(pid)
+ if size is None:
+ g.attributed = False # not measured yet (or footprint failed): unknown, not zero
+ else:
+ g.dedicated = float(size)
+ else:
+ g.attributed = False # footprint needs root for other users' processes
+ if pct < 0.5 and self._name(pid).lower() not in ALWAYS_SHOWN:
+ continue
+ procs[ADAPTER_KEY][pid] = g
+ self._prev = {pid: (ns, now) for pid, ns in times.items()}
+ self._owners = {p: o for p, o in self._owners.items() if p in times}
+ self._names = {p: n for p, n in self._names.items() if p in times}
+ self.poller.set_targets([pid for _, pid in sorted(own, reverse=True)])
+ return procs, adapters
+
+ def close(self) -> None:
+ self.poller.close()
+
+
+# ---------------------------------------------------------------- memory maps (psutil has none on macOS)
+
+PROC_PIDREGIONINFO = 7
+
+
+class _RegionInfo(ctypes.Structure): # struct proc_regioninfo, <sys/proc_info.h>
+ _fields_ = [(n, ctypes.c_uint32) for n in ("protection", "max_protection", "inheritance", "flags")] + [
+ ("offset", ctypes.c_uint64)] + [(n, ctypes.c_uint32) for n in (
+ "behavior", "user_wired_count", "user_tag", "pages_resident", "pages_shared_now_private",
+ "pages_swapped_out", "pages_dirtied", "ref_count", "shadow_depth", "share_mode",
+ "private_pages_resident", "shared_pages_resident", "obj_id", "depth")] + [
+ ("address", ctypes.c_uint64), ("size", ctypes.c_uint64)]
+
+
+@dataclass
+class MappedFile:
+ path: str
+ rss: int
+
+
+_libproc = None
+
+
+def _load_libproc():
+ global _libproc
+ if _libproc is None:
+ lib = ctypes.CDLL("/usr/lib/libproc.dylib", use_errno=True)
+ lib.proc_pidinfo.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_uint64, ctypes.c_void_p, ctypes.c_int]
+ lib.proc_regionfilename.argtypes = [ctypes.c_int, ctypes.c_uint64, ctypes.c_void_p, ctypes.c_uint32]
+ _libproc = lib
+ return _libproc
+
+
+def memory_maps(pid: int, max_regions: int = 200_000) -> list[MappedFile]:
+ """File-backed regions of a process, grouped by path (like psutil's memory_maps(grouped=True)). Walks the
+ address space with proc_pidinfo(PROC_PIDREGIONINFO) -- ~4 ms for a desktop app. Raises PermissionError
+ for processes this user can't inspect."""
+ lib = _load_libproc()
+ info, buf = _RegionInfo(), ctypes.create_string_buffer(4096)
+ page = os.sysconf("SC_PAGE_SIZE")
+ files: dict[str, int] = {}
+ addr, n = 0, 0
+ while n < max_regions:
+ if lib.proc_pidinfo(pid, PROC_PIDREGIONINFO, addr, ctypes.byref(info), ctypes.sizeof(info)) != ctypes.sizeof(info):
+ break
+ n += 1
+ if lib.proc_regionfilename(pid, info.address, buf, len(buf)) > 0:
+ path = buf.value.decode("utf-8", "replace")
+ files[path] = files.get(path, 0) + info.pages_resident * page
+ if info.size == 0:
+ break
+ addr = info.address + info.size
+ if n == 0:
+ raise PermissionError(f"cannot read the address space of pid {pid}")
+ return [MappedFile(p, rss) for p, rss in files.items()]
diff --git a/src/gputaskman/procinfo.py b/src/gputaskman/procinfo.py
index 7d589bf..902bc45 100644
--- a/src/gputaskman/procinfo.py
+++ b/src/gputaskman/procinfo.py
@@ -14,20 +14,22 @@ import psutil
from .gguf import is_gguf, read_gguf
from .stores import store_name
-# (tag, library patterns: Windows DLLs and Linux shared objects with the version suffix removed, see
-# _lib_name). Order = display priority (most specific first).
+# (tag, library patterns: Windows DLLs, Linux shared objects with the version suffix removed, and macOS
+# dylibs, see _lib_name). Order = display priority (most specific first).
RUNTIMES: list[tuple[str, tuple[str, ...]]] = [
- ("llama.cpp", ("llama.dll", "libllama*.dll", "llama-*.dll", "llm_engine*", "libllama*.so")),
- ("whisper.cpp", ("whisper*.dll", "libwhisper*.so")),
- ("ggml", ("ggml*.dll", "libggml*.so")),
- ("PyTorch", ("torch_cuda*.dll", "torch_cpu.dll", "libtorch_cuda*.so", "libtorch_cpu.so")),
+ ("llama.cpp", ("llama.dll", "libllama*.dll", "llama-*.dll", "llm_engine*", "libllama*.so", "libllama*.dylib")),
+ ("whisper.cpp", ("whisper*.dll", "libwhisper*.so", "libwhisper*.dylib")),
+ ("ggml", ("ggml*.dll", "libggml*.so", "libggml*.dylib")),
+ ("PyTorch", ("torch_cuda*.dll", "torch_cpu.dll", "libtorch_cuda*.so", "libtorch_cpu.so", "libtorch_cpu.dylib")),
+ ("MLX", ("libmlx*.dylib",)),
("TensorRT", ("nvinfer*.dll", "libnvinfer*.so")),
- ("ONNX RT", ("onnxruntime*.dll", "libonnxruntime*.so")),
+ ("ONNX RT", ("onnxruntime*.dll", "libonnxruntime*.so", "libonnxruntime*.dylib")),
("DirectML", ("directml.dll",)),
("cuDNN", ("cudnn*.dll", "libcudnn*.so")),
("CUDA", ("nvcuda.dll", "nvcuda64.dll", "cudart64_*.dll", "cublas64_*.dll",
"libcuda.so", "libcudart.so", "libcublas.so")),
- ("Vulkan", ("vulkan-1.dll", "libvulkan.so")),
+ ("Metal", ("agxmetal*",)), # the Apple GPU's Metal driver bundle, mapped by every Metal process
+ ("Vulkan", ("vulkan-1.dll", "libvulkan.so", "libmoltenvk.dylib")),
("D3D12", ("d3d12core.dll", "libd3d12core.so")),
("OpenGL", ("opengl32.dll", "libgl.so", "libglx*.so", "libegl*.so")),
("D3D11", ("d3d11.dll",)),
@@ -35,18 +37,31 @@ RUNTIMES: list[tuple[str, tuple[str, ...]]] = [
("NVDEC", ("nvcuvid.dll", "nvcuvid64.dll", "libnvcuvid.so")),
]
_SO = re.compile(r"^(.+\.so)(?:\.[0-9][0-9a-z.]*)?$")
-AI_RUNTIMES = {"llama.cpp", "whisper.cpp", "ggml", "PyTorch", "TensorRT", "ONNX RT", "DirectML", "cuDNN"}
+AI_RUNTIMES = {"llama.cpp", "whisper.cpp", "ggml", "PyTorch", "MLX", "TensorRT", "ONNX RT", "DirectML", "cuDNN"}
_RUNTIME_RX = [(tag, re.compile("|".join(fnmatch.translate(p) for p in pats))) for tag, pats in RUNTIMES]
MODEL_EXTS = {".gguf", ".ggml", ".safetensors", ".onnx", ".pt", ".pth", ".bin", ".engine", ".plan", ".tflite", ".ckpt"}
AMBIGUOUS_EXTS = {".bin", ".pt", ".pth", ".ckpt"} # also used for caches/tiles, so require size or a model store
_NOT_MODELS = {".dll", ".exe", ".sys", ".mui", ".ttf", ".ttc", ".otf", ".dat", ".db", ".nls", ".pak", ".mun"}
BROWSERS = {"msedge.exe", "chrome.exe", "firefox.exe", "msedgewebview2.exe", "brave.exe", "opera.exe", "arc.exe", "vivaldi.exe",
- "chrome", "chromium", "chromium-browser", "firefox", "firefox-bin", "brave", "msedge", "opera", "vivaldi-bin"}
+ "chrome", "chromium", "chromium-browser", "firefox", "firefox-bin", "brave", "msedge", "opera", "vivaldi-bin",
+ # macOS: browsers draw through a GPU helper process
+ "google chrome helper (gpu)", "microsoft edge helper (gpu)", "brave browser helper (gpu)",
+ "arc helper (gpu)", "chromium helper (gpu)", "com.apple.webkit.gpu", "safari", "firefox gpu helper"}
# Linux display servers / compositors: they own the desktop back buffers, like dwm.exe on Windows.
COMPOSITORS = {"dwm.exe", "xorg", "xwayland", "gnome-shell", "kwin_wayland", "kwin_x11", "sway", "hyprland",
- "mutter", "weston", "wayfire", "labwc", "niri", "cosmic-comp", "picom", "compiz"}
+ "mutter", "weston", "wayfire", "labwc", "niri", "cosmic-comp", "picom", "compiz", "windowserver"}
# Paths in /proc/<pid>/maps that are not regular files: never stat or open them.
_SPECIAL_PREFIXES = ("[", "/dev/", "/proc/", "/sys/", "/memfd:", "/SYSV", "anon_inode:")
+# macOS: other apps' sandbox containers are privacy-protected, and open() on them blocks waiting for a consent
+# prompt (seen with mediaanalysisd's caches over SSH). System files are never models: skip both unopened.
+_MAC_SKIP_PREFIXES = ("/System/", "/usr/lib/", "/usr/share/", "/private/var/db/", "/Library/Apple/")
+_MAC_SKIP_PARTS = ("/Library/Containers/", "/Library/Group Containers/")
+
+
+def _skip_path(path: str) -> bool:
+ if path.startswith(_SPECIAL_PREFIXES) or path.endswith(" (deleted)"):
+ return True
+ return sys.platform == "darwin" and (path.startswith(_MAC_SKIP_PREFIXES) or any(p in path for p in _MAC_SKIP_PARTS))
LLM_NAMES = ("llama-", "llama.", "ollama", "lm studio", "lmstudio", "llmster", "koboldcpp", "jan", "gpt4all", "llamafile")
# GGUF file kind -> process kind, in display priority order
MODEL_KINDS = {"LLM": "LLM", "decision model": "decision", "embedding model": "embedding",
@@ -122,7 +137,7 @@ def _lib_name(base: str) -> str | None:
"""Lower-cased library file name with any Linux version suffix removed ('libcudart.so.12.4' ->
'libcudart.so'), or None when this is not a library."""
ext = os.path.splitext(base)[1]
- if ext in (".dll", ".node"):
+ if ext in (".dll", ".node", ".dylib") or base.startswith("agxmetal"):
return base
m = _SO.match(base)
return m[1] if m else None
@@ -203,13 +218,15 @@ def _is_system_path(exe: str) -> bool:
if sys.platform == "win32":
return exe.startswith(os.path.normcase(os.environ.get("SystemRoot", r"C:\Windows")))
# /usr/bin/python3 is shared by every Python app: walking /usr/bin finds nothing about the process.
- return exe.startswith(_LINUX_SYSTEM_DIRS)
+ return exe.startswith(_LINUX_SYSTEM_DIRS) or (sys.platform == "darwin" and exe.startswith(("/system/", "/System/")))
def _data_dirs() -> list[str]:
if sys.platform == "win32":
return [d for d in (os.environ.get("APPDATA"), os.environ.get("LOCALAPPDATA")) if d]
home = os.path.expanduser("~")
+ if sys.platform == "darwin":
+ return [os.path.join(home, "Library", "Application Support")]
return [os.environ.get("XDG_DATA_HOME") or os.path.join(home, ".local", "share"),
os.environ.get("XDG_CONFIG_HOME") or os.path.join(home, ".config")]
@@ -342,7 +359,7 @@ class ProcInspector:
"""Memory maps -> loaded DLLs (runtimes) and mapped model files. Never uses open_files(): ~1-2 s/process."""
d.maps_time, d.scan_mem = time.time(), mem
try:
- maps = psutil.Process(d.pid).memory_maps(grouped=True)
+ maps = _memory_maps(d.pid)
except (psutil.Error, OSError):
d.access_denied = True
return
@@ -350,11 +367,14 @@ class ProcInspector:
models: dict[str, MappedModel] = {}
for m in maps:
path = m.path
- if path.startswith(_SPECIAL_PREFIXES) or path.endswith(" (deleted)"):
- continue
base = os.path.basename(path).lower()
- ext = os.path.splitext(base)[1]
lib = _lib_name(base)
+ if lib and base.startswith("agxmetal"):
+ dlls.add(lib) # the Metal driver lives under /System: record it before skipping system paths
+ continue
+ if _skip_path(path):
+ continue
+ ext = os.path.splitext(base)[1]
if lib:
dlls.add(lib)
continue
@@ -386,6 +406,13 @@ class ProcInspector:
del self._cache[pid]
+def _memory_maps(pid: int) -> list:
+ if sys.platform == "darwin": # psutil has no memory_maps() on macOS
+ from .macos import memory_maps
+ return memory_maps(pid)
+ return psutil.Process(pid).memory_maps(grouped=True)
+
+
def classify(d: ProcDetail, engines: dict[str, float]) -> str:
n = d.name.lower()
if d.pid == 4 and sys.platform == "win32": # "System"; PID 4 is an ordinary process on Linux
diff --git a/src/gputaskman/report.py b/src/gputaskman/report.py
index a9895f6..0df099c 100644
--- a/src/gputaskman/report.py
+++ b/src/gputaskman/report.py
@@ -57,6 +57,11 @@ def inferred_note(g) -> str:
return ORDER_NOTE if g.inferred_by == "order" else INFERRED_NOTE
+METAL_NOTE = ("macOS: unified memory, so GPU memory is part of system RAM. Rows show each process's graphics "
+ "footprint; other users' processes (WindowServer, daemons) show GPU% only, since reading their "
+ "memory needs root.")
+
+
def to_dict(s: Snapshot) -> dict:
nv = dataclasses.asdict(s.nv) if s.nv else None
procs = []
@@ -108,12 +113,19 @@ def to_text(s: Snapshot, limit: int = 30) -> str:
out = []
nv = s.nv
name = s.adapter.name if s.adapter else "GPU"
- out.append(f"{name} driver {s.driver} CUDA {s.cuda} {nv.driver_model if nv else ''}")
- shared = f" shared (in system RAM) {gb(s.shared_used)}" if s.backend == "wddm" or s.host_data else ""
- out.append(f"VRAM {gb(s.vram_used)} / {gb(s.vram_total)}{shared}")
+ if s.backend == "metal":
+ out.append(f"{name} {s.driver} Metal")
+ out.append(f"GPU memory {gb(s.vram_used)} allocated / {gb(s.vram_total)} unified")
+ out.append(METAL_NOTE)
+ if nv:
+ out.append(f"GPU {format_metric(nv.util_gpu, unit='%')}")
+ else:
+ out.append(f"{name} driver {s.driver} CUDA {s.cuda} {nv.driver_model if nv else ''}")
+ shared = f" shared (in system RAM) {gb(s.shared_used)}" if s.backend == "wddm" or s.host_data else ""
+ out.append(f"VRAM {gb(s.vram_used)} / {gb(s.vram_total)}{shared}")
if s.backend == "wsl":
out.append(wsl_note(s))
- if nv:
+ if nv and s.backend != "metal":
rx = nv.pcie_rx_kbs / 1024 if nv.pcie_rx_kbs is not None else None
tx = nv.pcie_tx_kbs / 1024 if nv.pcie_tx_kbs is not None else None
pstate = f"P{nv.pstate}" if nv.pstate is not None else "P N/A"
diff --git a/tests/test_core.py b/tests/test_core.py
index ed140cd..f2eba50 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -550,8 +550,7 @@ class IdentityTests(unittest.TestCase):
path = str(Path(directory) / "model.gguf")
Path(path).write_bytes(b"not a GGUF")
detail = ProcDetail(6, "llama-server.exe", cmdline=["server", "--model", path, "--mmproj", path])
- with patch("gputaskman.procinfo.psutil.Process") as process:
- process.return_value.memory_maps.return_value = []
+ with patch("gputaskman.procinfo._memory_maps", return_value=[]):
ProcInspector().scan(detail)
self.assertEqual(len(detail.models), 1)
self.assertEqual(detail.models[0].sources, ["cmdline"])
diff --git a/tests/test_macos.py b/tests/test_macos.py
new file mode 100644
index 0000000..8562e8e
--- /dev/null
+++ b/tests/test_macos.py
@@ -0,0 +1,185 @@
+"""macOS backend. Fixtures follow ioreg/footprint output measured on an M4 Mac mini (macOS 26.3.1)."""
+
+from __future__ import annotations
+
+import json
+import plistlib
+import unittest
+from unittest.mock import patch
+
+from gputaskman import macos
+from gputaskman.collector import ProcRow, Snapshot
+from gputaskman.pdh import ProcGpu
+from gputaskman.procinfo import ProcDetail, _lib_name, _match_runtimes
+from gputaskman.report import to_dict, to_text
+
+GiB = 1 << 30
+ME, ROOT = 501, 0
+
+
+def accel(util=28, alloc=2202157056):
+ return [{"IOClass": "AGXAcceleratorG16G", "model": "Apple M4", "gpu-core-count": 10,
+ "PerformanceStatistics": {"Device Utilization %": util, "Renderer Utilization %": util,
+ "Tiler Utilization %": util, "Alloc system memory": alloc,
+ "In use system memory": 13598720}}]
+
+
+def client(pid, name, *times):
+ return {"IOUserClientCreator": f"pid {pid}, {name}",
+ "AppUsage": [{"API": "Metal", "accumulatedGPUTime": t} for t in times]}
+
+
+class FakePoller:
+ def wait_pass(self, timeout):
+ return True
+
+ def __init__(self, sizes=None):
+ self.sizes = sizes or {}
+ self.targets = []
+
+ def start(self):
+ pass
+
+ def set_targets(self, pids):
+ self.targets = pids
+
+ def get(self, pid):
+ return self.sizes.get(pid)
+
+ def close(self):
+ pass
+
+
+class ParseTests(unittest.TestCase):
+ def test_ioreg_plist_round_trip(self):
+ entries = plistlib.loads(plistlib.dumps(accel(99, 5494423552)))
+ dev = macos.parse_accelerator(entries)
+ self.assertEqual((dev.model, dev.cores, dev.utilization, dev.allocated), ("Apple M4", 10, 99, 5494423552))
+ self.assertIsNone(macos.parse_accelerator([{"model": "x"}]))
+ self.assertIsNone(macos.parse_accelerator(None))
+
+ def test_gpu_time_is_summed_per_process(self):
+ # WindowServer has several Metal clients; runningboardd has one with no usage yet
+ times = macos.parse_clients([client(167, "WindowServer", 53012153708, 17704333),
+ client(167, "WindowServer", 262833), client(176, "runningboardd"),
+ {"IOUserClientCreator": "garbage"}])
+ self.assertEqual(times, {167: 53012153708 + 17704333 + 262833, 176: 0})
+
+ def test_graphics_footprint_counts_only_graphics_categories(self):
+ process = {"pid": 79379, "categories": {
+ "Owned physical footprint (unmapped) (graphics)": {"dirty": 2162163712, "swapped": 0},
+ "IOAccelerator (graphics)": {"dirty": 8880128, "swapped": 0},
+ "IOAccelerator": {"dirty": 65536}, "MALLOC_SMALL": {"dirty": 58 << 20}}}
+ self.assertEqual(macos.graphics_bytes(process), 2162163712 + 8880128)
+
+
+class CountersTests(unittest.TestCase):
+ def counters(self, sizes, owners):
+ poller = FakePoller(sizes)
+ with patch.object(macos, "_owner", side_effect=lambda pid: owners.get(pid)), \
+ patch.object(macos, "_ioreg", return_value=[]): # the constructor's baseline sees nothing
+ c = macos.MacCounters(poller=poller, uid=ME)
+ c._owners = dict(owners)
+ c._names = {167: "WindowServer", 176: "runningboardd", 900: "backupd"}
+ return c, poller
+
+ def test_gpu_percent_memory_and_honest_unknowns(self):
+ owners = {79379: ME, 486: ME, 167: ROOT, 176: ROOT, 900: ROOT}
+ c, poller = self.counters({79379: 2162163712 + 8880128}, owners)
+ first = [client(79379, "python3.13", 10 * 10**9), client(486, "wezterm-gui", 4 * 10**9),
+ client(167, "WindowServer", 50 * 10**9), client(176, "runningboardd", 0),
+ client(900, "backupd", 7 * 10**9)]
+ c.sample(accel(), first, now=100.0)
+ second = [client(79379, "python3.13", 10 * 10**9 + 1_968_000_000), client(486, "wezterm-gui", 4 * 10**9),
+ client(167, "WindowServer", 50 * 10**9 + 40_000_000), client(176, "runningboardd", 0),
+ client(900, "backupd", 7 * 10**9)]
+ procs, adapters = c.sample(accel(99, 5494423552), second, now=102.0)
+ per = procs[macos.ADAPTER_KEY]
+ self.assertAlmostEqual(per[79379].gpu_pct, 98.4) # measured: 98.4% vs Device Utilization 99%
+ self.assertEqual(per[79379].dedicated, 2162163712 + 8880128)
+ self.assertTrue(per[79379].attributed)
+ self.assertFalse(per[486].attributed) # own process, not measured yet: unknown, not 0
+ self.assertFalse(per[167].attributed) # root's WindowServer: GPU% only
+ self.assertAlmostEqual(per[167].gpu_pct, 2.0)
+ self.assertNotIn(176, per) # idle daemons of other users stay out of the table
+ self.assertNotIn(900, per)
+ self.assertEqual(poller.targets, [79379, 486]) # busiest own process measured first
+ self.assertEqual(adapters[macos.ADAPTER_KEY].dedicated, 5494423552)
+ self.assertEqual((c.device.name, c.device.util_gpu, c.device.driver_model), ("Apple M4", 99, "Metal"))
+
+ def test_counter_reset_is_not_negative(self):
+ c, _ = self.counters({}, {1: ME})
+ c.sample(accel(), [client(1, "a", 5 * 10**9)], now=1.0)
+ procs, _ = c.sample(accel(), [client(1, "a", 1 * 10**9)], now=2.0) # PID reused
+ self.assertEqual(procs[macos.ADAPTER_KEY][1].gpu_pct, 0.0)
+
+
+class PollerTests(unittest.TestCase):
+ def test_footprint_json_is_read_per_pid(self):
+ def run(args, **kw):
+ path = args[args.index("-j") + 1]
+ pid = int(args[-1])
+ with open(path, "w", encoding="utf-8") as f:
+ json.dump({"processes": [{"pid": pid, "categories": {
+ "IOAccelerator (graphics)": {"dirty": 3 * GiB}}}]}, f)
+
+ p = macos.FootprintPoller(run=run)
+ p.set_targets([42])
+ p.poll_once()
+ self.assertEqual(p.get(42), 3 * GiB)
+
+ def test_denied_processes_are_retried_later_not_every_pass(self):
+ calls = []
+
+ def run(args, **kw):
+ calls.append(args) # writes nothing, like footprint on a root process
+
+ p = macos.FootprintPoller(run=run)
+ p.set_targets([170])
+ p.poll_once()
+ p.poll_once()
+ self.assertEqual(len(calls), 1)
+ self.assertIsNone(p.get(170))
+
+
+class ProcInfoTests(unittest.TestCase):
+ def test_macos_libraries_and_metal_driver(self):
+ names = {_lib_name(b) for b in ("libggml-metal.dylib", "libllama.dylib", "libmlx.dylib",
+ "agxmetalg16g_b0", "libtorch_cpu.dylib", "assets.car")}
+ self.assertNotIn("assets.car", names)
+ self.assertEqual(_match_runtimes(names - {None}), ["llama.cpp", "ggml", "PyTorch", "MLX", "Metal"])
+
+
+class SkipPathTests(unittest.TestCase):
+ def test_protected_containers_and_system_files_are_never_opened(self):
+ from gputaskman import procinfo
+ with patch.object(procinfo.sys, "platform", "darwin"):
+ self.assertTrue(procinfo._skip_path(
+ "/Users/me/Library/Containers/com.apple.mediaanalysisd/Data/Library/Caches/PFSceneGeographyData.index"))
+ self.assertTrue(procinfo._skip_path("/Users/me/Library/Group Containers/group.x/db"))
+ self.assertTrue(procinfo._skip_path("/System/Library/Fonts/SFNS.ttf"))
+ self.assertFalse(procinfo._skip_path("/Users/me/.ollama/models/blobs/sha256-abc"))
+ with patch.object(procinfo.sys, "platform", "linux"):
+ self.assertFalse(procinfo._skip_path("/usr/lib/x86_64-linux-gnu/libcuda.so.1"))
+
+
+class ReportTests(unittest.TestCase):
+ def test_metal_header_and_json(self):
+ rows = [ProcRow(79379, "python3.13", "AI", ProcGpu(dedicated=2 * GiB, engines={"gpu": 98.4}),
+ ProcDetail(79379, "python3.13")),
+ ProcRow(167, "WindowServer", "compositor", ProcGpu(attributed=False, engines={"gpu": 2.0}),
+ ProcDetail(167, "WindowServer"))]
+ snap = Snapshot(taken=1, adapter=None, adapters=[], nv=None, driver="macOS 26.3.1", cuda="",
+ vram_total=16 * GiB, vram_used=5 * GiB, shared_used=0, backend="metal", procs=rows)
+ text = to_text(snap)
+ self.assertIn("unified", text)
+ self.assertNotIn("CUDA", text)
+ ws = next(line for line in text.splitlines() if line.lstrip().startswith("167"))
+ self.assertIn("n/a", ws)
+ data = to_dict(snap)["processes"]
+ self.assertEqual((data[0]["vram_bytes"], data[1]["vram_bytes"], data[1]["gpu_pct"]), (2 * GiB, None, 2.0))
+ self.assertIsNone(data[0]["shared_bytes"])
+
+
+if __name__ == "__main__":
+ unittest.main()