diff --git a/serve/server.py b/serve/server.py index 1951d998..b0087266 100644 --- a/serve/server.py +++ b/serve/server.py @@ -441,7 +441,10 @@ class Service: self.embeddings = threading.local() # the current request's image embeddings file (GENI) self.api_key = "" # when set, /v1/* needs it (Bearer or x-api-key) self.status = {"busy": False, "queued": 0} # GET /status: what the model is doing right now - self.history = collections.deque(maxlen=30) # the last finished requests, newest last (GET /metrics) + self.history = collections.deque(maxlen=500) # the last finished requests, newest last (GET /metrics) + # since the server started (the Monitor's totals, issue #35) + self.totals = {"since": time.time(), "requests": 0, "prompt_tokens": 0, "reused": 0, "output_tokens": 0, + "prompt_ms": 0.0, "decode_ms": 0.0} self.status_lock = threading.Lock() self.stop_ids = set(tokenizer.encode(IM_END, parse_special=True) + tokenizer.encode("<|endoftext|>", parse_special=True)) @@ -494,12 +497,13 @@ class Service: return 0.0 return s["generated"] / max(1e-6, time.time() - s["first_token"]) - def metrics(self) -> dict: + def metrics(self, all_requests=False) -> dict: """GET /metrics: what the Monitor tab shows - the engine's facts, what it is doing, the last requests, and the hardware (with a minute of history per series).""" with self.status_lock: s = dict(self.status) hist = list(self.history) + totals = dict(self.totals) now = time.time() progress = getattr(self.engine, "progress", None) if s.get("busy") and s.get("first_token") is None: @@ -519,7 +523,9 @@ class Service: engine = {"model": self.model, "max_context": self.engine.max_context, "images": self.vision is not None, **dict(getattr(self.engine, "info", {}) or {})} tel = self.telemetry.snapshot() if getattr(self, "telemetry", None) else {"now": {}, "history": {}, "static": {}} - return {"engine": engine, "live": live, "requests": hist[::-1], "hardware": tel["now"], "hardware_static": + return {"engine": engine, "live": live, "requests": hist[::-1][:None if all_requests else 12], + "requests_kept": len(hist), "totals": totals, "hardware": tel["now"], + "hardware_static": tel["static"], "history": tel["history"], "time": now} def prepare(self, messages, tools, kwargs, max_new=None): @@ -679,6 +685,13 @@ class Service: "prompt_ms": last.get("prompt_ms"), "decode_ms": last.get("decode_ms"), "decode_tok_s": round(last["generated"] / (last["decode_ms"] / 1000), 1) if n and last.get("generated") and last.get("decode_ms") else None}) + t = self.totals + t["requests"] += 1 + t["prompt_tokens"] += len(ids) + t["reused"] += last.get("reused") or 0 + t["output_tokens"] += n + t["prompt_ms"] += last.get("prompt_ms") or 0.0 + t["decode_ms"] += last.get("decode_ms") or 0.0 now = time.time() el = now - self.status.get("started", now) ft = self.status.get("first_token") @@ -930,7 +943,8 @@ def make_handler(svc: Service): return if path == "/metrics": if self._authorized(): - self._json(200, svc.metrics()) + # the last 12 requests; `?requests=all` every one kept (the Monitor's "Show all", issue #35) + self._json(200, svc.metrics(all_requests="requests=all" in self.path)) return if path == "/settings": if self._authorized(): diff --git a/serve/web/app.css b/serve/web/app.css index 9c8e190b..d4fc23b3 100644 --- a/serve/web/app.css +++ b/serve/web/app.css @@ -94,6 +94,10 @@ main { flex: 1; min-height: 0; display: flex; } margin-top: var(--st-s-2); font-variant-numeric: tabular-nums; } .req-card { display: flex; flex-direction: column; gap: var(--st-s-3); min-width: 0; } .table-wrap { overflow-x: auto; } +.req-head { display: flex; align-items: center; justify-content: space-between; gap: var(--st-s-2); } +.table-wrap.all { max-height: 420px; overflow-y: auto; } +.req-totals { margin: 0; font-size: var(--st-fs-sm); } +.req-totals:empty { display: none; } /* ---------------------------------------------------------------- about */ .about { max-width: 860px; } diff --git a/serve/web/app.js b/serve/web/app.js index 9ec3eaa6..43757b9a 100644 --- a/serve/web/app.js +++ b/serve/web/app.js @@ -143,9 +143,10 @@ function setMetric(key, value, unit, sub) { } let lastMetrics = null, metricsFailures = 0, keyWarned = false; +let reqShowAll = false; // the Monitor's request table: the last 12, or every one the server keeps (issue #35) async function poll() { try { - const r = await fetch("/metrics", {headers: headers()}); + const r = await fetch(reqShowAll ? "/metrics?requests=all" : "/metrics", {headers: headers()}); if (r.status === 401) { setPill("error", "API key needed"); if (!keyWarned) { keyWarned = true; toast("warn", "API key needed", "This server needs a key: add it under About > Settings.", 6000); } @@ -180,11 +181,20 @@ function render(m) { setPill("idle", "Idle"); } if (live.queued > 0) setPill("queued", `${live.queued} queued`); - if (tab === "monitor") renderMonitor(live, hw, st, eng, h, last, m.requests || []); + if (tab === "monitor") renderMonitor(live, hw, st, eng, h, last, m.requests || [], m.totals, m.requests_kept); if (tab === "about") renderAbout(eng, hw, st); } -function renderMonitor(live, hw, st, eng, h, last, requests) { +function renderTotals(t) { + if (!t || !t.requests) return ""; + const since = new Date(t.since * 1000).toLocaleString([], {weekday: "short", hour: "2-digit", minute: "2-digit"}); + const read = t.prompt_tokens - t.reused; + const pSpeed = t.prompt_ms > 0 && read > 0 ? ` at ${fmt(read / (t.prompt_ms / 1000))} tok/s` : ""; + const oSpeed = t.decode_ms > 0 && t.output_tokens > 0 ? ` at ${fmt(t.output_tokens / (t.decode_ms / 1000), 1)} tok/s` : ""; + return `Since ${since}: ${fmt(t.requests)} requests · ${fmt(read)} prompt tokens read${pSpeed} (${fmt(t.reused)} reused) · ` + + `${fmt(t.output_tokens)} written${oSpeed}`; +} +function renderMonitor(live, hw, st, eng, h, last, requests, totals, kept) { // model state const on = live.queued > 0 ? "queued" : live.state; for (const b of document.querySelectorAll("#state-badges .st-badge")) b.classList.toggle("on", b.dataset.s === on || b.dataset.s === live.state); @@ -268,7 +278,7 @@ function renderMonitor(live, hw, st, eng, h, last, requests) { } else { const badge = {stop: ["", "Done"], length: ["", "Max tokens"], cancel: ["st-badge--queued", "Stopped"], disconnect: ["st-badge--queued", "Closed"], error: ["st-badge--error", "Error"]}; - body.innerHTML = requests.slice(0, 12).map((r) => { + body.innerHTML = requests.slice(0, reqShowAll ? requests.length : 12).map((r) => { const [cls, text] = badge[r.finish] || ["", r.finish || "–"]; const t = new Date(r.time * 1000).toLocaleTimeString([], {hour: "2-digit", minute: "2-digit", second: "2-digit"}); const proj = r.projection == null ? "" : ` ${r.projection ? "ESP" : "stock"}`; @@ -277,6 +287,12 @@ function renderMonitor(live, hw, st, eng, h, last, requests) { ${fmt(r.duration_s, 1)} s`; }).join(""); } + const all = $("req-all"); + kept = kept == null ? requests.length : kept; + all.hidden = kept <= 12; + all.textContent = reqShowAll ? "Show fewer" : `Show all (${kept})`; + $("req-wrap").classList.toggle("all", reqShowAll); + $("req-totals").textContent = renderTotals(totals); } function facts(el, rows) { @@ -320,6 +336,7 @@ document.addEventListener("click", (e) => { const b = e.target.closest("[data-copy]"); if (b) copyText(b.dataset.copy, b); }); +$("req-all").addEventListener("click", () => { reqShowAll = !reqShowAll; if (lastMetrics) render(lastMetrics); }); // ------------------------------------------------------------------ Markdown (escaped first, then formatted) function inline(s) { diff --git a/serve/web/index.html b/serve/web/index.html index 60901f4a..bdf2b86e 100644 --- a/serve/web/index.html +++ b/serve/web/index.html @@ -112,14 +112,16 @@
- Recent requests -
+
Recent requests +
+
TimeStatusPromptReusedOutput Tok/sDuration
No requests yet
+

