pi-splash-server 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -2
- package/data/bench.txt +15 -0
- package/extensions/splash.ts +37 -7
- package/package.json +1 -1
- package/src/bench-env.ts +75 -0
- package/src/bench-report.ts +58 -0
- package/src/bench.ts +189 -0
- package/src/mac.ts +12 -1
- package/src/server.ts +26 -13
package/README.md
CHANGED
|
@@ -64,6 +64,7 @@ In Pi:
|
|
|
64
64
|
/splash start [model] start the recommended model, or any repo or repo:QUANT, in the background and switch to it
|
|
65
65
|
/splash status and the next step
|
|
66
66
|
/splash use switch to a Splash server started outside Pi
|
|
67
|
+
/splash bench [--long] measure speed and memory use on the running server
|
|
67
68
|
/splash stop stop the server
|
|
68
69
|
/splash log last lines of the server log
|
|
69
70
|
/splash install put the runtime's install command into the editor
|
|
@@ -85,6 +86,14 @@ comes in about 1 s instead of about 10 s on an M1 Pro. Splash 1.7.3 would not
|
|
|
85
86
|
keep such a state for a system prompt and tools under 2,048 tokens, as Pi's
|
|
86
87
|
are, unless the first message is a few words long.
|
|
87
88
|
|
|
89
|
+
## Measure your Mac
|
|
90
|
+
|
|
91
|
+
`/splash bench` measures prompt processing, cache reuse, decode speed and memory
|
|
92
|
+
use for any model started with `/splash start <repo or repo:QUANT>`. Close other
|
|
93
|
+
heavy apps and allow a few minutes, or longer with `--long` for a 32K prompt
|
|
94
|
+
if the context allows it. We welcome results as
|
|
95
|
+
[issues in this repo](https://github.com/sady4850/pi-splash-server/issues).
|
|
96
|
+
|
|
88
97
|
## What it picks
|
|
89
98
|
|
|
90
99
|
Qwen3.8-27B, by memory:
|
|
@@ -98,8 +107,8 @@ Qwen3.8-27B, by memory:
|
|
|
98
107
|
| 16 GB | `prism-ml/Ternary-Bonsai-2-27B-gguf:PQ2_0` | `--language-only` |
|
|
99
108
|
|
|
100
109
|
`/splash doctor` shows the evidence for each pick (measured on which Mac, or
|
|
101
|
-
not yet). The table lives in `data/recommendations.json
|
|
102
|
-
and 64 GB Macs are welcome.
|
|
110
|
+
not yet). The table lives in `data/recommendations.json`. Reports from
|
|
111
|
+
`/splash bench` on 16, 24 and 64 GB Macs are welcome.
|
|
103
112
|
|
|
104
113
|
## Settings
|
|
105
114
|
|
package/data/bench.txt
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
Field notes from the river survey
|
|
2
|
+
|
|
3
|
+
Each station keeps a notebook beside the gauge. At the start of a shift, the observer reads the water level against the brass mark on the east wall. The mark stays in the same place when the gauge is removed for cleaning. In winter a thin sheet of ice sometimes touches the ruler. The observer records that condition before breaking the ice to take a second reading.
|
|
4
|
+
|
|
5
|
+
The notebook has a pair of columns for each visit. The first column holds the reading exactly as it appeared in the field. The second holds the height relative to the survey datum. If the observer has to repeat a reading, both entries stay on the page. A short explanation beside the entry usually settles the matter when the office prepares its monthly tables.
|
|
6
|
+
|
|
7
|
+
At the end of each week a technician walks the bank between the station and the footbridge. Fallen branches can divert a small stream toward the stilling pool. A branch near the inlet can also make the gauge respond slowly to a rising river. The technician draws a plan of the inlet and writes down the distance from the nearest bridge pier. This makes it possible to find the same obstruction after the water has fallen.
|
|
8
|
+
|
|
9
|
+
Samples travel in glass bottles packed upright in a wooden case. A paper label on the cap carries the station code and the local time. A second label sits inside a clear sleeve on the bottle. When the case reaches the laboratory, the receiving clerk compares the two labels with the dispatch sheet before assigning a shelf. Bottles with a broken seal go on a separate tray for review.
|
|
10
|
+
|
|
11
|
+
The afternoon team checks the recorder clock against the office clock. A difference of a minute matters during a sudden rise because the upstream station may see the crest only a few minutes before the lower station. The team enters the difference in the log. The original series keeps the times shown on the recorder, and the working series carries the corrected times.
|
|
12
|
+
|
|
13
|
+
On quiet days the survey boat follows a line marked by two painted posts. One observer holds the sounding rod while another reads the distance from a tape stretched across the deck. The boat returns along the same line for a second pass. Where the bottom is soft, the rod sinks a little farther on each pass. The observer describes the surface in words as well as reporting a depth.
|
|
14
|
+
|
|
15
|
+
Before filing a chart, the office checks its scale against the first and last soundings. A nearby station can help explain a sudden change, but its readings cannot replace a missing page. Gaps remain visible on the chart. A note in the margin tells the next reader where to look for the original notebook and which part of the river the chart covers.
|
package/extensions/splash.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { readFileSync } from "node:fs";
|
|
3
3
|
import { join } from "node:path";
|
|
4
|
+
import { runBench } from "../src/bench.ts";
|
|
5
|
+
import { benchReport } from "../src/bench-report.ts";
|
|
4
6
|
import { detectMac, macosWarning, runtimeFor } from "../src/mac.ts";
|
|
5
7
|
import { DRAFT_GB, loadEntries, recommend, diskWarnings, isDownloaded } from "../src/recommend.ts";
|
|
6
8
|
import { bytes, bytesOnDisk, downloadLabel, downloadLines, downloadNotice, gb, planDownload } from "../src/download.ts";
|
|
@@ -55,7 +57,7 @@ export default async function (pi: ExtensionAPI) {
|
|
|
55
57
|
const mac = detectMac();
|
|
56
58
|
const { runtime, pick, smaller } = recommend(mac);
|
|
57
59
|
const l = launcher();
|
|
58
|
-
const installed = l.path ? versionOf(launcherVersion(l.path)) : null;
|
|
60
|
+
const installed = l.path ? versionOf(await launcherVersion(l.path)) : null;
|
|
59
61
|
const [latest, plan] = await Promise.all([
|
|
60
62
|
l.path ? latestRelease(l.name) : Promise.resolve(null),
|
|
61
63
|
pick ? planDownload(pick.model, pick.draft, pick.flags.includes("--language-only")).catch((e: Error) => e) : Promise.resolve(null),
|
|
@@ -204,7 +206,24 @@ export default async function (pi: ExtensionAPI) {
|
|
|
204
206
|
ctx?.ui.setStatus("splash", undefined);
|
|
205
207
|
}
|
|
206
208
|
|
|
209
|
+
let bench: { abort: AbortController; done: Promise<void> } | null = null;
|
|
210
|
+
|
|
211
|
+
async function benchmark(long: boolean, ctx: any, signal: AbortSignal) {
|
|
212
|
+
const p = port();
|
|
213
|
+
const progress = (text: string) => ctx.ui.setStatus("splash", `splash: bench ${text}`);
|
|
214
|
+
try {
|
|
215
|
+
const { result, filename } = await runBench(p, long, signal, launcher, progress);
|
|
216
|
+
ctx.ui.notify(`${benchReport(result)}\nJSON: ~/.pi/agent/splash/${filename}`, result.error ? "error" : "info");
|
|
217
|
+
} catch (e) {
|
|
218
|
+
ctx.ui.notify(`Splash bench: ${signal.aborted ? "aborted" : e instanceof Error ? e.message : String(e)}`, "error");
|
|
219
|
+
} finally {
|
|
220
|
+
bench = null;
|
|
221
|
+
ctx.ui.setStatus("splash", undefined);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
207
225
|
async function stopCmd(ctx: any) {
|
|
226
|
+
bench?.abort.abort();
|
|
208
227
|
const p = port();
|
|
209
228
|
const record = readRecord(p);
|
|
210
229
|
if (!record || describe(record) === "not running") {
|
|
@@ -231,7 +250,7 @@ export default async function (pi: ExtensionAPI) {
|
|
|
231
250
|
}
|
|
232
251
|
const l = launcher();
|
|
233
252
|
if (!l.path) return offer(INSTALL[runtime], `Install ${runtime}`, ctx);
|
|
234
|
-
const installed = versionOf(launcherVersion(l.path));
|
|
253
|
+
const installed = versionOf(await launcherVersion(l.path));
|
|
235
254
|
if (!update) {
|
|
236
255
|
ctx.ui.notify(`${l.name} ${installed ?? "?"} is installed (${l.path}). Newer release: /splash update`, "info");
|
|
237
256
|
return;
|
|
@@ -252,7 +271,11 @@ export default async function (pi: ExtensionAPI) {
|
|
|
252
271
|
if (running && startedByUs(p, running)) follow(p, running.pid, ownedModel(p), ctx);
|
|
253
272
|
});
|
|
254
273
|
|
|
255
|
-
pi.on("session_shutdown", async () =>
|
|
274
|
+
pi.on("session_shutdown", async () => {
|
|
275
|
+
unfollow();
|
|
276
|
+
bench?.abort.abort();
|
|
277
|
+
await bench?.done;
|
|
278
|
+
});
|
|
256
279
|
|
|
257
280
|
pi.on("before_provider_request", async (event: any, ctx: any) => {
|
|
258
281
|
const p = port();
|
|
@@ -265,15 +288,15 @@ export default async function (pi: ExtensionAPI) {
|
|
|
265
288
|
warmed.add(key);
|
|
266
289
|
writeWarmed(STATE_DIR, p, pid, warmed);
|
|
267
290
|
if (!needsWarm(await countTokens(p, event.payload, process.env.SPLASH_API_KEY))) return;
|
|
268
|
-
ctx.ui.setStatus("splash", "splash: caching the system prompt for new sessions");
|
|
291
|
+
if (!bench) ctx.ui.setStatus("splash", "splash: caching the system prompt for new sessions");
|
|
269
292
|
await warm(p, event.payload, process.env.SPLASH_API_KEY);
|
|
270
|
-
ctx.ui.setStatus("splash", undefined);
|
|
293
|
+
if (!bench) ctx.ui.setStatus("splash", undefined);
|
|
271
294
|
});
|
|
272
295
|
|
|
273
296
|
pi.registerCommand("splash", {
|
|
274
|
-
description: "Local Splash server: status, doctor, start [model], stop, use, log, install, update",
|
|
297
|
+
description: "Local Splash server: status, doctor, start [model], bench [--long], stop, use, log, install, update",
|
|
275
298
|
getArgumentCompletions: (prefix: string) => {
|
|
276
|
-
const items = ["doctor", "start", "stop", "use", "log", "install", "update"].filter((s) => s.startsWith(prefix)).map((s) => ({ value: s, label: s }));
|
|
299
|
+
const items = ["doctor", "start", "bench", "bench --long", "stop", "use", "log", "install", "update"].filter((s) => s.startsWith(prefix)).map((s) => ({ value: s, label: s }));
|
|
277
300
|
return items.length ? items : null;
|
|
278
301
|
},
|
|
279
302
|
handler: async (args: string, ctx: any) => {
|
|
@@ -285,6 +308,13 @@ export default async function (pi: ExtensionAPI) {
|
|
|
285
308
|
return ctx.ui.notify((await doctor()).join("\n"), "info");
|
|
286
309
|
case "start":
|
|
287
310
|
return startCmd(rest[0], ctx);
|
|
311
|
+
case "bench": {
|
|
312
|
+
if (rest.length && !(rest.length === 1 && rest[0] === "--long")) return ctx.ui.notify("Usage: /splash bench [--long]", "error");
|
|
313
|
+
if (bench) return ctx.ui.notify("A Splash bench is already running.", "info");
|
|
314
|
+
const abort = new AbortController();
|
|
315
|
+
bench = { abort, done: benchmark(rest[0] === "--long", ctx, abort.signal) };
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
288
318
|
case "stop":
|
|
289
319
|
return stopCmd(ctx);
|
|
290
320
|
case "use": {
|
package/package.json
CHANGED
package/src/bench-env.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { commandOutput, detectMac } from "./mac.ts";
|
|
3
|
+
import { launcherVersion, ownedFlags, readRecord, startedByUs, versionOf, type ServedModel } from "./server.ts";
|
|
4
|
+
|
|
5
|
+
export function swapGB(text: string): number | null {
|
|
6
|
+
const match = /\bused\s*=\s*([\d.]+)\s*([KMGT])\b/i.exec(text);
|
|
7
|
+
return match ? Number(match[1]) * 1024 ** ("KMGT".indexOf(match[2].toUpperCase()) - 2) : null;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function freeMemoryPercent(text: string): number | null {
|
|
11
|
+
const match = /system-wide memory free percentage:\s*(\d+)%/i.exec(text);
|
|
12
|
+
return match ? Number(match[1]) : null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function publicModel(id?: string): string | undefined {
|
|
16
|
+
return id && /^[\w-][\w.-]*(?:\/[\w-][\w.-]*)?(?::[\w.-]+)?$/.test(id) ? id : undefined;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function serverFlags(command: string): string | null {
|
|
20
|
+
const serve = /(?:^|\s)(?:serve|-m server\.server)(?:\s+|$)/.exec(command);
|
|
21
|
+
if (!serve) return null;
|
|
22
|
+
const internal = serve[0].includes("server.server");
|
|
23
|
+
const args = command.slice(serve.index + serve[0].length).trim();
|
|
24
|
+
const flags = [];
|
|
25
|
+
for (const arg of args.split(/\s+(?=--?[a-z])/i)) {
|
|
26
|
+
const option = /^(--?[\w-]+)(?:[=\s]+(.*))?$/.exec(arg);
|
|
27
|
+
if (!option) {
|
|
28
|
+
if (arg && !internal) flags.push(publicModel(arg) ?? "[redacted]");
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
if (option[1] === "--port" || (internal && /^--(?:model|binary|serve-record)$/.test(option[1]))) continue;
|
|
32
|
+
const [, name, value] = option;
|
|
33
|
+
flags.push(name);
|
|
34
|
+
if (value) {
|
|
35
|
+
const privateFlag = /key|token$|password|secret|host|user|path|dir|listen|bind|serial|address|url|header/i.test(name);
|
|
36
|
+
const safe = /^[\w.+:%-]+$/.test(value) || (/^--(?:model|draft-model)$/.test(name) && publicModel(value) === value);
|
|
37
|
+
flags.push(safe && !privateFlag ? value : "[redacted]");
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return flags.join(" ");
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function memorySample() {
|
|
44
|
+
const [swap, free] = await Promise.all([commandOutput("sysctl", ["-n", "vm.swapusage"]), commandOutput("memory_pressure", ["-Q"])]);
|
|
45
|
+
return { swapGB: swapGB(swap), freePercent: freeMemoryPercent(free) };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function environment(port: number, launcher: { name: string; path: string | null }, served: ServedModel & { instanceModel?: string }) {
|
|
49
|
+
const record = readRecord(port);
|
|
50
|
+
const pid = record?.pid;
|
|
51
|
+
const owned = startedByUs(port, record) ? ownedFlags(port) : null;
|
|
52
|
+
const [display, batt, power, therm, command, version] = await Promise.all([
|
|
53
|
+
commandOutput("system_profiler", ["SPDisplaysDataType"]), commandOutput("pmset", ["-g", "batt"]),
|
|
54
|
+
commandOutput("pmset", ["-g"]), commandOutput("pmset", ["-g", "therm"]),
|
|
55
|
+
pid ? commandOutput("ps", ["-o", "args=", "-p", String(pid)]) : "",
|
|
56
|
+
launcher.path ? launcherVersion(launcher.path) : "",
|
|
57
|
+
]);
|
|
58
|
+
const { chip, memoryGB, macos } = detectMac();
|
|
59
|
+
const cores = /Total Number of Cores:\s*(\d+)/i.exec(display);
|
|
60
|
+
const low = /^\s*lowpowermode\s+([01])\b/im.exec(power);
|
|
61
|
+
const warning = /\bthermal(?: warning)?\s*level\s*[:=]\s*(\w+)/i.exec(therm)?.[1];
|
|
62
|
+
return {
|
|
63
|
+
packageVersion: JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version as string,
|
|
64
|
+
chip, memoryGB, macos, gpuCores: cores ? Number(cores[1]) : undefined,
|
|
65
|
+
power: /'AC Power'/.test(batt) ? "AC" : /'Battery Power'/.test(batt) ? "battery" : undefined,
|
|
66
|
+
lowPower: low ? low[1] === "1" : undefined,
|
|
67
|
+
thermalWarning: warning && !/^(0|none|normal|nominal)$/i.test(warning) ? warning : undefined,
|
|
68
|
+
runtime: launcher.name, runtimeVersion: versionOf(version),
|
|
69
|
+
model: publicModel(served.instanceModel) ?? publicModel(served.id) ?? "[local model]", context: served.context, flags: owned ? serverFlags(["serve", ...owned].join(" ")) : serverFlags(command),
|
|
70
|
+
flagsSource: owned ? "start" : "server process",
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export type BenchEnvironment = Awaited<ReturnType<typeof environment>>;
|
|
75
|
+
export type MemorySample = Awaited<ReturnType<typeof memorySample>>;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { BenchRequest, BenchResult } from "./bench.ts";
|
|
2
|
+
|
|
3
|
+
export function stats(values: number[]) {
|
|
4
|
+
if (!values.length) return null;
|
|
5
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
6
|
+
const middle = Math.floor(sorted.length / 2);
|
|
7
|
+
const median = sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
|
|
8
|
+
return { median, min: sorted[0], max: sorted[sorted.length - 1] };
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function cell(values: (number | null | undefined)[], digits: number, scale = 1): string {
|
|
12
|
+
const numbers = values.filter((v): v is number => v != null);
|
|
13
|
+
const range = stats(numbers);
|
|
14
|
+
if (!range) return "-";
|
|
15
|
+
const format = (n: number) => (n * scale).toLocaleString("en-US", { useGrouping: false, maximumFractionDigits: digits });
|
|
16
|
+
const median = format(range.median);
|
|
17
|
+
return numbers.length > 1 && range.min !== range.max ? `${median} (${format(range.min)}-${format(range.max)})` : median;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function row(test: BenchRequest["test"], runs: BenchRequest[]) {
|
|
21
|
+
const decode = test === "code" || test === "prose";
|
|
22
|
+
const hits = runs.flatMap((r, i) => (r.cachedTokens ?? 0) > 0 ? [i + 1] : []);
|
|
23
|
+
const cached = cell(runs.map(r => r.cachedTokens), 1);
|
|
24
|
+
const columns = [
|
|
25
|
+
test, cell(runs.map(r => decode ? r.completionTokens : r.promptTokens), 1),
|
|
26
|
+
decode ? "-" : cell(runs.map(r => r.ttftMs), 2, 0.001),
|
|
27
|
+
test.startsWith("prefill") ? cell(runs.map(r => r.timings.prompt_per_second), 1) : "-",
|
|
28
|
+
decode ? cell(runs.map(r => r.timings.predicted_per_second), 1) : "-",
|
|
29
|
+
decode ? cell(runs.map(r => r.draftAcceptance), 1, 100) : "-",
|
|
30
|
+
test.startsWith("prefill") && hits.length ? `${cached} cache hit #${hits.join(",#")}` : cached,
|
|
31
|
+
];
|
|
32
|
+
return `| ${columns.join(" | ")} |`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function benchReport(result: BenchResult): string {
|
|
36
|
+
const { environment: env, requests, before, after } = result;
|
|
37
|
+
const mac = [
|
|
38
|
+
env.chip, env.gpuCores && `${env.gpuCores}-core GPU`, `${env.memoryGB} GB`, `macOS ${env.macos}`,
|
|
39
|
+
env.power && `on ${env.power}`, env.lowPower != null && `Low Power Mode ${env.lowPower ? "on" : "off"}`,
|
|
40
|
+
env.thermalWarning && `thermal warning ${env.thermalWarning}`,
|
|
41
|
+
].filter(Boolean);
|
|
42
|
+
const seconds = Math.round(result.durationMs / 1000);
|
|
43
|
+
const memory = [];
|
|
44
|
+
if (before.swapGB != null || after.swapGB != null) memory.push(`Swap: ${before.swapGB?.toFixed(1) ?? "?"} -> ${after.swapGB?.toFixed(1) ?? "?"} GB.`);
|
|
45
|
+
if (before.freePercent != null || after.freePercent != null) memory.push(`Free memory: ${before.freePercent ?? "?"}% -> ${after.freePercent ?? "?"}%.`);
|
|
46
|
+
memory.push(`Took ${Math.floor(seconds / 60)} min ${seconds % 60} s.`);
|
|
47
|
+
|
|
48
|
+
return [
|
|
49
|
+
`pi-splash-server bench v${result.benchVersion} (pi-splash-server ${env.packageVersion})`,
|
|
50
|
+
`Mac: ${mac.join(", ")}`, `Runtime: ${env.runtime} ${env.runtimeVersion ?? "unknown version"}`,
|
|
51
|
+
`Model: ${env.model}, ${env.context.toLocaleString("en-US")} context`, `${env.flagsSource === "start" ? "Flags" : "Server process flags"}: ${env.flags === null ? "unavailable" : env.flags || "(none)"}`,
|
|
52
|
+
"", "Median (min-max) across repeats.", "",
|
|
53
|
+
"| test | tokens | TTFT s | prefill tok/s | decode tok/s | draft accepted % | cached |",
|
|
54
|
+
"| --- | --- | --- | --- | --- | --- | --- |",
|
|
55
|
+
...Array.from(new Set(requests.map(r => r.test)), test => row(test, requests.filter(r => r.test === test))),
|
|
56
|
+
"", ...[result.note, result.error && `Stopped: ${result.error}`].filter(Boolean), memory.join(" "),
|
|
57
|
+
].join("\n");
|
|
58
|
+
}
|
package/src/bench.ts
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { environment, memorySample, type BenchEnvironment, type MemorySample } from "./bench-env.ts";
|
|
5
|
+
import { probe, STATE_DIR } from "./server.ts";
|
|
6
|
+
|
|
7
|
+
export const BENCH_VERSION = 1;
|
|
8
|
+
|
|
9
|
+
const code = `Rewrite this TypeScript function with clearer names and add input validation. Answer only with code.
|
|
10
|
+
|
|
11
|
+
function group(a: { day: string; site: string; value: number }[], n: number) {
|
|
12
|
+
const m = new Map<string, number[]>();
|
|
13
|
+
const d = new Map<string, Set<string>>();
|
|
14
|
+
for (const x of a) {
|
|
15
|
+
const k = x.site;
|
|
16
|
+
let v = m.get(k);
|
|
17
|
+
if (!v) {
|
|
18
|
+
v = [];
|
|
19
|
+
m.set(k, v);
|
|
20
|
+
}
|
|
21
|
+
v.push(x.value);
|
|
22
|
+
let s = d.get(k);
|
|
23
|
+
if (!s) {
|
|
24
|
+
s = new Set();
|
|
25
|
+
d.set(k, s);
|
|
26
|
+
}
|
|
27
|
+
s.add(x.day);
|
|
28
|
+
}
|
|
29
|
+
const r = [];
|
|
30
|
+
for (const [k, v] of m) {
|
|
31
|
+
if (v.length < n) continue;
|
|
32
|
+
let t = 0;
|
|
33
|
+
let lo = v[0];
|
|
34
|
+
let hi = v[0];
|
|
35
|
+
for (const x of v) {
|
|
36
|
+
t += x;
|
|
37
|
+
if (x < lo) lo = x;
|
|
38
|
+
if (x > hi) hi = x;
|
|
39
|
+
}
|
|
40
|
+
r.push({
|
|
41
|
+
site: k,
|
|
42
|
+
days: d.get(k)!.size,
|
|
43
|
+
count: v.length,
|
|
44
|
+
mean: t / v.length,
|
|
45
|
+
low: lo,
|
|
46
|
+
high: hi,
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
return r.sort((x, y) => y.mean - x.mean);
|
|
50
|
+
}`;
|
|
51
|
+
|
|
52
|
+
const prose = "Explain in about 250 words how a hash map handles collisions. Write plain prose.";
|
|
53
|
+
const nonce = () => `bench ${randomBytes(12).toString("hex")}`;
|
|
54
|
+
const user = (content: string) => ({ role: "user", content });
|
|
55
|
+
|
|
56
|
+
export async function buildPrompt(source: string, prefix: string, target: number, count: (prompt: string) => Promise<number>, limit = target * 1.05) {
|
|
57
|
+
if (!source || limit < target * 0.95) throw new Error(`Could not fit a ${target}-token prompt`);
|
|
58
|
+
let length = target * 4;
|
|
59
|
+
let lower = 0;
|
|
60
|
+
let upper = Infinity;
|
|
61
|
+
for (let i = 0; i < 24; i++) {
|
|
62
|
+
const prompt = prefix + "\n" + source.repeat(Math.ceil(length / source.length)).slice(0, length);
|
|
63
|
+
const tokens = await count(prompt);
|
|
64
|
+
if (!Number.isInteger(tokens) || tokens <= 0) throw new Error("Invalid input_tokens from count_tokens");
|
|
65
|
+
if (tokens >= target * 0.95 && tokens <= Math.min(target * 1.05, limit)) return prompt;
|
|
66
|
+
if (tokens < target * 0.95) lower = length;
|
|
67
|
+
else upper = length;
|
|
68
|
+
if (upper - lower <= 1 || lower >= target * 64) break;
|
|
69
|
+
length = Number.isFinite(upper) ? Math.floor((lower + upper) / 2) : Math.min(length * 2, Math.ceil(length * target / tokens));
|
|
70
|
+
}
|
|
71
|
+
throw new Error(`Could not fit a ${target}-token prompt`);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function numericFields(obj: any): Record<string, number> {
|
|
75
|
+
return Object.fromEntries(Object.entries(obj ?? {}).filter(([, value]) => Number.isFinite(value))) as Record<string, number>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function parseMeasurement(response: any) {
|
|
79
|
+
const usage = response?.usage;
|
|
80
|
+
if (!Number.isFinite(usage?.prompt_tokens) || !Number.isFinite(usage?.completion_tokens)) throw new Error("Missing token usage");
|
|
81
|
+
const latency = numericFields(response.metrics?.request_latency);
|
|
82
|
+
const timings = numericFields(response.timings);
|
|
83
|
+
const cached = usage.prompt_tokens_details?.cached_tokens;
|
|
84
|
+
return {
|
|
85
|
+
promptTokens: Number(usage.prompt_tokens), completionTokens: Number(usage.completion_tokens),
|
|
86
|
+
cachedTokens: Number.isFinite(cached) ? Number(cached) : null, ttftMs: latency.ttft_ms ?? latency.wall_ms ?? null,
|
|
87
|
+
timings, latency,
|
|
88
|
+
draftAcceptance: timings.draft_n > 0 && timings.draft_n_accepted != null ? timings.draft_n_accepted / timings.draft_n : null,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
type Group = "warm-up" | "prefill 1K" | "prefill 8K" | "replay 8K" | "code" | "prose" | "prefill 32K";
|
|
93
|
+
export type BenchRequest = { test: Group } & ReturnType<typeof parseMeasurement>;
|
|
94
|
+
export type BenchResult = {
|
|
95
|
+
benchVersion: number; startedAt: string; durationMs: number; long: boolean; environment: BenchEnvironment;
|
|
96
|
+
before: MemorySample; after: MemorySample; requests: BenchRequest[]; counts: { test: Group; inputTokens: number }[];
|
|
97
|
+
note?: string; error?: string;
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
type Message = { role: string; content: string };
|
|
101
|
+
type Launcher = { name: string; path: string | null };
|
|
102
|
+
type Progress = (step: string) => void;
|
|
103
|
+
|
|
104
|
+
async function workloads(port: number, model: string, signal: AbortSignal, progress: Progress, result: BenchResult) {
|
|
105
|
+
const { context } = result.environment;
|
|
106
|
+
const url = `http://127.0.0.1:${port}/v1/chat/completions`;
|
|
107
|
+
const apiKey = process.env.SPLASH_API_KEY;
|
|
108
|
+
const headers = { "content-type": "application/json", ...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}) };
|
|
109
|
+
const base = { model, reasoning_effort: "none", temperature: 0 };
|
|
110
|
+
const source = await readFile(new URL("../data/bench.txt", import.meta.url), "utf8");
|
|
111
|
+
const long = result.long && context >= 32768;
|
|
112
|
+
if (result.long && !long) result.note = `Skipped 32K prefill (${context} context).`;
|
|
113
|
+
let step = 0;
|
|
114
|
+
let test: Group = "warm-up";
|
|
115
|
+
|
|
116
|
+
function begin(group: Group) {
|
|
117
|
+
test = group;
|
|
118
|
+
progress(`${++step}/${long ? 13 : 12} ${test}`);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function post(messages: Message[], maxTokens?: number) {
|
|
122
|
+
const path = maxTokens === undefined ? "/count_tokens" : "";
|
|
123
|
+
const body = maxTokens === undefined ? { ...base, messages } : { ...base, messages, stream: false, max_completion_tokens: maxTokens };
|
|
124
|
+
const response = await fetch(url + path, {
|
|
125
|
+
method: "POST", headers, body: JSON.stringify(body), signal: AbortSignal.any([signal, AbortSignal.timeout(30 * 60_000)]),
|
|
126
|
+
});
|
|
127
|
+
if (!response.ok) {
|
|
128
|
+
await response.body?.cancel();
|
|
129
|
+
throw new Error(`${path ? "count_tokens" : "chat/completions"} returned HTTP ${response.status} ${response.statusText}`);
|
|
130
|
+
}
|
|
131
|
+
return response.json();
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function measure(messages: Message[], maxTokens: number) {
|
|
135
|
+
result.requests.push({ test, ...parseMeasurement(await post(messages, maxTokens)) });
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function prefill(group: Group, target: number) {
|
|
139
|
+
begin(group);
|
|
140
|
+
const prompt = await buildPrompt(source, nonce(), target, async (content) => {
|
|
141
|
+
const { input_tokens } = await post([user(content)]);
|
|
142
|
+
result.counts.push({ test, inputTokens: input_tokens });
|
|
143
|
+
return input_tokens;
|
|
144
|
+
}, context - 1);
|
|
145
|
+
const messages = [user(prompt)];
|
|
146
|
+
await measure(messages, 1);
|
|
147
|
+
return messages;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
try {
|
|
151
|
+
begin("warm-up");
|
|
152
|
+
await post([user("Hi")], 1);
|
|
153
|
+
for (let i = 0; i < 3; i++) await prefill("prefill 1K", 1024);
|
|
154
|
+
const messages = await prefill("prefill 8K", 8192);
|
|
155
|
+
begin("replay 8K");
|
|
156
|
+
await measure(messages, 1);
|
|
157
|
+
for (const group of ["code", "prose"] as const) {
|
|
158
|
+
for (let i = 0; i < 3; i++) {
|
|
159
|
+
begin(group);
|
|
160
|
+
await measure([{ role: "system", content: nonce() }, user(group === "code" ? code : prose)], 256);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (long) await prefill("prefill 32K", 32768);
|
|
164
|
+
} catch (e) {
|
|
165
|
+
result.error = `${test}: ${signal.aborted ? "aborted" : e instanceof Error ? e.message : String(e)}`;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export async function runBench(port: number, long: boolean, signal: AbortSignal, launcher: () => Launcher, progress: Progress) {
|
|
170
|
+
const start = new Date();
|
|
171
|
+
progress("checking server");
|
|
172
|
+
const served = await probe(port, signal);
|
|
173
|
+
signal.throwIfAborted();
|
|
174
|
+
if (!served) throw new Error(`No Splash server on port ${port}. Start one: /splash start`);
|
|
175
|
+
progress("collecting environment");
|
|
176
|
+
const env = await environment(port, launcher(), served);
|
|
177
|
+
const before = await memorySample();
|
|
178
|
+
const result: BenchResult = {
|
|
179
|
+
benchVersion: BENCH_VERSION, startedAt: start.toISOString(), durationMs: 0, long,
|
|
180
|
+
environment: env, before, after: before, requests: [], counts: [],
|
|
181
|
+
};
|
|
182
|
+
await workloads(port, served.id, signal, progress, result);
|
|
183
|
+
result.after = await memorySample();
|
|
184
|
+
result.durationMs = Date.now() - start.getTime();
|
|
185
|
+
const filename = `bench-${result.startedAt}.json`;
|
|
186
|
+
await mkdir(STATE_DIR, { recursive: true });
|
|
187
|
+
await writeFile(join(STATE_DIR, filename), JSON.stringify(result, null, 2) + "\n", { mode: 0o600 });
|
|
188
|
+
return { result, filename };
|
|
189
|
+
}
|
package/src/mac.ts
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
|
-
import { execFileSync } from "node:child_process";
|
|
1
|
+
import { execFile, execFileSync } from "node:child_process";
|
|
2
2
|
import { statfsSync } from "node:fs";
|
|
3
3
|
import { homedir, totalmem } from "node:os";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
|
|
6
|
+
const exec = promisify(execFile);
|
|
7
|
+
|
|
8
|
+
export async function commandOutput(cmd: string, args: string[], timeout = 5000): Promise<string> {
|
|
9
|
+
try {
|
|
10
|
+
return (await exec(cmd, args, { timeout, encoding: "utf8" })).stdout.trim();
|
|
11
|
+
} catch {
|
|
12
|
+
return "";
|
|
13
|
+
}
|
|
14
|
+
}
|
|
4
15
|
|
|
5
16
|
export type Mac = {
|
|
6
17
|
chip: string;
|
package/src/server.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { spawn, execFileSync } from "node:child_process";
|
|
|
2
2
|
import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, rmSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
+
import { commandOutput } from "./mac.ts";
|
|
5
6
|
|
|
6
7
|
export const DEFAULT_PORT = 8000;
|
|
7
8
|
export const RUNTIME_DIR = join(homedir(), "Library/Application Support/Splash/runtime");
|
|
@@ -25,12 +26,8 @@ export function findLauncher(name: string): string | null {
|
|
|
25
26
|
}
|
|
26
27
|
}
|
|
27
28
|
|
|
28
|
-
export function launcherVersion(path: string): string {
|
|
29
|
-
|
|
30
|
-
return execFileSync(path, ["--version"], { encoding: "utf8", timeout: 10000 }).trim();
|
|
31
|
-
} catch {
|
|
32
|
-
return "";
|
|
33
|
-
}
|
|
29
|
+
export function launcherVersion(path: string): Promise<string> {
|
|
30
|
+
return commandOutput(path, ["--version"], 10000);
|
|
34
31
|
}
|
|
35
32
|
|
|
36
33
|
export const RELEASES: { [runtime: string]: string } = { "splash-m1": "paperniuk/splash", splash: "incoai/splash" };
|
|
@@ -80,9 +77,13 @@ export function describe(record: Record | null): string {
|
|
|
80
77
|
|
|
81
78
|
const base = (port: number) => `http://127.0.0.1:${port}`;
|
|
82
79
|
|
|
83
|
-
async function getJSON(url: string,
|
|
80
|
+
async function getJSON(url: string, abort?: AbortSignal): Promise<any> {
|
|
84
81
|
try {
|
|
85
|
-
const
|
|
82
|
+
const timeout = AbortSignal.timeout(2000);
|
|
83
|
+
const r = await fetch(url, {
|
|
84
|
+
headers: process.env.SPLASH_API_KEY ? { authorization: `Bearer ${process.env.SPLASH_API_KEY}` } : {},
|
|
85
|
+
signal: abort ? AbortSignal.any([timeout, abort]) : timeout,
|
|
86
|
+
});
|
|
86
87
|
return r.ok ? await r.json() : null;
|
|
87
88
|
} catch {
|
|
88
89
|
return null;
|
|
@@ -107,10 +108,12 @@ export function parseLaterSystem(status: any): boolean {
|
|
|
107
108
|
return outcomes.every((o) => o === "native" || o === "patched");
|
|
108
109
|
}
|
|
109
110
|
|
|
110
|
-
export async function probe(port: number): Promise<ListedModel | null> {
|
|
111
|
-
const model = parseModels(await getJSON(`${base(port)}/v1/models
|
|
111
|
+
export async function probe(port: number, signal?: AbortSignal): Promise<(ListedModel & { instanceModel?: string }) | null> {
|
|
112
|
+
const model = parseModels(await getJSON(`${base(port)}/v1/models`, signal));
|
|
112
113
|
if (!model) return null;
|
|
113
|
-
|
|
114
|
+
const status = await getJSON(`${base(port)}/status`, signal);
|
|
115
|
+
return { ...model, instanceModel: typeof status?.instance?.model === "string" ? status.instance.model : undefined,
|
|
116
|
+
laterSystem: parseLaterSystem(status) };
|
|
114
117
|
}
|
|
115
118
|
|
|
116
119
|
export type StartOptions = { launcher: string; model: string; flags: string[]; port: number; keepAwake: boolean; stopWithPid?: number };
|
|
@@ -127,7 +130,7 @@ export function start(o: StartOptions): number {
|
|
|
127
130
|
const env = { ...process.env, ...(o.stopWithPid ? { SPLASH_APP_PID: String(o.stopWithPid) } : {}) };
|
|
128
131
|
const child = spawn(cmd, rest, { detached: true, stdio: ["ignore", out, out], env });
|
|
129
132
|
child.unref();
|
|
130
|
-
writeFileSync(join(STATE_DIR, `owned-${o.port}.json`), JSON.stringify({ pid: child.pid, model: o.model, started: new Date().toISOString() }));
|
|
133
|
+
writeFileSync(join(STATE_DIR, `owned-${o.port}.json`), JSON.stringify({ pid: child.pid, model: o.model, flags: o.flags, started: new Date().toISOString() }));
|
|
131
134
|
return child.pid!;
|
|
132
135
|
}
|
|
133
136
|
|
|
@@ -139,6 +142,15 @@ export function ownedPid(port: number): number | null {
|
|
|
139
142
|
}
|
|
140
143
|
}
|
|
141
144
|
|
|
145
|
+
export function ownedFlags(port: number): string[] | null {
|
|
146
|
+
try {
|
|
147
|
+
const { flags } = JSON.parse(readFileSync(join(STATE_DIR, `owned-${port}.json`), "utf8"));
|
|
148
|
+
return Array.isArray(flags) && flags.every((f) => typeof f === "string") ? flags : null;
|
|
149
|
+
} catch {
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
142
154
|
export function parentPid(pid: number): number | null {
|
|
143
155
|
try {
|
|
144
156
|
const out = execFileSync("/bin/ps", ["-o", "ppid=", "-p", String(pid)], { encoding: "utf8" }).trim();
|
|
@@ -192,7 +204,8 @@ export async function waitReady(port: number, signal: AbortSignal, onPhase: (tex
|
|
|
192
204
|
if (record?.phase === "ready" && (await probe(port))) return record;
|
|
193
205
|
if (record?.phase === "failed") return record;
|
|
194
206
|
const pid = ownedPid(port);
|
|
195
|
-
|
|
207
|
+
const owner = pid !== null && alive(pid);
|
|
208
|
+
if (!owner && (!record || !alive(record.pid)) && Date.now() - t0 > 5000) return record;
|
|
196
209
|
await new Promise((r) => setTimeout(r, 1000));
|
|
197
210
|
}
|
|
198
211
|
return null;
|