@fraczak/k 8.9.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.
Files changed (90) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/DOCS/ARCHITECTURE.md +5 -4
  3. package/DOCS/DICTIONARY.md +2 -2
  4. package/DOCS/FILE_FORMATS.md +11 -9
  5. package/DOCS/KIR_V1.md +5 -1
  6. package/DOCS/KTVM_SPEC.md +907 -0
  7. package/DOCS/KVM_EXECUTION_MODEL.md +3 -2
  8. package/DOCS/KVM_VS_KTVM_COMPARATIVE_STUDY.md +127 -0
  9. package/DOCS/PROFILING_AND_TRACING.md +13 -4
  10. package/DOCS/README.md +3 -2
  11. package/DOCS/REPL.md +16 -12
  12. package/README.md +138 -2
  13. package/backend-api.mjs +31 -16
  14. package/backends/llvm/README.md +4 -5
  15. package/backends/llvm/bin/k-llvm-build.mjs +7 -19
  16. package/backends/llvm/bin/k-llvm-compile.mjs +6 -18
  17. package/backends/llvm/bin/k-llvm.mjs +11 -33
  18. package/backends/llvm/src/cli.mjs +2 -12
  19. package/backends/llvm/src/executable.mjs +7 -95
  20. package/backends/llvm/src/kvm2llvm.mjs +1 -7
  21. package/backends/llvm/src/llvm.mjs +4 -113
  22. package/backends/llvm/tests/k-llvm-run.mjs +1 -6
  23. package/backends/llvm/tests/perf-support.mjs +3 -5
  24. package/backends/llvm/tests/test-llvm.mjs +2 -16
  25. package/backends/wasm/README.md +7 -3
  26. package/backends/wasm/bin/k-wasm-compile.mjs +4 -7
  27. package/backends/wasm/bin/k-wasm.mjs +4 -6
  28. package/backends/wasm/src/cli.mjs +8 -24
  29. package/backends/wasm/src/wasm.mjs +60 -57
  30. package/backends/wasm/tests/test-wasm.mjs +41 -2
  31. package/browser/repl-browser.mjs +9 -8
  32. package/browser/shims/buffer.mjs +31 -2
  33. package/browser/shims/child_process.mjs +26 -0
  34. package/browser/shims/fs.mjs +3 -1
  35. package/codecs/runtime/prefix-codec.mjs +67 -1
  36. package/conformance/run.mjs +17 -2
  37. package/harness/adapters/ktvm-llvm.mjs +118 -0
  38. package/harness/adapters/ktvm-wasm.mjs +104 -0
  39. package/harness/adapters/ktvm.mjs +133 -0
  40. package/harness/registry.mjs +9 -0
  41. package/ktvm/ast.mjs +218 -0
  42. package/ktvm/bit-deque.mjs +497 -0
  43. package/ktvm/fixtures/integer-streaming.k +477 -0
  44. package/ktvm/index.mjs +130 -0
  45. package/ktvm/llvm/index.mjs +202 -0
  46. package/ktvm/llvm/lower-c.mjs +1258 -0
  47. package/ktvm/llvm/runtime.h +3542 -0
  48. package/ktvm/llvm/test-llvm.mjs +476 -0
  49. package/ktvm/lower-kir.mjs +2221 -0
  50. package/ktvm/optimize/fuse-kernel.mjs +2111 -0
  51. package/ktvm/optimize/index.mjs +116 -0
  52. package/ktvm/optimize/mwtr.mjs +283 -0
  53. package/ktvm/optimize/simplify-procs.mjs +5250 -0
  54. package/ktvm/optimize/synthesize-tables.mjs +1105 -0
  55. package/ktvm/parser.mjs +1101 -0
  56. package/ktvm/printer.mjs +281 -0
  57. package/ktvm/schema.mjs +1134 -0
  58. package/ktvm/specialize.mjs +538 -0
  59. package/ktvm/test-conformance.mjs +597 -0
  60. package/ktvm/test-ktvm.mjs +1805 -0
  61. package/ktvm/test-optimize.mjs +598 -0
  62. package/ktvm/validator.mjs +1280 -0
  63. package/ktvm/vm.mjs +2225 -0
  64. package/ktvm/wasm/index.mjs +331 -0
  65. package/ktvm/wasm/lower-wasm.mjs +1272 -0
  66. package/ktvm/wasm/runtime.wat +4404 -0
  67. package/ktvm/wasm/test-wasm.mjs +429 -0
  68. package/ktvm/wire.mjs +679 -0
  69. package/package.json +1 -9
  70. package/paper/Makefile +8 -5
  71. package/paper/k-transducer-compiler.pdf +0 -0
  72. package/paper/k-transducer-compiler.tex +658 -0
  73. package/paper/replay-diagnostic.mjs +63 -0
  74. package/repl.mjs +101 -20
  75. package/scripts/build-repl-html.mjs +40 -18
  76. package/scripts/perf-bigint-compare.mjs +12 -16
  77. package/scripts/perf-ieee.mjs +14 -232
  78. package/scripts/perf-int.mjs +16 -274
  79. package/scripts/perf-multiplication.mjs +116 -121
  80. package/scripts/perf-poly.mjs +9 -263
  81. package/scripts/run-tests.mjs +5 -2
  82. package/scripts/test-package.mjs +15 -3
  83. package/tests/README.md +3 -3
  84. package/tests/test-repl-html.mjs +72 -15
  85. package/tests/test-repl.mjs +24 -17
  86. package/DOCS/POLYMORPHIC_IR.md +0 -86
  87. package/access-table.mjs +0 -343
  88. package/pkir.mjs +0 -772
  89. package/tests/test-access-table.mjs +0 -213
  90. package/tests/test-pkir.mjs +0 -530
