poker-flopsolve 0.3.0 → 0.3.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.
@@ -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';\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\tfor (;;) {\n\t\t\tconst ready = Atomics.load(control, ENGINE_CONTROL.ready);\n\t\t\tif (ready >= threads - 1 || failure) break;\n\t\t\tAtomics.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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,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.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,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AYAd/f39/f3x/AGADf
2084
2084
  // src/wasm/engine-shared.ts
2085
2085
  var ENGINE_SHARED_WASM = "AGFzbQEAAAABTglgAX8AYAZ/f39/f38Bf2AFf39/f38AYAd/f39/f3x/AGADf39/AGACf38AYAR/f39/AGAKf39/f399fX19fwF/YAl/f39/fX19fX8BfwISAQNlbnYGbWVtb3J5AgMAgIAEAwsKAQIDBAUABgcIAAaOAjJ/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt8AUQAAAAAAADwPwt/AUF/C38BQQALfwFBAAt/AUEAC38BQQELfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC30BQwAAgD8LfQFDAAAAAAt9AUMAAIA/C30BQwAAgD8LfwFBAAt/AUEBCwdXCAhzZXRTaGFyZAADC3NldEV4Y2hhbmdlAAYIc2V0UGhhc2UABARpbml0AAkNc2V0TWF4QWN0aW9ucwAFA3J1bgAICXJ1bkNoYW5jZQAHBm1lbW9yeQIACqshCuIYBBV/An0FewN8Ix0gBSMebGohDSACIwkjASABai0AACIHQQJ0aigCAGpBAXQiCCAAaiIPQQJ0IgkjCmooAgAhCiMLIAlqKAIAIQtBASAAayIQIAhqIghBAnQiESMKaigCACESIwsgEWooAgAhESMAIAFqLQAAIhNBAkYEQCMUIAlqKAIAIQIjBiABQQJ0aigCALciIpogIiAAQQFGGyMaIAdBA3RqKwMAoiMhoyEkQQAhAANAIAAgEUgEQCAjIAQgAEECdGoqAgC7IiKgISMjICAAIBJqIgEjDGotAABBA3RqIgMgAysDACAioDkDACMgIw0gAWotAABBA3RqIgEgASsDACAioDkDACAAQQFqIQAMAQsLQQAhAANAIAAgC0gEQCANIABBAnRqICQgIyM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AEEDdGorAwCgoTkDACAIQQFqIQgMAQsLIyBBAEGgA/wLAEQAAAAAAAAAACENIAJBAWshByAEQQFrIQIDQCACQQBOBEAjDiACIANqQQJ0aigCACEEA0AgB0EATgR/Iw4gASAHakECdGooAgAgBEoFQQALBEAgDSAAIAdBAnRqKgIAuyIOoCENIyAgASAHaiIIIwxqLQAAQQN0aiIKIAorAwAgDqA5AwAjICMNIAhqLQAAQQN0aiIIIAgrAwAgDqA5AwAgB0EBayEHDAELCyAGIAJBAnRqIAUgCSACQQN0aisDACANIyAgAiADaiIEIwxqLQAAQQN0aisDACMgIw0gBGotAABBA3RqKwMAoKGhorY4AgAgAkEBayECDAELCyMgQQBBoAP8CwALDgAgACQiIAEkIyACJCQLDQAgACQlIAFBAEckJgsGACAAJDELFQAgACQnIAEkKCACJCkgA0ECdCQqCysAIAAkKyAFJCwgBiQtIAckLiAIJC8gCUEARyQwIAEgAkEAIAMgBEEAEAALKwAgACQrIAQkLCAFJC0gBiQuIAckLyAIQQBHJDAgAUEAQQAgAiADQQAQAAv2AQAgACgCACQAIAAoAgQkASAAKAIIJAIgACgCDCQDIAAoAhAkBCAAKAIUJAUgACgCGCQGIAAoAhwkByAAKAIgJAggACgCJCQJIAAoAigkCiAAKAIsJAsgACgCMCQMIAAoAjQkDSAAKAI4JA4gACgCPCQPIABBQGsoAgAkECAAKAJEJBEgACgCSCQSIAAoAkwkEyAAKAJQJBQgACgCVCQVIAAoAlgkFiAAKAJcJBcgACgCYCQYIAAoAmQkGSAAKAJoJBogACgCbCQbIAAoAnAkHCAAKAJ0JB0gACgCeCQeIAAoAnwkHyAAKAKAASQgIAAoAoQBuCQhCw==";
