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

Refuse to diff snapshots of different adapters that share a GPU name

Scott Hanselmanb258b49be6dd
diff --git a/AGENTS.md b/AGENTS.md
index 0dc492b..1bec870 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -79,7 +79,7 @@ identify everything immediately; the TUI spreads scans across refreshes.
| Support an app that reads and closes its model | `handy.py` as the template | Read-only settings plus a bounded, mtime-cached log tail; never read transcription content. Generalize into data-driven adapters once a second app needs one |
| Add a GPU vendor or backend | `dxgi.py`, `collector.py`, a new module | Pair devices by LUID or PCI bus ID, never by name or index; load vendor DLLs by absolute system path |
| Add a column or JSON field | `report.py` and `app.py` | Follow the null rules above; update the README tables. If it is a measured byte count, consider adding it to `diff.py` `MEASURED` |
-| 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 |
+| 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 |
| Change WSL matching | `wslhost.py` `ContextTracker` | Keep `tests/test_wslhost.py` replays passing; they are measured sequences |
## Verify
diff --git a/README.md b/README.md
index af8550d..40f853e 100644
--- a/README.md
+++ b/README.md
@@ -556,6 +556,14 @@ model reload often restarts the server under a new PID. A process missing from o
`not listed`, not zero: it was not running or used too little GPU to be listed. Processes that
moved by less than 16 MB are hidden from the text output but included in `--json`.
+Two cards of one model share a name, so `diff` also compares the adapter each snapshot recorded.
+It refuses a pair whose vendor ID, PCI address or (off Windows) adapter key conflicts. A Windows
+adapter key changes at boot and when an adapter is re-enabled, so there it only produces a warning.
+`adapter_check` in `--json` says what was compared: `pci`, `key` or `name-only`. `name-only` means
+the snapshots (older ones, for example) do not both say which adapter they came from, so they were
+matched by GPU name and backend alone, and the text output warns. These identifiers tell GPUs apart
+within one machine; they do not prove two snapshots came from the same computer.
+
Take the "after" snapshot once the model has answered one request: CUDA and Vulkan can allocate
lazily, and allocators keep freed memory cached, so shrinkage may appear late. On an RTX 4080 SUPER
with Docker Model Runner's llama-server (Vulkan) and gemma-3-270m, changing `-c 4096` to `-c 32768`
diff --git a/src/gputaskman/diff.py b/src/gputaskman/diff.py
index aec01d6..479fb05 100644
--- a/src/gputaskman/diff.py
+++ b/src/gputaskman/diff.py
@@ -144,17 +144,67 @@ def _size(p: dict) -> int:
return v["after"] if v["after"] is not None else v["before"] or 0
+def _num(v) -> int | None:
+ return v if isinstance(v, int) and not isinstance(v, bool) else None
+
+
+def _identity(s: dict) -> dict:
+ """What a snapshot says about its adapter that can be compared: vendor, PCI address, adapter key.
+
+ Missing, zero (unknown) and malformed values are left out, so they can never conflict."""
+ a = s.get("adapter")
+ a = a if isinstance(a, dict) else {}
+ out = {name: a[field] for field, name in (("vendor_id", "vendor"), ("luid", "key")) if _num(a.get(field))}
+ pci = a.get("pci_address")
+ if isinstance(pci, (list, tuple)) and len(pci) == 3 and all(_num(x) is not None and x >= 0 for x in pci):
+ out["pci"] = tuple(pci)
+ return out
+
+
+def check_adapter(before: dict, after: dict) -> tuple[str, str | None]:
+ """How firmly two snapshots with the same GPU name are tied to one adapter: ("pci" | "key" | "name-only", note).
+
+ Raises ValueError when both snapshots say which adapter they came from and the answers differ. A matching
+ PCI address wins over the adapter key, which Windows reassigns at boot and when an adapter is re-enabled,
+ so there a differing key is only a warning. Both identifiers are host-local: they tell two GPUs in one
+ machine apart, not two computers.
+ """
+ b, a = _identity(before), _identity(after)
+
+ def different(what: str) -> ValueError:
+ return ValueError(f"snapshots are from different adapters, though both are named {after.get('gpu')!r}: {what}")
+
+ if "vendor" in b and "vendor" in a and b["vendor"] != a["vendor"]:
+ raise different(f"vendor {b['vendor']:#06x} vs {a['vendor']:#06x}")
+ if "pci" in b and "pci" in a:
+ if b["pci"] != a["pci"]:
+ raise different("PCI " + " vs ".join("{:02x}:{:02x}.{}".format(*x) for x in (b["pci"], a["pci"])))
+ return "pci", None
+ if "key" in b and "key" in a:
+ if b["key"] == a["key"]:
+ return "key", None
+ if after.get("backend") != "wddm":
+ raise different(f"adapter key {b['key']:#x} vs {a['key']:#x}")
+ return "name-only", ("Their adapter keys differ and no PCI address is available to settle it. Windows changes "
+ "those keys at boot, so this may be one GPU or two of the same model; they are matched "
+ "by GPU name and backend only.")
+ return "name-only", ("These snapshots do not both say which adapter they came from (an older gputaskman, or no "
+ "adapter details), so they are matched by GPU name and backend only.")
+
+
def diff(before: dict, after: dict) -> dict:
if before.get("gpu") != after.get("gpu") or before.get("backend") != after.get("backend"):
raise ValueError(f"snapshots are from different GPUs or backends: "
f"{before.get('gpu')} ({before.get('backend')}) vs {after.get('gpu')} ({after.get('backend')})")
+ adapter_check, adapter_note = check_adapter(before, after)
device = {k: change(before.get(k), after.get(k)) for k, _ in DEVICE if k != "unattributed"}
device["unattributed"] = change(_unattributed(before), _unattributed(after))
procs = [_proc(b, a, how) for b, a, how in match(before["processes"], after["processes"])]
procs.sort(key=_size, reverse=True)
taken_b, taken_a = before.get("taken"), after.get("taken")
seconds = round(taken_a - taken_b, 1) if isinstance(taken_b, (int, float)) and isinstance(taken_a, (int, float)) else None
- return {"gpu": after.get("gpu"), "backend": after.get("backend"), "seconds": seconds,
+ return {"gpu": after.get("gpu"), "backend": after.get("backend"),
+ "adapter_check": adapter_check, "adapter_note": adapter_note, "seconds": seconds,
"memory_note": after.get("memory_note") or before.get("memory_note"),
"device": device, "processes": procs}
@@ -205,8 +255,10 @@ def to_text(d: dict) -> str:
when = f", {d['seconds']} s apart" if d["seconds"] is not None else ""
out = [f"gputaskman diff: {d['gpu'] or 'unknown GPU'} ({d['backend']}){when}",
"Measured counters are compared directly. Runtime-reported and estimated values are listed",
- "separately and are not added to measured totals.", "",
- f"{'DEVICE (measured)':<26}{'BEFORE':>11}{'AFTER':>11}{'CHANGE':>11}"]
+ "separately and are not added to measured totals."]
+ if d.get("adapter_note"):
+ out.append(f"Warning: {d['adapter_note']}")
+ out += ["", f"{'DEVICE (measured)':<26}{'BEFORE':>11}{'AFTER':>11}{'CHANGE':>11}"]
for key, label in DEVICE:
c = d["device"][key]
out.append(f"{label:<26}{_gb(c['before']):>11}{_gb(c['after']):>11}{_signed(c['delta']):>11}")
diff --git a/tests/test_diff.py b/tests/test_diff.py
index aa0a685..72a2f9a 100644
--- a/tests/test_diff.py
+++ b/tests/test_diff.py
@@ -22,9 +22,15 @@ def proc(pid, name, vram=None, shared=0, host=None, ports=(), llm=None, files=()
**({"llm": llm} if llm else {})}
-def snap(procs, used, attributed, taken=100.0, gpu="RTX", backend="wddm"):
+def snap(procs, used, attributed, taken=100.0, gpu="RTX", backend="wddm", adapter=...):
return {"taken": taken, "gpu": gpu, "backend": backend, "vram_used": used, "shared_used": 0,
- "attributed": attributed, "processes": procs}
+ "attributed": attributed, "processes": procs, **({} if adapter is ... else {"adapter": adapter})}
+
+
+def gpu_adapter(luid=0x4BB7, pci=(1, 0, 0), vendor=0x10DE):
+ """The adapter block of a --json snapshot (a dataclass dump: the PCI address is a list)."""
+ return {"luid": luid, "name": "RTX", "vendor_id": vendor, "dedicated_vram": 16 * GiB, "shared_system": 0,
+ "software": False, "pci_address": list(pci) if pci else None}
def llm(n_ctx, kv, exact=False):
@@ -125,6 +131,58 @@ class DiffTests(unittest.TestCase):
self.assertNotIn("llama (1)", to_text(d))
+class AdapterGuardTests(unittest.TestCase):
+ def pair(self, before, after, backend="wddm"):
+ return diff(snap([], 0, 0, backend=backend, adapter=before), snap([], 0, 0, backend=backend, adapter=after))
+
+ def test_same_name_but_different_pci_addresses_are_not_one_gpu(self):
+ with self.assertRaisesRegex(ValueError, r"different adapters.*'RTX'.*PCI 01:00\.0 vs 02:00\.0"):
+ self.pair(gpu_adapter(pci=(1, 0, 0)), gpu_adapter(pci=(2, 0, 0)))
+
+ def test_a_matching_pci_address_survives_a_changed_luid(self):
+ d = self.pair(gpu_adapter(luid=0x4BB7), gpu_adapter(luid=0x5A01)) # a reboot, or the adapter was re-enabled
+ self.assertEqual((d["adapter_check"], d["adapter_note"]), ("pci", None))
+ self.assertNotIn("Warning", to_text(d))
+
+ def test_conflicting_vendors_are_refused_without_pci_addresses(self):
+ with self.assertRaisesRegex(ValueError, "vendor 0x10de vs 0x1002"):
+ self.pair(gpu_adapter(pci=None, vendor=0x10DE), gpu_adapter(pci=None, vendor=0x1002))
+
+ def test_stable_adapter_keys_separate_identical_gpus_off_windows(self):
+ # Linux and macOS keys derive from the PCI slot, so they hold from one snapshot to the next
+ with self.assertRaisesRegex(ValueError, "adapter key 0x1000 vs 0x2000"):
+ self.pair(gpu_adapter(luid=0x1000, pci=None), gpu_adapter(luid=0x2000, pci=None), backend="nvml")
+ d = self.pair(gpu_adapter(luid=0x1000, pci=None), gpu_adapter(luid=0x1000, pci=None), backend="nvml")
+ self.assertEqual((d["adapter_check"], d["adapter_note"]), ("key", None))
+
+ def test_a_windows_luid_alone_never_refuses_a_diff(self):
+ # Windows reassigns LUIDs at boot: without a PCI address on both sides a changed one proves nothing
+ d = self.pair(gpu_adapter(luid=0x4BB7, pci=None), gpu_adapter(luid=0x5A01, pci=None))
+ self.assertEqual(d["adapter_check"], "name-only")
+ self.assertIn("one GPU or two of the same model", d["adapter_note"])
+ self.assertIn("Warning: Their adapter keys differ", to_text(d))
+ mixed = self.pair(gpu_adapter(pci=(1, 0, 0)), gpu_adapter(pci=None)) # a PCI address on one side only
+ self.assertEqual(mixed["adapter_check"], "key")
+
+ def test_snapshots_with_nothing_to_compare_fall_back_to_name_and_backend_with_a_warning(self):
+ legacy = snap([], 0, 0) # saved by a version that wrote no adapter details
+ for before, after in ((legacy, legacy), (legacy, {**legacy, "adapter": gpu_adapter()}),
+ ({**legacy, "adapter": None}, {**legacy, "adapter": None})):
+ d = diff(before, after)
+ self.assertEqual(d["adapter_check"], "name-only")
+ self.assertIn("matched by GPU name and backend only", d["adapter_note"])
+ self.assertIn("Warning: These snapshots do not both say which adapter", to_text(d))
+
+ def test_zero_and_malformed_details_are_unknown_not_identities(self):
+ unknown = [{"luid": 0, "vendor_id": 0, "pci_address": None}, # zero means unknown, not "adapter 0"
+ {"luid": "4BB7", "vendor_id": True, "pci_address": [1, 0]}, # wrong types, wrong length
+ {"luid": None, "vendor_id": None, "pci_address": [1, 0, -1]}, "RTX", 7, []]
+ for backend in ("wddm", "nvml"): # on nvml a real key mismatch would be refused
+ for bad in unknown:
+ d = self.pair(bad, gpu_adapter(luid=0x4BB7), backend=backend)
+ self.assertEqual(d["adapter_check"], "name-only", (backend, bad))
+
+
class LoadAndCliTests(unittest.TestCase):
def setUp(self):
self.dir = tempfile.TemporaryDirectory()
@@ -160,6 +218,21 @@ class LoadAndCliTests(unittest.TestCase):
main()
self.assertIn("missing.json", err.getvalue())
+ def test_cli_refuses_conflicting_adapters_and_reports_what_was_compared(self):
+ a = self.write("a.json", snap([], 0, 0, adapter=gpu_adapter(pci=(1, 0, 0))), "utf-8")
+ b = self.write("b.json", snap([], 0, 0, adapter=gpu_adapter(pci=(2, 0, 0))), "utf-8")
+ err = io.StringIO()
+ with patch("sys.argv", ["gputaskman", "diff", a, b]), contextlib.redirect_stderr(err), \
+ self.assertRaises(SystemExit) as stop:
+ main()
+ self.assertEqual(stop.exception.code, 2)
+ self.assertIn("different adapters", err.getvalue())
+ c = self.write("c.json", snap([], 0, 0, adapter=gpu_adapter(luid=0x5A01)), "utf-16") # same PCI slot, new boot
+ out = io.StringIO()
+ with patch("sys.argv", ["gputaskman", "diff", a, c, "--json"]), contextlib.redirect_stdout(out):
+ main()
+ self.assertEqual(json.loads(out.getvalue())["adapter_check"], "pci")
+
if __name__ == "__main__":
unittest.main()