@fraczak/k 9.0.0 → 9.1.1
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/CHANGELOG.md +18 -0
- package/DOCS/KTVM_SPEC.md +45 -40
- package/DOCS/PROFILING_AND_TRACING.md +7 -0
- package/README.md +6 -0
- package/backends/llvm/README.md +4 -0
- package/backends/llvm/runtime/krt.c +63 -291
- package/backends/llvm/src/executable.mjs +33 -19
- package/backends/llvm/src/kvm2llvm.mjs +0 -2
- package/backends/llvm/src/llvm.mjs +0 -2
- package/backends/llvm/tests/compaction-driver.c +33 -0
- package/backends/llvm/tests/integration.sh +18 -0
- package/backends/llvm/tests/test-llvm.mjs +2 -0
- package/backends/wasm/README.md +5 -0
- package/backends/wasm/src/wasm.mjs +50 -1
- package/backends/wasm/tests/test-wasm.mjs +41 -2
- package/codecs/runtime/codec-sdk.mjs +1 -0
- package/codecs/runtime/prefix-codec.mjs +70 -4
- package/ktvm/bit-deque.mjs +19 -4
- package/ktvm/index.mjs +11 -0
- package/ktvm/schema.mjs +594 -3
- package/ktvm/test-ktvm.mjs +430 -1
- package/ktvm/wasm/runtime.wat +10 -19
- package/ktvm/wasm/test-wasm.mjs +3 -0
- package/ktvm/wire.mjs +222 -32
- package/package.json +1 -1
- package/paper/Makefile +8 -5
- package/paper/k-transducer-compiler.pdf +0 -0
- package/paper/k-transducer-compiler.tex +658 -0
- package/paper/replay-diagnostic.mjs +63 -0
- package/scripts/perf-ieee.mjs +5 -3
- package/scripts/perf-int.mjs +2 -2
- package/scripts/perf-multiplication.mjs +109 -68
- package/tests/test-codecs.mjs +8 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { BitDeque } from "../ktvm/bit-deque.mjs";
|
|
3
|
+
import { parseModule } from "../ktvm/parser.mjs";
|
|
4
|
+
import { validateModule } from "../ktvm/validator.mjs";
|
|
5
|
+
import { KTVMRuntime } from "../ktvm/vm.mjs";
|
|
6
|
+
|
|
7
|
+
const module = parseModule(`
|
|
8
|
+
ktvm 0.1 mono entry @choice;
|
|
9
|
+
schema $bits = union { 0: $bits, 1: $bits, _: unit };
|
|
10
|
+
|
|
11
|
+
proc @choice(%xs: $bits) -> (%out: $bits) {
|
|
12
|
+
spec (%xs) -> (%out) {
|
|
13
|
+
branch 0: { spawn @zeros(%xs) -> (%out); }
|
|
14
|
+
branch 1: { splice %xs -> %out; }
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
proc @zeros(%xs: $bits) -> (%out: $bits) {
|
|
19
|
+
switch (%xs) {
|
|
20
|
+
case (/0): {
|
|
21
|
+
chan %rest: $bits;
|
|
22
|
+
match /0 %xs -> %rest;
|
|
23
|
+
spawn @zeros(%rest) -> (%out);
|
|
24
|
+
}
|
|
25
|
+
default: {
|
|
26
|
+
chan %unit: unit;
|
|
27
|
+
match /_ %xs -> %unit;
|
|
28
|
+
wrap |_ %unit -> %out;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
`);
|
|
33
|
+
validateModule(module);
|
|
34
|
+
|
|
35
|
+
class ReplayDiagnostic extends KTVMRuntime {
|
|
36
|
+
peakReplayBits = 0;
|
|
37
|
+
|
|
38
|
+
_stepTap(node) {
|
|
39
|
+
const demand = super._stepTap(node);
|
|
40
|
+
this.peakReplayBits = Math.max(this.peakReplayBits, node.replay.length);
|
|
41
|
+
return demand;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const digits = 1024;
|
|
46
|
+
for (const oneAtDigit of [1, digits]) {
|
|
47
|
+
const tags = Array(digits).fill(0);
|
|
48
|
+
tags[oneAtDigit - 1] = 1;
|
|
49
|
+
tags.push(2); // The "_" terminator is the third tag in wire order.
|
|
50
|
+
const input = new BitDeque(10000);
|
|
51
|
+
for (const tag of tags) input.pushBits(tag, 2);
|
|
52
|
+
input.close();
|
|
53
|
+
|
|
54
|
+
const vm = new ReplayDiagnostic(module);
|
|
55
|
+
const { status, outputDeques, telemetry } = vm.run(module.entry, [input]);
|
|
56
|
+
assert.equal(status, "OK");
|
|
57
|
+
assert.equal(telemetry.specRollbacks, 1);
|
|
58
|
+
const [output] = outputDeques;
|
|
59
|
+
assert.equal(output.length, 2 * tags.length);
|
|
60
|
+
for (const tag of tags) assert.equal(output.shiftBits(2), tag);
|
|
61
|
+
output.release();
|
|
62
|
+
console.log({ oneAtDigit, rollbacks: telemetry.specRollbacks, peakReplayBits: vm.peakReplayBits });
|
|
63
|
+
}
|
package/scripts/perf-ieee.mjs
CHANGED
|
@@ -298,14 +298,16 @@ if (runWasm) {
|
|
|
298
298
|
console.log("==> Compiling WebAssembly executable (persistent runner)...");
|
|
299
299
|
try {
|
|
300
300
|
const wasmPath = path.join(cacheDir, "perf_ieee_wasm.wasm");
|
|
301
|
-
|
|
301
|
+
const exePath = path.join(cacheDir, "perf_ieee_wasm.exe");
|
|
302
302
|
const wasmBuf = await compileWasmArtifactFromObject(relation.object, {
|
|
303
|
-
entry:
|
|
303
|
+
entry: relation.relHash
|
|
304
304
|
});
|
|
305
305
|
fs.writeFileSync(wasmPath, wasmBuf);
|
|
306
306
|
const runBin = fileURLToPath(import.meta.resolve("../backends/wasm/bin/k-wasm-run.mjs"));
|
|
307
|
-
fs.writeFileSync(
|
|
307
|
+
fs.writeFileSync(exePath, `#!/bin/sh\nexec node "${runBin}" "${wasmPath}" "$@"\n`, { mode: 0o755 });
|
|
308
|
+
wasmExePath = exePath;
|
|
308
309
|
} catch (error) {
|
|
310
|
+
wasmExePath = null;
|
|
309
311
|
wasmCompileError = error.stack || error.message || String(error);
|
|
310
312
|
console.log("WebAssembly compilation failed:");
|
|
311
313
|
console.log(wasmCompileError.split("\n").slice(0, 8).join("\n"));
|
package/scripts/perf-int.mjs
CHANGED
|
@@ -254,7 +254,7 @@ if (runWasm) {
|
|
|
254
254
|
const wasmPath = path.join(cacheDir, `perf_int_wasm_${op}.wasm`);
|
|
255
255
|
const exePath = path.join(cacheDir, `perf_int_wasm_${op}.exe`);
|
|
256
256
|
const wasmBuf = await compileWasmArtifactFromObject(relation.object, {
|
|
257
|
-
entry:
|
|
257
|
+
entry: relation.relHash
|
|
258
258
|
});
|
|
259
259
|
fs.writeFileSync(wasmPath, wasmBuf);
|
|
260
260
|
const runBin = fileURLToPath(import.meta.resolve("../backends/wasm/bin/k-wasm-run.mjs"));
|
|
@@ -612,7 +612,7 @@ for (const algo of squaringAlgos) {
|
|
|
612
612
|
try {
|
|
613
613
|
const sWasmPath = path.join(cacheDir, `perf_int_wasm_${algo.id}.wasm`);
|
|
614
614
|
const sWasmExe = path.join(cacheDir, `perf_int_wasm_${algo.id}.exe`);
|
|
615
|
-
const wasmBuf = await compileWasmArtifactFromObject(algo.rel.object, { entry:
|
|
615
|
+
const wasmBuf = await compileWasmArtifactFromObject(algo.rel.object, { entry: algo.rel.relHash });
|
|
616
616
|
fs.writeFileSync(sWasmPath, wasmBuf);
|
|
617
617
|
const runBin = fileURLToPath(import.meta.resolve("../backends/wasm/bin/k-wasm-run.mjs"));
|
|
618
618
|
fs.writeFileSync(sWasmExe, `#!/bin/sh\nexec node "${runBin}" "${sWasmPath}" "$@"\n`, { mode: 0o755 });
|
|
@@ -35,9 +35,10 @@ import {
|
|
|
35
35
|
evaluateInput,
|
|
36
36
|
executeKVM,
|
|
37
37
|
run_converged,
|
|
38
|
-
|
|
38
|
+
Value
|
|
39
39
|
} from "@fraczak/k/backend-api.mjs";
|
|
40
|
-
import { parse as parseIntValue } from "@fraczak/k/codecs/int.mjs";
|
|
40
|
+
import { parse as parseIntValue, print as printIntValue, INT_PATTERN } from "@fraczak/k/codecs/int.mjs";
|
|
41
|
+
import { composePattern } from "@fraczak/k/Value.mjs";
|
|
41
42
|
import { compileObjectBuffer } from "@fraczak/k/object.mjs";
|
|
42
43
|
import {
|
|
43
44
|
compileObjectToExecutable
|
|
@@ -237,13 +238,19 @@ const arithLibChain = [
|
|
|
237
238
|
|
|
238
239
|
const cacheDir = makeCacheDir("k-mult-perf-");
|
|
239
240
|
|
|
240
|
-
// 2. Prepare
|
|
241
|
-
// For squaring: relation name `s_${algo} = {()x, ()y} ${algo}
|
|
241
|
+
// 2. Prepare Relations & Binaries
|
|
242
|
+
// For squaring: relation name `s_${algo} = {()x, ()y} ${algo};`
|
|
243
|
+
// For sizes: 2-arg relation `${algo}` taking `{ x: int[], y: int[] }`
|
|
242
244
|
const algoRelations = {};
|
|
243
245
|
const algoServers = { llvm: {}, wasm: {} };
|
|
244
246
|
|
|
245
247
|
let commonState = null;
|
|
246
248
|
|
|
249
|
+
const pairIntPattern = composePattern("closed-product", [["x", INT_PATTERN], ["y", INT_PATTERN]]);
|
|
250
|
+
const sampleInputPattern = mode === "squaring"
|
|
251
|
+
? wireInput(parseIntValue("0")).inputPattern
|
|
252
|
+
: wireInput(Value.product({ x: parseIntValue("0"), y: parseIntValue("0") }), pairIntPattern).inputPattern;
|
|
253
|
+
|
|
247
254
|
for (const algo of selectedAlgos) {
|
|
248
255
|
const filePath = arithLibChain[arithLibChain.length - 1];
|
|
249
256
|
|
|
@@ -255,9 +262,12 @@ for (const algo of selectedAlgos) {
|
|
|
255
262
|
|
|
256
263
|
if (!commonState) commonState = algoState;
|
|
257
264
|
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
265
|
+
let relName = algo;
|
|
266
|
+
if (mode === "squaring") {
|
|
267
|
+
relName = `s_${algo}`;
|
|
268
|
+
await evaluateInput(`${relName} = {()x, ()y} ${algo};`, algoState);
|
|
269
|
+
codes.load(algoState.codes);
|
|
270
|
+
}
|
|
261
271
|
|
|
262
272
|
const prepared = prepareRelation(algoState, relName, {
|
|
263
273
|
sourceLabel: `${filePath}#${relName}`
|
|
@@ -267,12 +277,12 @@ for (const algo of selectedAlgos) {
|
|
|
267
277
|
|
|
268
278
|
// LLVM
|
|
269
279
|
if (selectedBackends.includes("llvm")) {
|
|
270
|
-
const exePath = path.join(cacheDir, `perf_mult_llvm_${algo}`);
|
|
280
|
+
const exePath = path.join(cacheDir, `perf_mult_llvm_${mode}_${algo}`);
|
|
271
281
|
try {
|
|
272
282
|
compileObjectToExecutable(
|
|
273
283
|
algoRelations[algo].object, exePath, {
|
|
274
284
|
clangOpt: "-O2",
|
|
275
|
-
inputPattern:
|
|
285
|
+
inputPattern: sampleInputPattern
|
|
276
286
|
}
|
|
277
287
|
);
|
|
278
288
|
algoServers.llvm[algo] = new PersistentExecutable(exePath);
|
|
@@ -285,11 +295,11 @@ for (const algo of selectedAlgos) {
|
|
|
285
295
|
|
|
286
296
|
// Wasm
|
|
287
297
|
if (selectedBackends.includes("wasm")) {
|
|
288
|
-
const wasmPath = path.join(cacheDir, `perf_mult_wasm_${algo}.wasm`);
|
|
289
|
-
const exePath = path.join(cacheDir, `perf_mult_wasm_${algo}.exe`);
|
|
298
|
+
const wasmPath = path.join(cacheDir, `perf_mult_wasm_${mode}_${algo}.wasm`);
|
|
299
|
+
const exePath = path.join(cacheDir, `perf_mult_wasm_${mode}_${algo}.exe`);
|
|
290
300
|
try {
|
|
291
301
|
const wasmBuf = await compileWasmArtifactFromObject(
|
|
292
|
-
algoRelations[algo].object, { entry:
|
|
302
|
+
algoRelations[algo].object, { entry: algoRelations[algo].relHash }
|
|
293
303
|
);
|
|
294
304
|
fs.writeFileSync(wasmPath, wasmBuf);
|
|
295
305
|
const runBin = fileURLToPath(
|
|
@@ -309,6 +319,7 @@ for (const algo of selectedAlgos) {
|
|
|
309
319
|
}
|
|
310
320
|
}
|
|
311
321
|
|
|
322
|
+
try {
|
|
312
323
|
// 3. Squaring Mode Benchmark
|
|
313
324
|
if (mode === "squaring") {
|
|
314
325
|
const sInitVal = parseIntValue(squaringInputText);
|
|
@@ -536,14 +547,8 @@ if (mode === "squaring") {
|
|
|
536
547
|
}
|
|
537
548
|
|
|
538
549
|
console.log();
|
|
539
|
-
|
|
540
550
|
} finally {
|
|
541
|
-
//
|
|
542
|
-
for (const backend of ["llvm", "wasm"]) {
|
|
543
|
-
for (const algo of selectedAlgos) {
|
|
544
|
-
algoServers[backend]?.[algo]?.child?.kill();
|
|
545
|
-
}
|
|
546
|
-
}
|
|
551
|
+
// Cleanup handled in outer finally block
|
|
547
552
|
}
|
|
548
553
|
}
|
|
549
554
|
|
|
@@ -565,67 +570,103 @@ if (mode === "sizes") {
|
|
|
565
570
|
console.log("\n" + th);
|
|
566
571
|
console.log("-".repeat(th.length));
|
|
567
572
|
|
|
568
|
-
const
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
573
|
+
const relTimes = selectedAlgos.includes("times") ? algoRelations.times : null;
|
|
574
|
+
const relKara = selectedAlgos.includes("karatsuba") ? algoRelations.karatsuba : null;
|
|
575
|
+
|
|
576
|
+
async function runOneSize(backend, algo, rel, pairInput, pairWire) {
|
|
577
|
+
if (!rel) return { value: null, timeMs: null };
|
|
578
|
+
if (backend === "js") {
|
|
579
|
+
run_converged.defs = rel.state;
|
|
580
|
+
const t0 = performance.now();
|
|
581
|
+
const res = run_converged(
|
|
582
|
+
codes.find,
|
|
583
|
+
rel.relDef.def,
|
|
584
|
+
pairInput,
|
|
585
|
+
rel.relDef.typePatternGraph
|
|
586
|
+
);
|
|
587
|
+
return { value: res, timeMs: performance.now() - t0 };
|
|
588
|
+
}
|
|
589
|
+
if (backend === "kvm") {
|
|
590
|
+
const kvmContext = {
|
|
591
|
+
rels: rel.state.rels,
|
|
592
|
+
findCode: codes.find,
|
|
593
|
+
options: { envelopeFree: true }
|
|
594
|
+
};
|
|
595
|
+
const t0 = performance.now();
|
|
596
|
+
const res = executeKVM(rel.kvmFunc, pairInput, kvmContext);
|
|
597
|
+
return { value: res, timeMs: performance.now() - t0 };
|
|
598
|
+
}
|
|
599
|
+
if (backend === "llvm" || backend === "wasm") {
|
|
600
|
+
const server = algoServers[backend]?.[algo];
|
|
601
|
+
if (!server) return { value: null, timeMs: null, unavailable: true };
|
|
602
|
+
const t0 = performance.now();
|
|
603
|
+
const outWire = await requestWithTimeout(server, pairWire, stepTimeoutMs);
|
|
604
|
+
const timeMs = performance.now() - t0;
|
|
605
|
+
return { value: decodeWire(outWire).value, timeMs };
|
|
606
|
+
}
|
|
607
|
+
return { value: null, timeMs: null, unavailable: true };
|
|
608
|
+
}
|
|
574
609
|
|
|
575
610
|
for (const bits of sizesList) {
|
|
576
611
|
const strA = randomBigIntBits(bits);
|
|
577
612
|
const strB = randomBigIntBits(bits);
|
|
613
|
+
const expectedStr = (BigInt(strA) * BigInt(strB)).toString();
|
|
578
614
|
|
|
579
615
|
const valA = parseIntValue(strA);
|
|
580
616
|
const valB = parseIntValue(strB);
|
|
581
|
-
const pairInput =
|
|
617
|
+
const pairInput = Value.product({ x: valA, y: valB });
|
|
618
|
+
const { inputWire: pairWire } = wireInput(pairInput, pairIntPattern);
|
|
582
619
|
|
|
583
620
|
for (const backend of selectedBackends) {
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
if (relDefTimes) {
|
|
588
|
-
run_converged.defs = algoRelations.times.state;
|
|
589
|
-
const t0_t = performance.now();
|
|
590
|
-
resTimes = run_converged(
|
|
591
|
-
codes.find,
|
|
592
|
-
relDefTimes.def,
|
|
593
|
-
pairInput,
|
|
594
|
-
relDefTimes.typePatternGraph
|
|
595
|
-
);
|
|
596
|
-
tTime = performance.now() - t0_t;
|
|
597
|
-
}
|
|
621
|
+
let tRun = { value: null, timeMs: null };
|
|
622
|
+
let kRun = { value: null, timeMs: null };
|
|
623
|
+
let errMsg = null;
|
|
598
624
|
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
run_converged.defs = algoRelations.karatsuba.state;
|
|
603
|
-
const t0_k = performance.now();
|
|
604
|
-
resKara = run_converged(
|
|
605
|
-
codes.find,
|
|
606
|
-
relDefKara.def,
|
|
607
|
-
pairInput,
|
|
608
|
-
relDefKara.typePatternGraph
|
|
609
|
-
);
|
|
610
|
-
kTime = performance.now() - t0_k;
|
|
625
|
+
try {
|
|
626
|
+
if (relTimes) {
|
|
627
|
+
tRun = await runOneSize(backend, "times", relTimes, pairInput, pairWire);
|
|
611
628
|
}
|
|
629
|
+
if (relKara) {
|
|
630
|
+
kRun = await runOneSize(backend, "karatsuba", relKara, pairInput, pairWire);
|
|
631
|
+
}
|
|
632
|
+
} catch (e) {
|
|
633
|
+
errMsg = e.message;
|
|
634
|
+
}
|
|
612
635
|
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
const
|
|
620
|
-
const
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
636
|
+
if (tRun.unavailable && (!relKara || kRun.unavailable)) continue;
|
|
637
|
+
|
|
638
|
+
let statusText = "MATCH OK";
|
|
639
|
+
if (errMsg) {
|
|
640
|
+
statusText = `ERR: ${errMsg.split("\n")[0]}`;
|
|
641
|
+
} else {
|
|
642
|
+
const tOk = !relTimes || (tRun.value != null && printIntValue(tRun.value) === expectedStr);
|
|
643
|
+
const kOk = !relKara || (kRun.value != null && printIntValue(kRun.value) === expectedStr);
|
|
644
|
+
if (!tOk || !kOk) statusText = "MISMATCH";
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
const speedup = (tRun.timeMs != null && kRun.timeMs != null)
|
|
648
|
+
? fmtSpeedup(tRun.timeMs, kRun.timeMs)
|
|
649
|
+
: "-";
|
|
650
|
+
const colBits = bits.toString().padStart(11);
|
|
651
|
+
const colBe = backend.padEnd(7);
|
|
652
|
+
const colT = fmtMs(tRun.timeMs).padStart(11);
|
|
653
|
+
const colK = fmtMs(kRun.timeMs).padStart(11);
|
|
654
|
+
const colSp = speedup.padStart(13);
|
|
655
|
+
console.log(
|
|
656
|
+
`${colBits} | ${colBe} | ${colT} | ${colK} | ` +
|
|
657
|
+
`${colSp} | ${statusText}`
|
|
658
|
+
);
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
} finally {
|
|
663
|
+
// Always tear down persistent servers across both modes
|
|
664
|
+
for (const backend of ["llvm", "wasm"]) {
|
|
665
|
+
for (const algo of selectedAlgos) {
|
|
666
|
+
const server = algoServers[backend]?.[algo];
|
|
667
|
+
if (server) {
|
|
668
|
+
if (typeof server.close === "function") server.close();
|
|
669
|
+
else server.child?.kill();
|
|
629
670
|
}
|
|
630
671
|
}
|
|
631
672
|
}
|
package/tests/test-codecs.mjs
CHANGED
|
@@ -13,6 +13,7 @@ import * as Utf8Codec from "../codecs/utf8.mjs";
|
|
|
13
13
|
import * as Utf16Codec from "../codecs/utf16.mjs";
|
|
14
14
|
import * as IeeeCodec from "../codecs/ieee.mjs";
|
|
15
15
|
import * as UnitCodec from "../codecs/unit.mjs";
|
|
16
|
+
import { readBitsAt } from "../codecs/runtime/prefix-codec.mjs";
|
|
16
17
|
import {
|
|
17
18
|
valueToK,
|
|
18
19
|
valueWithEnvelopeToK
|
|
@@ -213,6 +214,13 @@ console.log("7. Verifying lazy prefix-free wire decoding...");
|
|
|
213
214
|
{
|
|
214
215
|
assert.equal(typeof SDK.decodeWireLazy, "function");
|
|
215
216
|
|
|
217
|
+
// Exercise large bit offsets without allocating a 256 MiB buffer.
|
|
218
|
+
const byte = 2 ** 28;
|
|
219
|
+
const sparseWire = { length: byte + 2, [byte]: 0b10000001, [byte + 1]: 0b10000000 };
|
|
220
|
+
assert.equal(readBitsAt(sparseWire, byte * 8, 1), 1);
|
|
221
|
+
assert.equal(readBitsAt(sparseWire, byte * 8 + 7, 3), 0b110);
|
|
222
|
+
assert.throws(() => readBitsAt(sparseWire, sparseWire.length * 8, 1), /Unexpected end of bitstream/);
|
|
223
|
+
|
|
216
224
|
// Lazy decoding should instantiate root in sub-millisecond time
|
|
217
225
|
const sampleStr = "a".repeat(20000);
|
|
218
226
|
const parsedStr = Utf8Codec.parse(sampleStr);
|