2086
2086
 
2087
+ // src/platform/node.ts
2088
+ import { availableParallelism } from "os";
2089
+ import { fileURLToPath } from "url";
2090
+ import { Worker } from "worker_threads";
2091
+ var PLATFORM = "node";
2092
+ var THREADS_AVAILABLE = true;
2093
+ var DEFAULT_MAX_BYTES = 6 * 1024 * 1024 * 1024;
2094
+ function workerFlags() {
2095
+ return process.execArgv.filter((flag) => !flag.startsWith("--input-type"));
2096
+ }
2097
+ function defaultWorkerCount() {
2098
+ const cores = availableParallelism();
2099
+ return cores < 2 ? 1 : Math.max(2, cores - 1);
2100
+ }
2101
+ function spawnWorker(setup, onError) {
2102
+ const url = new URL(import.meta.url.endsWith(".ts") ? "../worker.ts" : "./worker.js", import.meta.url);
2103
+ const thread = new Worker(fileURLToPath(url), { workerData: setup, execArgv: workerFlags() });
2104
+ thread.on("error", onError);
2105
+ thread.unref();
2106
+ return {
2107
+ terminate() {
2108
+ void thread.terminate();
2109
+ }
2110
+ };
2111
+ }
2112
+ function spawnEngineWorker(setup, onError) {
2113
+ const url = new URL(import.meta.url.endsWith(".ts") ? "../engine-worker.ts" : "./engine-worker.js", import.meta.url);
2114
+ const thread = new Worker(fileURLToPath(url), { workerData: setup, execArgv: workerFlags() });
2115
+ thread.on("error", onError);
2116
+ thread.unref();
2117
+ return {
2118
+ terminate() {
2119
+ void thread.terminate();
2120
+ }
2121
+ };
2122
+ }
2123
+
2124
+ // src/parallel.ts
2125
+ var CONTROL = {
2126
+ generation: 0,
2127
+ done: 1,
2128
+ command: 2,
2129
+ traverser: 3,
2130
+ iterWeight: 4,
2131
+ ready: 5,
2132
+ mode: 6,
2133
+ size: 8
2134
+ };
2135
+ var COMMAND = { work: 0, exit: 1 };
2136
+ var WORKER_START_MS = 3e4;
2137
+ var WORKER_START_ERROR = "Worker threads did not start within 30 s. Run with workers: 1, or check that worker threads can load this package.";
2138
+ function planShards(tree, runouts, workers) {
2139
+ if (workers < 2) return null;
2140
+ let round = -1;
2141
+ for (let r = 1; r < runouts.rounds; r++) {
2142
+ if (runouts.counts[r] > 1) {
2143
+ round = r;
2144
+ break;
2145
+ }
2146
+ }
2147
+ if (round < 0) return null;
2148
+ const boards = runouts.counts[round];
2149
+ if (boards < workers * 2) return null;
2150
+ const entryIndexOf = new Int32Array(tree.nodeCount).fill(-1);
2151
+ const entryNodes = [];
2152
+ for (let node = 0; node < tree.nodeCount; node++) {
2153
+ if (tree.kind[node] !== NodeKind.Chance) continue;
2154
+ if (tree.round[node] + 1 !== round) continue;
2155
+ entryIndexOf[node] = entryNodes.length;
2156
+ entryNodes.push(node);
2157
+ }
2158
+ if (entryNodes.length === 0) return null;
2159
+ const bounds = new Int32Array(workers + 1);
2160
+ for (let w = 0; w <= workers; w++) bounds[w] = Math.round(boards * w / workers);
2161
+ return { round, boards, entryNodes: Int32Array.from(entryNodes), entryIndexOf, bounds };
2162
+ }
2163
+ function startPool(ctx, solver, plan, payload, workers) {
2164
+ const entryCount = plan.entryNodes.length;
2165
+ const spawned = workers - 1;
2166
+ const reachFloats = entryCount * 2 * COMBOS;
2167
+ const partialFloats = spawned * entryCount * COMBOS;
2168
+ const exchangeBuffer = new SharedArrayBuffer((reachFloats + partialFloats) * 8);
2169
+ const exchange = new Float64Array(exchangeBuffer);
2170
+ const controlBuffer = new SharedArrayBuffer(CONTROL.size * 4);
2171
+ const control = new Int32Array(controlBuffer);
2172
+ const threads = [];
2173
+ let failure = null;
2174
+ for (let w = 0; w < spawned; w++) {
2175
+ const setup = {
2176
+ workerId: w,
2177
+ payload,
2178
+ plan: { round: plan.round, entryNodes: plan.entryNodes, entryIndexOf: plan.entryIndexOf },
2179
+ shardStart: plan.bounds[w + 1],
2180
+ shardEnd: plan.bounds[w + 2],
2181
+ regret: ctx.regret.buffer,
2182
+ strategySum: ctx.strategySum.buffer,
2183
+ regretScale: ctx.regretScale?.buffer ?? null,
2184
+ sumScale: ctx.sumScale?.buffer ?? null,
2185
+ control: controlBuffer,
2186
+ exchange: exchangeBuffer,
2187
+ entryCount
2188
+ };
2189
+ const thread = spawnWorker(setup, (error) => {
2190
+ failure ??= error;
2191
+ Atomics.store(control, CONTROL.ready, spawned);
2192
+ Atomics.add(control, CONTROL.done, spawned);
2193
+ Atomics.notify(control, CONTROL.done);
2194
+ Atomics.notify(control, CONTROL.ready);
2195
+ });
2196
+ threads.push(thread);
2197
+ }
2198
+ const deadline = Date.now() + WORKER_START_MS;
2199
+ for (; ; ) {
2200
+ const ready = Atomics.load(control, CONTROL.ready);
2201
+ if (ready >= spawned || failure) break;
2202
+ if (Date.now() > deadline) failure = new Error(WORKER_START_ERROR);
2203
+ else Atomics.wait(control, CONTROL.ready, ready, 20);
2204
+ }
2205
+ if (failure) {
2206
+ for (const thread of threads) thread.terminate();
2207
+ throw failure;
2208
+ }
2209
+ const total = new Float64Array(COMBOS);
2210
+ const chanceValues = new Float64Array(entryCount * COMBOS);
2211
+ const mainReachMe = new Float64Array(COMBOS);
2212
+ const mainReachOpp = new Float64Array(COMBOS);
2213
+ const dispatch = (mode, traverser, iterWeight) => {
2214
+ Atomics.store(control, CONTROL.done, 0);
2215
+ Atomics.store(control, CONTROL.mode, mode);
2216
+ Atomics.store(control, CONTROL.traverser, traverser);
2217
+ Atomics.store(control, CONTROL.iterWeight, iterWeight);
2218
+ Atomics.store(control, CONTROL.command, COMMAND.work);
2219
+ Atomics.add(control, CONTROL.generation, 1);
2220
+ Atomics.notify(control, CONTROL.generation);
2221
+ const fullStart = ctx.shardStart;
2222
+ const fullEnd = ctx.shardEnd;
2223
+ ctx.shardStart = plan.bounds[0];
2224
+ ctx.shardEnd = plan.bounds[1];
2225
+ ctx.applyUpdates = true;
2226
+ try {
2227
+ for (let entry = 0; entry < entryCount; entry++) {
2228
+ for (let i = 0; i < COMBOS; i++) {
2229
+ mainReachMe[i] = exchange[entry * 2 * COMBOS + i];
2230
+ mainReachOpp[i] = exchange[entry * 2 * COMBOS + COMBOS + i];
2231
+ }
2232
+ const value = solver.traverseChance(
2233
+ mode,
2234
+ traverser,
2235
+ iterWeight,
2236
+ plan.entryNodes[entry],
2237
+ mainReachMe,
2238
+ mainReachOpp
2239
+ );
2240
+ chanceValues.set(value.subarray(0, COMBOS), entry * COMBOS);
2241
+ }
2242
+ } finally {
2243
+ ctx.shardStart = fullStart;
2244
+ ctx.shardEnd = fullEnd;
2245
+ }
2246
+ for (; ; ) {
2247
+ const done = Atomics.load(control, CONTROL.done);
2248
+ if (done >= spawned) break;
2249
+ if (failure) throw failure;
2250
+ Atomics.wait(control, CONTROL.done, done, 50);
2251
+ }
2252
+ if (failure) throw failure;
2253
+ };
2254
+ return {
2255
+ workers,
2256
+ traverse(mode, traverser, iterWeight) {
2257
+ ctx.applyUpdates = false;
2258
+ ctx.chanceOverride = null;
2259
+ ctx.chanceCollect = (node, reachMe, reachOpp) => {
2260
+ const entry = plan.entryIndexOf[node];
2261
+ exchange.set(reachMe.subarray(0, COMBOS), entry * 2 * COMBOS);
2262
+ exchange.set(reachOpp.subarray(0, COMBOS), entry * 2 * COMBOS + COMBOS);
2263
+ };
2264
+ try {
2265
+ solver.traverseRoot(mode, traverser, iterWeight);
2266
+ } finally {
2267
+ ctx.chanceCollect = null;
2268
+ }
2269
+ dispatch(mode, traverser, iterWeight);
2270
+ for (let w = 0; w < spawned; w++) {
2271
+ const base = reachFloats + w * entryCount * COMBOS;
2272
+ for (let i = 0; i < entryCount * COMBOS; i++) chanceValues[i] += exchange[base + i];
2273
+ }
2274
+ ctx.chanceOverride = chanceValues;
2275
+ ctx.applyUpdates = true;
2276
+ try {
2277
+ const value = solver.traverseRoot(mode, traverser, iterWeight);
2278
+ total.set(value.subarray(0, COMBOS));
2279
+ } finally {
2280
+ ctx.chanceOverride = null;
2281
+ }
2282
+ return total;
2283
+ },
2284
+ close() {
2285
+ Atomics.store(control, CONTROL.command, COMMAND.exit);
2286
+ Atomics.add(control, CONTROL.generation, 1);
2287
+ Atomics.notify(control, CONTROL.generation);
2288
+ for (const thread of threads) thread.terminate();
2289
+ }
2290
+ };
2291
+ }
2292
+
2087
2293
  // src/engine.ts
