Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/DETAILS.md
Original file line number Diff line number Diff line change
Expand Up @@ -1092,6 +1092,9 @@ app from [Connecting apps](#connecting-apps)) or in the terminal (`python polyst

- **Monitor:** what the model is doing (reading the prompt, with progress, or writing, at how many tokens/s); GPU load,
VRAM, temperature, power and PCIe traffic; CPU and disk; the conversation cache and the MCP servers.
`STRATA_MONITOR_NET=1` (set where the server starts) adds a **Network in** card: MB/s received over the machine's network
cards, with Mbit/s and MB/s sent under it. It counts the cards that are up and leaves out loopback, containers, bridges
and VPN tunnels. Unset, the server reads no network counters and `/metrics` is as before. Needs `psutil`.
- **Requests:** always there. With the [API request monitor](#api-request-monitor) on, it has a button that opens
`/api-monitor` in a browser tab of its own (the page's security policy allows no frames); with the monitor off, it says
how to turn it on.
Expand Down
57 changes: 56 additions & 1 deletion terminal/serve/telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -1749,7 +1749,38 @@ def pcie_bottleneck(reads) -> dict | None:
"width_max": r.get("pcie_width_max")}


# The Monitor's Network card (#447) is opt-in: STRATA_MONITOR_NET=1. Unset, the sampler reads no network counters and
# /metrics has no net_* fields, as before.
NET_ENV = "STRATA_MONITOR_NET"
# interfaces the card leaves out: loopback, containers, bridges, VMs and tunnels (their bytes also cross a real card)
NET_SKIP = ("docker", "veth", "br-", "virbr", "vmnet", "vboxnet", "tun", "tap", "wg", "tailscale", "zt")
_NET_LOOPBACK = re.compile(r"lo\d*$|.*loopback", re.IGNORECASE) # lo, lo0 (macOS), Windows' Loopback Pseudo-Interface


def net_cards(counters, stats):
"""The interfaces the Network card adds up: the names in `counters` (psutil's per-NIC counters) that are up in `stats`
(psutil's net_if_stats; None when it could not be read: every name counts) and are not loopback or virtual."""
up = set(counters) if stats is None else {n for n, st in stats.items() if st.isup}
return sorted(n for n in counters if n in up and not n.lower().startswith(NET_SKIP) and not _NET_LOOPBACK.match(n))


def net_rate(prev, now):
"""MB/s received and sent between two readings (time, bytes received, bytes sent, card names). None, None for the
first reading, a clock that did not move on, a counter that went back, or a different set of cards (a cable plugged
in or out would show its whole counter as one second's traffic)."""
if prev is None or now[0] <= prev[0] or now[1] < prev[1] or now[2] < prev[2] or now[3] != prev[3]:
return None, None
dt = now[0] - prev[0]
return (now[1] - prev[1]) / dt / 2**20, (now[2] - prev[2]) / dt / 2**20


class Telemetry:
# the Network card's switch and state (#447): off unless __init__ finds STRATA_MONITOR_NET=1; class defaults so a Telemetry
# built without __init__ (the tests' stand-ins) samples as before
net = False
_net_prev = None
_net_hist = ()

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 the
engine runs on, numbered as nvidia-smi and NVML number them (by PCI bus); `gpu_indices`: all of them when
Expand Down Expand Up @@ -1805,6 +1836,9 @@ def __init__(self, extra=None, gpu_index=0, gpu_indices=None, amd=False):
"psutil": self.ps is not None,
}
self._disk_prev = None
self.net = os.environ.get(NET_ENV) == "1"
self._net_prev = None
self._net_hist = ("net_rx_mb", "net_tx_mb") if self.net else ()
self._stop = threading.Event()
self._thread = threading.Thread(target=self._loop, daemon=True)
self._thread.start()
Expand All @@ -1825,6 +1859,25 @@ def _disk(self):
dt = t - prev[0]
return (c.read_bytes - prev[1]) / dt / 2**20, (c.write_bytes - prev[2]) / dt / 2**20

def _net(self):
"""The Network card's reading (STRATA_MONITOR_NET=1): MB/s received and sent over net_cards(), and their names."""
if not self.ps:
return None, None, None
try:
per = self.ps.net_io_counters(pernic=True) or {}
except (OSError, RuntimeError):
return None, None, None
try:
stats = self.ps.net_if_stats()
except (OSError, RuntimeError):
stats = None
names = net_cards(per, stats)
now = (time.time(), sum(per[n].bytes_recv for n in names), sum(per[n].bytes_sent for n in names), names)
prev, self._net_prev = self._net_prev, now
if not names:
return None, None, names
return (*net_rate(prev, now), names)

def sample(self):
s = {}
if self.gpu.ok():
Expand Down Expand Up @@ -1870,6 +1923,8 @@ def vals(k):
if used is not None:
s["ram_used"], s["ram_total"] = used, cg.mem
s["disk_read_mb"], s["disk_write_mb"] = self._disk()
if self.net:
s["net_rx_mb"], s["net_tx_mb"], s["net_nics"] = self._net()
if self.extra:
try:
s.update(self.extra())
Expand Down Expand Up @@ -1902,7 +1957,7 @@ def _loop(self):
with self.lock:
self.now = s
for k in ("gpu_util", "gpu_mem_used", "gpu_temp", "gpu_power", "gpu_pcie_rx_mb", "cpu", "ram_used",
"disk_read_mb", "tok_s", "prefill_tok_s_mean"):
"disk_read_mb", "tok_s", "prefill_tok_s_mean") + self._net_hist:
v = s.get(k)
self.hist[k].append(round(v, 2) if isinstance(v, float) else v)
self._stop.wait(1.0)
Expand Down
135 changes: 135 additions & 0 deletions terminal/serve/test_web_monitor_net.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
"""#447: the Monitor's opt-in Network card. With STRATA_MONITOR_NET=1 the sampler adds MB/s received and sent over the machine's
real network cards (up, not loopback, containers, bridges or tunnels) and the page shows a Network in card; unset, the sampler
reads no network counters and /metrics has no net_* fields. psutil is a stand-in here; the page's code runs in node.

python -m pytest serve/test_web_monitor_net.py
"""
import json
import os
import shutil
import subprocess
import sys
import unittest
from collections import namedtuple
from pathlib import Path
from unittest import mock

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from serve import telemetry # noqa: E402

