Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
serve: AMD readings in the Monitor tab from Linux sysfs; free VRAM on HIP (#301)
Niko1221c03efab3196f
diff --git a/serve/server.py b/serve/server.pyindex d194233a2..9642ad455 100644--- a/serve/server.py+++ b/serve/server.py@@ -714,8 +714,12 @@ class Service:return self.vision is not None and hasattr(self.vision, "alive") and not self.vision.alive()def free_vram_mib(self) -> int | None:- """Free VRAM on the engine's (first) GPU, from NVML; None when it can't be read (then nothing is refused)."""+ """Free VRAM on the engine's (first) GPU, from NVML (AMD backend: amdgpu's sysfs files, #301); None when it can't+ be read (then nothing is refused)."""try:+ if getattr(self, "backend", None) == "hip":+ from serve.telemetry import free_vram_mib+ return free_vram_mib(int(getattr(self, "gpu_index", 0) or 0), amd=True)from serve.telemetry import _Nvmlnv = _Nvml(int(getattr(self, "gpu_index", 0) or 0))if not nv.ok():@@ -848,7 +852,8 @@ class Service:self.telemetry = Telemetry(extra=lambda: {"tok_s": self._tok_s(), "tok_s_mean": self._tok_s_mean(),"prefill_tok_s_mean": self._prefill_tok_s_mean()},gpu_index=int(getattr(self, "gpu_index", 0) or 0),- gpu_indices=getattr(self, "gpu_indices", None))+ gpu_indices=getattr(self, "gpu_indices", None),+ amd=getattr(self, "backend", None) == "hip")def _tok_s(self):"""tok/s over the last RATE_WINDOW_S seconds. Returns 0.0 while nothing is generating."""@@ -2086,6 +2091,7 @@ def main() -> int:flush=True)svc.gpu_index = (gpu_list(cfg) or [0])[0] # the Monitor reads the card the engine runs on (issue #51)svc.gpu_indices = gpu_list(cfg) # ... or every card of a layer split (issue #112)+ svc.backend = cfg.get("backend") # "hip": the AMD cards' readings come from sysfs (#301)if a.config: # the Chat settings shared with other apps, from last timesvc.shared_path = str(Path(a.config).with_suffix("")) + ".shared-settings.json"try:diff --git a/serve/telemetry.py b/serve/telemetry.pyindex 6cfd0e3be..6fc1a0304 100644--- a/serve/telemetry.py+++ b/serve/telemetry.py@@ -2,7 +2,8 @@A background thread samples once a second and keeps the last 60 readings of each series for the sparklines:- GPU: NVIDIA's own NVML library (nvml.dll / libnvidia-ml.so.1, installed with every driver) through ctypes, so no- pip package is needed: load, VRAM, temperature, power, PCIe link and throughput.+ pip package is needed: load, VRAM, temperature, power, PCIe link and throughput. With the AMD backend (#301): the+ amdgpu driver's Linux sysfs files - load, VRAM, temperature and power.- CPU, RAM, disk: `psutil` when it is installed (setup installs it); without it the CPU and RAM readings fall back tothe OS (Windows GlobalMemoryStatusEx / GetSystemTimes, Linux /proc) and the disk rate is absent.Anything that cannot be read is None; nothing here can stop the server.@@ -103,6 +104,100 @@ class _Nvml:return out+# ------------------------------------------------------------------------------------------------ AMD (Linux sysfs)+SYSFS = "/sys"+++def amd_device_dir(index, sysfs=None):+ """The amdgpu sysfs folder (/sys/class/drm/renderD<N>/device) of the AMD GPU that HIP numbers `index`: the KFD+ topology's GPU nodes in order, the CPU nodes skipped, linked to their render node by drm_render_minor - the+ numbering setup's amd_gpus() and HIP_VISIBLE_DEVICES use. None when there is no such card (or no amdgpu)."""+ base = os.path.join(sysfs or SYSFS, "class", "kfd", "kfd", "topology", "nodes")+ try:+ nodes = sorted((n for n in os.listdir(base) if n.isdigit()), key=int)+ except OSError:+ return None+ gpus = []+ for n in nodes:+ try:+ with open(os.path.join(base, n, "properties"), encoding="utf-8") as f:+ props = dict(line.strip().partition(" ")[::2] for line in f if line.strip())+ if int(props.get("gfx_target_version") or 0) == 0 or int(props.get("simd_count") or 0) == 0:+ continue+ gpus.append(props)+ except (OSError, ValueError):+ continue+ if not 0 <= index < len(gpus) or not gpus[index].get("drm_render_minor"):+ return None+ dev = os.path.join(sysfs or SYSFS, "class", "drm", "renderD" + gpus[index]["drm_render_minor"].strip(), "device")+ return dev if os.path.isdir(dev) else None+++class _Amd:+ """#301: an AMD card's readings from the amdgpu driver's sysfs files (Linux; no ROCm library needed), with _Nvml's+ interface: load (gpu_busy_percent), VRAM (mem_info_vram_used / _total), and from its hwmon folder the temperature+ (temp1_input, the edge sensor, m°C), power (power1_average or power1_input, µW) and its cap (power1_cap)."""++ def __init__(self, index=0, sysfs=None):+ self.dev = amd_device_dir(index, sysfs)+ self.hwmon = None+ if self.dev:+ try:+ hw = sorted(os.listdir(os.path.join(self.dev, "hwmon")))+ self.hwmon = os.path.join(self.dev, "hwmon", hw[0]) if hw else None+ except OSError:+ pass++ def ok(self):+ return self.dev is not None++ @staticmethod+ def _int(path):+ try:+ with open(path, encoding="utf-8") as f:+ return int(f.read().strip())+ except (OSError, ValueError, TypeError):+ return None++ def name(self):+ try:+ with open(os.path.join(self.dev, "product_name"), encoding="utf-8") as f:+ return f.read().strip() or "AMD Radeon"+ except (OSError, TypeError):+ return "AMD Radeon"++ def read(self):+ out = {"util": self._int(os.path.join(self.dev, "gpu_busy_percent")),+ "mem_used": self._int(os.path.join(self.dev, "mem_info_vram_used")),+ "mem_total": self._int(os.path.join(self.dev, "mem_info_vram_total"))}+ if self.hwmon:+ t = self._int(os.path.join(self.hwmon, "temp1_input"))+ out["temp"] = t / 1000.0 if t is not None else None+ p = self._int(os.path.join(self.hwmon, "power1_average"))+ if p is None:+ p = self._int(os.path.join(self.hwmon, "power1_input"))+ out["power"] = p / 1e6 if p is not None else None+ cap = self._int(os.path.join(self.hwmon, "power1_cap"))+ out["power_limit"] = cap / 1e6 if cap is not None else None+ return out+++def gpu_reader(index=0, amd=False):+ """The card's readings: NVML (NVIDIA), or the amdgpu sysfs files with the AMD backend (#301)."""+ return _Amd(index) if amd else _Nvml(index)+++def free_vram_mib(index=0, amd=False):+ """Free VRAM of a card in MiB, or None when it cannot be read."""+ g = gpu_reader(index, amd)+ if not g.ok():+ return None+ r = g.read()+ if r.get("mem_total") is None or r.get("mem_used") is None:+ return None+ return int((r["mem_total"] - r["mem_used"]) >> 20)++# ------------------------------------------------------------------------------------------------ CPU / RAMdef _cpu_name():if os.name == "nt":@@ -169,17 +264,18 @@ class _CpuRamFallback:# ------------------------------------------------------------------------------------------------ the samplerclass Telemetry:- def __init__(self, extra=None, gpu_index=0, gpu_indices=None):+ def __init__(self, extra=None, gpu_index=0, gpu_indices=None, amd=False):"""`extra()` -> dict of more series to record each second (the server's tok/s). `gpu_index`: the card theengine runs on, numbered as nvidia-smi and NVML number them (by PCI bus); `gpu_indices`: all of them whenthe model is split across several (issue #112) - the gpu_* readings are then their total (memory, power,- PCIe traffic), mean (load) or hottest (temperature), and "gpus" has each card's own."""+ PCIe traffic), mean (load) or hottest (temperature), and "gpus" has each card's own. `amd`: the AMD backend's+ cards, numbered as HIP numbers them, read from sysfs (#301)."""self.extra = extraself.lock = threading.Lock()self.now: dict = {}self.hist = collections.defaultdict(lambda: collections.deque(maxlen=HISTORY))idx = list(gpu_indices) if gpu_indices and len(gpu_indices) > 1 else [gpu_index]- self.gpus = [(i, _Nvml(i)) for i in idx]+ self.gpus = [(i, gpu_reader(i, amd)) for i in idx]self.gpus = [(i, g) for i, g in self.gpus if g.ok()] or self.gpus[:1]self.gpu = self.gpus[0][1]try:diff --git a/serve/test_server.py b/serve/test_server.pyindex ac1c47d22..7bcdd73a2 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -14,6 +14,7 @@ import unittestimport urllib.errorimport urllib.requestfrom pathlib import Path+from unittest import mocksys.path.insert(0, str(Path(__file__).resolve().parents[1]))from serve.frontend import ChatTemplate # noqa: E402@@ -1544,5 +1545,69 @@ class ModelAliases(unittest.TestCase):httpd.server_close()+class AmdTelemetry(unittest.TestCase):+ """#301: the AMD backend's readings from a fake amdgpu sysfs tree: KFD node -> render node, as setup numbers the+ cards (the CPU node skipped), and free_vram_mib on HIP."""++ def tree(self, d):+ nodes = Path(d) / "class/kfd/kfd/topology/nodes"+ for n, props in ((0, "cpu_cores_count 16\nsimd_count 0\ngfx_target_version 0\ndrm_render_minor 0\n"),+ (1, "simd_count 128\ngfx_target_version 120001\ndrm_render_minor 129\n"),+ (2, "simd_count 128\ngfx_target_version 120001\ndrm_render_minor 128\n")):+ (nodes / str(n)).mkdir(parents=True)+ (nodes / str(n) / "properties").write_text(props)+ for minor, used, busy, temp, power in ((129, 2 << 30, 37, 51000, 85000000), (128, 6 << 30, 99, 64000, None)):+ dev = Path(d) / f"class/drm/renderD{minor}/device"+ hw = dev / "hwmon" / "hwmon4"+ hw.mkdir(parents=True)+ (dev / "gpu_busy_percent").write_text(f"{busy}\n")+ (dev / "mem_info_vram_used").write_text(f"{used}\n")+ (dev / "mem_info_vram_total").write_text(f"{32 << 30}\n")+ (dev / "product_name").write_text("AMD Radeon AI PRO R9700\n")+ (hw / "temp1_input").write_text(f"{temp}\n")+ if power is not None:+ (hw / "power1_average").write_text(f"{power}\n")+ else:+ (hw / "power1_input").write_text("120000000\n")+ (hw / "power1_cap").write_text("300000000\n")++ def test_readings(self):+ from serve import telemetry+ with tempfile.TemporaryDirectory() as d:+ self.tree(d)+ with mock.patch.object(telemetry, "SYSFS", d):+ self.assertTrue(telemetry.amd_device_dir(0).endswith(os.path.join("renderD129", "device")))+ self.assertTrue(telemetry.amd_device_dir(1).endswith(os.path.join("renderD128", "device")))+ self.assertIsNone(telemetry.amd_device_dir(2))+ g = telemetry.gpu_reader(0, amd=True)+ self.assertTrue(g.ok())+ self.assertEqual(g.name(), "AMD Radeon AI PRO R9700")+ self.assertEqual(g.read(), {"util": 37, "mem_used": 2 << 30, "mem_total": 32 << 30, "temp": 51.0,+ "power": 85.0, "power_limit": 300.0})+ r = telemetry.gpu_reader(1, amd=True).read()+ self.assertEqual((r["util"], r["temp"], r["power"]), (99, 64.0, 120.0)) # power1_input+ self.assertEqual(telemetry.free_vram_mib(0, amd=True), 30 << 10)+ self.assertIsNone(telemetry.free_vram_mib(5, amd=True))+ t = telemetry.Telemetry(gpu_index=0, gpu_indices=[0, 1], amd=True)+ s = t.sample()+ self.assertEqual(t.static["gpu_name"], "AMD Radeon AI PRO R9700 + AMD Radeon AI PRO R9700")+ self.assertEqual((s["gpu_mem_used"], s["gpu_util"], s["gpu_temp"], s["gpu_power"]),+ (8 << 30, 68.0, 64.0, 205.0))+ with tempfile.TemporaryDirectory() as d: # no amdgpu: nothing, and nothing breaks+ with mock.patch.object(telemetry, "SYSFS", d):+ self.assertFalse(telemetry.gpu_reader(0, amd=True).ok())+ self.assertIsNone(telemetry.free_vram_mib(0, amd=True))++ def test_free_vram_on_hip(self):+ from serve import telemetry+ tok = ByteTokenizer()+ svc = Service(MockEngine(tok, "x", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))+ svc.backend, svc.gpu_index = "hip", 1+ with tempfile.TemporaryDirectory() as d:+ self.tree(d)+ with mock.patch.object(telemetry, "SYSFS", d):+ self.assertEqual(svc.free_vram_mib(), 26 << 10)++if __name__ == "__main__":unittest.main()