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
Identify loaded models by evidence, cheaply, across runtimes
Scott Hanselmanf2a74924ad89
diff --git a/README.md b/README.mdindex 2e56e16..67cca9d 100644--- a/README.md+++ b/README.md@@ -57,8 +57,9 @@ compatible dependencies; the uv route uses the checked-in lockfile.- **Device view:** VRAM usage, GPU activity, memory activity, PCIe traffic, temperature, power and clocks.- **Process view:** local GPU memory, GPU-accessible system RAM, estimated non-resident commit,engine activity, and detected runtimes such as CUDA, Vulkan, Direct3D, ggml and ONNX Runtime.-- **LLM inspector:** model name, architecture, quantization, layer count, weights, estimated KV cost,- and buffer sizes from compatible load logs.+- **Model inspector:** which model each process holds (LLM, decision, embedding, or speech), how+ it was identified, architecture, quantization, layer count, weights, estimated KV cost, and+ buffer sizes from compatible load logs.- **Live server hints:** context size, busy slots, throughput when available, and friendly Ollamaor LM Studio model names.- **Scriptable output:** one-shot text and JSON, using the same collector as the TUI.@@ -160,14 +161,49 @@ those bytes out of VRAM. The value is also less reliable when fallback countersMemory labels currently use `GB` / `MB` for binary units (GiB / MiB). The top-level `MemBW`reading is NVML's memory-activity percentage, **not measured bandwidth in GB/s**.-## LLM support+## LLM and model support| Runtime | Current support ||---|---|-| llama.cpp / llama-server | GGUF discovery, CLI settings, buffer logs, local API state; exercised live |-| Ollama | Bundled llama-server runners, mapped GGUF blobs, parent `/api/ps`, compatible `server.log`; exercised live |-| LM Studio | Process/file discovery and `/api/v0/models` probing; not yet validated end to end |-| Other AI runtimes | DLL and candidate model-file detection only; no general tensor inventory |+| llama.cpp / llama-server | GGUF discovery, CLI settings, buffer logs, `/props` + `/v1/models` state; exercised live |+| Ollama | Bundled runners, mapped GGUF blobs named from Ollama manifests (`qwen3:14b`), parent `/api/ps`, compatible `server.log`; exercised live |+| LM Studio | Mapped files named from its models folder, `/api/v1/models` (falls back to `/api/v0/models`); tested with fixture responses, not yet end to end |+| Hugging Face cache | `models--org--repo` paths are named `org/repo` |+| Other AI runtimes | DLL detection, plus model files installed with the app (marked *not proven loaded*) |++### How models are identified++Every model row shows its **evidence**, strongest first:++| Evidence | Meaning |+|---|---|+| `api` | The runtime's local API reports the model as loaded |+| `mapped` | Windows shows the file memory-mapped into the process right now |+| `cmdline` | The file was a launch argument (`-m model.gguf`) |+| `installed` | Found in the app's install or data folder; nothing proves it is loaded |++Two sources including `api` or `mapped` show as **confirmed**. Model-store folders only supply a+friendly name. The model *kind* comes from GGUF header keys, not filenames: `decision.type` marks a+decision model (for example [Laya](https://huggingface.co/ggml-org/Laya-GGUF)), `pooling_type`+an embedding model or reranker, `stt.*` a speech model, and a causal model with layers and a+trained context an LLM. llama-server's `/v1/models` `output_modalities` (`text`, `decisions`)+confirms it. Non-causal encoders such as Laya allocate no KV cache, so none is estimated.++Some runtimes (ONNX Runtime, whisper.cpp) read a model into memory and close the file. Windows then+has no record of which file is loaded, so the app's installed models are listed as candidates only.++Identification is designed to stay cheap. Measured on one Windows machine:++| Probe | Cost | Used |+|---|---|---|+| Process list, command line, listening ports | under 1 ms | Once per process / every 5 s |+| Memory-map scan (DLLs + mapped files) | 1-50 ms per process | New processes, a 64 MiB / 10% memory change, or every 2 min; at most 150 ms per refresh |+| GGUF header, model-store manifests | ms, cached | Once per file / every 60 s |+| Local API probes | ms, local only | llama-server `/v1/models` only when its model path changes |+| `psutil.open_files()` | 0.6-2.5 s per process | Never |++With two llama-servers running, a steady refresh costs roughly 15-30 ms of CPU (about 340 ms before+process details were cached).For log-reported buffer sizes, start your own llama-server with logging enabled:@@ -181,9 +217,9 @@ llama.cpp build. Prefer an absolute log path if the server and monitor use diffeworking directories.The collector probes existing local listening ports with GET requests to `/props`, `/slots`,-`/metrics`, `/api/ps`, and `/api/v0/models`. Endpoints may be absent, disabled, or authenticated;-other evidence is still useful. It does not launch `ollama`, `lms`, or an inference request.-Throughput may update only after a request completes.+`/metrics`, `/v1/models`, `/api/ps`, `/api/v1/models`, and `/api/v0/models`. Endpoints may be+absent, disabled, or authenticated; other evidence is still useful. It does not launch `ollama`,+`lms`, or an inference request. Throughput may update only after a request completes.Ollama's local `server.log` is considered when one Ollama runner is detected. Log formats,rotation, and stale load blocks can affect attribution, so compare the reported model and@@ -250,15 +286,15 @@ downloads are bundled in this repository.| `pdh.py` / `dxgi.py` | Windows counters and adapter enumeration || `nvml.py` | NVIDIA device readings || `procinfo.py` | Runtime, mapped-file, and process discovery |-| `gguf.py` | Model metadata and size estimates |+| `stores.py` | Friendly names from Ollama, LM Studio, and Hugging Face model stores |+| `gguf.py` | Model metadata, kind, and size estimates || `llm.py` | Buffer logs, local server probing, and breakdowns || `collector.py` | Shared snapshot collection || `app.py` / `report.py` / `cli.py` | TUI, text/JSON, and command-line entry points |## Next-- Decision models and non-LLM workloads: identify reliable model metadata and distinguish- classification, embedding, speech, and other inference workloads without guessing from a DLL.+- 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.- Live throughput deltas, LM Studio validation, and per-model context accounting.diff --git a/src/gputaskman/app.py b/src/gputaskman/app.pyindex 1cd65e8..ca9e3bf 100644--- a/src/gputaskman/app.py+++ b/src/gputaskman/app.py@@ -21,7 +21,8 @@ from .collector import Collector, ProcRow, Snapshotfrom .llm import gbKIND_STYLE = {- "LLM": "bold magenta", "AI": "medium_purple1", "compute": "orange3", "3D/game": "green3",+ "LLM": "bold magenta", "decision": "bold orchid", "embedding": "plum2", "speech": "light_sky_blue1",+ "AI": "medium_purple1", "compute": "orange3", "3D/game": "green3","video": "yellow", "browser": "dodger_blue2", "app": "cyan", "compositor": "grey50","kernel": "grey50", "system": "grey50",}@@ -55,9 +56,14 @@ HELP_MD = """\| **Per-process** VRAM, spill to RAM, per-engine load | Windows WDDM counters (dxgkrnl) | every API incl. **CUDA** || **Which runtime** (CUDA, Vulkan, D3D12, ggml, ONNX, PyTorch...) | DLLs mapped in the process | everything || **Which model file** | memory-mapped files + command line | llama.cpp, LM Studio, Ollama, llama-cpp-python |+| **Model name & kind** (LLM, decision, embedding, speech) | GGUF header, Ollama/LM Studio/Hugging Face stores, local server APIs | GGUF family || **Weights / KV cache / compute** split | GGUF header math, llama.cpp/Ollama logs, local server APIs | GGUF/llama.cpp family || Per-texture / per-buffer names | needs a debugger (PIX, Nsight) attached to the app | games, 3D apps |+**Evidence** shows how a model was identified: `api` (the runtime says it is loaded), `mapped`+(Windows shows the file mapped into the process right now), `cmdline` (a launch argument only).+Two sources, including `api` or `mapped`, is shown as *confirmed*.+**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.@@ -323,12 +329,15 @@ class GpuTaskManager(App):out.append(legend)if v.models:mt = Table(box=None, padding=(0, 1), show_edge=False, header_style="bold grey70")- for col in ("", "model", "arch", "params", "quant", "layers", "train ctx", "on GPU (est)", "file"):+ for col in ("", "model", "arch", "params", "quant", "layers", "train ctx", "on GPU (est)", "evidence", "file"):mt.add_column(col)- for g in v.models:- mt.add_row(Text(g.kind, style="magenta"), g.name, g.arch, g.params_label, g.quant,+ for i, g in enumerate(v.models):+ f = v.files[i] if i < len(v.files) else None+ kind = g.kind + (f" ({g.decision_type})" if g.decision_type else "")+ mt.add_row(Text(kind, style="magenta"), v.label(i), g.arch, g.params_label, g.quant,str(g.n_layers or ""), f"{g.ctx_train:,}" if g.ctx_train else "",- gb(g.gpu_weight_bytes()), Text(os.path.basename(g.path), style="grey50", overflow="ellipsis"))+ gb(g.gpu_weight_bytes()), Text(f.evidence if f else "", style="green"),+ Text(os.path.basename(g.path), style="grey50", overflow="ellipsis"))out.append(mt)for f in v.other_files:out.append(Text(f"file: {f.path} ({gb(f.size)})", style="grey62"))@@ -345,14 +354,19 @@ class GpuTaskManager(App):st.append(f" prompt {sv.prompt_tok_s:.0f} tok/s")for m in sv.models[:4]:if sv.kind == "lmstudio":- st.append(f"\n loaded: {m.get('id')} {m.get('quantization', '')} ctx {m.get('loaded_context_length') or m.get('max_context_length', '?')}")+ st.append(f"\n loaded: {m['name']} {m.get('type') or ''} {m.get('quant') or ''} ctx {m.get('ctx') or '?'}")out.append(st)for n in v.notes:out.append(Text("• " + n, style="bold red" if n.startswith("!") else "grey70"))else:out.append(Text(EXPLAIN.get(r.kind, ""), style="grey70"))for m in r.detail.models:- out.append(Text(f"file: {m.path} ({gb(m.size)}, {m.source})", style="magenta"))+ out.append(Text(f"file: {m.store_name or m.path} ({gb(m.size)}, {m.evidence})", style="magenta"))+ if r.detail.candidates:+ out.append(Text("This runtime read its model into memory and closed the file, so Windows cannot show "+ "which one is loaded. Model files installed with this app:", style="grey70"))+ for m in r.detail.candidates:+ out.append(Text(f" {m.store_name or m.path} ({gb(m.size)})", style="grey62"))if r.detail.ports:out.append(Text("listening: " + ", ".join(map(str, r.detail.ports[:8])), style="grey50"))if r.detail.cmdline:diff --git a/src/gputaskman/cli.py b/src/gputaskman/cli.pyindex 220de9c..c224cc7 100644--- a/src/gputaskman/cli.py+++ b/src/gputaskman/cli.py@@ -27,7 +27,7 @@ def main() -> None:from .collector import Collectorfrom .report import dump- c = Collector(args.gpu)+ c = Collector(args.gpu, scan_budget=None) # one-shot: identify everything in this sampletry:time.sleep(1.0) # engine utilization is a rate; needs two samplesprint(dump(c.sample(), args.json))diff --git a/src/gputaskman/collector.py b/src/gputaskman/collector.pyindex 53d9e0c..a3a2f81 100644--- a/src/gputaskman/collector.py+++ b/src/gputaskman/collector.py@@ -2,16 +2,17 @@from __future__ import annotations+import osimport timefrom dataclasses import dataclass, fieldimport psutilfrom .dxgi import VENDOR_NVIDIA, Adapter, enumerate_adapters-from .llm import LlmView, ServerProber, build_view, ollama_log_path+from .llm import LlmView, ServerProber, build_view, gb, ollama_log_pathfrom .nvml import Nvml, NvDevicefrom .pdh import GpuCounters, ProcGpu-from .procinfo import ProcDetail, ProcInspector, classify+from .procinfo import AI_KINDS, ProcDetail, ProcInspector, classifyMiB = 1 << 20@@ -34,16 +35,17 @@ class ProcRow:"""One-line 'what's in there' summary for the process table."""if self.llm and self.llm.models:parts = []- for g in self.llm.models:- label = g.metadata.get("general.basename") or g.name- if g.kind == "model":- parts.append(f"{label} {g.params_label} {g.quant}")- else:+ for i, g in enumerate(self.llm.models):+ if g.kind in ("vision projector", "LoRA adapter"):parts.append(f"+{g.kind}")+ else:+ parts.append(f"{self.llm.label(i)} {g.params_label} {g.quant}")return ", ".join(parts)if self.detail.models:- import os- return ", ".join(os.path.basename(m.path) for m in self.detail.models[:2])+ return ", ".join(m.store_name or os.path.basename(m.path) for m in self.detail.models[:2])+ if self.detail.candidates:+ return "installed (unproven): " + ", ".join(+ f"{m.store_name or os.path.basename(m.path)} {gb(m.size)}" for m in self.detail.candidates[:2])return {"compositor": "desktop back buffers + composed frames","kernel": "driver/kernel allocations",@@ -72,13 +74,15 @@ class Snapshot:class Collector:- DEEP_TOP_N = 25 # deep-scan (memory maps) the top N VRAM users each cycle (throttled per process)+ DEEP_TOP_N = 25 # memory-map candidates: the top N VRAM users plus anything busy+ SCAN_BUDGET = 0.15 # seconds of memory-map scanning per sample; leftovers wait for the next sample- def __init__(self, gpu_index: int = 0) -> None:+ def __init__(self, gpu_index: int = 0, scan_budget: float | None = SCAN_BUDGET) -> None:self.counters = GpuCounters()self.nvml = Nvml()self.inspector = ProcInspector()self.prober = ServerProber()+ self.scan_budget = scan_budget # None = scan every candidate now (one-shot output)self.adapters = [a for a in enumerate_adapters() if not a.software]nv = [a for a in self.adapters if a.vendor_id == VENDOR_NVIDIA] or self.adaptersnv.sort(key=lambda a: -a.dedicated_vram)@@ -86,17 +90,19 @@ class Collector:self.gpu_index = gpu_indexdef _parent_ports(self, pid: int, depth: int = 2) -> list[int]:- ports: list[int] = []- try:- p = psutil.Process(pid)- for _ in range(depth):- p = p.parent()- if p is None:- break- ports += self.inspector.get(p.pid, deep=False).ports- except (psutil.Error, OSError):- pass- return ports+ d = self.inspector.get(pid)+ if d.parents is None:+ d.parents = []+ try:+ p = psutil.Process(pid)+ for _ in range(depth):+ p = p.parent()+ if p is None:+ break+ d.parents.append(p.pid)+ except (psutil.Error, OSError):+ pass+ return [port for ppid in d.parents for port in self.inspector.ports(ppid)]def sample(self) -> Snapshot:per_luid, adapters = self.counters.sample()@@ -118,18 +124,23 @@ class Collector:if g.dedicated >= MiB or g.gpu_pct >= 0.5 or g.shared >= 16 * MiB or g.paged_out >= 16 * MiB]live.sort(key=lambda x: -x[1].dedicated)deep_pids = {pid for pid, _ in live[: self.DEEP_TOP_N]} | {pid for pid, g in live if g.gpu_pct >= 2}+ deadline = None if self.scan_budget is None else time.perf_counter() + self.scan_budgetollama_runners = []- for pid, g in live:- d = self.inspector.get(pid, deep=pid in deep_pids)+ for pid, g in live: # largest VRAM first, so the budget goes to what matters+ d = self.inspector.get(pid)+ mem = g.dedicated + g.shared+ if (pid in deep_pids and (deadline is None or time.perf_counter() < deadline)+ and self.inspector.needs_scan(d, mem)):+ self.inspector.scan(d, mem)row = ProcRow(pid=pid, name=d.name, kind=classify(d, g.engines), gpu=g, detail=d)snap.procs.append(row)# Old Ollama: "ollama.exe runner ..."; newer Ollama: its own lib\ollama\llama-server.exe- if row.kind == "LLM" and ("\\ollama\\" in d.exe.lower() or- (d.name.lower().startswith("ollama") and "runner" in d.cmdline)):+ if row.kind in AI_KINDS and ("\\ollama\\" in d.exe.lower() or+ (d.name.lower().startswith("ollama") and "runner" in d.cmdline)):ollama_runners.append(row)for row in snap.procs:- if row.kind not in ("LLM", "AI") or not (row.detail.models or row.kind == "LLM"):+ if 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 processdiff --git a/src/gputaskman/gguf.py b/src/gputaskman/gguf.pyindex 6917385..6075aeb 100644--- a/src/gputaskman/gguf.py+++ b/src/gputaskman/gguf.py@@ -50,15 +50,31 @@ class GgufInfo:@propertydef kind(self) -> str:+ """What the file is, from header keys only (most specific first)."""t = self.metadata.get("general.type", "model")if self.arch == "clip" or t == "mmproj":return "vision projector"if t == "adapter":return "LoRA adapter"- if self.metadata.get("bert.pooling_type") is not None or self.meta("pooling_type") is not None:- return "embedding model"+ if self.decision_type:+ return "decision model"+ pooling = self.meta("pooling_type")+ if pooling is not None:+ return "reranker" if pooling == 4 else "embedding model" # 4 = LLAMA_POOLING_TYPE_RANK+ if any(k.startswith("stt.") for k in self.metadata):+ return "speech model"+ if self.n_layers and self.ctx_train and self.causal:+ return "LLM"return "model"+ @property+ def decision_type(self) -> str | None:+ return self.meta("decision.type")++ @property+ def causal(self) -> bool:+ return self.meta("attention.causal", True) is not False+@propertydef name(self) -> str:return self.metadata.get("general.name") or os.path.basename(self.path)diff --git a/src/gputaskman/llm.py b/src/gputaskman/llm.pyindex af1db16..4968221 100644--- a/src/gputaskman/llm.py+++ b/src/gputaskman/llm.py@@ -2,13 +2,15 @@Evidence, best first:1. llama.cpp / Ollama load logs -> exact per-device buffer sizes- 2. Local server endpoints -> llama-server /props,/slots,/metrics; Ollama /api/ps; LM Studio /api/v0/models+ 2. Local server endpoints -> llama-server /props,/v1/models,/slots,/metrics; Ollama /api/ps;+ LM Studio /api/v1/models (falls back to /api/v0/models)3. GGUF header + command line -> estimates (weights per layer, KV bytes per token x context)The process's real VRAM total always comes from Windows, so the remainder is never invented."""from __future__ import annotations+import dataclassesimport jsonimport osimport re@@ -16,8 +18,8 @@ import timeimport urllib.requestfrom dataclasses import dataclass, field-from .gguf import GgufInfo, read_gguf-from .procinfo import MappedModel, ProcDetail+from .gguf import GgufInfo, is_gguf, read_gguf+from .procinfo import MappedModel, ProcDetail, make_modelMiB = 1 << 20KV_TYPE_BYTES = {"f32": 4, "f16": 2, "bf16": 2, "q8_0": 34 / 32, "q4_0": 18 / 32, "q4_1": 20 / 32,@@ -136,7 +138,8 @@ class ServerInfo:slots_busy: int | None = Nonegen_tok_s: float | None = Noneprompt_tok_s: float | None = None- models: list[dict] = field(default_factory=list) # ollama / lmstudio loaded models+ model_path: str | None = None # llama-server: the file it says it loaded+ models: list[dict] = field(default_factory=list) # normalized: name, type, quant, ctx, size, size_vram, pathdef _metric(text: str, name: str) -> float | None:@@ -144,14 +147,64 @@ def _metric(text: str, name: str) -> float | None:return float(m[1]) if m else None-def probe_server(port: int) -> ServerInfo | None:+def _model_entry(name, type_=None, quant=None, ctx=None, size=None, size_vram=None, path=None) -> dict:+ return {"name": name, "type": type_, "quant": quant, "ctx": ctx, "size": size, "size_vram": size_vram, "path": path}+++_MODALITY = {"text": "llm", "decisions": "decision", "embeddings": "embedding", "embedding": "embedding"}+++def llama_server_models(v1: dict, model_path: str | None) -> list[dict]:+ out = []+ for m in v1.get("data") or []:+ outs = (m.get("architecture") or {}).get("output_modalities") or []+ meta = m.get("meta") or {}+ out.append(_model_entry(os.path.basename(m.get("id") or model_path or "?"),+ next((_MODALITY.get(o, o) for o in outs), None),+ meta.get("ftype"), meta.get("n_ctx"), meta.get("size"), None, model_path))+ return out+++def ollama_models(ps: dict) -> list[dict]:+ return [_model_entry(m.get("name"), "llm", (m.get("details") or {}).get("quantization_level"),+ m.get("context_length"), m.get("size"), m.get("size_vram"))+ for m in ps.get("models") or []]+++def lmstudio_models(v1: dict | None, v0: dict | None) -> list[dict] | None:+ """Loaded models from LM Studio's /api/v1/models (preferred) or /api/v0/models."""+ if isinstance(v1, dict) and isinstance(v1.get("models"), list):+ out = []+ for m in v1["models"]:+ for inst in m.get("loaded_instances") or []:+ q = m.get("quantization") or {}+ t = m.get("type")+ if t == "decision" and m.get("decision_type"):+ t = f"decision ({m['decision_type']})"+ out.append(_model_entry(inst.get("id") or m.get("key"), t, q.get("name"),+ (inst.get("config") or {}).get("context_length"), m.get("size_bytes")))+ return out+ if isinstance(v0, dict) and isinstance(v0.get("data"), list):+ return [_model_entry(m.get("id"), m.get("type"), m.get("quantization"),+ m.get("loaded_context_length") or m.get("max_context_length"))+ for m in v0["data"] if m.get("state") == "loaded"]+ return None+++def probe_server(port: int, prev: ServerInfo | None = None) -> ServerInfo | None:+ """Read-only GETs. Never calls inference, load or download endpoints."""base = f"http://127.0.0.1:{port}"props = _get(base + "/props")if isinstance(props, dict) and ("default_generation_settings" in props or "model_path" in props):- s = ServerInfo("llama-server", base)+ s = ServerInfo("llama-server", base, model_path=props.get("model_path"))dgs = props.get("default_generation_settings") or {}s.n_ctx = dgs.get("n_ctx") or props.get("n_ctx")s.slots_total = props.get("total_slots")+ if prev and prev.kind == "llama-server" and prev.model_path == s.model_path:+ s.models = prev.models # identity only changes when the model does+ else:+ v1 = _get(base + "/v1/models")+ s.models = llama_server_models(v1, s.model_path) if isinstance(v1, dict) else []slots = _get(base + "/slots")if isinstance(slots, list):s.slots_total = len(slots)@@ -163,10 +216,12 @@ def probe_server(port: int) -> ServerInfo | None:return sps = _get(base + "/api/ps")if isinstance(ps, dict) and isinstance(ps.get("models"), list):- return ServerInfo("ollama", base, models=ps["models"])- lms = _get(base + "/api/v0/models")- if isinstance(lms, dict) and isinstance(lms.get("data"), list):- loaded = [m for m in lms["data"] if m.get("state") == "loaded"]+ return ServerInfo("ollama", base, models=ollama_models(ps))+ # Older LM Studio answers unknown endpoints with HTTP 200 + {"error": ...}, so fall back on shape, not status+ loaded = lmstudio_models(_get(base + "/api/v1/models"), None)+ if loaded is None:+ loaded = lmstudio_models(None, _get(base + "/api/v0/models"))+ if loaded is not None:return ServerInfo("lmstudio", base, models=loaded)return None@@ -178,6 +233,7 @@ class ServerProber:def __init__(self) -> None:self._cache: dict[int, tuple[float, ServerInfo | None]] = {}+ self._last: dict[int, ServerInfo] = {}def get(self, ports: list[int]) -> ServerInfo | None:now = time.time()@@ -186,8 +242,10 @@ class ServerProber:if hit and now - hit[0] < (self.TTL_HIT if hit[1] else self.TTL_MISS):info = hit[1]else:- info = probe_server(port)+ info = probe_server(port, self._last.get(port))self._cache[port] = (now, info)+ if info:+ self._last[port] = infoif info:return inforeturn None@@ -207,6 +265,7 @@ class Segment:@dataclassclass LlmView:models: list[GgufInfo] = field(default_factory=list)+ files: list[MappedModel] = field(default_factory=list) # evidence for models[i] (same order)other_files: list[MappedModel] = field(default_factory=list)flags: dict = field(default_factory=dict)server: ServerInfo | None = None@@ -219,6 +278,12 @@ class LlmView:kv_type: str = "f16"n_ctx: int | None = None+ def label(self, i: int) -> str:+ """Best human name for models[i]: model-store name, else GGUF basename/name."""+ f = self.files[i] if i < len(self.files) else None+ g = self.models[i]+ return (f.store_name if f and f.store_name else None) or g.metadata.get("general.basename") or g.name+def gb(n: float) -> str:if abs(n) >= 1 << 30:@@ -226,13 +291,45 @@ def gb(n: float) -> str:return f"{n / MiB:.0f} MB"+_SIDE_KINDS = ("vision projector", "LoRA adapter")+++def _merge_api(files: list[MappedModel], server: ServerInfo | None, host: ServerInfo | None) -> list[dict]:+ """Mark files a runtime API also reports; return the API entries that matched this process."""+ matched: list[dict] = []+ if server and server.kind == "llama-server" and server.model_path:+ key = os.path.normcase(os.path.abspath(server.model_path))+ hit = next((f for f in files if os.path.normcase(os.path.abspath(f.path)) == key), None)+ if hit:+ hit.sources.append("api")+ elif os.path.isfile(server.model_path): # loaded without mmap or via the router: API-only evidence+ files.insert(0, make_model(server.model_path, os.path.getsize(server.model_path), 0,+ is_gguf(server.model_path), "api"))+ for front in (s for s in (server, host) if s and s.kind == "ollama"):+ for f in files:+ names = set((f.store_name or "").split(", "))+ for om in front.models:+ if om["name"] in names:+ f.sources.append("api")+ matched.append(om)+ lms = host if host and host.kind == "lmstudio" else (server if server and server.kind == "lmstudio" else None)+ primary = [f for f in files if f.kind not in _SIDE_KINDS]+ if lms and len(lms.models) == 1 and len(primary) == 1: # LM Studio keys don't map to paths; only pair 1:1+ primary[0].sources.append("api")+ matched.append(lms.models[0])+ return matched++def build_view(d: ProcDetail, vram: float, shared: float, server: ServerInfo | None,log_path: str | None = None, host: ServerInfo | None = None) -> LlmView:v = LlmView(flags=parse_flags(d.cmdline), server=server, host=host)- for m in d.models:+ files = [dataclasses.replace(m, sources=list(m.sources)) for m in d.models] # cached details stay untouched+ matched = _merge_api(files, server, host)+ for m in files:g = read_gguf(m.path) if m.gguf else Noneif g is not None and not g.error:v.models.append(g)+ v.files.append(m)else:v.other_files.append(m)@@ -241,7 +338,7 @@ def build_view(d: ProcDetail, vram: float, shared: float, server: ServerInfo | Nv.log = parse_load_log(log_path, not_before=d.create_time - 5)v.log_source = log_path if v.log else None- main = next((g for g in v.models if g.kind == "model" and g.n_layers), None)+ main = next((g for g in v.models if g.kind == "LLM" and g.n_layers), None) # only causal LLMs grow a KV cachectk = str(v.flags.get("ctk", "f16")).lower()ctv = str(v.flags.get("ctv", "f16")).lower()v.kv_type = ctk if ctk == ctv else f"K {ctk}/V {ctv}"@@ -250,10 +347,12 @@ def build_view(d: ProcDetail, vram: float, shared: float, server: ServerInfo | Nif elems:v.kv_per_token = int(elems * (KV_TYPE_BYTES.get(ctk, 2) + KV_TYPE_BYTES.get(ctv, 2)) / 2)v.n_ctx = v.flags.get("ctx") or (server.n_ctx if server and server.kind == "llama-server" else None)- if server and server.kind == "ollama" and main:- for om in server.models:- if om.get("context_length"):- v.n_ctx = v.n_ctx or om["context_length"]+ if main:+ for om in matched or (server.models if server and server.kind == "ollama" else []):+ if om.get("ctx"):+ v.n_ctx = v.n_ctx or om["ctx"]+ primaries = [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)if v.log:@@ -292,11 +391,16 @@ def build_view(d: ProcDetail, vram: float, shared: float, server: ServerInfo | Nrest -= kvif rest > 0:v.segments.append(Segment("compute buffers + CUDA context", rest, "runtime"))+ elif rest > 0 and no_kv:+ v.segments.append(Segment("compute buffers + CUDA context", rest, "runtime"))elif rest > 0:v.segments.append(Segment("KV cache + compute + CUDA context", rest, "unknown"))if not v.models and not v.log and total > 0:v.notes.append("No GGUF mapped. Model may be loaded with --no-mmap or via another format.")+ if no_kv:+ kinds = ", ".join(sorted({f"{g.decision_type} {g.kind}" if g.decision_type else g.kind for g in primaries}))+ v.notes.append(f"Non-causal encoder ({kinds}): no KV cache grows with use; VRAM is weights + compute.")if main and v.kv_per_token:v.notes.append(f"KV cost {v.kv_per_token / 1024:.0f} KB/token ({v.kv_type}): "f"4k ctx = {gb(v.kv_per_token * 4096)}, 32k ctx = {gb(v.kv_per_token * 32768)}.")@@ -306,14 +410,14 @@ def build_view(d: ProcDetail, vram: float, shared: float, server: ServerInfo | Nif total < 64 * MiB and v.models:v.notes.append("Model is mapped but almost nothing is in VRAM: CPU inference, or another GPU.")for front in (s for s in (server, host) if s and s.kind == "ollama"):- for om in front.models:- size, vram_m = om.get("size", 0), om.get("size_vram", 0)- if size:- pct = 100 * vram_m / size- v.notes.append(f"Ollama: {om.get('name')} {gb(size)} total, {pct:.0f}% on GPU, "- f"ctx {om.get('context_length', '?')}.")+ mine = [om for om in front.models if om in matched]+ for om in mine or front.models: # unmatched: show everything Ollama has loaded+ if om.get("size"):+ pct = 100 * (om.get("size_vram") or 0) / om["size"]+ v.notes.append(f"Ollama{'' if mine else ' (not matched to this runner)'}: {om['name']} "+ f"{gb(om['size'])} total, {pct:.0f}% on GPU, ctx {om.get('ctx') or '?'}.")if host and host.kind == "lmstudio":for m in host.models[:4]:- v.notes.append(f"LM Studio: {m.get('id')} {m.get('quantization', '')} "- f"ctx {m.get('loaded_context_length') or m.get('max_context_length', '?')}.")+ v.notes.append(f"LM Studio: {m['name']} {m.get('type') or ''} {m.get('quant') or ''} "+ f"ctx {m.get('ctx') or '?'}.")return vdiff --git a/src/gputaskman/procinfo.py b/src/gputaskman/procinfo.pyindex b532849..b0ec9e8 100644--- a/src/gputaskman/procinfo.py+++ b/src/gputaskman/procinfo.py@@ -4,12 +4,14 @@ from __future__ import annotationsimport fnmatchimport os+import reimport timefrom dataclasses import dataclass, fieldimport psutil-from .gguf import is_gguf+from .gguf import is_gguf, read_gguf+from .stores import store_name# (tag, dll patterns). Order = display priority (most specific first).RUNTIMES: list[tuple[str, tuple[str, ...]]] = [@@ -30,10 +32,20 @@ RUNTIMES: list[tuple[str, tuple[str, ...]]] = [("NVDEC", ("nvcuvid.dll", "nvcuvid64.dll")),]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"}-LLM_NAMES = ("llama-", "ollama", "lm studio", "lmstudio", "llmster", "koboldcpp", "jan", "gpt4all", "llamafile")+LLM_NAMES = ("llama-", "llama.", "ollama", "lm studio", "lmstudio", "llmster", "koboldcpp", "jan", "gpt4all", "llamafile")+# GGUF file kind -> process kind, in display priority order+MODEL_KINDS = {"LLM": "LLM", "decision model": "decision", "embedding model": "embedding",+ "reranker": "embedding", "speech model": "speech"}+AI_KINDS = {"LLM", "decision", "embedding", "speech", "AI"}+MiB = 1 << 20+INSTALLED_TTL = 300.0+_SKIP_DIRS = {"ebwebview", "cache", "code cache", "gpucache", "node_modules", "logs", "crashpad", "locales", "__pycache__"}+_installed: dict[str, tuple[float, list[MappedModel]]] = {}@dataclass@@ -42,7 +54,19 @@ class MappedModel:size: intresident: int # bytes of the file currently in this process's RAM working setgguf: bool- source: str = "mapped" # "mapped" (memory-mapped) or "cmdline" (passed as an argument)+ sources: list[str] = field(default_factory=lambda: ["mapped"]) # mapped | cmdline | api | installed+ store_name: str | None = None # e.g. "qwen3:14b" from an Ollama manifest+ kind: str = "" # GGUF kind: LLM, decision model, embedding model, ...++ @property+ def evidence(self) -> str:+ s = set(self.sources)+ how = "+".join(x for x in ("api", "mapped", "cmdline") if x in s)+ if len(s) >= 2 and s & {"api", "mapped"}:+ return f"confirmed ({how})"+ if not how and "installed" in s:+ return "installed, not proven loaded"+ return {"mapped": "in use (mapped)", "cmdline": "launch arg", "api": "reported (api)"}.get(how, how)@dataclass@@ -54,9 +78,12 @@ class ProcDetail:create_time: float = 0.0runtimes: list[str] = field(default_factory=list)models: list[MappedModel] = field(default_factory=list)+ candidates: list[MappedModel] = field(default_factory=list) # installed with the app, not proven loadedports: list[int] = field(default_factory=list)+ parents: list[int] | None = None # parent PIDs, looked up once (each lookup enumerates all processes)access_denied: bool = Falsemaps_time: float = 0.0 # when memory maps were last scanned+ scan_mem: float = 0.0 # process GPU memory (dedicated + shared) at that scan@propertydef is_ai(self) -> bool:@@ -64,11 +91,7 @@ class ProcDetail:def _match_runtimes(dll_names: set[str]) -> list[str]:- found = []- for tag, patterns in RUNTIMES:- if any(fnmatch.fnmatch(d, p) for d in dll_names for p in patterns):- found.append(tag)- return found+ return [tag for tag, rx in _RUNTIME_RX if any(rx.match(d) for d in dll_names)]def _models_from_cmdline(cmd: list[str]) -> list[str]:@@ -84,10 +107,100 @@ def _models_from_cmdline(cmd: list[str]) -> list[str]:return paths+def _is_model_file(ext: str, size: int, gg: bool, store: str | None) -> bool:+ if gg:+ return True+ if ext not in MODEL_EXTS:+ return False+ if ext in AMBIGUOUS_EXTS:+ return size >= 64 * MiB or store is not None+ return size >= 4 * MiB+++def make_model(path: str, size: int, resident: int, gg: bool, source: str, store: str | None = None) -> MappedModel:+ g = read_gguf(path) if gg else None+ kind = g.kind if g is not None and not g.error else ""+ return MappedModel(path, size, resident, gg, [source], store if store is not None else store_name(path), kind)+++def _walk(root: str, depth: int, out: list[tuple[str, int]], budget: list[int]) -> None:+ try:+ it = os.scandir(root)+ except OSError:+ return+ with it:+ for e in it:+ budget[0] -= 1+ if budget[0] < 0:+ return+ try:+ if e.is_dir(follow_symlinks=False):+ if depth > 0 and e.name.lower() not in _SKIP_DIRS:+ _walk(e.path, depth - 1, out, budget)+ continue+ ext = os.path.splitext(e.name)[1].lower()+ if ext in MODEL_EXTS:+ size = e.stat().st_size+ if _is_model_file(ext, size, False, None):+ out.append((e.path, size))+ except OSError:+ continue+++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 and+ close the file (ONNX Runtime, whisper.cpp), which leaves no OS evidence of which model is loaded.+ Bounded walk (depth 4, 3000 entries) cached per exe for 5 minutes."""+ if not exe:+ return []+ now = now or time.time()+ key = os.path.normcase(exe)+ hit = _installed.get(key)+ if hit and now - hit[0] < INSTALLED_TTL:+ 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"))):+ roots.append(os.path.dirname(exe))+ if len(stem) >= 4:+ for base in filter(None, (os.environ.get("APPDATA"), os.environ.get("LOCALAPPDATA"))):+ try:+ roots += [e.path for e in os.scandir(base) if stem in e.name.lower() and e.is_dir()]+ except OSError:+ pass+ files: list[tuple[str, int]] = []+ budget = [3000]+ for root in {os.path.normcase(r): r for r in roots}.values():+ _walk(root, 4, files, budget)+ by_dir: dict[str, list[tuple[str, int]]] = {}+ for path, size in files:+ by_dir.setdefault(os.path.dirname(path), []).append((path, size))+ found = []+ for folder, group in by_dir.items():+ if len(group) == 1: # one file: name it by the file+ path, size = group[0]+ found.append(make_model(path, size, 0, path.lower().endswith(".gguf") and is_gguf(path), "installed"))+ else: # several files (encoder + decoder, shards): name it by the folder+ found.append(MappedModel(folder, sum(s for _, s in group), 0, False, ["installed"], store_name(group[0][0])))+ found = sorted(found, key=lambda m: -m.size)[:6]+ _installed[key] = (now, found)+ return found+++def _create_time(pid: int) -> float:+ try:+ return psutil.Process(pid).create_time()+ except (psutil.Error, OSError):+ return 0.0++class ProcInspector:- """Caches per-process details; memory-map scans are throttled because they can be slow."""+ """Caches per-process details. Memory-map scans are the only costly step (1-50 ms each), so they run+ for new processes, when a process's GPU memory changes noticeably, and on a slow backstop."""- MAPS_INTERVAL = 15.0+ SCAN_MIN_GAP = 5.0 # never rescan one process more often than this+ SCAN_BACKSTOP = 120.0 # rescan even without a memory change+ SCAN_DELTA = 64 * MiB # or 10% of the process's GPU memory, whichever is largerPORTS_INTERVAL = 5.0def __init__(self) -> None:@@ -108,39 +221,61 @@ class ProcInspector:self._ports = {pid: sorted(p) for pid, p in ports.items()}self._ports_time = time.time()- def get(self, pid: int, deep: bool) -> ProcDetail:- """deep=True scans memory maps (DLLs + mapped model files)."""+ def get(self, pid: int) -> ProcDetail:+ """Cheap details: name, exe, command line, listening ports. Built once per process: psutil.Process()+ enumerates every process for protected PIDs (System, csrss, dwm), ~40 ms each. Accessible processes+ are re-checked for PID reuse each call (~0.1 ms); protected ones leave through prune()."""self._refresh_ports()d = self._cache.get(pid)+ if d is not None and d.create_time and _create_time(pid) != d.create_time:+ d = None # PID reused (e.g. while the TUI was paused)+ if d is None:+ d = self._cache[pid] = self._new(pid)+ d.ports = self._ports.get(pid, [])+ return d++ def ports(self, pid: int) -> list[int]:+ self._refresh_ports()+ return self._ports.get(pid, [])++ @staticmethod+ def _new(pid: int) -> ProcDetail:+ d = ProcDetail(pid=pid)+ if pid == 0:+ d.name = "System Idle"+ return dtry:p = psutil.Process(pid)- ct = p.create_time()- except (psutil.NoSuchProcess, psutil.AccessDenied, OSError):- p, ct = None, 0.0- if d is None or d.create_time != ct:- d = ProcDetail(pid=pid, create_time=ct)- if pid == 0:- d.name = "System Idle"- elif p is not None:- try:- d.name = p.name()- except (psutil.Error, OSError):- pass- try:- d.exe = p.exe()- d.cmdline = p.cmdline()- except (psutil.Error, OSError):- d.access_denied = True- self._cache[pid] = d- d.ports = self._ports.get(pid, [])- if deep and p is not None and not d.access_denied and time.time() - d.maps_time > self.MAPS_INTERVAL:- self._scan_maps(p, d)+ except (psutil.Error, OSError):+ d.access_denied = True+ return d+ try:+ d.name = p.name()+ except (psutil.Error, OSError):+ pass+ try:+ d.exe = p.exe()+ d.cmdline = p.cmdline()+ d.create_time = p.create_time()+ except (psutil.Error, OSError):+ d.access_denied = Truereturn d- def _scan_maps(self, p: psutil.Process, d: ProcDetail) -> None:- d.maps_time = time.time()+ def needs_scan(self, d: ProcDetail, mem: float, now: float | None = None) -> bool:+ if d.access_denied or d.pid == 0:+ return False+ if not d.maps_time:+ return True+ age = (now or time.time()) - d.maps_time+ if age < self.SCAN_MIN_GAP:+ return False+ return age > self.SCAN_BACKSTOP or abs(mem - d.scan_mem) > max(self.SCAN_DELTA, 0.1 * d.scan_mem)++ def scan(self, d: ProcDetail, mem: float = 0.0) -> None:+ """Memory maps -> loaded DLLs (runtimes) and mapped model files. Never uses open_files(): ~1-2 s/process."""+ d.maps_time, d.scan_mem = time.time(), memtry:- maps = p.memory_maps(grouped=True)+ maps = psutil.Process(d.pid).memory_maps(grouped=True)except (psutil.Error, OSError):d.access_denied = Truereturn@@ -159,16 +294,21 @@ class ProcInspector:size = os.path.getsize(path)except OSError:continue- gg = is_gguf(path) if (ext in (".gguf", "") or size > 64 << 20) else False- if ext in MODEL_EXTS or gg:- if size < (4 << 20) and not gg:- continue- models[path.lower()] = MappedModel(path=path, size=size, resident=m.rss, gguf=gg)+ gg = is_gguf(path) if (ext in (".gguf", "") or size > 64 * MiB) else False+ if not (gg or ext in MODEL_EXTS):+ continue+ store = store_name(path)+ if _is_model_file(ext, size, gg, store):+ models[path.lower()] = make_model(path, size, m.rss, gg, "mapped", store)for path in _models_from_cmdline(d.cmdline):- if path.lower() not in models:- models[path.lower()] = MappedModel(path, os.path.getsize(path), 0, is_gguf(path), source="cmdline")+ if path.lower() in models:+ models[path.lower()].sources.append("cmdline")+ else:+ models[path.lower()] = make_model(path, os.path.getsize(path), 0, is_gguf(path), "cmdline")d.runtimes = _match_runtimes(dlls)d.models = sorted(models.values(), key=lambda m: -m.size)+ ai = any(r in AI_RUNTIMES for r in d.runtimes)+ d.candidates = installed_models(d.exe) if ai and not d.models else []def prune(self, live_pids: set[int]) -> None:for pid in list(self._cache):@@ -184,7 +324,11 @@ def classify(d: ProcDetail, engines: dict[str, float]) -> str:return "compositor"if n in ("csrss.exe", "winlogon.exe", "lsass.exe", "svchost.exe"):return "system"- if any(m.gguf for m in d.models) or "llama.cpp" in d.runtimes or n.startswith(LLM_NAMES):+ kinds = {MODEL_KINDS[m.kind] for m in d.models if m.kind in MODEL_KINDS}+ for k in ("LLM", "decision", "embedding", "speech"):+ if k in kinds:+ return k+ if "llama.cpp" in d.runtimes or n.startswith(LLM_NAMES):return "LLM"video = engines.get("decode", 0) + engines.get("encode", 0) > 1if d.is_ai and not video:diff --git a/src/gputaskman/report.py b/src/gputaskman/report.pyindex 80bf669..5978bed 100644--- a/src/gputaskman/report.py+++ b/src/gputaskman/report.py@@ -21,12 +21,17 @@ def to_dict(s: Snapshot) -> dict:"gpu_pct": round(p.gpu.gpu_pct, 1), "engines": {k: round(v, 1) for k, v in p.gpu.engines.items() if v},"ports": p.detail.ports, "inside": p.inside,"model_files": [dataclasses.asdict(m) for m in p.detail.models],+ "installed_models": [dataclasses.asdict(m) for m in p.detail.candidates],}if p.llm:item["llm"] = {- "models": [{"path": g.path, "name": g.name, "arch": g.arch, "kind": g.kind, "params": g.n_params,+ "models": [{"path": g.path, "name": g.name, "label": p.llm.label(i), "arch": g.arch, "kind": g.kind,+ "decision_type": g.decision_type, "params": g.n_params,"quant": g.quant, "layers": g.n_layers, "ctx_train": g.ctx_train,- "gpu_weight_bytes": g.gpu_weight_bytes()} for g in p.llm.models],+ "gpu_weight_bytes": g.gpu_weight_bytes(),+ "sources": p.llm.files[i].sources if i < len(p.llm.files) else [],+ "store_name": p.llm.files[i].store_name if i < len(p.llm.files) else None}+ for i, g in enumerate(p.llm.models)],"segments": [dataclasses.asdict(x) for x in p.llm.segments],"kv_bytes_per_token": p.llm.kv_per_token, "n_ctx": p.llm.n_ctx, "flags": p.llm.flags,"server": dataclasses.asdict(p.llm.server) if p.llm.server else None,@@ -61,9 +66,11 @@ def to_text(s: Snapshot, limit: int = 30) -> str:continueout.append("")out.append(f"== {p.name} ({p.pid}) VRAM {gb(p.gpu.dedicated)}")- for g in p.llm.models:- out.append(f" {g.kind}: {g.name} [{g.arch}, {g.params_label} params, {g.quant}, {g.n_layers} layers, "- f"ctx_train {g.ctx_train}] {os.path.basename(g.path)}")+ for i, g in enumerate(p.llm.models):+ kind = g.kind + (f" ({g.decision_type})" if g.decision_type else "")+ ev = p.llm.files[i].evidence if i < len(p.llm.files) else ""+ out.append(f" {kind}: {p.llm.label(i)} [{g.arch}, {g.params_label} params, {g.quant}, {g.n_layers} layers, "+ f"ctx_train {g.ctx_train}] {os.path.basename(g.path)} evidence: {ev}")for seg in p.llm.segments:out.append(f" {gb(seg.bytes):>9} {seg.label}{'' if seg.exact else ''}")if p.llm.server:diff --git a/src/gputaskman/stores.py b/src/gputaskman/stores.pynew file mode 100644index 0000000..b9b7a4a--- /dev/null+++ b/src/gputaskman/stores.py@@ -0,0 +1,87 @@+"""Friendly model names from where a file lives on disk (Ollama, Hugging Face cache, LM Studio).++Pure path work plus small cached manifest reads: no runtime is contacted and no model is loaded.+"""++from __future__ import annotations++import json+import os+import re+import time++_OLLAMA_BLOB = re.compile(r"^(.*)[\\/]blobs[\\/]sha256-([0-9a-f]{64})$", re.I)+_HF_REPO = re.compile(r"[\\/]models--([^\\/]+?)--([^\\/]+)[\\/]snapshots[\\/]", re.I)+_TTL = 60.0+_ollama_cache: dict[str, tuple[float, dict[str, list[str]]]] = {}+_lms_cache: tuple[float, list[str]] | None = None+++def ollama_names(models_root: str) -> dict[str, list[str]]:+ """{sha256 hex: ["qwen3:14b", ...]} from <root>/manifests/<registry>/<namespace>/<model>/<tag>."""+ now = time.time()+ hit = _ollama_cache.get(models_root)+ if hit and now - hit[0] < _TTL:+ return hit[1]+ names: dict[str, list[str]] = {}+ base = os.path.join(models_root, "manifests")+ for dirpath, _, files in os.walk(base):+ parts = os.path.relpath(dirpath, base).split(os.sep)+ if len(parts) != 3:+ continue+ registry, namespace, model = parts+ prefix = "" if registry == "registry.ollama.ai" else f"{registry}/"+ prefix += "" if namespace == "library" else f"{namespace}/"+ for tag in files:+ try:+ with open(os.path.join(dirpath, tag), encoding="utf-8") as f:+ layers = json.load(f).get("layers", [])+ except (OSError, ValueError, AttributeError):+ continue+ for layer in layers:+ digest = str(layer.get("digest", "")).removeprefix("sha256:").lower()+ if digest:+ names.setdefault(digest, []).append(f"{prefix}{model}:{tag}")+ _ollama_cache[models_root] = (now, names)+ return names+++def lmstudio_dirs() -> list[str]:+ global _lms_cache+ now = time.time()+ if _lms_cache and now - _lms_cache[0] < _TTL:+ return _lms_cache[1]+ home = os.path.expanduser("~")+ dirs = [os.path.join(home, ".lmstudio", "models"), os.path.join(home, ".cache", "lm-studio", "models")]+ for settings in (os.path.join(home, ".lmstudio", "settings.json"),+ os.path.join(home, ".cache", "lm-studio", "settings.json")):+ try:+ with open(settings, encoding="utf-8") as f:+ folder = json.load(f).get("downloadsFolder")+ if folder:+ dirs.insert(0, folder)+ except (OSError, ValueError, AttributeError):+ pass+ dirs = list(dict.fromkeys(os.path.normcase(os.path.abspath(d)) for d in dirs))+ _lms_cache = (now, dirs)+ return dirs+++def store_name(path: str, lmstudio: list[str] | None = None) -> str | None:+ """'qwen3:14b' (Ollama), 'org/repo' (Hugging Face cache) or 'publisher/repo' (LM Studio)."""+ m = _OLLAMA_BLOB.match(path)+ if m:+ names = ollama_names(m[1]).get(m[2].lower())+ return ", ".join(sorted(set(names))) if names else None+ m = _HF_REPO.search(path)+ if m:+ return f"{m[1]}/{m[2]}"+ full = os.path.normcase(os.path.abspath(path))+ for root in lmstudio if lmstudio is not None else lmstudio_dirs():+ if full.startswith(root + os.sep):+ parts = os.path.relpath(full, root).split(os.sep)+ if len(parts) >= 3:+ # normcase lowercases on Windows; recover the original casing from the input path.+ orig = os.path.abspath(path).split(os.sep)[-len(parts):]+ return f"{orig[0]}/{orig[1]}"+ return Nonediff --git a/tests/test_core.py b/tests/test_core.pyindex f0d0204..37e1283 100644--- a/tests/test_core.py+++ b/tests/test_core.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport contextlibimport ioimport json+import osimport tempfileimport unittestfrom pathlib import Path@@ -12,10 +13,12 @@ from gputaskman.app import GpuTaskManagerfrom gputaskman.cli import mainfrom gputaskman.collector import ProcRow, Snapshotfrom gputaskman.gguf import GgufInfo, read_gguf-from gputaskman.llm import LlmView, ServerInfo, is_gpu_device, parse_flags, parse_load_log+from gputaskman.llm import (LlmView, ServerInfo, build_view, is_gpu_device, llama_server_models, lmstudio_models,+ parse_flags, parse_load_log, probe_server)from gputaskman.pdh import GpuCounters, ProcGpu-from gputaskman.procinfo import ProcDetail+from gputaskman.procinfo import MappedModel, ProcDetail, ProcInspector, _is_model_file, classify, installed_modelsfrom gputaskman.report import to_dict, to_text+from gputaskman.stores import store_namefrom tools.capture_screenshots import for_publicationGiB = 1 << 30@@ -158,6 +161,151 @@ class ModelTests(unittest.TestCase):self.assertIsNone(parse_load_log(str(path), not_before=path.stat().st_mtime + 10))+def gguf(arch: str, **meta) -> GgufInfo:+ md = {"general.architecture": arch}+ md.update({k if k.startswith(("general.", "stt.")) else f"{arch}.{k}": v for k, v in meta.items()})+ return GgufInfo(path=f"{arch}.gguf", file_size=1000, version=3, metadata=md, layer_bytes={0: 400},+ tensor_bytes=400)+++LAYA = dict(block_count=30, context_length=8192, **{"decision.type": "laya", "attention.causal": False})+++class IdentityTests(unittest.TestCase):+ def test_gguf_kinds_come_from_header_keys(self):+ cases = {+ "LLM": gguf("qwen3", block_count=28, context_length=40960),+ "decision model": gguf("modern-bert", **LAYA),+ "embedding model": gguf("bert", pooling_type=1),+ "reranker": gguf("bert", pooling_type=4),+ "speech model": gguf("parakeet", **{"stt.variant": "tdt"}),+ "vision projector": gguf("clip"),+ "model": gguf("modern-bert", block_count=30, context_length=8192, **{"attention.causal": False}),+ }+ for kind, info in cases.items():+ with self.subTest(kind=kind):+ self.assertEqual(info.kind, kind)+ self.assertEqual(cases["decision model"].decision_type, "laya")++ def test_store_names(self):+ digest = "ab" * 32+ with tempfile.TemporaryDirectory() as root:+ for tag_dir, tag in (("registry.ollama.ai/library/qwen3", "14b"), ("hf.co/org/thing", "latest")):+ folder = Path(root, "manifests", *tag_dir.split("/"))+ folder.mkdir(parents=True)+ (folder / tag).write_text(json.dumps({"layers": [{"digest": f"sha256:{digest}"}]}), encoding="utf-8")+ self.assertEqual(store_name(str(Path(root, "blobs", f"sha256-{digest}"))), "hf.co/org/thing:latest, qwen3:14b")+ self.assertIsNone(store_name(str(Path(root, "blobs", "sha256-" + "cd" * 32))))+ lms = Path(root, "lms")+ path = lms / "lmstudio-community" / "Qwen3-GGUF" / "Qwen3-Q4_K_M.gguf"+ self.assertEqual(store_name(str(path), [os.path.normcase(str(lms))]), "lmstudio-community/Qwen3-GGUF")+ self.assertIsNone(store_name(str(Path(root, "elsewhere", "a", "b.gguf")), [os.path.normcase(str(lms))]))+ hf = r"C:\x\hub\models--ggml-org--Laya-GGUF\snapshots\0123\Laya-Q8_0.gguf"+ self.assertEqual(store_name(hf, []), "ggml-org/Laya-GGUF")++ def test_runtime_api_normalization(self):+ v1 = {"models": [+ {"type": "decision", "key": "laya", "decision_type": "laya", "quantization": {"name": "Q8_0"},+ "size_bytes": 449, "loaded_instances": [{"id": "laya", "config": {"context_length": 8192}}]},+ {"type": "llm", "key": "idle", "loaded_instances": []},+ ]}+ self.assertEqual(lmstudio_models(v1, None), [{"name": "laya", "type": "decision (laya)", "quant": "Q8_0",+ "ctx": 8192, "size": 449, "size_vram": None, "path": None}])+ v0 = {"data": [{"id": "a", "type": "llm", "state": "loaded", "quantization": "Q4_K_M", "loaded_context_length": 4096},+ {"id": "b", "state": "not-loaded"}]}+ self.assertEqual([(m["name"], m["ctx"]) for m in lmstudio_models(None, v0)], [("a", 4096)])+ self.assertIsNone(lmstudio_models(None, None))+ llama = {"data": [{"id": r"C:\m\Laya-Q8_0.gguf", "architecture": {"output_modalities": ["decisions"]},+ "meta": {"ftype": "Q8_0", "n_ctx": 8192, "size": 447}}]}+ self.assertEqual(llama_server_models(llama, r"C:\m\Laya-Q8_0.gguf")[0]["type"], "decision")++ def test_lmstudio_falls_back_to_v0_when_v1_is_an_error(self):+ replies = {"/api/v1/models": {"error": "Unexpected endpoint or method. (GET /api/v1/models)"},+ "/api/v0/models": {"data": [{"id": "qwen", "state": "loaded", "max_context_length": 8192}]}}+ with patch("gputaskman.llm._get", side_effect=lambda url: next(+ (v for k, v in replies.items() if url.endswith(k)), None)):+ s = probe_server(1234)+ self.assertEqual((s.kind, s.models[0]["name"]), ("lmstudio", "qwen"))++ def test_reused_pid_gets_fresh_details(self):+ inspector = ProcInspector()+ inspector._ports_time = float("inf") # no port scan in this test+ inspector._cache[42] = ProcDetail(42, "llama-server.exe", cmdline=["-m", "old.gguf"], create_time=100.0)+ with patch("gputaskman.procinfo._create_time", return_value=100.0):+ self.assertEqual(inspector.get(42).name, "llama-server.exe")+ fresh = ProcDetail(42, "msedge.exe", create_time=200.0)+ with patch("gputaskman.procinfo._create_time", return_value=200.0), \+ patch.object(ProcInspector, "_new", return_value=fresh):+ self.assertIs(inspector.get(42), fresh)++ def test_ambiguous_extensions_need_size_or_store(self):+ self.assertFalse(_is_model_file(".bin", 10 * MiB, False, None)) # e.g. a Start menu tile cache+ self.assertTrue(_is_model_file(".bin", 10 * MiB, False, "org/repo"))+ self.assertTrue(_is_model_file(".bin", 100 * MiB, False, None))+ self.assertTrue(_is_model_file(".safetensors", 10 * MiB, False, None))+ self.assertTrue(_is_model_file("", 1, True, None))+ self.assertFalse(_is_model_file(".txt", GiB, False, None))++ def test_scans_follow_memory_changes(self):+ inspector, now = ProcInspector(), 1000.0+ self.assertTrue(inspector.needs_scan(ProcDetail(1), GiB, now))+ self.assertFalse(inspector.needs_scan(ProcDetail(1, maps_time=now - 1, scan_mem=GiB), 4 * GiB, now))+ self.assertFalse(inspector.needs_scan(ProcDetail(1, maps_time=now - 10, scan_mem=GiB), GiB + 50 * MiB, now))+ self.assertTrue(inspector.needs_scan(ProcDetail(1, maps_time=now - 10, scan_mem=GiB), 2 * GiB, now))+ self.assertTrue(inspector.needs_scan(ProcDetail(1, maps_time=now - 200, scan_mem=GiB), GiB, now))+ self.assertFalse(inspector.needs_scan(ProcDetail(1, access_denied=True), GiB, now))++ def test_decision_model_has_no_kv_cache_and_api_evidence(self):+ laya = gguf("modern-bert", **LAYA)+ d = ProcDetail(5, "llama-server.exe", models=[MappedModel("laya.gguf", 1000, 0, True, kind="decision model")])+ self.assertEqual(classify(d, {}), "decision")+ server = ServerInfo("llama-server", "http://127.0.0.1:1", n_ctx=8192, model_path="laya.gguf")+ with patch("gputaskman.llm.read_gguf", return_value=laya):+ v = build_view(d, 1000, 0, server)+ self.assertEqual(v.files[0].evidence, "confirmed (api+mapped)")+ self.assertEqual(d.models[0].sources, ["mapped"]) # cached detail is not mutated+ self.assertIsNone(v.kv_per_token)+ self.assertEqual([s.label for s in v.segments], ["weights", "compute buffers + CUDA context"])+ self.assertTrue(any("laya decision model" in n for n in v.notes))++ def test_installed_models_are_candidates_only(self):+ with tempfile.TemporaryDirectory() as root:+ app = Path(root, "Speechy")+ (app / "models" / "parakeet").mkdir(parents=True)+ (app / "cache").mkdir()+ exe = app / "speechy.exe"+ exe.write_bytes(b"")+ for path, size in (("models/whisper-large.bin", 70 * MiB), ("models/parakeet/encoder.onnx", 8 * MiB),+ ("models/parakeet/decoder.onnx", 5 * MiB), ("models/tiles.bin", 5 * MiB),+ ("cache/big.onnx", 9 * MiB)):+ with open(app / path, "wb") as f:+ f.truncate(size)+ with patch.dict(os.environ, {"APPDATA": root, "LOCALAPPDATA": root, "SystemRoot": r"C:\Windows"}):+ found = installed_models(str(exe), now=1.0)+ self.assertEqual([(os.path.basename(m.path), m.size) for m in found],+ [("whisper-large.bin", 70 * MiB), ("parakeet", 13 * MiB)])+ self.assertEqual(found[0].evidence, "installed, not proven loaded")+ self.assertIs(installed_models(str(exe), now=2.0), found) # cached+ d = ProcDetail(7, "speechy.exe", runtimes=["ONNX RT"], candidates=found)+ self.assertEqual(classify(d, {}), "AI") # candidates never decide the kind+ self.assertTrue(ProcRow(7, "speechy.exe", "AI", ProcGpu(), d).inside.startswith("installed (unproven): "))++ def test_ollama_runner_shows_only_its_model(self):+ qwen = gguf("qwen3", block_count=1, context_length=4096)+ d = ProcDetail(6, "llama-server.exe", models=[MappedModel("blob", 1000, 0, True, store_name="qwen3:14b", kind="LLM")])+ host = ServerInfo("ollama", "http://127.0.0.1:11434", models=[+ {"name": "qwen3:14b", "size": GiB, "size_vram": GiB, "ctx": 4096},+ {"name": "other:1b", "size": GiB, "size_vram": 0, "ctx": 2048}])+ with patch("gputaskman.llm.read_gguf", return_value=qwen):+ v = build_view(d, GiB, 0, host)+ self.assertEqual(v.label(0), "qwen3:14b")+ self.assertIn("api", v.files[0].sources)+ self.assertEqual(v.n_ctx, 4096)+ ollama = [n for n in v.notes if n.startswith("Ollama")]+ self.assertEqual(len(ollama), 1)+ self.assertIn("qwen3:14b", ollama[0])++class UiTests(unittest.IsolatedAsyncioTestCase):async def test_navigation_sort_pause_and_help(self):with patch.object(GpuTaskManager, "poll"):diff --git a/tools/capture_screenshots.py b/tools/capture_screenshots.pyindex 6418e91..e3b8510 100644--- a/tools/capture_screenshots.py+++ b/tools/capture_screenshots.py@@ -19,13 +19,19 @@ def for_publication(snapshot: Snapshot) -> Snapshot:for row in snapshot.procs:row.detail.cmdline = []row.detail.exe = ""- for model in row.detail.models:+ for model in row.detail.models + row.detail.candidates:model.path = os.path.basename(model.path)if row.llm:for model in row.llm.models:model.path = os.path.basename(model.path)- for model in row.llm.other_files:+ for model in row.llm.files + row.llm.other_files:model.path = os.path.basename(model.path)+ if row.llm.server and row.llm.server.model_path:+ row.llm.server.model_path = os.path.basename(row.llm.server.model_path)+ for server in (row.llm.server, row.llm.host):+ for m in server.models if server else []:+ if m.get("path"):+ m["path"] = os.path.basename(m["path"])if row.llm.log_source:row.llm.log_source = os.path.basename(row.llm.log_source)return snapshot