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
43 changes: 43 additions & 0 deletions benchmarks/sdk-overhead/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# SDK overhead benchmarks

These scripts measure what NeuroLink itself costs, apart from the model call:
import time, memory, CPU per `generate()` and `stream()` call, and the
CPU-bound helpers. They were written to answer whether a Rust core would pay
off, and they are kept so the numbers can be rerun after a change such as
lazy loading.

Every call goes to a local fake OpenAI-compatible server
(`mock-server.mjs`) that returns a fixed 300-word reply. The benchmark
processes get only `PATH`, `HOME` and the mock server's settings, so no real
provider key is read and no paid API is called.

## Run

```bash
pnpm run build
node benchmarks/sdk-overhead/run.mjs # 3 runs of 200 calls each
node benchmarks/sdk-overhead/run.mjs --calls 3000 --runs 1
```

`--dist <path>` points at another build, for a before/after comparison. The
build can live anywhere: its own folder, not a folder named `dist`, decides
which loaded modules count as NeuroLink's.

## What each script measures

| Script | Measures |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `call-bench.mjs` | In one fresh process: import time, CPU and memory, then `new NeuroLink()` timed on its own; the first call; CPU per call, p50 and p95 latency and calls per second over sequential calls; then 50 calls at once; memory and heap at the end |
| `import-modules.mjs` | How many modules one import loads, and which packages they come from |
| `cpu-helpers.mjs` | Median time to chunk and tokenize 1 MB of text with each strategy, BM25 indexing and search over 10,000 documents, and 10,000 cosine similarities at 1,536 dimensions |
| `mock-server.mjs` | The fake server. It also runs alone: `node benchmarks/sdk-overhead/mock-server.mjs 18765` |

## Reading the numbers

Import time varies a lot between runs (1.7 to 6.0 s was seen on one
machine), because it is mostly file reads and compiling. Compare medians over
several runs, on the same machine, with nothing else heavy running. The fake
server runs in the parent process, so its CPU is never counted in the child's
figures.

These are not part of CI, and nothing in `test/` depends on them.
116 changes: 116 additions & 0 deletions benchmarks/sdk-overhead/call-bench.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
// Times one fresh process: importing dist/index.js, then generate() or
// stream() against the mock server. Run it through run.mjs, which starts the
// mock server and sets OPENAI_COMPATIBLE_* for this process.
// node --expose-gc call-bench.mjs <dist/index.js> <calls> <generate|stream>
import path from "node:path";
import { performance } from "node:perf_hooks";
import { pathToFileURL } from "node:url";

const [distArg, callsArg = "200", mode = "generate"] = process.argv.slice(2);
const distUrl = distArg.startsWith("file:")
? distArg
: pathToFileURL(path.resolve(distArg)).href;
const calls = Number(callsArg);
const CONCURRENT = 50;
const WARMUP = 20;

const cpuMs = (since) => {
const u = process.cpuUsage(since);
return (u.user + u.system) / 1000;
};
const rssMB = () => process.memoryUsage().rss / 1048576;

const importCpu = process.cpuUsage();
const importStart = performance.now();
const { NeuroLink } = await import(distUrl);
const importResult = {
ms: performance.now() - importStart,
cpuMs: cpuMs(importCpu),
rssMB: rssMB(),
};

const constructCpu = process.cpuUsage();
const constructStart = performance.now();
const neurolink = new NeuroLink();
const constructResult = {
ms: performance.now() - constructStart,
cpuMs: cpuMs(constructCpu),
rssMB: rssMB(),
};

async function one() {
const options = {
input: { text: "hello" },
provider: "openai-compatible",
model: "mock-model",
disableTools: true,
};
if (mode === "stream") {
const result = await neurolink.stream(options);
for await (const _ of result.stream) {
// Drain every chunk, as a caller would.
}
return;
}
await neurolink.generate(options);
}

