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 Linux and WSL support
Sameh Khamisca21a97aa61c
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex c7fb119..aae2f0d 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -9,9 +9,11 @@ permissions:jobs:test:- runs-on: windows-latest+ runs-on: ${{ matrix.os }}strategy:+ fail-fast: falsematrix:+ os: [windows-latest, ubuntu-latest]python: ["3.11", "3.13"]steps:- uses: actions/checkout@v4diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 826aad7..5437cdf 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -1,4 +1,4 @@-name: Portable Windows release+name: Portable releaseon:workflow_dispatch:@@ -64,19 +64,66 @@ jobs:dist/*.zip.sha256if-no-files-found: error+ build-linux:+ name: Linux ${{ matrix.arch }}+ # Built on the oldest supported Ubuntu: the frozen binary needs the build machine's glibc (2.35) or newer.+ runs-on: ${{ matrix.runner }}+ strategy:+ fail-fast: false+ matrix:+ include:+ - arch: x64+ runner: ubuntu-22.04+ - arch: arm64+ runner: ubuntu-22.04-arm+ steps:+ - uses: actions/checkout@v4+ - uses: astral-sh/setup-uv@v6+ with:+ version: "0.13.6"+ python-version: "3.13"+ - run: uv sync --locked --group release+ - run: uv run --locked python -m unittest discover -s tests -v+ - name: Build portable tarball+ env:+ BUILD_ARCH: ${{ matrix.arch }}+ run: |+ args=(--arch "$BUILD_ARCH")+ if [ "$GITHUB_REF_TYPE" = "tag" ]; then args+=(--tag "$GITHUB_REF_NAME"); fi+ uv run --locked --group release python tools/build_portable.py "${args[@]}"+ - name: Smoke-test the extracted executable without Python+ run: |+ portable="$RUNNER_TEMP/portable app"+ mkdir -p "$portable"+ tar -xzf dist/*.tar.gz -C "$portable"+ exe="$(find "$portable" -name gputaskman -type f -perm -u+x)"+ cd "$portable"+ env -i HOME="$HOME" PATH=/usr/bin:/bin "$exe" --help+ if find "$portable" -name 'libnvidia-ml*' -o -name 'libcuda*' | grep -q .; then+ echo "NVIDIA driver libraries must not be bundled" >&2+ exit 1+ fi+ - uses: actions/upload-artifact@v4+ with:+ name: linux-${{ matrix.arch }}-portable+ path: |+ dist/*.tar.gz+ dist/*.tar.gz.sha256+ if-no-files-found: error+publish:if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')- needs: build+ needs: [build, build-linux]runs-on: ubuntu-latestpermissions:contents: writesteps:- uses: actions/download-artifact@v4with:- pattern: windows-*-portable+ pattern: "*-portable"merge-multiple: truepath: release-assets- - name: Publish both architectures together+ - name: Publish all platforms togetherenv:GH_TOKEN: ${{ github.token }}GH_REPO: ${{ github.repository }}diff --git a/README.md b/README.mdindex ea05653..5f4cf78 100644--- a/README.md+++ b/README.md@@ -2,8 +2,9 @@**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.+Windows + NVIDIA, with Linux and WSL support (see [Linux and WSL](#linux-and-wsl)). 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?*@@ -86,6 +87,107 @@ If an alternate package index makes `--locked` report a stale lockfile on an unc`uv run --frozen gputaskman` uses the checked-in lockfile without re-resolving it. `--frozen`skips the consistency check, so do not use it after changing dependencies.+## Linux and WSL++Tagged releases include portable Linux builds: `gputaskman-VERSION-linux-x64.tar.gz` and+`gputaskman-VERSION-linux-arm64.tar.gz`. They need glibc 2.35 or newer (Ubuntu 22.04, Debian 12,+or newer) and an NVIDIA driver, and work natively, in containers, and in WSL:++```bash+tar -xzf gputaskman-VERSION-linux-x64.tar.gz+cd gputaskman-VERSION-linux-x64+./gputaskman+```++Or clone and run from source, in a Linux or WSL shell:++```bash+git clone https://github.com/shanselman/gputaskman.git+cd gputaskman+uv run --locked gputaskman+```++What can be measured depends on where it runs, and the UI says which mode it is in.++| | Native Linux | WSL, interop on (default) | WSL, interop off or `--no-host` |+|---|---|---|---|+| Device totals, load, temperature, power, clocks | NVML | NVML | NVML |+| Per-process VRAM | NVML, measured (in a container: owner matched, `*` or `?`) | Matched from the Windows host, marked `*` or `?` | `n/a` |+| Per-process GPU load | NVML (SM, encoder, decoder) | `n/a` for Linux processes | `n/a` |+| Spill / Paged | Not available (blank) | Windows rows only | Not available |+| WSL VM total, Windows apps | — | Windows host counters | — |+| Runtimes, model files, LLM breakdown | `/proc/<pid>/maps`, command line | Same | Same |++**Native Linux** reads per-process memory from NVML's running compute and graphics process lists+and per-process SM, encoder, and decoder load from NVML utilization samples. Linux has no+equivalent of WDDM's shared-memory or commit counters, so Spill and Paged stay blank rather than+showing zero. Only processes you can inspect are listed; other users' processes need `sudo`.++**Containers** (Docker, Kubernetes, rented GPU boxes) need one more step: NVML reports *host*+PIDs, which mean nothing in the container's `/proc`, and the container cannot see the host PID of+its own processes. gputaskman pairs NVML's unresolved PIDs with the container's processes that+have `libcuda.so` mapped (NVML-only tools such as `nvidia-smi` open the same device files but+never load libcuda). Both PID namespaces number processes in creation order, so the pairing is by+order: `*` when the counts match or a process starting while gputaskman runs pins it, `?` when+NVML lists more compute processes than the container has (another container on the same GPU).+Per-process GPU load follows the match. Anything left over is shown as `H:<pid>`,+*outside this container* (for example, the host's display server), and is never looked up locally.++Live check, on a Vast.ai Docker container (Ubuntu 22.04, RTX 3060 Ti, driver 580.82.09): two+PyTorch jobs already running at startup, a third started while watching, and one killed, were all+matched to the right container PIDs with their NVML sizes (1.12, 2.52 and 1.59 GB) and live GPU%.+An Ollama `qwen3:0.6b` runner was detected and named from Ollama's store with `api+mapped+cmdline`+evidence, its weights / KV-cache / compute split shown, and the TUI rendered. Bare-metal Linux+(same PID namespace, no matching needed) is covered by tests but has not been run on hardware.++**WSL** is different, because Windows owns the GPU. Linux cannot see how much VRAM its own+processes use: `nvidia-smi` lists no processes, NVML's per-process samples carry *Windows* PIDs+(never looked up in Linux's `/proc`), and Windows charges all Linux GPU memory to the VM worker+process, `vmwp.exe`. When WSL interop is enabled (`/proc/sys/fs/binfmt_misc/WSLInterop` reads+`enabled`), gputaskman starts one long-lived `powershell.exe` that reads the Windows GPU counters+through the same PDH array API as the Windows backend and streams them back once a second:++- **WSL VM (`vmwp.exe`)** is the exact total of Linux GPU memory, across every distro, WSLg, and+ Docker Desktop.+- **Windows apps** appear as `W:<pid>` rows with their VRAM, spill, paged, and engine load.+ Windows and Linux PIDs are separate namespaces, so the prefix keeps them apart.+- **Linux rows** get a size by matching `vmwp.exe`'s GPU contexts to Linux processes (below).++The first host sample takes about 2.5 s; the TUI shows `starting` until then, and `--once` waits+for it. The host adapter is paired with the NVML device by memory usage, because WSL's adapter+LUIDs differ from the host's. An ambiguous pairing shows `unmatched` instead of guessing. With other+Hyper-V VMs or Windows Sandbox running, the row is labeled `VM worker` because it cannot be tied+to WSL alone. `--no-host` turns the host stream off; without interop you get device-wide numbers+and a list of the Linux processes that hold `/dev/dxg`, with VRAM shown as `n/a`.++### How WSL per-process VRAM is matched++`vmwp.exe` exposes one GPU-memory instance per guest GPU context, all with the same name: sizes+without owners. Measured on WSL2 with driver 610.88, every Linux process that opens `/dev/dxg`+gets exactly one context (an NVML-only process too, at 0 bytes), and Windows lists them **newest+first**, keeping that order as contexts come and go. Contexts from outside this distro (WSLg, other+distros, Docker, services you cannot inspect) are interleaved by their own age.++gputaskman follows the contexts from sample to sample and labels them with evidence:++| Marker | Meaning | Established by |+|---|---|---|+| `*` matched | Windows' exact size; the owner is inferred, and only one explanation fits | A new Linux GPU process and a new context appearing together; elimination; contexts seen while no Linux process in this distro used the GPU (remembered for this WSL boot in `~/.cache/gputaskman/`); this monitor's own 0-byte context being newest at startup |+| `?` guess | Start-order guess for processes that were already running | Newer process ↔ newer context, outside contexts assumed oldest |+| `n/a` | No context could be assigned | For example, a process that has not created its GPU context yet |++A guess is recomputed every refresh and never counts as evidence for itself. An exited process's+context is held aside until it disappears, so it is not handed to a newcomer, and a context that+grows by gigabytes between refreshes (weights uploading) keeps its owner. The matched size also+feeds the LLM weights / KV-cache breakdown. The inspector and `--json` (`vram_inferred_by`) say+which kind of match each row has.++In one live check, a 2 GB and a 5 GB PyTorch allocation were matched to the right PIDs at+2.119 GiB and 4.914 GiB: the allocator's own figure plus about 0.26 GiB of CUDA context.+That is one machine and driver, not a guarantee. A process that started long before it first used+the GPU can break the start-order guess, and processes started in the same refresh are ordered by+guess unless their sizes match.+## What you get- **Device view:** VRAM usage, GPU activity, memory activity, PCIe traffic, temperature, power,@@ -125,6 +227,7 @@ uv run --locked gtm # shorter aliasuv run --locked gputaskman -i 2 # sample every two secondsuv run --locked gputaskman --once # one text snapshotuv run --locked gputaskman --json # one JSON snapshot; implies --once+uv run --locked gputaskman --no-host # WSL: don't read Windows host counters through interopuv run --locked gputaskman --help```@@ -170,7 +273,8 @@ but a runtime DLL or filename alone does not prove which allocation contains whi| Question | Evidence | Confidence / limitation ||---|---|---|| How full and busy is the card? | WDDM adapter counters and NVML | Measured; driver support varies by metric |-| Which process uses GPU memory? | WDDM process counters | Measured accounting, not a resource ownership graph |+| Which process uses GPU memory? | WDDM process counters; NVML on Linux | Measured accounting, not a resource ownership graph |+| Which WSL process uses GPU memory? | Windows host counters for `vmwp.exe`, matched to Linux processes | Exact VM total; per-process owner inferred (`*`) or guessed (`?`) || Which engines are active? | WDDM engine counters | CUDA can appear on the **3D** engine || Which runtime is loaded? | Mapped DLL names | Detection, not proof that every library is doing GPU work || Which model file is present? | Mapped files, CLI flags, GGUF magic/header | A file mapping does not prove GPU placement |@@ -181,7 +285,8 @@ but a runtime DLL or filename alone does not prove which allocation contains whiOn 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.+OpenGL, and CUDA. NVML remains useful for device-level readings. Under WSL, `nvidia-smi` lists+no processes at all; see [Linux and WSL](#linux-and-wsl).### DWM, Spill, and Paged: read these carefully@@ -350,7 +455,13 @@ 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 |+| "supports Windows and Linux/WSL only" | macOS is not supported |+| WSL: `Windows host counters: off (WSL interop is disabled)` | Enable `[interop]` in `/etc/wsl.conf`, then `wsl --shutdown`; or accept device-wide numbers |+| WSL: `starting` for a few seconds | The first Windows counter sample takes about 2.5 s |+| WSL: `unmatched` | No Windows adapter's usage matched the NVML device; multi-GPU WSL is not validated |+| WSL: Linux rows show `?` | Processes were running before gputaskman started; they become `*` with evidence (see the matching table) |+| Linux: a GPU process is missing | Processes owned by other users need `sudo`; Docker and other WSL distros are not visible from this one |+| Linux container: `H:<pid>` rows | GPU processes outside this container's PID namespace (host or other containers); NVML sees them, the container cannot name them || 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 |@@ -364,8 +475,9 @@ uv run --locked python -m unittest discover -s tests -vuv 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.+CI runs hardware-independent checks on Windows and Ubuntu, Python 3.11 and 3.13. Live GPU behavior+still needs real hardware; the CI does not pretend to validate that. The WSL matching tests replay+context sequences measured on a real WSL2 machine.### Building portable releases@@ -378,15 +490,20 @@ uv run --locked --group release python tools\build_portable.py --arch x64# On a native ARM64 interpreter, use --arch arm64 instead.```+The same command on Linux (`tools/build_portable.py`) produces a `.tar.gz`, which keeps the+executable bit. The builder refuses to package NVIDIA driver libraries (`libnvidia-ml.so`,+`libcuda.so`) on either platform; they come from the installed driver.+The builder verifies the interpreter and executable architectures, includes Textual resourcesand dependency licenses, and writes the complete portable ZIP and SHA-256 file to `dist`.It does not bundle Windows/NVIDIA DLLs, inference servers, or models. Keep uv for development;the executable ZIP is for running the monitor without a Python environment.-The **Portable Windows release** GitHub Actions workflow builds on `windows-2022` (x64) and-`windows-11-arm` (ARM64). A manual run produces downloadable workflow artifacts without publishing-a release. A pushed `vVERSION` tag must match `project.version` in `pyproject.toml`; once both builds-pass, the workflow publishes both ZIPs and checksums together with generated release notes.+The **Portable release** GitHub Actions workflow builds on `windows-2022` (x64), `windows-11-arm`+(ARM64), `ubuntu-22.04` (Linux x64), and `ubuntu-22.04-arm` (Linux ARM64). Linux builds use the+oldest supported Ubuntu because the frozen binary needs the build machine's glibc or newer. A manual run produces downloadable workflow artifacts without publishing+a release. A pushed `vVERSION` tag must match `project.version` in `pyproject.toml`; once all builds+pass, the workflow publishes all four archives and checksums together with generated release notes.Build jobs have read-only permissions; only the tag-triggered publish job can write releases.CI checks the extracted executable's `--help` outside the checkout with Python removed from `PATH`;interactive rendering and real GPU snapshots require local hardware testing.@@ -403,6 +520,8 @@ downloads are bundled in this repository.| Module | Responsibility ||---|---|| `pdh.py` / `dxgi.py` | Windows counters and adapter enumeration |+| `linux.py` | Linux backend: NVML adapters and per-process usage, container PID matching, WSL detection, `/dev/dxg` holders |+| `wslhost.py` | WSL: interop check, Windows host counter stream, adapter pairing, context matching || `nvml.py` | NVIDIA device readings || `procinfo.py` | Runtime, mapped-file, and process discovery || `stores.py` | Friendly names from Ollama, LM Studio, and Hugging Face model stores |@@ -416,6 +535,8 @@ downloads are bundled in this repository.- Model identity for non-GGUF runtimes (ONNX Runtime, PyTorch, TensorRT) beyond installed candidates.- Explicit provenance and availability for every counter and estimate.- Reliable multi-GPU matching and per-device model placement.+- Bare-metal Linux validation on hardware; AMD and Intel GPUs on Linux through DRM fdinfo.+- WSL: per-process GPU load for Linux rows, and Ollama's systemd journal as a log source.- Live throughput deltas, LM Studio validation, and per-model context accounting.- Opt-in ETW file-open tracing to name models loaded by read-and-close runtimes (any whisper or ONNXapp), correlated with the process's VRAM jump at load time.diff --git a/pyproject.toml b/pyproject.tomlindex 4a128bb..9ad75c9 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -13,6 +13,7 @@ classifiers = ["Development Status :: 3 - Alpha","Environment :: Console","Operating System :: Microsoft :: Windows",+ "Operating System :: POSIX :: Linux","Programming Language :: Python :: 3","Topic :: System :: Monitoring",]diff --git a/src/gputaskman/app.py b/src/gputaskman/app.pyindex 41dbfe9..034458f 100644--- a/src/gputaskman/app.py+++ b/src/gputaskman/app.py@@ -20,18 +20,22 @@ from textual.worker import get_current_workerfrom .collector import Collector, ProcRow, Snapshotfrom .llm import gbfrom .nvml import NvDevice, format_metric+from .report import WSL_EMPTY, inferred_note, vram_label, wsl_noteKIND_STYLE = {"LLM": "bold magenta", "decision": "bold orchid", "decision?": "orchid","embedding": "plum2", "speech": "light_sky_blue1", "diffusion": "orchid","AI": "medium_purple1", "compute": "orange3", "3D/game": "green3","video": "yellow", "browser": "dodger_blue2", "app": "cyan", "compositor": "grey50",- "kernel": "grey50", "system": "grey50",+ "kernel": "grey50", "system": "grey50", "wsl-vm": "bold spring_green2", "external": "grey50",}SEG_STYLE = {"weights": "magenta", "kv": "dark_orange", "compute": "yellow", "runtime": "grey58", "unknown": "grey42"}SPARK = "▁▂▃▄▅▆▇█"EXPLAIN = {+ "wsl-vm": "The WSL virtual machine as Windows sees it. Windows charges all GPU memory used by Linux processes "+ "in every WSL distro (and WSLg) to vmwp.exe, so this is the exact total. The split across Linux "+ "processes is not exposed.","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; "@@ -73,6 +77,15 @@ Cloud-hosted models are outside this monitor's scope. DLLs identify runtimes, noGGUF kind is missing. It does not confirm the kind, GPU residency, or execution. Installedcandidates remain unproven; engine activity is measured per process, not per model.+**Linux / WSL:** on native Linux, per-process VRAM and SM/encoder/decoder load come from NVML+(no spill or commit counters exist there, so those columns stay blank). Under **WSL**, Windows+charges all Linux GPU memory to the VM (`vmwp.exe`), so VRAM and load are device-wide only; rows+are Linux processes with `/dev/dxg` open and show `n/a` rather than a made-up share. When WSL+interop is enabled, the Windows host's counters are read through `powershell.exe`: **WSL VM**+(`vmwp.exe`) is then the exact total of Linux GPU memory, and Windows apps appear as `W:<pid>`+rows. `--no-host` turns this off. Linux rows get their VRAM by matching the VM's GPU contexts+(newest first) to Linux processes: `*` when only one explanation fits, `?` for a start-order guess.+**Why does nvidia-smi say N/A?** GeForce cards on Windows run in *WDDM* mode: Windows, not theNVIDIA driver, owns video memory, so NVML can't attribute it to processes. The Windows counters can.@@ -133,6 +146,16 @@ class HelpScreen(ModalScreen):HelpScreen > VerticalScroll { width: 140; max-width: 95%; height: 85%; border: thick $accent; background: $surface; padding: 1 2; }"""+ @property+ def selected_pid(self) -> int | None:+ """PID of the selected local (non-host) process."""+ key = self.selected_key+ return int(key) if key and not key.startswith("w") else None++ @selected_pid.setter+ def selected_pid(self, pid: int | None) -> None:+ self.selected_key = None if pid is None else str(pid)+def compose(self) -> ComposeResult:with VerticalScroll():yield Markdown(HELP_MD)@@ -177,12 +200,13 @@ class GpuTaskManager(App):}CHARTS = tuple(CHART_COLORS)- def __init__(self, gpu_index: int = 0, interval: float = 1.0) -> None:+ def __init__(self, gpu_index: int = 0, interval: float = 1.0, host: bool = True) -> None:super().__init__()self.gpu_index = gpu_indexself.interval = interval+ self.host = hostself.snap: Snapshot | None = None- self.selected_pid: int | None = None+ self.selected_key: str | None = None # ProcRow.key: Linux and Windows host PIDs can collideself.sort_idx = 0self.show_all = Falseself.paused = False@@ -197,6 +221,16 @@ class GpuTaskManager(App):self.chart_idx = -1self._auto_selected = False+ @property+ def selected_pid(self) -> int | None:+ """PID of the selected local (non-host) process."""+ key = self.selected_key+ return int(key) if key and not key.startswith("w") else None++ @selected_pid.setter+ def selected_pid(self, pid: int | None) -> None:+ self.selected_key = None if pid is None else str(pid)+def compose(self) -> ComposeResult:with VerticalScroll(id="dashboard"):yield Static("Sampling GPU counters...", id="device")@@ -225,7 +259,7 @@ class GpuTaskManager(App):@work(thread=True, exclusive=True)def poll(self) -> None:worker = get_current_worker()- collector = Collector(self.gpu_index)+ collector = Collector(self.gpu_index, host=self.host)time.sleep(0.5)try:while not worker.is_cancelled:@@ -257,7 +291,7 @@ class GpuTaskManager(App):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.selected_key = llm.keyself._auto_selected = Trueself.query_one("#device", Static).update(self.render_device(snap))self.render_charts()@@ -275,7 +309,8 @@ class GpuTaskManager(App):# 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+ if r.gpu.attributed: # unknown shares stay in "unattributed" instead of showing as 0+ by_kind[r.kind] = by_kind.get(r.kind, 0) + r.gpu.dedicatedattributed = sum(by_kind.values())scale = min(1.0, s.vram_used / attributed) if attributed else 1.0order = sorted(by_kind.items(), key=lambda kv: -kv[1])@@ -298,6 +333,8 @@ class GpuTaskManager(App):legend.append(f" shared(RAM) {gb(s.shared_used)}", style="yellow")if scale < 1.0:legend.append(" [bar normalized; labels are raw]", style="grey62")+ if s.backend == "wsl":+ legend.append("\n " + wsl_note(s), style="grey62")lines = [head, vram, legend]if nv:@@ -383,14 +420,22 @@ class GpuTaskManager(App):def visible_rows(self, s: Snapshot) -> list[ProcRow]:rows = s.procsif 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+ rows = [r for r in rows if not r.gpu.attributed or r.gpu.dedicated >= 32 << 20 or r.gpu.gpu_pct >= 1 or r.gpu.shared >= 64 << 20or r.gpu.paged_out >= 128 << 20 or r.llm]- return sorted(rows, key=self.SORTS[self.sort_idx][1])+ rows = sorted(rows, key=self.SORTS[self.sort_idx][1])+ vm = next((i for i, r in enumerate(rows) if r.kind == "wsl-vm"), None)+ if vm is not None and self.SORTS[self.sort_idx][0] == "VRAM":+ # Linux rows have no VRAM of their own here; keep them under the WSL VM row whose total they share.+ linux = [r for r in rows if not r.gpu.attributed and not r.host]+ rest = [r for r in rows if r not in linux]+ vm = rest.index(rows[vm])+ rows = rest[:vm + 1] + linux + rest[vm + 1:]+ return rowsdef render_table(self, s: Snapshot) -> None:t = self.query_one("#procs", DataTable)rows = self.visible_rows(s)- keep = self.selected_pid+ keep = self.selected_keyt.clear()def pct(v: float) -> Text:@@ -402,41 +447,54 @@ class GpuTaskManager(App):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.pid_label, justify="right", style="grey62" if r.host else ""),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),+ Text(vram_label(r.gpu), justify="right", style="bold" if r.gpu.attributed else "grey62"), spill, paged,+ pct(r.gpu.gpu_pct) if r.gpu.attributed else Text("n/a", justify="right", style="grey62"),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),+ key=r.key,)if keep is not None:try:- t.move_cursor(row=t.get_row_index(str(keep)), animate=False, scroll=False)+ t.move_cursor(row=t.get_row_index(keep), animate=False, scroll=False)except Exception:passt.border_subtitle = f"sort: {self.SORTS[self.sort_idx][0]} · {'all' if self.show_all else 'top'} processes"+ if s.backend == "wsl" and not any(not r.host for r in s.procs):+ t.border_subtitle = WSL_EMPTYdef 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+ r = next((x for x in s.procs if x.key == self.selected_key), None) if s else Noneif 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}"+ where = {"windows": "Windows PID ", "outside": "host PID "}.get(r.origin, "") if r.host else ""+ panel.border_title = f"{r.name} ({where}{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")+ wddm = s.backend == "wddm" or r.host # spill and commit counters only exist in WDDM+ engines = " ".join(f"{k} {v:.0f}%" for k, v in e.items() if v >= 0.5) or "idle"+ hdr = Text.assemble(("VRAM ", "bold"), (vram_label(r.gpu), "bold"), " spill(RAM) ",+ (gb(r.gpu.shared) if wddm else "n/a", "bold red" if r.gpu.shared > 256 << 20 else ""),+ " paged(est) ", gb(r.gpu.paged_out) if wddm else "n/a",+ " engines ", engines if r.gpu.attributed else "n/a")if r.detail.runtimes:hdr.append(" runtime ", style="grey62")hdr.append(" ".join(r.detail.runtimes), style="cyan")out.append(hdr)+ if not r.host and r.gpu.attributed and r.gpu.inferred_by:+ out.append(Text(inferred_note(r.gpu), style="grey62"))+ if not r.host and not r.gpu.attributed:+ if r.gpu.inferred is not None:+ out.append(Text(inferred_note(r.gpu), style="grey62"))+ elif s.wsl_split:+ out.append(Text(f"No per-process VRAM: {s.wsl_split}.", style="grey62"))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.",@@ -517,7 +575,7 @@ class GpuTaskManager(App):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.selected_key = str(event.row_key.value)self.render_inspector()def action_cycle_sort(self) -> None:diff --git a/src/gputaskman/cli.py b/src/gputaskman/cli.pyindex 59df309..737de75 100644--- a/src/gputaskman/cli.py+++ b/src/gputaskman/cli.py@@ -13,6 +13,8 @@ def main() -> None: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("--no-host", action="store_true",+ help="WSL: don't read Windows host GPU counters through interop (WSL VM total, Windows apps)")ap.add_argument("-i", "--interval", type=float, default=1.0, help="refresh seconds (default 1)")args = ap.parse_args()if args.gpu < 0:@@ -20,8 +22,8 @@ def main() -> None:if not math.isfinite(args.interval) or args.interval <= 0:ap.error("--interval must be a finite number greater than zero")- if sys.platform != "win32":- sys.exit("gputaskman currently supports Windows (WDDM) only.")+ if sys.platform != "win32" and not sys.platform.startswith("linux"):+ sys.exit("gputaskman supports Windows (WDDM) and Linux/WSL (NVML) only.")if args.gpu:from .collector import enumerate_adapters, select_adapter@@ -36,10 +38,12 @@ def main() -> None:from .report import dumptry:- c = Collector(args.gpu, scan_budget=None) # one-shot: identify everything in this sample+ c = Collector(args.gpu, scan_budget=None, host=not args.no_host) # one-shot: identify everything nowexcept ValueError as error:ap.error(str(error))try:+ if c.host is not None:+ c.host.wait(15.0) # WSL: the first Windows counter sample takes several secondstime.sleep(1.0) # engine utilization is a rate; needs two samplesprint(dump(c.sample(), args.json))finally:@@ -48,4 +52,4 @@ def main() -> None:from .app import GpuTaskManager- GpuTaskManager(gpu_index=args.gpu, interval=args.interval).run()+ GpuTaskManager(gpu_index=args.gpu, interval=args.interval, host=not args.no_host).run()diff --git a/src/gputaskman/collector.py b/src/gputaskman/collector.pyindex 216b4ae..7b84a95 100644--- a/src/gputaskman/collector.py+++ b/src/gputaskman/collector.py@@ -3,18 +3,32 @@from __future__ import annotationsimport os+import sysimport timefrom dataclasses import dataclass, fieldimport psutil-from .dxgi import VENDOR_NVIDIA, Adapter, enumerate_adapters+from .dxgi import VENDOR_NVIDIA, Adapterfrom .handy import HandyEvidence, inspect_handyfrom .llm import LlmView, ServerProber, build_view, gb, ollama_log_pathfrom .nvml import Nvml, NvDevice-from .pdh import GpuCounters, ProcGpu+from .pdh import ProcGpufrom .procinfo import AI_KINDS, ProcDetail, ProcInspector, classify+if sys.platform == "win32":+ from .dxgi import enumerate_adapters+ from .pdh import GpuCounters++ BACKEND = "wddm"+else:+ from .linux import LinuxCounters as GpuCounters+ from .linux import enumerate_adapters, is_wsl++ BACKEND = "wsl" if is_wsl() else "nvml"++from .wslhost import ContextTracker, HostStream, interop_enabled, match_adapter+MiB = 1 << 20@@ -27,6 +41,17 @@ class ProcRow:detail: ProcDetailllm: LlmView | None = Nonehandy: HandyEvidence | None = None+ host: bool = False # pid is from another PID namespace, never a local one (see origin)+ origin: str = "" # with host: "windows" (a Windows process seen from WSL) | "outside" (outside this container)++ @property+ def key(self) -> str:+ """Unique row id: PIDs from other namespaces and local PIDs can collide."""+ return f"{self.origin[0]}{self.pid}" if self.host else str(self.pid)++ @property+ def pid_label(self) -> str:+ return f"{'W' if self.origin == 'windows' else 'H'}:{self.pid}" if self.host else str(self.pid)@propertydef runtime(self) -> str:@@ -57,6 +82,8 @@ class ProcRow:(f" ({m.kind_label})" if m.kind_hint else "") for m in self.detail.candidates[:2])return {"compositor": "desktop back buffers + composed frames",+ "wsl-vm": "all Linux GPU memory (every WSL distro + WSLg)",+ "external": "a process in another PID namespace (host or another container)","kernel": "driver/kernel allocations","browser": "page textures, video, canvas/WebGL","video": "video frames (decode/encode)",@@ -73,15 +100,27 @@ class Snapshot:driver: strcuda: strvram_total: int- vram_used: int # WDDM adapter-wide dedicated usage (ground truth)+ vram_used: int # adapter-wide dedicated usage (WDDM counters, or NVML on Linux): the ground truthshared_used: intprocs: list[ProcRow] = field(default_factory=list)+ backend: str = "wddm" # wddm (Windows) | nvml (native Linux) | wsl (device-wide only)+ host_status: str = "" # WSL only: Windows host counters via interop -- ok | starting | off (...) | ...+ wsl_split: str = "" # WSL only: why Linux rows have no (inferred) VRAM, when they don't++ @property+ def host_data(self) -> bool:+ return self.host_status.startswith("ok")@propertydef attributed(self) -> int:return int(sum(p.gpu.dedicated for p in self.procs))+def _is_live(g: ProcGpu) -> bool:+ return (not g.attributed or g.dedicated >= MiB or g.gpu_pct >= 0.5 or g.shared >= 16 * MiB+ or g.paged_out >= 16 * MiB)++def select_adapter(adapters: list[Adapter], gpu_index: int) -> Adapter | None:hardware = [a for a in adapters if not a.software]choices = [a for a in hardware if a.vendor_id == VENDOR_NVIDIA] or hardware@@ -110,7 +149,7 @@ class Collector:DEEP_TOP_N = 25 # memory-map candidates: the top N VRAM users plus anything busySCAN_BUDGET = 0.15 # seconds of memory-map scanning per sample; leftovers wait for the next sample- def __init__(self, gpu_index: int = 0, scan_budget: float | None = SCAN_BUDGET) -> None:+ def __init__(self, gpu_index: int = 0, scan_budget: float | None = SCAN_BUDGET, host: bool = True) -> None:self.adapters = [a for a in enumerate_adapters() if not a.software]self.adapter = select_adapter(self.adapters, gpu_index)self.counters = GpuCounters()@@ -119,6 +158,20 @@ class Collector:self.prober = ServerProber()self.scan_budget = scan_budget # None = scan every candidate now (one-shot output)self.gpu_index = gpu_index+ # WSL: Linux can't see WSL's own VRAM, but the Windows host can. Ask it when interop is enabled.+ self.host: HostStream | None = None+ self.host_status = ""+ if BACKEND == "wsl":+ if not host:+ self.host_status = "off (--no-host)"+ elif not interop_enabled():+ self.host_status = "off (WSL interop is disabled)"+ else:+ self.host = HostStream()+ self._host_luid: int | None = None # host adapter for this GPU, matched once and kept+ self.tracker = ContextTracker(self_pid=os.getpid()) if self.host is not None else None+ self._own_start = time.time() # our NVML context is created now, not when the process started+ self._host_restarted = time.time()def _parent_ports(self, pid: int, depth: int = 2) -> list[int]:d = self.inspector.get(pid)@@ -148,11 +201,11 @@ class Collector: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,+ shared_used=int(a.shared) if a else 0, backend=BACKEND,)- 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]+ snap.host_status = self.host_status+ live = [(pid, g) for pid, g in procs.items() if _is_live(g)]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}deadline = None if self.scan_budget is None else time.perf_counter() + self.scan_budget@@ -166,24 +219,94 @@ class Collector: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 in AI_KINDS and ("\\ollama\\" in d.exe.lower() or+ exe = d.exe.lower()+ if row.kind in AI_KINDS and ("\\ollama\\" in exe or "/ollama/" in exe or(d.name.lower().startswith("ollama") and "runner" in d.cmdline)):ollama_runners.append(row)+ for pid, g in getattr(self.counters, "outside", {}).get(luid, {}).items():+ # A container sees the host's PIDs from NVML; unmatched ones are other containers or the host.+ snap.procs.append(ProcRow(pid, "(outside this container)", "external", g,+ ProcDetail(pid, "(outside this container)"), host=True, origin="outside"))+ if self.host is not None: # before LLM views, so an inferred VRAM total feeds the breakdown+ self._add_host_rows(snap)for row in snap.procs:- if os.path.basename(row.detail.exe).lower() == "handy.exe":+ if row.host:+ continue+ if os.path.basename(row.detail.exe).lower() in ("handy.exe", "handy"):row.handy = inspect_handy(row.detail.create_time)if row.detail.is_diffusion or row.kind not in AI_KINDS or not (row.detail.models or row.kind == "LLM"):continueown = self.prober.get(row.detail.ports)host = self.prober.get(self._parent_ports(row.pid)) # Ollama / LM Studio front-end processlog = 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)+ inferred = row.gpu.inferred+ row.llm = build_view(row.detail, row.gpu.dedicated if inferred is None else inferred, row.gpu.shared,+ own or host, log, host=host if own else None,+ attributed=row.gpu.attributed or inferred is not None)self.inspector.prune(set(procs))return snap+ def _add_host_rows(self, snap: Snapshot) -> None:+ """Windows processes on this GPU, plus the WSL VM itself (vmwp.exe: the exact total of Linux VRAM)."""+ if self.host.ended and time.time() - self._host_restarted > 30:+ self.host.close() # PowerShell exited (e.g. killed, or the host was busy): try again+ self.host = HostStream()+ self._host_restarted = time.time()+ hs = self.host.latest()+ if hs is None:+ snap.host_status = "starting" if self.host.status in ("starting", "ok") else self.host.status+ return+ # Match the host adapter once: NVML is read now while the host sample can be a second old, so+ # re-matching every refresh fails whenever memory moves fast (a model loading) and the rows flicker.+ luid = self._host_luid if self._host_luid in hs.adapters else match_adapter(hs, snap.vram_used)+ if luid is None:+ # Memory can swing by GBs between the two readings while a workload loads: retry for a while.+ early = time.time() - self._host_restarted < 20+ snap.host_status = "starting" if early else "unmatched (no Windows adapter matches this GPU's usage)"+ return+ self._host_luid = luid+ age = time.time() - hs.taken+ snap.host_status = "ok" if age < 3 else f"ok (last Windows sample {age:.0f}s old)"+ a = hs.adapters.get(luid)+ if a is not None:+ snap.shared_used = int(a.shared)+ procs = hs.procs.get(luid, {})+ vm_workers = [pid for pid in procs if hs.names.get(pid, "").lower() == "vmwp"]+ host_rows: list[ProcRow] = []+ for pid, g in procs.items():+ if not _is_live(g):+ continue+ raw = hs.names.get(pid, "?")+ if raw.lower() == "vmwp":+ # One VM worker is WSL's; several could include Hyper-V VMs or Windows Sandbox.+ name = "WSL VM (vmwp.exe)" if len(vm_workers) == 1 else "VM worker (vmwp.exe)"+ kind = "wsl-vm"+ else:+ name = raw if raw in ("System", "Idle", "?") or raw.lower().endswith(".exe") else f"{raw}.exe"+ kind = "kernel" if pid == 4 else classify(ProcDetail(pid, name), g.engines)+ host_rows.append(ProcRow(pid, name, kind, g, ProcDetail(pid, name), host=True, origin="windows"))+ # Largest first; Linux rows sit right under the WSL VM row, whose total they share.+ host_rows.sort(key=lambda r: -r.gpu.dedicated)+ at = next((i + 1 for i, r in enumerate(host_rows) if r.kind == "wsl-vm"), 0)+ if len(vm_workers) == 1 and self.tracker is not None:+ self._attribute(snap, luid, hs.contexts.get(luid, {}).get(vm_workers[0], []))+ snap.procs = host_rows[:at] + snap.procs + host_rows[at:]++ def _attribute(self, snap: Snapshot, luid: int, contexts: list[float]) -> None:+ linux = [r for r in snap.procs if not r.host and not r.gpu.attributed]+ # This monitor holds a (0-byte) context too, through NVML.+ holders = [(r.pid, r.detail.create_time) for r in linux] + [(os.getpid(), self._own_start)]+ guesses, reason = self.tracker.update(luid, contexts, holders)+ snap.wsl_split = reason+ for r in linux:+ g = guesses.get(r.pid)+ if g is not None:+ r.gpu.inferred, r.gpu.inferred_by = g.bytes, g.confidence+def close(self) -> None:self.counters.close()self.nvml.close()+ if self.host is not None:+ self.host.close()diff --git a/src/gputaskman/handy.py b/src/gputaskman/handy.pyindex 14380ea..4cc4036 100644--- a/src/gputaskman/handy.py+++ b/src/gputaskman/handy.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport jsonimport osimport re+import sysfrom dataclasses import dataclassfrom datetime import datetime, timezone@@ -118,8 +119,14 @@ def inspect_handy(localappdata: str | None = None,) -> HandyEvidence | None:"""Read Handy's selected model and latest model event after this process started."""- appdata = os.environ.get("APPDATA", "") if appdata is None else appdata- localappdata = os.environ.get("LOCALAPPDATA", "") if localappdata is None else localappdata+ if sys.platform == "win32":+ default_data = os.environ.get("APPDATA", "")+ default_local = os.environ.get("LOCALAPPDATA", "")+ else: # Tauri keeps both the settings store and logs/ under the XDG data dir on Linux+ default_data = default_local = os.environ.get("XDG_DATA_HOME") or os.path.join(+ os.path.expanduser("~"), ".local", "share")+ appdata = default_data if appdata is None else appdata+ localappdata = default_local if localappdata is None else localappdatasettings_path = os.path.join(appdata, "com.pais.handy", "settings_store.json")log_path = os.path.join(localappdata, "com.pais.handy", "logs", "handy.log")selected = _selected_model(settings_path)diff --git a/src/gputaskman/linux.py b/src/gputaskman/linux.pynew file mode 100644index 0000000..56dcf52--- /dev/null+++ b/src/gputaskman/linux.py@@ -0,0 +1,302 @@+"""Linux GPU backend: adapters and per-process usage from NVML, with an honest WSL mode.++Native Linux: NVML attributes VRAM (running compute/graphics processes) and SM/encoder/decoder load+(process utilization samples) to Linux PIDs, which plays the role the WDDM counters play on Windows.+There is no Linux equivalent of WDDM's shared-memory spill or commit counters, so those stay empty.++WSL: the GPU is paravirtualized through /dev/dxg and the Windows host charges every Linux process's+VRAM to the VM worker (vmwp.exe). NVML's process lists come back empty, and its utilization samples+carry *Windows host* PIDs, which must never be looked up in Linux's /proc. In WSL we therefore only+report device-wide numbers, plus the Linux processes that hold /dev/dxg open, marked unattributed.+"""++from __future__ import annotations++import os+import re+from collections import defaultdict+from functools import lru_cache++from .dxgi import VENDOR_NVIDIA, Adapter+from .pdh import AdapterGpu, ProcGpu++try:+ import pynvml as N+except ImportError: # pragma: no cover+ N = None+++@lru_cache(maxsize=1)+def is_wsl() -> bool:+ if os.path.exists("/dev/dxg"):+ return True+ try:+ with open("/proc/sys/kernel/osrelease", encoding="ascii") as f:+ return "microsoft" in f.read().lower()+ except OSError:+ return False+++def pci_key(bus_id: str) -> int:+ """'00000000:01:00.0' -> stable integer adapter key (the Linux stand-in for a WDDM LUID)."""+ return int(re.sub(r"[^0-9a-f]", "", bus_id.lower()) or "0", 16)+++def _bus_id(handle) -> str:+ pci = N.nvmlDeviceGetPciInfo(handle)+ bus = pci.busId+ return bus.decode() if isinstance(bus, bytes) else str(bus)+++def _nvml_devices() -> list[tuple[int, object]]:+ out = []+ for i in range(N.nvmlDeviceGetCount()):+ h = N.nvmlDeviceGetHandleByIndex(i)+ try:+ key = pci_key(_bus_id(h))+ except Exception:+ key = i + 1+ out.append((key, h))+ return out+++def enumerate_adapters() -> list[Adapter]:+ if N is None:+ return []+ try:+ N.nvmlInit()+ except Exception:+ return []+ out = []+ try:+ for key, h in _nvml_devices():+ try:+ name = N.nvmlDeviceGetName(h)+ name = name.decode() if isinstance(name, bytes) else name+ total = N.nvmlDeviceGetMemoryInfo(h).total+ except Exception:+ continue+ out.append(Adapter(luid=key, name=name, vendor_id=VENDOR_NVIDIA, dedicated_vram=total,+ shared_system=0, software=False))+ finally:+ try:+ N.nvmlShutdown()+ except Exception:+ pass+ return out+++def dxg_pids(exclude: set[int] | None = None) -> set[int]:+ """Linux PIDs with /dev/dxg open: the processes that use the GPU under WSL. Other users' processes+ are only visible when running as root."""+ exclude = exclude or set()+ pids = set()+ for entry in os.scandir("/proc"):+ if not entry.name.isdigit() or int(entry.name) in exclude:+ continue+ try:+ fds = os.scandir(f"/proc/{entry.name}/fd")+ except OSError:+ continue+ with fds:+ for fd in fds:+ try:+ if os.readlink(fd.path) == "/dev/dxg":+ pids.add(int(entry.name))+ break+ except OSError:+ continue+ return pids+++def nvidia_holders() -> set[int]:+ """Local PIDs with an NVIDIA device file open (/dev/nvidia0, nvidiactl, nvidia-uvm, ...)."""+ pids = set()+ for entry in os.scandir("/proc"):+ if not entry.name.isdigit():+ continue+ try:+ fds = os.scandir(f"/proc/{entry.name}/fd")+ except OSError:+ continue+ with fds:+ for fd in fds:+ try:+ if os.readlink(fd.path).startswith("/dev/nvidia"):+ pids.add(int(entry.name))+ break+ except OSError:+ continue+ return pids+++def has_cuda(pid: int) -> bool:+ """libcuda.so mapped: the process has (or is creating) a CUDA context. NVML-only tools (nvidia-smi,+ nvtop, this monitor) open the same device files but never load libcuda, so they don't count."""+ try:+ with open(f"/proc/{pid}/maps", encoding="utf-8", errors="replace") as f:+ return any("/libcuda.so" in line for line in f)+ except OSError:+ return False+++class PidMatcher:+ """Containers: NVML reports *host* PIDs, which mean nothing in the container's /proc. Both PID+ namespaces number processes in creation order, so the container's CUDA processes are matched to+ NVML's unresolved PIDs by order. A match is sure ("consistent") when a new NVML PID and a new local+ CUDA process appear together (kept while both live) or the counts are equal; otherwise newest is+ paired with newest as an "order" guess, and leftover NVML PIDs belong to processes outside+ this container (other containers, the host's display server)."""++ def __init__(self) -> None:+ self.pairs: dict[int, int] = {} # host pid -> local pid, from start events+ self.prev_host: set[int] | None = None+ self.prev_local: set[int] = set()++ def update(self, host: list[int], local: list[int]) -> tuple[dict[int, tuple[int, str]], list[int]]:+ """Returns ({host pid: (local pid, confidence)}, host pids left outside)."""+ first = self.prev_host is None+ hs, ls = set(host), set(local)+ self.pairs = {h: l for h, l in self.pairs.items() if h in hs and l in ls}+ if not first:+ new_h = [h for h in host if h not in self.prev_host and h not in self.pairs]+ new_l = [p for p in local if p not in self.prev_local and p not in self.pairs.values()]+ if len(new_h) == len(new_l) == 1:+ self.pairs[new_h[0]] = new_l[0]+ self.prev_host, self.prev_local = hs, ls+ out = {h: (l, "consistent") for h, l in self.pairs.items()}+ rest_h = sorted((h for h in host if h not in self.pairs), reverse=True) # newest first+ rest_l = sorted((p for p in local if p not in self.pairs.values()), reverse=True)+ sure = len(rest_h) == len(rest_l)+ for h, l in zip(rest_h, rest_l):+ out[h] = (l, "consistent" if sure else "order")+ return out, rest_h[len(rest_l):]+++def _value(v) -> int | None:+ # NVML reports NVML_VALUE_NOT_AVAILABLE (unsigned -1) or None when per-process memory is hidden.+ if v is None or v >= (1 << 63):+ return None+ return int(v)+++class LinuxCounters:+ """Same interface as pdh.GpuCounters: sample() -> ({adapter key: {pid: ProcGpu}}, {adapter key: AdapterGpu})."""++ def __init__(self) -> None:+ self.wsl = is_wsl()+ self.ok = False+ self._devices: list[tuple[int, object]] = []+ self._last_ts: dict[int, int] = {}+ self._matcher = PidMatcher()+ # {adapter key: {host pid: ProcGpu}}: NVML processes in another PID namespace that couldn't be+ # matched to a local process. Their PIDs must never be looked up in this /proc.+ self.outside: dict[int, dict[int, ProcGpu]] = {}+ if N is None:+ return+ try:+ N.nvmlInit()+ except Exception:+ return+ self.ok = True+ try:+ self._devices = _nvml_devices()+ except Exception:+ self._devices = []++ @staticmethod+ def _processes(fn, h) -> list:+ try:+ return list(fn(h))+ except Exception:+ return []++ def _utilization(self, key: int, h) -> dict[int, object]:+ """Latest utilization sample per PID since the previous call."""+ try:+ samples = N.nvmlDeviceGetProcessUtilization(h, self._last_ts.get(key, 0))+ except Exception: # NVML_ERROR_NOT_FOUND when nothing ran since the last sample+ return {}+ latest: dict[int, object] = {}+ for s in samples:+ if s.pid not in latest or s.timeStamp > latest[s.pid].timeStamp:+ latest[s.pid] = s+ if latest:+ self._last_ts[key] = max(s.timeStamp for s in latest.values())+ return latest++ def sample(self) -> tuple[dict[int, dict[int, ProcGpu]], dict[int, AdapterGpu]]:+ procs: dict[int, dict[int, ProcGpu]] = defaultdict(dict)+ adapters: dict[int, AdapterGpu] = defaultdict(AdapterGpu)+ self._compute_pids: set[int] = set()+ for key, h in self._devices:+ try:+ adapters[key].dedicated = float(N.nvmlDeviceGetMemoryInfo(h).used)+ except Exception:+ pass+ if self.wsl:+ continue # NVML per-process data is empty or keyed by Windows host PIDs here+ compute = self._processes(N.nvmlDeviceGetComputeRunningProcesses, h)+ graphics = self._processes(N.nvmlDeviceGetGraphicsRunningProcesses, h)+ compute_pids = {p.pid for p in compute}+ self._compute_pids |= compute_pids+ per = procs[key]+ for p in compute + graphics:+ g = per.setdefault(p.pid, ProcGpu())+ used = _value(getattr(p, "usedGpuMemory", None))+ if used is None:+ g.attributed = False+ else:+ # A process in both lists reports the same allocation twice; don't double count.+ g.dedicated = max(g.dedicated, float(used))+ for pid, s in self._utilization(key, h).items():+ if pid not in per:+ continue # utilization for a process NVML no longer lists (or another PID namespace)+ g = per[pid]+ g.engines["compute" if pid in compute_pids else "3d"] += float(s.smUtil)+ g.engines["encode"] += float(s.encUtil)+ g.engines["decode"] += float(s.decUtil)+ if not self.wsl:+ self._resolve_namespaces(procs)+ if self.wsl and self._devices:+ users = dxg_pids(exclude={os.getpid()})+ # WSL does not say which GPU a process uses; with one GPU (the common case) that's unambiguous.+ for key, _ in self._devices:+ for pid in users:+ procs[key][pid] = ProcGpu(attributed=False)+ return procs, adapters++ def _resolve_namespaces(self, procs: dict[int, dict[int, ProcGpu]]) -> None:+ """Re-key NVML's PIDs to local ones. Same namespace (bare metal, or a container sharing the host+ PID namespace): the PID exists here and holds an NVIDIA device. Otherwise (a container):+ match by creation order with PidMatcher."""+ self.outside = {}+ nv_pids = {pid for per in procs.values() for pid in per}+ if not nv_pids:+ self._matcher.update([], [])+ return+ holders = nvidia_holders()+ unresolved = sorted(pid for pid in nv_pids if pid not in holders)+ if not unresolved:+ return+ me = os.getpid()+ local = sorted(p for p in holders - nv_pids if p != me and has_cuda(p))+ compute = [pid for pid in unresolved if pid in self._compute_pids] # CUDA, so local libcuda users+ matched, _ = self._matcher.update(compute, local)+ for key, per in procs.items():+ for pid in [p for p in per if p in unresolved]:+ g = per.pop(pid)+ if pid in matched:+ lpid, confidence = matched[pid]+ g.inferred_by = confidence+ per[lpid] = g+ else:+ self.outside.setdefault(key, {})[pid] = g++ def close(self) -> None:+ if self.ok:+ try:+ N.nvmlShutdown()+ except Exception:+ pass+ self.ok = Falsediff --git a/src/gputaskman/llm.py b/src/gputaskman/llm.pyindex 7918163..3b9a520 100644--- a/src/gputaskman/llm.py+++ b/src/gputaskman/llm.py@@ -14,6 +14,7 @@ import dataclassesimport jsonimport osimport re+import sysimport timeimport urllib.requestfrom dataclasses import dataclass, field@@ -107,7 +108,10 @@ def parse_load_log(path: str, not_before: float = 0.0) -> dict[str, dict[str, indef ollama_log_path() -> str:- return os.path.join(os.environ.get("LOCALAPPDATA", ""), "Ollama", "server.log")+ if sys.platform == "win32":+ return os.path.join(os.environ.get("LOCALAPPDATA", ""), "Ollama", "server.log")+ # Linux service installs log to the systemd journal; a user-run `ollama serve` may write here.+ return os.path.join(os.path.expanduser("~"), ".ollama", "logs", "server.log")# ---------------------------------------------------------------- local servers@@ -330,7 +334,7 @@ def _merge_api(files: list[MappedModel], server: ServerInfo | None, host: Serverdef build_view(d: ProcDetail, vram: float, shared: float, server: ServerInfo | None,- log_path: str | None = None, host: ServerInfo | None = None) -> LlmView:+ log_path: str | None = None, host: ServerInfo | None = None, attributed: bool = True) -> LlmView:v = LlmView(flags=parse_flags(d.cmdline), server=server, host=host)files = [dataclasses.replace(m, sources=list(m.sources)) for m in d.models] # cached details stay untouchedmatched = _merge_api(files, server, host)@@ -363,7 +367,7 @@ def build_view(d: ProcDetail, vram: float, shared: float, server: ServerInfo | Nprimaries = [g for g in v.models if g.kind not in _SIDE_KINDS]no_kv = bool(primaries) and all(not g.causal for g in primaries)- total = int(vram)+ total = int(vram) if attributed else None # None: the OS can't say how much VRAM this process holdsif v.log:gpu = {dev: kinds for dev, kinds in v.log.items() if is_gpu_device(dev)}acc = 0@@ -376,22 +380,27 @@ def build_view(d: ProcDetail, vram: float, shared: float, server: ServerInfo | Ncpu_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:+ if total is not None and total > acc:v.segments.append(Segment("runtime and other overhead", total - acc, "runtime"))else:ngl = v.flags.get("ngl") if len(v.models) == 1 else Noneweights = 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:+ if total is not None and 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 = totalif weights:label = "weights" if len(v.models) == 1 else f"weights ({len(v.models)} files)"v.segments.append(Segment(label, weights, "weights"))- rest = total - weightskv = v.kv_per_token * v.n_ctx if (v.kv_per_token and v.n_ctx) else 0- if kv and kv <= rest:+ rest = total - weights if total is not None else None+ if rest is None:+ if kv:+ v.segments.append(Segment(f"KV cache ({v.n_ctx:,} ctx, {v.kv_type}) est.", kv, "kv"))+ v.notes.append("This process's VRAM total is unknown (WSL charges it to the VM on the Windows host); "+ "segments are estimates from the model file and launch flags.")+ elif kv and kv <= rest:swa = main.sliding_window if main else Nonev.segments.append(Segment(f"KV cache ({v.n_ctx:,} ctx, {v.kv_type}) est.{' max' if swa else ''}", kv, "kv"))if swa:@@ -405,7 +414,7 @@ def build_view(d: ProcDetail, vram: float, shared: float, server: ServerInfo | Nelif rest > 0:v.segments.append(Segment("KV cache + compute + runtime", rest, "unknown"))- if not v.models and not v.log and total > 0:+ if not v.models and not v.log and total:v.notes.append("No GGUF mapped. Model may be loaded with --no-mmap or via another format.")if no_kv:kinds = ", ".join(sorted({f"{g.decision_type} {g.kind}" if g.decision_type else g.kind for g in primaries}))@@ -416,7 +425,7 @@ def build_view(d: ProcDetail, vram: float, shared: float, server: ServerInfo | Nif 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:+ if total is not None and 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"):mine = [om for om in front.models if om in matched]diff --git a/src/gputaskman/pdh.py b/src/gputaskman/pdh.pyindex 3f16e41..1f9635f 100644--- a/src/gputaskman/pdh.py+++ b/src/gputaskman/pdh.py@@ -13,8 +13,6 @@ from collections import defaultdictfrom ctypes import wintypesfrom dataclasses import dataclass, field-_pdh = ctypes.WinDLL("pdh")-PDH_FMT_DOUBLE = 0x00000200PDH_FMT_NOCAP100 = 0x00008000PDH_MORE_DATA = 0x800007D2@@ -37,15 +35,26 @@ 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+_pdh = None+++def _load_pdh():+ """pdh.dll is loaded on first use so this module imports cleanly on Linux."""+ global _pdh+ if _pdh is None:+ lib = ctypes.WinDLL("pdh")+ lib.PdhOpenQueryW.argtypes = [wintypes.LPCWSTR, ctypes.c_size_t, ctypes.POINTER(wintypes.HANDLE)]+ lib.PdhAddEnglishCounterW.argtypes = [wintypes.HANDLE, wintypes.LPCWSTR, ctypes.c_size_t, ctypes.POINTER(wintypes.HANDLE)]+ lib.PdhCollectQueryData.argtypes = [wintypes.HANDLE]+ lib.PdhGetFormattedCounterArrayW.argtypes = [+ wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), ctypes.POINTER(wintypes.DWORD), ctypes.c_void_p,+ ]+ lib.PdhCloseQuery.argtypes = [wintypes.HANDLE]+ for _fn in ("PdhOpenQueryW", "PdhAddEnglishCounterW", "PdhCollectQueryData", "PdhGetFormattedCounterArrayW", "PdhCloseQuery"):+ getattr(lib, _fn).restype = wintypes.DWORD+ _pdh = lib+ return _pdh+_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+)")@@ -63,6 +72,13 @@ class ProcGpu: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 %+ # False when the OS knows this process uses the GPU but cannot say how much (WSL: the Windows host+ # charges every Linux process's VRAM to the VM). Numbers are then unknown, not zero.+ attributed: bool = True+ # WSL: VRAM matched from the VM's GPU contexts (see wslhost.ContextTracker). An exact counter value whose+ # owner is inferred; kept apart from `dedicated` so it isn't counted twice next to the WSL VM row.+ inferred: float | None = None+ inferred_by: str = "" # "consistent" (only one explanation fits) | "order" (start-order guess)@propertydef paged_out(self) -> float:@@ -96,6 +112,7 @@ class GpuCounters:}def __init__(self) -> None:+ _load_pdh()self._query = wintypes.HANDLE()self._check(_pdh.PdhOpenQueryW(None, 0, ctypes.byref(self._query)), "PdhOpenQuery")self._handles: dict[str, wintypes.HANDLE] = {}diff --git a/src/gputaskman/procinfo.py b/src/gputaskman/procinfo.pyindex 6ef0601..7f879c8 100644--- a/src/gputaskman/procinfo.py+++ b/src/gputaskman/procinfo.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport fnmatchimport osimport re+import sysimport timefrom dataclasses import dataclass, field@@ -13,30 +14,39 @@ import psutilfrom .gguf import is_gguf, read_gguffrom .stores import store_name-# (tag, dll patterns). Order = display priority (most specific first).+# (tag, library patterns: Windows DLLs and Linux shared objects with the version suffix removed, see+# _lib_name). Order = display priority (most specific first).RUNTIMES: list[tuple[str, tuple[str, ...]]] = [- ("llama.cpp", ("llama.dll", "libllama*.dll", "llama-*.dll", "llm_engine*")),- ("whisper.cpp", ("whisper*.dll",)),- ("ggml", ("ggml*.dll",)),- ("PyTorch", ("torch_cuda*.dll", "torch_cpu.dll")),- ("TensorRT", ("nvinfer*.dll",)),- ("ONNX RT", ("onnxruntime*.dll",)),+ ("llama.cpp", ("llama.dll", "libllama*.dll", "llama-*.dll", "llm_engine*", "libllama*.so")),+ ("whisper.cpp", ("whisper*.dll", "libwhisper*.so")),+ ("ggml", ("ggml*.dll", "libggml*.so")),+ ("PyTorch", ("torch_cuda*.dll", "torch_cpu.dll", "libtorch_cuda*.so", "libtorch_cpu.so")),+ ("TensorRT", ("nvinfer*.dll", "libnvinfer*.so")),+ ("ONNX RT", ("onnxruntime*.dll", "libonnxruntime*.so")),("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",)),+ ("cuDNN", ("cudnn*.dll", "libcudnn*.so")),+ ("CUDA", ("nvcuda.dll", "nvcuda64.dll", "cudart64_*.dll", "cublas64_*.dll",+ "libcuda.so", "libcudart.so", "libcublas.so")),+ ("Vulkan", ("vulkan-1.dll", "libvulkan.so")),+ ("D3D12", ("d3d12core.dll", "libd3d12core.so")),+ ("OpenGL", ("opengl32.dll", "libgl.so", "libglx*.so", "libegl*.so")),("D3D11", ("d3d11.dll",)),- ("NVENC", ("nvencodeapi64.dll",)),- ("NVDEC", ("nvcuvid.dll", "nvcuvid64.dll")),+ ("NVENC", ("nvencodeapi64.dll", "libnvidia-encode.so")),+ ("NVDEC", ("nvcuvid.dll", "nvcuvid64.dll", "libnvcuvid.so")),]+_SO = re.compile(r"^(.+\.so)(?:\.[0-9][0-9a-z.]*)?$")AI_RUNTIMES = {"llama.cpp", "whisper.cpp", "ggml", "PyTorch", "TensorRT", "ONNX RT", "DirectML", "cuDNN"}_RUNTIME_RX = [(tag, re.compile("|".join(fnmatch.translate(p) for p in pats))) for tag, pats in RUNTIMES]MODEL_EXTS = {".gguf", ".ggml", ".safetensors", ".onnx", ".pt", ".pth", ".bin", ".engine", ".plan", ".tflite", ".ckpt"}AMBIGUOUS_EXTS = {".bin", ".pt", ".pth", ".ckpt"} # also used for caches/tiles, so require size or a model store_NOT_MODELS = {".dll", ".exe", ".sys", ".mui", ".ttf", ".ttc", ".otf", ".dat", ".db", ".nls", ".pak", ".mun"}-BROWSERS = {"msedge.exe", "chrome.exe", "firefox.exe", "msedgewebview2.exe", "brave.exe", "opera.exe", "arc.exe", "vivaldi.exe"}+BROWSERS = {"msedge.exe", "chrome.exe", "firefox.exe", "msedgewebview2.exe", "brave.exe", "opera.exe", "arc.exe", "vivaldi.exe",+ "chrome", "chromium", "chromium-browser", "firefox", "firefox-bin", "brave", "msedge", "opera", "vivaldi-bin"}+# Linux display servers / compositors: they own the desktop back buffers, like dwm.exe on Windows.+COMPOSITORS = {"dwm.exe", "xorg", "xwayland", "gnome-shell", "kwin_wayland", "kwin_x11", "sway", "hyprland",+ "mutter", "weston", "wayfire", "labwc", "niri", "cosmic-comp", "picom", "compiz"}+# Paths in /proc/<pid>/maps that are not regular files: never stat or open them.+_SPECIAL_PREFIXES = ("[", "/dev/", "/proc/", "/sys/", "/memfd:", "/SYSV", "anon_inode:")LLM_NAMES = ("llama-", "llama.", "ollama", "lm studio", "lmstudio", "llmster", "koboldcpp", "jan", "gpt4all", "llamafile")# GGUF file kind -> process kind, in display priority orderMODEL_KINDS = {"LLM": "LLM", "decision model": "decision", "embedding model": "embedding",@@ -108,6 +118,16 @@ class ProcDetail:return _is_diffusion_cmdline(self.cmdline)+def _lib_name(base: str) -> str | None:+ """Lower-cased library file name with any Linux version suffix removed ('libcudart.so.12.4' ->+ 'libcudart.so'), or None when this is not a library."""+ ext = os.path.splitext(base)[1]+ if ext in (".dll", ".node"):+ return base+ m = _SO.match(base)+ return m[1] if m else None++def _match_runtimes(dll_names: set[str]) -> list[str]:return [tag for tag, rx in _RUNTIME_RX if any(rx.match(d) for d in dll_names)]@@ -176,6 +196,24 @@ def _walk(root: str, depth: int, out: list[tuple[str, int]], budget: list[int])continue+_LINUX_SYSTEM_DIRS = ("/usr/bin/", "/usr/sbin/", "/bin/", "/sbin/", "/usr/lib", "/lib", "/usr/libexec/", "/snap/")+++def _is_system_path(exe: str) -> bool:+ if sys.platform == "win32":+ return exe.startswith(os.path.normcase(os.environ.get("SystemRoot", r"C:\Windows")))+ # /usr/bin/python3 is shared by every Python app: walking /usr/bin finds nothing about the process.+ return exe.startswith(_LINUX_SYSTEM_DIRS)+++def _data_dirs() -> list[str]:+ if sys.platform == "win32":+ return [d for d in (os.environ.get("APPDATA"), os.environ.get("LOCALAPPDATA")) if d]+ home = os.path.expanduser("~")+ return [os.environ.get("XDG_DATA_HOME") or os.path.join(home, ".local", "share"),+ os.environ.get("XDG_CONFIG_HOME") or os.path.join(home, ".config")]++def installed_models(exe: str, now: float | None = None) -> list[MappedModel]:"""Model files in an app's install and data folders. Fallback for runtimes that read a model into RAM andclose the file (ONNX Runtime, whisper.cpp), which leaves no OS evidence of which model is loaded.@@ -189,10 +227,10 @@ def installed_models(exe: str, now: float | None = None) -> list[MappedModel]:return hit[1]stem = os.path.splitext(os.path.basename(key))[0]roots = []- if not key.startswith(os.path.normcase(os.environ.get("SystemRoot", r"C:\Windows"))):+ if not _is_system_path(key):roots.append(os.path.dirname(exe))if len(stem) >= 4:- for base in filter(None, (os.environ.get("APPDATA"), os.environ.get("LOCALAPPDATA"))):+ for base in _data_dirs():try:roots += [e.path for e in os.scandir(base) if stem in e.name.lower() and e.is_dir()]except OSError:@@ -312,10 +350,13 @@ class ProcInspector:models: dict[str, MappedModel] = {}for m in maps:path = m.path+ if path.startswith(_SPECIAL_PREFIXES) or path.endswith(" (deleted)"):+ continuebase = os.path.basename(path).lower()ext = os.path.splitext(base)[1]- if ext == ".dll" or ext == ".node":- dlls.add(base)+ lib = _lib_name(base)+ if lib:+ dlls.add(lib)continueif ext in _NOT_MODELS:continue@@ -347,9 +388,9 @@ class ProcInspector:def classify(d: ProcDetail, engines: dict[str, float]) -> str:n = d.name.lower()- if d.pid == 4:+ if d.pid == 4 and sys.platform == "win32": # "System"; PID 4 is an ordinary process on Linuxreturn "kernel"- if n == "dwm.exe":+ if n in COMPOSITORS:return "compositor"if n in ("csrss.exe", "winlogon.exe", "lsass.exe", "svchost.exe"):return "system"diff --git a/src/gputaskman/report.py b/src/gputaskman/report.pyindex 289d871..4ea29c4 100644--- a/src/gputaskman/report.py+++ b/src/gputaskman/report.py@@ -11,13 +11,52 @@ from .llm import gbfrom .nvml import format_metric+WSL_HOST_NOTE = ("WSL + Windows host counters: 'WSL VM' is the exact total of Linux GPU memory (all distros). "+ "Linux rows get their size by matching the VM's GPU contexts (* matched, ? guess). "+ "W: rows are Windows processes.")+++def wsl_note(s: Snapshot) -> str:+ if s.host_data:+ return WSL_HOST_NOTE+ status = f" Windows host counters: {s.host_status}." if s.host_status else ""+ return WSL_NOTE + status+++WSL_EMPTY = ("No Linux process in this distro has the GPU open (other WSL distros and Docker Desktop "+ "are not visible from here).")+WSL_NOTE = ("WSL: VRAM and engine load are device-wide. The Windows host charges every Linux process's "+ "VRAM to the VM, so rows below are processes using the GPU, not their share of it.")+++def vram_label(g) -> str:+ """Measured size; '*' / '?' when the size is exact but which local process owns it is inferred."""+ mark = {"order": "?", "consistent": "*"}.get(g.inferred_by, "")+ if g.attributed:+ return gb(g.dedicated) + mark+ return "n/a" if g.inferred is None else gb(g.inferred) + mark+++INFERRED_NOTE = ("* matched: the size is exact (Windows' counter for a WSL VM GPU context, or NVML for a host PID "+ "seen from a container); which local process owns it is inferred, and only one explanation fits.")+ORDER_NOTE = ("? order guess: the size is exact but several owners fit, so newer processes are paired with newer "+ "GPU contexts / PIDs and outside ones are assumed oldest. Becomes * with evidence, such as a process "+ "starting while gputaskman runs.")+++def inferred_note(g) -> str:+ return ORDER_NOTE if g.inferred_by == "order" else INFERRED_NOTE++def to_dict(s: Snapshot) -> dict:nv = dataclasses.asdict(s.nv) if s.nv else Noneprocs = []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),+ "pid": p.pid, "host": p.origin if p.host else None, "name": p.name, "kind": p.kind, "runtimes": p.detail.runtimes,+ "vram_attributed": p.gpu.attributed, "vram_inferred_bytes": p.gpu.inferred,+ "vram_inferred_by": p.gpu.inferred_by or None,+ "vram_bytes": int(p.gpu.dedicated) if p.gpu.attributed else None, "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,@@ -46,7 +85,8 @@ def to_dict(s: Snapshot) -> dict: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,+ "attributed": s.attributed, "backend": s.backend, "host_status": s.host_status or None,+ "wsl_split": s.wsl_split or None, "device": nv, "processes": procs,}@@ -55,7 +95,10 @@ def to_text(s: Snapshot, limit: int = 30) -> str:nv = s.nvname = 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)}")+ shared = f" shared (in system RAM) {gb(s.shared_used)}" if s.backend == "wddm" or s.host_data else ""+ out.append(f"VRAM {gb(s.vram_used)} / {gb(s.vram_total)}{shared}")+ if s.backend == "wsl":+ out.append(wsl_note(s))if nv:rx = nv.pcie_rx_kbs / 1024 if nv.pcie_rx_kbs is not None else Nonetx = nv.pcie_tx_kbs / 1024 if nv.pcie_tx_kbs is not None else None@@ -72,8 +115,20 @@ def to_text(s: Snapshot, limit: int = 30) -> str: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}")+ pid = p.pid_label+ pct = f"{p.gpu.gpu_pct:.0f}" if p.gpu.attributed else "n/a"+ out.append(f"{pid:>7} {p.name[:24]:<24} {p.kind:<10} {p.runtime[:24]:<24} {vram_label(p.gpu):>9} {spill:>8} "+ f"{paged:>8} {pct:>5} {p.inside}")+ shown = s.procs[:limit]+ if any(p.gpu.inferred_by == "consistent" for p in shown):+ out.append(INFERRED_NOTE)+ if any(p.gpu.inferred_by == "order" for p in shown):+ out.append(ORDER_NOTE)+ if s.backend == "wsl" and s.wsl_split and any(not p.host and not p.gpu.attributed and p.gpu.inferred is None+ for p in s.procs):+ out.append(f"Linux VRAM split: {s.wsl_split}")+ if s.backend == "wsl" and not any(not p.host for p in s.procs):+ out.append(f"{'':>7} {WSL_EMPTY}")for p in s.procs:if p.handy:out.append("")diff --git a/src/gputaskman/wslhost.py b/src/gputaskman/wslhost.pynew file mode 100644index 0000000..ef8ebf9--- /dev/null+++ b/src/gputaskman/wslhost.py@@ -0,0 +1,483 @@+"""Windows host GPU counters, read from inside WSL through interop.++Linux cannot see how much VRAM WSL uses: the Windows host charges all of it to the VM worker+(vmwp.exe). When WSL interop is enabled we can still ask Windows. One long-lived powershell.exe+streams the same WDDM counters the Windows backend reads (one JSON line per second), so the+~1.5 s PowerShell startup is paid once, not per refresh.+"""++from __future__ import annotations++import base64+import glob+import itertools+import json+import math+import os+import shutil+import subprocess+import threading+import time+from collections import defaultdict+from dataclasses import dataclass, field++from .pdh import _ADAPTER_RE, _ENGINE_RE, _PROC_RE, AdapterGpu, ProcGpu, _norm_engine, luid_key++_POWERSHELL_FALLBACK = "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe"++# PowerShell's Get-Counter resolves counters by instance *name*. vmwp.exe has one instance per guest GPU+# context, all with the same name, so Get-Counter reads the wrong one (or one twice) whenever contexts come+# and go. The PDH array API returns every instance as it exists at each collection, which is what the+# Windows backend (pdh.py) uses; this compiles the same calls once and streams one JSON line per second.+# Counter paths are English (PdhAddEnglishCounter), so this works on localized Windows too.+_SCRIPT = r"""+$ErrorActionPreference = 'Stop'+Add-Type -TypeDefinition @'+using System;+using System.Runtime.InteropServices;+using System.Text;+public static class GtmPdh {+ [DllImport("pdh.dll", CharSet = CharSet.Unicode)]+ static extern uint PdhOpenQueryW(string source, IntPtr user, out IntPtr query);+ [DllImport("pdh.dll", CharSet = CharSet.Unicode)]+ static extern uint PdhAddEnglishCounterW(IntPtr query, string path, IntPtr user, out IntPtr counter);+ [DllImport("pdh.dll")]+ static extern uint PdhCollectQueryData(IntPtr query);+ [DllImport("pdh.dll", CharSet = CharSet.Unicode)]+ static extern uint PdhGetFormattedCounterArrayW(IntPtr counter, uint format, ref uint size, out uint count, IntPtr items);+ static IntPtr query;+ static string[] keys;+ static IntPtr[] handles;+ public static void Open(string[] paths, string[] names) {+ PdhOpenQueryW(null, IntPtr.Zero, out query);+ keys = names;+ handles = new IntPtr[paths.Length];+ for (int i = 0; i < paths.Length; i++) PdhAddEnglishCounterW(query, paths[i], IntPtr.Zero, out handles[i]);+ PdhCollectQueryData(query);+ }+ public static string Sample() {+ PdhCollectQueryData(query);+ var sb = new StringBuilder("[");+ bool first = true;+ int stride = IntPtr.Size + 16; // PDH_FMT_COUNTERVALUE_ITEM_W: name pointer, CStatus (+pad), double+ for (int i = 0; i < handles.Length; i++) {+ if (handles[i] == IntPtr.Zero) continue;+ uint size = 0, count;+ if (PdhGetFormattedCounterArrayW(handles[i], 0x8200, ref size, out count, IntPtr.Zero) != 0x800007D2) continue;+ IntPtr buf = Marshal.AllocHGlobal((int)size);+ try {+ if (PdhGetFormattedCounterArrayW(handles[i], 0x8200, ref size, out count, buf) != 0) continue;+ for (int k = 0; k < count; k++) {+ IntPtr item = buf + k * stride;+ uint status = (uint)Marshal.ReadInt32(item, IntPtr.Size);+ double value = BitConverter.Int64BitsToDouble(Marshal.ReadInt64(item, IntPtr.Size + 8));+ // Zero-size GPU contexts still matter: vmwp.exe's instances are matched to Linux+ // processes by position, so "local usage" keeps them; everything else drops zeros.+ if ((status != 0 && status != 1) || (value == 0 && i != 0)) continue;+ string name = Marshal.PtrToStringUni(Marshal.ReadIntPtr(item)).Replace("\\", "\\\\").Replace("\"", "\\\"");+ if (!first) sb.Append(',');+ first = false;+ sb.Append("[\"").Append(keys[i]).Append("\",\"").Append(name).Append("\",").Append(value.ToString("R", System.Globalization.CultureInfo.InvariantCulture)).Append(']');+ }+ } finally { Marshal.FreeHGlobal(buf); }+ }+ return sb.Append(']').ToString();+ }+}+'@+[GtmPdh]::Open(+ @('\GPU Process Memory(*)\Local Usage', '\GPU Process Memory(*)\Non Local Usage',+ '\GPU Process Memory(*)\Total Committed', '\GPU Engine(*)\Utilization Percentage',+ '\GPU Adapter Memory(*)\Dedicated Usage', '\GPU Adapter Memory(*)\Shared Usage'),+ @('local usage', 'non local usage', 'total committed', 'utilization percentage', 'dedicated usage', 'shared usage'))+while ($true) {+ Start-Sleep -Milliseconds 1000+ $s = [GtmPdh]::Sample()+ $names = @{}+ foreach ($p in [System.Diagnostics.Process]::GetProcesses()) { $names[[string]$p.Id] = $p.ProcessName }+ [Console]::Out.WriteLine('{"s":' + $s + ',"n":' + ($names | ConvertTo-Json -Compress) + '}')+ [Console]::Out.Flush()+}+"""++_PROC_FIELDS = {"local usage": "dedicated", "non local usage": "shared", "total committed": "committed"}+_ADAPTER_FIELDS = {"dedicated usage": "dedicated", "shared usage": "shared"}+++def interop_enabled() -> bool:+ """True when this WSL distro can run Windows programs (interop not disabled in /etc/wsl.conf)."""+ for path in glob.glob("/proc/sys/fs/binfmt_misc/WSLInterop*"):+ try:+ with open(path, encoding="ascii") as f:+ if f.readline().strip() == "enabled":+ return True+ except OSError:+ continue+ return False+++def powershell_path() -> str | None:+ found = shutil.which("powershell.exe")+ if found:+ return found+ return _POWERSHELL_FALLBACK if os.path.exists(_POWERSHELL_FALLBACK) else None+++@dataclass+class HostSample:+ taken: float+ procs: dict[int, dict[int, ProcGpu]] = field(default_factory=dict) # {host luid: {host pid: ProcGpu}}+ adapters: dict[int, AdapterGpu] = field(default_factory=dict) # {host luid: AdapterGpu}+ names: dict[int, str] = field(default_factory=dict) # {host pid: process name without .exe}+ # {host luid: {host pid: [Local Usage per instance]}}. vmwp.exe has one instance per guest GPU context+ # (roughly one per Linux process using the GPU), all with the same name: sizes without owners.+ contexts: dict[int, dict[int, list[float]]] = field(default_factory=dict)+++def parse_line(line: str, now: float | None = None) -> HostSample | None:+ try:+ data = json.loads(line)+ except ValueError:+ return None+ if not isinstance(data, dict):+ return None+ sample = HostSample(taken=now if now is not None else time.time())+ procs: dict[int, dict[int, ProcGpu]] = defaultdict(dict)+ adapters: dict[int, AdapterGpu] = defaultdict(AdapterGpu)+ contexts: dict[int, dict[int, list[float]]] = defaultdict(lambda: defaultdict(list))+ for row in data.get("s") or []:+ try:+ counter, instance, value = str(row[0]).lower(), str(row[1]).lower(), float(row[2])+ except (TypeError, ValueError, IndexError):+ continue+ if counter == "utilization percentage":+ m = _ENGINE_RE.match(instance)+ if m:+ g = procs[luid_key(m[2], m[3])].setdefault(int(m[1]), ProcGpu())+ g.engines[_norm_engine(m[6])] += value+ elif counter in _PROC_FIELDS:+ m = _PROC_RE.match(instance)+ if m:+ g = procs[luid_key(m[2], m[3])].setdefault(int(m[1]), ProcGpu())+ attr = _PROC_FIELDS[counter]+ setattr(g, attr, getattr(g, attr) + value) # vmwp.exe has one instance per guest context+ if attr == "dedicated":+ contexts[luid_key(m[2], m[3])][int(m[1])].append(value)+ elif counter in _ADAPTER_FIELDS:+ m = _ADAPTER_RE.match(instance)+ if m:+ a = adapters[luid_key(m[1], m[2])]+ attr = _ADAPTER_FIELDS[counter]+ setattr(a, attr, getattr(a, attr) + value)+ for pid, name in (data.get("n") or {}).items():+ try:+ sample.names[int(pid)] = str(name)+ except ValueError:+ continue+ sample.procs, sample.adapters = dict(procs), dict(adapters)+ sample.contexts = {luid: dict(per) for luid, per in contexts.items()}+ return sample+++def match_adapter(sample: HostSample, device_used: float) -> int | None:+ """WSL's adapter LUIDs differ from the host's, so pair the host adapter whose dedicated usage matches+ NVML's device-wide usage. Ambiguous or distant matches return None: no host data beats wrong data."""+ if not device_used or not sample.adapters:+ return None+ ranked = sorted(sample.adapters.items(), key=lambda kv: abs(kv[1].dedicated - device_used))+ luid, best = ranked[0]+ tolerance = max(512 << 20, 0.15 * device_used)+ if abs(best.dedicated - device_used) > tolerance:+ return None+ if len(ranked) > 1 and abs(ranked[1][1].dedicated - device_used) <= tolerance:+ return None+ return luid+++class HostStream:+ """Background reader of the PowerShell counter stream. status: starting | ok | off | unavailable (...)."""++ STALE_AFTER = 30.0 # keep showing the last sample through PowerShell stalls; drop it only after this++ def __init__(self, exe: str | None = None, popen=subprocess.Popen) -> None:+ self.status = "starting"+ self._latest: HostSample | None = None+ self._ready = threading.Event()+ self._proc = None+ exe = exe or powershell_path()+ if exe is None:+ self.status = "unavailable (powershell.exe not found)"+ self._ready.set()+ return+ try:+ encoded = base64.b64encode(_SCRIPT.encode("utf-16-le")).decode("ascii")+ self._proc = popen([exe, "-NoProfile", "-NonInteractive", "-EncodedCommand", encoded],+ stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,+ text=True, bufsize=1)+ except (OSError, ValueError) as error:+ self.status = f"unavailable ({error})"+ self._ready.set()+ return+ threading.Thread(target=self._read, name="wsl-host-counters", daemon=True).start()++ def _read(self) -> None:+ for line in self._proc.stdout:+ sample = parse_line(line)+ if sample is not None and (sample.procs or sample.adapters):+ self._latest = sample+ self.status = "ok"+ self._ready.set()+ if self.status != "off":+ self.status = "unavailable (counter stream ended)"+ self._ready.set()++ def wait(self, timeout: float) -> bool:+ return self._ready.wait(timeout)++ def latest(self) -> HostSample | None:+ s = self._latest+ return s if s is not None and time.time() - s.taken <= self.STALE_AFTER else None++ @property+ def ended(self) -> bool:+ return self.status.startswith("unavailable")++ def close(self) -> None:+ self.status = "off"+ if self._proc is not None and self._proc.poll() is None:+ self._proc.terminate()+ try:+ self._proc.wait(timeout=2)+ except subprocess.TimeoutExpired:+ self._proc.kill()+++# ---------------------------------------------------------------- per-process VRAM by elimination++MiB = 1 << 20+++def _boot_id() -> str:+ try:+ with open("/proc/sys/kernel/random/boot_id", encoding="ascii") as f:+ return f.read().strip()+ except OSError:+ return ""+++def _default_cache() -> str:+ base = os.environ.get("XDG_CACHE_HOME") or os.path.join(os.path.expanduser("~"), ".cache")+ return os.path.join(base, "gputaskman", "wsl-idle-contexts.json")+++@dataclass+class ContextGuess:+ bytes: float+ confidence: str # "consistent": every equally good explanation agrees | "order": start-order guess+++FOREIGN = "foreign" # a context from outside this distro (WSLg, other distros, Docker, hidden services)+++@dataclass+class _Entry:+ value: float+ label: object = None # holder pid | FOREIGN | ("gone", pid): its holder exited, waiting to vanish+ sure: bool = False # established by an event or elimination, never by a guess+++class ContextTracker:+ """Matches vmwp.exe's GPU contexts to Linux processes by following them over time.++ Measured on WSL2 (driver 610.88): every Linux process that opens /dev/dxg gets one vmwp.exe context+ (an NVML-only process too, at 0 bytes), and the PDH instance array lists contexts newest first,+ keeping that order as others come and go. Contexts from outside this distro are interleaved by age.++ Contexts are aligned sample to sample (survivors keep their order). A match becomes *sure* only from+ evidence: a new Linux GPU process and a new context appearing together, elimination (as many unsure+ contexts as unsure processes, and just one process), contexts seen while no Linux process holds the GPU+ (foreign; cached per WSL boot), or this monitor's own 0-byte context being the newest at startup.+ Everything else is an order guess (newest process <-> newest context, foreign assumed oldest),+ recomputed each sample and never used as evidence.+ """++ PENDING = 5.0 # seconds a new process may take to create its context+ GONE = 5.0 # seconds an exited process's context may linger in the (older) host sample+ TOL_MIN = 64 * MiB+ TOL_REL = 0.10+ SAVE_EVERY = 60.0++ def __init__(self, path: str | None = None, boot_id: str | None = None, self_pid: object = None) -> None:+ self.path = path or _default_cache()+ self.boot_id = _boot_id() if boot_id is None else boot_id+ self.self_pid = self_pid+ self.luid: int | None = None+ self.cached_foreign: list[float] = []+ self._reset()+ self._saved = 0.0+ try:+ with open(self.path, encoding="utf-8") as f:+ data = json.load(f)+ if data.get("boot_id") == self.boot_id and self.boot_id:+ self.cached_foreign = [float(v) for v in data["foreign"]]+ self.luid = int(data["luid"])+ except (OSError, ValueError, KeyError, TypeError):+ pass++ def _reset(self) -> None:+ self.entries: list[_Entry] | None = None+ self.seen: dict[object, float] = {} # holder pid -> first seen+ self.initial: set = set() # holders already running at the first sample+ self.gone: dict[object, float] = {}++ def _tol(self, v: float) -> float:+ return max(self.TOL_MIN, self.TOL_REL * v)++ @staticmethod+ def _soft(x: float, y: float) -> float:+ return min(abs(x - y) / max(x, y, 256 * MiB), 1.0)++ EVENT_COST = 1.0 # per context appearing or vanishing beyond what process starts/exits explain++ def _align(self, prev: list[_Entry], cur: list[float], max_new: int, max_gone: int) -> list[_Entry | None]:+ """Previous context for each current one (None = new). New contexts are always a prefix (the list+ is newest first); vanished ones can be anywhere. Sizes decide among the structures that process+ starts/exits allow; other structures cost EVENT_COST per extra context, so a context that grows by+ GBs between samples (a model loading) stays the same context."""+ n, best, best_cost = len(prev), None, float("inf")+ for k in range(len(cur) + 1):+ surv = cur[k:]+ m = len(surv)+ if m > n:+ continue+ # f[i][j]: cost of matching all of surv[j:] in order to a subsequence of prev[i:]+ inf = float("inf")+ f = [[inf] * (m + 1) for _ in range(n + 1)]+ for i in range(n + 1):+ f[i][m] = 0.0+ for i in range(n - 1, -1, -1):+ for j in range(m - 1, -1, -1):+ f[i][j] = min(f[i + 1][j], self._soft(prev[i].value, surv[j]) + f[i + 1][j + 1])+ gone = n - m+ cost = f[0][0] + self.EVENT_COST * (max(0, k - max_new) + max(0, gone - max_gone))+ if cost < best_cost - 1e-9:+ out: list[_Entry | None] = [None] * len(cur)+ i = j = 0+ while j < m:+ if self._soft(prev[i].value, surv[j]) + f[i + 1][j + 1] <= f[i][j] + 1e-9:+ out[k + j] = prev[i]+ j += 1+ i += 1+ best, best_cost = out, cost+ return best++ def _save(self, force: bool = False) -> None:+ now = time.time()+ if not force and now - self._saved < self.SAVE_EVERY:+ return+ self._saved = now+ try:+ os.makedirs(os.path.dirname(self.path), exist_ok=True)+ tmp = f"{self.path}.{os.getpid()}.tmp"+ with open(tmp, "w", encoding="utf-8") as f:+ json.dump({"boot_id": self.boot_id, "luid": self.luid, "foreign": self.cached_foreign}, f)+ os.replace(tmp, self.path)+ except OSError:+ pass++ def update(self, luid: int, contexts: list[float], holders: list[tuple[object, float]],+ now: float | None = None) -> tuple[dict[object, ContextGuess], str]:+ """contexts: vmwp.exe sizes, newest first. holders: (pid, start time) of every Linux process in this+ distro with /dev/dxg open, this monitor included. Returns ({pid: guess}, reason)."""+ now = time.time() if now is None else now+ if luid != self.luid:+ self.luid, self.cached_foreign = luid, []+ self._reset()+ start = dict(holders)+ first = self.entries is None+ cur = [_Entry(v) for v in contexts]+ fresh: list[_Entry] = [] # contexts that appeared since the previous sample+ if not first:+ sure = {e.label for e in self.entries if e.sure}+ waiting = [p for p in start if p not in self.initial and p not in sure] # new or lagging processes+ exited = [p for p in self.seen if p not in start]+ lingering = sum(1 for e in self.entries if isinstance(e.label, tuple))+ for e, old in zip(cur, self._align(self.entries, contexts, len(waiting), len(exited) + lingering)):+ if old is None:+ fresh.append(e)+ else:+ e.label, e.sure = old.label, old.sure++ for pid in start:+ if pid not in self.seen:+ self.seen[pid] = now+ if first:+ self.initial.add(pid)+ for pid in [p for p in self.seen if p not in start]:+ del self.seen[pid]+ self.gone[pid] = now+ for e in cur:+ if e.label in self.gone and not isinstance(e.label, tuple):+ e.label, e.sure = ("gone", e.label), False+ if isinstance(e.label, tuple) and now - self.gone.get(e.label[1], 0) > self.GONE:+ e.label = None+ if e.label is not None and not isinstance(e.label, tuple) and e.label != FOREIGN and e.label not in start:+ e.label, e.sure = None, False+ self.gone = {p: t for p, t in self.gone.items() if now - t <= self.GONE}+ for e in cur: # guesses are recomputed below, never carried as evidence+ if not e.sure and not isinstance(e.label, tuple):+ e.label = None++ def labeled() -> set:+ return {e.label for e in cur if e.sure}++ def age(pid) -> float: # larger = newer GPU context+ return start.get(pid, 0.0) if pid in self.initial else self.seen[pid]++ if not start:+ for e in cur:+ if e.label is None:+ e.label, e.sure = FOREIGN, True+ elif first:+ if self.self_pid in start and cur and cur[0].value <= self.TOL_MIN:+ cur[0].label, cur[0].sure = self.self_pid, True # our NVML context: newest when we start+ for v in self.cached_foreign:+ free = [e for e in reversed(cur) if e.label is None and abs(e.value - v) <= self._tol(v)]+ if free:+ best = min(free, key=lambda e: abs(e.value - v))+ best.label, best.sure = FOREIGN, True+ elif fresh:+ pending = sorted((p for p in start if p not in labeled() and p not in self.initial+ and now - self.seen[p] <= self.PENDING),+ key=lambda p: -age(p))+ fresh = [e for e in fresh if e.label is None]+ if not pending:+ for e in fresh:+ e.label, e.sure = FOREIGN, True+ elif len(fresh) == len(pending) == 1:+ fresh[0].label, fresh[0].sure = pending[0], True++ unsure = sorted((p for p in start if p not in labeled()), key=lambda p: -age(p))+ free = [e for e in cur if e.label is None]+ reason = ""+ if unsure:+ if len(free) < len(unsure):+ reason = (f"{len(unsure)} Linux GPU process(es) without a VM context to match "+ "(one may not have created its GPU context yet)")+ elif len(free) == len(unsure) == 1:+ free[0].label, free[0].sure = unsure[0], True+ else:+ same = len(free) == len(unsure) and all(abs(e.value - free[0].value) <= self._tol(free[0].value)+ for e in free)+ for pid, e in zip(unsure, free): # newest process <-> newest context; leftovers are foreign+ e.label, e.sure = pid, same++ self.entries = cur+ foreign = [e.value for e in cur if e.label == FOREIGN and e.sure]+ if not start or foreign:+ changed = sorted(foreign) != sorted(self.cached_foreign)+ self.cached_foreign = foreign+ self._save(force=changed and not start)+ out = {e.label: ContextGuess(e.value, "consistent" if e.sure else "order")+ for e in cur if e.label in start}+ return out, reasondiff --git a/tests/test_core.py b/tests/test_core.pyindex 2896160..3333bf1 100644--- a/tests/test_core.py+++ b/tests/test_core.py@@ -32,6 +32,11 @@ from gputaskman.report import to_dict, to_textfrom gputaskman.stores import store_namefrom tools.capture_screenshots import for_publication++def native(path: str) -> str:+ """Windows-style test paths as native paths, so path logic is exercised the same way on Linux."""+ return path if os.sep == "\\" else "/" + path.split(":", 1)[-1].lstrip("\\").replace("\\", "/")+GiB = 1 << 30MiB = 1 << 20@@ -209,7 +214,7 @@ class MemoryTests(unittest.TestCase):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)+ GgufInfo(path=native(r"C:\Users\example\models\model.gguf"), file_size=1, version=3)]public = for_publication(original)self.assertEqual(public.procs[0].detail.cmdline, [])@@ -390,7 +395,7 @@ class IdentityTests(unittest.TestCase):for path, store in cases:with self.subTest(path=path, store=store), \patch("gputaskman.procinfo.store_name", return_value=store):- m = make_model(path, 1000, 0, False, "mapped", store)+ m = make_model(native(path), 1000, 0, False, "mapped", store)self.assertEqual(m.kind_hint, expected)self.assertEqual(m.sources, ["mapped"])self.assertEqual(m.evidence, "in use (mapped)")diff --git a/tests/test_linux.py b/tests/test_linux.pynew file mode 100644index 0000000..39abb41--- /dev/null+++ b/tests/test_linux.py@@ -0,0 +1,254 @@+from __future__ import annotations++import unittest+from types import SimpleNamespace+from unittest.mock import patch++from gputaskman import linux+from gputaskman.collector import ProcRow, Snapshot+from gputaskman.gguf import GgufInfo+from gputaskman.llm import build_view+from gputaskman.pdh import ProcGpu+from gputaskman.procinfo import ProcDetail, _lib_name, _match_runtimes, classify+from gputaskman.report import to_dict, to_text++GiB = 1 << 30+NOT_AVAILABLE = (1 << 64) - 1 # NVML_VALUE_NOT_AVAILABLE as an unsigned long long+++class FakeNvml:+ """Just enough of pynvml for LinuxCounters: one GPU, scripted process lists and utilization samples."""++ def __init__(self, compute=(), graphics=(), samples=(), used=4 * GiB):+ self.compute, self.graphics, self.samples, self.used = list(compute), list(graphics), list(samples), used+ self.util_calls = []++ def nvmlInit(self):+ pass++ def nvmlShutdown(self):+ pass++ def nvmlDeviceGetCount(self):+ return 1++ def nvmlDeviceGetHandleByIndex(self, i):+ return "h0"++ def nvmlDeviceGetPciInfo(self, h):+ return SimpleNamespace(busId=b"00000000:01:00.0")++ def nvmlDeviceGetName(self, h):+ return "NVIDIA GeForce RTX 3090 Ti"++ def nvmlDeviceGetMemoryInfo(self, h):+ return SimpleNamespace(total=24 * GiB, used=self.used)++ def nvmlDeviceGetComputeRunningProcesses(self, h):+ return self.compute++ def nvmlDeviceGetGraphicsRunningProcesses(self, h):+ return self.graphics++ def nvmlDeviceGetProcessUtilization(self, h, since):+ self.util_calls.append(since)+ return self.samples+++def proc(pid, used):+ return SimpleNamespace(pid=pid, usedGpuMemory=used)+++def sample(pid, sm, enc=0, dec=0, ts=1):+ return SimpleNamespace(pid=pid, smUtil=sm, encUtil=enc, decUtil=dec, timeStamp=ts)+++KEY = linux.pci_key("00000000:01:00.0")+++class LinuxLibraryTests(unittest.TestCase):+ def test_versioned_shared_objects_are_libraries(self):+ self.assertEqual(_lib_name("libcudart.so.12"), "libcudart.so")+ self.assertEqual(_lib_name("libcuda.so.1.1"), "libcuda.so")+ self.assertEqual(_lib_name("libtorch_cuda.so"), "libtorch_cuda.so")+ self.assertEqual(_lib_name("nvcuda.dll"), "nvcuda.dll")+ self.assertIsNone(_lib_name("model.gguf"))+ self.assertIsNone(_lib_name("weights.safetensors"))+ self.assertIsNone(_lib_name("model.so-weights.bin"))++ def test_linux_runtimes_are_detected(self):+ libs = {_lib_name(n) for n in ("libggml-cuda.so", "libllama.so", "libcudart.so.12", "libcuda.so.1",+ "libvulkan.so.1", "libtorch_cuda.so", "libnvidia-encode.so.1")}+ self.assertEqual(_match_runtimes(libs), ["llama.cpp", "ggml", "PyTorch", "CUDA", "Vulkan", "NVENC"])++ def test_linux_compositors_and_browsers(self):+ self.assertEqual(classify(ProcDetail(900, "Xorg"), {}), "compositor")+ self.assertEqual(classify(ProcDetail(901, "gnome-shell"), {}), "compositor")+ self.assertEqual(classify(ProcDetail(902, "firefox"), {}), "browser")++ def test_pid_4_is_only_special_on_windows(self):+ with patch("gputaskman.procinfo.sys.platform", "linux"):+ self.assertEqual(classify(ProcDetail(4, "kworker/0:0"), {}), "app")+ with patch("gputaskman.procinfo.sys.platform", "win32"):+ self.assertEqual(classify(ProcDetail(4, "System"), {}), "kernel")+++class PdhImportTests(unittest.TestCase):+ def test_pdh_module_is_complete_without_loading_the_dll(self):+ from gputaskman import pdh+ for name in ("PDH_FMT_DOUBLE", "PDH_FMT_NOCAP100", "PDH_MORE_DATA", "_Item", "_load_pdh"):+ self.assertTrue(hasattr(pdh, name), name)+++class LinuxCountersTests(unittest.TestCase):+ def setUp(self):+ # Same PID namespace (bare metal): NVML's PIDs are local processes holding an NVIDIA device.+ holders = patch.object(linux, "nvidia_holders", return_value={100, 101, 200, 300, 555})+ holders.start()+ self.addCleanup(holders.stop)++ def counters(self, fake, wsl):+ with patch.object(linux, "N", fake), patch.object(linux, "is_wsl", return_value=wsl):+ return linux.LinuxCounters()++ def test_native_linux_attributes_vram_and_engines_per_pid(self):+ fake = FakeNvml(compute=[proc(100, 3 * GiB), proc(200, 1 * GiB)],+ graphics=[proc(200, 1 * GiB), proc(300, 256 << 20)],+ samples=[sample(100, 80, ts=5), sample(100, 90, ts=9), sample(300, 30, dec=20, ts=7)])+ c = self.counters(fake, wsl=False)+ with patch.object(linux, "N", fake):+ procs, adapters = c.sample()+ c.sample()+ per = procs[KEY]+ self.assertEqual(adapters[KEY].dedicated, 4 * GiB)+ self.assertEqual(per[100].dedicated, 3 * GiB)+ self.assertEqual(per[200].dedicated, 1 * GiB) # in both lists: counted once+ self.assertEqual(per[100].engines["compute"], 90) # latest sample wins+ self.assertEqual(per[300].engines["3d"], 30) # graphics-only process: SM load is 3D work+ self.assertEqual(per[300].engines["decode"], 20)+ self.assertTrue(all(g.attributed for g in per.values()))+ self.assertEqual(fake.util_calls, [0, 9]) # next poll asks only for newer samples++ def test_hidden_per_process_memory_is_unknown_not_zero(self):+ fake = FakeNvml(compute=[proc(100, NOT_AVAILABLE), proc(101, None)])+ c = self.counters(fake, wsl=False)+ with patch.object(linux, "N", fake):+ procs, _ = c.sample()+ self.assertFalse(procs[KEY][100].attributed)+ self.assertFalse(procs[KEY][101].attributed)++ def test_utilization_for_unlisted_pids_is_ignored(self):+ fake = FakeNvml(compute=[proc(100, GiB)], samples=[sample(555, 50)])+ c = self.counters(fake, wsl=False)+ with patch.object(linux, "N", fake):+ procs, _ = c.sample()+ self.assertNotIn(555, procs[KEY])++ def test_wsl_never_uses_windows_host_pids(self):+ # Under WSL NVML reports Windows PIDs (dwm 2744, System 4); they must not become Linux rows.+ fake = FakeNvml(samples=[sample(2744, 12), sample(4, 88)], used=7 * GiB)+ c = self.counters(fake, wsl=True)+ with patch.object(linux, "N", fake), patch.object(linux, "dxg_pids", return_value={4242}):+ procs, adapters = c.sample()+ self.assertEqual(adapters[KEY].dedicated, 7 * GiB)+ self.assertEqual(set(procs[KEY]), {4242})+ self.assertFalse(procs[KEY][4242].attributed)+ self.assertEqual(fake.util_calls, [])++ def test_adapters_come_from_nvml(self):+ with patch.object(linux, "N", FakeNvml()):+ adapters = linux.enumerate_adapters()+ self.assertEqual([(a.luid, a.name, a.dedicated_vram) for a in adapters],+ [(KEY, "NVIDIA GeForce RTX 3090 Ti", 24 * GiB)])+++class ContainerTests(unittest.TestCase):+ """Measured on a Vast.ai Docker container: NVML lists host PIDs (2029701...) while the processes are+ 547 and 563 inside; the host's display server shows up only in the graphics list."""++ def sample(self, c, fake, holders, cuda):+ with patch.object(linux, "N", fake), patch.object(linux, "nvidia_holders", return_value=set(holders)), \+ patch.object(linux, "has_cuda", side_effect=lambda pid: pid in cuda):+ return c.sample()[0][KEY]++ def test_host_pids_are_matched_to_container_pids_by_creation_order(self):+ fake = FakeNvml(compute=[proc(2029701, GiB), proc(2029747, 2 * GiB)],+ graphics=[proc(1145, 58 << 20), proc(1360, 21 << 20)],+ samples=[sample(2029747, 95, ts=3)])+ with patch.object(linux, "N", fake), patch.object(linux, "is_wsl", return_value=False):+ c = linux.LinuxCounters()+ # 564 is an NVML-only tool (nvidia-smi, this monitor): it holds the devices but has no CUDA context+ per = self.sample(c, fake, holders={547, 563, 564}, cuda={547, 563})+ self.assertEqual({pid: (g.dedicated, g.inferred_by) for pid, g in per.items()},+ {547: (GiB, "consistent"), 563: (2 * GiB, "consistent")})+ self.assertEqual(per[563].engines["compute"], 95) # utilization follows the match+ self.assertEqual(set(c.outside[KEY]), {1145, 1360}) # never looked up in the container's /proc++ def test_extra_outside_compute_is_a_guess_until_a_start_event(self):+ fake = FakeNvml(compute=[proc(9000, GiB), proc(2029701, 3 * GiB)]) # 9000: another container+ with patch.object(linux, "N", fake), patch.object(linux, "is_wsl", return_value=False):+ c = linux.LinuxCounters()+ per = self.sample(c, fake, holders={547}, cuda={547})+ self.assertEqual((per[547].dedicated, per[547].inferred_by), (3 * GiB, "order"))+ self.assertEqual(set(c.outside[KEY]), {9000})+ fake.compute.append(proc(2029800, 2 * GiB)) # a new local job starts: one new PID on each side+ per = self.sample(c, fake, holders={547, 600}, cuda={547, 600})+ self.assertEqual((per[600].dedicated, per[600].inferred_by), (2 * GiB, "consistent"))++ def test_bare_metal_is_unchanged(self):+ fake = FakeNvml(compute=[proc(547, GiB)])+ with patch.object(linux, "N", fake), patch.object(linux, "is_wsl", return_value=False):+ c = linux.LinuxCounters()+ per = self.sample(c, fake, holders={547}, cuda={547})+ self.assertEqual((per[547].dedicated, per[547].inferred_by), (GiB, ""))+ self.assertEqual(c.outside, {})++ def test_outside_rows_never_borrow_a_local_identity(self):+ from gputaskman.collector import ProcRow as Row+ row = Row(1145, "(outside this container)", "external", ProcGpu(dedicated=58 << 20),+ ProcDetail(1145, "(outside this container)"), host=True, origin="outside")+ self.assertEqual((row.key, row.pid_label), ("o1145", "H:1145"))+ snap = Snapshot(taken=1, adapter=None, adapters=[], nv=None, driver="", cuda="", vram_total=8 * GiB,+ vram_used=GiB, shared_used=0, backend="nvml", procs=[row])+ self.assertIn("H:1145", to_text(snap))+ self.assertEqual(to_dict(snap)["processes"][0]["host"], "outside")+++class UnattributedReportTests(unittest.TestCase):+ def snapshot(self):+ return Snapshot(taken=1, adapter=None, adapters=[], nv=None, driver="", cuda="", vram_total=24 * GiB,+ vram_used=7 * GiB, shared_used=0, backend="wsl",+ procs=[ProcRow(4242, "python3", "AI", ProcGpu(attributed=False), ProcDetail(4242, "python3"))])++ def test_reports_say_unknown_instead_of_zero(self):+ data = to_dict(self.snapshot())+ self.assertEqual(data["backend"], "wsl")+ self.assertIsNone(data["processes"][0]["vram_bytes"])+ self.assertFalse(data["processes"][0]["vram_attributed"])+ text = to_text(self.snapshot())+ row = next(line for line in text.splitlines() if "4242" in line)+ self.assertIn("n/a", row)+ self.assertNotIn("0 B", row)+ self.assertIn("WSL:", text)+ self.assertNotIn("shared (in system RAM)", text)++ def test_empty_wsl_view_explains_itself(self):+ snap = self.snapshot()+ snap.procs = []+ self.assertIn("No Linux process", to_text(snap))++ def test_llm_view_does_not_claim_cpu_inference_when_vram_is_unknown(self):+ d = ProcDetail(4242, "llama-server", cmdline=["llama-server", "-c", "4096"])+ d.models = [SimpleNamespace(path="/m/x.gguf", gguf=True, sources=["mapped"], store_name=None,+ kind="", kind_hint="", size=GiB)]+ with patch("gputaskman.llm.dataclasses.replace", side_effect=lambda m, **kw: m), \+ patch("gputaskman.llm.read_gguf", return_value=GgufInfo(path="/m/x.gguf", file_size=GiB, version=3)):+ known = build_view(d, 0, 0, None)+ unknown = build_view(d, 0, 0, None, attributed=False)+ self.assertTrue(any("CPU inference" in n for n in known.notes))+ self.assertFalse(any("CPU inference" in n for n in unknown.notes))+ self.assertTrue(any("unknown" in n for n in unknown.notes))+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_portable.py b/tests/test_portable.pyindex e400a43..b7ea1bf 100644--- a/tests/test_portable.py+++ b/tests/test_portable.py@@ -5,7 +5,12 @@ import unittestimport zipfileimport hashlib-from tools.build_portable import architecture, check_executable, create_archive, nvidia_license, validate_version+import os+import stat+import tarfile++from tools.build_portable import (architecture, check_elf, check_executable, create_archive, create_linux_archive,+ nvidia_license, target, validate_version)class PortableTests(unittest.TestCase):@@ -79,5 +84,62 @@ class PortableTests(unittest.TestCase):create_archive(root, root / "output", "0.1.0", "arm64")+class LinuxPortableTests(unittest.TestCase):+ def write_elf(self, path, machine):+ header = bytearray(64)+ header[:4] = b"\x7fELF"+ header[4], header[5] = 2, 1 # 64-bit, little-endian+ struct.pack_into("<H", header, 18, machine)+ path.write_bytes(bytes(header))+ path.chmod(0o755)++ def test_linux_interpreters_map_to_targets(self):+ self.assertEqual(target("linux-x86_64"), ("linux", "x64"))+ self.assertEqual(target("linux-aarch64"), ("linux", "arm64"))+ self.assertEqual(architecture("linux-x86_64"), "x64")+ with self.assertRaises(ValueError):+ target("linux-i686")++ def test_elf_machine(self):+ with tempfile.TemporaryDirectory() as temporary:+ exe = Path(temporary) / "gputaskman"+ for arch, machine in [("x64", 0x3E), ("arm64", 0xB7)]:+ self.write_elf(exe, machine)+ check_elf(exe, arch)+ with self.assertRaises(ValueError):+ check_elf(exe, "x64")+ exe.write_bytes(b"MZ not an elf")+ with self.assertRaises(ValueError):+ check_elf(exe, "x64")++ def test_tarball_keeps_executable_bit_and_has_checksum(self):+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ bundle = root / "bundle"+ (bundle / "_internal").mkdir(parents=True)+ self.write_elf(bundle / "gputaskman", 0x3E)+ (bundle / "_internal" / "data.css").write_text("resource", encoding="utf-8")+ archive = create_linux_archive(bundle, root / "output", "0.1.0", "x64")+ self.assertEqual(archive.name, "gputaskman-0.1.0-linux-x64.tar.gz")+ with tarfile.open(archive) as packed:+ members = {m.name: m for m in packed.getmembers()}+ self.assertEqual(set(members), {"gputaskman-0.1.0-linux-x64/gputaskman",+ "gputaskman-0.1.0-linux-x64/_internal/data.css"})+ self.assertTrue(members["gputaskman-0.1.0-linux-x64/gputaskman"].mode & stat.S_IXUSR)+ self.assertEqual(members["gputaskman-0.1.0-linux-x64/gputaskman"].uid, 0)+ expected = hashlib.sha256(archive.read_bytes()).hexdigest()+ self.assertEqual(Path(f"{archive}.sha256").read_text(encoding="utf-8"), f"{expected} {archive.name}\n")++ def test_tarball_rejects_driver_libraries(self):+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ self.write_elf(root / "gputaskman", 0x3E)+ for lib in ("libnvidia-ml.so.1", "libcuda.so.1"):+ (root / lib).write_bytes(b"driver")+ with self.assertRaisesRegex(ValueError, "must not be distributed"):+ create_linux_archive(root, root / "output", "0.1.0", "x64")+ os.remove(root / lib)++if __name__ == "__main__":unittest.main()diff --git a/tests/test_wslhost.py b/tests/test_wslhost.pynew file mode 100644index 0000000..ed52ded--- /dev/null+++ b/tests/test_wslhost.py@@ -0,0 +1,364 @@+from __future__ import annotations++import io+import json+import os+import tempfile+import time+import unittest+from unittest.mock import mock_open, patch++from gputaskman import collector as collector_mod+from gputaskman import wslhost+from gputaskman.collector import Collector, ProcRow, Snapshot+from gputaskman.pdh import AdapterGpu, ProcGpu+from gputaskman.procinfo import ProcDetail+from gputaskman.report import to_dict, to_text+from gputaskman.wslhost import ContextTracker, HostSample, HostStream, match_adapter, parse_line++GiB = 1 << 30+MiB = 1 << 20+LUID = "luid_0x00000000_0x0000ff9b_phys_0"+RTX = 0xFF9B+++def line(rows, names):+ return json.dumps({"s": rows, "n": names})+++SAMPLE = line(+ [+ ["local usage", f"pid_24820_{LUID}", 2.0 * GiB], # vmwp: one instance per guest context, summed+ ["local usage", f"pid_24820_{LUID}", 0.4 * GiB],+ ["local usage", f"pid_2744_{LUID}", 300 * MiB],+ ["non local usage", f"pid_2744_{LUID}", 20 * MiB],+ ["utilization percentage", f"pid_24820_{LUID}_eng_0_engtype_3D", 40.0],+ ["utilization percentage", f"pid_2744_{LUID}_eng_0_engtype_3D", 3.0],+ ["dedicated usage", LUID, 3.0 * GiB],+ ["dedicated usage", "luid_0x00000000_0x00011431_phys_0", 2 * MiB],+ ["local usage", "garbage", 1.0],+ ],+ {"24820": "vmwp", "2744": "dwm", "4": "System"},+)+++class ParseTests(unittest.TestCase):+ def test_parses_counters_like_the_windows_backend(self):+ s = parse_line(SAMPLE, now=1.0)+ self.assertEqual(s.procs[RTX][24820].dedicated, 2.4 * GiB)+ self.assertEqual(s.procs[RTX][24820].engines["3d"], 40.0)+ self.assertEqual(s.procs[RTX][2744].shared, 20 * MiB)+ self.assertEqual(s.adapters[RTX].dedicated, 3.0 * GiB)+ self.assertEqual(s.names[24820], "vmwp")++ def test_bad_lines_are_ignored(self):+ self.assertIsNone(parse_line("WARNING: something"))+ self.assertIsNone(parse_line("[1, 2]"))+ self.assertEqual(parse_line(line([["local usage"]], {})).procs, {})+++class MatchTests(unittest.TestCase):+ def sample(self, *usages):+ return HostSample(taken=0, adapters={i + 1: AdapterGpu(dedicated=u) for i, u in enumerate(usages)})++ def test_matches_adapter_by_device_usage(self):+ self.assertEqual(match_adapter(self.sample(5.1 * GiB, 0), 5.3 * GiB), 1)++ def test_refuses_distant_or_ambiguous_matches(self):+ self.assertIsNone(match_adapter(self.sample(1 * GiB), 5 * GiB))+ self.assertIsNone(match_adapter(self.sample(5.0 * GiB, 5.1 * GiB), 5.05 * GiB))+ self.assertIsNone(match_adapter(self.sample(5 * GiB), 0))+++class InteropTests(unittest.TestCase):+ def test_interop_flag_reads_binfmt_entry(self):+ with patch("gputaskman.wslhost.glob.glob", return_value=["/proc/sys/fs/binfmt_misc/WSLInterop"]):+ with patch("builtins.open", mock_open(read_data="enabled\ninterpreter /init\n")):+ self.assertTrue(wslhost.interop_enabled())+ with patch("builtins.open", mock_open(read_data="disabled\n")):+ self.assertFalse(wslhost.interop_enabled())+ with patch("gputaskman.wslhost.glob.glob", return_value=[]):+ self.assertFalse(wslhost.interop_enabled())++ def test_stream_reads_lines_from_powershell(self):+ calls = []++ class FakeProc:+ def __init__(self, args, **kw):+ calls.append(args)+ self.stdout = io.StringIO(SAMPLE + "\n")++ def poll(self):+ return 0++ h = HostStream(exe="powershell.exe", popen=FakeProc)+ self.assertTrue(h.wait(2))+ deadline = time.time() + 2+ while h.status == "starting" and time.time() < deadline:+ time.sleep(0.01)+ self.assertIsNotNone(h.latest())+ self.assertEqual(calls[0][:4], ["powershell.exe", "-NoProfile", "-NonInteractive", "-EncodedCommand"])++ def test_missing_powershell_is_reported(self):+ with patch("gputaskman.wslhost.powershell_path", return_value=None):+ h = HostStream()+ self.assertTrue(h.status.startswith("unavailable"))+ self.assertIsNone(h.latest())+++def at(values_gib):+ return [v * GiB for v in values_gib]+++class TrackerTests(unittest.TestCase):+ """Replays context sequences measured on WSL2: contexts newest first, one per /dev/dxg holder."""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.path = os.path.join(self.tmp.name, "ctx.json")+ self.clock = 1000.0++ def make(self, boot="boot-1"):+ return ContextTracker(path=self.path, boot_id=boot, self_pid="S")++ def step(self, t, contexts, holders):+ self.clock += 1.1+ return t.update(RTX, at(contexts), holders, now=self.clock)++ def check(self, result, expected, reason=""):+ guesses, why = result+ self.assertIn(reason, why)+ got = {pid: (round(g.bytes / GiB, 2), "*" if g.confidence == "consistent" else "?")+ for pid, g in guesses.items() if pid != "S"}+ self.assertEqual(got, expected)++ def test_processes_started_while_watching_are_pinned(self):+ t = self.make()+ h = [("S", 900)]+ self.check(self.step(t, [0.0, 0.0], h), {}) # our context (newest) and one foreign+ h.append(("A", 950))+ self.check(self.step(t, [1.19, 0.0, 0.0], h), {"A": (1.19, "*")})+ h.append(("F1", 960))+ self.check(self.step(t, [0.4, 1.19, 0.0, 0.0], h), {"A": (1.19, "*"), "F1": (0.4, "*")})+ h.append(("B", 970))+ self.check(self.step(t, [3.05, 0.4, 1.19, 0.0, 0.0], h),+ {"A": (1.19, "*"), "F1": (0.4, "*"), "B": (3.05, "*")})+ h.remove(("A", 950)) # the oldest job exits; the others keep their contexts+ self.check(self.step(t, [3.05, 0.4, 0.0, 0.0], h), {"F1": (0.4, "*"), "B": (3.05, "*")})++ def test_already_running_processes_are_guesses_until_evidence(self):+ t = self.make()+ h = [("S", 900), ("C", 14), ("B", 13)]+ self.check(self.step(t, [0.0, 2.12, 3.05, 0.0], h), {"C": (2.12, "?"), "B": (3.05, "?")})+ h.append(("D", 950))+ self.check(self.step(t, [0.5, 0.0, 2.12, 3.05, 0.0], h), {"D": (0.5, "*"), "C": (2.12, "?"), "B": (3.05, "?")})+ # the guesses never promote themselves, however long they stay unchanged+ for _ in range(5):+ self.check(self.step(t, [0.5, 0.0, 2.12, 3.05, 0.0], h), {"D": (0.5, "*"), "C": (2.12, "?"), "B": (3.05, "?")})++ def test_no_holders_teaches_foreign_and_elimination_confirms(self):+ self.make().update(RTX, at([0.4]), [], now=self.clock) # nothing in this distro: 0.4 is foreign+ t = self.make() # a fresh start in the same boot, with a job already running+ self.check(self.step(t, [0.0, 2.0, 0.4], [("S", 900), ("X", 5)]), {"X": (2.0, "*")})+ t = self.make(boot="boot-2") # a new boot knows nothing+ self.check(self.step(t, [0.0, 2.0, 0.4], [("S", 900), ("X", 5)]), {"X": (2.0, "?")})++ def test_context_that_lags_its_process_is_still_pinned(self):+ t = self.make()+ self.step(t, [0.0], [("S", 900)])+ h = [("S", 900), ("P", 950)]+ self.check(self.step(t, [0.0], h), {}, reason="without a VM context")+ self.check(self.step(t, [0.8, 0.0], h), {"P": (0.8, "*")})++ def test_exited_process_context_is_not_handed_to_a_newcomer(self):+ t = self.make()+ self.step(t, [0.0], [("S", 900)])+ self.step(t, [1.19, 0.0], [("S", 900), ("A", 950)])+ # A exits and B starts; the host sample still shows A's context, B's hasn't appeared yet+ h = [("S", 900), ("B", 960)]+ guesses, _ = self.step(t, [1.19, 0.0], h)+ self.assertNotIn("B", guesses)+ self.check(self.step(t, [2.5, 0.0], h), {"B": (2.5, "*")})++ def test_model_loading_keeps_its_context(self):+ t = self.make()+ h = [("S", 900)]+ self.step(t, [0.0], h)+ h.append(("L", 950))+ self.check(self.step(t, [0.3, 0.0], h), {"L": (0.3, "*")})+ for gib in (2.5, 6.0, 11.0): # GBs per refresh while weights upload+ self.check(self.step(t, [gib, 0.0], h), {"L": (gib, "*")})++ def test_context_without_a_new_process_is_foreign(self):+ t = self.make()+ h = [("S", 900)]+ self.step(t, [0.0], h)+ h.append(("A", 950))+ self.step(t, [1.0, 0.0], h)+ # another distro / Docker starts something: a new context, but no new Linux process here+ self.check(self.step(t, [0.7, 1.0, 0.0], h), {"A": (1.0, "*")})+ h.append(("B", 990))+ self.check(self.step(t, [2.0, 0.7, 1.0, 0.0], h), {"A": (1.0, "*"), "B": (2.0, "*")})++ def test_equal_sizes_are_sure_even_when_order_is_not(self):+ t = self.make()+ self.check(self.step(t, [0.0, 0.4, 0.4], [("S", 900), ("F1", 5), ("F2", 6)]),+ {"F1": (0.4, "*"), "F2": (0.4, "*")})++ def test_different_adapter_resets_history(self):+ self.make().update(RTX, at([0.4]), [], now=self.clock)+ t = self.make()+ self.check(self.step(t, [0.0, 2.0, 0.4], [("S", 900), ("X", 5)]), {"X": (2.0, "*")})+ guesses, _ = t.update(0x1234, at([0.0, 2.0, 0.4]), [("S", 900), ("X", 5)], now=self.clock + 5)+ self.assertEqual(guesses["X"].confidence, "order")+++class FakeStream:+ def __init__(self, sample, status="ok"):+ self.sample, self.status = sample, status+ self.closed = False++ @property+ def ended(self):+ return self.status.startswith("unavailable")++ def latest(self):+ return self.sample++ def close(self):+ self.closed = True+++class HostRowTests(unittest.TestCase):+ def collector(self, stream):+ c = Collector.__new__(Collector) # only _add_host_rows is exercised+ c.host = stream+ c._host_luid = None+ c._host_restarted = time.time()+ c.tracker = ContextTracker(path=os.path.join(self.tmp.name, "ctx.json"), boot_id="boot", self_pid=os.getpid())+ c._own_start = time.time()+ return c++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)++ def snap(self, used=3.1 * GiB):+ linux = ProcRow(2744, "python3", "AI", ProcGpu(attributed=False), ProcDetail(2744, "python3"))+ return Snapshot(taken=1, adapter=None, adapters=[], nv=None, driver="", cuda="", vram_total=24 * GiB,+ vram_used=int(used), shared_used=0, backend="wsl", procs=[linux], host_status="")++ def test_wsl_vm_and_windows_rows(self):+ snap = self.snap()+ self.collector(FakeStream(parse_line(SAMPLE, now=time.time())))._add_host_rows(snap)+ self.assertEqual(snap.host_status, "ok")+ rows = {r.key: r for r in snap.procs}+ # Linux PID 2744 and Windows dwm PID 2744 coexist: distinct keys+ self.assertEqual(set(rows), {"2744", "w2744", "w24820"})+ vm = rows["w24820"]+ self.assertEqual((vm.name, vm.kind, vm.gpu.dedicated), ("WSL VM (vmwp.exe)", "wsl-vm", 2.4 * GiB))+ self.assertEqual((rows["w2744"].name, rows["w2744"].kind), ("dwm.exe", "compositor"))+ self.assertEqual(snap.shared_used, 0)++ text = to_text(snap)+ self.assertIn("W:24820", text)+ self.assertIn("WSL VM (vmwp.exe)", text)+ self.assertIn("exact total", text)+ data = to_dict(snap)+ self.assertEqual({p["host"] for p in data["processes"]}, {None, "windows"})+ self.assertEqual(data["host_status"], "ok")++ def test_linux_process_gets_matched_vram(self):+ # contexts newest first: this monitor's own 0-byte NVML context, then the workload (3 GB)+ busy = line([["local usage", f"pid_24820_{LUID}", v * GiB] for v in (0.0, 3.0)]+ + [["dedicated usage", LUID, 3.1 * GiB]], {"24820": "vmwp"})+ c = self.collector(FakeStream(parse_line(busy, now=time.time())))+ snap = self.snap()+ c._add_host_rows(snap)+ row = next(r for r in snap.procs if not r.host)+ self.assertEqual((row.gpu.inferred, row.gpu.inferred_by), (3.0 * GiB, "consistent"))+ self.assertFalse(row.gpu.attributed) # engines are still unknown+ text = to_text(snap)+ self.assertIn("3.00 GB*", text)+ self.assertIn("* matched", text)+ data = to_dict(snap)["processes"][1]+ self.assertEqual((data["vram_inferred_bytes"], data["vram_inferred_by"]), (3.0 * GiB, "consistent"))++ def test_order_guess_is_marked(self):+ # an extra (foreign) context and no history: placement is a guess+ busy = line([["local usage", f"pid_24820_{LUID}", v * GiB] for v in (0.0, 3.0, 0.4)]+ + [["dedicated usage", LUID, 3.1 * GiB]], {"24820": "vmwp"})+ c = self.collector(FakeStream(parse_line(busy, now=time.time())))+ snap = self.snap()+ c._add_host_rows(snap)+ row = next(r for r in snap.procs if not r.host)+ self.assertEqual(row.gpu.inferred_by, "order")+ self.assertIn("3.00 GB?", to_text(snap))+ self.assertIn("order guess", to_text(snap))++ def test_split_reason_is_reported(self):+ snap = self.snap() # SAMPLE has 2 vmwp contexts; add Linux rows until there are more holders+ snap.procs += [ProcRow(p, "python3", "AI", ProcGpu(attributed=False), ProcDetail(p, "python3"))+ for p in (2745, 2746)]+ self.collector(FakeStream(parse_line(SAMPLE, now=time.time())))._add_host_rows(snap)+ self.assertIn("without a VM context", snap.wsl_split)+ self.assertIn("Linux VRAM split:", to_text(snap))++ def test_unmatched_adapter_adds_nothing(self):+ snap = self.snap(used=12 * GiB)+ c = self.collector(FakeStream(parse_line(SAMPLE, now=time.time())))+ c._add_host_rows(snap)+ self.assertEqual(snap.host_status, "starting") # retried for a while first+ c._host_restarted -= 60+ snap = self.snap(used=12 * GiB)+ c._add_host_rows(snap)+ self.assertTrue(snap.host_status.startswith("unmatched"))+ self.assertEqual(len(snap.procs), 1)+ self.assertIn("unmatched", to_text(snap))++ def test_adapter_match_is_kept_while_memory_moves(self):+ c = self.collector(FakeStream(parse_line(SAMPLE, now=time.time())))+ c._add_host_rows(self.snap())+ moving = self.snap(used=12 * GiB) # a model loading between the NVML and host readings+ c._add_host_rows(moving)+ self.assertEqual(moving.host_status, "ok")+ self.assertEqual(len(moving.procs), 3)++ def test_late_samples_stay_visible_and_say_so(self):+ snap = self.snap()+ self.collector(FakeStream(parse_line(SAMPLE, now=time.time() - 8)))._add_host_rows(snap)+ self.assertTrue(snap.host_data)+ self.assertIn("8s old", snap.host_status)+ self.assertEqual(len(snap.procs), 3)++ def test_ended_stream_is_restarted(self):+ dead = FakeStream(None, status="unavailable (counter stream ended)")+ c = self.collector(dead)+ c._host_restarted = time.time() - 60+ with patch.object(collector_mod, "HostStream", return_value=FakeStream(None, "starting")) as stream:+ c._add_host_rows(self.snap())+ self.assertTrue(dead.closed)+ stream.assert_called_once()++ def test_no_sample_yet_is_starting(self):+ snap = self.snap()+ self.collector(FakeStream(None, status="starting"))._add_host_rows(snap)+ self.assertEqual(snap.host_status, "starting")++ def test_interop_off_and_flag_off_never_start_powershell(self):+ with patch.object(collector_mod, "BACKEND", "wsl"), patch.object(collector_mod, "enumerate_adapters",+ return_value=[]), \+ patch.object(collector_mod, "GpuCounters"), patch.object(collector_mod, "Nvml"), \+ patch.object(collector_mod, "HostStream") as stream:+ with patch.object(collector_mod, "interop_enabled", return_value=False):+ self.assertEqual(Collector().host_status, "off (WSL interop is disabled)")+ with patch.object(collector_mod, "interop_enabled", return_value=True):+ self.assertEqual(Collector(host=False).host_status, "off (--no-host)")+ stream.assert_not_called()+ Collector()+ stream.assert_called_once()+++if __name__ == "__main__":+ unittest.main()diff --git a/tools/build_portable.py b/tools/build_portable.pyindex fd70cce..522a077 100644--- a/tools/build_portable.py+++ b/tools/build_portable.py@@ -1,4 +1,4 @@-"""Build a native Windows console executable and ZIP its complete runtime."""+"""Build a native console executable (Windows or Linux) and archive its complete runtime."""from __future__ import annotations@@ -12,20 +12,34 @@ import structimport subprocessimport sysimport sysconfig+import tarfileimport tempfileimport tomllibimport zipfileROOT = Path(__file__).resolve().parents[1]-MACHINES = {"x64": 0x8664, "arm64": 0xAA64}+MACHINES = {"x64": 0x8664, "arm64": 0xAA64} # PE machine+ELF_MACHINES = {"x64": 0x3E, "arm64": 0xB7} # ELF e_machine+# Provided by Windows or the installed NVIDIA driver, never by the portable app.+FORBIDDEN = ("nvml.dll", "nvcuda.dll", "dxgi.dll", "pdh.dll", "libnvidia-ml.so", "libcuda.so", "libdxcore.so")+PLATFORMS = {"win-amd64": ("windows", "x64"), "win-arm64": ("windows", "arm64"),+ "linux-x86_64": ("linux", "x64"), "linux-aarch64": ("linux", "arm64")}-def architecture(platform_tag: str) -> str:- platforms = {"win-amd64": "x64", "win-arm64": "arm64"}- if platform_tag not in platforms:+def target(platform_tag: str) -> tuple[str, str]:+ if platform_tag not in PLATFORMS:raise ValueError(f"Unsupported build interpreter: {platform_tag}")- return platforms[platform_tag]+ return PLATFORMS[platform_tag]+++def architecture(platform_tag: str) -> str:+ return target(platform_tag)[1]+++def is_forbidden(name: str) -> bool:+ name = name.lower()+ return any(name == f or name.startswith(f + ".") for f in FORBIDDEN)def validate_version(version: str, tag: str | None = None) -> None:@@ -49,10 +63,19 @@ def check_executable(path: Path, arch: str) -> None:raise ValueError(f"Expected {arch} PE machine {MACHINES[arch]:#06x}, got {machine:#06x}")-def create_archive(bundle: Path, output: Path, version: str, arch: str) -> Path:- validate_version(version)- check_executable(bundle / "gputaskman.exe", arch)- forbidden = {"nvml.dll", "nvcuda.dll", "dxgi.dll", "pdh.dll"}+def check_elf(path: Path, arch: str) -> None:+ with path.open("rb") as binary:+ header = binary.read(20)+ if len(header) != 20 or header[:4] != b"\x7fELF":+ raise ValueError(f"Not an ELF executable: {path}")+ if header[4] != 2 or header[5] != 1:+ raise ValueError(f"Expected a 64-bit little-endian ELF: {path}")+ machine = struct.unpack_from("<H", header, 18)[0]+ if machine != ELF_MACHINES[arch]:+ raise ValueError(f"Expected {arch} ELF machine {ELF_MACHINES[arch]:#06x}, got {machine:#06x}")+++def _bundle_files(bundle: Path) -> list[Path]:# Editable-install origins contain build-machine paths and are not needed at runtime.files = sorted(path for path in bundle.rglob("*")@@ -60,17 +83,49 @@ def create_archive(bundle: Path, output: Path, version: str, arch: str) -> Path:and not (path.name == "direct_url.json" and path.parent.name.endswith(".dist-info")))for path in files:- if path.name.lower() in forbidden:- raise ValueError(f"Driver/system DLL must not be distributed: {path}")+ if is_forbidden(path.name):+ raise ValueError(f"Driver/system library must not be distributed: {path}")+ return files+++def _checksum(archive: Path) -> None:+ with archive.open("rb") as packaged:+ digest = hashlib.file_digest(packaged, "sha256").hexdigest()+ Path(f"{archive}.sha256").write_text(f"{digest} {archive.name}\n", encoding="utf-8")+++def create_linux_archive(bundle: Path, output: Path, version: str, arch: str) -> Path:+ """tar.gz keeps the executable bit, which a ZIP made with zipfile would drop."""+ validate_version(version)+ check_elf(bundle / "gputaskman", arch)+ files = _bundle_files(bundle)+ name = f"gputaskman-{version}-linux-{arch}"+ output.mkdir(parents=True, exist_ok=True)+ archive = output / f"{name}.tar.gz"++ def normalize(info: tarfile.TarInfo) -> tarfile.TarInfo:+ info.uid = info.gid = 0+ info.uname = info.gname = ""+ return info++ with tarfile.open(archive, "w:gz") as packed:+ for path in files:+ packed.add(path, str(Path(name) / path.relative_to(bundle)), recursive=False, filter=normalize)+ _checksum(archive)+ return archive+++def create_archive(bundle: Path, output: Path, version: str, arch: str) -> Path:+ validate_version(version)+ check_executable(bundle / "gputaskman.exe", arch)+ files = _bundle_files(bundle)name = f"gputaskman-{version}-windows-{arch}"output.mkdir(parents=True, exist_ok=True)archive = output / f"{name}.zip"with zipfile.ZipFile(archive, "w", compression=zipfile.ZIP_DEFLATED) as zipped:for path in files:zipped.write(path, Path(name) / path.relative_to(bundle))- with archive.open("rb") as packaged:- digest = hashlib.file_digest(packaged, "sha256").hexdigest()- archive.with_suffix(".zip.sha256").write_text(f"{digest} {archive.name}\n", encoding="utf-8")+ _checksum(archive)return archive@@ -81,9 +136,20 @@ def nvidia_license(source: str) -> str:return header + boundary-def add_notices(bundle: Path) -> None:+def python_license() -> Path:+ base = Path(sys.base_prefix)+ candidates = [base / "LICENSE.txt", Path(sysconfig.get_paths()["stdlib"]) / "LICENSE.txt",+ base / "share" / "doc" / f"python{sys.version_info.major}.{sys.version_info.minor}" / "LICENSE"]+ for path in candidates:+ if path.is_file():+ return path+ raise RuntimeError("Python's license text was not found")+++def add_notices(bundle: Path, system: str = "windows") -> None:+ sep = "\\" if system == "windows" else "/"shutil.copy2(ROOT / "LICENSE", bundle / "LICENSE")- shutil.copy2(Path(sys.base_prefix) / "LICENSE.txt", bundle / "PYTHON-LICENSE.txt")+ shutil.copy2(python_license(), bundle / "PYTHON-LICENSE.txt")installer = metadata.distribution("pyinstaller")license_files = [path for path in installer.files or ()@@ -104,16 +170,38 @@ def add_notices(bundle: Path) -> None:)(bundle / "THIRD-PARTY-NOTICES.txt").write_text("Python: see PYTHON-LICENSE.txt.\n"- "PyInstaller bootloader: see licenses\\pyinstaller (including its exception).\n"- "NVIDIA Python bindings: see licenses\\nvidia-ml-py.\n"- "Runtime package metadata and license texts are included in _internal\\*.dist-info.\n"- "NVIDIA and Windows DLLs are provided by the installed driver and operating system.\n",+ f"PyInstaller bootloader: see licenses{sep}pyinstaller (including its exception).\n"+ f"NVIDIA Python bindings: see licenses{sep}nvidia-ml-py.\n"+ f"Runtime package metadata and license texts are included in _internal{sep}*.dist-info.\n"+ "NVIDIA libraries are provided by the installed driver, system libraries by the operating system.\n",encoding="utf-8",)+README_LINUX = """GPU Task Manager {version} - Linux {arch}++Extract the whole archive and keep _internal beside gputaskman:++ tar -xzf gputaskman-{version}-linux-{arch}.tar.gz+ cd gputaskman-{version}-linux-{arch}+ ./gputaskman+ ./gputaskman --once+ ./gputaskman --json++Press q to quit the interactive display.+Requires an NVIDIA GPU and driver (NVML, libnvidia-ml.so.1, comes with the driver) and glibc 2.35++(Ubuntu 22.04, Debian 12, RHEL 10 or newer). Works natively, in containers, and in WSL; under WSL,+Windows host counters are read through interop when it is enabled (see the documentation).+No Python, CUDA Toolkit, models, or root is required; other users' processes need sudo to inspect.+No drivers or inference servers are bundled.+Snapshots can contain local paths and model names; redact before sharing.++Documentation: https://github.com/shanselman/gputaskman+"""++def build(output: Path, arch: str, tag: str | None = None) -> Path:- actual = architecture(sysconfig.get_platform())+ system, actual = target(sysconfig.get_platform())if actual != arch:raise ValueError(f"Requested {arch}, but this Python interpreter is {actual}")version = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8"))["project"]["version"]@@ -130,7 +218,10 @@ def build(output: Path, arch: str, tag: str | None = None) -> Path:check=True,)bundle = work / "dist" / "gputaskman"- add_notices(bundle)+ add_notices(bundle, system)+ if system == "linux":+ (bundle / "README.txt").write_text(README_LINUX.format(version=version, arch=arch), encoding="utf-8")+ return create_linux_archive(bundle, output, version, arch)(bundle / "README.txt").write_text(f"GPU Task Manager {version} - Windows {arch}\n\n""Extract the entire ZIP before running. Keep _internal beside gputaskman.exe.\n"diff --git a/tools/portable.spec b/tools/portable.specindex 2a72a0c..85154e8 100644--- a/tools/portable.spec+++ b/tools/portable.spec@@ -9,12 +9,16 @@ analysis = Analysis(datas=collect_data_files("textual") + copy_metadata("gputaskman", recursive=True),)-# These belong to Windows or the installed NVIDIA driver, not the portable app.-driver_dlls = {"nvml.dll", "nvcuda.dll", "dxgi.dll", "pdh.dll"}-analysis.binaries = [- entry for entry in analysis.binaries- if Path(entry[0]).name.lower() not in driver_dlls-]+# These belong to the operating system or the installed NVIDIA driver, not the portable app.+driver_libs = ("nvml.dll", "nvcuda.dll", "dxgi.dll", "pdh.dll", "libnvidia-ml.so", "libcuda.so", "libdxcore.so")+++def is_driver_lib(name):+ name = name.lower()+ return any(name == lib or name.startswith(lib + ".") for lib in driver_libs)+++analysis.binaries = [entry for entry in analysis.binaries if not is_driver_lib(Path(entry[0]).name)]pyz = PYZ(analysis.pure)exe = EXE(