offgrid-ai 0.16.0 → 0.17.0
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 +4 -6
- package/package.json +3 -11
- package/src/autodetect.mjs +1 -1
- package/src/backends.mjs +0 -12
- package/src/cli.mjs +1 -4
- package/src/commands/main.mjs +27 -3
- package/src/commands/models.mjs +115 -41
- package/src/commands/onboard.mjs +3 -31
- package/src/commands/run.mjs +2 -5
- package/src/config.mjs +62 -1
- package/src/harness-pi.mjs +3 -5
- package/src/managed.mjs +3 -3
- package/src/mlx-discovery.mjs +94 -1
- package/src/model-name.mjs +2 -2
- package/src/model-presenters.mjs +4 -14
- package/src/omlx-runtime.mjs +232 -0
- package/src/process.mjs +55 -5
- package/src/profile-setup.mjs +253 -70
- package/src/profiles.mjs +11 -3
- package/src/ui.mjs +10 -27
- package/src/benchmark/finalize.mjs +0 -169
- package/src/benchmark/flow.mjs +0 -239
- package/src/benchmark/metrics.mjs +0 -113
- package/src/benchmark/prepare.mjs +0 -118
- package/src/benchmark/repo.mjs +0 -77
- package/src/benchmark/sdk-runner.mjs +0 -363
- package/src/benchmark/shared.mjs +0 -46
- package/src/benchmark.mjs +0 -12
- package/src/commands/benchmark.mjs +0 -4
|
@@ -1,169 +0,0 @@
|
|
|
1
|
-
// ── Benchmark finalization (metadata + summary rendering) ───────────────────
|
|
2
|
-
// unloadModelFromServer has been moved to src/process.mjs (it's the managed-server
|
|
3
|
-
// counterpart to stopProfile, used by both the benchmark flow and the Pi chat flow).
|
|
4
|
-
|
|
5
|
-
import { existsSync } from "node:fs";
|
|
6
|
-
import { readFile, writeFile } from "node:fs/promises";
|
|
7
|
-
import { join } from "node:path";
|
|
8
|
-
import { pc, renderRows, renderSection } from "../ui.mjs";
|
|
9
|
-
|
|
10
|
-
export async function finalizeBenchmarkRun(runDirectory, runResult, speedMetrics, speedMetricsError = null) {
|
|
11
|
-
const metadataPath = join(runDirectory, "metadata.json");
|
|
12
|
-
const metadata = JSON.parse(await readFile(metadataPath, "utf8"));
|
|
13
|
-
const now = new Date();
|
|
14
|
-
const timestamp = now.toISOString();
|
|
15
|
-
|
|
16
|
-
const kind = metadata.kind ?? "visual";
|
|
17
|
-
const isDs = kind === "data-science";
|
|
18
|
-
const requiredFile = isDs ? "analysis.ipynb" : "index.html";
|
|
19
|
-
const requiredPath = join(runDirectory, requiredFile);
|
|
20
|
-
|
|
21
|
-
const outputFiles = [];
|
|
22
|
-
for (const candidate of [requiredFile, isDs ? "summary.json" : "preview.png", isDs ? "chart-distribution.png" : "preview.webm", "preview.mp4"]) {
|
|
23
|
-
if (existsSync(join(runDirectory, candidate))) {
|
|
24
|
-
outputFiles.push(candidate);
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
const success = existsSync(requiredPath) && (await readFile(requiredPath, "utf8")).trim().length > 0;
|
|
29
|
-
const hasTurns = runResult.agentTurns > 0;
|
|
30
|
-
|
|
31
|
-
let failureReason = null;
|
|
32
|
-
if (runResult.error) {
|
|
33
|
-
failureReason = typeof runResult.error === "string" ? runResult.error : (runResult.error.message ?? "Unknown error");
|
|
34
|
-
} else if (!hasTurns) {
|
|
35
|
-
failureReason = "The model did not produce any response turns.";
|
|
36
|
-
} else if (!success) {
|
|
37
|
-
if (runResult.toolCalls === 0) {
|
|
38
|
-
failureReason = `The model finished without writing the required output file (${requiredFile}). It may have returned the response as chat text instead of using the write tool.`;
|
|
39
|
-
} else {
|
|
40
|
-
failureReason = `The required output file (${requiredFile}) was missing or empty after the run.`;
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
const failed = failureReason !== null;
|
|
45
|
-
|
|
46
|
-
metadata.status = failed ? "failed" : "completed";
|
|
47
|
-
metadata.updatedAt = timestamp;
|
|
48
|
-
if (failed) {
|
|
49
|
-
metadata.failedAt = timestamp;
|
|
50
|
-
} else {
|
|
51
|
-
metadata.completedAt = timestamp;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
const totalTokens = runResult.promptTokens + runResult.completionTokens;
|
|
55
|
-
|
|
56
|
-
metadata.runner.tokenMetrics = {
|
|
57
|
-
reported: hasTurns,
|
|
58
|
-
promptTokens: runResult.promptTokens,
|
|
59
|
-
completionTokens: runResult.completionTokens,
|
|
60
|
-
totalTokens,
|
|
61
|
-
};
|
|
62
|
-
|
|
63
|
-
metadata.runner.speedMetrics = speedMetrics;
|
|
64
|
-
metadata.runner.metricSource = speedMetrics?.metricSource ?? null;
|
|
65
|
-
metadata.runner.speedMetricsError = speedMetricsError ?? null;
|
|
66
|
-
|
|
67
|
-
metadata.results = {
|
|
68
|
-
wallClockMs: runResult.wallClockMs,
|
|
69
|
-
agentTurns: runResult.agentTurns,
|
|
70
|
-
toolCalls: runResult.toolCalls,
|
|
71
|
-
toolResults: runResult.toolResults,
|
|
72
|
-
success,
|
|
73
|
-
outputFiles,
|
|
74
|
-
perTurn: runResult.perTurn,
|
|
75
|
-
};
|
|
76
|
-
|
|
77
|
-
if (failureReason) {
|
|
78
|
-
metadata.error = { message: failureReason, ...(typeof runResult.error === "object" && runResult.error?.stack ? { stack: runResult.error.stack } : {}) };
|
|
79
|
-
} else if (runResult.error) {
|
|
80
|
-
metadata.error = typeof runResult.error === "string"
|
|
81
|
-
? { message: runResult.error }
|
|
82
|
-
: { message: runResult.error.message ?? "Unknown error", ...(runResult.error.stack ? { stack: runResult.error.stack } : {}) };
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
await writeFile(metadataPath, JSON.stringify(metadata, null, 2) + "\n", "utf8");
|
|
86
|
-
return metadata;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
function formatMetric(value, formatter) {
|
|
90
|
-
if (value === null || value === undefined || !Number.isFinite(value)) return pc.dim("—");
|
|
91
|
-
return formatter(value);
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
function formatMs(ms) {
|
|
95
|
-
return formatMetric(ms, (n) => (n < 1000 ? `${Math.round(n)} ms` : `${(n / 1000).toFixed(1)} s`));
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
function formatNumber(n) {
|
|
99
|
-
return formatMetric(n, (v) => v.toLocaleString());
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
function formatTokPerSec(n) {
|
|
103
|
-
return formatMetric(n, (v) => `${v.toFixed(1)} tok/s`);
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
function formatPercent(n) {
|
|
107
|
-
return formatMetric(n, (v) => `${(v * 100).toFixed(0)} %`);
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
export function renderBenchmarkSummary(metadata) {
|
|
111
|
-
const { status, results, runner, error } = metadata;
|
|
112
|
-
|
|
113
|
-
const agentRows = [
|
|
114
|
-
["Status", status === "completed" ? pc.green("completed") : pc.red(status ?? "failed")],
|
|
115
|
-
["Duration", formatMs(results?.wallClockMs)],
|
|
116
|
-
["Agent turns", formatNumber(results?.agentTurns)],
|
|
117
|
-
["Input tokens", formatNumber(runner?.tokenMetrics?.promptTokens)],
|
|
118
|
-
["Output tokens", formatNumber(runner?.tokenMetrics?.completionTokens)],
|
|
119
|
-
["Total tokens", formatNumber(runner?.tokenMetrics?.totalTokens)],
|
|
120
|
-
["Tool calls", formatNumber(results?.toolCalls)],
|
|
121
|
-
["Tool results", formatNumber(results?.toolResults)],
|
|
122
|
-
["Output files", (results?.outputFiles?.length ?? 0) > 0 ? results.outputFiles.join(", ") : pc.dim("—")],
|
|
123
|
-
];
|
|
124
|
-
|
|
125
|
-
console.log("");
|
|
126
|
-
console.log(renderSection("Benchmark Result", renderRows(agentRows)));
|
|
127
|
-
|
|
128
|
-
if (status === "completed" && runner?.speedMetrics) {
|
|
129
|
-
const speed = runner.speedMetrics;
|
|
130
|
-
const speedRows = [
|
|
131
|
-
["Prefill tok/s", formatTokPerSec(speed.prefillTokensPerSecond)],
|
|
132
|
-
["Generation tok/s", formatTokPerSec(speed.generationTokensPerSecond)],
|
|
133
|
-
["TTFT", formatMs(speed.ttftMs)],
|
|
134
|
-
["Speculative decode", formatPercent(speed.speculativeDecodeAcceptance)],
|
|
135
|
-
["KV cache tokens", formatNumber(speed.kvCacheTokens)],
|
|
136
|
-
["Model load time", formatMs(speed.modelLoadMs)],
|
|
137
|
-
["Metric source", speed.metricSource ?? pc.dim("—")],
|
|
138
|
-
];
|
|
139
|
-
console.log(renderSection("Speed Metrics", renderRows(speedRows)));
|
|
140
|
-
} else if (error) {
|
|
141
|
-
const wrappedError = wrapText(error.message ?? "Unknown error");
|
|
142
|
-
console.log(renderSection("Error", pc.red(wrappedError)));
|
|
143
|
-
if (error.message?.includes("write tool") || error.message?.includes("required output file")) {
|
|
144
|
-
const tip = wrapText("Tip: This usually means the model returned the answer as chat text instead of writing the file. Try a model with stronger tool-use support, or run the prompt manually.", 64);
|
|
145
|
-
console.log(pc.dim("\n" + tip));
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
if (status === "completed" && !runner?.speedMetrics && runner?.speedMetricsError) {
|
|
150
|
-
console.log(pc.dim(`\nSpeed metrics unavailable: ${runner.speedMetricsError}`));
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
function wrapText(text, width = 64) {
|
|
155
|
-
if (!text) return "";
|
|
156
|
-
const words = text.split(/\s+/);
|
|
157
|
-
const lines = [];
|
|
158
|
-
let current = "";
|
|
159
|
-
for (const word of words) {
|
|
160
|
-
if ((current + " " + word).trim().length > width) {
|
|
161
|
-
if (current) lines.push(current.trim());
|
|
162
|
-
current = word;
|
|
163
|
-
} else {
|
|
164
|
-
current = current ? `${current} ${word}` : word;
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
if (current) lines.push(current.trim());
|
|
168
|
-
return lines.join("\n");
|
|
169
|
-
}
|
package/src/benchmark/flow.mjs
DELETED
|
@@ -1,239 +0,0 @@
|
|
|
1
|
-
// ── Benchmark command flows ───────────────────────────────────────────────────
|
|
2
|
-
|
|
3
|
-
import { join } from "node:path";
|
|
4
|
-
import { ensureDirs } from "../config.mjs";
|
|
5
|
-
import { backendFor } from "../backends.mjs";
|
|
6
|
-
import { serverReady, startServer, waitForReady, stopProfile, modelAvailableOnServer, unloadModelFromServer } from "../process.mjs";
|
|
7
|
-
import { loadProfiles } from "../profiles.mjs";
|
|
8
|
-
import { pc, createPrompt } from "../ui.mjs";
|
|
9
|
-
import { linkBenchmarkRepo } from "./repo.mjs";
|
|
10
|
-
import { loadBenchmarks } from "./shared.mjs";
|
|
11
|
-
import { prepareBenchmarkRun } from "./prepare.mjs";
|
|
12
|
-
import { runBenchmarkInPi } from "./sdk-runner.mjs";
|
|
13
|
-
import { queryServerMetrics } from "./metrics.mjs";
|
|
14
|
-
import { finalizeBenchmarkRun, renderBenchmarkSummary } from "./finalize.mjs";
|
|
15
|
-
|
|
16
|
-
function benchmarkModelSource(profile) {
|
|
17
|
-
if (!profile) return "cloud";
|
|
18
|
-
return profile.providerId === "llama-cpp-mtp" ? "llama-cpp-mtp" : profile.backend === "omlx" ? "omlx" : "llama-cpp";
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
async function chooseBenchmarkAction(prompt, canRun) {
|
|
22
|
-
const choices = [
|
|
23
|
-
{ value: "run", label: "Run Benchmark", hint: "Automated with Pi" },
|
|
24
|
-
{ value: "prepare", label: "Prepare Benchmark (manual)", hint: "Copy prompt and run yourself" },
|
|
25
|
-
];
|
|
26
|
-
return await prompt.choice("Action", canRun ? choices : choices.filter((c) => c.value === "prepare"), canRun ? "run" : "prepare");
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
function managedModelId(profile) {
|
|
30
|
-
return profile.omlxModel ?? profile.modelAlias ?? profile.label;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
async function ensureManagedModelAvailableForBenchmark(profile, backend) {
|
|
34
|
-
if (backend.type !== "managed-server") return;
|
|
35
|
-
if (await modelAvailableOnServer(profile)) return;
|
|
36
|
-
throw new Error(`${managedModelId(profile)} is not available on ${backend.label} at ${profile.baseUrl}.`);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
async function ensureServerForBenchmark(profile) {
|
|
40
|
-
const backend = backendFor(profile.backend);
|
|
41
|
-
if (await serverReady(profile.baseUrl)) {
|
|
42
|
-
await ensureManagedModelAvailableForBenchmark(profile, backend);
|
|
43
|
-
console.log(pc.green(`[ready] ${backend.label} at ${profile.baseUrl}`));
|
|
44
|
-
return { started: false };
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
if (backend.type === "managed-server") {
|
|
48
|
-
throw new Error(`${backend.label} is not running at ${profile.baseUrl}. Start it and try again.`);
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
console.log(pc.dim(`Starting ${backend.label} for ${profile.label}...`));
|
|
52
|
-
const state = await startServer(profile);
|
|
53
|
-
await waitForReady(profile, state?.pid, state?.rawLogPath);
|
|
54
|
-
console.log(pc.green(`[ready] ${profile.baseUrl}/models`));
|
|
55
|
-
return { started: true, state };
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
export async function runPreparedBenchmark(profile, runDirectory, options = {}) {
|
|
59
|
-
const controller = new AbortController();
|
|
60
|
-
if (options.signal) {
|
|
61
|
-
options.signal.addEventListener("abort", () => controller.abort(), { once: true });
|
|
62
|
-
}
|
|
63
|
-
let serverStarted = false;
|
|
64
|
-
let benchmarkStarted = false;
|
|
65
|
-
let metadata;
|
|
66
|
-
|
|
67
|
-
const onSigint = () => {
|
|
68
|
-
controller.abort();
|
|
69
|
-
};
|
|
70
|
-
process.on("SIGINT", onSigint);
|
|
71
|
-
|
|
72
|
-
try {
|
|
73
|
-
const serverState = await ensureServerForBenchmark(profile);
|
|
74
|
-
serverStarted = serverState.started;
|
|
75
|
-
|
|
76
|
-
benchmarkStarted = true;
|
|
77
|
-
const runResult = await runBenchmarkInPi(profile, runDirectory, { signal: controller.signal });
|
|
78
|
-
|
|
79
|
-
let speedMetrics = null;
|
|
80
|
-
let speedMetricsError = null;
|
|
81
|
-
if (!runResult.error) {
|
|
82
|
-
try {
|
|
83
|
-
speedMetrics = await queryServerMetrics(profile);
|
|
84
|
-
} catch (err) {
|
|
85
|
-
// Non-fatal: speed metrics are a supplementary measurement, not the
|
|
86
|
-
// benchmark itself. Don't poison the run result; surface it as a note.
|
|
87
|
-
speedMetricsError = err.message;
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
metadata = await finalizeBenchmarkRun(runDirectory, runResult, speedMetrics, speedMetricsError);
|
|
92
|
-
renderBenchmarkSummary(metadata);
|
|
93
|
-
} catch (err) {
|
|
94
|
-
const failedResult = {
|
|
95
|
-
error: { message: err.message },
|
|
96
|
-
wallClockMs: null,
|
|
97
|
-
agentTurns: 0,
|
|
98
|
-
promptTokens: 0,
|
|
99
|
-
completionTokens: 0,
|
|
100
|
-
totalTokens: 0,
|
|
101
|
-
cacheRead: 0,
|
|
102
|
-
cacheWrite: 0,
|
|
103
|
-
toolCalls: 0,
|
|
104
|
-
toolResults: 0,
|
|
105
|
-
perTurn: [],
|
|
106
|
-
};
|
|
107
|
-
metadata = await finalizeBenchmarkRun(runDirectory, failedResult, null);
|
|
108
|
-
renderBenchmarkSummary(metadata);
|
|
109
|
-
} finally {
|
|
110
|
-
process.removeListener("SIGINT", onSigint);
|
|
111
|
-
if (serverStarted && !options.keepServer) {
|
|
112
|
-
const backend = backendFor(profile.backend);
|
|
113
|
-
if (backend.type !== "managed-server") {
|
|
114
|
-
const result = await stopProfile(profile);
|
|
115
|
-
console.log(result.stopped ? pc.green(`[stop] ${result.message}`) : pc.dim(`[stop] ${result.message}`));
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
if (benchmarkStarted) {
|
|
119
|
-
const unloadResult = await unloadModelFromServer(profile);
|
|
120
|
-
if (!unloadResult.unloaded && unloadResult.error) {
|
|
121
|
-
console.log(pc.yellow(`[unload] ${unloadResult.backend}: ${unloadResult.error}`));
|
|
122
|
-
} else if (!unloadResult.unloaded && unloadResult.reason) {
|
|
123
|
-
console.log(pc.dim(`[unload] ${unloadResult.backend}: ${unloadResult.reason}`));
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
return metadata;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
// ── Shared benchmark selection ────────────────────────────────────────────
|
|
132
|
-
|
|
133
|
-
async function selectBenchmark(prompt, repoPath) {
|
|
134
|
-
const kind = await prompt.choice("Benchmark category", [
|
|
135
|
-
{ value: "visual", label: "Visual Benchmark", hint: "HTML/CSS/JS animation benchmarks" },
|
|
136
|
-
{ value: "data-science", label: "Data Science", hint: "Analysis and charting benchmarks" },
|
|
137
|
-
], "visual");
|
|
138
|
-
|
|
139
|
-
const benchDir = join(repoPath, "benchmarks");
|
|
140
|
-
const benchmarks = (await loadBenchmarks(benchDir)).filter((b) => b.kind === kind);
|
|
141
|
-
if (benchmarks.length === 0) {
|
|
142
|
-
console.log(pc.yellow(`No ${kind} benchmarks found in ${benchDir}`));
|
|
143
|
-
return null;
|
|
144
|
-
}
|
|
145
|
-
const benchmarkId = await prompt.choice("Prompt", benchmarks.map((b) => ({
|
|
146
|
-
value: b.id, label: b.title, hint: b.description || b.id,
|
|
147
|
-
})), benchmarks[0].id);
|
|
148
|
-
const benchmark = benchmarks.find((b) => b.id === benchmarkId);
|
|
149
|
-
if (!benchmark) return null;
|
|
150
|
-
return { kind, benchmark };
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
// ── Benchmark from a selected profile (from model picker) ────────────────
|
|
154
|
-
|
|
155
|
-
export async function benchmarkForProfile(profile) {
|
|
156
|
-
await ensureDirs();
|
|
157
|
-
const prompt = createPrompt();
|
|
158
|
-
try {
|
|
159
|
-
const repoPath = await linkBenchmarkRepo(prompt);
|
|
160
|
-
if (!repoPath) return;
|
|
161
|
-
|
|
162
|
-
const selected = await selectBenchmark(prompt, repoPath);
|
|
163
|
-
if (!selected) return;
|
|
164
|
-
const { kind, benchmark: selectedBenchmark } = selected;
|
|
165
|
-
|
|
166
|
-
const modelId = profile.modelAlias;
|
|
167
|
-
const modelSource = benchmarkModelSource(profile);
|
|
168
|
-
const backendLabel = backendFor(profile.backend).label;
|
|
169
|
-
|
|
170
|
-
const canRun = modelSource !== "cloud";
|
|
171
|
-
const action = await chooseBenchmarkAction(prompt, canRun);
|
|
172
|
-
|
|
173
|
-
const runDirectory = await prepareBenchmarkRun({ repoPath, benchmark: selectedBenchmark, kind, modelId, modelSource, backendLabel, profile, showNextSteps: action === "prepare" });
|
|
174
|
-
|
|
175
|
-
if (action === "run") {
|
|
176
|
-
return await runPreparedBenchmark(profile, runDirectory);
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
return runDirectory;
|
|
180
|
-
} finally {
|
|
181
|
-
prompt.close();
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
// ── Standalone benchmark flow (offgrid-ai benchmark) ──────────────────────
|
|
186
|
-
|
|
187
|
-
export async function benchmarkFlow() {
|
|
188
|
-
await ensureDirs();
|
|
189
|
-
const prompt = createPrompt();
|
|
190
|
-
try {
|
|
191
|
-
const repoPath = await linkBenchmarkRepo(prompt);
|
|
192
|
-
if (!repoPath) return;
|
|
193
|
-
|
|
194
|
-
const selected = await selectBenchmark(prompt, repoPath);
|
|
195
|
-
if (!selected) return;
|
|
196
|
-
const { kind, benchmark: selectedBenchmark } = selected;
|
|
197
|
-
|
|
198
|
-
const profiles = await loadProfiles();
|
|
199
|
-
const source = await prompt.choice("Model source", [
|
|
200
|
-
{ value: "profile", label: "Use existing profile", hint: "Pick a saved offgrid-ai profile" },
|
|
201
|
-
{ value: "cloud", label: "Custom / cloud", hint: "Free-form model label for cloud runs" },
|
|
202
|
-
], "profile");
|
|
203
|
-
|
|
204
|
-
let modelId, modelSource, backendLabel, profile;
|
|
205
|
-
|
|
206
|
-
if (source === "profile") {
|
|
207
|
-
if (profiles.length === 0) {
|
|
208
|
-
console.log(pc.yellow("No profiles yet. Run: offgrid-ai models"));
|
|
209
|
-
return;
|
|
210
|
-
}
|
|
211
|
-
const profileId = await prompt.choice("Profile", profiles.map((p) => ({
|
|
212
|
-
value: p.id, label: p.label, hint: `${backendFor(p.backend).label} · ${p.modelAlias}`,
|
|
213
|
-
})), profiles[0].id);
|
|
214
|
-
profile = profiles.find((p) => p.id === profileId);
|
|
215
|
-
if (!profile) return;
|
|
216
|
-
modelId = profile.modelAlias;
|
|
217
|
-
modelSource = benchmarkModelSource(profile);
|
|
218
|
-
backendLabel = backendFor(profile.backend).label;
|
|
219
|
-
} else {
|
|
220
|
-
backendLabel = await prompt.text("Backend label", "cloud");
|
|
221
|
-
modelId = await prompt.text("Model name", "");
|
|
222
|
-
if (!modelId) { console.log(pc.yellow("Model name is required.")); return; }
|
|
223
|
-
modelSource = "cloud";
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
const canRun = modelSource !== "cloud" && profile != null;
|
|
227
|
-
const action = await chooseBenchmarkAction(prompt, canRun);
|
|
228
|
-
|
|
229
|
-
const runDirectory = await prepareBenchmarkRun({ repoPath, benchmark: selectedBenchmark, kind, modelId, modelSource, backendLabel, profile, showNextSteps: action === "prepare" });
|
|
230
|
-
|
|
231
|
-
if (action === "run" && profile) {
|
|
232
|
-
return await runPreparedBenchmark(profile, runDirectory);
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
return runDirectory;
|
|
236
|
-
} finally {
|
|
237
|
-
prompt.close();
|
|
238
|
-
}
|
|
239
|
-
}
|
|
@@ -1,113 +0,0 @@
|
|
|
1
|
-
// ── Backend-aware server speed metrics ───────────────────────────────────────
|
|
2
|
-
|
|
3
|
-
import { backendFor } from "../backends.mjs";
|
|
4
|
-
|
|
5
|
-
const BENCH_SPEED_PROMPT = "Write a one-sentence summary of machine learning.";
|
|
6
|
-
const SPEED_QUERY_TIMEOUT_MS = 120_000;
|
|
7
|
-
const SPEED_QUERY_MAX_TOKENS = 64;
|
|
8
|
-
|
|
9
|
-
export async function queryServerMetrics(profile) {
|
|
10
|
-
const backend = backendFor(profile.backend);
|
|
11
|
-
|
|
12
|
-
if (backend.id === "llama-cpp" || backend.id === "llama-cpp-mtp") {
|
|
13
|
-
return await queryLlamaCppMetrics(profile);
|
|
14
|
-
}
|
|
15
|
-
if (backend.id === "omlx") {
|
|
16
|
-
return await queryOmlxMetrics(profile);
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
throw new Error(`Unsupported backend for benchmark speed metrics: ${backend.id}`);
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
async function queryLlamaCppMetrics(profile) {
|
|
23
|
-
const body = {
|
|
24
|
-
model: profile.modelAlias,
|
|
25
|
-
messages: [{ role: "user", content: BENCH_SPEED_PROMPT }],
|
|
26
|
-
stream: false,
|
|
27
|
-
max_tokens: SPEED_QUERY_MAX_TOKENS,
|
|
28
|
-
};
|
|
29
|
-
|
|
30
|
-
const response = await fetch(profile.baseUrl.replace(/\/$/u, "") + "/chat/completions", {
|
|
31
|
-
method: "POST",
|
|
32
|
-
headers: { "Content-Type": "application/json" },
|
|
33
|
-
body: JSON.stringify(body),
|
|
34
|
-
signal: AbortSignal.timeout(SPEED_QUERY_TIMEOUT_MS),
|
|
35
|
-
});
|
|
36
|
-
|
|
37
|
-
if (!response.ok) {
|
|
38
|
-
throw new Error(`llama.cpp speed query failed: ${response.status} ${response.statusText}`);
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
const data = await response.json();
|
|
42
|
-
const timings = data.timings;
|
|
43
|
-
if (!timings || typeof timings.prompt_per_second !== "number" || typeof timings.predicted_per_second !== "number") {
|
|
44
|
-
throw new Error("llama.cpp response did not include usable timings object");
|
|
45
|
-
}
|
|
46
|
-
const draftN = timings.draft_n;
|
|
47
|
-
const draftAccepted = timings.draft_n_accepted;
|
|
48
|
-
|
|
49
|
-
return {
|
|
50
|
-
prefillTokensPerSecond: timings.prompt_per_second ?? null,
|
|
51
|
-
generationTokensPerSecond: timings.predicted_per_second ?? null,
|
|
52
|
-
ttftMs: timings.prompt_ms ?? null,
|
|
53
|
-
modelLoadMs: null,
|
|
54
|
-
speculativeDecodeAcceptance: (draftN && Number.isFinite(draftAccepted) && Number.isFinite(draftN) && draftN > 0)
|
|
55
|
-
? draftAccepted / draftN
|
|
56
|
-
: null,
|
|
57
|
-
kvCacheTokens: timings.cache_n ?? null,
|
|
58
|
-
metricSource: "llama.cpp /v1/chat/completions timings",
|
|
59
|
-
};
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
async function queryOmlxMetrics(profile) {
|
|
63
|
-
const body = {
|
|
64
|
-
model: profile.modelAlias,
|
|
65
|
-
messages: [{ role: "user", content: BENCH_SPEED_PROMPT }],
|
|
66
|
-
stream: true,
|
|
67
|
-
stream_options: { include_usage: true },
|
|
68
|
-
max_tokens: SPEED_QUERY_MAX_TOKENS,
|
|
69
|
-
};
|
|
70
|
-
|
|
71
|
-
const response = await fetch(profile.baseUrl.replace(/\/$/u, "") + "/chat/completions", {
|
|
72
|
-
method: "POST",
|
|
73
|
-
headers: { "Content-Type": "application/json" },
|
|
74
|
-
body: JSON.stringify(body),
|
|
75
|
-
signal: AbortSignal.timeout(SPEED_QUERY_TIMEOUT_MS),
|
|
76
|
-
});
|
|
77
|
-
|
|
78
|
-
if (!response.ok) {
|
|
79
|
-
throw new Error(`oMLX speed query failed: ${response.status} ${response.statusText}`);
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
const text = await response.text();
|
|
83
|
-
let usage = null;
|
|
84
|
-
for (const line of text.split("\n").reverse()) {
|
|
85
|
-
const trimmed = line.trim();
|
|
86
|
-
if (!trimmed || !trimmed.startsWith("data:")) continue;
|
|
87
|
-
const payload = trimmed.slice(5).trim();
|
|
88
|
-
if (payload === "[DONE]") continue;
|
|
89
|
-
try {
|
|
90
|
-
const chunk = JSON.parse(payload);
|
|
91
|
-
if (chunk.usage) {
|
|
92
|
-
usage = chunk.usage;
|
|
93
|
-
break;
|
|
94
|
-
}
|
|
95
|
-
} catch {
|
|
96
|
-
// Ignore malformed SSE chunks.
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
if (!usage) {
|
|
101
|
-
throw new Error("oMLX speed query did not return usage in streaming response");
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
return {
|
|
105
|
-
prefillTokensPerSecond: usage.prompt_tokens_per_second ?? null,
|
|
106
|
-
generationTokensPerSecond: usage.generation_tokens_per_second ?? null,
|
|
107
|
-
ttftMs: usage.time_to_first_token != null ? usage.time_to_first_token * 1000 : null,
|
|
108
|
-
modelLoadMs: null,
|
|
109
|
-
speculativeDecodeAcceptance: null,
|
|
110
|
-
kvCacheTokens: usage.prompt_tokens_details?.cached_tokens ?? null,
|
|
111
|
-
metricSource: "oMLX /v1/chat/completions streaming include_usage",
|
|
112
|
-
};
|
|
113
|
-
}
|
|
@@ -1,118 +0,0 @@
|
|
|
1
|
-
// ── Create a benchmark run directory ────────────────────────────────────────
|
|
2
|
-
|
|
3
|
-
import { mkdir, writeFile } from "node:fs/promises";
|
|
4
|
-
import { join } from "node:path";
|
|
5
|
-
import { pc, renderRows, renderSection } from "../ui.mjs";
|
|
6
|
-
import { slugModelId, createRunId } from "./shared.mjs";
|
|
7
|
-
import { parseModelName } from "../model-name.mjs";
|
|
8
|
-
|
|
9
|
-
function harnessDisplayName(id) {
|
|
10
|
-
if (id === "pi") return "Pi";
|
|
11
|
-
return String(id).replace(/[-_]+/gu, " ").replace(/\b\w/gu, (char) => char.toUpperCase());
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
function intendedRunnerForProfile(profile) {
|
|
15
|
-
if (!profile) return "your tool";
|
|
16
|
-
const harnessEntries = Object.entries(profile.harnesses ?? {}).filter(([, config]) => config?.enabled !== false);
|
|
17
|
-
const [id] = harnessEntries.find(([key]) => key === "pi") ?? harnessEntries[0] ?? ["pi"];
|
|
18
|
-
return harnessDisplayName(id);
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
function printBenchmarkNextSteps({ repoPath, runDirectory, profile, modelId, runnerLabel }) {
|
|
22
|
-
const runCommand = profile ? `offgrid-ai run ${profile.id}` : null;
|
|
23
|
-
const runnerCommand = runCommand ?? `Open ${runnerLabel} for ${modelId}`;
|
|
24
|
-
|
|
25
|
-
console.log("");
|
|
26
|
-
console.log(pc.bold("Next steps"));
|
|
27
|
-
console.log(` 1. Open the gallery. If it is not running: ${pc.cyan(`cd ${repoPath} && npm run dev`)}`);
|
|
28
|
-
console.log(` 2. ${pc.cyan(`cd ${runDirectory}`)}`);
|
|
29
|
-
console.log(` 3. ${pc.cyan(runnerCommand)}, then copy this run's prompt from the gallery and paste it into ${runnerLabel}`);
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export async function prepareBenchmarkRun({ repoPath, benchmark, kind, modelId, modelSource, backendLabel, profile, showNextSteps = true }) {
|
|
33
|
-
const toolPrompt = benchmark.prompt;
|
|
34
|
-
const now = new Date();
|
|
35
|
-
const runId = createRunId(now);
|
|
36
|
-
const modelSlug = slugModelId(modelId);
|
|
37
|
-
const runnerLabel = intendedRunnerForProfile(profile);
|
|
38
|
-
const runsDir = join(repoPath, "runs");
|
|
39
|
-
const benchmarkDirectory = join(runsDir, benchmark.id);
|
|
40
|
-
const modelDirectory = join(benchmarkDirectory, modelSlug);
|
|
41
|
-
const runDirectory = join(modelDirectory, runId);
|
|
42
|
-
|
|
43
|
-
await mkdir(runDirectory, { recursive: true });
|
|
44
|
-
|
|
45
|
-
const isDs = kind === "data-science";
|
|
46
|
-
const baseAssets = {
|
|
47
|
-
metadata: "metadata.json",
|
|
48
|
-
prompt: "prompt.md",
|
|
49
|
-
};
|
|
50
|
-
const metadata = {
|
|
51
|
-
schemaVersion: 1,
|
|
52
|
-
kind,
|
|
53
|
-
runId,
|
|
54
|
-
benchmark: { id: benchmark.id, title: benchmark.title, description: benchmark.description, prompt: benchmark.prompt },
|
|
55
|
-
model: { id: modelId, slug: modelSlug, displayName: parseModelName(modelId, modelSource === "omlx" ? "omlx" : "local-gguf").display },
|
|
56
|
-
status: "prepared",
|
|
57
|
-
createdAt: now.toISOString(),
|
|
58
|
-
updatedAt: now.toISOString(),
|
|
59
|
-
preparedAt: now.toISOString(),
|
|
60
|
-
runDirectory,
|
|
61
|
-
assets: isDs
|
|
62
|
-
? { ...baseAssets, ds: { notebook: "analysis.ipynb", summary: "summary.json", chartDistribution: "chart-distribution.png", chartTreatmentEffect: "chart-treatment-effect.png", chartCompletionRates: "chart-completion-rates.png" } }
|
|
63
|
-
: { ...baseAssets, html: "index.html", preview: "preview.png", video: "preview.webm" },
|
|
64
|
-
runner: {
|
|
65
|
-
mode: modelSource === "cloud" ? "manual" : "external",
|
|
66
|
-
intendedRunner: profile ? runnerLabel : undefined,
|
|
67
|
-
...(profile?.harnesses?.pi || runnerLabel === "Pi" ? { tool: "pi" } : {}),
|
|
68
|
-
...(modelSource ? { modelSource } : {}),
|
|
69
|
-
...(backendLabel ? { backendLabel } : {}),
|
|
70
|
-
...(profile?.baseUrl ? { baseUrl: profile.baseUrl } : {}),
|
|
71
|
-
model: modelId,
|
|
72
|
-
retries: 0,
|
|
73
|
-
tokenMetrics: {
|
|
74
|
-
reported: false,
|
|
75
|
-
promptTokens: 0,
|
|
76
|
-
completionTokens: 0,
|
|
77
|
-
totalTokens: 0,
|
|
78
|
-
},
|
|
79
|
-
speedMetrics: {
|
|
80
|
-
prefillTokensPerSecond: null,
|
|
81
|
-
generationTokensPerSecond: null,
|
|
82
|
-
ttftMs: null,
|
|
83
|
-
modelLoadMs: null,
|
|
84
|
-
speculativeDecodeAcceptance: null,
|
|
85
|
-
kvCacheTokens: null,
|
|
86
|
-
},
|
|
87
|
-
metricSource: null,
|
|
88
|
-
},
|
|
89
|
-
results: {
|
|
90
|
-
wallClockMs: null,
|
|
91
|
-
agentTurns: 0,
|
|
92
|
-
toolCalls: 0,
|
|
93
|
-
toolResults: 0,
|
|
94
|
-
success: false,
|
|
95
|
-
outputFiles: [],
|
|
96
|
-
perTurn: [],
|
|
97
|
-
},
|
|
98
|
-
};
|
|
99
|
-
|
|
100
|
-
await writeFile(join(runDirectory, "metadata.json"), JSON.stringify(metadata, null, 2) + "\n", "utf8");
|
|
101
|
-
await writeFile(join(runDirectory, "prompt.md"), toolPrompt + "\n", "utf8");
|
|
102
|
-
|
|
103
|
-
console.log("");
|
|
104
|
-
console.log(pc.green("✓ Run slot prepared"));
|
|
105
|
-
console.log(renderSection("Run", renderRows([
|
|
106
|
-
["Directory", pc.cyan(runDirectory)],
|
|
107
|
-
["Benchmark", benchmark.title],
|
|
108
|
-
["Kind", kind],
|
|
109
|
-
["Model", pc.bold(modelId)],
|
|
110
|
-
["Source", backendLabel || modelSource],
|
|
111
|
-
])));
|
|
112
|
-
|
|
113
|
-
if (showNextSteps) {
|
|
114
|
-
printBenchmarkNextSteps({ repoPath, runDirectory, profile, modelId, runnerLabel });
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
return runDirectory;
|
|
118
|
-
}
|