@@ -7,7 +7,6 @@
7
7
  * across available execution backends:
8
8
  * - LLVM (native binary via Clang/LLVM)
9
9
  * - WebAssembly (persistent runner via Wasm)
10
- * - PKIR (persistent runner via Wasm/PKIR)
11
10
  * - kVM Interpreter (envelope-free bytecode engine)
12
11
  * - Native JS (envelope-free convergence engine)
13
12
  *
@@ -36,9 +35,10 @@ import {
36
35
  evaluateInput,
37
36
  executeKVM,
38
37
  run_converged,
39
- valueForCode
38
+ Value
40
39
  } from "@fraczak/k/backend-api.mjs";
41
- 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";
42
42
  import { compileObjectBuffer } from "@fraczak/k/object.mjs";
43
43
  import {
44
44
  compileObjectToExecutable
@@ -67,7 +67,7 @@ function printHelp() {
67
67
 
68
68
  Multiplication Performance Harness.
69
69
  Benchmarks lib/integer.k multiplication ('times', Karatsuba) across
70
- available execution backends (LLVM, Wasm, PKIR, kVM, JS).
70
+ available execution backends (LLVM, Wasm, kVM, JS).
71
71
 
72
72
  Options:
73
73
  --mode <squaring|sizes>
@@ -76,8 +76,8 @@ Options:
76
76
  (default: squaring)
77
77
  --backends <csv>
78
78
  Comma-separated list of execution backends to test:
79
- llvm, llvm-pkir, wasm, pkir, kvm, js.
80
- (default: llvm,llvm-pkir,wasm,pkir,kvm,js)
79
+ llvm, wasm, kvm, js.
80
+ (default: llvm,wasm,kvm,js)
81
81
  --algos <csv>
82
82
  Comma-separated list of multiplication algorithms to test:
83
83
  times. (default: times)
@@ -116,7 +116,7 @@ if (hasFlag("-h") || hasFlag("--help")) {
116
116
  }
117
117
 
118
118
  const mode = getArg("--mode", "squaring"); // 'squaring' or 'sizes'
119
- const defaultBackends = "llvm,llvm-pkir,wasm,pkir,kvm,js";
119
+ const defaultBackends = "llvm,wasm,kvm,js";
120
120
  const backendsArg = getArg(
121
121
  "--backends",
122
122
  process.env.BACKENDS || defaultBackends
@@ -238,13 +238,19 @@ const arithLibChain = [
238
238
 
239
239
  const cacheDir = makeCacheDir("k-mult-perf-");
240
240
 
241
- // 2. Prepare Squaring Relations & Binaries
242
- // 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[] }`
243
244
  const algoRelations = {};
244
- const algoServers = { llvm: {}, "llvm-pkir": {}, wasm: {}, pkir: {} };
245
+ const algoServers = { llvm: {}, wasm: {} };
245
246
 
246
247
  let commonState = null;
247
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
+
248
254
  for (const algo of selectedAlgos) {
249
255
  const filePath = arithLibChain[arithLibChain.length - 1];
250
256
 
@@ -256,9 +262,12 @@ for (const algo of selectedAlgos) {
256
262
 
257
263
  if (!commonState) commonState = algoState;
258
264
 
259
- const relName = `s_${algo}`;
260
- await evaluateInput(`${relName} = {()x, ()y} ${algo};`, algoState);
261
- 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
+ }
262
271
 
263
272
  const prepared = prepareRelation(algoState, relName, {
264
273
  sourceLabel: `${filePath}#${relName}`
@@ -268,12 +277,12 @@ for (const algo of selectedAlgos) {
268
277
 
269
278
  // LLVM
270
279
  if (selectedBackends.includes("llvm")) {
271
- const exePath = path.join(cacheDir, `perf_mult_llvm_${algo}`);
280
+ const exePath = path.join(cacheDir, `perf_mult_llvm_${mode}_${algo}`);
272
281
  try {
273
282
  compileObjectToExecutable(
274
283
  algoRelations[algo].object, exePath, {
275
284
  clangOpt: "-O2",
276
- inputPattern: parseIntValue("0").pattern
285
+ inputPattern: sampleInputPattern
277
286
  }
278
287
  );
279
288
  algoServers.llvm[algo] = new PersistentExecutable(exePath);
@@ -284,33 +293,13 @@ for (const algo of selectedAlgos) {
284
293
  }
285
294
  }
286
295
 
287
- // LLVM (via PKIR)
288
- if (selectedBackends.includes("llvm-pkir")) {
289
- const exePath = path.join(cacheDir, `perf_mult_llvm_pkir_${algo}`);
290
- try {
291
- compileObjectToExecutable(
292
- algoRelations[algo].object, exePath, {
293
- clangOpt: "-O2",
294
- inputPattern: parseIntValue("0").pattern,
295
- usePKIR: true
296
- }
297
- );
298
- algoServers["llvm-pkir"][algo] =
299
- new PersistentExecutable(exePath);
300
- } catch (e) {
301
- console.warn(
302
- `[WARN] Failed to compile LLVM-PKIR for ${algo}: ${e.message}`
303
- );
304
- }
305
- }
306
-
307
296
  // Wasm
308
297
  if (selectedBackends.includes("wasm")) {
309
- const wasmPath = path.join(cacheDir, `perf_mult_wasm_${algo}.wasm`);
310
- 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`);
311
300
  try {
312
301
  const wasmBuf = await compileWasmArtifactFromObject(
313
- algoRelations[algo].object, { entry: "__main__" }
302
+ algoRelations[algo].object, { entry: algoRelations[algo].relHash }
314
303
  );
315
304
  fs.writeFileSync(wasmPath, wasmBuf);
316
305
  const runBin = fileURLToPath(
@@ -328,33 +317,9 @@ for (const algo of selectedAlgos) {
328
317
  );
329
318
  }
330
319
  }
331
-
332
- // PKIR
333
- if (selectedBackends.includes("pkir")) {
334
- const pkirPath = path.join(cacheDir, `perf_mult_pkir_${algo}.wasm`);
335
- const exePath = path.join(cacheDir, `perf_mult_pkir_${algo}.exe`);
336
- try {
337
- const wasmBuf = await compileWasmArtifactFromObject(
338
- algoRelations[algo].object, { entry: "__main__", usePKIR: true }
339
- );
340
- fs.writeFileSync(pkirPath, wasmBuf);
341
- const runBin = fileURLToPath(
342
- import.meta.resolve("../backends/wasm/bin/k-wasm-run.mjs")
343
- );
344
- fs.writeFileSync(
345
- exePath,
346
- `#!/bin/sh\nexec node "${runBin}" "${pkirPath}" "$@"\n`,
347
- { mode: 0o755 }
348
- );
349
- algoServers.pkir[algo] = new PersistentExecutable(exePath);
350
- } catch (e) {
351
- console.warn(
352
- `[WARN] Failed to compile PKIR for ${algo}: ${e.message}`
353
- );
354
- }
355
- }
356
320
  }
357
321
 
322
+ try {
358
323
  // 3. Squaring Mode Benchmark
359
324
  if (mode === "squaring") {
360
325
  const sInitVal = parseIntValue(squaringInputText);
@@ -371,8 +336,8 @@ if (mode === "squaring") {
371
336
  const stepBits = [];
372
337
 
373
338
  try {
374
- // A. Run persistent backends (LLVM, LLVM-PKIR, Wasm, PKIR)
375
- const activeBackends = ["llvm", "llvm-pkir", "wasm", "pkir"]
339
+ // A. Run persistent backends (LLVM, Wasm)
340
+ const activeBackends = ["llvm", "wasm"]
376
341
  .filter(b => selectedBackends.includes(b));
377
342
  for (const backend of activeBackends) {
378
343
  for (const algo of selectedAlgos) {
@@ -582,14 +547,8 @@ if (mode === "squaring") {
582
547
  }
583
548
 
584
549
  console.log();
585
-
586
550
  } finally {
587
- // Teardown persistent servers
588
- for (const backend of ["llvm", "llvm-pkir", "wasm", "pkir"]) {
589
- for (const algo of selectedAlgos) {
590
- algoServers[backend]?.[algo]?.child?.kill();
591
- }
592
- }
551
+ // Cleanup handled in outer finally block
593
552
  }
594
553
  }
595
554
 
@@ -611,67 +570,103 @@ if (mode === "sizes") {
611
570
  console.log("\n" + th);
612
571
  console.log("-".repeat(th.length));
613
572
 
614
- const relDefTimes = selectedAlgos.includes("times")
615
- ? prepareRelation(algoRelations.times.state, "times").relDef
616
- : null;
617
- const relDefKara = selectedAlgos.includes("karatsuba")
618
- ? prepareRelation(algoRelations.karatsuba.state, "karatsuba").relDef
619
- : 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
+ }
620
609
 
621
610
  for (const bits of sizesList) {
622
611
  const strA = randomBigIntBits(bits);
623
612
  const strB = randomBigIntBits(bits);
613
+ const expectedStr = (BigInt(strA) * BigInt(strB)).toString();
624
614
 
625
615
  const valA = parseIntValue(strA);
626
616
  const valB = parseIntValue(strB);
627
- 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);
628
619
 
629
620
  for (const backend of selectedBackends) {
630
- if (backend === "js") {
631
- let resTimes = null;
632
- let tTime = null;
633
- if (relDefTimes) {
634
- run_converged.defs = algoRelations.times.state;
635
- const t0_t = performance.now();
636
- resTimes = run_converged(
637
- codes.find,
638
- relDefTimes.def,
639
- pairInput,
640
- relDefTimes.typePatternGraph
641
- );
642
- tTime = performance.now() - t0_t;
643
- }
621
+ let tRun = { value: null, timeMs: null };
622
+ let kRun = { value: null, timeMs: null };
623
+ let errMsg = null;
644
624
 
645
- let resKara = null;
646
- let kTime = null;
647
- if (relDefKara) {
648
- run_converged.defs = algoRelations.karatsuba.state;
649
- const t0_k = performance.now();
650
- resKara = run_converged(
651
- codes.find,
652
- relDefKara.def,
653
- pairInput,
654
- relDefKara.typePatternGraph
655
- );
656
- kTime = performance.now() - t0_k;
625
+ try {
626
+ if (relTimes) {
627
+ tRun = await runOneSize(backend, "times", relTimes, pairInput, pairWire);
657
628
  }
629
+ if (relKara) {
630
+ kRun = await runOneSize(backend, "karatsuba", relKara, pairInput, pairWire);
631
+ }
632
+ } catch (e) {
633
+ errMsg = e.message;
634
+ }
658
635
 
659
- const match = (!resTimes || !resKara)
660
- ? true
661
- : JSON.stringify(resTimes) === JSON.stringify(resKara);
662
- const speedup = (tTime != null && kTime != null)
663
- ? fmtSpeedup(tTime, kTime)
664
- : "-";
665
- const colBits = bits.toString().padStart(11);
666
- const colBe = backend.padEnd(7);
667
- const colT = fmtMs(tTime).padStart(11);
668
- const colK = fmtMs(kTime).padStart(11);
669
- const colSp = speedup.padStart(13);
670
- const colMatch = match ? "MATCH OK" : "MISMATCH";
671
- console.log(
672
- `${colBits} | ${colBe} | ${colT} | ${colK} | ` +
673
- `${colSp} | ${colMatch}`
674
- );
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();
675
670
  }
676
671
  }
677
672
  }