diff --git a/.gitignore b/.gitignore index 7256c56..7354c4b 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,12 @@ viewer/public/*.jpg viewer/public/*.jpeg viewer/public/*.png .pnpm-store + +ai/private-data/ +ai/runs/ +ai/.venv/ + +source-bundle/ + +ai/__pycache__/ +serving-bundle/ diff --git a/ai/README.md b/ai/README.md new file mode 100644 index 0000000..1f3b3e0 --- /dev/null +++ b/ai/README.md @@ -0,0 +1,87 @@ +# Powergrid AI — first executable baseline + +This is an experimental training/serving pipeline, **not a replacement for the current production bot**. The trained self-play model beats the new simple heuristic but loses heavily to the engine's existing bot. No BGS bot routing has been changed. + +## Scope and information + +Germany, three players, normal region setup, original and Recharged rules, open and sealed (`fastBid`) auctions. Money is visible for every player. Other maps, player counts and randomized maps need another feature schema and training distribution. Optional region/color drafts are not represented adequately and must not be used with this model. + +The existing compiled JavaScript engine is the authoritative simulator. No game rules were modified. The engine revision is `365fc519903fa2b4e8c593eed6cc5f5f77b5332a`. Schema v2 contains 541 state numbers and 74 numbers per candidate action. Its 44-city vocabulary covers both original and Recharged Germany, including Stralsund/Mainz and Torgelow/Wiesbaden. Schema v1 omitted the two replacement cities and is superseded; do not mix v1 weights with current features. The policy scores a variable list of legal candidates. Large bid lists are approximated by the lowest eight bids, multiples of ten, and the maximum; this is not exhaustive bidding. + +Feature extraction excludes seed, deck order, logs, queued plans, and sealed bid amounts, including already submitted opposing bids. Sealed auctions retain the engine's actual resolution rules, rather than being treated as faster ascending auctions. Player order, plant markets, resource markets, cities, all players' money and holdings remain visible. The server passes trusted engine state; the model itself sees only the allowlisted features. + +## Corrected schema v2 results + +The final HF job completed in 155 seconds. It uses the 44-city vocabulary, 600 synthetic games, 32 supported human games, 12 imitation epochs and 16 self-play updates (482 completed episodes). Four JS workers serve 64 environments; optimizer batch is 1,024. Source: dataset commit `65ecfa063c272bd72a805d45f4ba55dc84a28f42`, archive `source-v4.tgz`. Job: https://huggingface.co/jobs/coyotte508/6abd0cba404719ba3761324e. + +Each comparison has 480 games and zero truncations: + +| Candidate | Opponents | Win share | +| ------------ | ------------------- | --------: | +| Imitation v2 | New heuristic | 13.75% | +| Self-play v2 | New heuristic | 90.00% | +| Imitation v2 | Existing engine bot | 0.00% | +| Self-play v2 | Existing engine bot | 0.00% | + +This is a failed playing-strength gate, despite a working training pipeline. Do not deploy it as the production bot. The larger optimizer batch improved component throughput but reduced gradient updates per epoch; these runs also change schema and rollout configuration, so they are not a controlled batch-size quality comparison. + +On the 8840U, the corrected self-play model reproduces all 480 laptop game outcomes. Pure inference p95 is 0.130 ms. Full worker p50/p95 is 0.773/1.202 ms across 48 representative positions; startup plus first request is 152 ms. All returned actions are legal. Both exports agree with PyTorch on 128 checked decisions each, with maximum absolute error below 0.000007. + +The throughput microbenchmark measured 2,766 decisions/s with one worker/24 environments, 6,289 with four workers/256 environments, and 6,177 with eight. Optimizer sample throughput rose from 18,874 to 28,590/s when increasing batch 256 to 1,024. This does not translate directly into full training speed or playing strength. + +## Initial evidence (schema v1; corrected-model results accompany the package) + +- Read-only BGS audit: 4,007 records, 3,978 marked ended. Export restricted to non-unlisted, ended Germany games with three players. +- 66 candidate historical games; 33 replay exactly against the current engine, including 7 sealed games. Reject 14 dropped/quit/bot games, 15 records that do not reach engine termination, and 4 incompatible replays. The initial run used 11,675 decision examples. Corrected-schema training excludes one color-draft game outside its supported setup: 32 games and 11,366 historical decision examples remain. These records are private and excluded from Git and serving bundles. +- Initial HF job: 600 synthetic games plus verified human examples, 12 imitation epochs, 16 PPO updates, all three seats share the model. Split imitation validation by whole game. HF job completed in 147 seconds excluding queue. CPU training is not run on the 8840U. +- Evaluation: 40 unseen seeds × 3 rotated seats × 4 rule combinations = 480 games per comparison. Model gets one seat, the selected opponent fills the other two. Zero truncated evaluation games. + +| Candidate | Opponents | Win share | +| --------------- | ------------------- | --------: | +| Imitation model | New heuristic | 59.27% | +| Self-play model | New heuristic | 81.77% | +| Self-play model | Existing engine bot | 2.08% | + +These are observed win shares, splitting ties. Seats sharing a seed are correlated. The simple heuristic is a weak opponent; its score is not evidence of human-level play. Use the existing bot as a gate and a training teacher in the next experiment. Freeze separate final-test seeds before selecting many checkpoints. + +8840U: all 480 model-vs-heuristic games completed with identical outcomes to the laptop. Pure ONNX inference p50 0.082 ms / p95 0.165 ms. Persistent JSONL worker on 48 representative positions: p50 0.725 ms / p95 1.144 ms; first request including worker startup 182 ms. All returned actions passed the engine. These are one-run measurements, not concurrency/load guarantees. + +The value head is an **uncalibrated self-play win estimate**, not a forecast of a player's final score or objective position strength. Imitation held-out value MSE is approximately 0.244. Do not expose a player-analysis graph from it yet: add round-stratified calibration, stronger reference opponents, and a separate final-score target if that is the desired analysis. + +## Run and reproduce + +Install the engine dependencies and build `engine/tsconfig.json` using the repository's package manager. Use Python 3.11+, Node 24, and `numpy`, `onnxruntime` for serving. Cloud training additionally needs PyTorch, `onnx`, and `huggingface_hub`; launch scripts use the PyTorch 2.6.0 CUDA 12.4 image. + +```sh +node --test ai/test.cjs +hf download coyotte508/powergrid-ai-germany-v1 --include 'runs/baseline-v2/*' --local-dir ai/runs/download +python ai/evaluate.py ai/runs/download/runs/baseline-v2/selfplay.onnx --seeds 40 --output evaluation.json +python ai/evaluate.py ai/runs/download/runs/baseline-v2/selfplay.onnx --seeds 40 --opponent legacy --output evaluation-legacy.json +python ai/serving-smoke.py ai/runs/download/runs/baseline-v2/selfplay.onnx +``` + +Private HF repositories require the owner's token in the CLI credential store. `launch-v2.sh` trains the corrected schema using `source-v4.tgz`; `launch.sh` reproduces the initial frozen `source-v1.tgz` job; `launch-smoke.sh` checks the updated concurrent trainer with `source-v2.tgz`. `launch-profile.sh` measures batching/worker throughput. Source archives contain only the compiled engine, its production dependencies, AI scripts and the deidentified verified training records. Use the recorded dataset commit plus archive hash for exact provenance; uploaded archives are not automatically rebuilt when local files change. + +Trainer controls: `GAMES`, `BC_EPOCHS`, `RL_UPDATES`, `ENVS`, `WORKERS`, `BATCH_SIZE`, `ROLLOUT_SAMPLES`, `OUT`, `RUN_NAME`, `HF_MODEL_REPO`. Start with four workers and 256 environments, then tune the optimizer batch from measurements. Increasing batch changes optimization dynamics; compare strength as well as throughput. The small model does not need to fill GPU VRAM. Python JSON conversion and feature packing still take appreciable time; a packed binary/shared-memory interface is the next throughput improvement if needed. + +## Platform worker contract + +Keep one worker alive per CPU execution slot: + +```sh +python ai/infer.py selfplay.onnx +``` + +Input is one JSON object per line: `{ "requestId": "unique-job-id", "revision": 123, "player": 0, "state": }`. + +Output echoes the request ID/revision and returns `move`, `winProbabilities`, `valueStatus`, `playerOrder`, `model`, `modelSha256`, and `elapsedMs`, or an `error`. Probabilities are ordered `[acting seat, next seat clockwise, third seat]`. + +Each request chooses one **atomic** engine action. Before committing it, the platform must reload/check the game revision and acting player, validate the action with its pinned engine, and commit through its normal move path with a server timestamp. Revision is an echoed correlation value here, not a concurrency lock. Retry stale jobs from fresh state; deduplicate by request ID; use the existing bot on timeout/error or unsupported options. Multiple atomic actions can be needed to finish a player's turn. The process provides no HTTP endpoint or authentication; invoke it through the platform's existing job machinery. + +## Next strength experiment + +1. Generate demonstrations from the existing engine bot and improve the heuristic's build/auction economics. Preserve information boundaries for all teachers. +2. Train against a mixture of existing bots, frozen older policies and self-play; use larger rollout batches and enough completed games rather than simply more GPU memory. +3. Evaluate across rule combinations and held-out seeds with paired uncertainty estimates; require improvement over the existing bot before routing production moves. +4. Expand to other maps/player counts using graph/city features and variable player encodings. Retrain; do not silently apply the Germany model. +5. Train/calibrate analysis targets separately. Public-money assumptions must remain explicit in any analysis UI. diff --git a/ai/arena.cjs b/ai/arena.cjs new file mode 100644 index 0000000..f9f2a82 --- /dev/null +++ b/ai/arena.cjs @@ -0,0 +1,55 @@ +const c = require('./core.cjs'), + readline = require('node:readline'); +let g, seat, opponent, rng, steps; +function advance() { + while (!c.E.ended(g) && g.currentPlayers[0] !== seat && steps < 1600) { + const p = g.currentPlayers[0]; + if (opponent === 'legacy') { + const old = Math.random; + Math.random = rng; + try { + g = c.E.moveAI(g, p); + } finally { + Math.random = old; + } + } else g = c.E.move(g, c.heuristic(g, p, rng).action, p); + steps++; + } + if (c.E.ended(g) || steps >= 1600) + return { + done: true, + truncated: !c.E.ended(g), + win: c.E.ended(g) ? c.outcome(g)[seat] : 0, + round: g.round, + steps, + final: g.players.map((p) => ({ powered: p.citiesPowered, money: p.money, cities: p.cities.length })), + }; + const a = c.candidates(g, seat); + return { + done: false, + state: c.observe(g, seat), + actions: a.map((x) => c.actionFeatures(g, seat, x)), + heuristic: c.heuristic(g, seat, rng).index, + }; +} +(async () => { + for await (const line of readline.createInterface({ input: process.stdin })) { + try { + const q = JSON.parse(line); + if (q.op === 'reset') { + g = c.start(q.seed, q.variant, q.sealed); + seat = q.seat; + opponent = q.opponent || 'heuristic'; + rng = c.seedrandom(q.seed + '-opponents'); + steps = 0; + } else if (q.op === 'step') { + g = c.E.move(g, c.candidates(g, seat)[q.action], seat); + steps++; + } + console.log(JSON.stringify(advance())); + } catch (e) { + console.error(e.stack); + process.exit(1); + } + } +})(); diff --git a/ai/audit-remote.cjs b/ai/audit-remote.cjs new file mode 100644 index 0000000..f7f0f0d --- /dev/null +++ b/ai/audit-remote.cjs @@ -0,0 +1,59 @@ +const fs = require('node:fs'); +const { parseEnv } = require('node:util'); +const { createRequire } = require('node:module'); +const requireApi = createRequire('/home/bgs/boardgamers-mono/apps/api/package.json'); +const { MongoClient } = requireApi('mongodb'); +(async () => { + const env = parseEnv(fs.readFileSync('/home/bgs/boardgamers-mono/apps/api/.env', 'utf8')); + const client = await MongoClient.connect(env.dbUrl, { serverSelectionTimeoutMS: 10000 }); + try { + const db = client.db(env.dbName || 'bgs'); + const c = db.collection('games'); + const counts = await c + .aggregate( + [ + { $match: { 'game.name': 'powergrid' } }, + { + $group: { + _id: { + version: '$game.version', + status: '$status', + map: '$game.options.map', + variant: '$game.options.variant', + players: '$options.setup.nbPlayers', + }, + n: { $sum: 1 }, + }, + }, + ], + { maxTimeMS: 20000 } + ) + .toArray(); + const sample = await c.findOne( + { 'game.name': 'powergrid', status: 'ended' }, + { projection: { data: 1, game: 1, options: 1, players: 1, status: 1 } } + ); + console.log( + JSON.stringify( + { + counts, + sample: sample && { + dataType: typeof sample.data, + dataKeys: typeof sample.data === 'object' ? Object.keys(sample.data || {}) : undefined, + dataLength: typeof sample.data === 'string' ? sample.data.length : undefined, + game: sample.game, + playerFields: Object.keys(sample.players[0] || {}), + hasSeed: !!sample.options?.setup?.seed, + }, + }, + null, + 2 + ) + ); + } finally { + await client.close(); + } +})().catch((e) => { + console.error(e.name, e.code); + process.exit(1); +}); diff --git a/ai/audit-replays.cjs b/ai/audit-replays.cjs new file mode 100644 index 0000000..5a29118 --- /dev/null +++ b/ai/audit-replays.cjs @@ -0,0 +1,54 @@ +const fs = require('node:fs'), + assert = require('node:assert/strict'); +const c = require('./core.cjs'); +const games = fs.readFileSync('ai/private-data/human-games.jsonl', 'utf8').trim().split('\n').map(JSON.parse); +const results = []; +let admitted = []; +const clean = (p) => ({ + money: p.money, + citiesPowered: p.citiesPowered, + cities: p.cities.map((c) => c.name).sort(), + powerPlants: p.powerPlants.map((p) => p.number).sort((a, b) => a - b), +}); +for (const h of games) { + let count = 0; + try { + if (h.players.some((p) => p.dropped || p.quit || p.bot)) throw Error('dropped/quit/bot'); + if (h.phase !== c.E.Phase.GameEnd) throw Error('not engine terminal'); + let g = c.E.setup(3, h.options, h.seed); + for (const m of h.moves) { + g = c.E.move(g, m.move, m.player); + count++; + } + assert.deepEqual(g.players.map(clean), h.final); + assert.ok(c.E.ended(g)); + admitted.push(h); + results.push({ + id: h.id, + version: h.version, + variant: h.options.variant, + sealed: !!h.options.fastBid, + moves: count, + accepted: true, + }); + } catch (e) { + results.push({ id: h.id, version: h.version, moves: count, accepted: false, reason: e.message.split('\n')[0] }); + } +} +fs.writeFileSync('ai/private-data/verified-games.jsonl', admitted.map((x) => JSON.stringify(x)).join('\n')); +const report = { + total: games.length, + accepted: admitted.length, + acceptedSealed: admitted.filter((x) => x.options.fastBid).length, + results, +}; +fs.writeFileSync('ai/replay-audit.json', JSON.stringify(report, null, 2)); +console.log({ + total: games.length, + accepted: admitted.length, + reasons: results.reduce((o, r) => { + let k = r.accepted ? 'accepted' : r.reason; + o[k] = (o[k] || 0) + 1; + return o; + }, {}), +}); diff --git a/ai/benchmark.cjs b/ai/benchmark.cjs new file mode 100644 index 0000000..b7d597e --- /dev/null +++ b/ai/benchmark.cjs @@ -0,0 +1,35 @@ +const c = require('./core.cjs'), + fs = require('node:fs'), + os = require('node:os'), + { performance } = require('node:perf_hooks'); +let runs = []; +for (const variant of ['original', 'recharged']) + for (const sealed of [false, true]) { + let steps = 0, + ended = 0; + const t = performance.now(); + for (let i = 0; i < 100; i++) { + let g = c.start('benchmark-' + i, variant, sealed), + rng = c.seedrandom('policy-' + i), + n = 0; + while (!c.E.ended(g) && n++ < 1600) { + const p = g.currentPlayers[0]; + g = c.E.move(g, c.heuristic(g, p, rng).action, p); + steps++; + } + ended += +c.E.ended(g); + } + const sec = (performance.now() - t) / 1000; + runs.push({ + variant, + sealed, + games: 100, + ended, + steps, + seconds: sec, + gamesPerSecond: 100 / sec, + stepsPerSecond: steps / sec, + }); + } +const result = { cpu: os.cpus()[0].model, node: process.version, runs }; +console.log(JSON.stringify(result, null, 2)); diff --git a/ai/bridge.cjs b/ai/bridge.cjs new file mode 100644 index 0000000..2484512 --- /dev/null +++ b/ai/bridge.cjs @@ -0,0 +1,54 @@ +const c = require('./core.cjs'), + readline = require('node:readline'); +let envs = [], + sequence = 0; +const seed = process.env.SEED || 'rollout-v1'; +const rng = c.seedrandom(seed); +function reset() { + const id = sequence++; + return { g: c.start(seed + '-' + id, id % 2 ? 'recharged' : 'original', id % 4 < 2), id, steps: 0 }; +} +function obs(e) { + const seat = e.g.currentPlayers[0], + a = c.candidates(e.g, seat); + return { + state: c.observe(e.g, seat), + actions: a.map((x) => c.actionFeatures(e.g, seat, x)), + seat, + episode: e.id, + heuristic: c.heuristic(e.g, seat, rng).index, + }; +} +(async () => { + for await (const line of readline.createInterface({ input: process.stdin })) { + try { + const q = JSON.parse(line); + let ended = []; + if (q.op === 'reset') { + envs = Array.from({ length: q.n }, reset); + } else if (q.op === 'step') { + q.actions.forEach((action, i) => { + const e = envs[i], + seat = e.g.currentPlayers[0]; + e.g = c.E.move(e.g, c.candidates(e.g, seat)[action], seat); + e.steps++; + if (c.E.ended(e.g) || e.steps >= 1600) { + ended.push({ + env: i, + episode: e.id, + truncated: !c.E.ended(e.g), + value: c.E.ended(e.g) ? c.outcome(e.g) : null, + steps: e.steps, + round: e.g.round, + }); + envs[i] = reset(); + } + }); + } else throw Error('unknown operation'); + console.log(JSON.stringify({ observations: envs.map(obs), ended })); + } catch (e) { + console.error(e.stack); + process.exit(1); + } + } +})(); diff --git a/ai/core.cjs b/ai/core.cjs new file mode 100644 index 0000000..4236f00 --- /dev/null +++ b/ai/core.cjs @@ -0,0 +1,239 @@ +const E = require('../engine/dist/index.js'); +const { map: germany, mapRecharged: germanyRecharged } = require('../engine/dist/src/maps/germany.js'); +const seedrandom = require(require.resolve('seedrandom', { paths: [__dirname + '/../engine'] })); +const TYPES = [ + 'ChoosePowerPlant', + 'Bid', + 'DiscardPowerPlant', + 'DiscardResources', + 'BuyResource', + 'Build', + 'UsePowerPlant', + 'ChooseRegion', + 'ChooseColor', + 'Pass', +]; +const RES = ['coal', 'oil', 'garbage', 'uranium']; +const CITIES = [...new Set([...germany.cities, ...germanyRecharged.cities].map((c) => c.name))].sort(); +const PHASES = Object.values(E.Phase); +const onehot = (v, vs) => vs.map((x) => +(x === v)); +const plant = (p) => + p ? [p.number / 50, p.cost / 4, p.citiesPowered / 8, ...onehot(p.type, [0, 1, 2, 3, 4, 5])] : Array(9).fill(0); +function assertScope(g) { + if ( + g.map.name !== 'Germany' || + g.players.length !== 3 || + g.options.randomizeMap || + g.map.cities.some((city) => !CITIES.includes(city.name)) || + g.options.chooseRegions || + g.options.chooseColors + ) + throw Error('Baseline supports three-player Germany with automatic setup only'); +} +function observe(g, seat) { + assertScope(g); + const order = [seat, (seat + 1) % 3, (seat + 2) % 3]; + const s = [ + ...onehot(g.phase, PHASES), + g.round / 20, + g.step / 3, + +(g.options.variant === 'recharged'), + +g.options.fastBid, + g.cardsLeft / 50, + +g.nextCardWeak, + (g.options.fastBid ? 0 : g.currentBid || 0) / 100, + (g.minimunBid || 0) / 100, + ...onehot(g.auctioningPlayer, order), + g.citiesToEndGame / 25, + g.citiesToStep2 / 20, + ]; + for (const r of RES) + s.push( + (g[r + 'Market'] || 0) / 24, + (g[r + 'Supply'] || 0) / 24, + ...(g[r + 'Prices'] || []).slice(0, 24).map((x) => x / 20), + ...Array(Math.max(0, 24 - (g[r + 'Prices'] || []).length)).fill(0) + ); + for (const i of order) { + const p = g.players[i]; + s.push( + p.money / 500, + p.cities.length / 22, + p.housesLeft / 22, + p.citiesPowered / 22, + g.playerOrder.indexOf(i) / 2, + +p.skipAuction, + +p.passed, + (g.options.fastBid ? 0 : p.bid || 0) / 100 + ); + for (const r of RES) s.push((p[r + 'Left'] || 0) / 24, (p[r + 'Capacity'] || 0) / 24); + s.push(p.hybridCapacity / 24); + for (let j = 0; j < 4; j++) s.push(...plant(p.powerPlants[j])); + } + for (let i = 0; i < 4; i++) s.push(...plant(g.actualMarket[i]), ...plant(g.futureMarket[i])); + s.push(...plant(g.chosenPowerPlant)); + for (const city of CITIES) + s.push( + +g.map.cities.some((c) => c.name === city), + ...order.map((i) => +g.players[i].cities.some((c) => c.name === city)) + ); + if (!s.every(Number.isFinite)) throw Error('Non-finite observation'); + return s; +} +function allLegal(g, seat) { + return Object.entries(g.players[seat].availableMoves || {}).flatMap(([name, items]) => + (items || []).map((data) => ({ name, data })) + ); +} +function candidates(g, seat) { + const all = allLegal(g, seat), + bids = all.filter((a) => a.name === 'Bid'); + if (bids.length <= 48) return all; + const min = bids[0].data, + max = bids.at(-1).data; + return all.filter((a) => a.name !== 'Bid' || a.data < min + 8 || a.data % 10 === 0 || a.data === max); +} + +function actionFeatures(g, seat, a) { + const d = a.data, + p = g.players[seat]; + const pp = + a.name === 'ChoosePowerPlant' + ? g.actualMarket.find((x) => x.number === d) + : a.name === 'DiscardPowerPlant' + ? p.powerPlants.find((x) => x.number === d) + : a.name === 'UsePowerPlant' + ? p.powerPlants.find((x) => x.number === d.powerPlant) + : g.chosenPowerPlant; + const cost = a.name === 'Bid' ? d : d?.price || 0; + return [ + ...onehot(a.name, TYPES), + cost / 500, + cost / Math.max(p.money, 1), + ...onehot(d?.resource || (typeof d === 'string' ? d : ''), RES), + ...plant(pp), + ...onehot(d?.name, CITIES), + (d?.citiesPowered || 0) / 20, + ...RES.map((r) => (d?.resourcesSpent || []).filter((x) => x === r).length / 4), + ]; +} +function fuelDemand(g, p) { + const target = Math.min(Math.max(p.cities.length, Math.min(3, capacity(p))), capacity(p)); + let powered = 0; + const need = Object.fromEntries(RES.map((r) => [r, 0])); + const ps = [...p.powerPlants].sort((a, b) => fuelCost(g, a) / a.citiesPowered - fuelCost(g, b) / b.citiesPowered); + for (const pp of ps) { + if (powered >= target) break; + powered += pp.citiesPowered; + let resource = RES[pp.type]; + if (pp.type === 4) resource = (g.coalPrices[0] || 8) <= (g.oilPrices[0] || 8) ? 'coal' : 'oil'; + if (resource) need[resource] += pp.cost; + } + return need; +} +function fuelCost(g, pp) { + return ( + pp.cost * + (pp.type === 4 ? Math.min(g.coalPrices[0] || 8, g.oilPrices[0] || 8) : g[RES[pp.type] + 'Prices']?.[0] || 0) + ); +} +const capacity = (p) => p.powerPlants.reduce((n, x) => n + x.citiesPowered, 0); +function plantWorth(g, p, pp) { + let old = 0; + if (p.powerPlants.length >= 3) old = Math.min(...p.powerPlants.map((x) => x.citiesPowered)); + const gain = Math.max(0, pp.citiesPowered - old); + const reserve = Math.max(12, Math.min(40, p.cities.length * 2 + 10)); + const useful = gain > 0 || fuelCost(g, pp) < 3; + return useful ? Math.min(p.money - reserve, pp.number + gain * 5 - fuelCost(g, pp)) : 0; +} +function heuristicScore(g, seat, a) { + const p = g.players[seat], + d = a.data, + cap = capacity(p); + switch (a.name) { + case 'ChoosePowerPlant': { + const pp = g.actualMarket.find((x) => x.number === d); + const worth = plantWorth(g, p, pp); + return worth >= d ? 20 + pp.citiesPowered * 5 - fuelCost(g, pp) - d * 0.2 : -100 - d; + } + case 'Bid': { + const worth = Math.max(g.round === 1 ? g.minimunBid : 0, plantWorth(g, p, g.chosenPowerPlant)); + if (d > worth) return -100 - d; + return g.options.fastBid ? 20 - Math.abs(worth - d) : 30 - d * 0.1; + } + case 'DiscardPowerPlant': { + const pp = p.powerPlants.find((x) => x.number === d); + return 10 - pp.citiesPowered * 5 + fuelCost(g, pp); + } + case 'DiscardResources': + return 10 + (p[d + 'Left'] || 0); + case 'BuyResource': { + const need = fuelDemand(g, p); + return p[d.resource + 'Left'] < need[d.resource] && + p.money - d.price >= Math.max(0, p.cities.length ? 0 : 12) + ? 20 - d.price + : -100; + } + case 'Build': { + const desired = + p.money > 150 || g.round > 18 + ? g.citiesToEndGame + : Math.min(g.citiesToEndGame, cap + (p.money > 100 ? 1 : 0)); + return p.cities.length < desired ? 30 - d.price * 0.5 : -100; + } + case 'UsePowerPlant': + return ( + 40 + + (d.citiesPowered || 0) * 5 - + (d.resourcesSpent || []).reduce((n, r) => n + (g[r + 'Prices']?.[0] || 8), 0) + ); + case 'Pass': + return 0; + default: + return 1; + } +} +function heuristic(g, seat, rng = () => 0.5) { + const a = candidates(g, seat); + let best = 0, + v = -Infinity; + a.forEach((x, i) => { + const score = heuristicScore(g, seat, x) + rng() * 0.01; + if (score > v) { + v = score; + best = i; + } + }); + return { index: best, action: a[best] }; +} +function outcome(g) { + const sorted = E.playersSortedByScore(g), + top = sorted[0], + w = g.players.map( + (p) => + +( + p.citiesPowered === top.citiesPowered && + p.money === top.money && + p.cities.length === top.cities.length + ) + ); + return w.map((x) => x / w.reduce((a, b) => a + b, 0)); +} +function start(seed, variant = 'original', fastBid = false) { + return E.setup(3, { map: 'Germany', variant, fastBid, showMoney: true }, seed); +} +module.exports = { + E, + CITIES, + TYPES, + RES, + observe, + allLegal, + candidates, + actionFeatures, + heuristic, + heuristicScore, + outcome, + start, + seedrandom, +}; diff --git a/ai/data-audit.json b/ai/data-audit.json new file mode 100644 index 0000000..cb8443e --- /dev/null +++ b/ai/data-audit.json @@ -0,0 +1,4332 @@ +{ + "counts": [ + { + "_id": { + "version": 3, + "status": "ended", + "map": "Brazil", + "variant": "original", + "players": 4 + }, + "n": 10 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Quebec", + "variant": "recharged", + "players": 6 + }, + "n": 16 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Quebec", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "USA", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "UK & Ireland", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 13, + "status": "active", + "map": "China", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Benelux", + "variant": "original", + "players": 2 + }, + "n": 34 + }, + { + "_id": { + "version": 6, + "status": "ended", + "map": "UK & Ireland", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Middle East", + "variant": "original", + "players": 6 + }, + "n": 8 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Northern Europe", + "variant": "recharged", + "players": 5 + }, + "n": 4 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Italy", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Central Europe", + "variant": "recharged", + "players": 6 + }, + "n": 14 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Korea", + "variant": "recharged", + "players": 5 + }, + "n": 5 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Benelux", + "variant": "recharged", + "players": 3 + }, + "n": 10 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Benelux", + "variant": "recharged", + "players": 6 + }, + "n": 10 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Central Europe", + "variant": "recharged", + "players": 3 + }, + "n": 5 + }, + { + "_id": { + "version": 2, + "status": "ended", + "map": "USA", + "variant": "recharged", + "players": 3 + }, + "n": 2 + }, + { + "_id": { + "version": 5, + "status": "ended", + "map": "Europe", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Italy", + "variant": "recharged", + "players": 4 + }, + "n": 49 + }, + { + "_id": { + "version": 2, + "status": "ended", + "map": "USA", + "variant": "original", + "players": 2 + }, + "n": 74 + }, + { + "_id": { + "version": 6, + "status": "ended", + "map": "China", + "variant": "original", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Baden-Württemberg", + "variant": "original", + "players": 6 + }, + "n": 3 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "North America", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Italy", + "variant": "original", + "players": 6 + }, + "n": 4 + }, + { + "_id": { + "version": 7, + "status": "ended", + "map": "Spain & Portugal", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 6, + "status": "ended", + "map": "Benelux", + "variant": "recharged", + "players": 3 + }, + "n": 1 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "UK & Ireland", + "variant": "recharged", + "players": 2 + }, + "n": 2 + }, + { + "_id": { + "version": 5, + "status": "ended", + "map": "USA", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "Central Europe", + "variant": "recharged", + "players": 5 + }, + "n": 2 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Spain & Portugal", + "variant": "recharged", + "players": 6 + }, + "n": 20 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "France", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Quebec", + "variant": "original", + "players": 3 + }, + "n": 3 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "South Africa", + "variant": "original", + "players": 2 + }, + "n": 2 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Europe", + "variant": "recharged", + "players": 2 + }, + "n": 4 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Italy", + "variant": "recharged", + "players": 4 + }, + "n": 2 + }, + { + "_id": { + "version": 11, + "status": "active", + "map": "Bremen", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 12, + "status": "ended", + "map": "France", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Bremen", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "active", + "map": "India", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Central Europe", + "variant": "original", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "Quebec", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Germany", + "variant": "original", + "players": 2 + }, + "n": 3 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "China", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Spain & Portugal", + "variant": "original", + "players": 6 + }, + "n": 8 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Russia", + "variant": "original", + "players": 5 + }, + "n": 3 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Spain & Portugal", + "variant": "original", + "players": 3 + }, + "n": 3 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Russia", + "variant": "original", + "players": 6 + }, + "n": 6 + }, + { + "_id": { + "version": 6, + "status": "ended", + "map": "Northern Europe", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "USA", + "variant": "original", + "players": 4 + }, + "n": 3 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Korea", + "variant": "recharged", + "players": 4 + }, + "n": 3 + }, + { + "_id": { + "version": 13, + "status": "active", + "map": "China", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "USA", + "variant": "original", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 13, + "status": "active", + "map": "Benelux", + "variant": "original", + "players": 3 + }, + "n": 1 + }, + { + "_id": { + "version": 13, + "status": "active", + "map": "Central Europe", + "variant": "original", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Japan", + "variant": "recharged", + "players": 4 + }, + "n": 2 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "USA", + "variant": "recharged", + "players": 4 + }, + "n": 102 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "India", + "variant": "original", + "players": 3 + }, + "n": 7 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Germany", + "variant": "recharged", + "players": 6 + }, + "n": 22 + }, + { + "_id": { + "version": 13, + "status": "active", + "map": "India", + "variant": "original", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Korea", + "variant": "original", + "players": 3 + }, + "n": 1 + }, + { + "_id": { + "version": 6, + "status": "ended", + "map": "Bremen", + "variant": "original", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "USA", + "variant": "recharged", + "players": 2 + }, + "n": 2 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Bremen", + "variant": "original", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Germany", + "variant": "original", + "players": 3 + }, + "n": 67 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Germany", + "variant": "original", + "players": 3 + }, + "n": 2 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "China", + "variant": "original", + "players": 2 + }, + "n": 2 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Baden-Württemberg", + "variant": "original", + "players": 3 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Germany", + "variant": "recharged", + "players": 4 + }, + "n": 4 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Manhattan", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Europe", + "variant": "recharged", + "players": 3 + }, + "n": 1 + }, + { + "_id": { + "version": 6, + "status": "ended", + "map": "Bremen", + "variant": "recharged", + "players": 4 + }, + "n": 2 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "India", + "variant": "recharged", + "players": 5 + }, + "n": 27 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "France", + "variant": "recharged", + "players": 6 + }, + "n": 17 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Germany", + "variant": "original", + "players": 2 + }, + "n": 168 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "USA", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Middle East", + "variant": "original", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "France", + "variant": "original", + "players": 4 + }, + "n": 15 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Italy", + "variant": "original", + "players": 5 + }, + "n": 5 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Benelux", + "variant": "recharged", + "players": 3 + }, + "n": 2 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Middle East", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Germany", + "variant": "recharged", + "players": 3 + }, + "n": 29 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "China", + "variant": "original", + "players": 6 + }, + "n": 11 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Brazil", + "variant": "recharged", + "players": 4 + }, + "n": 66 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "South Africa", + "variant": "recharged", + "players": 4 + }, + "n": 2 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Korea", + "variant": "original", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "India", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Japan", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 2, + "status": "ended", + "map": "Germany", + "variant": "original", + "players": 5 + }, + "n": 11 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "Germany", + "variant": "original", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Manhattan", + "variant": "original", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "Italy", + "variant": "recharged", + "players": 3 + }, + "n": 2 + }, + { + "_id": { + "version": 2, + "status": "ended", + "map": "Germany", + "variant": "recharged", + "players": 4 + }, + "n": 6 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Italy", + "variant": "original", + "players": 3 + }, + "n": 9 + }, + { + "_id": { + "version": 2, + "status": "ended", + "map": "USA", + "variant": "recharged", + "players": 2 + }, + "n": 3 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Baden-Württemberg", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 5, + "status": "ended", + "map": "Brazil", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Manhattan", + "variant": "recharged", + "players": 4 + }, + "n": 2 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "China", + "variant": "recharged", + "players": 5 + }, + "n": 19 + }, + { + "_id": { + "version": 6, + "status": "ended", + "map": "France", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Korea", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "India", + "variant": "recharged", + "players": 6 + }, + "n": 7 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "UK & Ireland", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Europe", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "UK & Ireland", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Manhattan", + "variant": "recharged", + "players": 5 + }, + "n": 2 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "USA", + "variant": "original", + "players": 6 + }, + "n": 6 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Japan", + "variant": "recharged", + "players": 2 + }, + "n": 5 + }, + { + "_id": { + "version": 5, + "status": "ended", + "map": "North America", + "variant": "recharged", + "players": 4 + }, + "n": 2 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Spain & Portugal", + "variant": "recharged", + "players": 3 + }, + "n": 15 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Russia", + "variant": "recharged", + "players": 4 + }, + "n": 29 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Russia", + "variant": "recharged", + "players": 5 + }, + "n": 33 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "China", + "variant": "original", + "players": 5 + }, + "n": 10 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Central Europe", + "variant": "original", + "players": 3 + }, + "n": 3 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Brazil", + "variant": "recharged", + "players": 4 + }, + "n": 3 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "USA", + "variant": "recharged", + "players": 4 + }, + "n": 8 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Japan", + "variant": "original", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Brazil", + "variant": "recharged", + "players": 3 + }, + "n": 12 + }, + { + "_id": { + "version": 7, + "status": "ended", + "map": "Bremen", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 9, + "status": "ended", + "map": "North America", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 6, + "status": "ended", + "map": "Australia", + "variant": "recharged", + "players": 4 + }, + "n": 2 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Quebec", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Central Europe", + "variant": "original", + "players": 2 + }, + "n": 29 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Benelux", + "variant": "recharged", + "players": 4 + }, + "n": 2 + }, + { + "_id": { + "version": 6, + "status": "ended", + "map": "Manhattan", + "variant": "recharged", + "players": 5 + }, + "n": 3 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Spain & Portugal", + "variant": "recharged", + "players": 4 + }, + "n": 64 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Japan", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "UK & Ireland", + "variant": "original", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 1, + "status": "ended", + "players": 2 + }, + "n": 3 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Germany", + "variant": "recharged", + "players": 2 + }, + "n": 65 + }, + { + "_id": { + "version": 13, + "status": "active", + "map": "Central Europe", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Middle East", + "variant": "recharged", + "players": 5 + }, + "n": 46 + }, + { + "_id": { + "version": 5, + "status": "ended", + "map": "Benelux", + "variant": "recharged", + "players": 2 + }, + "n": 2 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Russia", + "variant": "original", + "players": 3 + }, + "n": 1 + }, + { + "_id": { + "version": 2, + "status": "ended", + "map": "Germany", + "variant": "original", + "players": 4 + }, + "n": 11 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "India", + "variant": "original", + "players": 5 + }, + "n": 8 + }, + { + "_id": { + "version": 2, + "status": "ended", + "map": "Germany", + "variant": "original", + "players": 6 + }, + "n": 4 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Australia", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 7, + "status": "ended", + "map": "Manhattan", + "variant": "original", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "USA", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "India", + "variant": "original", + "players": 6 + }, + "n": 2 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "Benelux", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Korea", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 9, + "status": "ended", + "map": "Northern Europe", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Italy", + "variant": "original", + "players": 2 + }, + "n": 2 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "China", + "variant": "recharged", + "players": 3 + }, + "n": 11 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "Central Europe", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 13, + "status": "active", + "map": "Korea", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 5, + "status": "ended", + "map": "Central Europe", + "variant": "recharged", + "players": 5 + }, + "n": 2 + }, + { + "_id": { + "version": 2, + "status": "ended", + "map": "Germany", + "variant": "original", + "players": 3 + }, + "n": 7 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Germany", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Middle East", + "variant": "recharged", + "players": 3 + }, + "n": 8 + }, + { + "_id": { + "version": 1, + "status": "ended", + "players": 5 + }, + "n": 2 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Quebec", + "variant": "original", + "players": 5 + }, + "n": 8 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "Baden-Württemberg", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "USA", + "variant": "recharged", + "players": 5 + }, + "n": 59 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Russia", + "variant": "recharged", + "players": 6 + }, + "n": 17 + }, + { + "_id": { + "version": 9, + "status": "ended", + "map": "Quebec", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "UK & Ireland", + "variant": "original", + "players": 3 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Central Europe", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Germany", + "variant": "recharged", + "players": 2 + }, + "n": 9 + }, + { + "_id": { + "version": 7, + "status": "ended", + "map": "Brazil", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 7, + "status": "ended", + "map": "Spain & Portugal", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "China", + "variant": "original", + "players": 2 + }, + "n": 3 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Northern Europe", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Middle East", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Middle East", + "variant": "recharged", + "players": 4 + }, + "n": 60 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Benelux", + "variant": "recharged", + "players": 2 + }, + "n": 14 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Russia", + "variant": "recharged", + "players": 2 + }, + "n": 10 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Northern Europe", + "variant": "original", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 6, + "status": "ended", + "map": "Quebec", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "France", + "variant": "recharged", + "players": 3 + }, + "n": 13 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Germany", + "variant": "original", + "players": 2 + }, + "n": 8 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "France", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "USA", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Quebec", + "variant": "recharged", + "players": 5 + }, + "n": 44 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Japan", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Spain & Portugal", + "variant": "original", + "players": 5 + }, + "n": 12 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Russia", + "variant": "original", + "players": 2 + }, + "n": 33 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "South Africa", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Middle East", + "variant": "recharged", + "players": 6 + }, + "n": 12 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Australia", + "variant": "original", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "India", + "variant": "recharged", + "players": 4 + }, + "n": 3 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "France", + "variant": "original", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Germany", + "variant": "original", + "players": 4 + }, + "n": 2 + }, + { + "_id": { + "version": 11, + "status": "active", + "map": "Northern Europe", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Japan", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Central Europe", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Quebec", + "variant": "original", + "players": 6 + }, + "n": 2 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "South Africa", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "active", + "map": "Spain & Portugal", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 13, + "status": "active", + "map": "Germany", + "variant": "original", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "China", + "variant": "original", + "players": 3 + }, + "n": 2 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "Germany", + "variant": "original", + "players": 2 + }, + "n": 2 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "USA", + "variant": "original", + "players": 2 + }, + "n": 114 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Baden-Württemberg", + "variant": "recharged", + "players": 5 + }, + "n": 3 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Middle East", + "variant": "original", + "players": 5 + }, + "n": 5 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "USA", + "variant": "recharged", + "players": 2 + }, + "n": 5 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Spain & Portugal", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 6, + "status": "ended", + "map": "Quebec", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "Australia", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Russia", + "variant": "recharged", + "players": 4 + }, + "n": 2 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "USA", + "variant": "recharged", + "players": 2 + }, + "n": 25 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Russia", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 5, + "status": "ended", + "map": "Manhattan", + "variant": "recharged", + "players": 3 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "India", + "variant": "recharged", + "players": 3 + }, + "n": 9 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "France", + "variant": "original", + "players": 3 + }, + "n": 4 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Middle East", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Spain & Portugal", + "variant": "recharged", + "players": 4 + }, + "n": 4 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Quebec", + "variant": "recharged", + "players": 4 + }, + "n": 61 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Northern Europe", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 6, + "status": "ended", + "map": "Australia", + "variant": "original", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 9, + "status": "ended", + "map": "Japan", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 9, + "status": "ended", + "map": "Baden-Württemberg", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "India", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Spain & Portugal", + "variant": "recharged", + "players": 5 + }, + "n": 49 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Benelux", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "India", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Germany", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Quebec", + "variant": "original", + "players": 2 + }, + "n": 2 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "Germany", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "Korea", + "variant": "recharged", + "players": 3 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Spain & Portugal", + "variant": "original", + "players": 4 + }, + "n": 10 + }, + { + "_id": { + "version": 2, + "status": "ended", + "map": "Germany", + "variant": "recharged", + "players": 3 + }, + "n": 3 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Benelux", + "variant": "recharged", + "players": 4 + }, + "n": 49 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Brazil", + "variant": "original", + "players": 6 + }, + "n": 5 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Brazil", + "variant": "original", + "players": 3 + }, + "n": 6 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Australia", + "variant": "recharged", + "players": 5 + }, + "n": 2 + }, + { + "_id": { + "version": 5, + "status": "ended", + "map": "Manhattan", + "variant": "recharged", + "players": 5 + }, + "n": 2 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Central Europe", + "variant": "recharged", + "players": 4 + }, + "n": 28 + }, + { + "_id": { + "version": 5, + "status": "ended", + "map": "Japan", + "variant": "recharged", + "players": 4 + }, + "n": 2 + }, + { + "_id": { + "version": 6, + "status": "ended", + "map": "Spain & Portugal", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "France", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 5, + "status": "ended", + "map": "Germany", + "variant": "recharged", + "players": 3 + }, + "n": 1 + }, + { + "_id": { + "version": 6, + "status": "ended", + "map": "Quebec", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Central Europe", + "variant": "recharged", + "players": 2 + }, + "n": 9 + }, + { + "_id": { + "version": 5, + "status": "ended", + "map": "Japan", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 9, + "status": "ended", + "map": "India", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "North America", + "variant": "recharged", + "players": 4 + }, + "n": 2 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "India", + "variant": "recharged", + "players": 2 + }, + "n": 19 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "China", + "variant": "original", + "players": 4 + }, + "n": 23 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "Europe", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Korea", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "China", + "variant": "original", + "players": 2 + }, + "n": 3 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Europe", + "variant": "recharged", + "players": 5 + }, + "n": 2 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Japan", + "variant": "recharged", + "players": 3 + }, + "n": 1 + }, + { + "_id": { + "version": 5, + "status": "ended", + "map": "Korea", + "variant": "original", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Middle East", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Russia", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Spain & Portugal", + "variant": "recharged", + "players": 2 + }, + "n": 10 + }, + { + "_id": { + "version": 2, + "status": "ended", + "map": "Germany", + "variant": "original", + "players": 2 + }, + "n": 24 + }, + { + "_id": { + "version": 13, + "status": "active", + "map": "Central Europe", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "Central Europe", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 13, + "status": "active", + "map": "Middle East", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Middle East", + "variant": "original", + "players": 4 + }, + "n": 9 + }, + { + "_id": { + "version": 2, + "status": "ended", + "map": "USA", + "variant": "recharged", + "players": 4 + }, + "n": 4 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Italy", + "variant": "original", + "players": 2 + }, + "n": 50 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "Europe", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 7, + "status": "ended", + "map": "Spain & Portugal", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "Baden-Württemberg", + "variant": "recharged", + "players": 5 + }, + "n": 2 + }, + { + "_id": { + "version": 1, + "status": "ended", + "players": 4 + }, + "n": 10 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Quebec", + "variant": "original", + "players": 4 + }, + "n": 14 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "UK & Ireland", + "variant": "original", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Korea", + "variant": "recharged", + "players": 2 + }, + "n": 4 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "USA", + "variant": "recharged", + "players": 3 + }, + "n": 26 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Quebec", + "variant": "recharged", + "players": 2 + }, + "n": 15 + }, + { + "_id": { + "version": 7, + "status": "ended", + "map": "Bremen", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Middle East", + "variant": "recharged", + "players": 2 + }, + "n": 20 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "France", + "variant": "recharged", + "players": 4 + }, + "n": 98 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "Germany", + "variant": "original", + "players": 4 + }, + "n": 2 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Middle East", + "variant": "original", + "players": 2 + }, + "n": 2 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "Spain & Portugal", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "USA", + "variant": "original", + "players": 4 + }, + "n": 44 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "South Africa", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 6, + "status": "ended", + "map": "Germany", + "variant": "recharged", + "players": 2 + }, + "n": 2 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Germany", + "variant": "original", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "UK & Ireland", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Baden-Württemberg", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "USA", + "variant": "original", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 9, + "status": "ended", + "map": "Baden-Württemberg", + "variant": "original", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "USA", + "variant": "recharged", + "players": 3 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "active", + "map": "India", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Japan", + "variant": "original", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Japan", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Bremen", + "variant": "recharged", + "players": 4 + }, + "n": 2 + }, + { + "_id": { + "version": 12, + "status": "ended", + "map": "Northern Europe", + "variant": "recharged", + "players": 4 + }, + "n": 2 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "Northern Europe", + "variant": "original", + "players": 3 + }, + "n": 1 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Northern Europe", + "variant": "recharged", + "players": 2 + }, + "n": 4 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "France", + "variant": "original", + "players": 6 + }, + "n": 4 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "USA", + "variant": "recharged", + "players": 6 + }, + "n": 25 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Germany", + "variant": "original", + "players": 2 + }, + "n": 3 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Benelux", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "France", + "variant": "original", + "players": 2 + }, + "n": 2 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Quebec", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "active", + "map": "Brazil", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Korea", + "variant": "recharged", + "players": 5 + }, + "n": 2 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Japan", + "variant": "original", + "players": 2 + }, + "n": 2 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "France", + "variant": "original", + "players": 5 + }, + "n": 15 + }, + { + "_id": { + "version": 6, + "status": "ended", + "map": "Korea", + "variant": "recharged", + "players": 5 + }, + "n": 3 + }, + { + "_id": { + "version": 2, + "status": "ended", + "map": "USA", + "variant": "original", + "players": 3 + }, + "n": 8 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "North America", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Australia", + "variant": "recharged", + "players": 5 + }, + "n": 2 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Brazil", + "variant": "original", + "players": 5 + }, + "n": 3 + }, + { + "_id": { + "version": 2, + "status": "ended", + "map": "Germany", + "variant": "recharged", + "players": 5 + }, + "n": 5 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "China", + "variant": "original", + "players": 2 + }, + "n": 60 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "USA", + "variant": "original", + "players": 3 + }, + "n": 25 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "India", + "variant": "recharged", + "players": 4 + }, + "n": 40 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Russia", + "variant": "original", + "players": 4 + }, + "n": 7 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "India", + "variant": "original", + "players": 4 + }, + "n": 7 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "UK & Ireland", + "variant": "recharged", + "players": 6 + }, + "n": 3 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Brazil", + "variant": "recharged", + "players": 5 + }, + "n": 46 + }, + { + "_id": { + "version": 7, + "status": "ended", + "map": "North America", + "variant": "original", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 2, + "status": "ended", + "map": "USA", + "variant": "original", + "players": 5 + }, + "n": 13 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Italy", + "variant": "recharged", + "players": 2 + }, + "n": 17 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Italy", + "variant": "recharged", + "players": 3 + }, + "n": 8 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "China", + "variant": "recharged", + "players": 2 + }, + "n": 9 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Brazil", + "variant": "recharged", + "players": 6 + }, + "n": 16 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Europe", + "variant": "original", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Northern Europe", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Middle East", + "variant": "original", + "players": 2 + }, + "n": 54 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Japan", + "variant": "recharged", + "players": 4 + }, + "n": 2 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "India", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "Baden-Württemberg", + "variant": "original", + "players": 4 + }, + "n": 2 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Central Europe", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "France", + "variant": "recharged", + "players": 2 + }, + "n": 21 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Brazil", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "active", + "map": "Europe", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Europe", + "variant": "recharged", + "players": 4 + }, + "n": 2 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Benelux", + "variant": "original", + "players": 6 + }, + "n": 2 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "Korea", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Italy", + "variant": "recharged", + "players": 6 + }, + "n": 19 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "Germany", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Russia", + "variant": "original", + "players": 3 + }, + "n": 3 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Quebec", + "variant": "original", + "players": 2 + }, + "n": 46 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Spain & Portugal", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Quebec", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "Germany", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 13, + "status": "active", + "map": "Australia", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "Central Europe", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "USA", + "variant": "original", + "players": 5 + }, + "n": 19 + }, + { + "_id": { + "version": 2, + "status": "ended", + "map": "USA", + "variant": "original", + "players": 4 + }, + "n": 14 + }, + { + "_id": { + "version": 7, + "status": "ended", + "map": "Russia", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 13, + "status": "active", + "map": "Quebec", + "variant": "original", + "players": 4 + }, + "n": 2 + }, + { + "_id": { + "version": 13, + "status": "active", + "map": "China", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Benelux", + "variant": "original", + "players": 3 + }, + "n": 5 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "Northern Europe", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "Spain & Portugal", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Baden-Württemberg", + "variant": "recharged", + "players": 2 + }, + "n": 3 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "UK & Ireland", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "USA", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 13, + "status": "active", + "map": "France", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Benelux", + "variant": "recharged", + "players": 5 + }, + "n": 44 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "South Africa", + "variant": "original", + "players": 3 + }, + "n": 1 + }, + { + "_id": { + "version": 2, + "status": "ended", + "map": "USA", + "variant": "recharged", + "players": 5 + }, + "n": 5 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "UK & Ireland", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "active", + "map": "Germany", + "variant": "original", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "France", + "variant": "recharged", + "players": 5 + }, + "n": 71 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Central Europe", + "variant": "original", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 6, + "status": "ended", + "map": "UK & Ireland", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Quebec", + "variant": "recharged", + "players": 3 + }, + "n": 9 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "India", + "variant": "original", + "players": 2 + }, + "n": 49 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "China", + "variant": "recharged", + "players": 4 + }, + "n": 27 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Germany", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Korea", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Benelux", + "variant": "original", + "players": 4 + }, + "n": 7 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Germany", + "variant": "original", + "players": 5 + }, + "n": 39 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Brazil", + "variant": "recharged", + "players": 5 + }, + "n": 2 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "South Africa", + "variant": "original", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 2, + "status": "ended", + "map": "Germany", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Benelux", + "variant": "recharged", + "players": 3 + }, + "n": 2 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "France", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Central Europe", + "variant": "original", + "players": 4 + }, + "n": 7 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Spain & Portugal", + "variant": "recharged", + "players": 5 + }, + "n": 2 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Spain & Portugal", + "variant": "original", + "players": 2 + }, + "n": 50 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Brazil", + "variant": "original", + "players": 2 + }, + "n": 51 + }, + { + "_id": { + "version": 1, + "status": "ended", + "players": 3 + }, + "n": 2 + }, + { + "_id": { + "version": 5, + "status": "ended", + "map": "Benelux", + "variant": "recharged", + "players": 3 + }, + "n": 1 + }, + { + "_id": { + "version": 7, + "status": "ended", + "map": "Central Europe", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Germany", + "variant": "recharged", + "players": 3 + }, + "n": 2 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Germany", + "variant": "original", + "players": 6 + }, + "n": 10 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "USA", + "variant": "original", + "players": 2 + }, + "n": 2 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "North America", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "North America", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "Japan", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "France", + "variant": "recharged", + "players": 3 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "France", + "variant": "original", + "players": 2 + }, + "n": 49 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Central Europe", + "variant": "original", + "players": 5 + }, + "n": 6 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Central Europe", + "variant": "recharged", + "players": 5 + }, + "n": 46 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Australia", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Russia", + "variant": "recharged", + "players": 3 + }, + "n": 2 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Brazil", + "variant": "recharged", + "players": 2 + }, + "n": 14 + }, + { + "_id": { + "version": 7, + "status": "ended", + "map": "UK & Ireland", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 7, + "status": "ended", + "map": "Germany", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Korea", + "variant": "recharged", + "players": 5 + }, + "n": 2 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Bremen", + "variant": "recharged", + "players": 2 + }, + "n": 2 + }, + { + "_id": { + "version": 10, + "status": "ended", + "map": "Korea", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Benelux", + "variant": "original", + "players": 5 + }, + "n": 2 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Germany", + "variant": "original", + "players": 4 + }, + "n": 87 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Manhattan", + "variant": "recharged", + "players": 2 + }, + "n": 3 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Manhattan", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Bremen", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Middle East", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "Baden-Württemberg", + "variant": "recharged", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 2, + "status": "ended", + "map": "USA", + "variant": "original", + "players": 6 + }, + "n": 3 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "France", + "variant": "recharged", + "players": 2 + }, + "n": 2 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "China", + "variant": "recharged", + "players": 6 + }, + "n": 10 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Northern Europe", + "variant": "recharged", + "players": 4 + }, + "n": 2 + }, + { + "_id": { + "version": 11, + "status": "active", + "map": "Germany", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 13, + "status": "active", + "map": "USA", + "variant": "recharged", + "players": 5 + }, + "n": 3 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "Japan", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 13, + "status": "active", + "map": "Russia", + "variant": "recharged", + "players": 4 + }, + "n": 1 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "North America", + "variant": "recharged", + "players": 5 + }, + "n": 2 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Italy", + "variant": "recharged", + "players": 5 + }, + "n": 37 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "UK & Ireland", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 11, + "status": "ended", + "map": "Northern Europe", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 13, + "status": "ended", + "map": "Japan", + "variant": "recharged", + "players": 5 + }, + "n": 1 + }, + { + "_id": { + "version": 6, + "status": "ended", + "map": "Brazil", + "variant": "recharged", + "players": 2 + }, + "n": 2 + }, + { + "_id": { + "version": 13, + "status": "active", + "map": "Benelux", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Middle East", + "variant": "original", + "players": 3 + }, + "n": 3 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Germany", + "variant": "recharged", + "players": 5 + }, + "n": 69 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "South Africa", + "variant": "recharged", + "players": 5 + }, + "n": 3 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Germany", + "variant": "recharged", + "players": 4 + }, + "n": 121 + }, + { + "_id": { + "version": 4, + "status": "ended", + "map": "Benelux", + "variant": "recharged", + "players": 6 + }, + "n": 1 + }, + { + "_id": { + "version": 3, + "status": "ended", + "map": "Italy", + "variant": "original", + "players": 4 + }, + "n": 12 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Australia", + "variant": "original", + "players": 2 + }, + "n": 1 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Northern Europe", + "variant": "original", + "players": 2 + }, + "n": 2 + }, + { + "_id": { + "version": 8, + "status": "ended", + "map": "Brazil", + "variant": "original", + "players": 5 + }, + "n": 1 + } + ], + "sample": { + "dataType": "object", + "dataKeys": [ + "map", + "players", + "playerOrder", + "currentPlayers", + "powerPlantsDeck", + "coalSupply", + "oilSupply", + "garbageSupply", + "uraniumSupply", + "coalResupply", + "oilResupply", + "garbageResupply", + "uraniumResupply", + "coalMarket", + "oilMarket", + "garbageMarket", + "uraniumMarket", + "coalPrices", + "oilPrices", + "garbagePrices", + "uraniumPrices", + "actualMarket", + "futureMarket", + "highestBidders", + "step", + "phase", + "options", + "log", + "hiddenLog", + "seed", + "round", + "newTurn", + "auctionSkips", + "citiesToStep2", + "citiesToEndGame", + "resourceResupply", + "paymentTable", + "variant", + "minimunBid", + "plantDiscountActive", + "discardSmallestPlant", + "cardsLeft", + "nextCardWeak", + "card39Bought", + "knownPowerPlantDeck", + "knownPowerPlantDeckStep3", + "automation", + "auctioningPlayer", + "pendingMarketRefill", + "chosenResource" + ], + "game": { + "name": "powergrid", + "version": 13, + "expansions": [], + "options": { + "map": "China", + "variant": "original" + } + }, + "playerFields": [ + "_id", + "remainingTime", + "dropped", + "score", + "name", + "quit", + "faction", + "ranking", + "elo" + ], + "hasSeed": true + } +} diff --git a/ai/evaluate.py b/ai/evaluate.py new file mode 100644 index 0000000..ab4a388 --- /dev/null +++ b/ai/evaluate.py @@ -0,0 +1,73 @@ +import argparse, json, time, platform +from pathlib import Path +import numpy as np +from infer import Model, Node + +p = argparse.ArgumentParser() +p.add_argument("model") +p.add_argument("--seeds", type=int, default=10) +p.add_argument("--opponent", default="heuristic", choices=["heuristic", "legacy"]) +p.add_argument("--output", default="evaluation.json") +args = p.parse_args() +net = None if args.model == "heuristic" else Model(args.model) +node = Node("arena.cjs") +results = [] +latency = [] +start = time.perf_counter() +try: + for variant in ["original", "recharged"]: + for sealed in [False, True]: + for seed in range(args.seeds): + for seat in range(3): + config = { + "op": "reset", + "seed": "heldout-arena-v1-" + str(seed), + "variant": variant, + "sealed": sealed, + "seat": seat, + "opponent": args.opponent, + } + o = node.call(config) + while not o["done"]: + t = time.perf_counter() + action = ( + net.predict(o["state"], o["actions"])[0] + if net + else o["heuristic"] + ) + latency.append((time.perf_counter() - t) * 1000) + o = node.call({"op": "step", "action": action}) + results.append({**config, **o}) + group = [ + r for r in results if r["variant"] == variant and r["sealed"] == sealed + ] + print( + json.dumps( + { + "variant": variant, + "sealed": sealed, + "games": len(group), + "win_rate": np.mean([r["win"] for r in group]), + "truncated": sum(r["truncated"] for r in group), + } + ), + flush=True, + ) +finally: + node.close() +report = { + "model": args.model, + "opponent": args.opponent, + "platform": platform.platform(), + "games": len(results), + "win_rate": np.mean([r["win"] for r in results]), + "truncated": sum(r["truncated"] for r in results), + "seconds": time.perf_counter() - start, + "inference_ms": { + k: float(np.percentile(latency, v)) + for k, v in [("p50", 50), ("p95", 95), ("p99", 99)] + }, + "results": results, +} +Path(args.output).write_text(json.dumps(report, indent=2)) +print(json.dumps({k: v for k, v in report.items() if k != "results"})) diff --git a/ai/export-remote.cjs b/ai/export-remote.cjs new file mode 100644 index 0000000..c8455e9 --- /dev/null +++ b/ai/export-remote.cjs @@ -0,0 +1,63 @@ +const fs = require('node:fs'), + { parseEnv } = require('node:util'), + { createRequire } = require('node:module'), + { createHash } = require('node:crypto'); +const { MongoClient } = createRequire('/home/bgs/boardgamers-mono/apps/api/package.json')('mongodb'); +(async () => { + const env = parseEnv(fs.readFileSync('/home/bgs/boardgamers-mono/apps/api/.env', 'utf8')); + const c = await MongoClient.connect(env.dbUrl); + try { + for await (const g of c + .db(env.dbName || 'bgs') + .collection('games') + .find( + { + 'game.name': 'powergrid', + status: 'ended', + 'game.options.map': 'Germany', + 'options.setup.nbPlayers': 3, + 'options.meta.unlisted': { $ne: true }, + }, + { projection: { _id: 1, game: 1, options: 1, data: 1, players: 1 } } + ) + .maxTimeMS(20000)) { + const d = g.data; + if (!d || typeof d !== 'object') continue; + const cleanPlayer = (p) => ({ + money: p.money, + citiesPowered: p.citiesPowered, + cities: p.cities?.map((c) => c.name).sort(), + powerPlants: p.powerPlants?.map((p) => p.number).sort((a, b) => a - b), + }); + console.log( + JSON.stringify({ + id: createHash('sha256') + .update('powergrid-ai-v1:' + g._id) + .digest('hex') + .slice(0, 20), + version: g.game.version, + options: d.options || g.game.options, + seed: d.seed || g.options.setup.seed, + players: g.players.map((p) => ({ + bot: !!p.isBot, + dropped: !!p.dropped, + quit: !!p.quit, + rating: p.elo?.initial, + ranking: p.ranking, + })), + moves: (d.log || []) + .filter((x) => x.type === 'move') + .map((x) => ({ player: x.player, move: x.move })), + final: d.players.map(cleanPlayer), + phase: d.phase, + round: d.round, + }) + ); + } + } finally { + await c.close(); + } +})().catch((e) => { + console.error(e.name, e.code); + process.exit(1); +}); diff --git a/ai/features.cjs b/ai/features.cjs new file mode 100644 index 0000000..45715e5 --- /dev/null +++ b/ai/features.cjs @@ -0,0 +1,25 @@ +const c = require('./core.cjs'), + readline = require('node:readline'); +(async () => { + for await (const line of readline.createInterface({ input: process.stdin })) { + try { + const q = JSON.parse(line), + g = q.state, + p = q.player; + if (!Number.isInteger(p) || !g.currentPlayers.includes(p)) + throw Error('Player cannot act in this position'); + const moves = c.candidates(g, p); + if (!moves.length) throw Error('No legal actions'); + console.log( + JSON.stringify({ + state: c.observe(g, p), + actions: moves.map((a) => c.actionFeatures(g, p, a)), + moves, + playerOrder: [p, (p + 1) % 3, (p + 2) % 3], + }) + ); + } catch (e) { + console.log(JSON.stringify({ error: e.message })); + } + } +})(); diff --git a/ai/generate.cjs b/ai/generate.cjs new file mode 100644 index 0000000..b77715a --- /dev/null +++ b/ai/generate.cjs @@ -0,0 +1,72 @@ +const fs = require('node:fs'), + c = require('./core.cjs'); +const count = Number(process.env.GAMES || 600), + rng = c.seedrandom('dataset-v1'), + out = fs.openSync(process.argv[2] || 'dataset.jsonl', 'w'); +let samples = 0, + completed = 0, + truncated = 0; +function writeEpisode(rows, g, id) { + const result = c.outcome(g); + for (const row of rows) { + row.value = [row.seat, (row.seat + 1) % 3, (row.seat + 2) % 3].map((i) => result[i]); + row.game = id; + fs.writeSync(out, JSON.stringify(row) + '\n'); + samples++; + } +} +for (let i = 0; i < count; i++) { + let g = c.start('train-v1-' + i, i % 2 ? 'recharged' : 'original', i % 4 < 2), + rows = [], + n = 0; + while (!c.E.ended(g) && n++ < 1600) { + const seat = g.currentPlayers[0], + a = c.candidates(g, seat), + h = c.heuristic(g, seat, rng); + if (a.length > 1 && rng() < 0.4) + rows.push({ + state: c.observe(g, seat), + actions: a.map((x) => c.actionFeatures(g, seat, x)), + target: h.index, + seat, + weight: 1, + }); + let index = rng() < 0.015 ? Math.floor(rng() * a.length) : h.index; + g = c.E.move(g, a[index], seat); + } + if (c.E.ended(g)) { + writeEpisode(rows, g, 'synthetic-' + i); + completed++; + } else truncated++; + if (i % 100 === 99) console.error(JSON.stringify({ games: i + 1, samples, completed, truncated })); +} +const path = 'ai/private-data/verified-games.jsonl'; +if (fs.existsSync(path)) + for (const line of fs.readFileSync(path, 'utf8').split('\n').filter(Boolean)) { + const h = JSON.parse(line); + if (h.options.chooseColors || h.options.chooseRegions || h.options.randomizeMap) { + console.error(JSON.stringify({ skippedHumanGame: h.id, reason: 'unsupported setup' })); + continue; + } + let g = c.E.setup(3, h.options, h.seed), + rows = []; + for (const m of h.moves) { + const seat = m.player, + a = c.candidates(g, seat), + target = a.findIndex( + (x) => JSON.stringify(x.data) === JSON.stringify(m.move.data) && x.name === m.move.name + ); + if (target >= 0 && a.length > 1) + rows.push({ + state: c.observe(g, seat), + actions: a.map((x) => c.actionFeatures(g, seat, x)), + target, + seat, + weight: 1.5, + }); + g = c.E.move(g, m.move, seat); + } + writeEpisode(rows, g, 'human-' + h.id); + } +fs.closeSync(out); +console.error(JSON.stringify({ completed, truncated, samples })); diff --git a/ai/infer.py b/ai/infer.py new file mode 100644 index 0000000..d9f8f42 --- /dev/null +++ b/ai/infer.py @@ -0,0 +1,95 @@ +import json, sys, subprocess, argparse, time, hashlib +from pathlib import Path +import numpy as np +import onnxruntime as ort + +ROOT = Path(__file__).resolve().parents[1] + + +class Model: + def __init__(self, path, threads=1): + self.sha256 = hashlib.sha256(Path(path).read_bytes()).hexdigest() + options = ort.SessionOptions() + options.intra_op_num_threads = threads + options.inter_op_num_threads = 1 + self.session = ort.InferenceSession( + str(path), sess_options=options, providers=["CPUExecutionProvider"] + ) + + def predict(self, state, actions): + a = np.asarray(actions, dtype=np.float32)[None] + s = np.asarray(state, dtype=np.float32)[None] + mask = np.ones(a.shape[:2], dtype=bool) + scores, values = self.session.run( + None, {"state": s, "actions": a, "mask": mask} + ) + return int(scores[0].argmax()), values[0].tolist() + + +class Node: + def __init__(self, script): + self.proc = subprocess.Popen( + ["node", str(ROOT / "ai" / script)], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + text=True, + bufsize=1, + ) + + def call(self, q): + self.proc.stdin.write(json.dumps(q) + "\n") + self.proc.stdin.flush() + line = self.proc.stdout.readline() + if not line: + raise RuntimeError("Engine worker exited") + return json.loads(line) + + def close(self): + self.proc.terminate() + self.proc.wait(timeout=5) + self.proc.stdin.close() + self.proc.stdout.close() + + +if __name__ == "__main__": + p = argparse.ArgumentParser() + p.add_argument("model") + args = p.parse_args() + model = Model(args.model) + node = Node("features.cjs") + try: + for line in sys.stdin: + q = {} + try: + decoded = json.loads(line) + if not isinstance(decoded, dict): + raise ValueError("Request must be a JSON object") + q = decoded + begin = time.perf_counter() + o = node.call(q) + if "error" in o: + raise ValueError(o["error"]) + index, value = model.predict(o["state"], o["actions"]) + print( + json.dumps( + { + "requestId": q.get("requestId"), + "revision": q.get("revision"), + "move": o["moves"][index], + "winProbabilities": value, + "valueStatus": "uncalibrated-selfplay-estimate", + "playerOrder": o["playerOrder"], + "model": Path(args.model).name, + "modelSha256": model.sha256, + "elapsedMs": (time.perf_counter() - begin) * 1000, + } + ), + flush=True, + ) + except Exception as e: + print( + json.dumps({"requestId": q.get("requestId"), "error": str(e)}), + flush=True, + ) + finally: + node.close() diff --git a/ai/launch-profile.sh b/ai/launch-profile.sh new file mode 100755 index 0000000..aca3b6c --- /dev/null +++ b/ai/launch-profile.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +set -euo pipefail +hf jobs run --detach --flavor l4x1 --timeout 2h \ + --secrets HF_TOKEN \ + --env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \ + --env RUN_NAME=profile-v1 --env GAMES=600 --env BC_EPOCHS=12 \ + --env RL_UPDATES=16 --env ENVS=24 --env ROLLOUT_SAMPLES=8000 \ + --label project=powergrid-ai --label stage=profile-v1 \ + -- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc ' +set -euo pipefail +python -m pip install --quiet huggingface_hub onnx onnxruntime +mkdir -p /workspace +python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")" +export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH +python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"profile-source.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")" +cd /workspace +node --test ai/test.cjs +python -u ai/performance.py +' diff --git a/ai/launch-smoke.sh b/ai/launch-smoke.sh new file mode 100755 index 0000000..25caa4d --- /dev/null +++ b/ai/launch-smoke.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +set -euo pipefail +hf jobs run --detach --flavor l4x1 --timeout 2h \ + --secrets HF_TOKEN \ + --env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \ + --env RUN_NAME=optimized-smoke --env GAMES=32 --env BC_EPOCHS=1 \ + --env RL_UPDATES=1 --env ENVS=64 --env WORKERS=4 --env BATCH_SIZE=1024 --env ROLLOUT_SAMPLES=2000 \ + --label project=powergrid-ai --label stage=optimized-smoke \ + -- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc ' +set -euo pipefail +python -m pip install --quiet huggingface_hub onnx +mkdir -p /workspace +python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")" +export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH +python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"source-v2.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")" +cd /workspace +node --test ai/test.cjs +python -u ai/train.py +' diff --git a/ai/launch-v2.sh b/ai/launch-v2.sh new file mode 100755 index 0000000..c0b8430 --- /dev/null +++ b/ai/launch-v2.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +set -euo pipefail +hf jobs run --detach --flavor l4x1 --timeout 2h \ + --secrets HF_TOKEN \ + --env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \ + --env RUN_NAME=baseline-v2 --env GAMES=600 --env BC_EPOCHS=12 \ + --env RL_UPDATES=16 --env ENVS=64 --env WORKERS=4 --env BATCH_SIZE=1024 --env ROLLOUT_SAMPLES=8000 \ + --label project=powergrid-ai --label stage=baseline-v2 \ + -- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc ' +set -euo pipefail +python -m pip install --quiet huggingface_hub onnx +mkdir -p /workspace +python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")" +export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH +python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"source-v4.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")" +cd /workspace +node --test ai/test.cjs +python -u ai/train.py +' diff --git a/ai/launch.sh b/ai/launch.sh new file mode 100755 index 0000000..940763c --- /dev/null +++ b/ai/launch.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +set -euo pipefail +hf jobs run --detach --flavor l4x1 --timeout 2h \ + --secrets HF_TOKEN \ + --env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \ + --env RUN_NAME=baseline-v1 --env GAMES=600 --env BC_EPOCHS=12 \ + --env RL_UPDATES=16 --env ENVS=24 --env ROLLOUT_SAMPLES=8000 \ + --label project=powergrid-ai --label stage=baseline-v1 \ + -- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc ' +set -euo pipefail +python -m pip install --quiet huggingface_hub onnx +mkdir -p /workspace +python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")" +export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH +python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"source-v1.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")" +cd /workspace +node --test ai/test.cjs +python -u ai/train.py +' diff --git a/ai/package-results.py b/ai/package-results.py new file mode 100644 index 0000000..4f1e46b --- /dev/null +++ b/ai/package-results.py @@ -0,0 +1,88 @@ +"""Create the user-facing report from completed, measured runs.""" + +import argparse, json, hashlib, html, shutil, tarfile +from pathlib import Path + +p = argparse.ArgumentParser() +p.add_argument("output") +args = p.parse_args() +out = Path(args.output) +out.mkdir(parents=True, exist_ok=True) +root = Path(__file__).resolve().parents[1] +runs = root / "ai/runs" +model = runs / "download/runs/baseline-v2" +summary = json.loads((runs / "v2-summary.json").read_text()) +profile = json.loads((runs / "download/runs/baseline-v1/profile.json").read_text()) +smoke = json.loads((runs / "8840u-serving-v2.json").read_text().split("\n", 1)[1]) +cpu = json.loads((runs / "8840u-evaluation-v2.json").read_text()) +parity = json.loads((runs / "parity-v2.json").read_text()) +bench = json.loads((runs / "8840u-simulation-v2.json").read_text()) +for name in [ + "v2-summary.json", + "8840u-evaluation-v2.json", + "8840u-serving-v2.json", + "8840u-simulation-v2.json", + "parity-v2.json", +]: + shutil.copy2(runs / name, out / name) +shutil.copy2(root / "ai/README.md", out / "README.md") +shutil.copy2(model / "metrics.json", out / "training-metrics.json") +shutil.copy2(model / "schema.json", out / "schema.json") +bundle = runs / "serving-bundle" +for name in [ + "core.cjs", + "arena.cjs", + "features.cjs", + "infer.py", + "evaluate.py", + "benchmark.cjs", + "test.cjs", + "serving-smoke.py", + "requirements-serve.txt", + "README.md", +]: + shutil.copy2(root / "ai" / name, bundle / "ai" / name) +shutil.copy2(model / "selfplay.onnx", bundle / "selfplay.onnx") +shutil.copy2(model / "schema.json", bundle / "schema.json") +with tarfile.open(out / "powergrid-ai-serving-v2.tgz", "w:gz") as tf: + for item in sorted(bundle.rglob("*")): + if item.is_file() and "__pycache__" not in item.parts: + tf.add(item, arcname=str(item.relative_to(bundle))) +manifest = { + "engine_revision": "365fc519903fa2b4e8c593eed6cc5f5f77b5332a", + "source_dataset_commit": "65ecfa063c272bd72a805d45f4ba55dc84a28f42", + "source_archive": "source-v4.tgz", + "source_sha256": hashlib.sha256((runs / "source-v4.tgz").read_bytes()).hexdigest(), + "job": "https://huggingface.co/jobs/coyotte508/6abd0cba404719ba3761324e", + "schema": 2, + "model_sha256": hashlib.sha256((model / "selfplay.onnx").read_bytes()).hexdigest(), + "deployment": "Research worker only; production bot unchanged", + "files": { + f.name: hashlib.sha256(f.read_bytes()).hexdigest() + for f in out.iterdir() + if f.is_file() and f.name not in ["report.html", "manifest.json"] + }, +} +(out / "manifest.json").write_text(json.dumps(manifest, indent=2)) +rows = "".join( + f"{html.escape(Path(r['model']).stem)}{html.escape(r['opponent'])}{r['win_rate']:.1%}{(format(r['seed_cluster_bootstrap_95pct'][0], '.1%') + '–' + format(r['seed_cluster_bootstrap_95pct'][1], '.1%')) if r['seed_cluster_bootstrap_95pct'] else 'Not estimated (identical outcomes)'}{r['truncated']}" + for r in summary +) +rollouts = profile["rollouts"] +speed = rollouts[2]["decisions_per_second"] / rollouts[0]["decisions_per_second"] +train_speed = ( + profile["training"][1]["samples_per_second"] + / profile["training"][0]["samples_per_second"] +) +report = f'''Powergrid AI baseline

Powergrid AI: executable baseline

30 September 2026 · Germany · 3 players · original / Recharged · open / sealed auctions

CPU deployment is feasible. Playing strength is not ready for production. The existing engine bot remains the baseline to beat. These value estimates are not calibrated for player analysis.

{speed:.1f}×
Rollout throughput improvement in the HF microbenchmark
{train_speed:.1f}×
Optimizer sample throughput with batch 1,024 versus 256
{smoke["warm_end_to_end_ms"]["p95"]:.2f} ms
8840U persistent worker p95, including state encoding and IPC
+

Measured playing strength

Each row is 480 games: 40 unseen seeds × 3 seat rotations × 4 rule combinations. One model faces two bots of the listed type. Ties split win credit. The intervals resample whole seed groups, retaining correlations between seats and rule variants.

{rows}
ModelOpponentsWin share95% seed-bootstrap intervalTruncated

This remains a small baseline experiment. Beating the new heuristic does not establish human-level play; performance against the existing bot is the relevant deployment gate.

+

What was built and checked

+

Why resource utilization was low

The initial configuration used one Node worker, 24 environments and optimizer batches of 256. This compact model alternates simulation and optimization, so GPU work arrives in bursts. Four workers and 256 environments reached {rollouts[2]["decisions_per_second"]:,.0f} decisions/s versus {rollouts[0]["decisions_per_second"]:,.0f}; eight workers offered no gain. Python feature packing and JSON communication still take substantial time.

These are component microbenchmarks, not an end-to-end speedup guarantee. Larger optimizer batches also reduce gradient updates per epoch. The replacement training run uses four workers, 64 environments and batch 1,024; 256 environments are more suitable when collecting substantially larger completed-episode batches.

+

Recommendation

Keep the JS engine authoritative and train on HF Jobs. Run persistent ONNX workers on the 8840U; this model needs neither its GPU nor NPU. Before production, train against the existing bot and a mixture of frozen opponents, use more completed games, and gate releases on held-out arena results. Expand maps/player counts with a new variable-size representation and retraining.

For round-by-round analysis, train and calibrate that target separately. The current three-way value output estimates outcomes under its training opponents; it is not an objective score evaluation.

+

Artifacts

Serving bundle · Setup and worker contract · Evaluation details · Throughput profile · Hashes and provenance · HF training job

One JSONL request chooses one atomic move. The platform must check the game revision, validate the move and commit it through its normal server path. No production routing was changed.

''' +(out / "report.html").write_text(report) +print( + json.dumps( + {"report": str(out / "report.html"), "model_sha256": manifest["model_sha256"]} + ) +) diff --git a/ai/performance.py b/ai/performance.py new file mode 100644 index 0000000..e06624a --- /dev/null +++ b/ai/performance.py @@ -0,0 +1,125 @@ +"""Run on HF Jobs: profile real engine rollouts, GPU batches and ONNX parity.""" + +import concurrent.futures, json, os, subprocess, time +from pathlib import Path +import numpy as np +import torch +import onnxruntime as ort +from huggingface_hub import hf_hub_download, HfApi +import train + +repo = "coyotte508/powergrid-ai-germany-v1" +ck = torch.load( + hf_hub_download(repo, "runs/baseline-v1/imitation.pt"), + map_location="cpu", + weights_only=True, +) +train.AD = ck["action_dim"] +net = train.Policy(ck["state_dim"], train.AD).cuda().eval() +net.load_state_dict(ck["state_dict"]) + + +class Worker: + def __init__(self, i): + self.p = subprocess.Popen( + ["node", "ai/bridge.cjs"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + text=True, + env={**os.environ, "SEED": f"profile-{i}"}, + ) + + def call(self, q): + self.p.stdin.write(json.dumps(q) + "\n") + self.p.stdin.flush() + return json.loads(self.p.stdout.readline()) + + +results = [] +sample = None +for workers, envs in [(1, 24), (1, 256), (4, 256), (8, 256)]: + pool = concurrent.futures.ThreadPoolExecutor(workers) + ws = [Worker(i) for i in range(workers)] + n = envs // workers + current = list(pool.map(lambda w: w.call({"op": "reset", "n": n}), ws)) + timing = {"packing_gpu": 0.0, "engine_ipc": 0.0} + started = time.perf_counter() + decisions = 0 + for step in range(120): + rows = [r for x in current for r in x["observations"]] + t = time.perf_counter() + with torch.no_grad(): + logits, _ = net(*train.tensors(rows)) + choices = ( + torch.distributions.Categorical(logits=logits).sample().cpu().tolist() + ) + timing["packing_gpu"] += time.perf_counter() - t + t = time.perf_counter() + current = list( + pool.map( + lambda pair: pair[1].call( + {"op": "step", "actions": choices[pair[0] * n : (pair[0] + 1) * n]} + ), + enumerate(ws), + ) + ) + timing["engine_ipc"] += time.perf_counter() - t + decisions += len(rows) + seconds = time.perf_counter() - started + entry = { + "workers": workers, + "envs": envs, + "decisions_per_second": decisions / seconds, + "seconds": seconds, + **timing, + } + results.append(entry) + print(json.dumps(entry), flush=True) + sample = rows + for w in ws: + w.p.terminate() + w.p.wait() + pool.shutdown() +# Compare GPU optimization throughput including normal data packing. +optimizer = torch.optim.Adam(net.parameters(), lr=3e-4) +training = [] +for size in [256, 1024]: + rows = (sample * ((size + len(sample) - 1) // len(sample)))[:size] + torch.cuda.synchronize() + t = time.perf_counter() + for _ in range(30): + logits, v = net(*train.tensors(rows)) + loss = -logits.log_softmax(-1)[:, 0].mean() + v.square().mean() + optimizer.zero_grad() + loss.backward() + optimizer.step() + torch.cuda.synchronize() + seconds = time.perf_counter() - t + training.append({"batch": size, "samples_per_second": 30 * size / seconds}) +# Validate original checkpoint export with real observations and varying masks. +net.load_state_dict(ck["state_dict"]) +net.eval() +session = ort.InferenceSession( + hf_hub_download(repo, "runs/baseline-v1/imitation.onnx"), + providers=["CPUExecutionProvider"], +) +errors = [] +for n in [1, 7, 24]: + x = train.tensors(sample[:n]) + feed = dict(zip(["state", "actions", "mask"], [a.cpu().numpy() for a in x])) + actual = session.run(None, feed) + with torch.no_grad(): + expected = [a.cpu().numpy() for a in net(*x)] + errors.append(max(float(np.max(np.abs(a - b))) for a, b in zip(actual, expected))) +assert max(errors) < 1e-4, errors +out = Path("profile.json") +out.write_text( + json.dumps( + {"rollouts": results, "training": training, "onnx_max_abs_error": max(errors)}, + indent=2, + ) +) +print(out.read_text(), flush=True) +HfApi().upload_file( + repo_id=repo, path_or_fileobj=str(out), path_in_repo="runs/baseline-v1/profile.json" +) diff --git a/ai/pool.py b/ai/pool.py new file mode 100644 index 0000000..57625f4 --- /dev/null +++ b/ai/pool.py @@ -0,0 +1,67 @@ +"""Concurrent isolated JS engines with one batched GPU policy call per step.""" + +import json +import os +import subprocess +from concurrent.futures import ThreadPoolExecutor + + +class EnginePool: + def __init__(self, workers=1, seed="rollout-v1"): + self.executor = ThreadPoolExecutor(workers) + self.processes = [ + subprocess.Popen( + ["node", "ai/bridge.cjs"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + text=True, + bufsize=1, + env={**os.environ, "SEED": f"{seed}-worker-{i}"}, + ) + for i in range(workers) + ] + self.sizes = [] + + @staticmethod + def _call(pair): + process, request = pair + process.stdin.write(json.dumps(request) + "\n") + process.stdin.flush() + line = process.stdout.readline() + if not line: + raise RuntimeError("Engine worker exited") + return json.loads(line) + + def call(self, request): + workers = len(self.processes) + if request["op"] == "reset": + n = request["n"] + if n < workers: + raise ValueError("Need at least one environment per worker") + self.sizes = [n // workers + (i < n % workers) for i in range(workers)] + requests = [{"op": "reset", "n": n} for n in self.sizes] + else: + requests = [] + offset = 0 + for n in self.sizes: + requests.append( + {"op": "step", "actions": request["actions"][offset : offset + n]} + ) + offset += n + if offset != len(request["actions"]): + raise ValueError("Incorrect action count") + results = self.executor.map(self._call, zip(self.processes, requests)) + observations, ended, offset = [], [], 0 + for result, n in zip(results, self.sizes): + observations.extend(result["observations"]) + ended.extend({**e, "env": e["env"] + offset} for e in result["ended"]) + offset += n + return {"observations": observations, "ended": ended} + + def close(self): + for process in self.processes: + process.terminate() + process.wait(timeout=5) + process.stdin.close() + process.stdout.close() + self.executor.shutdown() diff --git a/ai/replay-audit.json b/ai/replay-audit.json new file mode 100644 index 0000000..5e4fc01 --- /dev/null +++ b/ai/replay-audit.json @@ -0,0 +1,502 @@ +{ + "total": 66, + "accepted": 33, + "acceptedSealed": 7, + "results": [ + { + "id": "ab995e827dbb1e02ade0", + "version": 11, + "variant": "original", + "sealed": false, + "moves": 318, + "accepted": true + }, + { + "id": "928d7ae9824c4e016bf6", + "version": 8, + "variant": "recharged", + "sealed": true, + "moves": 418, + "accepted": true + }, + { + "id": "143b518757e189efc7e3", + "version": 8, + "variant": "recharged", + "sealed": false, + "moves": 351, + "accepted": true + }, + { + "id": "6fcca63a2d0f6c9b306b", + "version": 5, + "variant": "recharged", + "sealed": false, + "moves": 388, + "accepted": true + }, + { + "id": "607961f608892c628873", + "version": 3, + "variant": "recharged", + "sealed": true, + "moves": 380, + "accepted": true + }, + { + "id": "2af648ee2c81b05daa9c", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "dropped/quit/bot" + }, + { + "id": "19ea5e783adbad9865d4", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "dropped/quit/bot" + }, + { + "id": "549451ce830ac138852f", + "version": 3, + "variant": "original", + "sealed": false, + "moves": 391, + "accepted": true + }, + { + "id": "54e393e828a04be005b8", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "dropped/quit/bot" + }, + { + "id": "d9a4234d28fdb5a8547b", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "not engine terminal" + }, + { + "id": "eb708533d3ebd35d724a", + "version": 3, + "variant": "recharged", + "sealed": false, + "moves": 405, + "accepted": true + }, + { + "id": "d4c097c3d06fe3975517", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "dropped/quit/bot" + }, + { + "id": "210a7d1dfd4b54d11c2c", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "dropped/quit/bot" + }, + { + "id": "c9537b635df301d5d05b", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "dropped/quit/bot" + }, + { + "id": "6f7f5a1973f1476ef44d", + "version": 3, + "variant": "original", + "sealed": true, + "moves": 369, + "accepted": true + }, + { + "id": "44817ee07143fb7704c4", + "version": 3, + "variant": "original", + "sealed": false, + "moves": 434, + "accepted": true + }, + { + "id": "65ddf54509b49a8aa36f", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "dropped/quit/bot" + }, + { + "id": "0f9f19bd7730819956b3", + "version": 3, + "variant": "original", + "sealed": false, + "moves": 440, + "accepted": true + }, + { + "id": "a8250d7cd92ca6e0e8b3", + "version": 3, + "variant": "recharged", + "sealed": false, + "moves": 441, + "accepted": true + }, + { + "id": "3b5968bedb92d0f8bd79", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "dropped/quit/bot" + }, + { + "id": "092879ca1fe46053827e", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "not engine terminal" + }, + { + "id": "6bf265fe48dae34c6101", + "version": 3, + "variant": "recharged", + "sealed": true, + "moves": 372, + "accepted": true + }, + { + "id": "09d086a97424a4a9b912", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "not engine terminal" + }, + { + "id": "0488c48741af557764af", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "not engine terminal" + }, + { + "id": "c448d8a0c7a6c9557f5f", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "not engine terminal" + }, + { + "id": "142899655d055b4bc61e", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "not engine terminal" + }, + { + "id": "e00b68c936f0ccdcd0e7", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "not engine terminal" + }, + { + "id": "9dba6d7432a8f41e6083", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "not engine terminal" + }, + { + "id": "4622adbf48bc58ce9ce2", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "not engine terminal" + }, + { + "id": "4ca01233be2fd72067a0", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "not engine terminal" + }, + { + "id": "2faf87e068025d212b9c", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "not engine terminal" + }, + { + "id": "6cfdadead45769953298", + "version": 3, + "moves": 21, + "accepted": false, + "reason": "Wrong argument for the command Build" + }, + { + "id": "8a881b6eaf108c303025", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "dropped/quit/bot" + }, + { + "id": "8df1a59ac269271dbc46", + "version": 3, + "moves": 22, + "accepted": false, + "reason": "Wrong argument for the command Build" + }, + { + "id": "a74cabc1bba0781fd23f", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "not engine terminal" + }, + { + "id": "1f9f4a3777e43af15c54", + "version": 3, + "moves": 19, + "accepted": false, + "reason": "Wrong argument for the command Build" + }, + { + "id": "d018dbf18dbe82273a6b", + "version": 3, + "variant": "original", + "sealed": true, + "moves": 454, + "accepted": true + }, + { + "id": "72c34fdee48fe10fdc7f", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "not engine terminal" + }, + { + "id": "83416c44fa84004a5f45", + "version": 3, + "variant": "recharged", + "sealed": false, + "moves": 370, + "accepted": true + }, + { + "id": "b76ed70e5aa1ae33b963", + "version": 3, + "variant": "recharged", + "sealed": false, + "moves": 405, + "accepted": true + }, + { + "id": "54d6f0e36f565a708c9b", + "version": 3, + "variant": "recharged", + "sealed": false, + "moves": 390, + "accepted": true + }, + { + "id": "718f4881af994c1faf9a", + "version": 3, + "variant": "original", + "sealed": false, + "moves": 383, + "accepted": true + }, + { + "id": "433cf6558b24a0bbdbf9", + "version": 3, + "variant": "original", + "sealed": false, + "moves": 444, + "accepted": true + }, + { + "id": "eb0cec0a066e8b33bad2", + "version": 3, + "variant": "original", + "sealed": false, + "moves": 405, + "accepted": true + }, + { + "id": "c2894a48c0a27444e114", + "version": 3, + "variant": "original", + "sealed": false, + "moves": 436, + "accepted": true + }, + { + "id": "31610763def175adf40b", + "version": 3, + "variant": "original", + "sealed": false, + "moves": 538, + "accepted": true + }, + { + "id": "1312804c48c9f82aa016", + "version": 3, + "variant": "original", + "sealed": false, + "moves": 482, + "accepted": true + }, + { + "id": "adf42d5b3442634e4caf", + "version": 3, + "variant": "recharged", + "sealed": true, + "moves": 381, + "accepted": true + }, + { + "id": "5068dbfee4b33c649609", + "version": 3, + "variant": "original", + "sealed": false, + "moves": 373, + "accepted": true + }, + { + "id": "933fb07b88c95c2bbe96", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "dropped/quit/bot" + }, + { + "id": "b43887f769649ff3c89d", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "not engine terminal" + }, + { + "id": "6c1d332a20633eea9f94", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "dropped/quit/bot" + }, + { + "id": "dcd4475ef997f56beb6f", + "version": 3, + "variant": "original", + "sealed": false, + "moves": 427, + "accepted": true + }, + { + "id": "e3d7fed6a1e2b332bf0a", + "version": 3, + "variant": "original", + "sealed": false, + "moves": 430, + "accepted": true + }, + { + "id": "32df38734319c7b5dfde", + "version": 3, + "variant": "original", + "sealed": false, + "moves": 392, + "accepted": true + }, + { + "id": "b019571e788c2fc32cd4", + "version": 3, + "variant": "recharged", + "sealed": true, + "moves": 381, + "accepted": true + }, + { + "id": "2b63676563cda6368b48", + "version": 3, + "moves": 144, + "accepted": false, + "reason": "You are not allowed to run the command DiscardPowerPlant" + }, + { + "id": "dc4da51d596babae1a94", + "version": 2, + "variant": "recharged", + "sealed": false, + "moves": 429, + "accepted": true + }, + { + "id": "7034b82777f64af7059a", + "version": 3, + "variant": "original", + "sealed": false, + "moves": 320, + "accepted": true + }, + { + "id": "b42f7181fe6174bfcf9b", + "version": 2, + "moves": 0, + "accepted": false, + "reason": "dropped/quit/bot" + }, + { + "id": "8232d800063a67651177", + "version": 2, + "moves": 0, + "accepted": false, + "reason": "dropped/quit/bot" + }, + { + "id": "0304865b35466d23992c", + "version": 3, + "moves": 0, + "accepted": false, + "reason": "not engine terminal" + }, + { + "id": "b1befc19a57d12d4a1a0", + "version": 2, + "variant": "recharged", + "sealed": false, + "moves": 418, + "accepted": true + }, + { + "id": "6bdc5e3f925879f358b3", + "version": 2, + "moves": 0, + "accepted": false, + "reason": "dropped/quit/bot" + }, + { + "id": "21040a462644ef9ce599", + "version": 2, + "variant": "original", + "sealed": false, + "moves": 397, + "accepted": true + }, + { + "id": "48965364741e57901f71", + "version": 2, + "variant": "original", + "sealed": false, + "moves": 354, + "accepted": true + } + ] +} \ No newline at end of file diff --git a/ai/requirements-serve.txt b/ai/requirements-serve.txt new file mode 100644 index 0000000..78f3eb4 --- /dev/null +++ b/ai/requirements-serve.txt @@ -0,0 +1,2 @@ +numpy==2.4.6 +onnxruntime==1.30.0 diff --git a/ai/serving-smoke.py b/ai/serving-smoke.py new file mode 100644 index 0000000..747216b --- /dev/null +++ b/ai/serving-smoke.py @@ -0,0 +1,48 @@ +"""Exercise the full persistent JSONL worker; validate returned engine actions.""" + +import json, subprocess, sys, time +from pathlib import Path +import numpy as np + +root = Path(__file__).resolve().parents[1] +generate = """const c=require('./ai/core.cjs');for(const variant of ['original','recharged'])for(const sealed of [false,true]){let g=c.start('serving-smoke',variant,sealed),rng=c.seedrandom('smoke'),seen=new Set();for(let n=0;n<1600&&!c.E.ended(g);n++){const p=g.currentPlayers[0],key=g.phase+':'+Math.min(g.round,3);if(!seen.has(key)){seen.add(key);console.log(JSON.stringify({state:g,player:p,revision:n,requestId:variant+'-'+sealed+'-'+n}));}g=c.E.move(g,c.heuristic(g,p,rng).action,p);}}""" +requests = [ + json.loads(l) + for l in subprocess.check_output( + ["node", "-e", generate], cwd=root, text=True + ).splitlines() +] +p = subprocess.Popen( + [sys.executable, str(root / "ai/infer.py"), sys.argv[1]], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + text=True, +) +latency = [] +checks = [] +for q in requests: + t = time.perf_counter() + p.stdin.write(json.dumps(q) + "\n") + p.stdin.flush() + r = json.loads(p.stdout.readline()) + latency.append((time.perf_counter() - t) * 1000) + assert "error" not in r, r + assert r["requestId"] == q["requestId"] and r["revision"] == q["revision"] + assert abs(sum(r["winProbabilities"]) - 1) < 1e-5 + checks.append({"state": q["state"], "player": q["player"], "move": r["move"]}) +p.stdin.close() +p.wait(timeout=10) +validate = """const c=require('./ai/core.cjs'),fs=require('fs');for(const q of JSON.parse(fs.readFileSync(0,'utf8'))){if(!c.allLegal(q.state,q.player).some(x=>JSON.stringify(x)===JSON.stringify(q.move)))throw Error('Illegal move');c.E.move(q.state,q.move,q.player);}console.log('all legal');""" +subprocess.run( + ["node", "-e", validate], input=json.dumps(checks), cwd=root, text=True, check=True +) +report = { + "requests": len(requests), + "first_request_including_startup_ms": latency[0], + "warm_end_to_end_ms": { + k: float(np.percentile(latency[1:], v)) + for k, v in [("p50", 50), ("p95", 95), ("p99", 99)] + }, + "all_moves_legal": True, +} +print(json.dumps(report, indent=2)) diff --git a/ai/summarize.py b/ai/summarize.py new file mode 100644 index 0000000..0f318da --- /dev/null +++ b/ai/summarize.py @@ -0,0 +1,50 @@ +"""Aggregate arenas with confidence intervals clustered by shared game seed.""" + +import argparse, json +from pathlib import Path +import numpy as np + +p = argparse.ArgumentParser() +p.add_argument("files", nargs="+") +args = p.parse_args() +summaries = [] +for file in args.files: + r = json.loads(Path(file).read_text()) + groups = {} + for row in r["results"]: + groups.setdefault(row["seed"], []).append(row["win"]) + means = np.array([np.mean(xs) for xs in groups.values()]) + rng = np.random.default_rng(171) + ci = np.percentile( + rng.choice(means, (10000, len(means))).mean(axis=1), [2.5, 97.5] + ).tolist() + degenerate = bool(np.all(means == means[0])) + if degenerate: + ci = None + summaries.append( + { + **{k: v for k, v in r.items() if k != "results"}, + "seed_cluster_bootstrap_95pct": ci, + "interval_note": "Not estimated: identical seed outcomes make percentile bootstrap degenerate" + if degenerate + else "Percentile bootstrap over shared seeds", + "by_rules": [ + { + "variant": variant, + "sealed": sealed, + "win_share": float( + np.mean( + [ + x["win"] + for x in r["results"] + if x["variant"] == variant and x["sealed"] == sealed + ] + ) + ), + } + for variant in ["original", "recharged"] + for sealed in [False, True] + ], + } + ) +print(json.dumps(summaries, indent=2)) diff --git a/ai/test.cjs b/ai/test.cjs new file mode 100644 index 0000000..9f19526 --- /dev/null +++ b/ai/test.cjs @@ -0,0 +1,81 @@ +const test = require('node:test'), + assert = require('node:assert/strict'), + c = require('./core.cjs'); +test('hidden deck, seed, premoves and sealed bids cannot change observations or candidates', () => { + let g = c.start('privacy', 'original', true); + g = c.E.move(g, c.candidates(g, g.currentPlayers[0])[0], g.currentPlayers[0]); + const p = g.currentPlayers[0], + a = c.observe(g, p), + moves = c.candidates(g, p).map((m) => c.actionFeatures(g, p, m)); + g.seed = 'do not use'; + g.powerPlantsDeck.reverse(); + g.hiddenLog = [{ secret: 123 }]; + g.automation = { plans: { 1: { secret: 321 } } }; + g.currentBid = 999; + g.players.forEach((x, i) => { + if (i !== p) x.bid = 987 + i; + }); + assert.deepEqual(c.observe(g, p), a); + assert.deepEqual( + c.candidates(g, p).map((m) => c.actionFeatures(g, p, m)), + moves + ); +}); +test('original/recharged and sealed/open produce finite fixed features and legal complete games', () => { + for (let seed = 0; seed < 16; seed++) { + let g = c.start('test-' + seed, seed % 2 ? 'original' : 'recharged', seed % 4 < 2), + rng = c.seedrandom('bot' + seed), + steps = 0; + while (!c.E.ended(g) && steps++ < 1600) { + const p = g.currentPlayers[0], + a = c.candidates(g, p); + assert.equal(c.observe(g, p).length, 541); + for (const m of a) { + const f = c.actionFeatures(g, p, m); + assert.equal(f.length, 74); + assert.ok(f.every(Number.isFinite)); + } + g = c.E.move(g, c.heuristic(g, p, rng).action, p); + } + assert.ok(c.E.ended(g)); + assert.equal( + c.outcome(g).reduce((a, b) => a + b, 0), + 1 + ); + } +}); +test('seeded heuristic runs reproduce terminal state', () => { + function run() { + let g = c.start('repeat', 'recharged', true), + r = c.seedrandom('tie'); + for (let i = 0; i < 1600 && !c.E.ended(g); i++) { + const p = g.currentPlayers[0]; + g = c.E.move(g, c.heuristic(g, p, r).action, p); + } + return JSON.stringify(g); + } + assert.equal(run(), run()); +}); + +test('unsupported maps, player counts and drafts are rejected', () => { + for (const options of [{ map: 'USA' }, { randomizeMap: true }, { chooseRegions: true }, { chooseColors: true }]) { + const g = c.E.setup(3, { map: 'Germany', ...options }, 'scope'); + assert.throws(() => c.observe(g, g.currentPlayers[0]), /Baseline supports/); + } + const g = c.E.setup(4, { map: 'Germany' }, 'scope'); + assert.throws(() => c.observe(g, g.currentPlayers[0]), /Baseline supports/); +}); + +test('Recharged replacement cities have distinct action features', () => { + const g = c.start('city-encoding', 'recharged'); + for (const [replacement, original] of [ + ['Stralsund', 'Torgelow'], + ['Mainz', 'Wiesbaden'], + ]) { + assert.ok(c.CITIES.includes(replacement)); + assert.notDeepEqual( + c.actionFeatures(g, 0, { name: 'Build', data: { name: replacement, price: 10 } }), + c.actionFeatures(g, 0, { name: 'Build', data: { name: original, price: 10 } }) + ); + } +}); diff --git a/ai/test_pool.py b/ai/test_pool.py new file mode 100644 index 0000000..b123108 --- /dev/null +++ b/ai/test_pool.py @@ -0,0 +1,32 @@ +"""Exercise uneven sharding and terminal episode ownership without training.""" + +import unittest +from pool import EnginePool + + +class PoolTest(unittest.TestCase): + def test_uneven_shards_complete_legal_games(self): + pool = EnginePool(4, seed="pool-regression") + try: + reply = pool.call({"op": "reset", "n": 25}) + finished = set() + for _ in range(1000): + self.assertEqual(len(reply["observations"]), 25) + reply = pool.call( + { + "op": "step", + "actions": [o["heuristic"] for o in reply["observations"]], + } + ) + for end in reply["ended"]: + self.assertFalse(end["truncated"]) + self.assertTrue(0 <= end["env"] < 25) + self.assertAlmostEqual(sum(end["value"]), 1) + finished.add(end["env"]) + self.assertEqual(finished, set(range(25))) + finally: + pool.close() + + +if __name__ == "__main__": + unittest.main() diff --git a/ai/train.py b/ai/train.py new file mode 100644 index 0000000..5c7fbdb --- /dev/null +++ b/ai/train.py @@ -0,0 +1,283 @@ +import os, json, random, hashlib, subprocess, time, copy +from pathlib import Path +import numpy as np +import torch +from torch import nn +from torch.distributions import Categorical + +random.seed(7) +np.random.seed(7) +torch.manual_seed(7) +torch.set_num_threads(4) +BATCH_SIZE = int(os.getenv("BATCH_SIZE", "256")) +DEVICE = "cuda" if torch.cuda.is_available() else "cpu" + + +class Policy(nn.Module): + def __init__(self, sd, ad): + super().__init__() + self.state = nn.Sequential( + nn.Linear(sd, 512), nn.Tanh(), nn.Linear(512, 256), nn.Tanh() + ) + self.action = nn.Sequential(nn.Linear(ad, 128), nn.Tanh()) + self.score = nn.Sequential(nn.Linear(384, 128), nn.Tanh(), nn.Linear(128, 1)) + self.value = nn.Linear(256, 3) + + def forward(self, state, actions, mask): + s = self.state(state) + a = self.action(actions) + logits = self.score( + torch.cat((s[:, None, :].expand(-1, a.shape[1], -1), a), -1) + ).squeeze(-1) + return logits.masked_fill(~mask, -1e9), self.value(s).softmax(-1) + + +def tensors(rows): + states = torch.tensor( + np.asarray([r["state"] for r in rows], dtype=np.float32), device=DEVICE + ) + m = max(len(r["actions"]) for r in rows) + a = np.zeros((len(rows), m, AD), np.float32) + mask = np.zeros((len(rows), m), bool) + for i, r in enumerate(rows): + a[i, : len(r["actions"])] = r["actions"] + mask[i, : len(r["actions"])] = True + return states, torch.tensor(a, device=DEVICE), torch.tensor(mask, device=DEVICE) + + +def split(game): + return int(hashlib.sha256(game.encode()).hexdigest()[:8], 16) % 5 == 0 + + +if __name__ == "__main__": + out = Path(os.environ.get("OUT", "ai/runs/baseline")) + out.mkdir(parents=True, exist_ok=True) + if not Path("dataset.jsonl").exists(): + subprocess.run(["node", "ai/generate.cjs", "dataset.jsonl"], check=True) + rows = [json.loads(l) for l in open("dataset.jsonl")] + SD = len(rows[0]["state"]) + AD = len(rows[0]["actions"][0]) + train = [r for r in rows if not split(r["game"])] + valid = [r for r in rows if split(r["game"])] + net = Policy(SD, AD).to(DEVICE) + opt = torch.optim.Adam(net.parameters(), lr=3e-4) + metrics = [] + + def save(name): + torch.save( + {"state_dim": SD, "action_dim": AD, "state_dict": net.cpu().state_dict()}, + out / (name + ".pt"), + ) + net.to(DEVICE) + + print( + json.dumps( + { + "device": DEVICE, + "training": len(train), + "validation": len(valid), + "parameters": sum(p.numel() for p in net.parameters()), + } + ), + flush=True, + ) + for epoch in range(int(os.getenv("BC_EPOCHS", "12"))): + random.shuffle(train) + net.train() + losses = [] + for k in range(0, len(train), BATCH_SIZE): + b = train[k : k + BATCH_SIZE] + logits, v = net(*tensors(b)) + target = torch.tensor([r["target"] for r in b], device=DEVICE) + value = torch.tensor([r["value"] for r in b], device=DEVICE) + w = torch.tensor([r["weight"] for r in b], device=DEVICE) + loss = ( + nn.functional.cross_entropy(logits, target, reduction="none") * w + ).mean() + 0.5 * ((v - value) ** 2).mean() + opt.zero_grad() + loss.backward() + nn.utils.clip_grad_norm_(net.parameters(), 1) + opt.step() + losses.append(loss.item()) + correct = total = 0 + vl = [] + net.eval() + with torch.no_grad(): + for k in range(0, len(valid), 256): + b = valid[k : k + 256] + l, v = net(*tensors(b)) + correct += ( + (l.argmax(-1).cpu().numpy() == [r["target"] for r in b]) + .sum() + .item() + ) + total += len(b) + vl.append( + ((v.cpu().numpy() - np.array([r["value"] for r in b])) ** 2) + .mean() + .item() + ) + entry = { + "stage": "bc", + "epoch": epoch, + "loss": float(np.mean(losses)), + "heldout_action_accuracy": correct / total, + "heldout_value_mse": float(np.mean(vl)), + } + metrics.append(entry) + print(json.dumps(entry), flush=True) + save("imitation") + teacher = copy.deepcopy(net).eval() + from pool import EnginePool + + pool = EnginePool(int(os.getenv("WORKERS", "1"))) + rpc = pool.call + nenv = int(os.getenv("ENVS", "24")) + current = rpc({"op": "reset", "n": nenv})["observations"] + pending = [[] for _ in range(nenv)] + completed = 0 + for update in range(int(os.getenv("RL_UPDATES", "24"))): + batch = [] + start = time.time() + truncated = 0 + while len(batch) < int(os.getenv("ROLLOUT_SAMPLES", "8000")): + with torch.no_grad(): + x = tensors(current) + logits, v = net(*x) + dist = Categorical(logits=logits) + actions = dist.sample() + logps = dist.log_prob(actions) + for i, r in enumerate(current): + pending[i].append( + { + **r, + "choice": actions[i].item(), + "oldlogp": logps[i].item(), + "oldvalue": v[i, 0].item(), + } + ) + result = rpc({"op": "step", "actions": actions.tolist()}) + current = result["observations"] + for end in result["ended"]: + i = end["env"] + completed += 1 + if end["truncated"]: + truncated += 1 + else: + for r in pending[i]: + seat = r["seat"] + r["value"] = [end["value"][(seat + j) % 3] for j in range(3)] + r["advantage"] = r["value"][0] - r["oldvalue"] + batch.append(r) + pending[i] = [] + # Freeze the rollout policy during collection; never reuse unfinished episodes across updates. + current = rpc({"op": "reset", "n": nenv})["observations"] + pending = [[] for _ in range(nenv)] + rollout_seconds = time.time() - start + optimization_start = time.time() + adv = np.array([r["advantage"] for r in batch]) + mean, std = float(adv.mean()), float(adv.std() + 1e-6) + for epoch in range(3): + random.shuffle(batch) + for k in range(0, len(batch), BATCH_SIZE): + b = batch[k : k + BATCH_SIZE] + x = tensors(b) + logits, v = net(*x) + dist = Categorical(logits=logits) + act = torch.tensor([r["choice"] for r in b], device=DEVICE) + old = torch.tensor([r["oldlogp"] for r in b], device=DEVICE) + advantage = torch.tensor( + [(r["advantage"] - mean) / std for r in b], device=DEVICE + ) + target = torch.tensor([r["value"] for r in b], device=DEVICE) + ratio = (dist.log_prob(act) - old).exp() + policy = -torch.minimum( + ratio * advantage, ratio.clamp(0.8, 1.2) * advantage + ).mean() + with torch.no_grad(): + tl, _ = teacher(*x) + kl = nn.functional.kl_div( + logits.log_softmax(-1), tl.softmax(-1), reduction="batchmean" + ) + loss = ( + policy + + 0.5 * ((v - target) ** 2).mean() + - 0.005 * dist.entropy().mean() + + 0.05 * kl + ) + opt.zero_grad() + loss.backward() + nn.utils.clip_grad_norm_(net.parameters(), 1) + opt.step() + entry = { + "stage": "selfplay_ppo", + "update": update, + "episodes_total": completed, + "truncated": truncated, + "samples": len(batch), + "seconds": round(time.time() - start, 2), + "rollout_seconds": rollout_seconds, + "optimization_seconds": time.time() - optimization_start, + } + metrics.append(entry) + print(json.dumps(entry), flush=True) + if update % 4 == 3: + save("selfplay-" + str(update + 1)) + pool.close() + save("selfplay") + net.cpu().eval() + # Export both imitation and final RL checkpoints; evaluation selects the serving model. + for name in ["imitation", "selfplay"]: + ck = torch.load(out / (name + ".pt"), map_location="cpu", weights_only=True) + net.load_state_dict(ck["state_dict"]) + net.eval() + torch.onnx.export( + net, + ( + torch.zeros(1, SD), + torch.zeros(1, 8, AD), + torch.ones(1, 8, dtype=torch.bool), + ), + str(out / (name + ".onnx")), + input_names=["state", "actions", "mask"], + output_names=["logits", "value"], + dynamic_axes={ + "state": {0: "batch"}, + "actions": {0: "batch", 1: "candidates"}, + "mask": {0: "batch", 1: "candidates"}, + "logits": {0: "batch", 1: "candidates"}, + "value": {0: "batch"}, + }, + opset_version=17, + dynamo=False, + ) + (out / "metrics.json").write_text(json.dumps(metrics, indent=2)) + (out / "schema.json").write_text( + json.dumps( + { + "version": 2, + "state_dim": SD, + "action_dim": AD, + "map": "Germany", + "players": 3, + "variants": ["original", "recharged"], + "fastBid": [False, True], + "money": "all players visible", + "hidden": [ + "seed", + "deck order", + "opponent bids when sealed", + "queued moves", + ], + }, + indent=2, + ) + ) + if os.getenv("HF_MODEL_REPO"): + from huggingface_hub import HfApi + + HfApi().upload_folder( + repo_id=os.environ["HF_MODEL_REPO"], + folder_path=str(out), + path_in_repo="runs/" + os.environ.get("RUN_NAME", "baseline"), + ) diff --git a/ai/verify-export.py b/ai/verify-export.py new file mode 100644 index 0000000..58c66b5 --- /dev/null +++ b/ai/verify-export.py @@ -0,0 +1,57 @@ +"""CPU inference-only parity check of trained checkpoints versus exported ONNX.""" + +import argparse, json, subprocess +from pathlib import Path +import numpy as np +import torch +import onnxruntime as ort +import train + +p = argparse.ArgumentParser() +p.add_argument("directory") +args = p.parse_args() +root = Path(__file__).resolve().parents[1] +script = """const c=require('./ai/core.cjs');for(const variant of ['original','recharged'])for(const sealed of [false,true]){let g=c.start('parity',variant,sealed),rng=c.seedrandom('parity');for(let i=0;i<240&&!c.E.ended(g);i++){const p=g.currentPlayers[0],a=c.candidates(g,p);if(i%10===0)console.log(JSON.stringify({state:c.observe(g,p),actions:a.map(x=>c.actionFeatures(g,p,x))}));g=c.E.move(g,c.heuristic(g,p,rng).action,p);}}""" +rows = [ + json.loads(l) + for l in subprocess.check_output( + ["node", "-e", script], cwd=root, text=True + ).splitlines() +] +train.DEVICE = "cpu" +results = {} +for name in ["imitation", "selfplay"]: + ck = torch.load( + Path(args.directory) / (name + ".pt"), map_location="cpu", weights_only=True + ) + train.AD = ck["action_dim"] + net = train.Policy(ck["state_dim"], train.AD).eval() + net.load_state_dict(ck["state_dict"]) + opts = ort.SessionOptions() + opts.intra_op_num_threads = 1 + session = ort.InferenceSession( + str(Path(args.directory) / (name + ".onnx")), + sess_options=opts, + providers=["CPUExecutionProvider"], + ) + errors = [] + matches = 0 + for n in [1, 7, 24, len(rows)]: + x = train.tensors(rows[:n]) + actual = session.run( + None, dict(zip(["state", "actions", "mask"], [t.numpy() for t in x])) + ) + with torch.no_grad(): + expected = [t.numpy() for t in net(*x)] + errors.append( + max(float(np.max(np.abs(a - b))) for a, b in zip(actual, expected)) + ) + assert np.array_equal(actual[0].argmax(-1), expected[0].argmax(-1)) + matches += n + assert max(errors) < 1e-4, errors + results[name] = { + "max_abs_error": max(errors), + "matching_decisions": matches, + "batch_sizes": [1, 7, 24, len(rows)], + } +print(json.dumps(results, indent=2))