const firstCpu = process.cpuUsage();
const firstStart = performance.now();
await one();
const firstCall = {
ms: performance.now() - firstStart,
cpuMs: cpuMs(firstCpu),
};

for (let i = 0; i < WARMUP; i++) {
await one();
}
global.gc?.();
const rssWarmMB = rssMB();

const latencies = [];
const seqCpu = process.cpuUsage();
const seqStart = performance.now();
for (let i = 0; i < calls; i++) {
const start = performance.now();
await one();
latencies.push(performance.now() - start);
}
const seqWall = performance.now() - seqStart;
const seqCpuMs = cpuMs(seqCpu);
latencies.sort((a, b) => a - b);

const concCpu = process.cpuUsage();
const concStart = performance.now();
await Promise.all(Array.from({ length: CONCURRENT }, one));
const concurrent = {
calls: CONCURRENT,
wallMs: performance.now() - concStart,
cpuMs: cpuMs(concCpu),
rssMB: rssMB(),
};

global.gc?.();
console.log(
JSON.stringify({
mode,
calls,
import: importResult,
construct: constructResult,
firstCall,
rssWarmMB,
perCall: {
cpuMs: seqCpuMs / calls,
p50Ms: latencies[calls >> 1],
p95Ms: latencies[Math.floor(calls * 0.95)],
callsPerSecond: calls / (seqWall / 1000),
},
concurrent,
end: {
rssMB: rssMB(),
heapMB: process.memoryUsage().heapUsed / 1048576,
},
}),
);
process.exit(0);
84 changes: 84 additions & 0 deletions benchmarks/sdk-overhead/cpu-helpers.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// Times the CPU-bound public helpers on realistic inputs: chunking and
// tokenizing 1 MB of text, BM25 over 10,000 documents, and 10,000 cosine
// similarities at 1,536 dimensions.
// node cpu-helpers.mjs <dist/index.js>
import path from "node:path";
import { performance } from "node:perf_hooks";
import { pathToFileURL } from "node:url";

const distArg = process.argv[2];
const neurolink = await import(
distArg.startsWith("file:")
? distArg
: pathToFileURL(path.resolve(distArg)).href
);

const PARAGRAPH =
"Juspay processes payments for merchants across India. The orchestration layer routes each transaction to the best gateway. ";
const TEXT_1MB = PARAGRAPH.repeat(Math.ceil(1_048_576 / PARAGRAPH.length));
const results = [];

async function time(name, fn, reps = 5) {
try {
await fn();
const samples = [];
for (let i = 0; i < reps; i++) {
const start = performance.now();
await fn();
samples.push(performance.now() - start);
}
samples.sort((a, b) => a - b);
results.push({ name, medianMs: samples[samples.length >> 1] });
} catch (error) {
results.push({ name, error: error.message });
}
}

for (const strategy of [
"character",
"recursive",
"sentence",
"token",
"markdown",
]) {
await time(
`chunk 1 MB (${strategy})`,
async () => {
const chunker = await neurolink.createChunker(strategy);
return chunker.chunk(TEXT_1MB, { maxSize: 1000, overlap: 100 });
},
3,
);
}
await time("tokenize 1 MB", () => neurolink.tokenize(TEXT_1MB), 3);

const DOCS = Array.from({ length: 10_000 }, (_, i) => ({
id: `d${i}`,
text: `${PARAGRAPH} document ${i}`,
}));
await time(
"BM25 index 10,000 docs",
async () => {
const index = new neurolink.InMemoryBM25Index();
await index.addDocuments(DOCS);
},
3,
);
const bm25 = new neurolink.InMemoryBM25Index();
await bm25.addDocuments(DOCS);
await time("BM25 search 10,000 docs", () =>
bm25.search("payment gateway routing", 10),
);

const a = Array.from({ length: 1536 }, Math.random);
const b = Array.from({ length: 1536 }, Math.random);
await time("cosine 1536-dim x 10,000", () => {
let sum = 0;
for (let i = 0; i < 10_000; i++) {
sum += neurolink.cosineSimilarity(a, b);
}
return sum;
});

