@fraczak/k 8.8.0 → 8.9.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.
@@ -0,0 +1,279 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * End-to-End Integer Squaring Benchmark: K vs JS BigInt
5
+ *
6
+ * Compares the full UTF-8 decimal string -> parse -> N squarings -> decimal print
7
+ * pipeline between JavaScript BigInt and K (lib/integer.k) across backends:
8
+ * llvm, llvm-pkir, wasm, pkir, kvm, js
9
+ *
10
+ * Usage:
11
+ * node scripts/perf-bigint-compare.mjs [options]
12
+ */
13
+
14
+ import fs from "node:fs";
15
+ import path from "node:path";
16
+ import { performance } from "node:perf_hooks";
17
+ import { fileURLToPath } from "node:url";
18
+
19
+ import k from "../index.mjs";
20
+ import {
21
+ codes,
22
+ createState,
23
+ decodeWire,
24
+ encodeToWire,
25
+ evaluateInput,
26
+ executeKVM
27
+ } from "../backend-api.mjs";
28
+ import { compileLibrary, loadLibrary } from "../object.mjs";
29
+ import { parse as parseIntVal, print as printIntVal } from "../codecs/int.mjs";
30
+ import { compileObjectToExecutable } from "../backends/llvm/src/executable.mjs";
31
+ import {
32
+ compileWasmArtifact,
33
+ instantiateWasmArtifact
34
+ } from "../backends/wasm/src/wasm.mjs";
35
+ import {
36
+ PersistentExecutable,
37
+ makeCacheDir,
38
+ prepareRelation
39
+ } from "../backends/llvm/tests/perf-support.mjs";
40
+
41
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
42
+ const args = process.argv.slice(2);
43
+
44
+ function getArg(flag, fallback) {
45
+ const idx = args.indexOf(flag);
46
+ return idx !== -1 && args[idx + 1] ? args[idx + 1] : fallback;
47
+ }
48
+
49
+ if (args.includes("-h") || args.includes("--help")) {
50
+ console.log(`Usage: node scripts/perf-bigint-compare.mjs [options]
51
+
52
+ End-to-end decimal parse -> N squarings -> decimal print benchmark comparing
53
+ JS BigInt against K (lib/integer.k) across execution backends.
54
+
55
+ Options:
56
+ --input <decimal> Starting decimal integer (default: 987654321)
57
+ --steps <n> Number of consecutive squarings (default: 10)
58
+ --backends <csv> K backends: llvm,llvm-pkir,wasm,pkir,kvm,js
59
+ (default: llvm,wasm,pkir)
60
+ --iters <n> Measured iterations per K backend (default: 3)
61
+ -h, --help Show this help message and exit`);
62
+ process.exit(0);
63
+ }
64
+
65
+ const INPUT = getArg("--input", "987654321");
66
+ const STEPS = Number.parseInt(getArg("--steps", "10"), 10);
67
+ const ITERS = Number.parseInt(getArg("--iters", "3"), 10);
68
+ const BACKENDS = getArg("--backends", "llvm,wasm,pkir")
69
+ .split(",")
70
+ .map((b) => b.trim().toLowerCase())
71
+ .filter(Boolean);
72
+
73
+ function fmtMs(ms) {
74
+ if (ms < 0.01) return `${(ms * 1000).toFixed(2)} µs`;
75
+ if (ms < 1) return `${(ms * 1000).toFixed(0)} µs`;
76
+ if (ms < 100) return `${ms.toFixed(2)} ms`;
77
+ if (ms < 1000) return `${ms.toFixed(1)} ms`;
78
+ return `${(ms / 1000).toFixed(2)} s`;
79
+ }
80
+
81
+ // 1. JS BigInt baseline
82
+ function benchBigInt(iters = 500) {
83
+ let expected;
84
+ for (let i = 0; i < 20; i++) {
85
+ let x = BigInt(INPUT);
86
+ for (let s = 0; s < STEPS; s++) x = x * x;
87
+ expected = x.toString(10);
88
+ }
89
+ let parseMs = 0;
90
+ let computeMs = 0;
91
+ let printMs = 0;
92
+ for (let i = 0; i < iters; i++) {
93
+ const t0 = performance.now();
94
+ let x = BigInt(INPUT);
95
+ const t1 = performance.now();
96
+ for (let s = 0; s < STEPS; s++) x = x * x;
97
+ const t2 = performance.now();
98
+ const out = x.toString(10);
99
+ const t3 = performance.now();
100
+ if (out.length !== expected.length) throw new Error("BigInt mismatch");
101
+ parseMs += t1 - t0;
102
+ computeMs += t2 - t1;
103
+ printMs += t3 - t2;
104
+ }
105
+ return {
106
+ name: "JS BigInt",
107
+ parseMs: parseMs / iters,
108
+ computeMs: computeMs / iters,
109
+ printMs: printMs / iters,
110
+ totalMs: (parseMs + computeMs + printMs) / iters,
111
+ output: expected
112
+ };
113
+ }
114
+
115
+ const bigRes = benchBigInt();
116
+ console.log(
117
+ `Input: "${INPUT}" | Squarings: ${STEPS} | Output: ${bigRes.output.length} decimal digits`
118
+ );
119
+ console.log(
120
+ `Result: ${bigRes.output.slice(0, 30)}...${bigRes.output.slice(-20)}\n`
121
+ );
122
+
123
+ // 2. Compile sqN in K (both library form for Wasm/JS and REPL state for LLVM/kVM)
124
+ const intSource = fs.readFileSync(path.join(root, "lib/integer.k"), "utf8");
125
+ const sqDefs = `\nsq = ?int[] { () x, () y } times ?int[];\nsqN = ${Array(STEPS).fill("sq").join(" ")};\n`;
126
+ const intLib = loadLibrary(
127
+ compileLibrary(intSource + sqDefs, { source: "lib/integer.k+sqN" })
128
+ );
129
+ const sqNAlias = intLib.relAlias.sqN;
130
+ const intPattern = parseIntVal("0").pattern;
131
+
132
+ const results = [bigRes];
133
+
134
+ async function benchInProcess(name, runFn, iters) {
135
+ // Warmup & conformance check
136
+ {
137
+ const val = parseIntVal(INPUT);
138
+ const outStr = printIntVal(runFn(val));
139
+ if (outStr !== bigRes.output) throw new Error(`${name}: output mismatch`);
140
+ }
141
+ let parseMs = 0;
142
+ let computeMs = 0;
143
+ let printMs = 0;
144
+ for (let i = 0; i < iters; i++) {
145
+ const t0 = performance.now();
146
+ const val = parseIntVal(INPUT);
147
+ const t1 = performance.now();
148
+ const outVal = runFn(val);
149
+ const t2 = performance.now();
150
+ const outStr = printIntVal(outVal);
151
+ const t3 = performance.now();
152
+ if (outStr !== bigRes.output) throw new Error(`${name}: output mismatch`);
153
+ parseMs += t1 - t0;
154
+ computeMs += t2 - t1;
155
+ printMs += t3 - t2;
156
+ }
157
+ return {
158
+ name,
159
+ parseMs: parseMs / iters,
160
+ computeMs: computeMs / iters,
161
+ printMs: printMs / iters,
162
+ totalMs: (parseMs + computeMs + printMs) / iters
163
+ };
164
+ }
165
+
166
+ async function benchWireServer(name, server, iters) {
167
+ // Warmup & conformance check
168
+ {
169
+ const val = parseIntVal(INPUT);
170
+ const wire = encodeToWire(val, val.pattern);
171
+ const outWire = await server.request(wire);
172
+ const outStr = printIntVal(decodeWire(outWire).value);
173
+ if (outStr !== bigRes.output) throw new Error(`${name}: output mismatch`);
174
+ }
175
+ let parseMs = 0;
176
+ let computeMs = 0;
177
+ let printMs = 0;
178
+ for (let i = 0; i < iters; i++) {
179
+ const t0 = performance.now();
180
+ const val = parseIntVal(INPUT);
181
+ const wire = encodeToWire(val, val.pattern);
182
+ const t1 = performance.now();
183
+ const outWire = await server.request(wire);
184
+ const t2 = performance.now();
185
+ const outStr = printIntVal(decodeWire(outWire).value);
186
+ const t3 = performance.now();
187
+ if (outStr !== bigRes.output) throw new Error(`${name}: output mismatch`);
188
+ parseMs += t1 - t0;
189
+ computeMs += t2 - t1;
190
+ printMs += t3 - t2;
191
+ }
192
+ return {
193
+ name,
194
+ parseMs: parseMs / iters,
195
+ computeMs: computeMs / iters,
196
+ printMs: printMs / iters,
197
+ totalMs: (parseMs + computeMs + printMs) / iters
198
+ };
199
+ }
200
+
201
+ // Prepare LLVM/kVM relation object if needed
202
+ let prepared = null;
203
+ let preparedState = null;
204
+ let cacheDir = null;
205
+ if (BACKENDS.some((b) => b === "llvm" || b === "llvm-pkir" || b === "kvm")) {
206
+ preparedState = createState();
207
+ await evaluateInput(`:load ${path.join(root, "lib/integer.k")}`, preparedState);
208
+ await evaluateInput("sq = ?int[] { () x, () y } times ?int[];", preparedState);
209
+ await evaluateInput(`sqN = ${Array(STEPS).fill("sq").join(" ")};`, preparedState);
210
+ codes.load(preparedState.codes);
211
+ prepared = prepareRelation(preparedState, "sqN", { sourceLabel: "lib/integer.k#sqN" });
212
+ cacheDir = makeCacheDir("k-bigint-cmp-");
213
+ }
214
+
215
+ for (const backend of BACKENDS) {
216
+ try {
217
+ if (backend === "llvm" || backend === "llvm-pkir") {
218
+ const usePKIR = backend === "llvm-pkir";
219
+ const label = usePKIR ? "K LLVM-PKIR (-O3)" : "K LLVM (-O3)";
220
+ const exe = path.join(cacheDir, `sqN_${backend.replace("-", "_")}`);
221
+ compileObjectToExecutable(prepared.object, exe, {
222
+ clangOpt: "-O3",
223
+ inputPattern: intPattern,
224
+ usePKIR
225
+ });
226
+ const srv = new PersistentExecutable(exe, {
227
+ env: { ...process.env, K_ARENA_CAPACITY_MB: "4096" }
228
+ });
229
+ try {
230
+ results.push(await benchWireServer(label, srv, ITERS));
231
+ } finally {
232
+ await srv.close();
233
+ }
234
+ } else if (backend === "wasm" || backend === "pkir") {
235
+ const usePKIR = backend === "pkir";
236
+ const label = usePKIR ? "K PKIR-Wasm" : "K Wasm";
237
+ const artifact = await compileWasmArtifact(sqNAlias, {
238
+ libraries: [intLib],
239
+ usePKIR
240
+ });
241
+ const inst = await instantiateWasmArtifact(artifact);
242
+ results.push(
243
+ await benchInProcess(label, (val) => inst.executeValue(val), ITERS)
244
+ );
245
+ } else if (backend === "kvm") {
246
+ const kvmContext = {
247
+ rels: preparedState.rels,
248
+ findCode: codes.find,
249
+ options: { envelopeFree: true }
250
+ };
251
+ results.push(
252
+ await benchInProcess(
253
+ "K kVM",
254
+ (val) => executeKVM(prepared.kvmFunc, val, kvmContext),
255
+ Math.min(ITERS, 2)
256
+ )
257
+ );
258
+ } else if (backend === "js") {
259
+ const fn = k.compile(sqNAlias, { libraries: [intLib] });
260
+ results.push(await benchInProcess("K JS", fn, Math.min(ITERS, 2)));
261
+ } else {
262
+ console.warn(`[WARN] Unknown backend: ${backend}`);
263
+ }
264
+ } catch (err) {
265
+ console.warn(`[SKIP] ${backend}: ${err.message}`);
266
+ }
267
+ }
268
+
269
+ console.log(
270
+ `| Engine | Parse | Compute (${STEPS}x sq) | Print | Total | vs BigInt (Compute) | vs BigInt (Total) |`
271
+ );
272
+ console.log("| --- | ---: | ---: | ---: | ---: | ---: | ---: |");
273
+ for (const r of results) {
274
+ const cRatio = `${(r.computeMs / bigRes.computeMs).toFixed(1)}x`;
275
+ const tRatio = `${(r.totalMs / bigRes.totalMs).toFixed(1)}x`;
276
+ console.log(
277
+ `| ${r.name} | ${fmtMs(r.parseMs)} | ${fmtMs(r.computeMs)} | ${fmtMs(r.printMs)} | ${fmtMs(r.totalMs)} | ${cRatio} | ${tRatio} |`
278
+ );
279
+ }
@@ -85,7 +85,6 @@ for (const [type, value] of [
85
85
  ]) {
86
86
  const input = fromJsonValue(value);
87
87
  assert.ok(run(`${type}?`, input), type);
88
- assert.ok(run("json?", input), `json? ${type}`);
89
88
  }