diff --git a/setup.py b/setup.py index 40ec012d..2a9d1568 100644 --- a/setup.py +++ b/setup.py @@ -717,7 +717,7 @@ def main() -> int: ap.add_argument("--experimental-speed-projection", metavar="on|off|GGUF", help="EXPERIMENTAL, off by default: the control vector in data/experimental-speed-projection " "(or another GGUF) as a projection on layers 4-44; see docs/DETAILS.md") - ap.add_argument("--port", type=int, default=8080) + ap.add_argument("--port", type=int, help="the server's port (default: the one the install was set up with, 8080 for a new one)") ap.add_argument("--host", help="where the server listens: 127.0.0.1 = this PC only (default), 0.0.0.0 = also other " "devices on your network (issue #26; set --api-key too)") ap.add_argument("--api-key", help="require this key from clients (recommended with --host 0.0.0.0)") @@ -732,6 +732,7 @@ def main() -> int: ap.add_argument("--check", action="store_true", help="only check this PC and exit") ap.add_argument("--skip-build", action="store_true", help=argparse.SUPPRESS) a = ap.parse_args() + port = a.port or 8080 # a new install's port (issue #32: --port for an existing one) say("Strata - Qwen3.8-Flash-Next on a normal PC (NVIDIA GPU + system RAM + CPU)") @@ -741,14 +742,14 @@ def main() -> int: if not a.build: update_installed_engine(a.prebuilt) if len(have) == 1: - return start(have[0], None) + return start(have[0], a.port) say() for i, c in enumerate(have, 1): say(f" {i}) {json.loads(c.read_text(encoding='utf-8-sig')).get('model_name', c.stem)}") say(f" {len(have) + 1}) install another model / change settings") pick = int(ask("Which one?", [str(i) for i in range(1, len(have) + 2)], "1", a.yes)) if pick <= len(have): - return start(have[pick - 1], None) + return start(have[pick - 1], a.port) # ---- 1. the PC step(1, "checking your PC") @@ -986,7 +987,7 @@ def main() -> int: "--cvec-mode", "project", "--cvec-dir", "per-layer"] cfg = {"exe": str(eng / EXE), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"), "model_name": f"{fam['name']}-{model.lower()}", "log": str(ROOT / f"strata-{tag.lower()}.log"), - "lib_dirs": lib_dirs, "port": a.port} + "lib_dirs": lib_dirs, "port": port} if a.host: cfg["host"] = a.host if a.api_key: @@ -998,22 +999,22 @@ def main() -> int: cfg["vision"]["threads"] = max(1, (os.cpu_count() or 8) // 2) cfg_path = ROOT / f"strata-{tag.lower()}.json" cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8") - script = write_run_script(tag, cfg_path, a.port) + script = write_run_script(tag, cfg_path, port) ok(f"start script: {script.name}") say() say("All set.") - say(f" API (OpenAI): http://127.0.0.1:{a.port}/v1 (any API key; model name: anything)") - say(f" API (Anthropic): http://127.0.0.1:{a.port}/v1/messages") + say(f" API (OpenAI): http://127.0.0.1:{port}/v1 (any API key; model name: anything)") + say(f" API (Anthropic): http://127.0.0.1:{port}/v1/messages") if a.host and a.host not in ("127.0.0.1", "localhost"): - say(f" Other devices: the server window prints this PC's address (http://:{a.port}/)" + say(f" Other devices: the server window prints this PC's address (http://:{port}/)" + ("" if a.api_key else " - no API key set: anyone on your network can use it")) say(f" Next time: just run {'START-HERE.bat' if WIN else './setup.sh'} (or {script.name}) - it starts right away") if vision != "none": say(" Images: send them in the chat page, in chat.py (/image ) or over the API") if a.no_start: return 0 - return start(cfg_path, a.port) + return start(cfg_path, port) if __name__ == "__main__": diff --git a/setup.sh b/setup.sh old mode 100644 new mode 100755 index 5ba074ce..c5b1249d --- a/setup.sh +++ b/setup.sh @@ -2,10 +2,17 @@ # Strata for Linux: the first run installs everything and starts the model; later runs just start it. # Needs only an NVIDIA driver. Python (with venv) is installed through apt/dnf if it is missing (asks for sudo). cd "$(dirname "$0")" || exit 1 +# Python 3.10+ that can make a venv WITH pip: Debian/Ubuntu ship `venv` without `ensurepip` (that is the separate +# python3-venv package), and a venv made without it has no pip +ok_py() { "$1" -c 'import sys, venv, ensurepip; sys.exit(0 if sys.version_info >= (3, 10) else 1)' 2>/dev/null; } +# a .venv from an earlier run that failed half-way has a python but no pip: start it again +if [ -x .venv/bin/python ] && ! .venv/bin/python -m pip --version >/dev/null 2>&1; then + rm -rf .venv +fi if [ ! -x .venv/bin/python ]; then PY="" for c in python3 python; do - if command -v $c >/dev/null 2>&1 && $c -c 'import sys, venv; sys.exit(0 if sys.version_info >= (3, 10) else 1)' 2>/dev/null; then + if command -v $c >/dev/null 2>&1 && ok_py $c; then PY=$c; break fi done @@ -19,12 +26,13 @@ if [ ! -x .venv/bin/python ]; then sudo pacman -S --noconfirm python python-pip fi PY=python3 - if ! $PY -c 'import sys, venv; sys.exit(0 if sys.version_info >= (3, 10) else 1)' 2>/dev/null; then - echo "Please install Python 3.10 or newer (with venv), then run ./setup.sh again." + if ! ok_py $PY; then + echo "Please install Python 3.10 or newer with venv (Ubuntu/Debian: sudo apt install python3-venv), then run" + echo "./setup.sh again." exit 1 fi fi # a private environment inside this folder (system Python stays untouched; newer distros refuse global pip) - $PY -m venv .venv || { echo "could not create .venv: sudo apt install python3-venv"; exit 1; } + $PY -m venv .venv || { rm -rf .venv; echo "could not create .venv: sudo apt install python3-venv"; exit 1; } fi exec .venv/bin/python setup.py "$@" diff --git a/src/kernels/cpu/pool.cpp b/src/kernels/cpu/pool.cpp index 87841231..c5f4075d 100644 --- a/src/kernels/cpu/pool.cpp +++ b/src/kernels/cpu/pool.cpp @@ -55,13 +55,38 @@ std::vector physical_cores(bool skip_first) { } } #else + // The logical CPUs this process may run on, ONE PER PHYSICAL CORE (issue #40): SMT siblings share a core's + // load/store bandwidth, so a worker on each would put two workers on one core, as the Windows branch above + // explains. sysfs names each CPU's (package, core); the first allowed CPU of each pair is kept, so a taskset + // that leaves out the first sibling still gets its core. Without sysfs every allowed CPU counts, as before. + auto topo = [](int cpu, const char* what) -> long { + char path[96]; + std::snprintf(path, sizeof path, "/sys/devices/system/cpu/cpu%d/topology/%s", cpu, what); + long v = -1; + if (std::FILE* f = std::fopen(path, "r")) { + if (std::fscanf(f, "%ld", &v) != 1) v = -1; + std::fclose(f); + } + return v; + }; + std::vector allowed; cpu_set_t set; CPU_ZERO(&set); if (sched_getaffinity(0, sizeof set, &set) == 0) { for (int i = 0; i < CPU_SETSIZE; ++i) - if (CPU_ISSET(i, &set)) cores.push_back(i); + if (CPU_ISSET(i, &set)) allowed.push_back(i); } else { - for (unsigned i = 0; i < std::thread::hardware_concurrency(); ++i) cores.push_back((int) i); + for (unsigned i = 0; i < std::thread::hardware_concurrency(); ++i) allowed.push_back((int) i); + } + std::vector> seen; + for (int cpu : allowed) { + const long pkg = topo(cpu, "physical_package_id"), core = topo(cpu, "core_id"); + if (pkg >= 0 && core >= 0) { + const std::pair key{pkg, core}; + if (std::find(seen.begin(), seen.end(), key) != seen.end()) continue; // an SMT sibling + seen.push_back(key); + } + cores.push_back(cpu); } #endif if (skip_first && !cores.empty()) cores.erase(cores.begin());