@fraczak/k 8.8.0 → 9.0.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 (94) 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 +902 -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 +6 -4
  10. package/DOCS/README.md +3 -2
  11. package/DOCS/REPL.md +16 -12
  12. package/README.md +132 -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 -5
  21. package/backends/llvm/src/llvm.mjs +4 -111
  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 +0 -16
  25. package/backends/wasm/README.md +2 -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 +10 -56
  30. package/browser/repl-browser.mjs +9 -8
  31. package/browser/shims/buffer.mjs +31 -2
  32. package/browser/shims/child_process.mjs +26 -0
  33. package/browser/shims/fs.mjs +3 -1
  34. package/codecs/djson.mjs +2 -3
  35. package/codecs/int.mjs +66 -14
  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 +482 -0
  43. package/ktvm/fixtures/integer-streaming.k +477 -0
  44. package/ktvm/index.mjs +119 -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 +543 -0
  58. package/ktvm/specialize.mjs +538 -0
  59. package/ktvm/test-conformance.mjs +597 -0
  60. package/ktvm/test-ktvm.mjs +1376 -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 +4413 -0
  67. package/ktvm/wasm/test-wasm.mjs +426 -0
  68. package/ktvm/wire.mjs +489 -0
  69. package/lib/djson.k +175 -173
  70. package/lib/generic.k +82 -97
  71. package/lib/ieee.k +110 -115
  72. package/lib/integer.k +25 -31
  73. package/package.json +1 -9
  74. package/repl.mjs +101 -20
  75. package/scripts/build-repl-html.mjs +40 -18
  76. package/scripts/perf-bigint-compare.mjs +275 -0
  77. package/scripts/perf-ieee.mjs +9 -229
  78. package/scripts/perf-int.mjs +14 -272
  79. package/scripts/perf-multiplication.mjs +8 -54
  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-djson-methods.mjs +0 -1
  85. package/tests/test-djson.mjs +0 -1
  86. package/tests/test-generic.mjs +5 -7
  87. package/tests/test-repl-html.mjs +72 -15
  88. package/tests/test-repl.mjs +27 -20
  89. package/tests/test-structural-values.mjs +1 -1
  90. package/DOCS/POLYMORPHIC_IR.md +0 -86
  91. package/access-table.mjs +0 -343
  92. package/pkir.mjs +0 -772
  93. package/tests/test-access-table.mjs +0 -213
  94. package/tests/test-pkir.mjs +0 -530
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Verified `kTVM -> kTVM` Optimization Pipeline (Milestone 3).
3
+ *
4
+ * Stages:
5
+ * 1. `fuseKernels`: CPS symbolic `proc -> kernel` fusion, TMC forward
6
+ * streaming, finite-enum register promotion, and virtual LIFO bit-stack
7
+ * promotion (gracefully skipping wide alphabets and branching recursion).
8
+ * 2. `synthesizeTables`: Bit-chunk / stack-chunk / FSM table synthesis with
9
+ * SWAR don't-care bit compression and Howard's MWTR global L1 budget
10
+ * allocation (default 64 KB).
11
+ * 3. Always-on `validateModule(..., { verifyTables })` proving SPSC linearity,
12
+ * dual-schema typing, and table-to-CFG bisimulation equivalence.
13
+ */
14
+
15
+ import { validateModule } from "../validator.mjs";
16
+ import {
17
+ simplifyProcs,
18
+ inlinePostFusionWrappers,
19
+ unfoldShortBitRecProcs,
20
+ computeProcMinBitConsumption
21
+ } from "./simplify-procs.mjs";
22
+ import { fuseKernels } from "./fuse-kernel.mjs";
23
+ import { synthesizeTables } from "./synthesize-tables.mjs";
24
+ import {
25
+ DEFAULT_L1_BUDGET_BYTES,
26
+ allocateTableBudgets,
27
+ budgetClassForBytes,
28
+ computeMWTR
29
+ } from "./mwtr.mjs";
30
+
31
+ export {
32
+ DEFAULT_L1_BUDGET_BYTES,
33
+ computeMWTR,
34
+ budgetClassForBytes,
35
+ allocateTableBudgets,
36
+ simplifyProcs,
37
+ unfoldShortBitRecProcs,
38
+ computeProcMinBitConsumption,
39
+ fuseKernels,
40
+ synthesizeTables
41
+ };
42
+
43
+ /**
44
+ * Run the full verified `kTVM -> kTVM` optimization pipeline on a concrete
45
+ * `mono` kTVM module.
46
+ */
47
+ export function optimizeKTVM(
48
+ monoModule,
49
+ {
50
+ simplify = true,
51
+ fuse = true,
52
+ tables = true,
53
+ unfold = true,
54
+ budgetBytes = DEFAULT_L1_BUDGET_BYTES,
55
+ verifyTables = true,
56
+ validate = true,
57
+ maxDecisionNodes = 192,
58
+ maxUnionTags = 12,
59
+ enableVirtualStack = true
60
+ } = {}
61
+ ) {
62
+ let cur = monoModule;
63
+ let simplifyStats = null;
64
+ let fuseStats = null;
65
+ let tableStats = null;
66
+
67
+ if (simplify) {
68
+ const s = simplifyProcs(cur);
69
+ cur = s.module;
70
+ simplifyStats = s.stats;
71
+ }
72
+
73
+ if (fuse) {
74
+ const f = fuseKernels(cur, { maxDecisionNodes, maxUnionTags, enableVirtualStack });
75
+ cur = f.module;
76
+ fuseStats = f.stats;
77
+ }
78
+
79
+ if (tables) {
80
+ const t = synthesizeTables(cur, { budgetBytes });
81
+ cur = t.module;
82
+ tableStats = t.stats;
83
+ } else {
84
+ // Strip any internal `_optMeta` if tables were skipped
85
+ for (const k of cur.kernels || []) delete k._optMeta;
86
+ }
87
+
88
+ let postFusionStats = null;
89
+ if (simplify && fuse) {
90
+ const pf = inlinePostFusionWrappers(cur);
91
+ cur = pf.module;
92
+ postFusionStats = pf.stats;
93
+ }
94
+
95
+ let unfoldStats = null;
96
+ if (simplify && unfold) {
97
+ const uf = unfoldShortBitRecProcs(cur);
98
+ cur = uf.module;
99
+ unfoldStats = uf.stats;
100
+ }
101
+
102
+ if (validate) {
103
+ validateModule(cur, { verifyTables });
104
+ }
105
+
106
+ return {
107
+ module: cur,
108
+ stats: {
109
+ simplify: simplifyStats,
110
+ fuse: fuseStats,
111
+ tables: tableStats,
112
+ postFusion: postFusionStats,
113
+ unfold: unfoldStats
114
+ }
115
+ };
116
+ }
@@ -0,0 +1,283 @@
1
+ /**
2
+ * Exact Worst-Case Throughput Evaluator (Howard's Policy-Improvement MWTR)
3
+ * and Global L1 Table Budget Allocator for `kTVM`.
4
+ *
5
+ * Implements DOCS/KTVM_SPEC.md §6.2:
6
+ * - Howard's policy-improvement algorithm in Max-Plus algebra computing:
7
+ * rho*(G) = min_{C in G} ( sum_{e in C} w(e) / sum_{e in C} t(e) )
8
+ * where w(e) = input bits shifted along transition e, t(e) = table lookups.
9
+ * - Global L1 budget allocator (default 65,536 bytes = 64 KB) choosing the
10
+ * highest-MWTR table configuration per kernel within the memory budget,
11
+ * gracefully falling back to un-chunked kernel CFG when over budget or
12
+ * on wide alphabets.
13
+ */
14
+
15
+ const EPS = 1e-11;
16
+
17
+ export const DEFAULT_L1_BUDGET_BYTES = 65536; // 64 KB L1-resident default
18
+
19
+ /**
20
+ * Compute exact Minimum Weight-to-Time Ratio `rho*(G)` and critical bottleneck
21
+ * cycle `C*` via Howard's policy-improvement algorithm.
22
+ *
23
+ * @param {number} numNodes
24
+ * @param {Array<{from: number, to: number, w: number, t: number, label?: string}>} edges
25
+ * @param {{ maxIters?: number }} [opts]
26
+ * @returns {{ rho: number, cycleNodes: number[], cycleEdges: object[], iterations: number }}
27
+ */
28
+ export function computeMWTR(numNodes, edges, { maxIters = 200 } = {}) {
29
+ const out = Array.from({ length: numNodes }, () => []);
30
+ for (const e of edges) {
31
+ out[e.from].push(e);
32
+ }
33
+
34
+ // Prune vertices with out-degree 0 (cannot lie on any directed cycle)
35
+ const alive = new Uint8Array(numNodes).fill(1);
36
+ let changed = true;
37
+ while (changed) {
38
+ changed = false;
39
+ for (let u = 0; u < numNodes; u++) {
40
+ if (!alive[u]) continue;
41
+ let hasAliveOut = false;
42
+ for (const e of out[u]) {
43
+ if (alive[e.to]) {
44
+ hasAliveOut = true;
45
+ break;
46
+ }
47
+ }
48
+ if (!hasAliveOut) {
49
+ alive[u] = 0;
50
+ changed = true;
51
+ }
52
+ }
53
+ }
54
+
55
+ const activeNodes = [];
56
+ for (let u = 0; u < numNodes; u++) {
57
+ if (alive[u]) activeNodes.push(u);
58
+ }
59
+ if (activeNodes.length === 0) {
60
+ return { rho: Infinity, cycleNodes: [], cycleEdges: [], iterations: 0 };
61
+ }
62
+
63
+ const adj = Array.from({ length: numNodes }, () => []);
64
+ for (const u of activeNodes) {
65
+ for (const e of out[u]) {
66
+ if (alive[e.to]) adj[u].push(e);
67
+ }
68
+ }
69
+
70
+ // Initial policy: pick minimum local ratio w / t per vertex
71
+ const policy = new Array(numNodes).fill(null);
72
+ for (const u of activeNodes) {
73
+ let best = adj[u][0];
74
+ let bestScore = best.t > 0 ? best.w / best.t : Infinity;
75
+ for (let i = 1; i < adj[u].length; i++) {
76
+ const e = adj[u][i];
77
+ const sc = e.t > 0 ? e.w / e.t : Infinity;
78
+ if (sc < bestScore) {
79
+ best = e;
80
+ bestScore = sc;
81
+ }
82
+ }
83
+ policy[u] = best;
84
+ }
85
+
86
+ const eta = new Float64Array(numNodes);
87
+ const bias = new Float64Array(numNodes);
88
+ const state = new Int8Array(numNodes);
89
+ let iterations = 0;
90
+ let lastCycles = [];
91
+
92
+ for (let iter = 0; iter < maxIters; iter++) {
93
+ iterations++;
94
+ state.fill(0);
95
+ lastCycles = [];
96
+
97
+ const revPolicy = Array.from({ length: numNodes }, () => []);
98
+ for (const u of activeNodes) {
99
+ revPolicy[policy[u].to].push(u);
100
+ }
101
+
102
+ // Step 1: Policy evaluation on the functional graph `policy`
103
+ const cycleRoots = [];
104
+ for (const start of activeNodes) {
105
+ if (state[start] !== 0) continue;
106
+ const path = [];
107
+ let cur = start;
108
+ while (state[cur] === 0) {
109
+ state[cur] = 1;
110
+ path.push(cur);
111
+ cur = policy[cur].to;
112
+ }
113
+ if (state[cur] === 1) {
114
+ const cStart = path.indexOf(cur);
115
+ const cNodes = path.slice(cStart);
116
+ let sumW = 0;
117
+ let sumT = 0;
118
+ let root = cNodes[0];
119
+ const cEdges = [];
120
+ for (const u of cNodes) {
121
+ const e = policy[u];
122
+ cEdges.push(e);
123
+ sumW += e.w;
124
+ sumT += e.t;
125
+ if (u < root) root = u;
126
+ }
127
+ const ratio = sumT > 0 ? sumW / sumT : (sumW === 0 ? 0 : Infinity);
128
+ cycleRoots.push({ root, ratio, cNodes, cEdges });
129
+ lastCycles.push({ ratio, cNodes, cEdges });
130
+ }
131
+ for (const u of path) state[u] = 2;
132
+ }
133
+
134
+ // Propagate `(eta, bias)` backwards from each cycle root
135
+ const visited = new Uint8Array(numNodes);
136
+ for (const { root, ratio } of cycleRoots) {
137
+ eta[root] = ratio;
138
+ bias[root] = 0;
139
+ visited[root] = 1;
140
+ const queue = [root];
141
+ for (let qi = 0; qi < queue.length; qi++) {
142
+ const v = queue[qi];
143
+ for (const u of revPolicy[v]) {
144
+ if (visited[u]) continue;
145
+ visited[u] = 1;
146
+ eta[u] = ratio;
147
+ const e = policy[u];
148
+ bias[u] = e.w - ratio * e.t + bias[v];
149
+ queue.push(u);
150
+ }
151
+ }
152
+ }
153
+
154
+ // Step 2: Policy improvement
155
+ let improved = false;
156
+ for (const u of activeNodes) {
157
+ let bestEta = eta[u];
158
+ let bestEdge = null;
159
+ for (const e of adj[u]) {
160
+ if (eta[e.to] < bestEta - EPS) {
161
+ bestEta = eta[e.to];
162
+ bestEdge = e;
163
+ }
164
+ }
165
+ if (bestEdge) {
166
+ policy[u] = bestEdge;
167
+ improved = true;
168
+ }
169
+ }
170
+ if (improved) continue;
171
+
172
+ for (const u of activeNodes) {
173
+ let bestVal = bias[u];
174
+ let bestEdge = null;
175
+ for (const e of adj[u]) {
176
+ if (Math.abs(eta[e.to] - eta[u]) > EPS) continue;
177
+ const val = e.w - eta[u] * e.t + bias[e.to];
178
+ if (val < bestVal - EPS) {
179
+ bestVal = val;
180
+ bestEdge = e;
181
+ }
182
+ }
183
+ if (bestEdge) {
184
+ policy[u] = bestEdge;
185
+ improved = true;
186
+ }
187
+ }
188
+
189
+ if (!improved) break;
190
+ }
191
+
192
+ let bestCycle = lastCycles[0] || { ratio: Infinity, cNodes: [], cEdges: [] };
193
+ for (const c of lastCycles) {
194
+ if (c.ratio < bestCycle.ratio) bestCycle = c;
195
+ }
196
+ return {
197
+ rho: bestCycle.ratio,
198
+ cycleNodes: bestCycle.cNodes,
199
+ cycleEdges: bestCycle.cEdges,
200
+ iterations
201
+ };
202
+ }
203
+
204
+ /**
205
+ * Classify table byte footprint into cache-residency classes.
206
+ */
207
+ export function budgetClassForBytes(bytes) {
208
+ if (bytes <= 16384) return "L1-small";
209
+ if (bytes <= 65536) return "L1";
210
+ if (bytes <= 262144) return "L2";
211
+ return "L3";
212
+ }
213
+
214
+ /**
215
+ * Global L1 budget allocator across multiple kernels.
216
+ *
217
+ * Each item in `kernelFrontiers` is `{ kernelName, candidates }` where each
218
+ * candidate has `{ bytes, rho, score?, ... }` sorted from smallest to largest
219
+ * byte footprint (Pareto-pruned to strictly increasing `rho`).
220
+ *
221
+ * Greedy marginal-gain knapsack (`delta_rho / delta_bytes`) starts every kernel
222
+ * at "no table" (0 bytes, un-chunked CFG fallback) and upgrades the kernel with
223
+ * the best marginal throughput-per-byte gain until `budgetBytes` is exhausted.
224
+ */
225
+ export function allocateTableBudgets(kernelFrontiers, { budgetBytes = DEFAULT_L1_BUDGET_BYTES } = {}) {
226
+ const chosen = new Map(); // kernelName -> candidate | null
227
+ const paretoByKernel = new Map();
228
+
229
+ for (const { kernelName, candidates } of kernelFrontiers) {
230
+ // Filter candidates that fit alone and extract Pareto frontier (strictly better rho for more bytes)
231
+ const sorted = [...candidates]
232
+ .filter((c) => c.bytes <= budgetBytes && c.rho > 0)
233
+ .sort((a, b) => a.bytes - b.bytes || b.rho - a.rho);
234
+ const frontier = [];
235
+ let bestRho = -1;
236
+ for (const c of sorted) {
237
+ if (c.rho > bestRho + 1e-9) {
238
+ frontier.push(c);
239
+ bestRho = c.rho;
240
+ }
241
+ }
242
+ paretoByKernel.set(kernelName, frontier);
243
+ chosen.set(kernelName, null);
244
+ }
245
+
246
+ let usedBytes = 0;
247
+ const idxByKernel = new Map([...paretoByKernel.keys()].map((k) => [k, -1]));
248
+
249
+ while (true) {
250
+ let bestKernel = null;
251
+ let bestNextIdx = -1;
252
+ let bestEfficiency = -1;
253
+
254
+ for (const [kName, frontier] of paretoByKernel.entries()) {
255
+ const curIdx = idxByKernel.get(kName);
256
+ const curBytes = curIdx >= 0 ? frontier[curIdx].bytes : 0;
257
+ const curRho = curIdx >= 0 ? frontier[curIdx].rho : 0;
258
+
259
+ // Consider upgrading `kName` to any higher frontier point that fits remaining budget
260
+ for (let nxt = curIdx + 1; nxt < frontier.length; nxt++) {
261
+ const deltaBytes = frontier[nxt].bytes - curBytes;
262
+ if (usedBytes + deltaBytes > budgetBytes) continue;
263
+ const deltaRho = frontier[nxt].rho - curRho;
264
+ const eff = deltaBytes > 0 ? deltaRho / deltaBytes : Infinity;
265
+ if (eff > bestEfficiency) {
266
+ bestEfficiency = eff;
267
+ bestKernel = kName;
268
+ bestNextIdx = nxt;
269
+ }
270
+ }
271
+ }
272
+
273
+ if (bestKernel === null) break;
274
+ const frontier = paretoByKernel.get(bestKernel);
275
+ const prevIdx = idxByKernel.get(bestKernel);
276
+ const prevBytes = prevIdx >= 0 ? frontier[prevIdx].bytes : 0;
277
+ usedBytes += frontier[bestNextIdx].bytes - prevBytes;
278
+ idxByKernel.set(bestKernel, bestNextIdx);
279
+ chosen.set(bestKernel, frontier[bestNextIdx]);
280
+ }
281
+
282
+ return { chosen, usedBytes, budgetBytes };
283
+ }