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 GPU introspection TUI with documented quick start and screenshots

Scott Hanselmand793e249ad73
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..dfd092a
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,8 @@
+* text=auto
+*.py text eol=lf
+*.md text eol=lf
+*.toml text eol=lf
+*.lock text eol=lf
+*.yml text eol=lf
+*.svg text eol=lf
+*.png binary
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..c7fb119
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,25 @@
+name: Python checks
+
+on:
+ push:
+ pull_request:
+
+permissions:
+ contents: read
+
+jobs:
+ test:
+ runs-on: windows-latest
+ strategy:
+ matrix:
+ python: ["3.11", "3.13"]
+ steps:
+ - uses: actions/checkout@v4
+ - uses: astral-sh/setup-uv@v6
+ with:
+ version: "0.9.26"
+ python-version: ${{ matrix.python }}
+ - run: uv sync --locked
+ - run: uv run --locked python -m unittest discover -s tests -v
+ - run: uv run --locked gputaskman --help
+ - run: uv build
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..ecaad54
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,27 @@
+# Python-generated files
+__pycache__/
+*.py[oc]
+build/
+dist/
+wheels/
+*.egg-info
+
+# Virtual environments
+.venv
+.venv-*
+
+# Local captures, credentials and model downloads
+.env
+.env.*
+*.log
+*.gguf
+*.ggml
+*.safetensors
+*.onnx
+*.pt
+*.pth
+.coverage
+htmlcov/
+.pytest_cache/
+.ruff_cache/
+captures/
diff --git a/.python-version b/.python-version
new file mode 100644
index 0000000..24ee5b1
--- /dev/null
+++ b/.python-version
@@ -0,0 +1 @@
+3.13
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..2d44baa
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Scott Hanselman
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..2e56e16
--- /dev/null
+++ b/README.md
@@ -0,0 +1,269 @@
+# gputaskman
+
+**An `htop` for what's inside your GPU, not just how full it is.**
+
+Windows + NVIDIA. A terminal UI that connects per-process GPU memory and engine activity
+with loaded runtimes, model files, and LLM buffer breakdowns.
+
+Task Manager says "15 GB used." This tries to answer: *by what? Model weights? KV cache?
+Your browser? The desktop compositor? And why is so much GPU memory in system RAM?*
+
+![Live GPU overview with an LLM's weights, KV cache, and compute buffer breakdown](docs/screenshots/overview.png)
+
+> Early, experimental software. Device and process counters are measurements; classifications
+> and GGUF-derived breakdowns are estimates. This does not dump VRAM or enumerate a game's textures.
+
+## Clone and run
+
+Use **64-bit Windows 10/11**, an **NVIDIA GPU with a current WDDM driver**, and a terminal
+(Windows Terminal is recommended). Development and live workload checks used an RTX 4080 SUPER.
+
+Install [Git for Windows](https://git-scm.com/downloads/win) and
+[uv](https://docs.astral.sh/uv/getting-started/installation/) if needed. With WinGet:
+
+```powershell
+winget install --id Git.Git --exact
+winget install --id astral-sh.uv --exact
+```
+
+Open a new PowerShell window so those tools are on `PATH`, then:
+
+```powershell
+git clone https://github.com/shanselman/gputaskman.git
+cd gputaskman
+uv run --locked gputaskman
+```
+
+**That's it.** uv obtains the pinned Python version if needed, creates `.venv`, and installs
+the locked dependencies. The first run needs internet access. There is no CUDA Toolkit,
+Visual Studio, administrator session, API key, or model download required to monitor the GPU.
+NVML ships with the NVIDIA driver.
+
+Already have Python 3.11+ and prefer pip?
+
+```powershell
+git clone https://github.com/shanselman/gputaskman.git
+cd gputaskman
+py -m venv .venv
+.\.venv\Scripts\python.exe -m pip install .
+.\.venv\Scripts\gputaskman.exe
+```
+
+No PowerShell activation script or execution-policy change is needed. The pip route resolves
+compatible dependencies; the uv route uses the checked-in lockfile.
+
+## What you get
+
+- **Device view:** VRAM usage, GPU activity, memory activity, PCIe traffic, temperature, power and clocks.
+- **Process view:** local GPU memory, GPU-accessible system RAM, estimated non-resident commit,
+ engine activity, and detected runtimes such as CUDA, Vulkan, Direct3D, ggml and ONNX Runtime.
+- **LLM inspector:** model name, architecture, quantization, layer count, weights, estimated KV cost,
+ and buffer sizes from compatible load logs.
+- **Live server hints:** context size, busy slots, throughput when available, and friendly Ollama
+ or LM Studio model names.
+- **Scriptable output:** one-shot text and JSON, using the same collector as the TUI.
+
+### Screenshots
+
+These are captures of real local workloads through Textual's screenshot renderer, not mock data.
+Full filesystem paths and command lines were omitted in the capture copy. Measurements vary
+with the workload; the examples are not benchmarks.
+
+**The compositor, without treating all shared surfaces as its private VRAM**
+
+![Compositor selected, showing local memory and the explanation of shared-surface accounting](docs/screenshots/compositor.png)
+
+**GPU-accessible system RAM, sorted by the Spill column**
+
+![Processes sorted by system-memory usage, alongside the selected process's memory explanation](docs/screenshots/system-memory.png)
+
+**An explanation of what is measured, inferred, and unavailable**
+
+![Built-in help explaining GPU counters and the limits of memory introspection](docs/screenshots/help.png)
+
+## Usage
+
+```powershell
+uv run --locked gputaskman # live TUI
+uv run --locked gtm # shorter alias
+uv run --locked gputaskman -i 2 # sample every two seconds
+uv run --locked gputaskman --once # one text snapshot
+uv run --locked gputaskman --json # one JSON snapshot; implies --once
+uv run --locked gputaskman --help
+```
+
+| Key | Action |
+|---|---|
+| Up / Down | Select a process and inspect it |
+| `s` | Cycle sort: VRAM, GPU%, spill, paged, name |
+| `a` | Switch between top and all collected processes |
+| `p` | Pause / resume collection |
+| `?` | Explain the counters and their limits |
+| Escape | Close help |
+| `q` | Quit |
+
+A wide terminal (roughly 140 columns or more) makes the full table easier to read.
+Model/runtime discovery is throttled, so newly loaded models may take about 15 seconds to appear.
+
+`--gpu N` is available, but **single-NVIDIA-GPU systems are the validated configuration**.
+On multi-GPU systems, DXGI and NVML ordering may differ, and buffer logs can span devices;
+cross-device attribution is not yet reliable.
+
+## How can it know what's inside?
+
+It combines evidence rather than reading arbitrary GPU memory. Windows' graphics kernel supplies
+per-process memory and engine counters, while NVML supplies device metrics. Process DLLs suggest
+the runtime, and mapped files or command-line arguments identify candidate models. GGUF metadata
+and tensor offsets let it estimate weights and KV-cache costs; compatible runtime logs and local
+server APIs add allocated buffer sizes and live state. That can explain a llama.cpp process well,
+but a runtime DLL or filename alone does not prove which allocation contains which object.
+
+| Question | Evidence | Confidence / limitation |
+|---|---|---|
+| How full and busy is the card? | WDDM adapter counters and NVML | Measured; driver support varies by metric |
+| Which process uses GPU memory? | WDDM process counters | Measured accounting, not a resource ownership graph |
+| 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 |
+| Which model file is present? | Mapped files, CLI flags, GGUF magic/header | A file mapping does not prove GPU placement |
+| Weights / KV / compute sizes? | Load logs, GGUF math, server state | Log-reported allocations or estimates, not a VRAM scan |
+| Which texture, tensor, or kernel is this? | Not available here | Use PIX, Nsight, or runtime-specific instrumentation |
+
+### Why not just `nvidia-smi`?
+
+On GeForce under **WDDM**, Windows manages GPU memory and NVML may report per-process memory as
+`N/A`. Windows GPU counters can still attribute memory and activity across Direct3D, Vulkan,
+OpenGL, and CUDA. NVML remains useful for device-level readings.
+
+### DWM, Spill, and Paged: read these carefully
+
+**DWM is not everything.** Windows' per-process `Dedicated Usage` includes resources shared
+between processes. The same surface may appear against its application, `csrss.exe`, and
+`dwm.exe`. Adding those rows double-counts memory. This tool prefers `Local Usage` and
+`Non Local Usage`; it falls back to `Dedicated Usage` / `Shared Usage` when the preferred
+counters cannot be added. The adapter total remains the reference. See Microsoft's
+[GPU accounting explanation](https://devblogs.microsoft.com/directx/gpus-in-the-task-manager/).
+
+In one live sample, DWM's older counter read about 15.3 GiB while `Local Usage` was about
+1.4 GiB. The latter reduced the inflated process sum substantially. This is an observed
+improvement, not a guarantee that every driver's process counters add up exactly.
+When the row sum exceeds the adapter total, the category bar is normalized to fit;
+legend values remain raw, and the UI labels the normalization.
+
+**Spill means GPU-accessible system RAM, not proven overflow.** It can include intentionally
+allocated or pinned host buffers. Large usage alongside a nearly full GPU can indicate
+fallback and slower inference, but the counter alone cannot establish why it was allocated.
+
+**Paged is an estimate:** `max(Total Committed - Local Usage - Non Local Usage, 0)`.
+It is not an eviction trace, a pagefile measurement, or proof that Windows just moved
+those bytes out of VRAM. The value is also less reliable when fallback counters are in use.
+
+Memory labels currently use `GB` / `MB` for binary units (GiB / MiB). The top-level `MemBW`
+reading is NVML's memory-activity percentage, **not measured bandwidth in GB/s**.
+
+## LLM support
+
+| Runtime | Current support |
+|---|---|
+| llama.cpp / llama-server | GGUF discovery, CLI settings, buffer logs, local API state; exercised live |
+| Ollama | Bundled llama-server runners, mapped GGUF blobs, parent `/api/ps`, compatible `server.log`; exercised live |
+| LM Studio | Process/file discovery and `/api/v0/models` probing; not yet validated end to end |
+| Other AI runtimes | DLL and candidate model-file detection only; no general tensor inventory |
+
+For log-reported buffer sizes, start your own llama-server with logging enabled:
+
+```powershell
+llama-server.exe -m .\model.gguf -ngl 99 -c 8192 --metrics --log-file server.log -lv 4
+```
+
+Use a real model you already have. This is an example workload, **not a prerequisite for
+running gputaskman**. Verbosity 4 was needed to capture the buffer-size lines in the tested
+llama.cpp build. Prefer an absolute log path if the server and monitor use different
+working directories.
+
+The collector probes existing local listening ports with GET requests to `/props`, `/slots`,
+`/metrics`, `/api/ps`, and `/api/v0/models`. Endpoints may be absent, disabled, or authenticated;
+other evidence is still useful. It does not launch `ollama`, `lms`, or an inference request.
+Throughput may update only after a request completes.
+
+Ollama's local `server.log` is considered when one Ollama runner is detected. Log formats,
+rotation, and stale load blocks can affect attribution, so compare the reported model and
+process when interpreting logs. Log sizes describe allocations at load time, not necessarily
+which pages remain resident now. An inferred remainder is runtime/unknown overhead, not an
+exact measurement of the CUDA context.
+
+Without logs, estimates assume llama.cpp-style placement. Architecture, partial offload,
+KV quantization, sliding-window attention, and multiple models in one process can all change
+the result. Separate runner processes get separate rows; per-model KV accounting within
+one process is not yet supported.
+
+### Spot checks against llama.cpp
+
+The following comparisons used llama.cpp b12061, CUDA 13.4, and an RTX 4080 SUPER.
+They validate these examples, not every model architecture or backend.
+
+| Allocation | GGUF estimate | Runtime log |
+|---|---|---|
+| Qwen3-0.6B Q8_0 GPU weights | 604.15 MiB | 604.15 MiB |
+| Qwen3-0.6B KV, 8,192 context, f16 | 896 MiB | 896 MiB |
+| Gemma-3-270M GPU weights | 271.81 MiB | 271.86 MiB |
+| Gemma-3-270M KV, 4,096 context | 72 MiB upper bound | 49.5 MiB with sliding-window attention |
+
+## Privacy and troubleshooting
+
+The monitor reads local process metadata, compatible model headers, load logs, and local server
+responses. It does not dump model weights or send telemetry. **The normal inspector and JSON
+output can contain paths, command-line flags, model names, and local ports. Review and redact
+captures before posting them publicly.** The screenshot helper omits command lines and full
+file paths, but model and process names still require review.
+
+| Symptom | What to check |
+|---|---|
+| `uv` or `git` is not recognized | Install the prerequisites, then open a new terminal |
+| Windows-only message | Run on native Windows, not Linux, macOS, or WSL |
+| Empty or incomplete GPU readings | Check the NVIDIA driver and WDDM 2.0+ support in `dxdiag`; use a normal local desktop session |
+| Missing DLLs or model details | Protected processes may deny inspection; basic counters can still work without elevation |
+| No exact LLM breakdown | Enable compatible buffer logging, or use the GGUF estimate; API/log access is optional |
+| The screen looks cramped | Widen the terminal or use `--once` / `--json` |
+
+## Development
+
+```powershell
+uv sync --locked
+uv run --locked python -m unittest discover -s tests -v
+uv build
+```
+
+The Windows CI runs hardware-independent checks on Python 3.11 and 3.13. Live GPU behavior
+still needs a real Windows GPU; the CI does not pretend to validate that.
+
+To capture native SVG screenshots of your own running workloads:
+
+```powershell
+uv run --locked python tools\capture_screenshots.py --output .\captures
+```
+
+The checked-in gallery uses PNG renderings of these captures. No models, logs, or executable
+downloads are bundled in this repository.
+
+| Module | Responsibility |
+|---|---|
+| `pdh.py` / `dxgi.py` | Windows counters and adapter enumeration |
+| `nvml.py` | NVIDIA device readings |
+| `procinfo.py` | Runtime, mapped-file, and process discovery |
+| `gguf.py` | Model metadata and size estimates |
+| `llm.py` | Buffer logs, local server probing, and breakdowns |
+| `collector.py` | Shared snapshot collection |
+| `app.py` / `report.py` / `cli.py` | TUI, text/JSON, and command-line entry points |
+
+## Next
+
+- Decision models and non-LLM workloads: identify reliable model metadata and distinguish
+ classification, embedding, speech, and other inference workloads without guessing from a DLL.
+- Explicit provenance and availability for every counter and estimate.
+- Reliable multi-GPU matching and per-device model placement.
+- Live throughput deltas, LM Studio validation, and per-model context accounting.
+- Optional ETW / runtime instrumentation for allocation lifetime and residency detail.
+
+## License
+
+[MIT](LICENSE).
diff --git a/docs/screenshots/compositor.png b/docs/screenshots/compositor.png
new file mode 100644
index 0000000..9fa7cdf
Binary files /dev/null and b/docs/screenshots/compositor.png differ
diff --git a/docs/screenshots/help.png b/docs/screenshots/help.png
new file mode 100644
index 0000000..f765bf3
Binary files /dev/null and b/docs/screenshots/help.png differ
diff --git a/docs/screenshots/overview.png b/docs/screenshots/overview.png
new file mode 100644
index 0000000..d16c1fd
Binary files /dev/null and b/docs/screenshots/overview.png differ
diff --git a/docs/screenshots/system-memory.png b/docs/screenshots/system-memory.png
new file mode 100644
index 0000000..f839996
Binary files /dev/null and b/docs/screenshots/system-memory.png differ
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..aa1e1c4
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,35 @@
+[project]
+name = "gputaskman"
+version = "0.1.0"
+description = "An htop for what's inside your GPU: per-process VRAM, engine load, and LLM weights / KV cache breakdown"
+readme = "README.md"
+license = "MIT"
+license-files = ["LICENSE"]
+authors = [
+ { name = "Scott Hanselman" }
+]
+requires-python = ">=3.11"
+classifiers = [
+ "Development Status :: 3 - Alpha",
+ "Environment :: Console",
+ "Operating System :: Microsoft :: Windows",
+ "Programming Language :: Python :: 3",
+ "Topic :: System :: Monitoring",
+]
+dependencies = [
+ "nvidia-ml-py>=13.615.71",
+ "psutil>=7.2.2",
+ "textual>=8.2.8",
+]
+
+[project.scripts]
+gputaskman = "gputaskman.cli:main"
+gtm = "gputaskman.cli:main"
+
+[project.urls]
+Repository = "https://github.com/shanselman/gputaskman"
+Issues = "https://github.com/shanselman/gputaskman/issues"
+
+[build-system]
+requires = ["uv_build>=0.9.26,<0.10.0"]
+build-backend = "uv_build"
diff --git a/src/gputaskman/__init__.py b/src/gputaskman/__init__.py
new file mode 100644
index 0000000..60b417e
--- /dev/null
+++ b/src/gputaskman/__init__.py
@@ -0,0 +1 @@
+"""gputaskman - an htop for what's *inside* your GPU."""
diff --git a/src/gputaskman/__main__.py b/src/gputaskman/__main__.py
new file mode 100644
index 0000000..4e28416
--- /dev/null
+++ b/src/gputaskman/__main__.py
@@ -0,0 +1,3 @@
+from .cli import main
+
+main()
diff --git a/src/gputaskman/app.py b/src/gputaskman/app.py
new file mode 100644
index 0000000..1cd65e8
--- /dev/null
+++ b/src/gputaskman/app.py
@@ -0,0 +1,387 @@
+"""The htop-style Textual UI."""
+
+from __future__ import annotations
+
+import os
+import time
+from collections import deque
+
+from rich.console import Group
+from rich.table import Table
+from rich.text import Text
+from textual import work
+from textual.app import App, ComposeResult
+from textual.binding import Binding
+from textual.containers import VerticalScroll
+from textual.screen import ModalScreen
+from textual.widgets import DataTable, Footer, Markdown, Static
+from textual.worker import get_current_worker
+
+from .collector import Collector, ProcRow, Snapshot
+from .llm import gb
+
+KIND_STYLE = {
+ "LLM": "bold magenta", "AI": "medium_purple1", "compute": "orange3", "3D/game": "green3",
+ "video": "yellow", "browser": "dodger_blue2", "app": "cyan", "compositor": "grey50",
+ "kernel": "grey50", "system": "grey50",
+}
+SEG_STYLE = {"weights": "magenta", "kv": "dark_orange", "compute": "yellow", "runtime": "grey58", "unknown": "grey42"}
+SPARK = "▁▂▃▄▅▆▇█"
+
+EXPLAIN = {
+ "compositor": "Desktop Window Manager: its own back buffers and the composed image for each monitor. "
+ "Windows' 'Dedicated Usage' counter shows dwm as huge (it counts every app surface it can see); "
+ "this tool prefers Local Usage for attribution. The adapter counter is the total; "
+ "per-process samples can overlap or differ in timing.",
+ "kernel": "Driver/kernel-owned allocations: paging buffers, display scan-out, firmware, scheduler state.",
+ "system": "Session/system process holding display and cursor surfaces.",
+ "browser": "Chromium GPU process: page tiles, images, video frames, canvas, WebGL/WebGPU buffers. "
+ "Deeper: edge://gpu, or DevTools > Performance with the GPU track.",
+ "3D/game": "Textures, meshes, render targets and descriptor heaps. Windows only sees opaque allocations; "
+ "per-resource names need a graphics debugger (PIX on Windows, NVIDIA Nsight Graphics).",
+ "video": "Decoded/encoded video frames and codec surfaces (NVDEC/NVENC).",
+ "compute": "CUDA allocations are opaque to the OS. For more detail trace cudaMalloc with Nsight Systems.",
+ "AI": "ML runtime allocations (tensors, workspaces). PyTorch: torch.cuda.memory_summary(); "
+ "ONNX Runtime/DirectML pools are opaque from outside.",
+ "app": "UI surfaces: swap chains, window back-buffers, cached bitmaps/glyphs.",
+}
+
+HELP_MD = """\
+# What can be known about GPU memory?
+
+| Layer | Source | Works for |
+|---|---|---|
+| **Device** totals, load, bandwidth, PCIe, power | NVML (`nvml.dll`) | NVIDIA |
+| **Per-process** VRAM, spill to RAM, per-engine load | Windows WDDM counters (dxgkrnl) | every API incl. **CUDA** |
+| **Which runtime** (CUDA, Vulkan, D3D12, ggml, ONNX, PyTorch...) | DLLs mapped in the process | everything |
+| **Which model file** | memory-mapped files + command line | llama.cpp, LM Studio, Ollama, llama-cpp-python |
+| **Weights / KV cache / compute** split | GGUF header math, llama.cpp/Ollama logs, local server APIs | GGUF/llama.cpp family |
+| Per-texture / per-buffer names | needs a debugger (PIX, Nsight) attached to the app | games, 3D apps |
+
+**Why does nvidia-smi say N/A?** GeForce cards on Windows run in *WDDM* mode: Windows, not the
+NVIDIA driver, owns video memory, so NVML can't attribute it to processes. The Windows counters can.
+
+**dwm.exe looks huge elsewhere?** Windows' per-process "Dedicated Usage" counts every surface a
+process can *see*, so dwm can show nearly the whole card. VRAM here is what's charged to each
+process ("Local Usage" when available). The adapter counter is the total, not the sum of rows.
+
+**SPILL** = GPU-accessible system RAM. This can include pinned host buffers or intentional
+allocations, not just overflow. Large usage under VRAM pressure can indicate fallback;
+the counter alone does not prove it.
+
+**PAGED** = max(Total Committed - Local Usage - Non Local Usage, 0). This is an estimate of
+non-resident committed memory, not a measured eviction count or proof of pagefile activity.
+
+**Inside** labels are inferred from runtimes and files. Log sizes describe allocated buffers,
+not necessarily current residency. A game's textures cannot be enumerated here.
+
+**GPU%** = busiest engine (like Task Manager). On GeForce/WDDM, CUDA kernels are usually reported
+on the **3D** engine.
+
+Keys: `↑/↓` select · `s` sort · `a` show all · `p` pause · `?` this help · `q` quit
+"""
+
+
+def spark(values, width: int = 30, top: float = 100.0) -> str:
+ vals = list(values)[-width:]
+ return "".join(SPARK[min(int(v / top * (len(SPARK) - 1) + 0.5), len(SPARK) - 1)] if v else " " for v in vals)
+
+
+def stacked_bar(parts: list[tuple[float, str]], total: float, width: int) -> Text:
+ t = Text()
+ used = 0
+ for value, style in parts:
+ n = int(round(value / total * width)) if total else 0
+ n = min(n, width - used)
+ if n > 0:
+ t.append("█" * n, style=style)
+ used += n
+ t.append("░" * (width - used), style="grey27")
+ return t
+
+
+class HelpScreen(ModalScreen):
+ BINDINGS = [Binding("escape,q,question_mark", "app.pop_screen", "Close")]
+ DEFAULT_CSS = """
+ HelpScreen { align: center middle; }
+ HelpScreen > VerticalScroll { width: 140; max-width: 95%; height: 85%; border: thick $accent; background: $surface; padding: 1 2; }
+ """
+
+ def compose(self) -> ComposeResult:
+ with VerticalScroll():
+ yield Markdown(HELP_MD)
+
+
+class GpuTaskManager(App):
+ TITLE = "gputaskman"
+ CSS = """
+ Screen { layout: vertical; }
+ #device { height: auto; border: round $accent; padding: 0 1; }
+ #procs { height: 1fr; min-height: 8; }
+ #inspector { height: auto; max-height: 55%; border: round $secondary; padding: 0 1; }
+ """
+ BINDINGS = [
+ Binding("q", "quit", "Quit"),
+ Binding("s", "cycle_sort", "Sort"),
+ Binding("a", "toggle_all", "All/Top"),
+ Binding("p", "pause", "Pause"),
+ Binding("question_mark", "help", "Explain"),
+ ]
+ SORTS = [("VRAM", lambda r: -r.gpu.dedicated), ("GPU%", lambda r: -r.gpu.gpu_pct),
+ ("spill", lambda r: -r.gpu.shared), ("paged", lambda r: -r.gpu.paged_out),
+ ("name", lambda r: r.name.lower())]
+
+ def __init__(self, gpu_index: int = 0, interval: float = 1.0) -> None:
+ super().__init__()
+ self.gpu_index = gpu_index
+ self.interval = interval
+ self.snap: Snapshot | None = None
+ self.selected_pid: int | None = None
+ self.sort_idx = 0
+ self.show_all = False
+ self.paused = False
+ self.hist_util: deque = deque(maxlen=60)
+ self.hist_bw: deque = deque(maxlen=60)
+ self.hist_vram: deque = deque(maxlen=60)
+ self._auto_selected = False
+
+ def compose(self) -> ComposeResult:
+ yield Static("Sampling GPU counters...", id="device")
+ table = DataTable(id="procs", cursor_type="row", zebra_stripes=True)
+ yield table
+ yield Static("", id="inspector")
+ yield Footer()
+
+ def on_mount(self) -> None:
+ t = self.query_one("#procs", DataTable)
+ for col in ("PID", "Process", "Kind", "Runtime", "VRAM", "Spill", "Paged", "GPU%", "3D", "Copy", "Video", "What's inside"):
+ t.add_column(col, key=col)
+ self.poll()
+
+ @work(thread=True, exclusive=True)
+ def poll(self) -> None:
+ worker = get_current_worker()
+ collector = Collector(self.gpu_index)
+ time.sleep(0.5)
+ try:
+ while not worker.is_cancelled:
+ if not self.paused:
+ snap = collector.sample()
+ self.call_from_thread(self.apply, snap)
+ time.sleep(self.interval)
+ finally:
+ collector.close()
+
+ # ------------------------------------------------------------------ rendering
+
+ def apply(self, snap: Snapshot) -> None:
+ self.snap = snap
+ nv = snap.nv
+ if nv:
+ self.hist_util.append(nv.util_gpu or 0)
+ self.hist_bw.append(nv.util_mem or 0)
+ self.hist_vram.append(100 * snap.vram_used / snap.vram_total if snap.vram_total else 0)
+ if not self._auto_selected:
+ llm = next((r for r in sorted(snap.procs, key=lambda r: -r.gpu.dedicated) if r.llm), None)
+ if llm:
+ self.selected_pid = llm.pid
+ self._auto_selected = True
+ self.query_one("#device", Static).update(self.render_device(snap))
+ self.render_table(snap)
+ self.render_inspector()
+
+ 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 self.paused:
+ head.append(" [PAUSED]", style="bold red")
+
+ # Fit category proportions to the adapter total; row samples need not sum exactly.
+ by_kind: dict[str, float] = {}
+ for r in s.procs:
+ by_kind[r.kind] = by_kind.get(r.kind, 0) + r.gpu.dedicated
+ attributed = sum(by_kind.values())
+ scale = min(1.0, s.vram_used / attributed) if attributed else 1.0
+ order = sorted(by_kind.items(), key=lambda kv: -kv[1])
+ parts = [(v * scale, KIND_STYLE.get(k, "white")) for k, v in order]
+ 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.append_text(stacked_bar(parts, s.vram_total, width))
+ vram.append(f" {gb(s.vram_used)} / {gb(s.vram_total)}", style="bold")
+ legend = Text(" ")
+ for k, v in order[:7]:
+ legend.append("■ ", style=KIND_STYLE.get(k, "white"))
+ legend.append(f"{k} {gb(v)} ")
+ if other > 32 << 20:
+ legend.append("■ ", style="grey35")
+ legend.append(f"unattributed {gb(other)} ")
+ legend.append(f"free {gb(max(s.vram_total - s.vram_used, 0))}", style="grey62")
+ if s.shared_used > 64 << 20:
+ legend.append(f" shared(RAM) {gb(s.shared_used)}", style="yellow")
+ if scale < 1.0:
+ legend.append(" [bar normalized; labels are raw]", style="grey62")
+
+ lines = [head, vram, legend]
+ if nv:
+ m = Text()
+ m.append("GPU ", style="bold")
+ m.append(f"{nv.util_gpu:>3}% ", style="bold green")
+ m.append(spark(self.hist_util, 24), style="green")
+ m.append(" MemBW ", style="bold")
+ m.append(f"{nv.util_mem:>3}% ", style="bold dark_orange")
+ m.append(spark(self.hist_bw, 24), style="dark_orange")
+ m.append(f" PCIe↓{(nv.pcie_rx_kbs or 0) / 1024:>5.0f} ↑{(nv.pcie_tx_kbs or 0) / 1024:>4.0f} MB/s")
+ if nv.enc or nv.dec:
+ m.append(f" enc {nv.enc}% dec {nv.dec}%")
+ lines.append(m)
+ st = Text(f"{nv.temp}°C {nv.power_w or 0:.0f}/{nv.power_limit_w or 0:.0f} W P{nv.pstate} "
+ f"SM {nv.sm_clock}/{nv.sm_clock_max} MHz mem {nv.mem_clock} MHz "
+ f"PCIe gen{nv.pcie_gen} x{nv.pcie_width} CC {nv.compute_cap}", style="grey70")
+ if nv.throttle:
+ st.append(" throttle: " + ",".join(nv.throttle), style="yellow")
+ lines.append(st)
+ return Group(*lines)
+
+ def visible_rows(self, s: Snapshot) -> list[ProcRow]:
+ rows = s.procs
+ if not self.show_all:
+ rows = [r for r in rows if r.gpu.dedicated >= 32 << 20 or r.gpu.gpu_pct >= 1 or r.gpu.shared >= 64 << 20
+ or r.gpu.paged_out >= 128 << 20 or r.llm]
+ return sorted(rows, key=self.SORTS[self.sort_idx][1])
+
+ def render_table(self, s: Snapshot) -> None:
+ t = self.query_one("#procs", DataTable)
+ rows = self.visible_rows(s)
+ keep = self.selected_pid
+ t.clear()
+
+ def pct(v: float) -> Text:
+ return Text(f"{v:.0f}" if v >= 0.5 else "", justify="right", style="bold" if v >= 20 else "")
+
+ for r in rows:
+ e = r.gpu.engines
+ spill = Text(gb(r.gpu.shared) if r.gpu.shared >= 1 << 20 else "", justify="right",
+ style="bold red" if r.gpu.shared >= 256 << 20 and r.kind in ("LLM", "AI") else "yellow")
+ paged = Text(gb(r.gpu.paged_out) if r.gpu.paged_out >= 1 << 20 else "", justify="right", style="grey62")
+ t.add_row(
+ Text(str(r.pid), justify="right"),
+ Text(r.name),
+ Text(r.kind, style=KIND_STYLE.get(r.kind, "")),
+ Text(" ".join(r.detail.runtimes[:3]), style="grey70"),
+ Text(gb(r.gpu.dedicated), justify="right", style="bold"), spill, paged, pct(r.gpu.gpu_pct),
+ pct(e.get("3d", 0) + e.get("compute", 0)), pct(e.get("copy", 0)),
+ pct(e.get("decode", 0) + e.get("encode", 0)),
+ Text(r.inside, style="magenta" if r.llm else "grey62", overflow="ellipsis", no_wrap=True),
+ key=str(r.pid),
+ )
+ if keep is not None:
+ try:
+ t.move_cursor(row=t.get_row_index(str(keep)), animate=False, scroll=False)
+ except Exception:
+ pass
+ t.border_subtitle = f"sort: {self.SORTS[self.sort_idx][0]} · {'all' if self.show_all else 'top'} processes"
+
+ def render_inspector(self) -> None:
+ panel = self.query_one("#inspector", Static)
+ s = self.snap
+ r = next((x for x in s.procs if x.pid == self.selected_pid), None) if s else None
+ if r is None:
+ panel.update(Text("Select a process (↑/↓) to see what's inside its GPU memory. Press ? to learn what's knowable.", style="grey62"))
+ return
+ panel.border_title = f"{r.name} ({r.pid}) - {r.kind}"
+ out: list = []
+ e = r.gpu.engines
+ hdr = Text.assemble(("VRAM ", "bold"), (gb(r.gpu.dedicated), "bold"), " spill(RAM) ",
+ (gb(r.gpu.shared), "bold red" if r.gpu.shared > 256 << 20 else ""),
+ " paged(est) ", gb(r.gpu.paged_out),
+ " engines ", " ".join(f"{k} {v:.0f}%" for k, v in e.items() if v >= 0.5) or "idle")
+ if r.detail.runtimes:
+ hdr.append(" runtime ", style="grey62")
+ hdr.append(" ".join(r.detail.runtimes), style="cyan")
+ out.append(hdr)
+ if 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.",
+ style="yellow"))
+
+ v = r.llm
+ if v:
+ width = max(min(self.size.width - 8, 100), 20)
+ total = max(r.gpu.dedicated, sum(x.bytes for x in v.segments), 1)
+ out.append(stacked_bar([(x.bytes, SEG_STYLE[x.kind]) for x in v.segments], total, width))
+ legend = Text()
+ for x in v.segments:
+ legend.append("■ ", style=SEG_STYLE[x.kind])
+ legend.append(f"{x.label} {gb(x.bytes)}", style="bold" if x.exact else "")
+ legend.append(" ")
+ if v.log_source:
+ legend.append(f"(allocated sizes from {os.path.basename(v.log_source)})", style="green")
+ out.append(legend)
+ if v.models:
+ mt = Table(box=None, padding=(0, 1), show_edge=False, header_style="bold grey70")
+ for col in ("", "model", "arch", "params", "quant", "layers", "train ctx", "on GPU (est)", "file"):
+ mt.add_column(col)
+ for g in v.models:
+ mt.add_row(Text(g.kind, style="magenta"), g.name, g.arch, g.params_label, g.quant,
+ str(g.n_layers or ""), f"{g.ctx_train:,}" if g.ctx_train else "",
+ gb(g.gpu_weight_bytes()), Text(os.path.basename(g.path), style="grey50", overflow="ellipsis"))
+ out.append(mt)
+ for f in v.other_files:
+ out.append(Text(f"file: {f.path} ({gb(f.size)})", style="grey62"))
+ if v.server:
+ sv = v.server
+ st = Text.assemble(("server ", "bold"), (f"{sv.kind} {sv.url}", "cyan"))
+ if sv.n_ctx:
+ st.append(f" ctx {sv.n_ctx:,}")
+ if sv.slots_total is not None:
+ st.append(f" slots busy {sv.slots_busy}/{sv.slots_total}")
+ if sv.gen_tok_s:
+ st.append(f" gen {sv.gen_tok_s:.1f} tok/s", style="bold green")
+ if sv.prompt_tok_s:
+ st.append(f" prompt {sv.prompt_tok_s:.0f} tok/s")
+ for m in sv.models[:4]:
+ if sv.kind == "lmstudio":
+ st.append(f"\n loaded: {m.get('id')} {m.get('quantization', '')} ctx {m.get('loaded_context_length') or m.get('max_context_length', '?')}")
+ out.append(st)
+ for n in v.notes:
+ out.append(Text("• " + n, style="bold red" if n.startswith("!") else "grey70"))
+ else:
+ out.append(Text(EXPLAIN.get(r.kind, ""), style="grey70"))
+ for m in r.detail.models:
+ out.append(Text(f"file: {m.path} ({gb(m.size)}, {m.source})", style="magenta"))
+ if r.detail.ports:
+ out.append(Text("listening: " + ", ".join(map(str, r.detail.ports[:8])), style="grey50"))
+ if r.detail.cmdline:
+ out.append(Text(" ".join(r.detail.cmdline)[:400], style="grey42", overflow="ellipsis"))
+ elif r.detail.access_denied:
+ out.append(Text("(protected process - run elevated for runtime/file details)", style="grey42"))
+ panel.update(Group(*out))
+
+ # ------------------------------------------------------------------ events/actions
+
+ def on_data_table_row_highlighted(self, event: DataTable.RowHighlighted) -> None:
+ if event.row_key is not None and event.row_key.value is not None:
+ self.selected_pid = int(event.row_key.value)
+ self.render_inspector()
+
+ def action_cycle_sort(self) -> None:
+ self.sort_idx = (self.sort_idx + 1) % len(self.SORTS)
+ if self.snap:
+ self.render_table(self.snap)
+
+ def action_toggle_all(self) -> None:
+ self.show_all = not self.show_all
+ if self.snap:
+ self.render_table(self.snap)
+
+ def action_pause(self) -> None:
+ self.paused = not self.paused
+ if self.snap:
+ self.query_one("#device", Static).update(self.render_device(self.snap))
+
+ def action_help(self) -> None:
+ self.push_screen(HelpScreen())
diff --git a/src/gputaskman/cli.py b/src/gputaskman/cli.py
new file mode 100644
index 0000000..220de9c
--- /dev/null
+++ b/src/gputaskman/cli.py
@@ -0,0 +1,40 @@
+"""gputaskman - an htop for what's *inside* your GPU."""
+
+from __future__ import annotations
+
+import argparse
+import math
+import sys
+import time
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(prog="gputaskman", description="What's inside your GPU: per-process VRAM, engines, and LLM weights/KV-cache breakdown.")
+ ap.add_argument("--once", action="store_true", help="print one snapshot and exit (no TUI)")
+ ap.add_argument("--json", action="store_true", help="print one JSON snapshot and exit (implies --once)")
+ ap.add_argument("--gpu", type=int, default=0, help="GPU index (default 0)")
+ ap.add_argument("-i", "--interval", type=float, default=1.0, help="refresh seconds (default 1)")
+ args = ap.parse_args()
+ if args.gpu < 0:
+ ap.error("--gpu must be a non-negative index")
+ 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":
+ sys.exit("gputaskman currently supports Windows (WDDM) only.")
+
+ if args.once or args.json:
+ from .collector import Collector
+ from .report import dump
+
+ c = Collector(args.gpu)
+ try:
+ time.sleep(1.0) # engine utilization is a rate; needs two samples
+ print(dump(c.sample(), args.json))
+ finally:
+ c.close()
+ return
+
+ from .app import GpuTaskManager
+
+ GpuTaskManager(gpu_index=args.gpu, interval=args.interval).run()
diff --git a/src/gputaskman/collector.py b/src/gputaskman/collector.py
new file mode 100644
index 0000000..53d9e0c
--- /dev/null
+++ b/src/gputaskman/collector.py
@@ -0,0 +1,145 @@
+"""Assembles one Snapshot from Windows counters, NVML, process inspection and LLM introspection."""
+
+from __future__ import annotations
+
+import time
+from dataclasses import dataclass, field
+
+import psutil
+
+from .dxgi import VENDOR_NVIDIA, Adapter, enumerate_adapters
+from .llm import LlmView, ServerProber, build_view, ollama_log_path
+from .nvml import Nvml, NvDevice
+from .pdh import GpuCounters, ProcGpu
+from .procinfo import ProcDetail, ProcInspector, classify
+
+MiB = 1 << 20
+
+
+@dataclass
+class ProcRow:
+ pid: int
+ name: str
+ kind: str
+ gpu: ProcGpu
+ detail: ProcDetail
+ llm: LlmView | None = None
+
+ @property
+ def runtime(self) -> str:
+ return "+".join(self.detail.runtimes[:3])
+
+ @property
+ def inside(self) -> str:
+ """One-line 'what's in there' summary for the process table."""
+ if self.llm and self.llm.models:
+ parts = []
+ for g in self.llm.models:
+ label = g.metadata.get("general.basename") or g.name
+ if g.kind == "model":
+ parts.append(f"{label} {g.params_label} {g.quant}")
+ else:
+ parts.append(f"+{g.kind}")
+ return ", ".join(parts)
+ if self.detail.models:
+ import os
+ return ", ".join(os.path.basename(m.path) for m in self.detail.models[:2])
+ return {
+ "compositor": "desktop back buffers + composed frames",
+ "kernel": "driver/kernel allocations",
+ "browser": "page textures, video, canvas/WebGL",
+ "video": "video frames (decode/encode)",
+ "3D/game": "textures, meshes, render targets",
+ }.get(self.kind, "")
+
+
+@dataclass
+class Snapshot:
+ taken: float
+ adapter: Adapter | None
+ adapters: list[Adapter]
+ nv: NvDevice | None
+ driver: str
+ cuda: str
+ vram_total: int
+ vram_used: int # WDDM adapter-wide dedicated usage (ground truth)
+ shared_used: int
+ procs: list[ProcRow] = field(default_factory=list)
+
+ @property
+ def attributed(self) -> int:
+ return int(sum(p.gpu.dedicated for p in self.procs))
+
+
+class Collector:
+ DEEP_TOP_N = 25 # deep-scan (memory maps) the top N VRAM users each cycle (throttled per process)
+
+ def __init__(self, gpu_index: int = 0) -> None:
+ self.counters = GpuCounters()
+ self.nvml = Nvml()
+ self.inspector = ProcInspector()
+ self.prober = ServerProber()
+ self.adapters = [a for a in enumerate_adapters() if not a.software]
+ nv = [a for a in self.adapters if a.vendor_id == VENDOR_NVIDIA] or self.adapters
+ nv.sort(key=lambda a: -a.dedicated_vram)
+ self.adapter = nv[min(gpu_index, len(nv) - 1)] if nv else None
+ self.gpu_index = gpu_index
+
+ def _parent_ports(self, pid: int, depth: int = 2) -> list[int]:
+ ports: list[int] = []
+ try:
+ p = psutil.Process(pid)
+ for _ in range(depth):
+ p = p.parent()
+ if p is None:
+ break
+ ports += self.inspector.get(p.pid, deep=False).ports
+ except (psutil.Error, OSError):
+ pass
+ return ports
+
+ def sample(self) -> Snapshot:
+ per_luid, adapters = self.counters.sample()
+ luid = self.adapter.luid if self.adapter else (next(iter(per_luid), 0))
+ procs = per_luid.get(luid, {})
+ a = adapters.get(luid)
+ nvs = self.nvml.sample() if self.nvml.ok else []
+ nv = nvs[self.gpu_index] if self.gpu_index < len(nvs) else None
+ 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,
+ vram_used=int(a.dedicated) if a else (nv.mem_used if nv else 0),
+ shared_used=int(a.shared) if a else 0,
+ )
+
+ live = [(pid, g) for pid, g in procs.items()
+ if g.dedicated >= MiB or g.gpu_pct >= 0.5 or g.shared >= 16 * MiB or g.paged_out >= 16 * MiB]
+ live.sort(key=lambda x: -x[1].dedicated)
+ deep_pids = {pid for pid, _ in live[: self.DEEP_TOP_N]} | {pid for pid, g in live if g.gpu_pct >= 2}
+ ollama_runners = []
+ for pid, g in live:
+ d = self.inspector.get(pid, deep=pid in deep_pids)
+ row = ProcRow(pid=pid, name=d.name, kind=classify(d, g.engines), gpu=g, detail=d)
+ snap.procs.append(row)
+ # Old Ollama: "ollama.exe runner ..."; newer Ollama: its own lib\ollama\llama-server.exe
+ if row.kind == "LLM" and ("\\ollama\\" in d.exe.lower() or
+ (d.name.lower().startswith("ollama") and "runner" in d.cmdline)):
+ ollama_runners.append(row)
+
+ for row in snap.procs:
+ if row.kind not in ("LLM", "AI") or not (row.detail.models or row.kind == "LLM"):
+ continue
+ own = self.prober.get(row.detail.ports)
+ host = self.prober.get(self._parent_ports(row.pid)) # Ollama / LM Studio front-end process
+ log = ollama_log_path() if row in ollama_runners and len(ollama_runners) == 1 else None
+ row.llm = build_view(row.detail, row.gpu.dedicated, row.gpu.shared, own or host, log,
+ host=host if own else None)
+
+ self.inspector.prune(set(procs))
+ return snap
+
+ def close(self) -> None:
+ self.counters.close()
+ self.nvml.close()
diff --git a/src/gputaskman/dxgi.py b/src/gputaskman/dxgi.py
new file mode 100644
index 0000000..9af8d2b
--- /dev/null
+++ b/src/gputaskman/dxgi.py
@@ -0,0 +1,90 @@
+"""Enumerate GPU adapters via DXGI so performance-counter LUIDs map to real GPU names."""
+
+from __future__ import annotations
+
+import ctypes
+from ctypes import wintypes
+from dataclasses import dataclass
+
+
+class _LUID(ctypes.Structure):
+ _fields_ = [("LowPart", wintypes.DWORD), ("HighPart", wintypes.LONG)]
+
+
+class _DESC1(ctypes.Structure):
+ _fields_ = [
+ ("Description", ctypes.c_wchar * 128),
+ ("VendorId", wintypes.UINT),
+ ("DeviceId", wintypes.UINT),
+ ("SubSysId", wintypes.UINT),
+ ("Revision", wintypes.UINT),
+ ("DedicatedVideoMemory", ctypes.c_size_t),
+ ("DedicatedSystemMemory", ctypes.c_size_t),
+ ("SharedSystemMemory", ctypes.c_size_t),
+ ("AdapterLuid", _LUID),
+ ("Flags", wintypes.UINT),
+ ]
+
+
+class _GUID(ctypes.Structure):
+ _fields_ = [("d1", wintypes.DWORD), ("d2", wintypes.WORD), ("d3", wintypes.WORD), ("d4", ctypes.c_ubyte * 8)]
+
+
+_IID_IDXGIFactory1 = _GUID(0x770AAE78, 0xF26F, 0x4DBA, (ctypes.c_ubyte * 8)(0xA8, 0x29, 0x25, 0x3C, 0x83, 0xD1, 0xB3, 0x87))
+VENDOR_NVIDIA = 0x10DE
+VENDORS = {0x10DE: "NVIDIA", 0x1002: "AMD", 0x8086: "Intel", 0x1414: "Microsoft", 0x5143: "Qualcomm"}
+
+
+@dataclass
+class Adapter:
+ luid: int
+ name: str
+ vendor_id: int
+ dedicated_vram: int
+ shared_system: int
+ software: bool
+
+ @property
+ def vendor(self) -> str:
+ return VENDORS.get(self.vendor_id, hex(self.vendor_id))
+
+
+def _vcall(obj: ctypes.c_void_p, index: int, restype, *argtypes):
+ vtbl = ctypes.cast(obj, ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p)))[0]
+ return ctypes.WINFUNCTYPE(restype, ctypes.c_void_p, *argtypes)(vtbl[index])
+
+
+def enumerate_adapters() -> list[Adapter]:
+ try:
+ dxgi = ctypes.WinDLL("dxgi")
+ except OSError:
+ return []
+ factory = ctypes.c_void_p()
+ if dxgi.CreateDXGIFactory1(ctypes.byref(_IID_IDXGIFactory1), ctypes.byref(factory)) != 0:
+ return []
+ out: list[Adapter] = []
+ try:
+ enum_adapters1 = _vcall(factory, 12, ctypes.c_long, wintypes.UINT, ctypes.POINTER(ctypes.c_void_p))
+ i = 0
+ while True:
+ adapter = ctypes.c_void_p()
+ if enum_adapters1(factory, i, ctypes.byref(adapter)) != 0:
+ break # DXGI_ERROR_NOT_FOUND
+ try:
+ desc = _DESC1()
+ if _vcall(adapter, 10, ctypes.c_long, ctypes.POINTER(_DESC1))(adapter, ctypes.byref(desc)) == 0:
+ luid = (desc.AdapterLuid.HighPart << 32) | desc.AdapterLuid.LowPart
+ out.append(Adapter(
+ luid=luid,
+ name=desc.Description,
+ vendor_id=desc.VendorId,
+ dedicated_vram=desc.DedicatedVideoMemory,
+ shared_system=desc.SharedSystemMemory,
+ software=bool(desc.Flags & 2),
+ ))
+ finally:
+ _vcall(adapter, 2, wintypes.ULONG)(adapter) # Release
+ i += 1
+ finally:
+ _vcall(factory, 2, wintypes.ULONG)(factory)
+ return out
diff --git a/src/gputaskman/gguf.py b/src/gputaskman/gguf.py
new file mode 100644
index 0000000..6917385
--- /dev/null
+++ b/src/gputaskman/gguf.py
@@ -0,0 +1,238 @@
+"""GGUF header reader: what model is this file, and what will it cost in VRAM?
+
+Only the header and tensor table are read (a few MB at most), never the weights.
+Tensor byte sizes come from the tensor offset table, so new quant types don't need a lookup table.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import struct
+from dataclasses import dataclass, field
+from functools import lru_cache
+
+_SCALARS = {0: "<B", 1: "<b", 2: "<H", 3: "<h", 4: "<I", 5: "<i", 6: "<f", 7: "<?", 10: "<Q", 11: "<q", 12: "<d"}
+_STRING, _ARRAY = 8, 9
+
+FILE_TYPES = {
+ 0: "F32", 1: "F16", 2: "Q4_0", 3: "Q4_1", 7: "Q8_0", 8: "Q5_0", 9: "Q5_1", 10: "Q2_K", 11: "Q3_K_S",
+ 12: "Q3_K_M", 13: "Q3_K_L", 14: "Q4_K_S", 15: "Q4_K_M", 16: "Q5_K_S", 17: "Q5_K_M", 18: "Q6_K",
+ 19: "IQ2_XXS", 20: "IQ2_XS", 21: "Q2_K_S", 22: "IQ3_XS", 23: "IQ3_XXS", 24: "IQ1_S", 25: "IQ4_NL",
+ 26: "IQ3_S", 27: "IQ3_M", 28: "IQ2_S", 29: "IQ2_M", 30: "IQ4_XS", 31: "IQ1_M", 32: "BF16",
+ 36: "TQ1_0", 37: "TQ2_0", 38: "MXFP4_MOE",
+}
+
+_BLK_RE = re.compile(r"^blk\.(\d+)\.")
+
+
+@dataclass
+class GgufInfo:
+ path: str
+ file_size: int
+ version: int
+ metadata: dict = field(default_factory=dict)
+ n_params: int = 0
+ tensor_bytes: int = 0
+ layer_bytes: dict[int, int] = field(default_factory=dict) # blk index -> bytes
+ token_embd_bytes: int = 0
+ output_bytes: int = 0 # output.weight (or tied token_embd copy) + output_norm
+ other_bytes: int = 0
+ error: str | None = None
+
+ def meta(self, key: str, default=None):
+ arch = self.metadata.get("general.architecture", "")
+ return self.metadata.get(f"{arch}.{key}", default)
+
+ @property
+ def arch(self) -> str:
+ return self.metadata.get("general.architecture", "?")
+
+ @property
+ def kind(self) -> str:
+ t = self.metadata.get("general.type", "model")
+ if self.arch == "clip" or t == "mmproj":
+ return "vision projector"
+ if t == "adapter":
+ return "LoRA adapter"
+ if self.metadata.get("bert.pooling_type") is not None or self.meta("pooling_type") is not None:
+ return "embedding model"
+ return "model"
+
+ @property
+ def name(self) -> str:
+ return self.metadata.get("general.name") or os.path.basename(self.path)
+
+ @property
+ def quant(self) -> str:
+ ft = self.metadata.get("general.file_type")
+ return FILE_TYPES.get(ft, f"type{ft}") if ft is not None else "?"
+
+ @property
+ def n_layers(self) -> int:
+ return int(self.meta("block_count", 0) or 0)
+
+ @property
+ def ctx_train(self) -> int | None:
+ return self.meta("context_length")
+
+ @property
+ def sliding_window(self) -> int | None:
+ return self.meta("attention.sliding_window")
+
+ @property
+ def params_label(self) -> str:
+ n = self.n_params
+ if n >= 1e9:
+ return f"{n / 1e9:.1f}B"
+ if n >= 1e6:
+ return f"{n / 1e6:.0f}M"
+ return str(n)
+
+ def gpu_weight_bytes(self, n_gpu_layers: int | None = None) -> int:
+ """Bytes llama.cpp would place on the GPU. Input embeddings always stay on the CPU."""
+ L = self.n_layers or len(self.layer_bytes)
+ ngl = L + 1 if n_gpu_layers is None or n_gpu_layers < 0 else n_gpu_layers
+ first_gpu = max(L - ngl, 0)
+ total = sum(b for i, b in self.layer_bytes.items() if i >= first_gpu)
+ if ngl > L:
+ total += self.output_bytes
+ if not self.layer_bytes: # non-transformer (e.g. CLIP/whisper): assume everything goes up
+ total = self.tensor_bytes
+ return total
+
+ def kv_bytes_per_token(self, type_bytes: float = 2.0) -> int | None:
+ """Per-token KV cache cost (K+V, all layers) at the given element size (f16 = 2)."""
+ L = self.n_layers
+ n_head = self.meta("attention.head_count")
+ n_kv = self.meta("attention.head_count_kv", n_head)
+ n_embd = self.meta("embedding_length")
+ if not L or n_kv is None:
+ return None
+ if isinstance(n_head, list):
+ n_head = max(n_head) if n_head else None
+ head_dim = (n_embd // n_head) if (n_embd and n_head) else None
+ k_len = self.meta("attention.key_length", head_dim)
+ v_len = self.meta("attention.value_length", head_dim)
+ if not k_len or not v_len:
+ return None
+ per_layer = n_kv if isinstance(n_kv, list) else [n_kv] * L
+ elems = sum(int(h) * (k_len + v_len) for h in per_layer[:L])
+ return int(elems * type_bytes)
+
+
+class _Reader:
+ def __init__(self, f, version: int):
+ self.f = f
+ self.v = version
+
+ def unpack(self, fmt: str):
+ size = struct.calcsize(fmt)
+ data = self.f.read(size)
+ if len(data) != size:
+ raise EOFError("truncated GGUF header")
+ return struct.unpack(fmt, data)[0]
+
+ def length(self) -> int:
+ return self.unpack("<Q" if self.v >= 2 else "<I")
+
+ def string(self) -> str:
+ return self.f.read(self.length()).decode("utf-8", "replace")
+
+ def skip_string(self) -> None:
+ self.f.seek(self.length(), 1)
+
+ def value(self, vtype: int):
+ if vtype in _SCALARS:
+ return self.unpack(_SCALARS[vtype])
+ if vtype == _STRING:
+ return self.string()
+ if vtype == _ARRAY:
+ etype = self.unpack("<I")
+ n = self.length()
+ if etype in _SCALARS:
+ size = struct.calcsize(_SCALARS[etype])
+ if n <= 4096:
+ raw = self.f.read(size * n)
+ return list(struct.unpack("<" + _SCALARS[etype][1] * n, raw))
+ self.f.seek(size * n, 1)
+ return f"<array[{n}]>"
+ if etype == _STRING:
+ for _ in range(n):
+ self.skip_string()
+ return f"<string[{n}]>"
+ for _ in range(n):
+ self.value(etype)
+ return f"<array[{n}]>"
+ raise ValueError(f"unknown GGUF value type {vtype}")
+
+
+def is_gguf(path: str) -> bool:
+ try:
+ with open(path, "rb") as f:
+ return f.read(4) == b"GGUF"
+ except OSError:
+ return False
+
+
+@lru_cache(maxsize=64)
+def _read_cached(path: str, size: int, mtime: float) -> GgufInfo:
+ info = GgufInfo(path=path, file_size=size, version=0)
+ try:
+ with open(path, "rb", buffering=1 << 20) as f:
+ if f.read(4) != b"GGUF":
+ info.error = "not a GGUF file"
+ return info
+ info.version = struct.unpack("<I", f.read(4))[0]
+ r = _Reader(f, info.version)
+ n_tensors = r.length()
+ n_kv = r.length()
+ for _ in range(n_kv):
+ key = r.string()
+ info.metadata[key] = r.value(r.unpack("<I"))
+ tensors = []
+ for _ in range(n_tensors):
+ name = r.string()
+ n_dims = r.unpack("<I")
+ dims = [r.length() for _ in range(n_dims)]
+ r.unpack("<I") # ggml type
+ offset = r.unpack("<Q")
+ n = 1
+ for d in dims:
+ n *= d
+ tensors.append((offset, name, n))
+ align = int(info.metadata.get("general.alignment", 32))
+ data_start = (f.tell() + align - 1) // align * align
+ except Exception as e: # noqa: BLE001 - show the problem in the UI rather than crash
+ info.error = f"{type(e).__name__}: {e}"
+ return info
+
+ tensors.sort()
+ names = set()
+ for i, (offset, name, n) in enumerate(tensors):
+ end = tensors[i + 1][0] if i + 1 < len(tensors) else size - data_start
+ nbytes = max(end - offset, 0)
+ info.n_params += n
+ info.tensor_bytes += nbytes
+ names.add(name)
+ m = _BLK_RE.match(name)
+ if m:
+ idx = int(m[1])
+ info.layer_bytes[idx] = info.layer_bytes.get(idx, 0) + nbytes
+ elif name.startswith("token_embd."):
+ info.token_embd_bytes += nbytes
+ elif name.startswith("output"):
+ info.output_bytes += nbytes
+ else:
+ info.other_bytes += nbytes
+ if "output.weight" not in names and info.layer_bytes:
+ info.output_bytes += info.token_embd_bytes # tied embeddings: llama.cpp puts a copy on the GPU
+ return info
+
+
+def read_gguf(path: str) -> GgufInfo | None:
+ try:
+ st = os.stat(path)
+ except OSError:
+ return None
+ return _read_cached(path, st.st_size, st.st_mtime)
diff --git a/src/gputaskman/llm.py b/src/gputaskman/llm.py
new file mode 100644
index 0000000..af1db16
--- /dev/null
+++ b/src/gputaskman/llm.py
@@ -0,0 +1,319 @@
+"""What's inside an LLM process's VRAM: weights vs KV cache vs compute/runtime.
+
+Evidence, best first:
+ 1. llama.cpp / Ollama load logs -> exact per-device buffer sizes
+ 2. Local server endpoints -> llama-server /props,/slots,/metrics; Ollama /api/ps; LM Studio /api/v0/models
+ 3. GGUF header + command line -> estimates (weights per layer, KV bytes per token x context)
+The process's real VRAM total always comes from Windows, so the remainder is never invented.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import time
+import urllib.request
+from dataclasses import dataclass, field
+
+from .gguf import GgufInfo, read_gguf
+from .procinfo import MappedModel, ProcDetail
+
+MiB = 1 << 20
+KV_TYPE_BYTES = {"f32": 4, "f16": 2, "bf16": 2, "q8_0": 34 / 32, "q4_0": 18 / 32, "q4_1": 20 / 32,
+ "q5_0": 22 / 32, "q5_1": 24 / 32, "iq4_nl": 18 / 32}
+
+_FLAGS = {
+ "-c": "ctx", "--ctx-size": "ctx", "-ngl": "ngl", "--n-gpu-layers": "ngl", "--gpu-layers": "ngl",
+ "-np": "parallel", "--parallel": "parallel", "-ctk": "ctk", "--cache-type-k": "ctk",
+ "-ctv": "ctv", "--cache-type-v": "ctv", "--port": "port", "--log-file": "log_file",
+}
+_BOOL_FLAGS = {"--no-mmap": "no_mmap"}
+
+
+def parse_flags(cmd: list[str]) -> dict:
+ out: dict = {}
+ for i, arg in enumerate(cmd):
+ key, val = arg, None
+ if arg.startswith("--") and "=" in arg:
+ key, val = arg.split("=", 1)
+ if key in _BOOL_FLAGS:
+ out[_BOOL_FLAGS[key]] = True
+ elif key in _FLAGS:
+ if val is None and i + 1 < len(cmd):
+ val = cmd[i + 1]
+ if val is not None:
+ name = _FLAGS[key]
+ if name in ("ctx", "ngl", "parallel", "port"):
+ try:
+ out[name] = int(val)
+ except ValueError:
+ if name == "ngl" and val in ("all", "auto"):
+ out[name] = -1
+ else:
+ out[name] = val
+ return out
+
+
+# ---------------------------------------------------------------- logs (exact numbers)
+
+_LLAMA_BUF = re.compile(r"(\S+)\s+(model|KV|compute|output|RS)\s+buffer size\s*=\s*([\d.]+)\s*MiB")
+_OLLAMA_BUF = re.compile(r'msg="(model weights|kv cache|compute graph)"\s+device=(\S+)\s+size="([\d.]+)\s*(GiB|MiB|KiB|B)"')
+_UNIT = {"GiB": 1 << 30, "MiB": 1 << 20, "KiB": 1 << 10, "B": 1}
+_KIND = {"model": "weights", "model weights": "weights", "KV": "kv", "kv cache": "kv", "RS": "kv",
+ "compute": "compute", "compute graph": "compute", "output": "compute"}
+
+
+def is_gpu_device(dev: str) -> bool:
+ d = dev.upper()
+ return not (d.startswith("CPU") or "HOST" in d or d.startswith("MMAP"))
+
+
+def parse_load_log(path: str, not_before: float = 0.0) -> dict[str, dict[str, int]] | None:
+ """Most recent model-load block in a llama.cpp/Ollama log -> {device: {kind: bytes}}."""
+ try:
+ if os.path.getmtime(path) < not_before:
+ return None
+ with open(path, "rb") as f:
+ f.seek(0, 2)
+ f.seek(max(f.tell() - (512 << 10), 0))
+ lines = f.read().decode("utf-8", "replace").splitlines()
+ except OSError:
+ return None
+ start = None
+ for i in range(len(lines) - 1, -1, -1): # last load starts at its first weights line
+ if "model buffer size" in lines[i] or 'msg="model weights"' in lines[i]:
+ start = i
+ while start > 0 and ("model buffer size" in lines[start - 1] or 'msg="model weights"' in lines[start - 1]):
+ start -= 1
+ break
+ if start is None:
+ return None
+ out: dict[str, dict[str, int]] = {}
+ for line in lines[start:]:
+ m = _LLAMA_BUF.search(line)
+ if m:
+ dev, kind, n = m[1].rstrip(":"), _KIND[m[2]], int(float(m[3]) * MiB)
+ else:
+ m = _OLLAMA_BUF.search(line)
+ if not m:
+ continue
+ dev, kind, n = m[2], _KIND[m[1]], int(float(m[3]) * _UNIT[m[4]])
+ out.setdefault(dev, {}).setdefault(kind, 0)
+ out[dev][kind] += n
+ return out or None
+
+
+def ollama_log_path() -> str:
+ return os.path.join(os.environ.get("LOCALAPPDATA", ""), "Ollama", "server.log")
+
+
+# ---------------------------------------------------------------- local servers
+
+_opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
+
+
+def _get(url: str, timeout: float = 0.5):
+ try:
+ with _opener.open(urllib.request.Request(url, headers={"Accept": "application/json"}), timeout=timeout) as r:
+ if r.status != 200:
+ return None
+ body = r.read(4 << 20)
+ except Exception:
+ return None
+ try:
+ return json.loads(body)
+ except ValueError:
+ return body.decode("utf-8", "replace")
+
+
+@dataclass
+class ServerInfo:
+ kind: str # llama-server | ollama | lmstudio
+ url: str
+ n_ctx: int | None = None
+ slots_total: int | None = None
+ slots_busy: int | None = None
+ gen_tok_s: float | None = None
+ prompt_tok_s: float | None = None
+ models: list[dict] = field(default_factory=list) # ollama / lmstudio loaded models
+
+
+def _metric(text: str, name: str) -> float | None:
+ m = re.search(rf"^llamacpp:{name}\s+([\d.eE+-]+)", text, re.M)
+ return float(m[1]) if m else None
+
+
+def probe_server(port: int) -> ServerInfo | None:
+ base = f"http://127.0.0.1:{port}"
+ props = _get(base + "/props")
+ if isinstance(props, dict) and ("default_generation_settings" in props or "model_path" in props):
+ s = ServerInfo("llama-server", base)
+ dgs = props.get("default_generation_settings") or {}
+ s.n_ctx = dgs.get("n_ctx") or props.get("n_ctx")
+ s.slots_total = props.get("total_slots")
+ slots = _get(base + "/slots")
+ if isinstance(slots, list):
+ s.slots_total = len(slots)
+ s.slots_busy = sum(1 for x in slots if x.get("is_processing"))
+ metrics = _get(base + "/metrics")
+ if isinstance(metrics, str):
+ s.gen_tok_s = _metric(metrics, "predicted_tokens_seconds")
+ s.prompt_tok_s = _metric(metrics, "prompt_tokens_seconds")
+ return s
+ ps = _get(base + "/api/ps")
+ if isinstance(ps, dict) and isinstance(ps.get("models"), list):
+ return ServerInfo("ollama", base, models=ps["models"])
+ lms = _get(base + "/api/v0/models")
+ if isinstance(lms, dict) and isinstance(lms.get("data"), list):
+ loaded = [m for m in lms["data"] if m.get("state") == "loaded"]
+ return ServerInfo("lmstudio", base, models=loaded)
+ return None
+
+
+class ServerProber:
+ """Throttled, cached probes. Only localhost, only read-only GET endpoints."""
+
+ TTL_HIT, TTL_MISS = 3.0, 30.0
+
+ def __init__(self) -> None:
+ self._cache: dict[int, tuple[float, ServerInfo | None]] = {}
+
+ def get(self, ports: list[int]) -> ServerInfo | None:
+ now = time.time()
+ for port in ports:
+ hit = self._cache.get(port)
+ if hit and now - hit[0] < (self.TTL_HIT if hit[1] else self.TTL_MISS):
+ info = hit[1]
+ else:
+ info = probe_server(port)
+ self._cache[port] = (now, info)
+ if info:
+ return info
+ return None
+
+
+# ---------------------------------------------------------------- the breakdown
+
+
+@dataclass
+class Segment:
+ label: str
+ bytes: int
+ kind: str # weights | kv | compute | runtime | unknown
+ exact: bool = False
+
+
+@dataclass
+class LlmView:
+ models: list[GgufInfo] = field(default_factory=list)
+ other_files: list[MappedModel] = field(default_factory=list)
+ flags: dict = field(default_factory=dict)
+ server: ServerInfo | None = None
+ host: ServerInfo | None = None # managing front-end (Ollama / LM Studio) when the runner has its own server
+ log_source: str | None = None
+ log: dict | None = None
+ segments: list[Segment] = field(default_factory=list)
+ notes: list[str] = field(default_factory=list)
+ kv_per_token: int | None = None
+ kv_type: str = "f16"
+ n_ctx: int | None = None
+
+
+def gb(n: float) -> str:
+ if abs(n) >= 1 << 30:
+ return f"{n / (1 << 30):.2f} GB"
+ return f"{n / MiB:.0f} MB"
+
+
+def build_view(d: ProcDetail, vram: float, shared: float, server: ServerInfo | None,
+ log_path: str | None = None, host: ServerInfo | None = None) -> LlmView:
+ v = LlmView(flags=parse_flags(d.cmdline), server=server, host=host)
+ for m in d.models:
+ g = read_gguf(m.path) if m.gguf else None
+ if g is not None and not g.error:
+ v.models.append(g)
+ else:
+ v.other_files.append(m)
+
+ log_path = log_path or v.flags.get("log_file")
+ if log_path:
+ v.log = parse_load_log(log_path, not_before=d.create_time - 5)
+ v.log_source = log_path if v.log else None
+
+ main = next((g for g in v.models if g.kind == "model" and g.n_layers), None)
+ ctk = str(v.flags.get("ctk", "f16")).lower()
+ ctv = str(v.flags.get("ctv", "f16")).lower()
+ v.kv_type = ctk if ctk == ctv else f"K {ctk}/V {ctv}"
+ if main:
+ elems = main.kv_bytes_per_token(1.0) # K+V elements per token (K and V are usually equal width)
+ if elems:
+ v.kv_per_token = int(elems * (KV_TYPE_BYTES.get(ctk, 2) + KV_TYPE_BYTES.get(ctv, 2)) / 2)
+ v.n_ctx = v.flags.get("ctx") or (server.n_ctx if server and server.kind == "llama-server" else None)
+ if server and server.kind == "ollama" and main:
+ for om in server.models:
+ if om.get("context_length"):
+ v.n_ctx = v.n_ctx or om["context_length"]
+
+ total = int(vram)
+ if v.log:
+ gpu = {dev: kinds for dev, kinds in v.log.items() if is_gpu_device(dev)}
+ acc = 0
+ for kind, label in (("weights", "weights"), ("kv", "KV cache"), ("compute", "compute buffers")):
+ n = sum(k.get(kind, 0) for k in gpu.values())
+ if n:
+ devs = ",".join(sorted(dev for dev, k in gpu.items() if k.get(kind)))
+ v.segments.append(Segment(f"{label} ({devs})", n, kind, exact=True))
+ acc += n
+ cpu_w = sum(k.get("weights", 0) for dev, k in v.log.items() if not is_gpu_device(dev))
+ if cpu_w and main and cpu_w > main.token_embd_bytes * 1.5:
+ v.notes.append(f"{gb(cpu_w)} of weights are on the CPU side (partial offload or CPU-mapped).")
+ if total > acc:
+ v.segments.append(Segment("CUDA context, cuBLAS & other", total - acc, "runtime"))
+ else:
+ ngl = v.flags.get("ngl") if len(v.models) == 1 else None
+ weights = sum(g.gpu_weight_bytes(ngl) for g in v.models if g.kind != "LoRA adapter")
+ weights += sum(g.tensor_bytes for g in v.models if g.kind == "LoRA adapter")
+ if weights > total * 1.03 and total > 0:
+ v.notes.append(f"Weights need ~{gb(weights)} but the process holds {gb(total)} of VRAM: "
+ "partial offload, paging, or placement on another GPU may explain the gap.")
+ weights = total
+ if weights:
+ label = "weights" if len(v.models) == 1 else f"weights ({len(v.models)} files)"
+ v.segments.append(Segment(label, weights, "weights"))
+ rest = total - weights
+ kv = v.kv_per_token * v.n_ctx if (v.kv_per_token and v.n_ctx) else 0
+ if kv and kv <= rest:
+ swa = main.sliding_window if main else None
+ v.segments.append(Segment(f"KV cache ({v.n_ctx:,} ctx, {v.kv_type}) est.{' max' if swa else ''}", kv, "kv"))
+ if swa:
+ v.notes.append(f"Sliding-window attention ({swa} tokens): most layers keep a short KV window, "
+ "so the real KV cache is smaller than this estimate.")
+ rest -= kv
+ if rest > 0:
+ v.segments.append(Segment("compute buffers + CUDA context", rest, "runtime"))
+ elif rest > 0:
+ v.segments.append(Segment("KV cache + compute + CUDA context", rest, "unknown"))
+
+ if not v.models and not v.log and total > 0:
+ v.notes.append("No GGUF mapped. Model may be loaded with --no-mmap or via another format.")
+ if main and v.kv_per_token:
+ v.notes.append(f"KV cost {v.kv_per_token / 1024:.0f} KB/token ({v.kv_type}): "
+ f"4k ctx = {gb(v.kv_per_token * 4096)}, 32k ctx = {gb(v.kv_per_token * 32768)}.")
+ if shared > 256 * MiB:
+ v.notes.append(f"! {gb(shared)} is in SHARED GPU memory (system RAM over PCIe). "
+ "May include pinned host buffers; under VRAM pressure, fallback can slow inference.")
+ if total < 64 * MiB and v.models:
+ v.notes.append("Model is mapped but almost nothing is in VRAM: CPU inference, or another GPU.")
+ for front in (s for s in (server, host) if s and s.kind == "ollama"):
+ for om in front.models:
+ size, vram_m = om.get("size", 0), om.get("size_vram", 0)
+ if size:
+ pct = 100 * vram_m / size
+ v.notes.append(f"Ollama: {om.get('name')} {gb(size)} total, {pct:.0f}% on GPU, "
+ f"ctx {om.get('context_length', '?')}.")
+ if host and host.kind == "lmstudio":
+ for m in host.models[:4]:
+ v.notes.append(f"LM Studio: {m.get('id')} {m.get('quantization', '')} "
+ f"ctx {m.get('loaded_context_length') or m.get('max_context_length', '?')}.")
+ return v
diff --git a/src/gputaskman/nvml.py b/src/gputaskman/nvml.py
new file mode 100644
index 0000000..350cb82
--- /dev/null
+++ b/src/gputaskman/nvml.py
@@ -0,0 +1,129 @@
+"""Device-level NVIDIA metrics via NVML (nvml.dll ships with the driver)."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+try:
+ import pynvml as N
+except ImportError: # pragma: no cover
+ N = None
+
+
+@dataclass
+class NvDevice:
+ index: int
+ name: str = "?"
+ pci_bus: str = ""
+ driver_model: str = "" # WDDM / TCC / MCDM
+ mem_total: int = 0
+ mem_used: int = 0
+ mem_reserved: int = 0
+ util_gpu: float | None = None # % of time a kernel was running
+ util_mem: float | None = None # % of time device memory was being read/written (bandwidth pressure)
+ enc: float | None = None
+ dec: float | None = None
+ temp: int | None = None
+ power_w: float | None = None
+ power_limit_w: float | None = None
+ fan: int | None = None
+ pstate: int | None = None
+ sm_clock: int | None = None
+ sm_clock_max: int | None = None
+ mem_clock: int | None = None
+ pcie_rx_kbs: int | None = None # host -> GPU
+ pcie_tx_kbs: int | None = None # GPU -> host
+ pcie_gen: int | None = None
+ pcie_width: int | None = None
+ throttle: list[str] = field(default_factory=list)
+ compute_cap: str = ""
+
+
+_THROTTLE = {
+ 0x2: "app-clocks",
+ 0x4: "sw-power-cap",
+ 0x8: "hw-slowdown",
+ 0x20: "sw-thermal",
+ 0x40: "hw-thermal",
+ 0x80: "power-brake",
+}
+
+
+def _try(fn, *a, default=None):
+ try:
+ return fn(*a)
+ except Exception:
+ return default
+
+
+class Nvml:
+ def __init__(self) -> None:
+ self.ok = False
+ self.driver = ""
+ self.cuda_version = ""
+ self.handles = []
+ if N is None:
+ return
+ try:
+ N.nvmlInit()
+ except Exception:
+ return
+ self.ok = True
+ self.driver = _try(N.nvmlSystemGetDriverVersion, default="") or ""
+ cv = _try(N.nvmlSystemGetCudaDriverVersion_v2) or _try(N.nvmlSystemGetCudaDriverVersion)
+ if cv:
+ self.cuda_version = f"{cv // 1000}.{(cv % 1000) // 10}"
+ for i in range(_try(N.nvmlDeviceGetCount, default=0)):
+ self.handles.append(N.nvmlDeviceGetHandleByIndex(i))
+
+ def sample(self) -> list[NvDevice]:
+ out = []
+ for i, h in enumerate(self.handles):
+ d = NvDevice(index=i)
+ d.name = _try(N.nvmlDeviceGetName, h, default="?")
+ pci = _try(N.nvmlDeviceGetPciInfo, h)
+ if pci is not None:
+ d.pci_bus = pci.busId.decode() if isinstance(pci.busId, bytes) else str(pci.busId)
+ dm = _try(N.nvmlDeviceGetDriverModel, h)
+ if dm:
+ d.driver_model = {0: "WDDM", 1: "TCC", 2: "MCDM"}.get(dm[0], str(dm[0]))
+ mem = _try(N.nvmlDeviceGetMemoryInfo, h, N.nvmlMemory_v2) or _try(N.nvmlDeviceGetMemoryInfo, h)
+ if mem is not None:
+ d.mem_total, d.mem_used = mem.total, mem.used
+ d.mem_reserved = getattr(mem, "reserved", 0)
+ u = _try(N.nvmlDeviceGetUtilizationRates, h)
+ if u is not None:
+ d.util_gpu, d.util_mem = u.gpu, u.memory
+ enc = _try(N.nvmlDeviceGetEncoderUtilization, h)
+ dec = _try(N.nvmlDeviceGetDecoderUtilization, h)
+ d.enc = enc[0] if enc else None
+ d.dec = dec[0] if dec else None
+ d.temp = _try(N.nvmlDeviceGetTemperature, h, N.NVML_TEMPERATURE_GPU)
+ p = _try(N.nvmlDeviceGetPowerUsage, h)
+ d.power_w = p / 1000 if p is not None else None
+ pl = _try(N.nvmlDeviceGetEnforcedPowerLimit, h)
+ d.power_limit_w = pl / 1000 if pl is not None else None
+ d.fan = _try(N.nvmlDeviceGetFanSpeed, h)
+ d.pstate = _try(N.nvmlDeviceGetPerformanceState, h)
+ d.sm_clock = _try(N.nvmlDeviceGetClockInfo, h, N.NVML_CLOCK_SM)
+ d.sm_clock_max = _try(N.nvmlDeviceGetMaxClockInfo, h, N.NVML_CLOCK_SM)
+ d.mem_clock = _try(N.nvmlDeviceGetClockInfo, h, N.NVML_CLOCK_MEM)
+ d.pcie_rx_kbs = _try(N.nvmlDeviceGetPcieThroughput, h, N.NVML_PCIE_UTIL_RX_BYTES)
+ d.pcie_tx_kbs = _try(N.nvmlDeviceGetPcieThroughput, h, N.NVML_PCIE_UTIL_TX_BYTES)
+ d.pcie_gen = _try(N.nvmlDeviceGetCurrPcieLinkGeneration, h)
+ d.pcie_width = _try(N.nvmlDeviceGetCurrPcieLinkWidth, h)
+ reasons = _try(N.nvmlDeviceGetCurrentClocksEventReasons, h)
+ if reasons is None:
+ reasons = _try(N.nvmlDeviceGetCurrentClocksThrottleReasons, h)
+ if reasons:
+ d.throttle = [n for bit, n in _THROTTLE.items() if reasons & bit]
+ cc = _try(N.nvmlDeviceGetCudaComputeCapability, h)
+ if cc:
+ d.compute_cap = f"{cc[0]}.{cc[1]}"
+ out.append(d)
+ return out
+
+ def close(self) -> None:
+ if self.ok:
+ _try(N.nvmlShutdown)
+ self.ok = False
diff --git a/src/gputaskman/pdh.py b/src/gputaskman/pdh.py
new file mode 100644
index 0000000..3f16e41
--- /dev/null
+++ b/src/gputaskman/pdh.py
@@ -0,0 +1,186 @@
+"""Windows GPU performance counters (the same data Task Manager uses).
+
+These come from the WDDM graphics kernel (dxgkrnl), so they work for every API that
+goes through it -- D3D, Vulkan, OpenGL, *and* CUDA on GeForce/WDDM -- even when
+nvidia-smi/NVML report per-process memory as "N/A".
+"""
+
+from __future__ import annotations
+
+import ctypes
+import re
+from collections import defaultdict
+from ctypes import wintypes
+from dataclasses import dataclass, field
+
+_pdh = ctypes.WinDLL("pdh")
+
+PDH_FMT_DOUBLE = 0x00000200
+PDH_FMT_NOCAP100 = 0x00008000
+PDH_MORE_DATA = 0x800007D2
+
+
+class _Value(ctypes.Union):
+ _fields_ = [
+ ("longValue", ctypes.c_long),
+ ("doubleValue", ctypes.c_double),
+ ("largeValue", ctypes.c_longlong),
+ ("str", ctypes.c_wchar_p),
+ ]
+
+
+class _FmtValue(ctypes.Structure):
+ _fields_ = [("CStatus", wintypes.DWORD), ("u", _Value)]
+
+
+class _Item(ctypes.Structure):
+ _fields_ = [("szName", ctypes.c_wchar_p), ("FmtValue", _FmtValue)]
+
+
+_pdh.PdhOpenQueryW.argtypes = [wintypes.LPCWSTR, ctypes.c_size_t, ctypes.POINTER(wintypes.HANDLE)]
+_pdh.PdhAddEnglishCounterW.argtypes = [wintypes.HANDLE, wintypes.LPCWSTR, ctypes.c_size_t, ctypes.POINTER(wintypes.HANDLE)]
+_pdh.PdhCollectQueryData.argtypes = [wintypes.HANDLE]
+_pdh.PdhGetFormattedCounterArrayW.argtypes = [
+ wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), ctypes.POINTER(wintypes.DWORD), ctypes.c_void_p,
+]
+_pdh.PdhCloseQuery.argtypes = [wintypes.HANDLE]
+for _fn in ("PdhOpenQueryW", "PdhAddEnglishCounterW", "PdhCollectQueryData", "PdhGetFormattedCounterArrayW", "PdhCloseQuery"):
+ getattr(_pdh, _fn).restype = wintypes.DWORD
+
+_LUID_RE = r"luid_0x([0-9a-fA-F]+)_0x([0-9a-fA-F]+)"
+_PROC_RE = re.compile(rf"pid_(\d+)_{_LUID_RE}_phys_(\d+)")
+_ENGINE_RE = re.compile(rf"pid_(\d+)_{_LUID_RE}_phys_(\d+)_eng_(\d+)_engtype_(.*)$")
+_ADAPTER_RE = re.compile(rf"^{_LUID_RE}_phys_(\d+)$")
+
+
+def luid_key(hi: str, lo: str) -> int:
+ return (int(hi, 16) << 32) | int(lo, 16)
+
+
+@dataclass
+class ProcGpu:
+ dedicated: float = 0.0 # bytes resident in VRAM charged to this process ("Local Usage")
+ shared: float = 0.0 # bytes resident in shared (system RAM) GPU memory -- "spill" ("Non Local Usage")
+ committed: float = 0.0 # all GPU memory this process allocated, resident or not ("Total Committed")
+ engines: dict[str, float] = field(default_factory=lambda: defaultdict(float)) # engtype -> util %
+
+ @property
+ def paged_out(self) -> float:
+ """Commit minus local/non-local usage: a non-residency estimate, not an eviction trace."""
+ return max(self.committed - self.dedicated - self.shared, 0.0)
+
+ @property
+ def gpu_pct(self) -> float:
+ # Task Manager semantics: busiest engine wins.
+ return max(self.engines.values(), default=0.0)
+
+
+@dataclass
+class AdapterGpu:
+ dedicated: float = 0.0
+ shared: float = 0.0
+
+
+class GpuCounters:
+ # Per-process "Dedicated/Shared Usage" count every allocation a process can *see*, including surfaces
+ # shared from other processes: dwm.exe read 15+ GB on a 16 GB card and the per-process sum was 2x the
+ # adapter total. "Local/Non Local Usage" is what's charged to each process and adds up to the adapter
+ # total. The older counters are only a fallback.
+ _COUNTERS = {
+ "dedicated": (r"\GPU Process Memory(*)\Local Usage", r"\GPU Process Memory(*)\Dedicated Usage"),
+ "shared": (r"\GPU Process Memory(*)\Non Local Usage", r"\GPU Process Memory(*)\Shared Usage"),
+ "committed": (r"\GPU Process Memory(*)\Total Committed",),
+ "engine": (r"\GPU Engine(*)\Utilization Percentage",),
+ "a_dedicated": (r"\GPU Adapter Memory(*)\Dedicated Usage",),
+ "a_shared": (r"\GPU Adapter Memory(*)\Shared Usage",),
+ }
+
+ def __init__(self) -> None:
+ self._query = wintypes.HANDLE()
+ self._check(_pdh.PdhOpenQueryW(None, 0, ctypes.byref(self._query)), "PdhOpenQuery")
+ self._handles: dict[str, wintypes.HANDLE] = {}
+ for key, paths in self._COUNTERS.items():
+ for path in paths:
+ h = wintypes.HANDLE()
+ if _pdh.PdhAddEnglishCounterW(self._query, path, 0, ctypes.byref(h)) == 0:
+ self._handles[key] = h
+ break
+ _pdh.PdhCollectQueryData(self._query) # rate counters need a baseline sample
+
+ @staticmethod
+ def _check(status: int, what: str) -> None:
+ if status != 0:
+ raise OSError(f"{what} failed: 0x{status:08X}")
+
+ def _read(self, key: str) -> list[tuple[str, float]]:
+ h = self._handles.get(key)
+ if h is None:
+ return []
+ size = wintypes.DWORD(0)
+ count = wintypes.DWORD(0)
+ fmt = PDH_FMT_DOUBLE | PDH_FMT_NOCAP100
+ status = _pdh.PdhGetFormattedCounterArrayW(h, fmt, ctypes.byref(size), ctypes.byref(count), None)
+ if status != PDH_MORE_DATA:
+ return []
+ buf = ctypes.create_string_buffer(size.value)
+ status = _pdh.PdhGetFormattedCounterArrayW(h, fmt, ctypes.byref(size), ctypes.byref(count), buf)
+ if status != 0:
+ return []
+ items = ctypes.cast(buf, ctypes.POINTER(_Item))
+ out = []
+ for i in range(count.value):
+ it = items[i]
+ if it.FmtValue.CStatus in (0, 1): # PDH_CSTATUS_VALID_DATA / NEW_DATA
+ out.append((it.szName, it.FmtValue.u.doubleValue))
+ return out
+
+ def sample(self) -> tuple[dict[int, dict[int, ProcGpu]], dict[int, AdapterGpu]]:
+ """Returns ({luid: {pid: ProcGpu}}, {luid: AdapterGpu})."""
+ _pdh.PdhCollectQueryData(self._query)
+ procs: dict[int, dict[int, ProcGpu]] = defaultdict(dict)
+
+ def proc(luid: int, pid: int) -> ProcGpu:
+ p = procs[luid].get(pid)
+ if p is None:
+ p = procs[luid][pid] = ProcGpu()
+ return p
+
+ for attr in ("dedicated", "shared", "committed"):
+ for name, val in self._read(attr):
+ m = _PROC_RE.match(name)
+ if m:
+ p = proc(luid_key(m[2], m[3]), int(m[1]))
+ setattr(p, attr, getattr(p, attr) + val)
+ for name, val in self._read("engine"):
+ m = _ENGINE_RE.match(name)
+ if m:
+ proc(luid_key(m[2], m[3]), int(m[1])).engines[_norm_engine(m[6])] += val
+
+ adapters: dict[int, AdapterGpu] = defaultdict(AdapterGpu)
+ for attr, key in (("dedicated", "a_dedicated"), ("shared", "a_shared")):
+ for name, val in self._read(key):
+ m = _ADAPTER_RE.match(name)
+ if m:
+ a = adapters[luid_key(m[1], m[2])]
+ setattr(a, attr, getattr(a, attr) + val)
+ return procs, adapters
+
+ def close(self) -> None:
+ if self._query:
+ _pdh.PdhCloseQuery(self._query)
+ self._query = wintypes.HANDLE()
+
+
+def _norm_engine(t: str) -> str:
+ t = t.lower()
+ if t.startswith("3d"):
+ return "3d"
+ if t.startswith("compute") or t.startswith("cuda"):
+ return "compute"
+ if t.startswith("copy"):
+ return "copy"
+ if t.startswith("videodecode"):
+ return "decode"
+ if t.startswith("videoencode"):
+ return "encode"
+ return "other"
diff --git a/src/gputaskman/procinfo.py b/src/gputaskman/procinfo.py
new file mode 100644
index 0000000..b532849
--- /dev/null
+++ b/src/gputaskman/procinfo.py
@@ -0,0 +1,200 @@
+"""Per-process introspection: which GPU runtimes are loaded, which model files are mapped."""
+
+from __future__ import annotations
+
+import fnmatch
+import os
+import time
+from dataclasses import dataclass, field
+
+import psutil
+
+from .gguf import is_gguf
+
+# (tag, dll patterns). Order = display priority (most specific first).
+RUNTIMES: list[tuple[str, tuple[str, ...]]] = [
+ ("llama.cpp", ("llama.dll", "libllama*.dll", "llama-*.dll", "llm_engine*")),
+ ("whisper.cpp", ("whisper*.dll",)),
+ ("ggml", ("ggml*.dll",)),
+ ("PyTorch", ("torch_cuda*.dll", "torch_cpu.dll")),
+ ("TensorRT", ("nvinfer*.dll",)),
+ ("ONNX RT", ("onnxruntime*.dll",)),
+ ("DirectML", ("directml.dll",)),
+ ("cuDNN", ("cudnn*.dll",)),
+ ("CUDA", ("nvcuda.dll", "nvcuda64.dll", "cudart64_*.dll", "cublas64_*.dll")),
+ ("Vulkan", ("vulkan-1.dll",)),
+ ("D3D12", ("d3d12core.dll",)),
+ ("OpenGL", ("opengl32.dll",)),
+ ("D3D11", ("d3d11.dll",)),
+ ("NVENC", ("nvencodeapi64.dll",)),
+ ("NVDEC", ("nvcuvid.dll", "nvcuvid64.dll")),
+]
+AI_RUNTIMES = {"llama.cpp", "whisper.cpp", "ggml", "PyTorch", "TensorRT", "ONNX RT", "DirectML", "cuDNN"}
+MODEL_EXTS = {".gguf", ".ggml", ".safetensors", ".onnx", ".pt", ".pth", ".bin", ".engine", ".plan", ".tflite", ".ckpt"}
+_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"}
+LLM_NAMES = ("llama-", "ollama", "lm studio", "lmstudio", "llmster", "koboldcpp", "jan", "gpt4all", "llamafile")
+
+
+@dataclass
+class MappedModel:
+ path: str
+ size: int
+ resident: int # bytes of the file currently in this process's RAM working set
+ gguf: bool
+ source: str = "mapped" # "mapped" (memory-mapped) or "cmdline" (passed as an argument)
+
+
+@dataclass
+class ProcDetail:
+ pid: int
+ name: str = "?"
+ exe: str = ""
+ cmdline: list[str] = field(default_factory=list)
+ create_time: float = 0.0
+ runtimes: list[str] = field(default_factory=list)
+ models: list[MappedModel] = field(default_factory=list)
+ ports: list[int] = field(default_factory=list)
+ access_denied: bool = False
+ maps_time: float = 0.0 # when memory maps were last scanned
+
+ @property
+ def is_ai(self) -> bool:
+ return bool(self.models) or any(r in AI_RUNTIMES for r in self.runtimes)
+
+
+def _match_runtimes(dll_names: set[str]) -> list[str]:
+ found = []
+ for tag, patterns in RUNTIMES:
+ if any(fnmatch.fnmatch(d, p) for d in dll_names for p in patterns):
+ found.append(tag)
+ return found
+
+
+def _models_from_cmdline(cmd: list[str]) -> list[str]:
+ paths = []
+ for i, arg in enumerate(cmd):
+ val = None
+ if arg in ("-m", "--model", "--mmproj", "-md", "--model-draft", "--lora") and i + 1 < len(cmd):
+ val = cmd[i + 1]
+ elif arg.startswith("--model="):
+ val = arg.split("=", 1)[1]
+ if val and os.path.isfile(val):
+ paths.append(os.path.abspath(val))
+ return paths
+
+
+class ProcInspector:
+ """Caches per-process details; memory-map scans are throttled because they can be slow."""
+
+ MAPS_INTERVAL = 15.0
+ PORTS_INTERVAL = 5.0
+
+ def __init__(self) -> None:
+ self._cache: dict[int, ProcDetail] = {}
+ self._ports: dict[int, list[int]] = {}
+ self._ports_time = 0.0
+
+ def _refresh_ports(self) -> None:
+ if time.time() - self._ports_time < self.PORTS_INTERVAL:
+ return
+ ports: dict[int, set[int]] = {}
+ try:
+ for c in psutil.net_connections(kind="tcp"):
+ if c.status == psutil.CONN_LISTEN and c.pid and c.laddr:
+ ports.setdefault(c.pid, set()).add(c.laddr.port)
+ except (psutil.AccessDenied, OSError):
+ pass
+ self._ports = {pid: sorted(p) for pid, p in ports.items()}
+ self._ports_time = time.time()
+
+ def get(self, pid: int, deep: bool) -> ProcDetail:
+ """deep=True scans memory maps (DLLs + mapped model files)."""
+ self._refresh_ports()
+ d = self._cache.get(pid)
+ try:
+ p = psutil.Process(pid)
+ ct = p.create_time()
+ except (psutil.NoSuchProcess, psutil.AccessDenied, OSError):
+ p, ct = None, 0.0
+ if d is None or d.create_time != ct:
+ d = ProcDetail(pid=pid, create_time=ct)
+ if pid == 0:
+ d.name = "System Idle"
+ elif p is not None:
+ try:
+ d.name = p.name()
+ except (psutil.Error, OSError):
+ pass
+ try:
+ d.exe = p.exe()
+ d.cmdline = p.cmdline()
+ except (psutil.Error, OSError):
+ d.access_denied = True
+ self._cache[pid] = d
+ d.ports = self._ports.get(pid, [])
+ if deep and p is not None and not d.access_denied and time.time() - d.maps_time > self.MAPS_INTERVAL:
+ self._scan_maps(p, d)
+ return d
+
+ def _scan_maps(self, p: psutil.Process, d: ProcDetail) -> None:
+ d.maps_time = time.time()
+ try:
+ maps = p.memory_maps(grouped=True)
+ except (psutil.Error, OSError):
+ d.access_denied = True
+ return
+ dlls: set[str] = set()
+ models: dict[str, MappedModel] = {}
+ for m in maps:
+ path = m.path
+ base = os.path.basename(path).lower()
+ ext = os.path.splitext(base)[1]
+ if ext == ".dll" or ext == ".node":
+ dlls.add(base)
+ continue
+ if ext in _NOT_MODELS:
+ continue
+ try:
+ size = os.path.getsize(path)
+ except OSError:
+ continue
+ gg = is_gguf(path) if (ext in (".gguf", "") or size > 64 << 20) else False
+ if ext in MODEL_EXTS or gg:
+ if size < (4 << 20) and not gg:
+ continue
+ models[path.lower()] = MappedModel(path=path, size=size, resident=m.rss, gguf=gg)
+ for path in _models_from_cmdline(d.cmdline):
+ if path.lower() not in models:
+ models[path.lower()] = MappedModel(path, os.path.getsize(path), 0, is_gguf(path), source="cmdline")
+ d.runtimes = _match_runtimes(dlls)
+ d.models = sorted(models.values(), key=lambda m: -m.size)
+
+ def prune(self, live_pids: set[int]) -> None:
+ for pid in list(self._cache):
+ if pid not in live_pids:
+ del self._cache[pid]
+
+
+def classify(d: ProcDetail, engines: dict[str, float]) -> str:
+ n = d.name.lower()
+ if d.pid == 4:
+ return "kernel"
+ if n == "dwm.exe":
+ return "compositor"
+ if n in ("csrss.exe", "winlogon.exe", "lsass.exe", "svchost.exe"):
+ return "system"
+ if any(m.gguf for m in d.models) or "llama.cpp" in d.runtimes or n.startswith(LLM_NAMES):
+ return "LLM"
+ video = engines.get("decode", 0) + engines.get("encode", 0) > 1
+ if d.is_ai and not video:
+ return "AI"
+ if n in BROWSERS:
+ return "browser"
+ if video or "NVENC" in d.runtimes:
+ return "video"
+ if "CUDA" in d.runtimes:
+ return "compute"
+ if ("D3D12" in d.runtimes or "Vulkan" in d.runtimes) and engines.get("3d", 0) > 10:
+ return "3D/game"
+ return "app"
diff --git a/src/gputaskman/report.py b/src/gputaskman/report.py
new file mode 100644
index 0000000..80bf669
--- /dev/null
+++ b/src/gputaskman/report.py
@@ -0,0 +1,81 @@
+"""Plain-text / JSON snapshot output (no TUI) - handy for scripts, agents and bug reports."""
+
+from __future__ import annotations
+
+import dataclasses
+import json
+import os
+
+from .collector import Snapshot
+from .llm import gb
+
+
+def to_dict(s: Snapshot) -> dict:
+ nv = dataclasses.asdict(s.nv) if s.nv else None
+ procs = []
+ for p in s.procs:
+ item = {
+ "pid": p.pid, "name": p.name, "kind": p.kind, "runtimes": p.detail.runtimes,
+ "vram_bytes": int(p.gpu.dedicated), "shared_bytes": int(p.gpu.shared),
+ "committed_bytes": int(p.gpu.committed), "paged_out_bytes": int(p.gpu.paged_out),
+ "gpu_pct": round(p.gpu.gpu_pct, 1), "engines": {k: round(v, 1) for k, v in p.gpu.engines.items() if v},
+ "ports": p.detail.ports, "inside": p.inside,
+ "model_files": [dataclasses.asdict(m) for m in p.detail.models],
+ }
+ if p.llm:
+ item["llm"] = {
+ "models": [{"path": g.path, "name": g.name, "arch": g.arch, "kind": g.kind, "params": g.n_params,
+ "quant": g.quant, "layers": g.n_layers, "ctx_train": g.ctx_train,
+ "gpu_weight_bytes": g.gpu_weight_bytes()} for g in p.llm.models],
+ "segments": [dataclasses.asdict(x) for x in p.llm.segments],
+ "kv_bytes_per_token": p.llm.kv_per_token, "n_ctx": p.llm.n_ctx, "flags": p.llm.flags,
+ "server": dataclasses.asdict(p.llm.server) if p.llm.server else None,
+ "log_source": p.llm.log_source, "notes": p.llm.notes,
+ }
+ procs.append(item)
+ return {
+ "taken": s.taken, "gpu": s.adapter.name if s.adapter else None, "driver": s.driver, "cuda": s.cuda,
+ "vram_total": s.vram_total, "vram_used": s.vram_used, "shared_used": s.shared_used,
+ "attributed": s.attributed, "device": nv, "processes": procs,
+ }
+
+
+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 ''}")
+ out.append(f"VRAM {gb(s.vram_used)} / {gb(s.vram_total)} shared (in system RAM) {gb(s.shared_used)}")
+ if nv:
+ out.append(f"GPU {nv.util_gpu}% mem-bandwidth {nv.util_mem}% {nv.temp}C {nv.power_w:.0f}/{nv.power_limit_w:.0f} W "
+ f"P{nv.pstate} SM {nv.sm_clock} MHz PCIe rx {(nv.pcie_rx_kbs or 0) / 1024:.0f} MB/s tx {(nv.pcie_tx_kbs or 0) / 1024:.0f} MB/s")
+ out.append("")
+ out.append(f"{'PID':>7} {'PROCESS':<24} {'KIND':<10} {'RUNTIME':<24} {'VRAM':>9} {'SPILL':>8} {'PAGED':>8} {'GPU%':>5} INSIDE")
+ for p in s.procs[:limit]:
+ spill = gb(p.gpu.shared) if p.gpu.shared >= 1 << 20 else ""
+ paged = gb(p.gpu.paged_out) if p.gpu.paged_out >= 1 << 20 else ""
+ out.append(f"{p.pid:>7} {p.name[:24]:<24} {p.kind:<10} {p.runtime[:24]:<24} {gb(p.gpu.dedicated):>9} {spill:>8} "
+ f"{paged:>8} {p.gpu.gpu_pct:>5.0f} {p.inside}")
+ for p in s.procs:
+ if not p.llm:
+ continue
+ out.append("")
+ out.append(f"== {p.name} ({p.pid}) VRAM {gb(p.gpu.dedicated)}")
+ for g in p.llm.models:
+ out.append(f" {g.kind}: {g.name} [{g.arch}, {g.params_label} params, {g.quant}, {g.n_layers} layers, "
+ f"ctx_train {g.ctx_train}] {os.path.basename(g.path)}")
+ for seg in p.llm.segments:
+ out.append(f" {gb(seg.bytes):>9} {seg.label}{'' if seg.exact else ''}")
+ if p.llm.server:
+ sv = p.llm.server
+ out.append(f" server: {sv.kind} {sv.url} ctx={sv.n_ctx} slots={sv.slots_busy}/{sv.slots_total}"
+ + (f" gen={sv.gen_tok_s:.1f} tok/s" if sv.gen_tok_s is not None else ""))
+ if p.llm.log_source:
+ out.append(f" exact sizes from log: {p.llm.log_source}")
+ for n in p.llm.notes:
+ out.append(f" - {n}")
+ return "\n".join(out)
+
+
+def dump(s: Snapshot, as_json: bool) -> str:
+ return json.dumps(to_dict(s), indent=2, default=str) if as_json else to_text(s)
diff --git a/tests/test_core.py b/tests/test_core.py
new file mode 100644
index 0000000..f0d0204
--- /dev/null
+++ b/tests/test_core.py
@@ -0,0 +1,189 @@
+from __future__ import annotations
+
+import contextlib
+import io
+import json
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+from gputaskman.app import GpuTaskManager
+from gputaskman.cli import main
+from gputaskman.collector import ProcRow, Snapshot
+from gputaskman.gguf import GgufInfo, read_gguf
+from gputaskman.llm import LlmView, ServerInfo, is_gpu_device, parse_flags, parse_load_log
+from gputaskman.pdh import GpuCounters, ProcGpu
+from gputaskman.procinfo import ProcDetail
+from gputaskman.report import to_dict, to_text
+from tools.capture_screenshots import for_publication
+
+GiB = 1 << 30
+MiB = 1 << 20
+
+
+def snapshot() -> Snapshot:
+ return Snapshot(
+ taken=1, adapter=None, adapters=[], nv=None, driver="", cuda="",
+ vram_total=16 * GiB, vram_used=10 * GiB, shared_used=GiB,
+ procs=[
+ ProcRow(10, "llama-server.exe", "LLM",
+ ProcGpu(dedicated=8 * GiB, shared=GiB, committed=9 * GiB),
+ ProcDetail(10, "llama-server.exe", cmdline=["server.exe", "--api-key", "private-test-value"]),
+ LlmView(server=ServerInfo("llama-server", "http://127.0.0.1:8080"))),
+ ProcRow(20, "dwm.exe", "compositor",
+ ProcGpu(dedicated=2 * GiB, committed=3 * GiB),
+ ProcDetail(20, "dwm.exe")),
+ ],
+ )
+
+
+class CliTests(unittest.TestCase):
+ def test_invalid_options_fail_before_collecting(self):
+ for args in (["--gpu", "-1"], ["-i", "0"], ["-i", "-1"],
+ ["-i", "nan"], ["-i", "inf"]):
+ with self.subTest(args=args), patch("sys.argv", ["gputaskman", *args]):
+ with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as error:
+ main()
+ self.assertEqual(error.exception.code, 2)
+
+ def test_help_needs_no_gpu(self):
+ output = io.StringIO()
+ with patch("sys.argv", ["gputaskman", "--help"]), contextlib.redirect_stdout(output):
+ with self.assertRaises(SystemExit) as error:
+ main()
+ self.assertEqual(error.exception.code, 0)
+ self.assertIn("implies --once", output.getvalue())
+
+ def test_json_implies_once(self):
+ output = io.StringIO()
+ with patch("sys.argv", ["gputaskman", "--json"]), patch("gputaskman.cli.time.sleep"):
+ with patch("gputaskman.collector.Collector") as collector, contextlib.redirect_stdout(output):
+ collector.return_value.sample.return_value = snapshot()
+ main()
+ collector.return_value.close.assert_called_once()
+ self.assertEqual(len(json.loads(output.getvalue())["processes"]), 2)
+
+ def test_snapshot_failure_closes_collector(self):
+ with patch("sys.argv", ["gputaskman", "--once"]), patch("gputaskman.cli.time.sleep"):
+ with patch("gputaskman.collector.Collector") as collector:
+ collector.return_value.sample.side_effect = OSError("counter unavailable")
+ with self.assertRaisesRegex(OSError, "counter unavailable"):
+ main()
+ collector.return_value.close.assert_called_once()
+
+
+class MemoryTests(unittest.TestCase):
+ def test_local_counters_are_preferred(self):
+ self.assertTrue(GpuCounters._COUNTERS["dedicated"][0].endswith(r"\Local Usage"))
+ self.assertTrue(GpuCounters._COUNTERS["shared"][0].endswith(r"\Non Local Usage"))
+
+ def test_paged_is_clamped_commit_difference(self):
+ gpu = ProcGpu(dedicated=100, shared=20, committed=150)
+ self.assertEqual(gpu.paged_out, 30)
+ gpu.committed = 10
+ self.assertEqual(gpu.paged_out, 0)
+
+ def test_compositor_is_in_attribution(self):
+ self.assertEqual(snapshot().attributed, 10 * GiB)
+
+ def test_json_and_text_match_the_snapshot(self):
+ data = to_dict(snapshot())
+ self.assertEqual(data["processes"][1]["paged_out_bytes"], GiB)
+ self.assertEqual(data["processes"][0]["shared_bytes"], GiB)
+ self.assertEqual(data["attributed"], 10 * GiB)
+ text = to_text(snapshot())
+ self.assertIn("PAGED", text)
+ self.assertNotIn("gen=None", text)
+
+ def test_capture_does_not_change_original_or_publish_command_line(self):
+ original = snapshot()
+ original.procs[0].llm.models = [
+ GgufInfo(path=r"C:\Users\example\models\model.gguf", file_size=1, version=3)
+ ]
+ public = for_publication(original)
+ self.assertEqual(public.procs[0].detail.cmdline, [])
+ self.assertEqual(public.procs[0].llm.models[0].path, "model.gguf")
+ self.assertIn("private-test-value", original.procs[0].detail.cmdline)
+ self.assertIn("Users", original.procs[0].llm.models[0].path)
+
+
+class ModelTests(unittest.TestCase):
+ def test_layer_and_kv_estimates(self):
+ model = GgufInfo(
+ path="model.gguf", file_size=1000, version=3,
+ metadata={"general.architecture": "test", "test.block_count": 2,
+ "test.attention.head_count": 4, "test.attention.head_count_kv": 2,
+ "test.embedding_length": 16},
+ layer_bytes={0: 100, 1: 100}, output_bytes=50, token_embd_bytes=50,
+ )
+ self.assertEqual(model.gpu_weight_bytes(), 250)
+ self.assertEqual(model.gpu_weight_bytes(1), 100)
+ self.assertEqual(model.gpu_weight_bytes(0), 0)
+ self.assertEqual(model.kv_bytes_per_token(), 64)
+
+ def test_truncated_model_reports_error(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "truncated.gguf"
+ path.write_bytes(b"GGUF")
+ self.assertIsNotNone(read_gguf(str(path)).error)
+
+ def test_flags_include_equals_and_gpu_layers(self):
+ self.assertEqual(parse_flags(["server", "--ctx-size=8192", "-ngl", "all", "--cache-type-k=q8_0"]),
+ {"ctx": 8192, "ngl": -1, "ctk": "q8_0"})
+
+ def test_gpu_buffers_exclude_host_and_cpu(self):
+ for device in ("CPU", "CPU_Mapped", "CUDA_Host"):
+ self.assertFalse(is_gpu_device(device))
+ self.assertTrue(is_gpu_device("CUDA0"))
+
+ def test_latest_load_and_multiple_kv_buffers(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "server.log"
+ path.write_text(
+ "load_tensors: CUDA0 model buffer size = 900 MiB\n"
+ "llama_context: CUDA0 KV buffer size = 800 MiB\n"
+ "new load\n"
+ "load_tensors: CPU_Mapped model buffer size = 30 MiB\n"
+ "load_tensors: CUDA0 model buffer size = 100 MiB\n"
+ "llama_context: CUDA0 KV buffer size = 20 MiB\n"
+ "llama_context: CUDA0 KV buffer size = 10 MiB\n"
+ "llama_context: CUDA0 compute buffer size = 5 MiB\n",
+ encoding="utf-8",
+ )
+ self.assertEqual(parse_load_log(str(path)), {
+ "CPU_Mapped": {"weights": 30 * MiB},
+ "CUDA0": {"weights": 100 * MiB, "kv": 30 * MiB, "compute": 5 * MiB},
+ })
+ self.assertIsNone(parse_load_log(str(path), not_before=path.stat().st_mtime + 10))
+
+
+class UiTests(unittest.IsolatedAsyncioTestCase):
+ async def test_navigation_sort_pause_and_help(self):
+ with patch.object(GpuTaskManager, "poll"):
+ app = GpuTaskManager()
+ async with app.run_test(size=(140, 42)) as pilot:
+ app.apply(snapshot())
+ await pilot.pause()
+ self.assertEqual(app.query_one("#procs").row_count, 2)
+ await pilot.press("down")
+ await pilot.pause()
+ self.assertEqual(app.selected_pid, 20)
+ app.apply(snapshot())
+ await pilot.pause()
+ self.assertEqual(app.selected_pid, 20)
+ for _ in app.SORTS:
+ await pilot.press("s")
+ self.assertEqual(app.sort_idx, 0)
+ await pilot.press("a", "p")
+ self.assertTrue(app.show_all)
+ self.assertTrue(app.paused)
+ await pilot.press("question_mark")
+ self.assertEqual(len(app.screen_stack), 2)
+ await pilot.press("escape", "p")
+ self.assertEqual(len(app.screen_stack), 1)
+ self.assertFalse(app.paused)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/capture_screenshots.py b/tools/capture_screenshots.py
new file mode 100644
index 0000000..6418e91
--- /dev/null
+++ b/tools/capture_screenshots.py
@@ -0,0 +1,93 @@
+"""Capture real local measurements through Textual, without publishing command lines or full paths."""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import copy
+import os
+import time
+from pathlib import Path
+from unittest.mock import patch
+
+from gputaskman.app import GpuTaskManager
+from gputaskman.collector import Collector, Snapshot
+
+
+def for_publication(snapshot: Snapshot) -> Snapshot:
+ snapshot = copy.deepcopy(snapshot)
+ for row in snapshot.procs:
+ row.detail.cmdline = []
+ row.detail.exe = ""
+ for model in row.detail.models:
+ model.path = os.path.basename(model.path)
+ if row.llm:
+ for model in row.llm.models:
+ model.path = os.path.basename(model.path)
+ for model in row.llm.other_files:
+ model.path = os.path.basename(model.path)
+ if row.llm.log_source:
+ row.llm.log_source = os.path.basename(row.llm.log_source)
+ return snapshot
+
+
+async def capture(snapshots: list[Snapshot], output: Path) -> None:
+ output.mkdir(parents=True, exist_ok=True)
+ app = GpuTaskManager()
+ # Freeze a real sample for each view rather than inventing demonstration metrics.
+ with patch.object(GpuTaskManager, "poll"):
+ async with app.run_test(size=(160, 48)) as pilot:
+ for snapshot in snapshots:
+ app.apply(snapshot)
+ await pilot.pause()
+ final = snapshots[-1]
+ llm = next((row for row in final.procs if row.llm and row.llm.models), None)
+ if llm:
+ app.selected_pid = llm.pid
+ else:
+ print("No loaded LLM found; overview will show the available GPU processes.")
+ app.render_table(final)
+ app.render_inspector()
+ await pilot.pause()
+ app.save_screenshot("overview.svg", path=str(output))
+
+ dwm = next((row for row in final.procs if row.kind == "compositor"), None)
+ if dwm:
+ app.selected_pid = dwm.pid
+ app.render_table(final)
+ app.render_inspector()
+ await pilot.pause()
+ app.save_screenshot("compositor.svg", path=str(output))
+ else:
+ print("No compositor row available; compositor capture skipped.")
+
+ app.sort_idx = next(i for i, (name, _) in enumerate(app.SORTS) if name == "spill")
+ app.selected_pid = max(final.procs, key=lambda row: row.gpu.shared).pid if final.procs else None
+ app.render_table(final)
+ app.render_inspector()
+ await pilot.pause()
+ app.save_screenshot("system-memory.svg", path=str(output))
+
+ await pilot.press("question_mark")
+ await pilot.pause()
+ app.save_screenshot("help.svg", path=str(output))
+ print(f"Captured local measurements to {output}. Review all images before publishing.")
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--output", type=Path, default=Path("docs") / "screenshots")
+ args = parser.parse_args()
+ collector = Collector()
+ try:
+ snapshots = []
+ for _ in range(8):
+ time.sleep(1)
+ snapshots.append(for_publication(collector.sample()))
+ finally:
+ collector.close()
+ asyncio.run(capture(snapshots, args.output))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/uv.lock b/uv.lock
new file mode 100644
index 0000000..71c179e
--- /dev/null
+++ b/uv.lock
@@ -0,0 +1,161 @@
+version = 1
+revision = 3
+requires-python = ">=3.11"
+
+[[package]]
+name = "gputaskman"
+version = "0.1.0"
+source = { editable = "." }
+dependencies = [
+ { name = "nvidia-ml-py" },
+ { name = "psutil" },
+ { name = "textual" },
+]
+
+[package.metadata]
+requires-dist = [
+ { name = "nvidia-ml-py", specifier = ">=13.615.71" },
+ { name = "psutil", specifier = ">=7.2.2" },
+ { name = "textual", specifier = ">=8.2.8" },
+]
+
+[[package]]
+name = "linkify-it-py"
+version = "2.2.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/45/98/7a1a5f31fd5c7ba93e963b168e244b8e3dd705b3d2a718e3c3307583bf57/linkify_it_py-2.2.0.tar.gz", hash = "sha256:907acd2d17ac1fbb9ddb62c8957ccbd6158cac602231a15c3b0cd1e215f03cee", size = 32939, upload-time = "2026-08-29T07:07:08.305Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/13/d4/1152d1c7ab42d8b908be64fd200ddc870dc9d4925e951198702084aa1a7d/linkify_it_py-2.2.0-py3-none-any.whl", hash = "sha256:3adc40eb5af300b2605fcfdb968c24e1d780a90f1f2221af7c15e5111e94d443", size = 21971, upload-time = "2026-08-29T07:07:07.164Z" },
+]
+
+[[package]]
+name = "markdown-it-py"
+version = "4.2.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "mdurl" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/06/ff/7841249c247aa650a76b9ee4bbaeae59370dc8bfd2f6c01f3630c35eb134/markdown_it_py-4.2.0.tar.gz", hash = "sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49", size = 82454, upload-time = "2026-05-07T12:08:28.36Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b3/81/4da04ced5a082363ecfa159c010d200ecbd959ae410c10c0264a38cac0f5/markdown_it_py-4.2.0-py3-none-any.whl", hash = "sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a", size = 91687, upload-time = "2026-05-07T12:08:27.182Z" },
+]
+
+[package.optional-dependencies]
+linkify = [
+ { name = "linkify-it-py" },
+]
+
+[[package]]
+name = "mdit-py-plugins"
+version = "0.6.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "markdown-it-py" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/59/fc/f8d0863f8862f25602c0404d75568e89fb6b4109804645e5cdfb1be5cf56/mdit_py_plugins-0.6.1.tar.gz", hash = "sha256:a2bca0f039f39dbd35fb74ae1b5f998608c437463371f0ff7f49a19a17a114d0", size = 56114, upload-time = "2026-05-13T09:03:38.91Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a5/69/6da5581c6a7fede7dc261bf4e67d6adca4196f176b43288b55b3db395b6e/mdit_py_plugins-0.6.1-py3-none-any.whl", hash = "sha256:214c82fb2ac524472ab6a5bcab1de80f73b50443e187f401bfd77efbc7c6481d", size = 66663, upload-time = "2026-05-13T09:03:37.76Z" },
+]
+
+[[package]]
+name = "mdurl"
+version = "0.1.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" },
+]
+
+[[package]]
+name = "nvidia-ml-py"
+version = "13.615.71"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/fd/30/b25216758be3d3e2834825d8193609e2d71c770a8bd7984438c058c90268/nvidia_ml_py-13.615.71.tar.gz", hash = "sha256:bebe4e48f51b1dc75028c0815cb7bfa14a31a5bb80be70c9d980c6036953fc3d", size = 57485, upload-time = "2026-09-25T15:15:28.226Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/53/a1/1681dfa1c904d4e3e72e51b55a0ff012d50b766843ef832d584abe2113c6/nvidia_ml_py-13.615.71-py3-none-any.whl", hash = "sha256:959bf4adf6fe1308e4bd739e722236b0d1ec8392e2cefad33ff70c311380b9b6", size = 58132, upload-time = "2026-09-25T15:15:26.54Z" },
+]
+
+[[package]]
+name = "platformdirs"
+version = "4.14.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/9a/6e/886dc7c9d21e2d95aceb696f1e31271742033aeef3661f6e9c8921493592/platformdirs-4.14.3.tar.gz", hash = "sha256:021add1ab113483edbcd4694f5fbb2d688b893ea30d35e1155bb371cf4be0be8", size = 71124, upload-time = "2026-11-01T16:27:32.928Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/93/41/f0aa003909ee77a9e7e55f8659abb635ca23ab0d022a449bbb18da87a1ef/platformdirs-4.14.3-py3-none-any.whl", hash = "sha256:cba2d05fe5e18b26b1fa6f376b8e6234c012abe1f8696c486fface7d0054e931", size = 35276, upload-time = "2026-11-01T16:27:31.498Z" },
+]
+
+[[package]]
+name = "psutil"
+version = "7.2.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/aa/c6/d1ddf4abb55e93cebc4f2ed8b5d6dbad109ecb8d63748dd2b20ab5e57ebe/psutil-7.2.2.tar.gz", hash = "sha256:0746f5f8d406af344fd547f1c8daa5f5c33dbc293bb8d6a16d80b4bb88f59372", size = 493740, upload-time = "2026-01-28T18:14:54.428Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/51/08/510cbdb69c25a96f4ae523f733cdc963ae654904e8db864c07585ef99875/psutil-7.2.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:2edccc433cbfa046b980b0df0171cd25bcaeb3a68fe9022db0979e7aa74a826b", size = 130595, upload-time = "2026-01-28T18:14:57.293Z" },
+ { url = "https://files.pythonhosted.org/packages/d6/f5/97baea3fe7a5a9af7436301f85490905379b1c6f2dd51fe3ecf24b4c5fbf/psutil-7.2.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:e78c8603dcd9a04c7364f1a3e670cea95d51ee865e4efb3556a3a63adef958ea", size = 131082, upload-time = "2026-01-28T18:14:59.732Z" },
+ { url = "https://files.pythonhosted.org/packages/37/d6/246513fbf9fa174af531f28412297dd05241d97a75911ac8febefa1a53c6/psutil-7.2.2-cp313-cp313t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1a571f2330c966c62aeda00dd24620425d4b0cc86881c89861fbc04549e5dc63", size = 181476, upload-time = "2026-01-28T18:15:01.884Z" },
+ { url = "https://files.pythonhosted.org/packages/b8/b5/9182c9af3836cca61696dabe4fd1304e17bc56cb62f17439e1154f225dd3/psutil-7.2.2-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:917e891983ca3c1887b4ef36447b1e0873e70c933afc831c6b6da078ba474312", size = 184062, upload-time = "2026-01-28T18:15:04.436Z" },
+ { url = "https://files.pythonhosted.org/packages/16/ba/0756dca669f5a9300d0cbcbfae9a4c30e446dfc7440ffe43ded5724bfd93/psutil-7.2.2-cp313-cp313t-win_amd64.whl", hash = "sha256:ab486563df44c17f5173621c7b198955bd6b613fb87c71c161f827d3fb149a9b", size = 139893, upload-time = "2026-01-28T18:15:06.378Z" },
+ { url = "https://files.pythonhosted.org/packages/1c/61/8fa0e26f33623b49949346de05ec1ddaad02ed8ba64af45f40a147dbfa97/psutil-7.2.2-cp313-cp313t-win_arm64.whl", hash = "sha256:ae0aefdd8796a7737eccea863f80f81e468a1e4cf14d926bd9b6f5f2d5f90ca9", size = 135589, upload-time = "2026-01-28T18:15:08.03Z" },
+ { url = "https://files.pythonhosted.org/packages/81/69/ef179ab5ca24f32acc1dac0c247fd6a13b501fd5534dbae0e05a1c48b66d/psutil-7.2.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:eed63d3b4d62449571547b60578c5b2c4bcccc5387148db46e0c2313dad0ee00", size = 130664, upload-time = "2026-01-28T18:15:09.469Z" },
+ { url = "https://files.pythonhosted.org/packages/7b/64/665248b557a236d3fa9efc378d60d95ef56dd0a490c2cd37dafc7660d4a9/psutil-7.2.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7b6d09433a10592ce39b13d7be5a54fbac1d1228ed29abc880fb23df7cb694c9", size = 131087, upload-time = "2026-01-28T18:15:11.724Z" },
+ { url = "https://files.pythonhosted.org/packages/d5/2e/e6782744700d6759ebce3043dcfa661fb61e2fb752b91cdeae9af12c2178/psutil-7.2.2-cp314-cp314t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1fa4ecf83bcdf6e6c8f4449aff98eefb5d0604bf88cb883d7da3d8d2d909546a", size = 182383, upload-time = "2026-01-28T18:15:13.445Z" },
+ { url = "https://files.pythonhosted.org/packages/57/49/0a41cefd10cb7505cdc04dab3eacf24c0c2cb158a998b8c7b1d27ee2c1f5/psutil-7.2.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e452c464a02e7dc7822a05d25db4cde564444a67e58539a00f929c51eddda0cf", size = 185210, upload-time = "2026-01-28T18:15:16.002Z" },
+ { url = "https://files.pythonhosted.org/packages/dd/2c/ff9bfb544f283ba5f83ba725a3c5fec6d6b10b8f27ac1dc641c473dc390d/psutil-7.2.2-cp314-cp314t-win_amd64.whl", hash = "sha256:c7663d4e37f13e884d13994247449e9f8f574bc4655d509c3b95e9ec9e2b9dc1", size = 141228, upload-time = "2026-01-28T18:15:18.385Z" },
+ { url = "https://files.pythonhosted.org/packages/f2/fc/f8d9c31db14fcec13748d373e668bc3bed94d9077dbc17fb0eebc073233c/psutil-7.2.2-cp314-cp314t-win_arm64.whl", hash = "sha256:11fe5a4f613759764e79c65cf11ebdf26e33d6dd34336f8a337aa2996d71c841", size = 136284, upload-time = "2026-01-28T18:15:19.912Z" },
+ { url = "https://files.pythonhosted.org/packages/e7/36/5ee6e05c9bd427237b11b3937ad82bb8ad2752d72c6969314590dd0c2f6e/psutil-7.2.2-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:ed0cace939114f62738d808fdcecd4c869222507e266e574799e9c0faa17d486", size = 129090, upload-time = "2026-01-28T18:15:22.168Z" },
+ { url = "https://files.pythonhosted.org/packages/80/c4/f5af4c1ca8c1eeb2e92ccca14ce8effdeec651d5ab6053c589b074eda6e1/psutil-7.2.2-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:1a7b04c10f32cc88ab39cbf606e117fd74721c831c98a27dc04578deb0c16979", size = 129859, upload-time = "2026-01-28T18:15:23.795Z" },
+ { url = "https://files.pythonhosted.org/packages/b5/70/5d8df3b09e25bce090399cf48e452d25c935ab72dad19406c77f4e828045/psutil-7.2.2-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:076a2d2f923fd4821644f5ba89f059523da90dc9014e85f8e45a5774ca5bc6f9", size = 155560, upload-time = "2026-01-28T18:15:25.976Z" },
+ { url = "https://files.pythonhosted.org/packages/63/65/37648c0c158dc222aba51c089eb3bdfa238e621674dc42d48706e639204f/psutil-7.2.2-cp36-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b0726cecd84f9474419d67252add4ac0cd9811b04d61123054b9fb6f57df6e9e", size = 156997, upload-time = "2026-01-28T18:15:27.794Z" },
+ { url = "https://files.pythonhosted.org/packages/8e/13/125093eadae863ce03c6ffdbae9929430d116a246ef69866dad94da3bfbc/psutil-7.2.2-cp36-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:fd04ef36b4a6d599bbdb225dd1d3f51e00105f6d48a28f006da7f9822f2606d8", size = 148972, upload-time = "2026-01-28T18:15:29.342Z" },
+ { url = "https://files.pythonhosted.org/packages/04/78/0acd37ca84ce3ddffaa92ef0f571e073faa6d8ff1f0559ab1272188ea2be/psutil-7.2.2-cp36-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b58fabe35e80b264a4e3bb23e6b96f9e45a3df7fb7eed419ac0e5947c61e47cc", size = 148266, upload-time = "2026-01-28T18:15:31.597Z" },
+ { url = "https://files.pythonhosted.org/packages/b4/90/e2159492b5426be0c1fef7acba807a03511f97c5f86b3caeda6ad92351a7/psutil-7.2.2-cp37-abi3-win_amd64.whl", hash = "sha256:eb7e81434c8d223ec4a219b5fc1c47d0417b12be7ea866e24fb5ad6e84b3d988", size = 137737, upload-time = "2026-01-28T18:15:33.849Z" },
+ { url = "https://files.pythonhosted.org/packages/8c/c7/7bb2e321574b10df20cbde462a94e2b71d05f9bbda251ef27d104668306a/psutil-7.2.2-cp37-abi3-win_arm64.whl", hash = "sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee", size = 134617, upload-time = "2026-01-28T18:15:36.514Z" },
+]
+
+[[package]]
+name = "pygments"
+version = "2.21.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" },
+]
+
+[[package]]
+name = "rich"
+version = "15.0.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "markdown-it-py" },
+ { name = "pygments" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/c0/8f/0722ca900cc807c13a6a0c696dacf35430f72e0ec571c4275d2371fca3e9/rich-15.0.0.tar.gz", hash = "sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36", size = 230680, upload-time = "2026-04-12T08:24:00.75Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/82/3b/64d4899d73f91ba49a8c18a8ff3f0ea8f1c1d75481760df8c68ef5235bf5/rich-15.0.0-py3-none-any.whl", hash = "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", size = 310654, upload-time = "2026-04-12T08:24:02.83Z" },
+]
+
+[[package]]
+name = "textual"
+version = "8.2.8"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "markdown-it-py", extra = ["linkify"] },
+ { name = "mdit-py-plugins" },
+ { name = "platformdirs" },
+ { name = "pygments" },
+ { name = "rich" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/00/21/39a76b01bd5eea82a04baaca7580e105d8c59450df03998345bb2cfb307b/textual-8.2.8.tar.gz", hash = "sha256:3f106a9fbc73e39dd266c9712432087de78a6d644084c7c241d6a25c3169115b", size = 1860502, upload-time = "2026-06-30T06:51:24.495Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/fb/be/35261223d9416a0751cdff1c7b4a6f881387218a12d439fe22fefebc8c04/textual-8.2.8-py3-none-any.whl", hash = "sha256:267375fd402dc8d981457212efa71f0e3365fd17bba144ba9bb3ed7563cb374a", size = 731418, upload-time = "2026-06-30T06:51:26.364Z" },
+]
+
+[[package]]
+name = "typing-extensions"
+version = "4.16.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" },
+]