90
89
  assert.equal(run("object?", fromJsonValue([1, 2])), undefined);
91
90
  assert.equal(run("list?", fromJsonValue({ a: 1 })), undefined);
@@ -77,7 +77,6 @@ for (const [filterName, jsonVal] of [
77
77
  ["list?", [1, 2]],
78
78
  ["object?", { a: 1 }]
79
79
  ]) {
80
- assert.ok(runRel("json?", fromJsonValue(jsonVal)), `json? failed for ${JSON.stringify(jsonVal)}`);
81
80
  assert.ok(runRel(filterName, fromJsonValue(jsonVal)), `${filterName} failed for ${JSON.stringify(jsonVal)}`);
82
81
  }
83
82
  assert.equal(runRel("null?", fromJsonValue(0)), undefined);
@@ -92,7 +92,7 @@ assert.equal(runRel("lt?", Value.variant("gt", Value.product({}))), undefined);
92
92
  assert.equal(runRel("nil?", Value.variant("nil", Value.product({}))).tag, "nil");
93
93
  assert.equal(runRel("nil?", Value.variant("val", Value.product({}))), undefined);
94
94
 
95
- // 2. list[X]: reverse & rev_append
95
+ // 2. list[X]: reverse
96
96
  assert.deepEqual(listToArray(runRel("reverse", listFrom([]))).length, 0);
