okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-container-mem-core: memory checks that read a container's limit correctly6b63729a9

main
14.1 KiB313 linesraw
1"""What the tuner needs to know about this PC, read without ever raising.
2
3Every probe here is optional: a missing tool or an unreadable file gives ``None`` (or an empty list), never an
4exception, because the tuner must still run on a machine whose sensors it cannot read, only with fewer guards.
5A guard that cannot read its input says so in the report ("the free graphics memory could not be read"); it does not
6pretend the memory was free.
7
8Stdlib only, like the rest of Strata Control.
9"""
10
11from __future__ import annotations
12
13import hashlib
14import json
15import os
16from strata_control import sysinfo
17import re
18import shutil
19import subprocess
20import sys
21import time
22from pathlib import Path
23from typing import Any
24
25MIB = 1024 * 1024
26
27
28# --------------------------------------------------------------------------- memory
29
30def memory() -> dict[str, int | None]:
31    """System RAM in MiB: ``total`` and ``available`` (what a new process could use without swapping)."""
32    try:
33        if os.name == "nt":
34            import ctypes
35
36            class _Status(ctypes.Structure):
37                _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong),
38                            ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong),
39                            ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong),
40                            ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong),
41                            ("ullAvailExtendedVirtual", ctypes.c_ulonglong)]
42
43            status = _Status()
44            status.dwLength = ctypes.sizeof(_Status)
45            if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)):
46                return {"total_mib": int(status.ullTotalPhys // MIB), "available_mib": int(status.ullAvailPhys // MIB)}
47        elif sys.platform == "darwin":
48            total = int(subprocess.run(["sysctl", "-n", "hw.memsize"], capture_output=True, text=True,
49                                       timeout=5).stdout.strip()) // MIB
50            vm = subprocess.run(["vm_stat"], capture_output=True, text=True, timeout=5).stdout
51            page = int(re.search(r"page size of (\d+)", vm).group(1)) if re.search(r"page size of (\d+)", vm) else 16384
52            pages = 0
53            for key in ("Pages free", "Pages inactive", "Pages speculative"):
54                m = re.search(rf"{key}:\s+(\d+)", vm)
55                pages += int(m.group(1)) if m else 0
56            return {"total_mib": total, "available_mib": pages * page // MIB}
57        else:
58            # /proc/meminfo; inside a container its memory limit (strata_control/cgroup_memory.py)
59            from strata_control import cgroup_memory
60            total, available = cgroup_memory.ram_bytes()
61            if total is not None and available is not None:
62                return {"total_mib": total // MIB, "available_mib": available // MIB}
63    except Exception:  # noqa: BLE001 - a probe must not raise
64        pass
65    return {"total_mib": None, "available_mib": None}
66
67
68# --------------------------------------------------------------------------- graphics cards
69
70def _run(argv: list[str], timeout: float = 10.0) -> str | None:
71    try:
72        return subprocess.run(argv, capture_output=True, text=True, errors="replace", timeout=timeout).stdout
73    except Exception:  # noqa: BLE001
74        return None
75
76
77def gpus() -> list[dict[str, Any]]:
78    """Graphics cards with their memory: ``name``, ``vram_total_mib``, ``vram_used_mib`` (None when unreadable),
79    ``driver``, ``vendor``. NVIDIA through nvidia-smi, AMD through the kernel's sysfs files; Intel and Apple report
80    their name only where it is known, and leave the memory unreadable."""
81    out: list[dict[str, Any]] = []
82    smi = shutil.which("nvidia-smi")
83    if smi:
84        text = _run([smi, "--query-gpu=index,name,memory.total,memory.used,driver_version",
85                     "--format=csv,noheader,nounits"])
86        for line in (text or "").splitlines():
87            parts = [p.strip() for p in line.split(",")]
88            if len(parts) >= 5:
89                try:
90                    out.append({"vendor": "nvidia", "index": int(parts[0]), "name": parts[1],
91                                "vram_total_mib": int(float(parts[2])), "vram_used_mib": int(float(parts[3])),
92                                "driver": parts[4]})
93                except ValueError:
94                    continue
95    if not out and sys.platform.startswith("linux"):
96        base = Path("/sys/class/drm")
97        if base.is_dir():
98            index = 0
99            for card in sorted(base.glob("card[0-9]*")):
100                dev = card / "device"
101                try:
102                    vendor = (dev / "vendor").read_text().strip()
103                    total = int((dev / "mem_info_vram_total").read_text()) // MIB
104                    used = int((dev / "mem_info_vram_used").read_text()) // MIB
105                except (OSError, ValueError):
106                    continue
107                if vendor != "0x1002":
108                    continue
109                name = None
110                try:
111                    name = (dev / "product_name").read_text().strip()
112                except OSError:
113                    pass
114                out.append({"vendor": "amd", "index": index, "name": name or f"AMD GPU {index}",
115                            "vram_total_mib": total, "vram_used_mib": used, "driver": None})
116                index += 1
117    return out
118
119
120def gpu_used_mib(indexes: list[int] | None = None) -> int | None:
121    """Graphics memory in use now, summed over the cards the model runs on (all when ``indexes`` is None)."""
122    cards = gpus()
123    if not cards:
124        return None
125    vals = [c["vram_used_mib"] for c in cards if c.get("vram_used_mib") is not None
126            and (not indexes or c["index"] in indexes)]
127    return sum(vals) if vals else None
128
129
130# --------------------------------------------------------------------------- processor
131
132def cpu() -> dict[str, Any]:
133    """``model``, ``logical`` and ``physical`` thread counts, and ``hybrid`` (performance plus efficiency cores)."""
134    logical = os.cpu_count() or 1
135    model = sysinfo.processor() or sysinfo.machine()
136    physical: int | None = None
137    hybrid = False
138    try:
139        if sys.platform.startswith("linux"):
140            text = Path("/proc/cpuinfo").read_text()
141            m = re.search(r"model name\s*:\s*(.+)", text)
142            if m:
143                model = m.group(1).strip()
144            cores = set()
145            for block in text.split("\n\n"):
146                pid = re.search(r"physical id\s*:\s*(\d+)", block)
147                cid = re.search(r"core id\s*:\s*(\d+)", block)
148                if pid and cid:
149                    cores.add((pid.group(1), cid.group(1)))
150            physical = len(cores) or None
151            hybrid = Path("/sys/devices/cpu_core").exists() and Path("/sys/devices/cpu_atom").exists()
152        elif os.name == "nt":
153            try:
154                import winreg
155                with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"HARDWARE\DESCRIPTION\System\CentralProcessor\0") as k:
156                    model = str(winreg.QueryValueEx(k, "ProcessorNameString")[0]).strip() or model
157            except OSError:
158                pass
159            physical, hybrid = _windows_cores()
160        elif sys.platform == "darwin":
161            model = (_run(["sysctl", "-n", "machdep.cpu.brand_string"]) or model).strip()
162            phys = _run(["sysctl", "-n", "hw.physicalcpu"])
163            physical = int(phys) if phys and phys.strip().isdigit() else None
164            hybrid = False
165    except Exception:  # noqa: BLE001
166        pass
167    return {"model": model, "logical": logical, "physical": physical, "hybrid": hybrid}
168
169
170def _windows_cores() -> tuple[int | None, bool]:
171    """(physical cores, hybrid) from GetLogicalProcessorInformationEx: hybrid when the cores have more than one
172    efficiency class (performance and efficiency cores)."""
173    try:
174        import ctypes
175        from ctypes import wintypes
176
177        k = ctypes.windll.kernel32
178        k.GetLogicalProcessorInformationEx.argtypes = [wintypes.DWORD, ctypes.c_void_p, ctypes.POINTER(wintypes.DWORD)]
179        size = wintypes.DWORD(0)
180        k.GetLogicalProcessorInformationEx(0, None, ctypes.byref(size))      # 0 = RelationProcessorCore
181        buf = ctypes.create_string_buffer(size.value)
182        if not k.GetLogicalProcessorInformationEx(0, buf, ctypes.byref(size)):
183            return None, False
184        raw = bytes(buf.raw[:size.value])
185        classes, cores, offset = set(), 0, 0
186        while offset + 10 <= len(raw):
187            rel_size = int.from_bytes(raw[offset + 4:offset + 8], "little")
188            if rel_size <= 0:
189                break
190            classes.add(raw[offset + 9])       # PROCESSOR_RELATIONSHIP.EfficiencyClass
191            cores += 1
192            offset += rel_size
193        return (cores or None), len(classes) > 1
194    except Exception:  # noqa: BLE001
195        return None, False
196
197
198_last_cpu: tuple[float, int, int] | None = None
199
200
201def cpu_busy_percent(sample_s: float = 1.0) -> float | None:
202    """How busy the whole CPU was over the last ``sample_s`` seconds (0-100), or None when unreadable."""
203    def read() -> tuple[int, int] | None:
204        try:
205            if sys.platform.startswith("linux"):
206                f = Path("/proc/stat").read_text().splitlines()[0].split()[1:]
207                v = [int(x) for x in f]
208                idle = v[3] + (v[4] if len(v) > 4 else 0)
209                return sum(v), idle
210            if os.name == "nt":
211                import ctypes
212                from ctypes import wintypes
213                idle, kern, user = wintypes.FILETIME(), wintypes.FILETIME(), wintypes.FILETIME()
214                if not ctypes.windll.kernel32.GetSystemTimes(ctypes.byref(idle), ctypes.byref(kern), ctypes.byref(user)):
215                    return None
216                q = lambda t: (t.dwHighDateTime << 32) | t.dwLowDateTime  # noqa: E731
217                return q(kern) + q(user), q(idle)
218        except Exception:  # noqa: BLE001
219            return None
220        return None
221
222    a = read()
223    if a is None:
224        return None
225    time.sleep(sample_s)
226    b = read()
227    if b is None or b[0] == a[0]:
228        return None
229    return round(100.0 * (1.0 - (b[1] - a[1]) / (b[0] - a[0])), 1)
230
231
232def other_engines(own_pids: set[int] | None = None) -> list[str]:
233    """Command lines of Strata engines that this tune did not start (a second engine changes every number)."""
234    own = own_pids or set()
235    found: list[str] = []
236    try:
237        if os.name == "nt":
238            text = _run(["powershell", "-NoProfile", "-Command",
239                         "Get-CimInstance Win32_Process -Filter \"Name='strata.exe'\" | "
240                         "Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress"], timeout=20)
241            if text and text.strip():
242                data = json.loads(text)
243                for row in data if isinstance(data, list) else [data]:
244                    if int(row.get("ProcessId", 0)) not in own and "--serve" in (row.get("CommandLine") or ""):
245                        found.append((row.get("CommandLine") or "")[:160])
246        else:
247            text = _run(["ps", "-eo", "pid=,args="]) or ""
248            for line in text.splitlines():
249                pid_s, _, args = line.strip().partition(" ")
250                if pid_s.isdigit() and int(pid_s) not in own and re.search(r"(^|/)strata(\s|$)", args.split(" --serve")[0]) \
251                        and " --serve" in args:
252                    found.append(args[:160])
253    except Exception:  # noqa: BLE001
254        pass
255    return found
256
257
258# --------------------------------------------------------------------------- the key a preset is valid for
259
260def _round_down(value: int | None, step: int) -> int | None:
261    return None if value is None else value - value % step
262
263
264def hardware_identity(*, pcie: str | None = None) -> dict[str, Any]:
265    """Hardware in two parts. ``hard``: a change means the stored settings may not even start (graphics card,
266    memory sizes, processor). ``soft``: a change deserves a short re-check (graphics driver)."""
267    cards = gpus()
268    mem = memory()
269    c = cpu()
270    return {
271        "hard": {
272            "gpus": [{"name": g["name"], "vram_mib": g["vram_total_mib"]} for g in cards],
273            "cpu": c["model"], "logical": c["logical"], "physical": c["physical"], "hybrid": c["hybrid"],
274            "ram_gib": _round_down((mem["total_mib"] or 0) // 1024 or None, 2),
275            "pcie": pcie, "os": sysinfo.system(),
276        },
277        "soft": {"driver": sorted({g["driver"] for g in cards if g.get("driver")}), "os_release": sysinfo.release()},
278    }
279
280
281def engine_identity(exe: str | os.PathLike[str]) -> dict[str, Any]:
282    """The engine build: version, backend, build id and executable SHA-256 from its manifest, plus the manifest's
283    ``tuning_epoch`` (bumped when a kernel or default change can move a tuning result)."""
284    folder = Path(exe).resolve().parent
285    manifest: dict[str, Any] = {}
286    try:
287        manifest = json.loads((folder / "engine-component.json").read_text(encoding="utf-8"))
288    except (OSError, ValueError):
289        pass
290    sha = None
291    for entry in manifest.get("files") or []:
292        if entry.get("path") == manifest.get("entrypoint", Path(exe).name):
293            sha = entry.get("sha256")
294    return {"version": manifest.get("version"), "backend": manifest.get("backend"),
295            "build_id": manifest.get("build_id"), "sha256": sha,
296            "tuning_epoch": int(manifest.get("tuning_epoch") or 0), "path": str(exe)}
297
298
299def model_identity(files: list[str | os.PathLike[str]]) -> dict[str, Any]:
300    """The model file(s): size and a digest of the head, middle and tail of the first shard (the whole file would
301    mean reading tens of gigabytes before every tune)."""
302    from strata_control import tune_history
303    out: list[dict[str, Any]] = []
304    for f in files[:2]:
305        ident = tune_history.file_identity(Path(f))
306        out.append({"name": Path(f).name, "bytes": ident.get("bytes"), "digest": ident.get("digest"),
307                    "method": ident.get("method")})
308    first = out[0] if out else {}
309    return {"files": out, "sha256_shard1": first.get("digest"), "bytes": first.get("bytes")}
310
311
312def stable_hash(obj: Any) -> str:
313    return hashlib.sha256(json.dumps(obj, sort_keys=True, default=str).encode()).hexdigest()[:16]