WEB = Path(__file__).resolve().parent / "web"
NODE = shutil.which("node")
Io = namedtuple("Io", "bytes_sent bytes_recv")
If = namedtuple("If", "isup")
MB = 2**20


class FakePs:
"""psutil's net_io_counters(pernic=True) and net_if_stats(), with counters the test moves on."""
def __init__(self, counters, up):
self.counters, self.up = counters, up

def net_io_counters(self, pernic=False):
return dict(self.counters)

def net_if_stats(self):
return {n: If(n in self.up) for n in self.counters}


class NetCards(unittest.TestCase):
def test_real_cards_that_are_up(self):
counters = {n: Io(0, 0) for n in ("lo", "enp3s0", "enp2s0", "docker0", "veth12ab", "br-5f", "wg0", "tailscale0",
"Ethernet", "Local Area Connection", "lo0", "Loopback Pseudo-Interface 1")}
stats = {n: If(n != "enp2s0") for n in counters} # enp2s0 has no cable
self.assertEqual(telemetry.net_cards(counters, stats), ["Ethernet", "Local Area Connection", "enp3s0"])

def test_unreadable_link_state_counts_every_real_card(self):
self.assertEqual(telemetry.net_cards({"lo": Io(0, 0), "eth0": Io(0, 0), "eth1": Io(0, 0)}, None), ["eth0", "eth1"])


class NetRate(unittest.TestCase):
def test_rate_between_two_readings(self):
rx, tx = telemetry.net_rate((10.0, 0, 0, ["eth0"]), (12.0, 20 * MB, 4 * MB, ["eth0"]))
self.assertAlmostEqual(rx, 10.0)
self.assertAlmostEqual(tx, 2.0)