97
97
  assert.deepEqual(
98
98
  listToArray(runRel("reverse", textToStringValue("abc"))).map((ch) =>
@@ -102,7 +102,7 @@ assert.deepEqual(
102
102
  );
103
103
  assert.equal(
104
104
  stringValueToText(
105
- runRel("rev_append", Value.product({
105
+ runRel("_reverse", Value.product({
106
106
  xs: textToStringValue("ab"),
107
107
  acc: textToStringValue("cd")
108
108
  }))
@@ -110,13 +110,11 @@ assert.equal(
110
110
  "bacd"
111
111
  );
112
112
 
113
- // 3. bits[]: zero_bits?, trim_bits, inc_bits
114
- assert.ok(runRel("zero_bits?", bitsFromStr("0")));
115
- assert.equal(runRel("zero_bits?", bitsFromStr("1")), undefined);
116
- assert.equal(bitsToStr(runRel("trim_bits", bitsFromStr("000"))), "0");
113
+ // 3. bits[]: trim_bits, inc_bits
114
+ assert.equal(bitsToStr(runRel("trim_bits", bitsFromStr("000"))), "");
117
115
  assert.equal(bitsToStr(runRel("trim_bits", bitsFromStr("00101"))), "101");
118
116
 
119
- const expectedBits = ["0", "1", "10", "11", "100", "101", "110", "111", "1000"];
117
+ const expectedBits = ["", "1", "10", "11", "100", "101", "110", "111", "1000"];
120
118
  for (let i = 0; i < expectedBits.length - 1; i++) {
121
119
  const next = runRel("inc_bits", bitsFromStr(expectedBits[i]));
122
120
  assert.equal(bitsToStr(next), expectedBits[i + 1]);
@@ -645,7 +645,7 @@ await evaluateInput(
645
645
  djsonKState
646
646
  );
647
647
  output = await evaluateInput(
648
- "{{{}|_|0 index, () json} nth /string key, " +
648
+ "{{{}|_ index, () json} nth /string key, " +
649
649
  "{{}|_|1 index, () json} nth json} get",
650
650
  djsonKState
651
651
  );
@@ -656,7 +656,7 @@ await evaluateInput(
656
656
  djsonKState
657
657
  );
658
658
  output = await evaluateInput(
659
- "{{{}|_|0 index, () json} nth /string key, " +
659
+ "{{{}|_ index, () json} nth /string key, " +
660
660
  "{{}|_|1 index, () json} nth json} del",
661
661
  djsonKState
662
662
  );
@@ -1015,7 +1015,7 @@ assert.equal(
1015
1015
  "?@Pt3MwQwzUPxQKu58zXR3qUBHWTzfycx5bSZGzcK6EZQK[] " +
1016
1016
  "dj_json_value {.rest dj_ws /nil _, .value value} .value " +
1017
1017
  "?@P5C7TQKTSPnFUkYkYzTudJamxAQ3T3fHbvZNqwWMfAA2[]; " +
1018
- "-- @w4Qr99UxapJGFraYLvGkAsc9VZFvsSsUV8i5isvG5Z6F"
1018
+ "-- @3dPQGT29U9k4zMc8WizAimZtrhb6BHtY3UZEHtq7FPwN"
1019
1019
  );
1020
1020
  const shortThresholdState = createState();
1021
1021
  output = await evaluateInput(":max-pat-length", shortThresholdState);
@@ -34,7 +34,7 @@ const listWire = encodeToWire(parsedList, INT_LIST_PATTERN);
34
34
  const decodedList = decodeWire(listWire).value;
35
35
  assert.equal(
36
36
  valueWithEnvelopeToK(decodedList),
37
- "{{}|_|0|+ car, {{}|_|1|+ car, {{}|_|0|1|+ car, {}|nil cdr}|cons cdr}|cons cdr}|cons ?<{<<X1 0, X1 1, {}=X2 _>=X1 +, X1 -> car, X0 cdr} cons, X2 nil>=X0"
37
+ "{{}|_|+ car, {{}|_|1|+ car, {{}|_|0|1|+ car, {}|nil cdr}|cons cdr}|cons cdr}|cons ?<{<<X1 0, X1 1, {}=X2 _>=X1 +, X1 -> car, X0 cdr} cons, X2 nil>=X0"
38
38
  );
39
39
  assert.equal(printInt(decodedList), "[0,1,2]");
40
40