@fraczak/k 9.0.0 → 9.1.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,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
+ }
@@ -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
- wasmExePath = path.join(cacheDir, "perf_ieee_wasm.exe");
301
+ const exePath = path.join(cacheDir, "perf_ieee_wasm.exe");
302
302
  const wasmBuf = await compileWasmArtifactFromObject(relation.object, {
303
- entry: "__main__"
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(wasmExePath, `#!/bin/sh\nexec node "${runBin}" "${wasmPath}" "$@"\n`, { mode: 0o755 });
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"));
@@ -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: "__main__"
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: "__main__" });
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
- valueForCode
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 Squaring Relations & Binaries
241
- // For squaring: relation name `s_${algo} = {()x, ()y} ${algo}; s_${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
- const relName = `s_${algo}`;
259
- await evaluateInput(`${relName} = {()x, ()y} ${algo};`, algoState);
260
- codes.load(algoState.codes);
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: parseIntValue("0").pattern
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: "__main__" }
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
- // Teardown persistent servers
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 relDefTimes = selectedAlgos.includes("times")
569
- ? prepareRelation(algoRelations.times.state, "times").relDef
570
- : null;
571
- const relDefKara = selectedAlgos.includes("karatsuba")
572
- ? prepareRelation(algoRelations.karatsuba.state, "karatsuba").relDef
573
- : null;
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 = { tag: "product", value: { x: valA, y: valB } };
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
- if (backend === "js") {
585
- let resTimes = null;
586
- let tTime = null;
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
- let resKara = null;
600
- let kTime = null;
601
- if (relDefKara) {
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
- const match = (!resTimes || !resKara)
614
- ? true
615
- : JSON.stringify(resTimes) === JSON.stringify(resKara);
616
- const speedup = (tTime != null && kTime != null)
617
- ? fmtSpeedup(tTime, kTime)
618
- : "-";
619
- const colBits = bits.toString().padStart(11);
620
- const colBe = backend.padEnd(7);
621
- const colT = fmtMs(tTime).padStart(11);
622
- const colK = fmtMs(kTime).padStart(11);
623
- const colSp = speedup.padStart(13);
624
- const colMatch = match ? "MATCH OK" : "MISMATCH";
625
- console.log(
626
- `${colBits} | ${colBe} | ${colT} | ${colK} | ` +
627
- `${colSp} | ${colMatch}`
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
  }