def test_no_rate_without_a_comparable_reading(self):
now = (12.0, 20 * MB, 4 * MB, ["eth0"])
for prev in (None, # first reading
(12.0, 0, 0, ["eth0"]), # the clock did not move on
(10.0, 30 * MB, 0, ["eth0"]), # a counter went back (driver reset)
(10.0, 0, 0, ["eth0", "eth1"])): # a card went down: its bytes leave the sum
self.assertEqual(telemetry.net_rate(prev, now), (None, None), prev)


class Sampler(unittest.TestCase):
"""Telemetry._net and the opt-in switch, on a Telemetry built without its __init__ (no GPU probe, no thread)."""
def tele(self, ps, net=True):
t = telemetry.Telemetry.__new__(telemetry.Telemetry)
t.ps, t.net, t._net_prev = ps, net, None
return t

def test_two_samples_give_the_rate_over_the_cards_that_count(self):
ps = FakePs({"lo": Io(0, 0), "eth0": Io(0, 0), "docker0": Io(0, 0)}, up={"lo", "eth0", "docker0"})
t = self.tele(ps)
with mock.patch.object(telemetry.time, "time", return_value=100.0):
self.assertEqual(t._net(), (None, None, ["eth0"]))
ps.counters = {"lo": Io(50 * MB, 50 * MB), "eth0": Io(1 * MB, 8 * MB), "docker0": Io(9 * MB, 9 * MB)}
with mock.patch.object(telemetry.time, "time", return_value=102.0):
rx, tx, names = t._net()
self.assertEqual(names, ["eth0"])
self.assertAlmostEqual(rx, 4.0)
self.assertAlmostEqual(tx, 0.5)

def test_no_psutil_or_no_card_reads_nothing(self):
self.assertEqual(self.tele(None)._net(), (None, None, None))
self.assertEqual(self.tele(FakePs({"lo": Io(0, 0)}, up={"lo"}))._net(), (None, None, []))

def test_off_by_default_and_on_with_the_variable(self):
env = {k: v for k, v in os.environ.items() if k != telemetry.NET_ENV}
with mock.patch.dict(os.environ, env, clear=True):
t = telemetry.Telemetry()
try:
self.assertFalse(t.net)
s = t.sample()
self.assertFalse([k for k in s if k.startswith("net_")])
finally:
t.close()
with mock.patch.dict(os.environ, {telemetry.NET_ENV: "1"}):
t = telemetry.Telemetry()
try:
self.assertTrue(t.net)
self.assertEqual(t._net_hist, ("net_rx_mb", "net_tx_mb"))
self.assertTrue({"net_rx_mb", "net_tx_mb", "net_nics"} <= set(t.sample()))
finally:
t.close()


def function_source(text: str, name: str) -> str:
start = text.index(f"function {name}(")
return text[start:text.index("\n}\n", start) + 3]


@unittest.skipUnless(NODE, "node is needed to run the page's own code")
class NetworkCard(unittest.TestCase):
def line(self, hw):
src = function_source((WEB / "app.js").read_text(encoding="utf-8"), "netLine")
script = ("const fmt = (n, d = 0) => (n == null ? '–' : Number(n).toFixed(d));\n"
f"{src}\nprocess.stdout.write(JSON.stringify(netLine({json.dumps(hw)})));")
out = subprocess.run([NODE, "-e", script], capture_output=True, text=True, encoding="utf-8", timeout=60, check=True)
return json.loads(out.stdout)

def test_reading_with_cards_mbit_and_sent(self):
self.assertEqual(self.line({"net_rx_mb": 6.5, "net_tx_mb": 0.25, "net_nics": ["enp3s0"]}),
{"value": "6.5", "sub": "enp3s0 · 55 Mbit/s · out 0.3 MB/s"})
self.assertEqual(self.line({"net_rx_mb": 29.0, "net_tx_mb": None, "net_nics": ["eth0", "eth1"]}),
{"value": "29", "sub": "eth0 + eth1 · 243 Mbit/s"})

def test_first_second_and_no_card(self):
self.assertEqual(self.line({"net_rx_mb": None, "net_tx_mb": None, "net_nics": ["eth0"]}), {"value": None, "sub": ""})
self.assertEqual(self.line({"net_rx_mb": None, "net_tx_mb": None, "net_nics": []}),
{"value": None, "sub": "no network card up"})


