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

Show NVIDIA TCC-mode GPUs on Windows (#37)

Scott Hanselmanb4d7052d5d6d
diff --git a/AGENTS.md b/AGENTS.md
index af43d0e..4d77026 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -51,8 +51,9 @@ these rules:
```
cli.py ──► Collector.sample() (collector.py)
- ├─ adapters dxgi.py (Windows) / linux.enumerate_adapters / macos.enumerate_adapters
- ├─ counters pdh.py GpuCounters (Windows PDH) / linux.py LinuxCounters (NVML, + drm.py for amdgpu and Intel) /
+ ├─ adapters dxgi.py (Windows; tcc.py adds NVIDIA TCC GPUs that DXGI omits) / linux.enumerate_adapters / macos.enumerate_adapters
+ ├─ counters pdh.py GpuCounters (Windows PDH) / tcc.py TccCounters (NVML, TCC GPUs on Windows) /
+ │ linux.py LinuxCounters (NVML, + drm.py for amdgpu and Intel) /
│ macos.py MacCounters (IOKit Metal clients + footprint poller)
├─ device metrics nvml.py; drm.py read_device (AMD and Intel, Linux) (macOS: MacCounters.device from IOKit)
├─ WSL host wslhost.py: HostStream (powershell PDH via interop), ContextTracker
@@ -87,6 +88,7 @@ identify everything immediately; the TUI spreads scans across refreshes.
| Change snapshot comparison | `diff.py` | Works only on saved `--json` files, never live state. Compare measured fields directly; keep runtime-reported and estimated values in their own sections; an absent row is `not listed`, not zero. Refuse only when both snapshots name conflicting adapters (vendor, PCI address, a non-Windows key); when they cannot be compared, warn (`name-only`) instead, because a Windows LUID changes at boot and `diff` has no override flag. A PID whose two `started_at` values are both valid and more than `SAME_PROCESS_SECS` apart is a different process: no pairing rule may join it (unknown or malformed start times never conflict, so older snapshots pair as before) |
| Change system RAM/CPU | `host.py` | Machine memory and load as the OS reports them: never GPU bytes, never added to `Snapshot.attributed`, and `diff` ignores it. Unknown is `None`/`null` and a failure carries a reason, never zeros. The JSON key is `system` because `host` already means the WSL Windows host. Windows uses the NT process list (psutil per process takes about 6 s per pass for 1,000 processes), checked against psutil at startup; CPU rates are keyed by `(pid, create_time)` so a reused PID never inherits another process's history (on the psutil path, `is_running()` is what makes psutil drop its cached object for a reused PID; keep that call) |
| Change WSL matching | `wslhost.py` `ContextTracker` | Keep `tests/test_wslhost.py` replays passing; they are measured sequences |
+| Change TCC support | `tcc.py`, the win32 `enumerate_adapters` wrapper in `collector.py` | NVML only, never a PDH query (Windows publishes no counters for a TCC GPU). NVML is asked once per process; TCC GPUs are paired to DXGI only when the domainless address is unambiguous (PCI domain 0), while the full domain stays in TCC identity and its synthetic LUID. Append after listed adapters so no existing GPU index moves. A process whose memory NVML hides is `n/a` with `attributed` unknown, never 0. No model breakdown (it needs the shared counter). `--list-gpus` distinguishes a successful empty probe from a failed/incomplete probe. Keep `tests/test_tcc.py` passing; mocks do not validate TCC hardware |
| Change recording | `record.py`, `cli.py` `record_main` | Every line must equal the `--json` object (`report.to_json_dict`, which `dump()` also uses), so unknown stays `null` and nothing is added or summed. Append only, one compact line per sample, flushed as it is written: Ctrl+C or a kill keeps every finished sample, and an interrupted sample writes nothing. Sample the way the TUI does (budgeted scanning, `LiveCollectors` on Windows so a GPU disable/re-enable is recorded as unavailable with a reason); never add a probe, `scan_budget=None`, or `psutil.open_files()` |
## Verify
@@ -148,6 +150,8 @@ bare-metal Linux with an amdgpu Radeon RX 9070-series card plus a Radeon 610M (D
bare-metal Linux on a laptop with an RTX 4050 Laptop GPU plus an AMD Phoenix iGPU (NVML and DRM side by side).
Intel i915 (an Arc A770 with resizable BAR plus a UHD 730) was validated by a contributor, not repeated by
the maintainer.
-Not yet validated on hardware: systems with two discrete GPUs, multi-GPU on Windows, Intel `xe` and Arc cards
+Not yet validated on hardware: systems with two discrete GPUs, multi-GPU on Windows, NVIDIA TCC-mode GPUs
+(run `gputaskman --list-gpus` and `gputaskman --once --gpu N`, then compare device and per-process VRAM
+with `nvidia-smi`; the code path was exercised against a WDDM GPU only), Intel `xe` and Arc cards
without resizable BAR, and GPU-backed WinML on Copilot+ PCs. Planned work is listed under **Next** in the
README.
diff --git a/README.md b/README.md
index f1eefbd..faeba02 100644
--- a/README.md
+++ b/README.md
@@ -548,7 +548,8 @@ display adapters), or hardware adapters on other platforms, with their vendor an
one of these adapters: NVIDIA adapters are listed first, followed by other vendors, with each
group ordered by dedicated memory. An out-of-range
index is rejected rather than silently selecting another device. Compute-only devices such as an
-NPU are not graphics adapters. AMD and NVIDIA hardware coverage is described below; configurations
+NPU are not graphics adapters and are not listed; an NVIDIA GPU in TCC mode is the exception
+(below). AMD and NVIDIA hardware coverage is described below; configurations
with multiple GPUs and mixed vendors need further hardware validation. `--once` and `--json`
still default to GPU 0; use `--gpu N` to collect another device without changing the snapshot format.
Device telemetry is matched to WDDM adapters by PCI location, not display name or enumeration order.
@@ -556,6 +557,26 @@ If a unique match cannot be established, telemetry is unavailable; buffer logs c
so model-buffer attribution across GPUs is not yet reliable. This conservative matching also applies
to NVIDIA and may suppress telemetry when Windows does not expose a usable PCI address.
+An NVIDIA GPU in **TCC** mode (a datacenter card, or a mining card such as the P102-100) has no
+display driver, so Windows lists no adapter for it and publishes no GPU counters. On Windows,
+gputaskman asks NVML, once when it starts, for TCC devices that DXGI did not list and adds them
+**after** the listed adapters, so no existing GPU number moves. `--list-gpus` marks them
+`TCC compute-only` with their PCI address (including the PCI domain when nonzero), and `--gpu N`
+selects one. Adapter VRAM and each
+process's VRAM come from NVML. NVML documents per-process memory as always unavailable under WDDM
+(Windows manages it, not the NVIDIA driver), so a TCC GPU is where it should be reported; a process
+whose memory the driver does not report is `n/a`, never 0. Engine load, shared memory and commit are
+`n/a`, and no model breakdown is attempted because it needs the shared memory counter too. A TCC GPU
+added or removed while gputaskman runs needs a restart to be noticed. This is covered by mocks, and
+`--list-gpus` reports whether NVML found no TCC GPU or could not complete its probe; raw driver
+exception details are not printed. To validate a real TCC card, run `gputaskman --list-gpus`, then
+`gputaskman --once --gpu N` for the TCC index and compare device and per-process VRAM with
+`nvidia-smi` under the same workload. Record the GPU, driver and workload. The same code path was run
+against a WDDM GPU (RTX 4080 SUPER, NVIDIA 630.20: adapter VRAM matched
+`nvidia-smi` to the MiB with and without a 1 GiB CUDA allocation, and every per-process number stayed
+`n/a`, as NVML documents for WDDM). It is **not validated on TCC hardware**, so per-process VRAM on a
+real TCC card is expected, not confirmed.
+
On Windows, each exact DXGI LUID is also resolved through `DisplayConfigGetDeviceInfo` to its
PnP device interface, including inactive displays, then read through SetupAPI. A `ROOT\DISPLAY`
instance uses its PnP friendly name (device description as fallback) and is labelled `ROOT display
@@ -734,7 +755,7 @@ but a runtime DLL or filename alone does not prove which allocation contains whi
| Question | Evidence | Confidence / limitation |
|---|---|---|
| How full and busy is the card? | WDDM adapter counters and NVML or AMD ADL/SMI | Measured; driver support varies by metric |
-| Which process uses GPU memory? | WDDM process counters; NVML on Linux | Measured accounting, not a resource ownership graph |
+| Which process uses GPU memory? | WDDM process counters; NVML on Linux and for TCC GPUs | Measured accounting, not a resource ownership graph |
| Which WSL process uses GPU memory? | Windows host counters for `vmwp.exe`, matched to Linux processes | Exact VM total; per-process owner inferred (`*`) or guessed (`?`) |
| Which engines are active? | WDDM engine counters | CUDA can appear on the **3D** engine |
| Which runtime is loaded? | Mapped DLL names | Detection, not proof that every library is doing GPU work |
@@ -907,6 +928,7 @@ Identification is designed to stay cheap. Measured on one Windows machine:
| Process list, command line, listening ports | under 1 ms | Once per process / every 5 s |
| Windows adapter discovery (DXGI + exact-LUID PnP identity + PCI location, no telemetry sample) | ~0.86 ms median, 2.60 ms max in 30 warm reads, 26.1 ms first/cold call (Windows 11 build 28000, RTX Spark N1X, driver 32.0.16.2114); same machine without the PnP probe: ~0.36 ms median | Once at startup; TUI rediscovery every 5 s. PnP uses fixed buffers, one interface lookup per adapter and at most two name-property reads, no path/device enumeration or retries. Synchronous OS calls are not a hard latency bound. Other drivers, virtual displays and multi-GPU laptops unmeasured; provider reconstruction has additional driver-dependent cost |
| Windows NVML handle reacquisition (no telemetry sample) | ~8.7 ms median, 9.3 ms max in 30 reads (Windows 11 build 26340, RTX 4080 SUPER, NVIDIA 630.20) | Every 5 s per active collector; retries initialization after NVML session-loss errors. Other drivers unmeasured |
+| Windows TCC discovery (NVML init, device count, one driver-model read per GPU, shutdown) | First call in 15 fresh processes on the same machine, one WDDM GPU: median 37.6 ms, 27.8-43.8 ms. About 15 ms of that is the first `nvmlInit` (it loads `nvml.dll`), which NVML readings pay anyway; the added cost is one extra init-to-shutdown cycle, median 20.7 ms (13.3-30.3 ms). Later calls are cached (about 3 µs). A TCC GPU adds PCI, name and memory reads, which are unmeasured (no TCC hardware here) | Once per process on Windows, including `--list-gpus`; never repeated while running |
| Memory-map scan (DLLs + mapped files) | 1-50 ms per process | New processes, a 64 MiB / 10% memory change, or every 2 min; at most 150 ms per refresh |
| Model-path argument fallback | 0.14 ms median / 0.20 ms max for 256 non-model arguments; 5.51 / 6.58 ms for 16 local GGUF paths; 0.18 / 0.62 ms for 16 missing paths (30 warm reads, Windows 11 build 26340, x64, Python 3.13.17; synthetic files, no GPU workload). First 16-file call: 7.74 ms | Same cached scan cadence as memory maps; at most 256 tokens and 16 candidate paths, no directory walk or full GGUF headers. Counts bound work, not synchronous filesystem latency; other platforms and network filesystems unmeasured |
| GGUF header, model-store manifests | ms, cached | Once per file / every 60 s |
@@ -1073,6 +1095,7 @@ downloads are bundled in this repository.
| `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 |
+| `tcc.py` | NVIDIA TCC-mode GPUs on Windows: finds the ones DXGI does not list, and reads their VRAM and per-process VRAM from NVML |
| `adl.py`, `amdsmi.py` | Optional AMD device readings |
| `procinfo.py` | Runtime, mapped-file, and process discovery |
| `stores.py` | Friendly names from Ollama, LM Studio, and Hugging Face model stores |
@@ -1089,6 +1112,8 @@ downloads are bundled in this repository.
- Model identity for non-GGUF runtimes (ONNX Runtime, PyTorch, TensorRT) beyond installed candidates.
- Explicit provenance and availability for every counter and estimate.
- Reliable multi-GPU matching and per-device model placement.
+- NVIDIA TCC-mode GPUs: validation on TCC hardware, then per-process load and model breakdowns, which
+ the Windows counters would supply for a WDDM GPU.
- Intel `xe` per-process memory and load (`drm-cycles-*`), the Intel GT clock in the device panel, and Intel
validation beyond the Arc A770 / UHD 730 pair.
- macOS: a portable build, Ollama/llama.cpp/MLX validation, and compressed GPU memory (footprint's
diff --git a/src/gputaskman/cli.py b/src/gputaskman/cli.py
index cc98274..2fc8721 100644
--- a/src/gputaskman/cli.py
+++ b/src/gputaskman/cli.py
@@ -108,11 +108,21 @@ def main() -> None:
if args.list_gpus:
from .collector import enumerate_adapters, ordered_adapters
+ from .tcc import TccAdapter, tcc_discovery_status
for i, adapter in enumerate(ordered_adapters(enumerate_adapters())):
- print(f"{i}: {adapter.name} ({adapter.vendor}, LUID 0x{adapter.luid & 0xffffffffffffffff:016x})")
+ if isinstance(adapter, TccAdapter): # its LUID is made up from the PCI identity, so show the address
+ bus, device, function = adapter.pci_address
+ pci = f"{adapter.pci_domain:08x}:" if adapter.pci_domain else ""
+ print(f"{i}: {adapter.name} ({adapter.vendor}, TCC compute-only, "
+ f"PCI {pci}{bus:02x}:{device:02x}.{function:x})")
+ else:
+ print(f"{i}: {adapter.name} ({adapter.vendor}, LUID 0x{adapter.luid & 0xffffffffffffffff:016x})")
if adapter.identity_status:
print(f" {adapter.identity_status}")
+ status = tcc_discovery_status()
+ if status:
+ print(f"TCC discovery: {status}", file=sys.stderr)
return
_check_gpu(ap, args.gpu)
diff --git a/src/gputaskman/collector.py b/src/gputaskman/collector.py
index 422d5ca..3d15262 100644
--- a/src/gputaskman/collector.py
+++ b/src/gputaskman/collector.py
@@ -19,13 +19,19 @@ from . import nvml as nvml_mod
from .nvml import Nvml, NvDevice
from .pdh import ProcGpu
from .procinfo import AI_KINDS, ProcDetail, ProcInspector, classify
+from .tcc import TccAdapter, TccCounters, tcc_adapters
from .telemetry import DeviceTelemetry
if sys.platform == "win32":
- from .dxgi import enumerate_adapters
+ from . import dxgi
from .pdh import GpuCounters
BACKEND = "wddm"
+
+ def enumerate_adapters(*, strict: bool = False) -> list[Adapter]:
+ """DXGI's adapters plus the TCC-mode NVIDIA GPUs it does not list."""
+ listed = dxgi.enumerate_adapters(strict=strict) # a strict DXGI failure raises before NVML is asked
+ return listed + tcc_adapters(listed)
elif sys.platform == "darwin":
from .macos import MacCounters as GpuCounters
from .macos import enumerate_adapters, macos_version
@@ -162,9 +168,10 @@ def select_adapter(adapters: list[Adapter], gpu_index: int) -> Adapter | None:
def ordered_adapters(adapters: list[Adapter]) -> list[Adapter]:
- """List all hardware adapters; retain NVIDIA-first ordering for existing users."""
+ """List all hardware adapters; retain NVIDIA-first ordering for existing users. TCC GPUs come last, so
+ adding one never changes the index of a GPU that Windows lists."""
return sorted((a for a in adapters if not a.software),
- key=lambda a: (a.vendor_id != VENDOR_NVIDIA, -a.dedicated_vram, a.luid))
+ key=lambda a: (isinstance(a, TccAdapter), a.vendor_id != VENDOR_NVIDIA, -a.dedicated_vram, a.luid))
def select_nv_device(adapter: Adapter | None, devices: list[NvDevice], gpu_index: int,
@@ -176,6 +183,9 @@ def select_nv_device(adapter: Adapter | None, devices: list[NvDevice], gpu_index
from .linux import pci_key
matches = [d for d in devices if d.pci_bus and pci_key(d.pci_bus) == adapter.luid]
return matches[0] if len(matches) == 1 else None
+ if isinstance(adapter, TccAdapter):
+ matches = [d for d in devices if adapter.matches_pci(d.pci_bus) and d.driver_model == "TCC"]
+ return matches[0] if len(matches) == 1 else None
if adapter.pci_address is None:
return None
if adapters is not None and sum(a.pci_address == adapter.pci_address for a in adapters) != 1:
@@ -218,10 +228,16 @@ class Collector:
self.adapters = [a for a in (enumerate_adapters() if adapters is None else adapters) if not a.software]
self.adapter = select_adapter(self.adapters, gpu_index)
with ExitStack() as resources:
- self.counters = GpuCounters()
- resources.callback(self.counters.close)
- self.nvml = Nvml()
- resources.callback(self.nvml.close)
+ if isinstance(self.adapter, TccAdapter): # no Windows counters exist for it: NVML is the source
+ self.nvml = Nvml()
+ resources.callback(self.nvml.close)
+ self.counters = TccCounters(self.adapter, self.nvml)
+ resources.callback(self.counters.close)
+ else:
+ self.counters = GpuCounters()
+ resources.callback(self.counters.close)
+ self.nvml = Nvml()
+ resources.callback(self.nvml.close)
self.amdsmi = AmdSmi(self.adapter, self.adapters)
resources.callback(self.amdsmi.close)
self.adl = Adl(self.adapter, self.adapters)
@@ -362,7 +378,13 @@ class Collector:
snap.host_status = self.host_status
if BACKEND == "wddm" and self.adapter:
snap.counter_adapter_matched = luid in per_luid or luid in adapters
- if not snap.counter_adapter_matched:
+ if isinstance(self.adapter, TccAdapter):
+ snap.counter_status = (
+ "TCC compute-only GPU: Windows publishes no GPU counters for it, so VRAM and processes come "
+ "from NVML. Per-process engine load, shared memory and commit are n/a, and per-process VRAM "
+ "is n/a when the driver does not report it." if snap.counter_adapter_matched else
+ "NVML could not read this TCC GPU; VRAM and processes are unavailable.")
+ elif not snap.counter_adapter_matched:
snap.counter_status = ("Windows GPU counters could not be matched to the selected adapter; "
"VRAM and processes are unavailable. The adapter may be temporarily "
"unavailable, or GPU-PV VMs may not expose these counters.")
diff --git a/src/gputaskman/nvml.py b/src/gputaskman/nvml.py
index 65f9738..e488a89 100644
--- a/src/gputaskman/nvml.py
+++ b/src/gputaskman/nvml.py
@@ -31,12 +31,14 @@ _unsafe = False
def mark_unsafe() -> None:
- """An NVIDIA adapter went away: skip nvmlShutdown() from now on and let process exit clean up."""
+ """An NVML call faulted: make no further DLL calls and let process exit clean up."""
global _unsafe
_unsafe = True
def _try(fn, *a, default=None):
+ if _unsafe:
+ return default
try:
return fn(*a)
except Exception:
@@ -55,21 +57,28 @@ class Nvml:
def refresh(self) -> None:
"""Reacquire handles without sampling telemetry or restarting a healthy NVML session."""
- if N is None:
+ if N is None or _unsafe:
return
if self.needs_reset:
self.close()
self.needs_reset = False
if not self.ok:
try:
+ if _unsafe:
+ return
N.nvmlInit()
except Exception:
return
self.ok = True
try:
+ if _unsafe:
+ return
+ count = N.nvmlDeviceGetCount()
handles = []
reset_needed = False
- for i in range(N.nvmlDeviceGetCount()):
+ for i in range(count):
+ if _unsafe:
+ return
try:
handles.append((i, N.nvmlDeviceGetHandleByIndex(i)))
except Exception as error:
@@ -88,6 +97,8 @@ class Nvml:
self.cuda_version = f"{cv // 1000}.{(cv % 1000) // 10}"
def _read(self, fn, *args, default=None):
+ if _unsafe:
+ return default
try:
return fn(*args)
except OSError: # access violation inside nvml.dll, not an NVML error code
@@ -100,7 +111,11 @@ class Nvml:
def sample(self) -> list[NvDevice]:
out = []
+ if _unsafe:
+ return out
for i, h in self.handles:
+ if _unsafe:
+ break
self._faulted = False
d = NvDevice(index=i)
d.name = self._read(N.nvmlDeviceGetName, h, default="?")
diff --git a/src/gputaskman/tcc.py b/src/gputaskman/tcc.py
new file mode 100644
index 0000000..776ebcd
--- /dev/null
+++ b/src/gputaskman/tcc.py
@@ -0,0 +1,205 @@
+"""NVIDIA GPUs in TCC mode: compute-only, so Windows lists no adapter and publishes no GPU counters for them."""
+
+from __future__ import annotations
+
+import re
+import threading
+
+from . import nvml as nvml_mod
+from .dxgi import VENDOR_NVIDIA, Adapter
+from .nvml import Nvml
+from .pdh import AdapterGpu, ProcGpu
+
+NVML_DRIVER_TCC = 1
+
+
+class TccAdapter(Adapter):
+ """A TCC-mode NVIDIA GPU, found through NVML because DXGI does not list it. It adds no fields, so --json
+ looks the same for every adapter. Its luid is made up from the PCI address, so it is the same on every run
+ (`diff` pairs adapters by it)."""
+
+ def __init__(self, luid: int, name: str, vendor_id: int, dedicated_vram: int, shared_system: int, software: bool,
+ pci_address: tuple[int, int, int] | None = None, pci_domain: int = 0) -> None:
+ super().__init__(luid, name, vendor_id, dedicated_vram, shared_system, software, pci_address)
+ self._pci_domain = pci_domain
+
+ @property
+ def pci_domain(self) -> int:
+ return self._pci_domain
+
+ def matches_pci(self, value) -> bool:
+ return _pci_identity(value) == (self.pci_domain, self.pci_address)
+
+
+_lock = threading.Lock()
+_found: list[TccAdapter] | None = None # NVML is asked once per process
+_discovery_status = ""
+
+
+def _text(value) -> str:
+ return value.decode() if isinstance(value, bytes) else str(value)
+
+
+def _value(v) -> int | None:
+ # NVML reports NVML_VALUE_NOT_AVAILABLE (unsigned -1) or None when a process's memory is hidden.
+ if v is None or v >= (1 << 63):
+ return None
+ return int(v)
+
+
+def _pci_identity(value) -> tuple[int, tuple[int, int, int]] | None:
+ text = _text(value)
+ match = re.fullmatch(r"([0-9a-fA-F]+):([0-9a-fA-F]+):([0-9a-fA-F]+)\.([0-9a-fA-F]+)", text)
+ if not match:
+ return None
+ domain, bus, device, function = (int(part, 16) for part in match.groups())
+ if domain > 0xFFFFFFFF or bus > 0xFF or device > 0x1F or function > 7:
+ return None
+ return domain, (bus, device, function)
+
+
+def _nvml_call(N, name: str, *args):
+ if nvml_mod._unsafe:
+ raise RuntimeError("NVML is marked unsafe")
+ return getattr(N, name)(*args)
+
+
+def _read_device(N, index: int) -> TccAdapter | None:
+ handle = _nvml_call(N, "nvmlDeviceGetHandleByIndex", index)
+ if _nvml_call(N, "nvmlDeviceGetDriverModel", handle)[0] != NVML_DRIVER_TCC:
+ return None
+ identity = _pci_identity(_nvml_call(N, "nvmlDeviceGetPciInfo", handle).busId)
+ if identity is None:
+ raise ValueError("NVML returned an invalid PCI address")
+ domain, bdf = identity
+ packed_bdf = bdf[0] << 8 | bdf[1] << 3 | bdf[2]
+ luid = (1 << 62) | domain << 16 | packed_bdf
+ return TccAdapter(luid=luid, name=_text(_nvml_call(N, "nvmlDeviceGetName", handle)),
+ vendor_id=VENDOR_NVIDIA, dedicated_vram=_nvml_call(N, "nvmlDeviceGetMemoryInfo", handle).total,
+ shared_system=0, software=False, pci_address=bdf, pci_domain=domain)
+
+
+def _discover() -> list[TccAdapter]:
+ global _discovery_status
+ N = nvml_mod.N
+ if N is None:
+ _discovery_status = "NVML is unavailable; TCC GPUs could not be checked."
+ return []
+ if nvml_mod._unsafe:
+ _discovery_status = "NVML is marked unsafe; TCC GPUs were not checked."
+ return []
+ try:
+ _nvml_call(N, "nvmlInit")
+ except Exception:
+ _discovery_status = "NVML initialization failed; TCC GPUs could not be checked."
+ return []
+ found, faulted, failed, shutdown_failed = [], False, False, False
+ try:
+ for i in range(_nvml_call(N, "nvmlDeviceGetCount")):
+ if nvml_mod._unsafe:
+ failed = True
+ break
+ try:
+ adapter = _read_device(N, i)
+ except Exception as error: # one unreadable device must not hide a TCC peer
+ failed = True
+ faulted |= isinstance(error, OSError) # an access violation inside nvml.dll
+ continue
+ if adapter is not None:
+ found.append(adapter)
+ except Exception as error:
+ failed = True
+ faulted |= isinstance(error, OSError)
+ if faulted:
+ nvml_mod.mark_unsafe() # nvmlShutdown() can hang after a fault; process exit cleans up
+ if not nvml_mod._unsafe:
+ try:
+ _nvml_call(N, "nvmlShutdown")
+ except Exception:
+ shutdown_failed = True
+ if nvml_mod._unsafe:
+ _discovery_status = "NVML encountered an unsafe driver fault; TCC discovery is incomplete."
+ elif failed:
+ _discovery_status = "NVML TCC discovery was incomplete; one or more devices could not be read."
+ elif found:
+ _discovery_status = f"NVML TCC discovery succeeded; found {len(found)} TCC GPU(s)."
+ else:
+ _discovery_status = "NVML TCC discovery succeeded; no TCC GPUs found."
+ if shutdown_failed:
+ _discovery_status += " NVML shutdown failed."
+ return found
+
+
+def tcc_discovery_status() -> str:
+ """A safe, user-facing summary of the one-time TCC discovery attempt."""
+ return _discovery_status
+
+
+def tcc_adapters(listed: list[Adapter]) -> list[Adapter]:
+ """TCC GPUs that DXGI (`listed`) does not show. NVML is asked once, at the first call: a TCC GPU added or
+ removed while gputaskman runs needs a restart."""
+ global _found
+ with _lock:
+ if _found is None:
+ _found = _discover()
+ found = list(_found)
+ seen = {a.pci_address for a in listed if a.pci_address}
+ return [a for a in found if a.pci_domain != 0 or a.pci_address not in seen]
+
+
+class TccCounters:
+ """pdh.GpuCounters' interface for one TCC GPU. Windows publishes no GPU counters for it, so adapter memory and
+ per-process memory come from NVML. NVML documents per-process memory as never available under WDDM (Windows
+ manages it); under TCC the NVIDIA driver does, so it is expected here, and an entry without it stays unknown.
+ It uses the collector's NVML session and never opens or closes one."""
+
+ def __init__(self, adapter: TccAdapter, nvml: Nvml) -> None:
+ self.adapter = adapter
+ self.nvml = nvml
+ self._handles: list | None = None # the list `_located` was resolved from
+ self._located: tuple[object, str] | None = None # this GPU's (NVML handle, PCI bus ID)
+
+ def close(self) -> None:
+ pass
+
+ def _locate(self) -> tuple[object, str] | None:
+ nvml = self.nvml
+ if self._handles is not nvml.handles: # Nvml.refresh() builds a new list whenever it reacquires handles
+ self._handles, self._located = nvml.handles, None
+ if self._located is None:
+ for _index, handle in self._handles:
+ pci = nvml._read(nvml_mod.N.nvmlDeviceGetPciInfo, handle)
+ bus = _text(pci.busId) if pci is not None else ""
+ if _pci_identity(bus) == (self.adapter.pci_domain, self.adapter.pci_address):
+ self._located = (handle, bus)
+ break
+ return self._located
+
+ def sample(self) -> tuple[dict[int, dict[int, ProcGpu]], dict[int, AdapterGpu]]:
+ nvml = self.nvml
+ located = self._locate() if nvml.ok else None
+ if located is None or any(_pci_identity(bus) == (self.adapter.pci_domain, self.adapter.pci_address)
+ for bus in nvml_mod.LOST):
+ return {}, {}
+ handle, bus = located
+ N = nvml_mod.N
+ nvml._faulted = False # Nvml._read: an OSError is an access violation inside nvml.dll
+ memory = (nvml._read(N.nvmlDeviceGetMemoryInfo, handle, N.nvmlMemory_v2)
+ or nvml._read(N.nvmlDeviceGetMemoryInfo, handle))
+ running = nvml._read(N.nvmlDeviceGetComputeRunningProcesses, handle)
+ if nvml._faulted:
+ nvml_mod.LOST.add(bus)
+ nvml_mod.mark_unsafe()
+ return {}, {}
+ if memory is None or running is None: # unreadable is not empty: the collector says why
+ return {}, {}
+ procs: dict[int, ProcGpu] = {}
+ for p in running:
+ g = procs.setdefault(p.pid, ProcGpu(available={"dedicated"}))
+ used = _value(getattr(p, "usedGpuMemory", None))
+ if used is None:
+ g.attributed, g.available = False, set()
+ else:
+ g.dedicated = max(g.dedicated, float(used))
+ luid = self.adapter.luid
+ return {luid: procs}, {luid: AdapterGpu(dedicated=float(memory.used))}
diff --git a/tests/test_recovery.py b/tests/test_recovery.py
index 4a27ebb..8f08913 100644
--- a/tests/test_recovery.py
+++ b/tests/test_recovery.py
@@ -471,7 +471,7 @@ class NvmlRecoveryTests(TestCase):
self.assertFalse(nv.needs_reset)
nv.close()
- def test_access_violation_stops_reading_that_gpu_and_skips_hanging_shutdown(self):
+ def test_access_violation_stops_all_nvml_reads_and_skips_hanging_shutdown(self):
class Api(SimpleNamespace):
def __getattr__(self, name):
return 0 if name.startswith("NVML_") else lambda *args: None
@@ -490,8 +490,8 @@ class NvmlRecoveryTests(TestCase):
self.assertEqual([(d.pci_bus, d.temp) for d in nv.sample()], [("00000000:01:00.0", 40)])
self.assertEqual(nvml.LOST, {"00000000:05:00.0"})
calls = api.nvmlDeviceGetTemperature.call_count
- self.assertEqual(len(nv.sample()), 1)
- self.assertEqual(api.nvmlDeviceGetTemperature.call_count, calls + 1) # the lost GPU is skipped
+ self.assertEqual(nv.sample(), [])
+ self.assertEqual(api.nvmlDeviceGetTemperature.call_count, calls)
nv.close()
api.nvmlShutdown.assert_not_called()
diff --git a/tests/test_tcc.py b/tests/test_tcc.py
new file mode 100644
index 0000000..280b5fc
--- /dev/null
+++ b/tests/test_tcc.py
@@ -0,0 +1,754 @@
+"""NVIDIA GPUs in TCC mode: found through NVML (DXGI does not list them) and sampled through NVML.
+
+No TCC GPU was available when this was written. FakeNvml replays what NVIDIA documents: a TCC device answers
+nvmlDeviceGetDriverModel with TCC and, unlike a WDDM device, reports each process's memory. The sizes are made up;
+what is tested is discovery, ordering, and the rules that keep an unknown value from becoming a zero.
+"""
+
+import contextlib
+import dataclasses
+import io
+import sys
+import threading
+import time
+import unittest
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+import gputaskman.collector as collector_mod
+from gputaskman import nvml as nvml_mod
+from gputaskman import tcc as tcc_mod
+from gputaskman.cli import main
+from gputaskman.collector import Collector, Snapshot, ordered_adapters, select_adapter
+from gputaskman.dxgi import VENDOR_AMD, VENDOR_NVIDIA, Adapter
+from gputaskman.nvml import Nvml
+from gputaskman.procinfo import ProcDetail
+from gputaskman.recovery import LiveCollectors
+from gputaskman.report import to_dict, to_text
+from gputaskman.tcc import TccAdapter, TccCounters, tcc_adapters
+
+GiB = 1 << 30
+MEMORY_V2 = object() # stands for N.nvmlMemory_v2
+NOT_AVAILABLE = (1 << 64) - 1 # NVML_VALUE_NOT_AVAILABLE, as ctypes reports it
+
+
+def listed_adapter(luid, vendor=VENDOR_NVIDIA, bus=1, total=16 * GiB):
+ return Adapter(luid, f"GPU at {bus}", vendor, total, 0, False, (bus, 0, 0))
+
+
+def tcc_adapter(bus=0x0A, name="Tesla P40", total=24 * GiB, domain=0):
+ packed_bdf = bus << 8
+ luid = (1 << 62) | domain << 16 | packed_bdf
+ return TccAdapter(luid, name, VENDOR_NVIDIA, total, 0, False, (bus, 0, 0), domain)
+
+
+def device(bus, *, model=1, pending=None, name="Tesla P40", total=24 * GiB, used=0, processes=(), bus_id=None):
+ """One NVML device: model 0 is WDDM, 1 is TCC, 2 is MCDM; `processes` are (pid, usedGpuMemory) pairs."""
+ return SimpleNamespace(handle=f"handle-{bus:02x}", model=model, pending=pending, name=name, total=total,
+ used=used, processes=list(processes), bus_id=bus_id or f"00000000:{bus:02X}:00.0")
+
+
+class NvmlError(Exception):
+ def __init__(self, value):
+ super().__init__(value)
+ self.value = value
+
+
+class FakeNvml:
+ """The pynvml calls gputaskman makes, over fixed devices. `log` records every explicit call in order."""
+
+ nvmlMemory_v2 = MEMORY_V2
+
+ def __init__(self):
+ self.devices = []
+ self.log = []
+ self.memory_requests = []
+ self.faults = {} # (function, handle or index) -> the exception that call raises
+ self.init_error = self.count_error = None
+ self.init_delay = 0.0
+ self.v2_rejected = False
+
+ def __getattr__(self, name): # everything gputaskman reads but these tests do not care about
+ if name.startswith("__"):
+ raise AttributeError(name)
+ return 0 if name.startswith("NVML_") else (lambda *args: None)
+
+ def _call(self, function, key=None):
+ self.log.append((function, key))
+ error = self.faults.get((function, key))
+ if error is not None:
+ raise error
+
+ def _device(self, handle):
+ for candidate in self.devices:
+ if candidate.handle == handle:
+ return candidate
+ raise NvmlError(2)
+
+ def rehandle(self, candidate, handle):
+ """NVML hands out a new handle after it reacquires the device; the old one stops working."""
+ candidate.handle = handle
+
+ def nvmlInit(self):
+ self._call("nvmlInit")
+ if self.init_delay:
+ time.sleep(self.init_delay)
+ if self.init_error is not None:
+ raise self.init_error
+
+ def nvmlShutdown(self):
+ self._call("nvmlShutdown")
+
+ def nvmlDeviceGetCount(self):
+ self._call("nvmlDeviceGetCount")
+ if self.count_error is not None:
+ raise self.count_error
+ return len(self.devices)
+
+ def nvmlDeviceGetHandleByIndex(self, index):
+ self._call("nvmlDeviceGetHandleByIndex", index)
+ return self.devices[index].handle
+
+ def nvmlDeviceGetDriverModel(self, handle):
+ self._call("nvmlDeviceGetDriverModel", handle)
+ candidate = self._device(handle)
+ return [candidate.model, candidate.model if candidate.pending is None else candidate.pending]
+
+ def nvmlDeviceGetPciInfo(self, handle):
+ self._call("nvmlDeviceGetPciInfo", handle)
+ return SimpleNamespace(busId=self._device(handle).bus_id)
+
+ def nvmlDeviceGetName(self, handle):
+ self._call("nvmlDeviceGetName", handle)
+ return self._device(handle).name
+
+ def nvmlDeviceGetMemoryInfo(self, handle, version=None):
+ self.memory_requests.append(version)
+ self._call("nvmlDeviceGetMemoryInfo", handle)
+ if version is not None and self.v2_rejected:
+ raise NvmlError(3)
+ candidate = self._device(handle)
+ return SimpleNamespace(total=candidate.total, used=candidate.used, free=candidate.total - candidate.used,
+ reserved=0)
+
+ def nvmlDeviceGetComputeRunningProcesses(self, handle):
+ self._call("nvmlDeviceGetComputeRunningProcesses", handle)
+ return [SimpleNamespace(pid=pid, usedGpuMemory=used) for pid, used in self._device(handle).processes]
+
+ def nvmlSystemGetDriverVersion(self):
+ return "581.15"
+
+ def nvmlSystemGetCudaDriverVersion_v2(self):
+ return 13000
+
+
+class TccTestCase(unittest.TestCase):
+ def setUp(self):
+ self.api = FakeNvml()
+ for target, value in (("gputaskman.nvml.N", self.api), ("gputaskman.nvml._unsafe", False),
+ ("gputaskman.nvml.LOST", set()), ("gputaskman.tcc._found", None),
+ ("gputaskman.tcc._discovery_status", "")):
+ patcher = patch(target, value)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def names(self):
+ return [name for name, _key in self.api.log]
+
+ def counters(self, adapter=None):
+ """A TccCounters over a real Nvml session on the fake, with the setup calls cleared from the log."""
+ nvml = Nvml()
+ self.api.log.clear()
+ self.api.memory_requests.clear()
+ return TccCounters(adapter or tcc_adapter(), nvml), nvml
+
+
+class DiscoveryTests(TccTestCase):
+ def test_finds_a_tcc_gpu_with_every_field(self):
+ self.api.devices = [device(0x0A)]
+ (found,) = tcc_adapters([])
+ self.assertIsInstance(found, TccAdapter)
+ self.assertEqual((found.name, found.vendor_id, found.vendor, found.dedicated_vram, found.shared_system,
+ found.software, found.pci_address),
+ ("Tesla P40", VENDOR_NVIDIA, "NVIDIA", 24 * GiB, 0, False, (0x0A, 0, 0)))
+
+ def test_only_a_gpu_that_is_in_tcc_mode_now_counts(self):
+ # WDDM, MCDM, an unknown model, a WDDM GPU that will switch to TCC at the next reboot, and the reverse.
+ self.api.devices = [device(1, model=0), device(2, model=2), device(3, model=7),
+ device(4, model=0, pending=1), device(5, model=1, pending=0)]
+ self.assertEqual([a.pci_address[0] for a in tcc_adapters([])], [5])
+
+ def test_a_gpu_dxgi_lists_is_never_added_again(self):
+ self.api.devices = [device(0x0A), device(0x0B)]
+ listed = Adapter(7, "Tesla P40", VENDOR_NVIDIA, 24 * GiB, 0, False, (0x0A, 0, 0))
+ self.assertEqual([a.pci_address for a in tcc_adapters([listed])], [(0x0B, 0, 0)])
+
+ def test_listed_adapters_that_cannot_be_paired_hide_nothing(self):
+ self.api.devices = [device(0x0A)]
+ unpaired = Adapter(7, "Tesla P40", VENDOR_NVIDIA, 24 * GiB, 0, False)
+ elsewhere = Adapter(8, "Tesla P40", VENDOR_NVIDIA, 24 * GiB, 0, False, (0x0B, 0, 0))
+ self.assertEqual(len(tcc_adapters([unpaired, elsewhere])), 1)
+
+ def test_a_nonzero_pci_domain_is_preserved_in_tcc_identity(self):
+ self.api.devices = [device(1, bus_id="00010000:01:00.0"), device(2)]
+ found = tcc_adapters([])
+ self.assertEqual([(a.pci_domain, a.pci_address) for a in found], [(0x10000, (1, 0, 0)), (0, (2, 0, 0))])
+ self.assertNotEqual(found[0].luid, found[1].luid)
+
+ def test_identical_bdf_values_in_different_domains_have_distinct_ids(self):
+ self.api.devices = [device(1, bus_id="00000000:01:00.0"), device(2, bus_id="00010000:01:00.0")]
+ found = tcc_adapters([])
+ self.assertEqual([(a.pci_domain, a.pci_address) for a in found],
+ [(0, (1, 0, 0)), (0x10000, (1, 0, 0))])
+ self.assertEqual(len({a.luid for a in found}), 2)
+
+ def test_only_domain_zero_can_be_deduplicated_against_dxgi(self):
+ self.api.devices = [device(1, bus_id="00000000:01:00.0"), device(2, bus_id="00010000:01:00.0")]
+ listed = Adapter(7, "Listed GPU", VENDOR_NVIDIA, 24 * GiB, 0, False, (1, 0, 0))
+ found = tcc_adapters([listed])
+ self.assertEqual([(a.pci_domain, a.pci_address) for a in found], [(0x10000, (1, 0, 0))])
+
+ def test_bytes_and_lowercase_text_from_other_bindings(self):
+ self.api.devices = [device(0x0A, bus_id=b"00000000:0a:00.0", name=b"Tesla P40")]
+ (found,) = tcc_adapters([])
+ self.assertEqual((found.name, found.pci_address), ("Tesla P40", (0x0A, 0, 0)))
+
+ def test_never_raises_without_pynvml(self):
+ with patch("gputaskman.nvml.N", None):
+ self.assertEqual(tcc_adapters([]), [])
+ self.assertEqual(self.api.log, [])
+
+ def test_nvml_that_cannot_start_means_no_tcc_gpus_and_no_shutdown(self):
+ self.api.devices = [device(0x0A)]
+ self.api.init_error = NvmlError(9)
+ self.assertEqual(tcc_adapters([]), [])
+ self.assertEqual(self.api.log, [("nvmlInit", None)])
+
+ def test_a_failing_device_count_is_survivable(self):
+ self.api.devices = [device(0x0A)]
+ for error, unsafe in ((NvmlError(999), False), (OSError("access violation"), True)):
+ with self.subTest(error=type(error).__name__):
+ self.api.log.clear()
+ self.api.count_error = error
+ tcc_mod._found = None
+ nvml_mod._unsafe = False
+ self.assertEqual(tcc_adapters([]), [])
+ self.assertIs(nvml_mod._unsafe, unsafe)
+ self.assertEqual(self.names().count("nvmlShutdown"), 0 if unsafe else 1)
+ self.assertIn("unsafe driver fault" if unsafe else "incomplete", tcc_mod.tcc_discovery_status())
+
+ def test_one_unreadable_device_does_not_hide_a_tcc_peer(self):
+ self.api.devices = [device(1), device(2)]
+ for key, error, unsafe in (
+ (("nvmlDeviceGetHandleByIndex", 0), NvmlError(15), False),
+ (("nvmlDeviceGetDriverModel", "handle-01"), NvmlError(3), False),
+ (("nvmlDeviceGetMemoryInfo", "handle-01"), NvmlError(3), False),
+ (("nvmlDeviceGetPciInfo", "handle-01"), OSError("access violation"), True)):
+ with self.subTest(call=key[0]):
+ self.api.faults = {key: error}
+ self.api.log.clear()
+ tcc_mod._found = None
+ nvml_mod._unsafe = False
+ self.assertEqual([a.pci_address for a in tcc_adapters([])], [(2, 0, 0)])
+ self.assertIs(nvml_mod._unsafe, unsafe) # an access violation inside nvml.dll can hang a shutdown
+ self.assertEqual(self.names().count("nvmlShutdown"), 0 if unsafe else 1)
+ self.assertIn("unsafe driver fault" if unsafe else "incomplete", tcc_mod.tcc_discovery_status())
+
+ def test_nvml_is_asked_once_per_process_even_when_it_found_nothing(self):
+ for devices in ([device(0x0A)], []):
+ with self.subTest(devices=len(devices)):
+ self.api.devices = devices
+ self.api.log.clear()
+ tcc_mod._found = None
+ first = tcc_adapters([])
+ self.assertEqual(tcc_adapters([]), first)
+ self.assertEqual(self.names().count("nvmlInit"), 1)
+
+ def test_init_comes_first_and_exactly_one_shutdown_comes_last(self):
+ self.api.devices = [device(1), device(2, model=0), device(3)]
+ tcc_adapters([])
+ names = self.names()
+ self.assertEqual((names[0], names[-1]), ("nvmlInit", "nvmlShutdown"))
+ self.assertEqual((names.count("nvmlInit"), names.count("nvmlShutdown")), (1, 1))
+
+ def test_no_shutdown_once_nvml_is_marked_unsafe(self):
+ self.api.devices = [device(0x0A)]
+ nvml_mod._unsafe = True
+ self.assertEqual(tcc_adapters([]), [])
+ self.assertEqual(self.api.log, [])
+ self.assertIn("marked unsafe", tcc_mod.tcc_discovery_status())
+
+ def test_nvml_sessions_make_no_dll_calls_after_the_unsafe_flag_is_set(self):
+ nvml_mod._unsafe = True
+ nvml = Nvml()
+ nvml.refresh()
+ self.assertEqual(nvml.sample(), [])
+ nvml.close()
+ self.assertEqual(self.api.log, [])
+
+ def test_discovery_status_distinguishes_no_tcc_devices_from_a_failed_probe(self):
+ self.assertEqual(tcc_adapters([]), [])
+ self.assertIn("succeeded; no TCC GPUs found", tcc_mod.tcc_discovery_status())
+ tcc_mod._found = None
+ self.api.init_error = NvmlError("private driver detail")
+ self.assertEqual(tcc_adapters([]), [])
+ self.assertIn("initialization failed", tcc_mod.tcc_discovery_status())
+ self.assertNotIn("private driver detail", tcc_mod.tcc_discovery_status())
+
+ def test_a_failing_shutdown_is_reported_without_hiding_discovery(self):
+ self.api.devices = [device(0x0A)]
+ self.api.faults = {("nvmlShutdown", None): NvmlError(3)}
+ self.assertEqual(len(tcc_adapters([])), 1)
+ self.assertIn("shutdown failed", tcc_mod.tcc_discovery_status())
+
+ def test_the_listed_adapters_filter_every_call_while_nvml_is_asked_once(self):
+ self.api.devices = [device(0x0A)]
+ listed = Adapter(7, "Tesla P40", VENDOR_NVIDIA, 24 * GiB, 0, False, (0x0A, 0, 0))
+ self.assertEqual(len(tcc_adapters([])), 1)
+ self.assertEqual(tcc_adapters([listed]), [])
+ self.assertEqual(len(tcc_adapters([])), 1)
+ self.assertEqual(self.names().count("nvmlInit"), 1)
+
+ def test_concurrent_first_calls_ask_nvml_once(self):
+ self.api.devices = [device(0x0A)]
+ self.api.init_delay = 0.05
+ barrier, results = threading.Barrier(6), []
+
+ def ask():
+ barrier.wait()
+ results.append(len(tcc_adapters([])))
+
+ threads = [threading.Thread(target=ask, daemon=True) for _ in range(6)]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join(10)
+ self.assertEqual(results, [1] * 6)
+ self.assertEqual(self.names().count("nvmlInit"), 1)
+
+ def test_luids_are_made_from_the_pci_address_and_never_change(self):
+ self.api.devices = [device(0x3B, bus_id="00000000:3B:02.1"), device(0x0A)]
+ first = tcc_adapters([])
+ tcc_mod._found = None
+ again = tcc_adapters([])
+ self.assertEqual([a.luid for a in first], [a.luid for a in again])
+ self.assertEqual([a.luid for a in first], [(1 << 62) | 0x3B << 8 | 2 << 3 | 1,
+ (1 << 62) | 0x0A << 8])
+ self.assertTrue(all(a.luid >= 1 << 62 for a in first)) # far from the small LUIDs DXGI hands out
+
+
+class OrderingTests(unittest.TestCase):
+ def test_tcc_gpus_sort_after_every_listed_adapter_so_indexes_never_shift(self):
+ listed = [listed_adapter(1, 0x8086, 1, 2 * GiB), listed_adapter(2, VENDOR_NVIDIA, 2, 16 * GiB),
+ listed_adapter(3, VENDOR_AMD, 3, 8 * GiB)]
+ tcc = tcc_adapter(total=48 * GiB) # more memory than any of them
+ ordered = ordered_adapters(listed + [tcc])
+ self.assertEqual(ordered[:-1], ordered_adapters(listed))
+ self.assertIs(ordered[-1], tcc)
+
+ def test_two_tcc_gpus_sort_by_memory_then_luid(self):
+ small, big, twin = tcc_adapter(0x0A, total=12 * GiB), tcc_adapter(0x0B, total=24 * GiB), tcc_adapter(0x0C, total=12 * GiB)
+ self.assertEqual(ordered_adapters([small, big]), [big, small])
+ self.assertEqual(ordered_adapters([twin, small]), [small, twin])
+
+ def test_a_machine_with_only_a_tcc_gpu_selects_it(self):
+ tcc = tcc_adapter()
+ self.assertIs(select_adapter([tcc], 0), tcc)
+
+ def test_gpu_index_after_the_listed_adapters_selects_the_tcc_gpu(self):
+ listed, tcc = listed_adapter(1), tcc_adapter()
+ self.assertIs(select_adapter([tcc, listed], 0), listed)
+ self.assertIs(select_adapter([tcc, listed], 1), tcc)
+ with self.assertRaisesRegex(ValueError, "out of range; 2 GPU adapter"):
+ select_adapter([tcc, listed], 2)
+
+ def test_json_describes_a_tcc_adapter_like_any_other(self):
+ self.assertEqual(set(dataclasses.asdict(tcc_adapter())), set(dataclasses.asdict(listed_adapter(1))))
+
+
+class CounterTests(TccTestCase):
+ def test_reports_nvml_memory_for_the_adapter_and_each_process(self):
+ self.api.devices = [device(0x0A, used=9 * GiB, processes=[(100, 6 * GiB), (200, 3 * GiB)])]
+ counters, _ = self.counters()
+ per_luid, adapters = counters.sample()
+ luid = counters.adapter.luid
+ self.assertEqual(list(per_luid), [luid])
+ self.assertEqual({pid: g.dedicated for pid, g in per_luid[luid].items()}, {100: 6 * GiB, 200: 3 * GiB})
+ for g in per_luid[luid].values():
+ self.assertEqual(g.available, {"dedicated"}) # no shared, commit or engine counters exist for TCC
+ self.assertTrue(g.attributed)
+ self.assertEqual((adapters[luid].dedicated, adapters[luid].shared), (9 * GiB, None))
+
+ def test_the_adapter_discovery_returns_is_the_one_the_counters_find(self):
+ self.api.devices = [device(0x3B, bus_id="00000000:3B:02.1", used=GiB, processes=[(5, GiB)])]
+ (found,) = tcc_adapters([])
+ per_luid, adapters = TccCounters(found, Nvml()).sample()
+ self.assertEqual((list(per_luid), list(adapters)), ([found.luid], [found.luid]))
+ self.assertEqual(per_luid[found.luid][5].dedicated, GiB)
+
+ def test_counters_locate_the_gpu_by_domain_when_bdf_values_match(self):
+ self.api.devices = [device(1, bus_id="00000000:01:00.0", used=GiB, processes=[(5, GiB)]),
+ device(2, bus_id="00010000:01:00.0", used=2 * GiB, processes=[(6, GiB)])]
+ counters = TccCounters(tcc_adapter(1, domain=0x10000), Nvml())
+ per_luid, adapters = counters.sample()
+ self.assertEqual(list(per_luid[counters.adapter.luid]), [6])
+ self.assertEqual(adapters[counters.adapter.luid].dedicated, 2 * GiB)
+
+ def test_memory_uses_the_v2_query_and_falls_back_to_the_plain_one(self):
+ self.api.devices = [device(0x0A, used=GiB)]
+ counters, _ = self.counters()
+ counters.sample()
+ self.assertEqual(self.api.memory_requests, [MEMORY_V2])
+ self.api.memory_requests.clear()
+ self.api.v2_rejected = True
+ _, adapters = counters.sample()
+ self.assertEqual(self.api.memory_requests, [MEMORY_V2, None])
+ self.assertEqual(adapters[counters.adapter.luid].dedicated, GiB)
+
+ def test_hidden_process_memory_is_unknown_not_zero(self):
+ for hidden in (None, NOT_AVAILABLE, 1 << 63):
+ with self.subTest(value=hidden):
+ self.api.devices = [device(0x0A, used=GiB, processes=[(100, hidden)])]
+ counters, _ = self.counters()
+ (g,) = counters.sample()[0][counters.adapter.luid].values()
+ self.assertFalse(g.attributed)
+ self.assertEqual(g.available, set())
+ self.assertIsNone(g.shown_vram)
+
+ def test_a_measured_zero_and_the_largest_signed_value_stay_measured(self):
+ self.api.devices = [device(0x0A, processes=[(100, 0), (200, (1 << 63) - 1)])]
+ counters, _ = self.counters()
+ procs = counters.sample()[0][counters.adapter.luid]
+ self.assertEqual([(g.attributed, g.dedicated, g.available) for g in (procs[100], procs[200])],
+ [(True, 0.0, {"dedicated"}), (True, float((1 << 63) - 1), {"dedicated"})])
+
+ def test_a_process_listed_twice_is_counted_once_at_its_larger_size(self):
+ for entries in ([(100, 2 * GiB), (100, 3 * GiB)], [(100, 3 * GiB), (100, 2 * GiB)]):
+ with self.subTest(entries=entries):
+ self.api.devices = [device(0x0A, processes=entries)]
+ counters, _ = self.counters()
+ (g,) = counters.sample()[0][counters.adapter.luid].values()
+ self.assertEqual(g.dedicated, 3 * GiB)
+
+ def test_one_unknown_entry_makes_a_process_unknown_in_either_order(self):
+ for entries in ([(100, 2 * GiB), (100, None)], [(100, None), (100, 2 * GiB)]):
+ with self.subTest(entries=entries):
+ self.api.devices = [device(0x0A, processes=entries)]
+ counters, _ = self.counters()
+ (g,) = counters.sample()[0][counters.adapter.luid].values()
+ self.assertFalse(g.attributed)
+ self.assertIsNone(g.shown_vram)
+
+ def test_a_gpu_with_no_processes_reports_an_empty_set_not_unavailable(self):
+ self.api.devices = [device(0x0A, used=GiB)]
+ counters, _ = self.counters()
+ per_luid, adapters = counters.sample()
+ self.assertEqual(per_luid, {counters.adapter.luid: {}})
+ self.assertEqual(adapters[counters.adapter.luid].dedicated, GiB)
+
+ def test_unreadable_is_reported_as_nothing_never_as_a_partial_guess(self):
+ for case in ("nvml did not start", "gpu is not in the handle list", "process list failed", "memory failed"):
+ with self.subTest(case=case):
+ self.api.devices = [device(0x0B if case == "gpu is not in the handle list" else 0x0A,
+ used=GiB, processes=[(100, GiB)])]
+ self.api.faults = {}
+ self.api.init_error = NvmlError(9) if case == "nvml did not start" else None
+ if case == "process list failed":
+ self.api.faults = {("nvmlDeviceGetComputeRunningProcesses", "handle-0a"): NvmlError(3)}
+ if case == "memory failed": # both the v2 and the plain query fail
+ self.api.faults = {("nvmlDeviceGetMemoryInfo", "handle-0a"): NvmlError(3)}
+ counters, _ = self.counters()
+ self.assertEqual(counters.sample(), ({}, {}))
+ self.assertEqual(nvml_mod.LOST, set()) # an NVML error code is not a fault inside nvml.dll
+ self.assertFalse(nvml_mod._unsafe)
+ if case != "process list failed" and case != "memory failed":
+ self.assertNotIn("nvmlDeviceGetMemoryInfo", self.names())
+ self.assertNotIn("nvmlDeviceGetComputeRunningProcesses", self.names())
+
+ def test_a_fault_inside_nvml_stops_reading_this_gpu_for_good(self):
+ for function in ("nvmlDeviceGetMemoryInfo", "nvmlDeviceGetComputeRunningProcesses"):
+ with self.subTest(function=function):
+ nvml_mod.LOST.clear()
+ nvml_mod._unsafe = False
+ self.api.devices = [device(0x0A, used=GiB, processes=[(100, GiB)])]
+ self.api.faults = {(function, "handle-0a"): OSError("access violation")}
+ counters, _ = self.counters()
+ self.assertEqual(counters.sample(), ({}, {}))
+ self.assertEqual(nvml_mod.LOST, {"00000000:0A:00.0"})
+ self.assertTrue(nvml_mod._unsafe)
+ self.api.log.clear()
+ self.api.faults = {}
+ self.assertEqual(counters.sample(), ({}, {}))
+ self.assertEqual(self.api.log, []) # not one more read of a GPU whose reads faulted
+
+ def test_a_bus_nvml_already_lost_is_matched_by_address_not_by_text(self):
+ nvml_mod.LOST.add("00000000:0a:00.0") # another reader's spelling of the same address
+ self.api.devices = [device(0x0A, used=GiB, processes=[(100, GiB)])]
+ counters, _ = self.counters()
+ self.assertEqual(counters.sample(), ({}, {}))
+ self.assertEqual(self.names(), ["nvmlDeviceGetPciInfo"])
+
+ def test_a_fault_flag_left_by_another_gpu_does_not_mark_this_one_lost(self):
+ self.api.devices = [device(0x0A, used=GiB)]
+ counters, nvml = self.counters()
+ nvml._faulted = True # Nvml.sample() sets it while it reads some other GPU
+ per_luid, _ = counters.sample()
+ self.assertEqual(per_luid, {counters.adapter.luid: {}})
+ self.assertEqual(nvml_mod.LOST, set())
+ self.assertFalse(nvml_mod._unsafe)
+
+ def test_it_finds_its_handle_again_after_nvml_reacquires_handles(self):
+ self.api.devices = [device(0x0A, used=GiB)]
+ counters, nvml = self.counters()
+ self.assertIn(counters.adapter.luid, counters.sample()[1])
+ self.api.rehandle(self.api.devices[0], "handle-new")
+ self.assertEqual(counters.sample(), ({}, {})) # the old handle no longer works
+ nvml.refresh()
+ self.assertIn(counters.adapter.luid, counters.sample()[1])
+
+ def test_a_failed_pci_lookup_is_retried_on_the_next_sample(self):
+ self.api.devices = [device(0x0A, used=GiB)]
+ counters, _ = self.counters()
+ self.api.faults = {("nvmlDeviceGetPciInfo", "handle-0a"): NvmlError(3)}
+ self.assertEqual(counters.sample(), ({}, {}))
+ self.api.faults = {}
+ self.assertIn(counters.adapter.luid, counters.sample()[1])
+
+ def test_the_pci_address_is_read_once(self):
+ self.api.devices = [device(0x0A, used=GiB)]
+ counters, _ = self.counters()
+ counters.sample()
+ counters.sample()
+ self.assertEqual(self.names().count("nvmlDeviceGetPciInfo"), 1)
+
+ def test_close_never_touches_the_collectors_nvml_session(self):
+ self.api.devices = [device(0x0A)]
+ counters, nvml = self.counters()
+ counters.close()
+ counters.close()
+ self.assertTrue(nvml.ok)
+ self.assertEqual(self.api.log, [])
+
+ def test_nothing_is_read_once_the_nvml_session_is_closed(self):
+ self.api.devices = [device(0x0A, used=GiB, processes=[(100, GiB)])]
+ counters, nvml = self.counters()
+ self.assertIn(counters.adapter.luid, counters.sample()[1])
+ nvml.close() # keeps its old handles, which are not valid after nvmlShutdown
+ self.api.log.clear()
+ self.assertEqual(counters.sample(), ({}, {}))
+ self.assertEqual(self.api.log, [])
+
+ def test_each_gpu_sees_only_its_own_processes(self):
+ self.api.devices = [device(1, model=0, processes=[(10, GiB)]),
+ device(0x0A, used=3 * GiB, processes=[(20, 2 * GiB)]),
+ device(0x0B, used=5 * GiB, processes=[(30, 4 * GiB)])]
+ nvml = Nvml()
+ first, second = TccCounters(tcc_adapter(0x0A), nvml), TccCounters(tcc_adapter(0x0B), nvml)
+ for counters, pid, used, memory in ((first, 20, 2 * GiB, 3 * GiB), (second, 30, 4 * GiB, 5 * GiB)):
+ per_luid, adapters = counters.sample()
+ luid = counters.adapter.luid
+ self.assertEqual({p: g.dedicated for p, g in per_luid[luid].items()}, {pid: used})
+ self.assertEqual(adapters[luid].dedicated, memory)
+
+
+class CollectorTests(TccTestCase):
+ def collector(self, adapter=None, *, listed=()):
+ adapter = adapter or tcc_adapter()
+ c = Collector.__new__(Collector)
+ c.adapter = adapter
+ c.adapters = [*listed, adapter]
+ c.gpu_index, c.scan_budget, c.host, c.host_status = len(listed), None, None, ""
+ c.nvml = Nvml()
+ c.counters = TccCounters(adapter, c.nvml)
+ c.adl, c.amdsmi = Mock(), Mock()
+ c.inspector, c.prober = Mock(), Mock()
+ c.inspector.get.side_effect = lambda pid: ProcDetail(pid, f"app{pid}.exe")
+ c.inspector.needs_scan.return_value = False
+ return c
+
+ def sample(self, c):
+ with patch("gputaskman.collector.BACKEND", "wddm"), patch("gputaskman.collector.sys.platform", "win32"):
+ return c.sample()
+
+ def test_a_tcc_gpu_gets_its_memory_and_processes_from_nvml(self):
+ self.api.devices = [device(0x0A, used=9 * GiB, processes=[(200, 2 * GiB), (100, 6 * GiB)])]
+ snap = self.sample(self.collector())
+ self.assertEqual((snap.nv.driver_model, snap.nv.mem_total, snap.vram_total), ("TCC", 24 * GiB, 24 * GiB))
+ self.assertEqual((snap.driver, snap.cuda, snap.backend), ("581.15", "13.0", "wddm"))
+ self.assertEqual((snap.vram_used, snap.shared_used), (9 * GiB, None))
+ self.assertTrue(snap.counter_adapter_matched)
+ self.assertIn("TCC compute-only", snap.counter_status)
+ self.assertEqual([r.pid for r in snap.procs], [100, 200]) # largest first
+ self.assertEqual(snap.attributed, 8 * GiB)
+ data = to_dict(snap)
+ self.assertEqual({p["pid"]: p["vram_bytes"] for p in data["processes"]}, {100: 6 * GiB, 200: 2 * GiB})
+ for process in data["processes"]:
+ for key in ("shared_bytes", "committed_bytes", "paged_out_bytes", "gpu_pct", "engines"):
+ self.assertIsNone(process[key], key) # no such counters exist for a TCC GPU: unknown, not zero
+ self.assertIsNone(data["shared_used"])
+ self.assertIn("TCC compute-only", to_text(snap))
+
+ def test_it_is_told_apart_from_a_wddm_gpu_in_the_same_machine(self):
+ self.api.devices = [device(1, model=0, name="GTX 1080 Ti", total=11 * GiB, used=2 * GiB),
+ device(0x0A, name="P102-100", total=10 * GiB, used=GiB, processes=[(7, GiB)])]
+ snap = self.sample(self.collector(tcc_adapter(0x0A, "P102-100", 10 * GiB), listed=[listed_adapter(1, bus=1)]))
+ self.assertEqual((snap.nv.name, snap.nv.driver_model, snap.vram_used), ("P102-100", "TCC", GiB))
+ self.assertEqual([(r.pid, r.gpu.dedicated) for r in snap.procs], [(7, GiB)])
+
+ def test_device_telemetry_matches_tcc_adapter_by_domain(self):
+ self.api.devices = [device(1, bus_id="00010000:01:00.0", total=24 * GiB, used=GiB)]
+ snap = self.sample(self.collector(tcc_adapter(1, domain=0x10000)))
+ self.assertEqual((snap.nv.driver_model, snap.nv.mem_total, snap.vram_used),
+ ("TCC", 24 * GiB, GiB))
+
+ def test_hidden_process_memory_leaves_the_total_unknown_but_the_adapter_measured(self):
+ self.api.devices = [device(0x0A, used=9 * GiB, processes=[(100, 6 * GiB), (200, None)])]
+ snap = self.sample(self.collector())
+ self.assertIsNone(snap.attributed)
+ self.assertEqual(snap.vram_used, 9 * GiB)
+ data = to_dict(snap)
+ self.assertEqual({p["pid"]: p["vram_bytes"] for p in data["processes"]}, {100: 6 * GiB, 200: None})
+ self.assertIsNone(data["attributed"])
+
+ def test_unreadable_nvml_is_explained_not_guessed(self):
+ self.api.init_error = NvmlError(9)
+ c = self.collector()
+ snap = self.sample(c)
+ self.assertFalse(snap.counter_adapter_matched)
+ self.assertIn("NVML could not read this TCC GPU", snap.counter_status)
+ self.assertEqual(snap.procs, [])
+ self.assertIsNone(snap.vram_used)
+ self.assertIsNone(snap.attributed)
+ self.assertEqual(snap.vram_total, c.adapter.dedicated_vram)
+
+ def test_a_lost_gpu_says_to_restart(self):
+ nvml_mod.LOST.add("00000000:0A:00.0")
+ self.api.devices = [device(0x0A, used=GiB)]
+ snap = self.sample(self.collector())
+ self.assertTrue(snap.nv_lost)
+ self.assertIn("restart gputaskman", snap.counter_status)
+ self.assertIsNone(snap.vram_used)
+
+
+class CollectorSetupTests(TccTestCase):
+ NAMES = ("GpuCounters", "Nvml", "AmdSmi", "Adl", "ProcInspector", "ServerProber")
+
+ def mocks(self, stack):
+ mocks = {name: stack.enter_context(patch(f"gputaskman.collector.{name}")) for name in self.NAMES}
+ stack.enter_context(patch("gputaskman.collector.BACKEND", "wddm"))
+ return mocks
+
+ def test_a_tcc_gpu_never_creates_windows_counters(self):
+ with contextlib.ExitStack() as stack:
+ mocks = self.mocks(stack)
+ c = Collector(0, adapters=[tcc_adapter()], host=False)
+ mocks["GpuCounters"].assert_not_called()
+ mocks["Nvml"].assert_called_once_with() # one NVML session, shared with the counters
+ self.assertIsInstance(c.counters, TccCounters)
+ self.assertIs(c.counters.nvml, mocks["Nvml"].return_value)
+ self.assertIs(c.nvml, mocks["Nvml"].return_value)
+
+ def test_a_listed_nvidia_gpu_still_uses_windows_counters(self):
+ with contextlib.ExitStack() as stack:
+ mocks = self.mocks(stack)
+ c = Collector(0, adapters=[listed_adapter(1)], host=False)
+ mocks["GpuCounters"].assert_called_once_with()
+ self.assertIs(c.counters, mocks["GpuCounters"].return_value)
+
+ def test_a_failure_while_building_closes_the_nvml_session_it_opened(self):
+ with contextlib.ExitStack() as stack:
+ mocks = self.mocks(stack)
+ mocks["Adl"].side_effect = OSError("no ADL")
+ with self.assertRaises(OSError):
+ Collector(0, adapters=[tcc_adapter()], host=False)
+ mocks["Nvml"].return_value.close.assert_called_once()
+ mocks["GpuCounters"].assert_not_called()
+
+
+class CliTests(unittest.TestCase):
+ def test_list_gpus_shows_a_tcc_gpu_by_pci_address_after_the_listed_ones(self):
+ output = io.StringIO()
+ with patch("sys.argv", ["gputaskman", "--list-gpus"]), \
+ patch("gputaskman.collector.enumerate_adapters",
+ return_value=[tcc_adapter(0x0A), listed_adapter(0x1234ABCD)]), \
+ patch("gputaskman.tcc.tcc_discovery_status", return_value=""), \
+ contextlib.redirect_stdout(output):
+ main()
+ self.assertEqual(output.getvalue().splitlines(), [
+ "0: GPU at 1 (NVIDIA, LUID 0x000000001234abcd)",
+ "1: Tesla P40 (NVIDIA, TCC compute-only, PCI 0a:00.0)"])
+
+ def test_list_gpus_reports_nvml_discovery_status_on_stderr(self):
+ output, error = io.StringIO(), io.StringIO()
+ with patch("sys.argv", ["gputaskman", "--list-gpus"]), \
+ patch("gputaskman.collector.enumerate_adapters", return_value=[]), \
+ patch("gputaskman.tcc.tcc_discovery_status",
+ return_value="NVML initialization failed; TCC GPUs could not be checked."), \
+ contextlib.redirect_stdout(output), contextlib.redirect_stderr(error):
+ main()
+ self.assertEqual(output.getvalue(), "")
+ self.assertEqual(error.getvalue().strip(),
+ "TCC discovery: NVML initialization failed; TCC GPUs could not be checked.")
+
+ def test_list_gpus_displays_full_domain_for_tcc_gpu(self):
+ output = io.StringIO()
+ with patch("sys.argv", ["gputaskman", "--list-gpus"]), \
+ patch("gputaskman.collector.enumerate_adapters", return_value=[tcc_adapter(1, domain=0x10000)]), \
+ patch("gputaskman.tcc.tcc_discovery_status", return_value=""), \
+ contextlib.redirect_stdout(output):
+ main()
+ self.assertEqual(output.getvalue().strip(),
+ "0: Tesla P40 (NVIDIA, TCC compute-only, PCI 00010000:01:00.0)")
+
+
[email protected](sys.platform == "win32", "the DXGI wrapper exists only on Windows")
+class WindowsEnumerationTests(unittest.TestCase):
+ def test_tcc_gpus_come_after_the_adapters_dxgi_lists(self):
+ listed, tcc = [listed_adapter(1)], tcc_adapter()
+ with patch("gputaskman.collector.dxgi.enumerate_adapters", return_value=listed) as dxgi, \
+ patch("gputaskman.collector.tcc_adapters", return_value=[tcc]) as found:
+ self.assertEqual(collector_mod.enumerate_adapters(strict=True), [*listed, tcc])
+ dxgi.assert_called_once_with(strict=True)
+ found.assert_called_once_with(listed)
+
+ def test_without_tcc_gpus_the_dxgi_list_is_returned_unchanged(self):
+ listed = [listed_adapter(1)]
+ with patch("gputaskman.collector.dxgi.enumerate_adapters", return_value=listed), \
+ patch("gputaskman.collector.tcc_adapters", return_value=[]):
+ self.assertEqual(collector_mod.enumerate_adapters(), listed)
+
+ def test_a_strict_dxgi_failure_propagates_before_nvml_is_asked(self):
+ with patch("gputaskman.collector.dxgi.enumerate_adapters", side_effect=OSError("DXGI failed")), \
+ patch("gputaskman.collector.tcc_adapters") as found:
+ with self.assertRaises(OSError):
+ collector_mod.enumerate_adapters(strict=True)
+ found.assert_not_called()
+
+
+class RecoveryTests(TccTestCase):
+ def test_a_tcc_slot_keeps_its_collector_while_a_listed_gpu_is_re_enabled(self):
+ wddm, tcc = listed_adapter(1), tcc_adapter()
+ topology, created = [tcc, wddm], []
+
+ def factory(index, *, adapters, scan_budget):
+ adapter = adapters[index]
+ collector = Mock(adapter=adapter, scan_budget=scan_budget)
+ collector.sample.side_effect = lambda: Snapshot(1, adapter, adapters, None, "", "", adapter.dedicated_vram,
+ 0, 0, counter_adapter_matched=True)
+ created.append(collector)
+ return collector
+
+ live = LiveCollectors(None, collector_factory=factory, discover=lambda **_kwargs: list(topology))
+ self.addCleanup(live.close)
+ self.assertEqual([slot.adapter for slot in live.slots], [wddm, tcc]) # TCC last
+ tcc_collector = created[1]
+ topology[:] = [tcc, listed_adapter(11)] # Windows re-enabled the listed GPU under a new LUID
+ snaps = live.sample(now=live.next_discovery)
+ self.assertEqual([s.adapter.luid for s in snaps], [11, tcc.luid])
+ self.assertIs(live.slots[1].collector, tcc_collector)
+ tcc_collector.close.assert_not_called()
+ tcc_collector.nvml.refresh.assert_called_once() # so TccCounters finds its handle again
+
+
+if __name__ == "__main__":
+ unittest.main()