console.log(JSON.stringify({ helpers: results }));
process.exit(0);
48 changes: 48 additions & 0 deletions benchmarks/sdk-overhead/import-modules.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Counts the modules one import of dist/index.js loads, grouped by package.
// node import-modules.mjs <dist/index.js>
import { registerHooks } from "node:module";
import path from "node:path";
import { pathToFileURL } from "node:url";

const distArg = process.argv[2];
const distUrl = distArg.startsWith("file:")
? distArg
: pathToFileURL(path.resolve(distArg)).href;
// The selected build's own folder, wherever it lives (dist/ or a copy).
const buildRoot = new URL(".", distUrl).href;
const loaded = new Set();
registerHooks({
load(url, context, next) {
loaded.add(url);
return next(url, context);
},
});

await import(distUrl);

const byPackage = {};
let ownFiles = 0;
for (const url of loaded) {
const match = url.match(
/node_modules\/\.pnpm\/[^/]+\/node_modules\/((?:@[^/]+\/)?[^/]+)/,
);
if (match) {
byPackage[match[1]] = (byPackage[match[1]] || 0) + 1;
} else if (url.startsWith(buildRoot) && !url.includes("/node_modules/")) {
ownFiles++;
}
}
const top = Object.entries(byPackage)
.sort((a, b) => b[1] - a[1])
.slice(0, 15)
.map(([name, files]) => ({ name, files }));

console.log(
JSON.stringify({
totalModules: loaded.size,
neurolinkFiles: ownFiles,
thirdPartyPackages: Object.keys(byPackage).length,
topPackages: top,
}),
);
process.exit(0);
76 changes: 76 additions & 0 deletions benchmarks/sdk-overhead/mock-server.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// A fake OpenAI-compatible server with a fixed 300-word reply, so the
// benchmarks time NeuroLink's own work and never the network or a model.
import http from "node:http";

const WORDS = Array.from({ length: 300 }, (_, i) => `word${i}`);
const USAGE = { prompt_tokens: 50, completion_tokens: 300, total_tokens: 350 };

function chunk(delta, finishReason, extra = {}) {
return `data: ${JSON.stringify({
id: "bench",
object: "chat.completion.chunk",
created: 1,
model: "mock-model",
choices: [{ index: 0, delta, finish_reason: finishReason }],
...extra,
})}\n\n`;
}

export function startMockServer(port = 0) {
const server = http.createServer((req, res) => {
let body = "";
req.on("data", (c) => (body += c));
req.on("end", () => {
if (req.url.endsWith("/models")) {
res.setHeader("content-type", "application/json");
res.end(
JSON.stringify({
object: "list",
data: [{ id: "mock-model", object: "model" }],
}),
);
return;
}
let request = {};
try {
request = JSON.parse(body || "{}");
} catch {
// A malformed body still gets the plain reply.
}
if (request.stream) {
res.writeHead(200, { "content-type": "text/event-stream" });
for (const word of WORDS) {
res.write(chunk({ content: `${word} ` }, null));
}
res.write(chunk({}, "stop", { usage: USAGE }));
res.end("data: [DONE]\n\n");
return;
}
res.setHeader("content-type", "application/json");
res.end(
JSON.stringify({
id: "bench",
object: "chat.completion",
created: 1,
model: "mock-model",
choices: [
{
index: 0,
message: { role: "assistant", content: WORDS.join(" ") },
finish_reason: "stop",
},
],
usage: USAGE,
}),
);
});
});
return new Promise((resolve) => {
server.listen(port, "127.0.0.1", () => resolve(server));
});
}

if (import.meta.main) {
const server = await startMockServer(Number(process.argv[2] || 0));
console.log(`mock server on http://127.0.0.1:${server.address().port}/v1`);
}
Loading
Loading