if __name__ == "__main__":
unittest.main()
21 changes: 20 additions & 1 deletion terminal/serve/web/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -184,9 +184,12 @@ const METRICS = [
{key: "pcie", label: "PCIe", icon: "link", unit: "", series: "gpu_pcie_rx_mb", tone: "info"},
{key: "cpu", label: "CPU", icon: "cpu", unit: "%", series: "cpu", max: 100},
{key: "disk", label: "Disk read", icon: "disk", unit: "MB/s", series: "disk_read_mb", tone: "info"},
// #447: shown only when the server runs with STRATA_MONITOR_NET=1 (its /metrics then has net_rx_mb)
{key: "net", label: "Network in", icon: "download", unit: "MB/s", series: "net_rx_mb", tone: "info", optIn: true,
hint: "Bytes received over the network cards (internet and LAN); loopback, containers, bridges and VPN tunnels left out."},
];
$("metrics").innerHTML = METRICS.map((m) => `
<div class="st-card metric-card${m.key === "model" ? " model-card" : ""}"><div class="st-metric">
<div class="st-card metric-card${m.key === "model" ? " model-card" : ""}"${m.optIn ? ` id="mc-${m.key}" hidden` : ""}><div class="st-metric">
<span class="st-metric__label" id="ml-${m.key}"${m.hint ? ` title="${esc(m.hint)}"` : ""}>${icon(m.icon, "st-icon st-icon--sm")}${esc(m.label)}</span>
${m.key === "speed" ? `<div class="speed-values">
<div><span class="st-metric__value" id="mv-speed">-</span><span class="st-metric__sub" id="ms-speed">Decode</span><span class="st-metric__sub speed-range" id="sr-speed"></span></div>
Expand All @@ -211,6 +214,16 @@ function spark(id, values, max) {
svg.querySelector(".line").setAttribute("d", line);
svg.querySelector(".area").setAttribute("d", `${line}L100,32L0,32Z`);
}
// The Network card (#447): MB/s received; under it the cards counted, the same in Mbit/s, and MB/s sent
function netLine(hw) {
const num = (v) => fmt(v, v < 10 ? 1 : 0);
if (hw.net_rx_mb == null) return {value: null, sub: hw.net_nics && !hw.net_nics.length ? "no network card up" : ""};
const parts = hw.net_nics && hw.net_nics.length ? [hw.net_nics.join(" + ")] : [];
parts.push(`${num(hw.net_rx_mb * 8.388608)} Mbit/s`);
if (hw.net_tx_mb != null) parts.push(`out ${num(hw.net_tx_mb)} MB/s`);
return {value: num(hw.net_rx_mb), sub: parts.join(" · ")};
}

function setMetric(key, value, unit, sub, why) {
$(`mv-${key}`).innerHTML = value == null ? "–" : `${esc(value)}${unit ? `<small>${esc(unit)}</small>` : ""}`;
$(`ms-${key}`).textContent = sub || "";
Expand Down Expand Up @@ -721,6 +734,12 @@ function renderMonitor(live, hw, st, eng, h, last, requests, totals, kept) {
hw.disk_write_mb == null ? "" : `write ${fmt(hw.disk_write_mb, 1)} MB/s`);
}
spark("sp-disk", h.disk_read_mb);
$("mc-net").hidden = !("net_rx_mb" in hw);
if ("net_rx_mb" in hw) {
const net = netLine(hw);
setMetric("net", net.value, "MB/s", st.psutil ? net.sub : "needs psutil (setup installs it)");
spark("sp-net", h.net_rx_mb);
}
// power and temperature averages (#4968); after the cards block above so that block stays self-contained
sampleHw(hw, !!live.state && live.state !== "idle" && live.state !== "unloaded", `${totals && totals.since}|${eng.model || ""}`);

Expand Down
2 changes: 1 addition & 1 deletion terminal/serve/web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@
</div>

<div class="metrics" id="metrics">
<!-- filled by app.js: Speed, GPU load, VRAM, GPU temp, Power, PCIe, CPU, Disk read -->
<!-- filled by app.js: Speed, GPU load, VRAM, GPU temp, Power, PCIe, CPU, Disk read, Network in (opt-in) -->
</div>

<div class="monitor-row">
Expand Down