2088
2294
  var wasm2 = globalThis.WebAssembly;
2089
2295
  var modules = { plain: void 0, shared: void 0 };
@@ -2255,10 +2461,12 @@ function createEngine(input, pool) {
2255
2461
  Atomics.notify(control, ENGINE_CONTROL.ready);
2256
2462
  }));
2257
2463
  }
2464
+ const deadline = Date.now() + WORKER_START_MS;
2258
2465
  for (; ; ) {
2259
2466
  const ready = Atomics.load(control, ENGINE_CONTROL.ready);
2260
2467
  if (ready >= threads - 1 || failure) break;
2261
- Atomics.wait(control, ENGINE_CONTROL.ready, ready, 20);
2468
+ if (Date.now() > deadline) failure = new Error(WORKER_START_ERROR);
2469
+ else Atomics.wait(control, ENGINE_CONTROL.ready, ready, 20);
2262
2470
  }
2263
2471
  if (failure) {
2264
2472
  for (const worker of workers) worker.terminate();
@@ -2464,205 +2672,6 @@ function warmStart(to, from, averages) {
2464
2672
  return { matchedNodes: matched, decisionNodes: tree.decisionNodes.length, averages };
2465
2673
  }
2466
2674
 
2467
- // src/platform/node.ts
2468
- import { availableParallelism } from "os";
2469
- import { fileURLToPath } from "url";
2470
- import { Worker } from "worker_threads";
2471
- var PLATFORM = "node";
2472
- var THREADS_AVAILABLE = true;
2473
- var DEFAULT_MAX_BYTES = 6 * 1024 * 1024 * 1024;
2474
- function defaultWorkerCount() {
2475
- const cores = availableParallelism();
2476
- return cores < 2 ? 1 : Math.max(2, cores - 1);
2477
- }
2478
- function spawnWorker(setup, onError) {
2479
- const url = new URL(import.meta.url.endsWith(".ts") ? "../worker.ts" : "./worker.js", import.meta.url);
2480
- const thread = new Worker(fileURLToPath(url), { workerData: setup });
2481
- thread.on("error", onError);
2482
- thread.unref();
2483
- return {
2484
- terminate() {
2485
- void thread.terminate();
2486
- }
2487
- };
2488
- }
2489
- function spawnEngineWorker(setup, onError) {
2490
- const url = new URL(import.meta.url.endsWith(".ts") ? "../engine-worker.ts" : "./engine-worker.js", import.meta.url);
2491
- const thread = new Worker(fileURLToPath(url), { workerData: setup });
2492
- thread.on("error", onError);
2493
- thread.unref();
2494
- return {
2495
- terminate() {
2496
- void thread.terminate();
2497
- }
2498
- };
2499
- }
2500
-
2501
- // src/parallel.ts
2502
- var CONTROL = {
2503
- generation: 0,
2504
- done: 1,
2505
- command: 2,
2506
- traverser: 3,
2507
- iterWeight: 4,
2508
- ready: 5,
2509
- mode: 6,
2510
- size: 8
2511
- };
2512
- var COMMAND = { work: 0, exit: 1 };
2513
- function planShards(tree, runouts, workers) {
2514
- if (workers < 2) return null;
2515
- let round = -1;
2516
- for (let r = 1; r < runouts.rounds; r++) {
2517
- if (runouts.counts[r] > 1) {
2518
- round = r;
2519
- break;
2520
- }
2521
- }
2522
- if (round < 0) return null;
2523
- const boards = runouts.counts[round];
2524
- if (boards < workers * 2) return null;
2525
- const entryIndexOf = new Int32Array(tree.nodeCount).fill(-1);
2526
- const entryNodes = [];
2527
- for (let node = 0; node < tree.nodeCount; node++) {
2528
- if (tree.kind[node] !== NodeKind.Chance) continue;
2529
- if (tree.round[node] + 1 !== round) continue;
2530
- entryIndexOf[node] = entryNodes.length;
2531
- entryNodes.push(node);
2532
- }
2533
- if (entryNodes.length === 0) return null;
2534
- const bounds = new Int32Array(workers + 1);
2535
- for (let w = 0; w <= workers; w++) bounds[w] = Math.round(boards * w / workers);
2536
- return { round, boards, entryNodes: Int32Array.from(entryNodes), entryIndexOf, bounds };
2537
- }
2538
- function startPool(ctx, solver, plan, payload, workers) {
2539
- const entryCount = plan.entryNodes.length;
2540
- const spawned = workers - 1;
2541
- const reachFloats = entryCount * 2 * COMBOS;
2542
- const partialFloats = spawned * entryCount * COMBOS;
2543
- const exchangeBuffer = new SharedArrayBuffer((reachFloats + partialFloats) * 8);
2544
- const exchange = new Float64Array(exchangeBuffer);
2545
- const controlBuffer = new SharedArrayBuffer(CONTROL.size * 4);
2546
- const control = new Int32Array(controlBuffer);
2547
- const threads = [];
2548
- let failure = null;
2549
- for (let w = 0; w < spawned; w++) {
2550
- const setup = {
2551
- workerId: w,
2552
- payload,
2553
- plan: { round: plan.round, entryNodes: plan.entryNodes, entryIndexOf: plan.entryIndexOf },
2554
- shardStart: plan.bounds[w + 1],
2555
- shardEnd: plan.bounds[w + 2],
2556
- regret: ctx.regret.buffer,
2557
- strategySum: ctx.strategySum.buffer,
2558
- regretScale: ctx.regretScale?.buffer ?? null,
2559
- sumScale: ctx.sumScale?.buffer ?? null,
2560
- control: controlBuffer,
2561
- exchange: exchangeBuffer,
2562
- entryCount
2563
- };
2564
- const thread = spawnWorker(setup, (error) => {
2565
- failure ??= error;
2566
- Atomics.store(control, CONTROL.ready, spawned);
2567
- Atomics.add(control, CONTROL.done, spawned);
2568
- Atomics.notify(control, CONTROL.done);
2569
- Atomics.notify(control, CONTROL.ready);
2570
- });
2571
- threads.push(thread);
2572
- }
2573
- for (; ; ) {
2574
- const ready = Atomics.load(control, CONTROL.ready);
2575
- if (ready >= spawned || failure) break;
2576
- Atomics.wait(control, CONTROL.ready, ready, 20);
2577
- }
2578
- if (failure) {
2579
- for (const thread of threads) thread.terminate();
2580
- throw failure;
2581
- }
2582
- const total = new Float64Array(COMBOS);
2583
- const chanceValues = new Float64Array(entryCount * COMBOS);
2584
- const mainReachMe = new Float64Array(COMBOS);
2585
- const mainReachOpp = new Float64Array(COMBOS);
2586
- const dispatch = (mode, traverser, iterWeight) => {
2587
- Atomics.store(control, CONTROL.done, 0);
2588
- Atomics.store(control, CONTROL.mode, mode);
2589
- Atomics.store(control, CONTROL.traverser, traverser);
2590
- Atomics.store(control, CONTROL.iterWeight, iterWeight);
2591
- Atomics.store(control, CONTROL.command, COMMAND.work);
2592
- Atomics.add(control, CONTROL.generation, 1);
2593
- Atomics.notify(control, CONTROL.generation);
2594
- const fullStart = ctx.shardStart;
2595
- const fullEnd = ctx.shardEnd;
2596
- ctx.shardStart = plan.bounds[0];
2597
- ctx.shardEnd = plan.bounds[1];
2598
- ctx.applyUpdates = true;
2599
- try {
2600
- for (let entry = 0; entry < entryCount; entry++) {
2601
- for (let i = 0; i < COMBOS; i++) {
2602
- mainReachMe[i] = exchange[entry * 2 * COMBOS + i];
2603
- mainReachOpp[i] = exchange[entry * 2 * COMBOS + COMBOS + i];
2604
- }
2605
- const value = solver.traverseChance(
2606
- mode,
2607
- traverser,
2608
- iterWeight,
2609
- plan.entryNodes[entry],
2610
- mainReachMe,
2611
- mainReachOpp
2612
- );
2613
- chanceValues.set(value.subarray(0, COMBOS), entry * COMBOS);
2614
- }
2615
- } finally {
2616
- ctx.shardStart = fullStart;
2617
- ctx.shardEnd = fullEnd;
2618
- }
2619
- for (; ; ) {
2620
- const done = Atomics.load(control, CONTROL.done);
2621
- if (done >= spawned) break;
2622
- if (failure) throw failure;
2623
- Atomics.wait(control, CONTROL.done, done, 50);
2624
- }
2625
- if (failure) throw failure;
2626
- };
2627
- return {
2628
- workers,
2629
- traverse(mode, traverser, iterWeight) {
2630
- ctx.applyUpdates = false;
2631
- ctx.chanceOverride = null;
2632
- ctx.chanceCollect = (node, reachMe, reachOpp) => {
2633
- const entry = plan.entryIndexOf[node];
2634
- exchange.set(reachMe.subarray(0, COMBOS), entry * 2 * COMBOS);
2635
- exchange.set(reachOpp.subarray(0, COMBOS), entry * 2 * COMBOS + COMBOS);
2636
- };
2637
- try {
2638
- solver.traverseRoot(mode, traverser, iterWeight);
2639
- } finally {
2640
- ctx.chanceCollect = null;
2641
- }
2642
- dispatch(mode, traverser, iterWeight);
2643
- for (let w = 0; w < spawned; w++) {
2644
- const base = reachFloats + w * entryCount * COMBOS;
2645
- for (let i = 0; i < entryCount * COMBOS; i++) chanceValues[i] += exchange[base + i];
2646
- }
2647
- ctx.chanceOverride = chanceValues;
2648
- ctx.applyUpdates = true;
2649
- try {
2650
- const value = solver.traverseRoot(mode, traverser, iterWeight);
2651
- total.set(value.subarray(0, COMBOS));
2652
- } finally {
2653
- ctx.chanceOverride = null;
2654
- }
2655
- return total;
2656
- },
2657
- close() {
2658
- Atomics.store(control, CONTROL.command, COMMAND.exit);
2659
- Atomics.add(control, CONTROL.generation, 1);
2660
- Atomics.notify(control, CONTROL.generation);
2661
- for (const thread of threads) thread.terminate();
2662
- }
2663
- };
2664
- }
2665
-
2666
2675
  // src/index.ts
2667
2676
  var DEFAULT_CHIP_SCALE = 100;
2668
2677
  var OPS_PER_SECOND = 2e8;