poker-flopsolve 0.4.1 → 0.5.0-beta.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.
- package/CHANGELOG.md +73 -0
- package/README.md +936 -86
- package/dist/browser-threads.js +238 -0
- package/dist/browser-threads.js.map +1 -0
- package/dist/browser.js +2195 -396
- package/dist/browser.js.map +1 -1
- package/dist/engine-worker.js +81 -50
- package/dist/engine-worker.js.map +1 -1
- package/dist/index.d.ts +1251 -30
- package/dist/index.js +2178 -392
- package/dist/index.js.map +1 -1
- package/dist/threads.d.ts +41 -0
- package/dist/threads.js +28 -0
- package/dist/threads.js.map +1 -0
- package/dist/wasm-storage.d.ts +84 -0
- package/dist/wasm-storage.js +532 -0
- package/dist/wasm-storage.js.map +1 -0
- package/dist/worker.js +1037 -240
- package/dist/worker.js.map +1 -1
- package/docs/APPROXIMATIONS.md +588 -0
- package/package.json +19 -4
package/dist/engine-worker.js
CHANGED
|
@@ -1,57 +1,88 @@
|
|
|
1
1
|
// src/engine-worker.ts
|
|
2
2
|
import { parentPort, workerData } from "worker_threads";
|
|
3
3
|
|
|
4
|
-
// src/engine.ts
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
engine
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
if (
|
|
34
|
-
const
|
|
35
|
-
const
|
|
36
|
-
const
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
);
|
|
51
|
-
|
|
4
|
+
// src/engine-thread.ts
|
|
5
|
+
function serveEngine(setup) {
|
|
6
|
+
const GENERATION = 0;
|
|
7
|
+
const DONE = 1;
|
|
8
|
+
const COMMAND = 2;
|
|
9
|
+
const MODE = 3;
|
|
10
|
+
const TRAVERSER = 4;
|
|
11
|
+
const READY = 5;
|
|
12
|
+
const FAILED = 6;
|
|
13
|
+
const EXIT = 1;
|
|
14
|
+
const api = globalThis.WebAssembly;
|
|
15
|
+
const memory = setup.memory;
|
|
16
|
+
const imports = {
|
|
17
|
+
env: {
|
|
18
|
+
memory,
|
|
19
|
+
abort() {
|
|
20
|
+
throw new Error("engine abort");
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
const engine = new api.Instance(setup.module, imports).exports;
|
|
25
|
+
engine.init(setup.header);
|
|
26
|
+
engine.setMaxActions(setup.maxActions);
|
|
27
|
+
engine.setExchange(setup.exchange[0], setup.exchange[1], setup.exchange[2], setup.exchange[3]);
|
|
28
|
+
engine.setShard(setup.shard[0], setup.shard[1], setup.shard[2]);
|
|
29
|
+
engine.setPhase(0, 1);
|
|
30
|
+
const shared = setup.shared;
|
|
31
|
+
if (shared) engine.setShared(shared[0], shared[1], shared[2]);
|
|
32
|
+
const s = setup.sampling;
|
|
33
|
+
if (s) engine.setSampling(s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], s[11]);
|
|
34
|
+
const needsIteration = shared !== void 0 || setup.storage === true || s !== void 0;
|
|
35
|
+
const control = new Int32Array(setup.control);
|
|
36
|
+
const settings = new Float64Array(setup.settings);
|
|
37
|
+
const entries = setup.entryNodes.length;
|
|
38
|
+
const rowBytes = setup.stride * 4;
|
|
39
|
+
const partials = new Float32Array(memory.buffer, setup.partial, entries * setup.stride);
|
|
40
|
+
const reach = setup.exchange[1];
|
|
41
|
+
let generation = Atomics.load(control, GENERATION);
|
|
42
|
+
Atomics.add(control, READY, 1);
|
|
43
|
+
Atomics.notify(control, READY);
|
|
44
|
+
if (Atomics.load(control, COMMAND) === EXIT) return;
|
|
45
|
+
for (; ; ) {
|
|
46
|
+
Atomics.wait(control, GENERATION, generation);
|
|
47
|
+
generation = Atomics.load(control, GENERATION);
|
|
48
|
+
if (Atomics.load(control, COMMAND) === EXIT) return;
|
|
49
|
+
const mode = Atomics.load(control, MODE);
|
|
50
|
+
const traverser = Atomics.load(control, TRAVERSER);
|
|
51
|
+
const positive = settings[0];
|
|
52
|
+
const negative = settings[1];
|
|
53
|
+
const sum = settings[2];
|
|
54
|
+
const weight = settings[3];
|
|
55
|
+
const clamp = settings[4];
|
|
56
|
+
try {
|
|
57
|
+
engine.setPhase(0, settings[5]);
|
|
58
|
+
if (needsIteration) engine.setIteration(settings[6], settings[7]);
|
|
59
|
+
for (let entry = 0; entry < entries; entry++) {
|
|
60
|
+
const slot = reach + entry * 2 * rowBytes;
|
|
61
|
+
const out = engine.runChance(
|
|
62
|
+
mode,
|
|
63
|
+
traverser,
|
|
64
|
+
setup.entryNodes[entry],
|
|
65
|
+
slot,
|
|
66
|
+
slot + rowBytes,
|
|
67
|
+
positive,
|
|
68
|
+
negative,
|
|
69
|
+
sum,
|
|
70
|
+
weight,
|
|
71
|
+
clamp
|
|
72
|
+
) >>> 0;
|
|
73
|
+
partials.set(new Float32Array(memory.buffer, out, setup.stride), entry * setup.stride);
|
|
74
|
+
}
|
|
75
|
+
} catch (error) {
|
|
76
|
+
Atomics.store(control, FAILED, 1);
|
|
77
|
+
throw error;
|
|
78
|
+
} finally {
|
|
79
|
+
Atomics.add(control, DONE, 1);
|
|
80
|
+
Atomics.notify(control, DONE);
|
|
81
|
+
}
|
|
52
82
|
}
|
|
53
|
-
Atomics.add(control, ENGINE_CONTROL.done, 1);
|
|
54
|
-
Atomics.notify(control, ENGINE_CONTROL.done);
|
|
55
83
|
}
|
|
84
|
+
|
|
85
|
+
// src/engine-worker.ts
|
|
86
|
+
serveEngine(workerData);
|
|
56
87
|
parentPort?.close();
|
|
57
88
|
//# sourceMappingURL=engine-worker.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/engine-worker.ts","../src/engine.ts"],"sourcesContent":["/**\n * An engine worker: one thread of a WebAssembly solve.\n *\n * Purpose: walk this thread's slice of the runouts at the split round, over\n * the memory every thread shares, when the main thread signals. The protocol\n * is src/parallel.ts's: the main thread collects the reach each entry needs,\n * every thread walks its slice from each entry, the main thread adds the\n * slices up and finishes. Here all of it happens in shared WebAssembly\n * memory, so nothing is copied between threads but a few numbers of control.\n */\n\nimport { parentPort, workerData } from 'node:worker_threads';\nimport type { EngineExports, EngineWorkerSetup } from './engine.ts';\nimport { ENGINE_CONTROL } from './engine.ts';\n\nconst setup = workerData as EngineWorkerSetup;\nconst { WebAssembly: wasm } = globalThis as unknown as {\n\tWebAssembly: { Instance: new (module: unknown, imports: object) => { exports: Record<string, unknown> } };\n};\nconst memory = setup.memory as { buffer: SharedArrayBuffer };\nconst instance = new wasm.Instance(setup.module, { env: { memory, abort: () => { throw new Error('engine abort'); } } });\nconst engine = instance.exports as unknown as EngineExports;\nengine.init(setup.header);\nengine.setMaxActions(setup.maxActions);\nengine.setExchange(...setup.exchange);\nengine.setShard(...setup.shard);\nengine.setPhase(0, 1);\n\nconst control = new Int32Array(setup.control);\nconst settings = new Float64Array(setup.settings);\nconst entries = setup.entryNodes.length;\nconst rowBytes = setup.stride * 4;\nconst partials = new Float32Array(memory.buffer, setup.partial, entries * setup.stride);\nconst [, reach] = setup.exchange;\n\n// Latch the generation before announcing readiness, so no dispatch is missed.\nlet generation = Atomics.load(control, ENGINE_CONTROL.generation);\nAtomics.add(control, ENGINE_CONTROL.ready, 1);\nAtomics.notify(control, ENGINE_CONTROL.ready);\n\nfor (;;) {\n\tAtomics.wait(control, ENGINE_CONTROL.generation, generation);\n\tgeneration = Atomics.load(control, ENGINE_CONTROL.generation);\n\tif (Atomics.load(control, ENGINE_CONTROL.command) === 1) break;\n\tconst mode = Atomics.load(control, ENGINE_CONTROL.mode);\n\tconst traverser = Atomics.load(control, ENGINE_CONTROL.traverser);\n\tconst [positive, negative, sum, weight, clamp] = settings;\n\tfor (let entry = 0; entry < entries; entry++) {\n\t\tconst slot = reach + entry * 2 * rowBytes;\n\t\tconst out = engine.runChance(\n\t\t\tmode, traverser, setup.entryNodes[entry], slot, slot + rowBytes, positive, negative, sum, weight, clamp,\n\t\t);\n\t\tpartials.set(new Float32Array(memory.buffer, out, setup.stride), entry * setup.stride);\n\t}\n\tAtomics.add(control, ENGINE_CONTROL.done, 1);\n\tAtomics.notify(control, ENGINE_CONTROL.done);\n}\n\nparentPort?.close();\n","/**\n * The WebAssembly traversal engine, set up.\n *\n * Purpose: lay a prepared spot out in one WebAssembly memory for\n * `assembly/engine.ts`, and give the solver its storage and a root traversal.\n *\n * The engine keeps the accumulators in its own memory as 32-bit floats; the\n * solver's `regret` and `strategySum` are views onto them, so everything that\n * reads storage from JavaScript — strategy queries, warm starts, `valuesAt` —\n * sees the very same numbers. It runs single-threaded, with 32-bit storage,\n * where WebAssembly SIMD is available; otherwise the JavaScript traversal in\n * cfr.ts runs.\n */\n\nimport { COMBOS, DECK } from './cards.ts';\nimport type { ActiveLists, Layout, PlayerIndex, RootTraversal } from './cfr.ts';\nimport { dcfrFactors, Mode, treeDepth } from './cfr.ts';\nimport type { HandSpace } from './hands.ts';\nimport type { Runouts } from './runouts.ts';\nimport type { Tree } from './tree.ts';\nimport { ENGINE_WASM } from './wasm/engine.ts';\nimport { ENGINE_SHARED_WASM } from './wasm/engine-shared.ts';\nimport type { ShardPlan } from './parallel.ts';\nimport { WORKER_START_ERROR, WORKER_START_MS } from './parallel.ts';\n\n/** The parts of the WebAssembly API used here, typed locally: the project builds without DOM typings. */\ninterface WasmApi {\n\tvalidate(bytes: Uint8Array): boolean;\n\tModule: new (bytes: Uint8Array) => object;\n\tInstance: new (module: object, imports: object) => { exports: Record<string, unknown> };\n\tMemory: new (descriptor: { initial: number; maximum?: number; shared?: boolean }) => { buffer: ArrayBuffer };\n}\n\nconst wasm = (globalThis as unknown as { WebAssembly?: WasmApi }).WebAssembly;\nconst modules: Record<'plain' | 'shared', object | null | undefined> = { plain: undefined, shared: undefined };\n\n/** The compiled engine, over plain or shared memory; null where unavailable. */\nexport function compiledEngine(kind: 'plain' | 'shared'): object | null {\n\tif (modules[kind] !== undefined) return modules[kind]!;\n\tmodules[kind] = null;\n\ttry {\n\t\tif (!wasm) return null;\n\t\tconst text = kind === 'plain' ? ENGINE_WASM : ENGINE_SHARED_WASM;\n\t\tconst bytes = Uint8Array.from(atob(text), (c) => c.charCodeAt(0));\n\t\tif (!wasm.validate(bytes)) return null;\n\t\tmodules[kind] = new wasm.Module(bytes);\n\t} catch {\n\t\tmodules[kind] = null;\n\t}\n\treturn modules[kind]!;\n}\n\nfunction compiled(): object | null {\n\treturn compiledEngine('plain');\n}\n\n/** Whether this platform can run the WebAssembly engine. */\nexport function engineAvailable(): boolean {\n\treturn compiled() !== null;\n}\n\n/** What the engine needs from a prepared spot. */\nexport interface EngineInput {\n\treadonly tree: Tree;\n\treadonly runouts: Runouts;\n\treadonly players: readonly [PlayerIndex, PlayerIndex];\n\treadonly layout: Layout;\n\treadonly active: ActiveLists;\n\treadonly hands: HandSpace;\n\treadonly runoutWeight: Float64Array;\n\treadonly chipScale: number;\n}\n\n/** A running engine. */\nexport interface Engine {\n\t/** The accumulators, as views onto the engine's memory. */\n\treadonly regret: Float32Array;\n\treadonly strategySum: Float32Array;\n\t/** Install as the solver's root traversal; `dcfr` picks the update rule. */\n\troot(dcfr: boolean): RootTraversal;\n\t/** Release worker threads, if any. */\n\tclose(): void;\n\t/** Threads doing the work, this one included. */\n\treadonly threads: number;\n}\n\n/** What an engine worker needs; see src/engine-worker.ts. */\nexport interface EngineWorkerSetup {\n\treadonly memory: unknown;\n\treadonly module: unknown;\n\treadonly header: number;\n\treadonly maxActions: number;\n\treadonly exchange: readonly [number, number, number, number];\n\treadonly shard: readonly [number, number, number];\n\treadonly entryNodes: Int32Array;\n\treadonly rootMe: number;\n\treadonly rootOpp: number;\n\treadonly partial: number;\n\treadonly stride: number;\n\treadonly control: SharedArrayBuffer;\n\treadonly settings: SharedArrayBuffer;\n}\n\n/** How a pool starts its workers; the platform layer supplies it. */\nexport type SpawnEngineWorker = (setup: EngineWorkerSetup, onError: (error: Error) => void) => { terminate(): void };\n\n/** Control slots shared with engine workers. */\nexport const ENGINE_CONTROL = { generation: 0, done: 1, command: 2, mode: 3, traverser: 4, ready: 5, size: 8 } as const;\n\n/**\n * Lay a spot out in a fresh memory and instantiate the engine over it, or\n * null where unavailable. With `pool`, the memory is shared and that many\n * threads split the runouts at the plan's round, as src/parallel.ts does for\n * the JavaScript engine.\n */\nexport function createEngine(\n\tinput: EngineInput,\n\tpool?: { plan: ShardPlan; threads: number; spawn: SpawnEngineWorker },\n): Engine | null {\n\tconst shared = pool !== undefined;\n\tconst compiledModule = compiledEngine(shared ? 'shared' : 'plain');\n\tif (!compiledModule || !wasm) return null;\n\tconst { tree, runouts, layout, active, hands } = input;\n\tconst threads = pool ? pool.threads : 1;\n\n\tconst flatten = (parts: readonly Int32Array[]): [Int32Array, Int32Array] => {\n\t\tconst bases = new Int32Array(parts.length + 1);\n\t\tfor (let i = 0; i < parts.length; i++) bases[i + 1] = bases[i] + parts[i].length;\n\t\tconst flat = new Int32Array(bases[parts.length]);\n\t\tparts.forEach((part, i) => flat.set(part, bases[i]));\n\t\treturn [bases, flat];\n\t};\n\tconst [upRound, upStart] = flatten(hands.upStart);\n\tconst [childRound, childStart] = flatten(runouts.childStart);\n\tconst [orbitRound, orbitStart] = flatten(runouts.orbitStart);\n\tconst maxCount = Math.max(4, ...active.count);\n\tconst stride = Math.ceil(maxCount / 4) * 4;\n\tconst maxActions = Math.max(1, layout.maxActions);\n\tconst depths = treeDepth(tree) + 2;\n\tconst rowBytes = stride * 4;\n\tconst depthBytes = rowBytes * (3 + 2 * maxActions);\n\n\tconst pieces: { data: ArrayBufferView | null; bytes: number }[] = [];\n\tconst add = (data: ArrayBufferView | null, bytes = data ? data.byteLength : 0): number => {\n\t\tpieces.push({ data, bytes: Math.ceil(Math.max(bytes, 4) / 16) * 16 });\n\t\treturn pieces.length - 1;\n\t};\n\t// Shared by every thread, in header order.\n\tconst common = [\n\t\tadd(tree.kind), add(tree.round), add(Uint8Array.from(tree.player, (p) => (p < 0 ? 255 : p))), add(tree.firstEdge),\n\t\tadd(tree.numEdges), add(tree.edgeChild), add(tree.payoff), add(layout.offset), add(layout.rowStart),\n\t\tadd(active.roundBase), add(active.start), add(Int32Array.from(active.count)), add(active.cardA), add(active.cardB),\n\t\tadd(active.strength), add(active.tieStart), add(active.ties), add(upRound), add(upStart), add(hands.up),\n\t\tadd(hands.sameStart), add(hands.same), add(childRound), add(childStart), add(orbitRound), add(orbitStart),\n\t\tadd(input.runoutWeight),\n\t\tadd(null, layout.totalSlots * 4), // regret\n\t\tadd(null, layout.totalSlots * 4), // strategy sums\n\t];\n\tconst REGRET = common[27];\n\tconst SUMS = common[28];\n\t// Each thread's own.\n\tconst own = Array.from({ length: threads }, () => ({\n\t\tbuffers: add(null, depths * depthBytes),\n\t\tcardSums: add(null, 52 * 8 + stride * 8),\n\t\trootMe: add(null, rowBytes),\n\t\trootOpp: add(null, rowBytes),\n\t\theader: add(null, 40 * 4),\n\t}));\n\t// The exchange between threads.\n\tconst entries = pool ? pool.plan.entryNodes.length : 0;\n\tconst entryIndexOf = pool ? add(pool.plan.entryIndexOf) : -1;\n\tconst reach = pool ? add(null, entries * 2 * rowBytes) : -1;\n\tconst values = pool ? add(null, entries * rowBytes) : -1;\n\tconst partials = pool ? add(null, (threads - 1) * entries * rowBytes) : -1;\n\n\tconst offsets: number[] = [];\n\tlet total = 64;\n\tfor (const piece of pieces) {\n\t\toffsets.push(total);\n\t\ttotal += piece.bytes;\n\t}\n\tif (total > 0xffff0000) return null; // past wasm32's 4 GB\n\tconst pages = Math.ceil(total / 65536) + 1;\n\tconst memory = shared ? new wasm.Memory({ initial: pages, maximum: pages, shared: true }) : new wasm.Memory({ initial: pages });\n\tconst bytes = new Uint8Array(memory.buffer);\n\tpieces.forEach((piece, i) => {\n\t\tif (piece.data) bytes.set(new Uint8Array(piece.data.buffer, piece.data.byteOffset, piece.data.byteLength), offsets[i]);\n\t});\n\tfor (const mine of own) {\n\t\tconst head = new Uint32Array(memory.buffer, offsets[mine.header], 40);\n\t\tcommon.forEach((slot, i) => (head[i] = offsets[slot]));\n\t\thead[29] = offsets[mine.buffers];\n\t\thead[30] = depthBytes;\n\t\thead[31] = rowBytes;\n\t\thead[32] = offsets[mine.cardSums];\n\t\thead[33] = input.chipScale;\n\t}\n\n\tconst instance = new wasm.Instance(compiledModule, { env: { memory, abort: () => { throw new Error('engine abort'); } } });\n\tconst exports = instance.exports as unknown as EngineExports;\n\texports.init(offsets[own[0].header]);\n\texports.setMaxActions(maxActions);\n\n\tconst regret = new Float32Array(memory.buffer, offsets[REGRET], layout.totalSlots);\n\tconst strategySum = new Float32Array(memory.buffer, offsets[SUMS], layout.totalSlots);\n\tconst me = new Float32Array(memory.buffer, offsets[own[0].rootMe], stride);\n\tconst opp = new Float32Array(memory.buffer, offsets[own[0].rootOpp], stride);\n\tconst result = new Float64Array(COMBOS);\n\tconst rootList = (player: 0 | 1): [number, number] => {\n\t\tconst slot = active.roundBase[0] * 2 + player;\n\t\treturn [active.start[slot], active.count[slot]];\n\t};\n\tconst settingsFor = (mode: number, iterWeight: number, dcfr: boolean): [number, number, number, number, number] => {\n\t\tif (mode === Mode.Train && dcfr) {\n\t\t\tconst { keepPositive, keepNegative, keepSum } = dcfrFactors(iterWeight);\n\t\t\treturn [keepPositive, keepNegative, keepSum, 1, 0];\n\t\t}\n\t\treturn [1, 1, 1, iterWeight, dcfr ? 0 : 1];\n\t};\n\n\t// Threads: workers over the same memory, each with its own header.\n\tlet control: Int32Array | null = null;\n\tlet settings: Float64Array | null = null;\n\tconst workers: { terminate(): void }[] = [];\n\tlet failure: Error | null = null;\n\tif (pool) {\n\t\tconst plan = pool.plan;\n\t\tconst controlBuffer = new SharedArrayBuffer(ENGINE_CONTROL.size * 4);\n\t\tconst settingsBuffer = new SharedArrayBuffer(8 * 8);\n\t\tcontrol = new Int32Array(controlBuffer);\n\t\tsettings = new Float64Array(settingsBuffer);\n\t\texports.setExchange(offsets[entryIndexOf], offsets[reach], offsets[values], stride);\n\t\tfor (let w = 1; w < threads; w++) {\n\t\t\tconst setup: EngineWorkerSetup = {\n\t\t\t\tmemory, module: compiledModule, header: offsets[own[w].header], maxActions,\n\t\t\t\texchange: [offsets[entryIndexOf], offsets[reach], offsets[values], stride],\n\t\t\t\tshard: [plan.round, plan.bounds[w], plan.bounds[w + 1]],\n\t\t\t\tentryNodes: plan.entryNodes,\n\t\t\t\trootMe: offsets[own[w].rootMe], rootOpp: offsets[own[w].rootOpp],\n\t\t\t\tpartial: offsets[partials] + (w - 1) * entries * rowBytes,\n\t\t\t\tstride, control: controlBuffer, settings: settingsBuffer,\n\t\t\t};\n\t\t\tworkers.push(pool.spawn(setup, (error) => {\n\t\t\t\tfailure ??= error;\n\t\t\t\tAtomics.store(control!, ENGINE_CONTROL.ready, threads);\n\t\t\t\tAtomics.add(control!, ENGINE_CONTROL.done, threads);\n\t\t\t\tAtomics.notify(control!, ENGINE_CONTROL.done);\n\t\t\t\tAtomics.notify(control!, ENGINE_CONTROL.ready);\n\t\t\t}));\n\t\t}\n\t\t// A worker that fails to start reports it by an event, which cannot\n\t\t// be delivered while this thread waits here, so the wait is bounded.\n\t\tconst deadline = Date.now() + WORKER_START_MS;\n\t\tfor (;;) {\n\t\t\tconst ready = Atomics.load(control, ENGINE_CONTROL.ready);\n\t\t\tif (ready >= threads - 1 || failure) break;\n\t\t\tif (Date.now() > deadline) failure = new Error(WORKER_START_ERROR);\n\t\t\telse Atomics.wait(control, ENGINE_CONTROL.ready, ready, 20);\n\t\t}\n\t\tif (failure) {\n\t\t\tfor (const worker of workers) worker.terminate();\n\t\t\tthrow failure;\n\t\t}\n\t}\n\n\tconst run = (mode: number, traverser: 0 | 1, iterWeight: number, dcfr: boolean): Float64Array => {\n\t\tfor (const player of [0, 1] as const) {\n\t\t\tconst [from, count] = rootList(player);\n\t\t\tconst into = player === traverser ? me : opp;\n\t\t\tconst weights = input.players[player].weights;\n\t\t\tfor (let i = 0; i < count; i++) into[i] = weights[active.list[from + i]];\n\t\t}\n\t\tconst [positive, negative, sum, weight, clamp] = settingsFor(mode, iterWeight, dcfr);\n\t\tlet at: number;\n\t\tif (!pool) {\n\t\t\tat = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp);\n\t\t} else {\n\t\t\tconst plan = pool.plan;\n\t\t\t// Collect: walk above the split, recording what the workers need.\n\t\t\texports.setShard(plan.round, 0, 0);\n\t\t\texports.setPhase(1, 0);\n\t\t\texports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp);\n\t\t\t// Every thread walks its slice of the split round.\n\t\t\tsettings!.set([positive, negative, sum, weight, clamp]);\n\t\t\tAtomics.store(control!, ENGINE_CONTROL.done, 0);\n\t\t\tAtomics.store(control!, ENGINE_CONTROL.mode, mode);\n\t\t\tAtomics.store(control!, ENGINE_CONTROL.traverser, traverser);\n\t\t\tAtomics.store(control!, ENGINE_CONTROL.command, 0);\n\t\t\tAtomics.add(control!, ENGINE_CONTROL.generation, 1);\n\t\t\tAtomics.notify(control!, ENGINE_CONTROL.generation);\n\t\t\texports.setShard(plan.round, plan.bounds[0], plan.bounds[1]);\n\t\t\texports.setPhase(0, 1);\n\t\t\tconst valueView = new Float32Array(memory.buffer, offsets[values], entries * stride);\n\t\t\tfor (let entry = 0; entry < entries; entry++) {\n\t\t\t\tconst slot = offsets[reach] + entry * 2 * rowBytes;\n\t\t\t\tconst out = exports.runChance(mode, traverser, plan.entryNodes[entry], slot, slot + rowBytes, positive, negative, sum, weight, clamp);\n\t\t\t\tvalueView.set(new Float32Array(memory.buffer, out, stride), entry * stride);\n\t\t\t}\n\t\t\tfor (;;) {\n\t\t\t\tconst done = Atomics.load(control!, ENGINE_CONTROL.done);\n\t\t\t\tif (done >= threads - 1 || failure) break;\n\t\t\t\tAtomics.wait(control!, ENGINE_CONTROL.done, done, 50);\n\t\t\t}\n\t\t\tif (failure) throw failure;\n\t\t\tconst partialView = new Float32Array(memory.buffer, offsets[partials], (threads - 1) * entries * stride);\n\t\t\tfor (let w = 0; w < threads - 1; w++) {\n\t\t\t\tfor (let i = 0; i < entries * stride; i++) valueView[i] += partialView[w * entries * stride + i];\n\t\t\t}\n\t\t\t// Finish above the split from the totals, now applying updates.\n\t\t\texports.setShard(plan.round, 0, 0);\n\t\t\texports.setPhase(2, 1);\n\t\t\tat = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp);\n\t\t\texports.setPhase(0, 1);\n\t\t\texports.setShard(-1, 0, 0);\n\t\t}\n\t\tconst [, count] = rootList(traverser);\n\t\tconst values32 = new Float32Array(memory.buffer, at, count);\n\t\tfor (let i = 0; i < count; i++) result[i] = values32[i];\n\t\treturn result;\n\t};\n\n\treturn {\n\t\tregret,\n\t\tstrategySum,\n\t\tthreads,\n\t\troot(dcfr) {\n\t\t\treturn (mode, traverser, iterWeight) => run(mode, traverser, iterWeight, dcfr);\n\t\t},\n\t\tclose() {\n\t\t\tif (!control) return;\n\t\t\tAtomics.store(control, ENGINE_CONTROL.command, 1);\n\t\t\tAtomics.add(control, ENGINE_CONTROL.generation, 1);\n\t\t\tAtomics.notify(control, ENGINE_CONTROL.generation);\n\t\t\tfor (const worker of workers) worker.terminate();\n\t\t},\n\t};\n}\n\n/** The engine's exports. */\nexport interface EngineExports {\n\tinit(header: number): void;\n\tsetMaxActions(count: number): void;\n\tsetShard(round: number, start: number, end: number): void;\n\tsetExchange(entries: number, reach: number, values: number, stride: number): void;\n\tsetPhase(phase: number, apply: number): void;\n\trun(mode: number, traverser: number, me: number, opp: number, positive: number, negative: number, sum: number, weight: number, clamp: number): number;\n\trunChance(mode: number, traverser: number, node: number, me: number, opp: number, positive: number, negative: number, sum: number, weight: number, clamp: number): number;\n}\n"],"mappings":";AAWA,SAAS,YAAY,kBAAkB;;;ACsBvC,IAAM,OAAQ,WAAoD;AA0E3D,IAAM,iBAAiB,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,WAAW,GAAG,OAAO,GAAG,MAAM,EAAE;;;AD5F7G,IAAM,QAAQ;AACd,IAAM,EAAE,aAAaA,MAAK,IAAI;AAG9B,IAAM,SAAS,MAAM;AACrB,IAAM,WAAW,IAAIA,MAAK,SAAS,MAAM,QAAQ,EAAE,KAAK,EAAE,QAAQ,OAAO,MAAM;AAAE,QAAM,IAAI,MAAM,cAAc;AAAG,EAAE,EAAE,CAAC;AACvH,IAAM,SAAS,SAAS;AACxB,OAAO,KAAK,MAAM,MAAM;AACxB,OAAO,cAAc,MAAM,UAAU;AACrC,OAAO,YAAY,GAAG,MAAM,QAAQ;AACpC,OAAO,SAAS,GAAG,MAAM,KAAK;AAC9B,OAAO,SAAS,GAAG,CAAC;AAEpB,IAAM,UAAU,IAAI,WAAW,MAAM,OAAO;AAC5C,IAAM,WAAW,IAAI,aAAa,MAAM,QAAQ;AAChD,IAAM,UAAU,MAAM,WAAW;AACjC,IAAM,WAAW,MAAM,SAAS;AAChC,IAAM,WAAW,IAAI,aAAa,OAAO,QAAQ,MAAM,SAAS,UAAU,MAAM,MAAM;AACtF,IAAM,CAAC,EAAE,KAAK,IAAI,MAAM;AAGxB,IAAI,aAAa,QAAQ,KAAK,SAAS,eAAe,UAAU;AAChE,QAAQ,IAAI,SAAS,eAAe,OAAO,CAAC;AAC5C,QAAQ,OAAO,SAAS,eAAe,KAAK;AAE5C,WAAS;AACR,UAAQ,KAAK,SAAS,eAAe,YAAY,UAAU;AAC3D,eAAa,QAAQ,KAAK,SAAS,eAAe,UAAU;AAC5D,MAAI,QAAQ,KAAK,SAAS,eAAe,OAAO,MAAM,EAAG;AACzD,QAAM,OAAO,QAAQ,KAAK,SAAS,eAAe,IAAI;AACtD,QAAM,YAAY,QAAQ,KAAK,SAAS,eAAe,SAAS;AAChE,QAAM,CAAC,UAAU,UAAU,KAAK,QAAQ,KAAK,IAAI;AACjD,WAAS,QAAQ,GAAG,QAAQ,SAAS,SAAS;AAC7C,UAAM,OAAO,QAAQ,QAAQ,IAAI;AACjC,UAAM,MAAM,OAAO;AAAA,MAClB;AAAA,MAAM;AAAA,MAAW,MAAM,WAAW,KAAK;AAAA,MAAG;AAAA,MAAM,OAAO;AAAA,MAAU;AAAA,MAAU;AAAA,MAAU;AAAA,MAAK;AAAA,MAAQ;AAAA,IACnG;AACA,aAAS,IAAI,IAAI,aAAa,OAAO,QAAQ,KAAK,MAAM,MAAM,GAAG,QAAQ,MAAM,MAAM;AAAA,EACtF;AACA,UAAQ,IAAI,SAAS,eAAe,MAAM,CAAC;AAC3C,UAAQ,OAAO,SAAS,eAAe,IAAI;AAC5C;AAEA,YAAY,MAAM;","names":["wasm"]}
|
|
1
|
+
{"version":3,"sources":["../src/engine-worker.ts","../src/engine-thread.ts"],"sourcesContent":["/**\n * An engine worker in Node: one thread of a WebAssembly solve.\n *\n * Purpose: start `serveEngine` (src/engine-thread.ts) on the setup the main\n * thread passed, and let the thread end once it returns.\n */\n\nimport { parentPort, workerData } from 'node:worker_threads';\nimport type { EngineWorkerSetup } from './engine.ts';\nimport { serveEngine } from './engine-thread.ts';\n\nserveEngine(workerData as EngineWorkerSetup);\nparentPort?.close();\n","/**\n * One thread of a WebAssembly solve: the loop every engine worker runs.\n *\n * Purpose: walk this thread's slice of the runouts at the split round, over\n * the memory every thread shares, each time the main thread signals, until it\n * says exit. The protocol is src/parallel.ts's: the main thread collects the\n * reach each entry needs, every thread walks its slice from each entry, the\n * main thread adds the slices up and finishes. All of it happens in shared\n * WebAssembly memory, so nothing is copied between threads but a few numbers\n * of control.\n *\n * Node runs it from `engine-worker.ts`. The browser build has no file to\n * start a worker from, so `platform/browser.ts` ships this function as its\n * own source text (`Function.prototype.toString`) inside a Blob worker. That\n * is why it must stay self-contained: no imports, no reference to anything\n * outside its body, no nested named functions (a bundler may wrap those in a\n * helper the worker would not have). The control slots are written out as\n * numbers for the same reason; a test pins them to `ENGINE_CONTROL`.\n */\n\nimport type { EngineWorkerSetup } from './engine.ts';\n\n/**\n * Serve one solve, returning once the main thread sends exit.\n * @param setup what `createEngine` hands each worker\n */\nexport function serveEngine(setup: EngineWorkerSetup): void {\n\t// ENGINE_CONTROL, inlined.\n\tconst GENERATION = 0;\n\tconst DONE = 1;\n\tconst COMMAND = 2;\n\tconst MODE = 3;\n\tconst TRAVERSER = 4;\n\tconst READY = 5;\n\tconst FAILED = 6;\n\tconst EXIT = 1;\n\n\tconst api = (globalThis as unknown as {\n\t\tWebAssembly: { Instance: new (module: unknown, imports: object) => { exports: Record<string, unknown> } };\n\t}).WebAssembly;\n\tconst memory = setup.memory as { buffer: SharedArrayBuffer };\n\tconst imports = {\n\t\tenv: {\n\t\t\tmemory,\n\t\t\tabort(): never {\n\t\t\t\tthrow new Error('engine abort');\n\t\t\t},\n\t\t},\n\t};\n\tconst engine = new api.Instance(setup.module, imports).exports as unknown as {\n\t\tinit(header: number): void;\n\t\tsetMaxActions(count: number): void;\n\t\tsetShard(round: number, start: number, end: number): void;\n\t\tsetExchange(entries: number, reach: number, values: number, stride: number): void;\n\t\tsetPhase(phase: number, apply: number): void;\n\t\tsetShared(marks: number, blockOffsets: number, weighted: number): void;\n\t\tsetSampling(\n\t\t\trounds: number, p: number, every: number, unbiased: number, catchUp: number,\n\t\t\tbaseOffsets: number, boardOffsets: number, walkOffsets: number,\n\t\t\tbaselines: number, lastWalks: number, lastUpdates: number, blockOffsets: number,\n\t\t): void;\n\t\tsetIteration(t: number, dcfr: number): void;\n\t\trunChance(\n\t\t\tmode: number, traverser: number, node: number, me: number, opp: number,\n\t\t\tpositive: number, negative: number, sum: number, weight: number, clamp: number,\n\t\t): number;\n\t};\n\tengine.init(setup.header);\n\tengine.setMaxActions(setup.maxActions);\n\tengine.setExchange(setup.exchange[0], setup.exchange[1], setup.exchange[2], setup.exchange[3]);\n\tengine.setShard(setup.shard[0], setup.shard[1], setup.shard[2]);\n\tengine.setPhase(0, 1);\n\tconst shared = setup.shared;\n\tif (shared) engine.setShared(shared[0], shared[1], shared[2]);\n\t// Chance sampling's state is in the shared memory, at the main thread's offsets.\n\tconst s = setup.sampling;\n\tif (s) engine.setSampling(s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], s[11]);\n\t// Shared storage discounts by iteration, the storage engine's rounding\n\t// hashes it, and chance sampling picks deals and catches up by it.\n\tconst needsIteration = shared !== undefined || setup.storage === true || s !== undefined;\n\n\tconst control = new Int32Array(setup.control);\n\tconst settings = new Float64Array(setup.settings);\n\tconst entries = setup.entryNodes.length;\n\tconst rowBytes = setup.stride * 4;\n\tconst partials = new Float32Array(memory.buffer, setup.partial, entries * setup.stride);\n\tconst reach = setup.exchange[1];\n\n\t// Latch the generation before announcing readiness, so no dispatch is missed.\n\tlet generation = Atomics.load(control, GENERATION);\n\tAtomics.add(control, READY, 1);\n\tAtomics.notify(control, READY);\n\t// A solve that gave up before this thread started has already said exit.\n\tif (Atomics.load(control, COMMAND) === EXIT) return;\n\n\tfor (;;) {\n\t\tAtomics.wait(control, GENERATION, generation);\n\t\tgeneration = Atomics.load(control, GENERATION);\n\t\tif (Atomics.load(control, COMMAND) === EXIT) return;\n\t\tconst mode = Atomics.load(control, MODE);\n\t\tconst traverser = Atomics.load(control, TRAVERSER);\n\t\tconst positive = settings[0];\n\t\tconst negative = settings[1];\n\t\tconst sum = settings[2];\n\t\tconst weight = settings[3];\n\t\tconst clamp = settings[4];\n\t\ttry {\n\t\t\t// Off for a current-profile read, which updates nothing.\n\t\t\tengine.setPhase(0, settings[5]);\n\t\t\tif (needsIteration) engine.setIteration(settings[6], settings[7]);\n\t\t\tfor (let entry = 0; entry < entries; entry++) {\n\t\t\t\tconst slot = reach + entry * 2 * rowBytes;\n\t\t\t\tconst out = engine.runChance(\n\t\t\t\t\tmode, traverser, setup.entryNodes[entry], slot, slot + rowBytes, positive, negative, sum, weight, clamp,\n\t\t\t\t) >>> 0; // a usize, signed on its way out; see `EngineExports`\n\t\t\t\tpartials.set(new Float32Array(memory.buffer, out, setup.stride), entry * setup.stride);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// The main thread is blocked in Atomics.wait and cannot see this\n\t\t\t// thread's error event, so say so in shared memory (and count as\n\t\t\t// done, below). Then let the thread die: its engine is not to be trusted.\n\t\t\tAtomics.store(control, FAILED, 1);\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tAtomics.add(control, DONE, 1);\n\t\t\tAtomics.notify(control, DONE);\n\t\t}\n\t}\n}\n"],"mappings":"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","names":[]}
|