Integrate AI research and harden analysis autoplay
This commit is contained in:
commit
1e73e53664
147 changed files with 52071 additions and 9049 deletions
10
.gitignore
vendored
10
.gitignore
vendored
|
|
@ -5,3 +5,13 @@ viewer/public/*.jpg
|
|||
viewer/public/*.jpeg
|
||||
viewer/public/*.png
|
||||
.pnpm-store
|
||||
|
||||
ai/private-data/
|
||||
ai/runs/
|
||||
ai/.venv/
|
||||
|
||||
source-bundle/
|
||||
|
||||
ai/__pycache__/
|
||||
ai/strong/__pycache__/
|
||||
serving-bundle/
|
||||
|
|
|
|||
15
AGENTS.md
Normal file
15
AGENTS.md
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
# Agent instructions
|
||||
|
||||
## BGS publication and Git delivery
|
||||
|
||||
Whenever changes are published to BGS, commit the corresponding source, tests,
|
||||
dependency/lockfile changes and version bumps, then push them to this repository's
|
||||
`main` or `master` release branch in the same task. A BGS upload or a push only to
|
||||
a feature branch does not complete delivery. This is standing authorization to
|
||||
commit and push published changes without asking for separate confirmation.
|
||||
|
||||
Fetch and integrate the latest release-branch changes, run the relevant repository
|
||||
checks, and push without force. Update any public mirrors required by this repo's
|
||||
existing workflow too. Keep credentials, generated artifacts excluded by the repo,
|
||||
and unrelated unfinished work out of the commit. Verify the remote branch contains
|
||||
the delivered commit and report any blocker instead of claiming delivery.
|
||||
87
ai/README.md
Normal file
87
ai/README.md
Normal file
|
|
@ -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 `pip install -r ai/requirements-serve.txt` for serving. Verified runtimes: Python 3.11 / NumPy 2.4.6 on the laptop; Python 3.12 / NumPy 2.5.3 on the 8840U; ONNX Runtime 1.30.0 on both. 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": <authoritative raw engine 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.
|
||||
55
ai/arena.cjs
Normal file
55
ai/arena.cjs
Normal file
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
})();
|
||||
59
ai/audit-remote.cjs
Normal file
59
ai/audit-remote.cjs
Normal file
|
|
@ -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);
|
||||
});
|
||||
54
ai/audit-replays.cjs
Normal file
54
ai/audit-replays.cjs
Normal file
|
|
@ -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;
|
||||
}, {}),
|
||||
});
|
||||
35
ai/benchmark.cjs
Normal file
35
ai/benchmark.cjs
Normal file
|
|
@ -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));
|
||||
54
ai/bridge.cjs
Normal file
54
ai/bridge.cjs
Normal file
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
})();
|
||||
239
ai/core-v2.cjs
Normal file
239
ai/core-v2.cjs
Normal file
|
|
@ -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,
|
||||
};
|
||||
250
ai/core.cjs
Normal file
250
ai/core.cjs
Normal file
|
|
@ -0,0 +1,250 @@
|
|||
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 : a.name === 'BuyResource' ? resourcePrice(g, d.resource) : 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 resourcePrice(g, resource, offset = 0) {
|
||||
const prices = g[resource + 'Prices'];
|
||||
const count = g[resource + 'Market'];
|
||||
return prices && count > offset ? prices[prices.length - count + offset] : 20;
|
||||
}
|
||||
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 = resourcePrice(g, 'coal') <= resourcePrice(g, 'oil') ? 'coal' : 'oil';
|
||||
if (resource) need[resource] += pp.cost;
|
||||
}
|
||||
return need;
|
||||
}
|
||||
function fuelCost(g, pp) {
|
||||
return (
|
||||
pp.cost *
|
||||
(pp.type === 4
|
||||
? Math.min(resourcePrice(g, 'coal'), resourcePrice(g, 'oil'))
|
||||
: RES[pp.type]
|
||||
? resourcePrice(g, RES[pp.type])
|
||||
: 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),
|
||||
price = resourcePrice(g, d.resource);
|
||||
return p[d.resource + 'Left'] < need[d.resource] && p.money - price >= Math.max(0, p.cities.length ? 0 : 12)
|
||||
? 20 - 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 + resourcePrice(g, r), 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,
|
||||
resourcePrice,
|
||||
fuelDemand,
|
||||
fuelCost,
|
||||
capacity,
|
||||
};
|
||||
4322
ai/data-audit.json
Normal file
4322
ai/data-audit.json
Normal file
File diff suppressed because it is too large
Load diff
73
ai/evaluate.py
Normal file
73
ai/evaluate.py
Normal file
|
|
@ -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"}))
|
||||
63
ai/export-remote.cjs
Normal file
63
ai/export-remote.cjs
Normal file
|
|
@ -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);
|
||||
});
|
||||
25
ai/features.cjs
Normal file
25
ai/features.cjs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
const c = require('./core-v2.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 }));
|
||||
}
|
||||
}
|
||||
})();
|
||||
72
ai/generate.cjs
Normal file
72
ai/generate.cjs
Normal file
|
|
@ -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 }));
|
||||
95
ai/infer.py
Normal file
95
ai/infer.py
Normal file
|
|
@ -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()
|
||||
19
ai/launch-profile.sh
Executable file
19
ai/launch-profile.sh
Executable file
|
|
@ -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
|
||||
'
|
||||
19
ai/launch-smoke.sh
Executable file
19
ai/launch-smoke.sh
Executable file
|
|
@ -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
|
||||
'
|
||||
19
ai/launch-v2.sh
Executable file
19
ai/launch-v2.sh
Executable file
|
|
@ -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
|
||||
'
|
||||
19
ai/launch.sh
Executable file
19
ai/launch.sh
Executable file
|
|
@ -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
|
||||
'
|
||||
88
ai/package-results.py
Normal file
88
ai/package-results.py
Normal file
|
|
@ -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"<tr><td>{html.escape(Path(r['model']).stem)}</td><td>{html.escape(r['opponent'])}</td><td>{r['win_rate']:.1%}</td><td>{(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)'}</td><td>{r['truncated']}</td></tr>"
|
||||
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'''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Powergrid AI baseline</title><style>body{{font:17px/1.6 system-ui,sans-serif;max-width:1050px;margin:40px auto;padding:0 24px;color:#19302a;background:#f5f7f2}}h1,h2{{line-height:1.2}}.cards{{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px}}.card,section{{background:white;padding:22px;border:1px solid #d4e1d8;border-radius:12px;margin:16px 0}}.metric{{font-size:30px;font-weight:700}}table{{width:100%;border-collapse:collapse;font-size:15px}}th,td{{padding:10px;text-align:left;border-bottom:1px solid #d4e1d8}}.scroll{{overflow:auto}}a{{color:#176145}}code{{overflow-wrap:anywhere}}.note{{background:#fff4da;padding:18px;border-radius:8px}}</style><h1>Powergrid AI: executable baseline</h1><p>30 September 2026 · Germany · 3 players · original / Recharged · open / sealed auctions</p><p class="note"><b>CPU deployment is feasible. Playing strength is not ready for production.</b> The existing engine bot remains the baseline to beat. These value estimates are not calibrated for player analysis.</p><div class="cards"><div class="card"><div class="metric">{speed:.1f}×</div>Rollout throughput improvement in the HF microbenchmark</div><div class="card"><div class="metric">{train_speed:.1f}×</div>Optimizer sample throughput with batch 1,024 versus 256</div><div class="card"><div class="metric">{smoke["warm_end_to_end_ms"]["p95"]:.2f} ms</div>8840U persistent worker p95, including state encoding and IPC</div></div>
|
||||
<section><h2>Measured playing strength</h2><p>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.</p><div class="scroll"><table><tr><th>Model</th><th>Opponents</th><th>Win share</th><th>95% seed-bootstrap interval</th><th>Truncated</th></tr>{rows}</table></div><p>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.</p></section>
|
||||
<section><h2>What was built and checked</h2><ul><li>Reproducible JavaScript simulator, heuristic, masked candidate-scoring policy, whole-game imitation split, multi-player self-play, ONNX export and CPU worker.</li><li>All 4,007 game records counted. 66 candidate Germany replays inspected; 33 match the current engine exactly. Corrected training uses 32 supported historical games, with one color-draft game excluded.</li><li>Schema v2 covers both Germany city lists (44 cities), including the Recharged replacements Mainz and Stralsund. Bids remain sealed in model observations; other players’ money is intentionally visible.</li><li>{smoke["requests"]} end-to-end worker requests returned legal actions; {cpu["games"]} CPU arena games completed on the 8840U. Pure model inference p95: {cpu["inference_ms"]["p95"]:.3f} ms. Cold first request: {smoke["first_request_including_startup_ms"]:.0f} ms.</li><li>PyTorch / ONNX maximum absolute error: {max(x["max_abs_error"] for x in parity.values()):.2g}; all checked action choices agree.</li><li><code>minipc-wg</code> now reaches the verified 8840U at WireGuard address <code>10.90.0.3</code>.</li></ul></section>
|
||||
<section><h2>Why resource utilization was low</h2><p>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.</p><p>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.</p></section>
|
||||
<section><h2>Recommendation</h2><p>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.</p><p>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.</p></section>
|
||||
<section><h2>Artifacts</h2><p><a href="powergrid-ai-serving-v2.tgz">Serving bundle</a> · <a href="README.md">Setup and worker contract</a> · <a href="v2-summary.json">Evaluation details</a> · <a href="throughput-profile.json">Throughput profile</a> · <a href="manifest.json">Hashes and provenance</a> · <a href="{manifest["job"]}">HF training job</a></p><p>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.</p></section></html>'''
|
||||
(out / "report.html").write_text(report)
|
||||
print(
|
||||
json.dumps(
|
||||
{"report": str(out / "report.html"), "model_sha256": manifest["model_sha256"]}
|
||||
)
|
||||
)
|
||||
125
ai/performance.py
Normal file
125
ai/performance.py
Normal file
|
|
@ -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"
|
||||
)
|
||||
71
ai/pool.py
Normal file
71
ai/pool.py
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
"""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", script="ai/bridge.cjs"):
|
||||
self.executor = ThreadPoolExecutor(workers)
|
||||
self.processes = [
|
||||
subprocess.Popen(
|
||||
["node", script],
|
||||
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 = []
|
||||
offset = request.get("offset", 0)
|
||||
for n in self.sizes:
|
||||
requests.append({**request, "n": n, "offset": offset})
|
||||
offset += n
|
||||
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()
|
||||
502
ai/replay-audit.json
Normal file
502
ai/replay-audit.json
Normal file
|
|
@ -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
|
||||
}
|
||||
]
|
||||
}
|
||||
3
ai/requirements-serve.txt
Normal file
3
ai/requirements-serve.txt
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
numpy==2.4.6; python_version < "3.12"
|
||||
numpy==2.5.3; python_version >= "3.12"
|
||||
onnxruntime==1.30.0
|
||||
48
ai/serving-smoke.py
Normal file
48
ai/serving-smoke.py
Normal file
|
|
@ -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))
|
||||
101
ai/strong/README.md
Normal file
101
ai/strong/README.md
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
# Strong-policy research (active)
|
||||
|
||||
The target is substantially stronger play, not merely beating the engine's default bot. No strength claim is made from the first prototype. Training runs on HF Jobs; CPU inference and correctness checks run locally and on the 8840U.
|
||||
|
||||
## Critical diagnosis
|
||||
|
||||
The first heuristic incorrectly read `BuyResource.data.price`, which the engine does not provide. The resulting NaN comparison suppressed fuel buying. It also used the beginning of a price schedule instead of the slot indexed by remaining market stock. Both are fixed and covered by a test against the engine's actual cash deduction. The corrected heuristic wins 85.1% against the default bot over 960 games. Thus the default bot is only a sanity check.
|
||||
|
||||
`../core-v2.cjs` preserves the old feature semantics solely for compatibility with old exported research artifacts. New strong models use the corrected core and this directory's features. Do not evaluate new models with old feature encoders.
|
||||
|
||||
## Model information and strategy
|
||||
|
||||
Schema 3 has 738 state features and 96 features per candidate action. All opponents' money is visible by user instruction. Hidden deck order, random seed, sealed bid amounts and queued plans are excluded.
|
||||
|
||||
Feature revision `3.1-uranium39` corrects the effective uranium refill after plant 39 has been bought in Recharged Germany (also handled by the helper for Italy). The engine's persistent flag matters even after that plant is discarded. A test compares the feature's predicted refill with a real engine round transition. Older checkpoints use frozen revision `3.0`; the arena and worker select the matching encoder from ONNX metadata. The old encoder's output was verified byte-for-byte against the archived runtime over 427 positions. Unknown revisions and mismatched data fail explicitly. Revision 3.0 datasets and source bundles are retained for reproducibility, not silently reinterpreted.
|
||||
|
||||
The observation explicitly includes all players' cities, plants, fuel, money, current order and remaining actors; per-resource replenishment for every step; current prices and capped refill; and generation capacity with current fuel. Territory features describe each player's presence in map-defined regions/islands and their remaining legal building slots. Building actions include the projected next order with highest-plant tie breaking. Terminal winning is the optimization objective; there is no reward for indiscriminately adding cities.
|
||||
|
||||
`public-graph.cjs` exports map topology, owner vectors, slot rules, edges, islands and crossing costs for subsequent multi-map model work. UK/Ireland territory behavior is tested, but the current trained policy remains Germany/three players. Exporting generic map features does not establish playing strength on another map.
|
||||
|
||||
## Opponents and training
|
||||
|
||||
The economic opponent enumerates feasible plant/fuel combinations and considers purchase cost, income, generation capacity, resource replenishment and stockpiling. A rush variant and the corrected heuristic supply different styles. The residual policy starts with economic action scores and learns neural corrections, rather than initially relearning how to buy fuel from scratch.
|
||||
|
||||
PPO collects complete episodes against a mixture of fixed bots, self-play and frozen earlier neural policies. The four learners vary seed, learning rate, entropy and prior regularization. Each is configured for 300 updates × 128 completed games. Development evaluation uses 96 games per opponent every 20 updates. It selects checkpoints; it is not the final test.
|
||||
|
||||
A separate rollout-search opponent uses the engine's public-information scenario sampler and evaluates counterfactual actions across sampled unknown decks and sealed bids. Its choices are tested for invariance to the actual hidden deck and bids. The initial search benchmark is held separately from training.
|
||||
|
||||
The search reference scored 64.8% against the economic bot and 76.3% against the corrected heuristic, 240 games each with no truncations. Bootstrap 95% intervals, clustered by the 20 independent deals, were [57.9%, 71.7%] and [70.8%, 81.3%]. The B learner's update-20 checkpoint scored 42.2% against the economic bot on 480 fresh paired games (40 deals; interval [38.1%, 46.3%]). These are development/screening results, not a final strength claim; the comparison also uses different deals.
|
||||
|
||||
Four HF CPU jobs generated a separate search-teacher dataset: 512 games, 25,268 strategic positions, 6,769 disagreements with the economic teacher, zero truncated games. `distill.py` trains on HF GPUs, splitting whole games for validation and selecting checkpoints using actual arena performance. Its seeds do not overlap the reference benchmark, screening, or reserved final test.
|
||||
|
||||
The first distillation run deteriorated after epoch 5. Its epoch-30 model scored 8.6% against the economic bot on 480 screening games. Restricting its learned corrections to auction/build decisions raised that to 22.3% on exactly the same deals, still worse than the economic prior. This isolates harmful changes in unsupervised phases as one contributor, not a complete explanation. The next dataset covers every phase and uses 12 search samples instead of four. Hard labels and distributions over counterfactual action values are separate experiments; no improvement is assumed in advance.
|
||||
|
||||
The high-exploration league runs C and D were stopped after sustained regression around updates 60–80, retaining their best checkpoints. A and B completed all 300 updates. The neural B20 checkpoint scored 23.8% against two search opponents over 240 paired screening games (20 deals; 95% interval [17.1%, 30.4%]). Thus it has not passed the strength gate.
|
||||
|
||||
B160 subsequently scored 46.0% against the economic bot and 40.4% against two B20 neural opponents, each over 480 paired screening games (40 independent deals) with no truncations. B20 with 16-sample search scored 47.9% against two four-sample search opponents on 96 screening games (eight deals; interval [36.5%, 59.4%]), but its original/open subset was only 25%; broader evaluation is needed. These runs use their archived revision-3.0 runtime. B160 scored 47.9% with 16 samples and 61.5% with 48 samples against the four-sample reference, each over 96 games/eight deals. The 48-sample interval is [53.6%, 71.4%]; all four rule subsets exceeded 54%. This remains a small development test against a limited reference.
|
||||
|
||||
The corrected revision-3.1 dataset (`search-teacher-v3`) contains 247,104 decisions from 2,048 complete games, with 33,130 search/economic disagreements and no truncations. It includes all phases and uses 12 search samples per strategic decision. Hard-label and uncertainty-preserving distillation completed separately on HF Jobs. Their best checkpoints scored 37.9% and 42.5%, respectively, against the corrected economic opponent over 480 paired screening games each. The corrected soft-label checkpoint is the starting point for two new PPO refinements, with an anchor to its initial policy; one includes search opponents and restricts learned corrections to strategic phases. The new dataset replaces the intermediate revision-3.0 all-phase dataset for corrected-model training.
|
||||
|
||||
## Evidence required before declaring strength
|
||||
|
||||
- Robust gains over the economic, corrected-heuristic, rush, and frozen neural opponents—not just the default bot.
|
||||
- Independent matches against the search reference, with confidence intervals and each rule combination reported separately.
|
||||
- Fresh final-test seeds, balanced seats, original/Recharged and open/sealed auctions, no silent dropping of failed or truncated games.
|
||||
- Tactical and information-boundary tests, ONNX parity, and measured full-worker latency on the 8840U.
|
||||
- Human/expert matches would still be needed to substantiate an expert-level claim. Other maps need training and validation, even though their topology can be encoded.
|
||||
|
||||
## Runtime
|
||||
|
||||
The initial whole-engine JavaScript simulation benchmark was already fast. Repeated economic and regional feature calculations were a larger bottleneck. Hoisting them out of candidate-action loops made the feature benchmark 2.2× faster while preserving the exact output hash across 1,786 positions. A Rust rewrite remains an option if later profiling warrants it.
|
||||
|
||||
`infer.py` serves schema 3 over persistent JSONL; it preserves the same revision-validation obligation as the baseline worker. `evaluate.py` runs independent CPU matches. The current policies are research artifacts, not routed into production bot moves.
|
||||
|
||||
The arena supports `--opponent search` and `--opponent-model frozen.onnx`. Every deal is repeated across three candidate seats and four rule combinations. Results retain the deal identifier; confidence intervals resample deals, not correlated seat repeats. A same-checkpoint-in-all-seats test yields exactly 1/3 for every rule combination, including with uneven worker batches.
|
||||
|
||||
`serving-fixtures.cjs` and `benchmark-serving.py` check full JSONL round trips, legal responses, request/revision preservation and latency across all phases. The update-20 B model's ONNX logits matched PyTorch within 4.1e-6 on 39 search positions, with all argmax actions identical. CPU serving is still a research installation and its value outputs are uncalibrated.
|
||||
|
||||
On the 8840U, all 427 fixture requests returned legal moves: warm round-trip median 1.78 ms, p95 3.80 ms, cold start 167 ms. Optional 16-sample public-belief search, guided by the model's proposed move, had a p95 of 704 ms on 43 sampled requests, all legal. The guided variant is under independent arena evaluation; runtime feasibility alone is not evidence of strength. The isolated research installation is `~/powergrid-ai-strong` and has no production routing.
|
||||
|
||||
## Current deeper evaluation
|
||||
|
||||
Optional geographic proposals broaden build shortlists using connection costs and nearby available expansion sites, while preserving the classic reference for reproducibility. The independent `search_geo` opponent uses 16 sampled worlds and six proposals. Three configurations (B160/48 samples, corrected soft/48, corrected soft/16) each have four HF CPU shards of 48 games against it, sharing deals across configurations. These are development tests; reserved final seeds remain unused. Source v11 is pinned in `experiments.json`.
|
||||
|
||||
The corrected soft model passed PyTorch/ONNX parity across all 427 fixture positions: all actions identical, maximum logit error 3.82e-5 and value error 2.15e-6. On the 8840U, all requests were legal, with 1.87 ms median and 3.45 ms p95 full-worker response. With 48-sample geographic search, a smaller 43-position sample had a 2.02-second p95 and all legal moves. These timings support feasibility, not playing strength.
|
||||
|
||||
A bounded cache of static plant/fuel combinations was tested and removed: feature/search output hashes stayed identical, but measured runtime increased. No cache is included in source v11.
|
||||
|
||||
The later A260 checkpoint scored 67.5% against two economic opponents on the same 480 paired screening games (40 deals; 95% interval [62.3%, 72.5%]), compared with B160’s 46.0%. Its four rule subsets scored 57.5%, 65.8%, 71.7%, and 75.0%. The corrected refinement checkpoint at update 30 scored 54.7%. Both exports matched checkpoint actions on all 427 fixtures. A260 is now tested against frozen B160 and the deeper geographic search reference, both raw and with 48-sample guided search. These remain development tests; final seeds are reserved.
|
||||
|
||||
An explicit, limited 3.0 → 3.1 uranium-feature transfer experiment starts from pinned A260 weights. Ordinary checkpoint loading still rejects mismatched input revisions. The experiment evaluates its transferred starting policy before any gradient update, anchors refinement to that policy, records the original feature revision, and trains only on an HF GPU job. It does not relabel the old ONNX model or claim unchanged behavior. The complete 427-position corrected-soft/search-48 benchmark on the 8840U returned only legal moves with a 2.50-second p95. Raw A260 serving also passed all 427 positions at 3.74 ms p95.
|
||||
|
||||
The corrected soft policy with 16-sample geographic search scored 34.9% against two independent 16-sample geographic search opponents across 192 games/16 paired deals (95% interval [28.9%, 40.4%]), with no truncations. This is consistent with parity and does not pass the strength gate. A260 scored 42.5% against two frozen B160 policies over 480 games/40 deals ([37.5%, 47.9%]); original/open was only 30.0%, so the aggregate gain does not establish superiority in every ruleset.
|
||||
|
||||
A260 without inference-time search scored 34.1% against two 16-sample geographic search opponents over 192 games/16 deals ([29.7%, 38.5%]), consistent with parity. The completed A run selected update 299; it scored 62.2% against economic opponents and 44.2% against B160 on 480 paired games each. All A299/B160 rule subsets exceeded 39%, while A260/B160 original-open scored 30%; the tradeoff requires the separate search comparison rather than selecting only the highest economic score. The corrected full-refinement update-60 checkpoint reached 60.8% against economic opponents.
|
||||
|
||||
No further training experiments will be started until the current fixed cohort is compared: completed original A/B, corrected full refinement, search-opponent refinement, and corrected A260 refinement. Final-test seeds remain unused. A second bounded-cache experiment avoided freezing and copied returned arrays instead; six alternating benchmark runs retained identical search output hashes but showed no runtime gain, so that implementation was also discarded.
|
||||
|
||||
On the deeper reference, 48-sample geographic B160 scored 46.9% over 192 games/16 deals ([40.6%, 52.6%]); all four rule subsets were 45.8–47.9%. Corrected soft/48 scored 44.3% ([37.5%, 51.0%]), with all subsets above 33.3%. Both completed without truncations. The corrected A260 refinement at update 40 scored 72.3% against economic opponents ([67.7%, 76.7%]) and 40.6% against A260 ([37.1%, 44.2%]), 480 games each; its search-reference tests are pending.
|
||||
|
||||
`package-serving.py` builds a frozen CPU runtime archive with a model hash, feature revision, scope, source revision, per-file hashes, bundled engine dependencies, and JSONL startup instructions. An archive containing the corrected refinement checkpoint was extracted outside the worktree and passed nine legal-request checks each with zero and 48 search samples; every file hash matched. This is a packaging check, not a strength approval.
|
||||
|
||||
The final evaluation protocol is fixed in `final-protocol.json` before candidate selection or use of final seeds. It requires fresh balanced matches against six opponent styles, confidence intervals and minimum win shares, with per-rule gains rather than an aggregate-only pass. Source v13 adds search rollout diagnostics; a 12-game regression preserved every terminal state, action count and outcome while recording 22,927 rollouts with zero truncations. Historical reports without these counters explicitly mark them unreported.
|
||||
|
||||
A299 without search scored 51.0% against the geographic search reference over 192 games/16 deals ([44.8%, 57.8%]); corrected A260-refinement update 40 scored 47.9% ([41.1%, 54.2%]). Both had only 33.3% in Recharged sealed auctions, so neither result alone establishes superiority in every rule combination. The same A40 checkpoint remains best after its full 80-update training run. All A10G training jobs are complete; the H200 search-opponent experiment was subsequently stopped after regression, retaining its best checkpoint.
|
||||
|
||||
The corrected A40 policy passed all 427 CPU serving requests and checkpoint/export action comparisons. Its 48-sample serving mode had 2.38-second overall p95, 2.65-second p95 among the 161 actual search decisions, and a 3.04-second maximum over the fixture set.
|
||||
|
||||
## Frozen specialist configuration under evaluation
|
||||
|
||||
Applying 48-sample search to every rule combination reduced corrected A40’s aggregate search-reference result from 47.9% to 43.2%. It helped Recharged sealed (33.3% → 39.6%) but hurt the other three subsets. B160/search-48 was stronger and more balanced in that mode (45.8%). A CPU-only composition therefore combines corrected A40 for three rule combinations with B160 weights for Recharged sealed, and spends the 48-sample search budget only in that last combination. Both branches consume corrected feature revision 3.1. The B160 input correction is explicit in component provenance; it is a new, unapproved candidate whose playing strength must be measured, not an assertion that the old policy is unchanged. No gradient training occurs during composition.
|
||||
|
||||
The single ONNX export has SHA `b4cae14eb6e1aff72b16e5056983b2a57ad42984f4a27cf99dd70bb63e86be32`. `check-export.py` independently selected the expected component from the original engine options and verified all 427 positions (337 default, 90 Recharged sealed), along with ONNX/checkpoint action parity. Its isolated 8840U archive passed all 1,201 file hashes and all 427 legal requests. There were 33 actual search decisions: 2.36-second search-only p95, 2.57-second maximum; zero of 7,872 rollouts were truncated. Full-worker median was 2.42 ms, with search scoped to Recharged sealed. Development matches against the full opponent suite are running on immutable source v14; final seeds remain unused.
|
||||
|
||||
The completed full-distillation refinement’s update-119 checkpoint scored 65.9% against economic opponents and 35.7% against A260 over 480 games each; the latter interval [30.3%, 41.3%] did not establish a reliable gain. It is not replacing the stronger corrected A40 checkpoint.
|
||||
|
||||
The combined candidate’s first full development result is 76.7% against two economic opponents over 480 games/40 deals ([72.7%, 80.6%]). The unchanged three A40 branches reproduce their earlier win rates; the corrected B160/search branch scored 96.7% in Recharged sealed. All games completed, and none of 1,204,368 candidate search rollouts hit the step limit. Other opponent results are still required.
|
||||
|
||||
`launch-final.py` prepares 3,840 fresh games in 80 CPU shards and defaults to a dry run. It verifies the selected model hash, freezes the candidate/protocol/launcher fingerprint, and records each dispatched job for resumption without silently changing the test. `verify-final.py` recomputes paired-deal intervals from raw matches and audits model/configuration hashes, exact game counts, every seat/rule pairing, held-out seed prefixes, terminal credit, rollout reporting, parity, the 8840U benchmark, and the extracted archive. A negative check correctly rejected development seeds and a mismatched/unfrozen candidate.
|
||||
|
||||
The standalone archive provides `serve.py`, which reads the frozen manifest and checks the model hash before starting the worker. It was tested from an unrelated working directory with legal responses and the intended rule-specific search budget. Final CPU arenas use source v15 (policy unchanged; adds completed-game progress logs) and pinned dependencies.
|
||||
55
ai/strong/arena-job.py
Normal file
55
ai/strong/arena-job.py
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
"""Pinned-checkpoint CPU evaluation on HF Jobs."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
from huggingface_hub import HfApi, hf_hub_download
|
||||
|
||||
repo = os.environ["HF_MODEL_REPO"]
|
||||
model = hf_hub_download(
|
||||
repo, os.environ["MODEL_PATH"], revision=os.environ["MODEL_REVISION"]
|
||||
)
|
||||
command = [
|
||||
sys.executable,
|
||||
"ai/strong/evaluate.py",
|
||||
model,
|
||||
"--players",
|
||||
os.getenv("PLAYER_COUNT", "3"),
|
||||
"--deal-offset",
|
||||
os.getenv("DEAL_OFFSET", "0"),
|
||||
"--opponent",
|
||||
os.environ.get("OPPONENT", "search_geo"),
|
||||
"--games",
|
||||
os.environ.get("GAMES", "48"),
|
||||
"--workers",
|
||||
os.environ.get("WORKERS", "24"),
|
||||
"--seed",
|
||||
os.environ["EVAL_SEED"],
|
||||
"--search-scope",
|
||||
os.environ.get("SEARCH_SCOPE", "all"),
|
||||
"--search-samples",
|
||||
os.environ.get("SEARCH_SAMPLES", "0"),
|
||||
"--output",
|
||||
"evaluation.json",
|
||||
]
|
||||
if os.getenv("ASYNC_ARENA") == "1":
|
||||
command.append("--async-rollout")
|
||||
if os.getenv("DISABLE_SEARCH_PROPOSAL") == "1":
|
||||
command.append("--disable-search-proposal")
|
||||
if os.getenv("GEOGRAPHY") == "1":
|
||||
command.append("--geographic-search")
|
||||
if os.getenv("OPPONENT_MODEL_PATH"):
|
||||
opponent = hf_hub_download(
|
||||
repo,
|
||||
os.environ["OPPONENT_MODEL_PATH"],
|
||||
revision=os.environ["OPPONENT_MODEL_REVISION"],
|
||||
)
|
||||
command.extend(["--opponent-model", opponent])
|
||||
subprocess.run(command, check=True)
|
||||
assert Path("evaluation.json").exists()
|
||||
HfApi().upload_file(
|
||||
repo_id=repo,
|
||||
path_or_fileobj="evaluation.json",
|
||||
path_in_repo=f"runs/{os.environ['RUN_NAME']}/evaluation.json",
|
||||
)
|
||||
74
ai/strong/arena_statistics.py
Normal file
74
ai/strong/arena_statistics.py
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
"""Uncertainty over independent deals, keeping seat/rule repeats together."""
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
def win_summary(rows, key="gameSeed"):
|
||||
groups = {}
|
||||
for row in rows:
|
||||
groups.setdefault(row[key], []).append(float(row["win"]))
|
||||
totals = np.asarray([sum(v) for v in groups.values()])
|
||||
counts = np.asarray([len(v) for v in groups.values()])
|
||||
result = {
|
||||
"games": len(rows),
|
||||
"independent_seeds": len(groups),
|
||||
"win_rate": float(totals.sum() / counts.sum()),
|
||||
"truncated": sum(row["truncated"] for row in rows),
|
||||
}
|
||||
if len(groups) >= 2:
|
||||
rng = np.random.default_rng(8501)
|
||||
picks = rng.integers(len(groups), size=(10000, len(groups)))
|
||||
draws = totals[picks].sum(axis=1) / counts[picks].sum(axis=1)
|
||||
result["seed_bootstrap_95_interval"] = np.quantile(
|
||||
draws, [0.025, 0.975]
|
||||
).tolist()
|
||||
else:
|
||||
result["seed_bootstrap_95_interval"] = None
|
||||
return result
|
||||
|
||||
|
||||
def search_summary(rows):
|
||||
if not all("searchStats" in row for row in rows):
|
||||
return {"search_rollouts_reported": False}
|
||||
totals = {}
|
||||
for row in rows:
|
||||
for role, stats in row["searchStats"].items():
|
||||
target = totals.setdefault(
|
||||
role, {"decisions": 0, "evaluations": 0, "truncated": 0}
|
||||
)
|
||||
for key in target:
|
||||
target[key] += stats[key]
|
||||
return {"search_rollouts_reported": True, "search_stats": totals}
|
||||
|
||||
|
||||
def validate_pairs(rows, players):
|
||||
"""Reject missing seats/rules and malformed outcomes, including in old reports."""
|
||||
if players not in range(2, 7) or not rows:
|
||||
raise ValueError("Expected nonempty 2–6 player arena")
|
||||
expected = {
|
||||
(seat, variant, sealed)
|
||||
for seat in range(players)
|
||||
for variant in ["original", "recharged"]
|
||||
for sealed in [False, True]
|
||||
}
|
||||
deals = {}
|
||||
for row in rows:
|
||||
if row.get("playerCount", players) != players:
|
||||
raise ValueError("Mixed player counts")
|
||||
key = (row["seat"], row["variant"], row["sealed"])
|
||||
seen = deals.setdefault(row["gameSeed"], set())
|
||||
if key in seen or key not in expected:
|
||||
raise ValueError("Duplicate or invalid paired match")
|
||||
seen.add(key)
|
||||
if len(row["value"]) != players or len(row["roles"]) != players:
|
||||
raise ValueError("Wrong terminal vector or role count")
|
||||
if row["roles"].count("learner") != 1 or row["roles"][row["seat"]] != "learner":
|
||||
raise ValueError("Wrong candidate seat")
|
||||
if any(not np.isfinite(v) or v < 0 or v > 1 for v in row["value"]):
|
||||
raise ValueError("Invalid terminal credits")
|
||||
if not row["truncated"] and not np.isclose(sum(row["value"]), 1):
|
||||
raise ValueError("Terminal credits must sum to one")
|
||||
if row["win"] != row["value"][row["seat"]]:
|
||||
raise ValueError("Candidate win differs from terminal credit")
|
||||
if any(seen != expected for seen in deals.values()):
|
||||
raise ValueError("Incomplete paired deal")
|
||||
71
ai/strong/async_pool.py
Normal file
71
ai/strong/async_pool.py
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
"""One engine per game; advance ready games without a global step barrier."""
|
||||
|
||||
from concurrent.futures import FIRST_COMPLETED, wait
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from pool import EnginePool
|
||||
|
||||
|
||||
class AsyncEnginePool(EnginePool):
|
||||
def __init__(self, workers, seed="rollout-v1", script="ai/strong/bridge.cjs"):
|
||||
super().__init__(workers, seed, script)
|
||||
self.pending = {}
|
||||
self.ready = set()
|
||||
self.started = False
|
||||
|
||||
def _submit(self, index, request):
|
||||
future = self.executor.submit(self._call, (self.processes[index], request))
|
||||
self.pending[future] = index
|
||||
|
||||
def _collect(self):
|
||||
observations = [None] * len(self.processes)
|
||||
ended = []
|
||||
while self.pending:
|
||||
done, _ = wait(self.pending, return_when=FIRST_COMPLETED)
|
||||
# Also consume replies that finished during the wakeup.
|
||||
done.update(f for f in self.pending if f.done())
|
||||
for future in sorted(done, key=lambda f: self.pending[f]):
|
||||
index = self.pending.pop(future)
|
||||
result = future.result()
|
||||
if len(result["observations"]) != 1:
|
||||
raise ValueError("Async engines must own exactly one game")
|
||||
row = result["observations"][0]
|
||||
observations[index] = row
|
||||
if row is not None:
|
||||
self.ready.add(index)
|
||||
for e in result["ended"]:
|
||||
if e["env"] != 0:
|
||||
raise ValueError("Unexpected worker-local environment index")
|
||||
ended.append({**e, "env": index})
|
||||
if self.ready:
|
||||
break
|
||||
# Completed games alone must not end the caller's loop while other
|
||||
# engines still have requests in flight.
|
||||
return {"observations": observations, "ended": ended}
|
||||
|
||||
def call(self, request):
|
||||
count = len(self.processes)
|
||||
if request["op"] == "reset":
|
||||
if self.pending or self.ready:
|
||||
raise ValueError("Cannot reset while a batch is active")
|
||||
if request["n"] != count:
|
||||
raise ValueError("Async training needs one worker per environment")
|
||||
self.started = True
|
||||
offset = request.get("offset", 0)
|
||||
for index in range(count):
|
||||
self._submit(index, {**request, "n": 1, "offset": offset + index})
|
||||
elif request["op"] == "step":
|
||||
actions = request["actions"]
|
||||
if not self.started or len(actions) != count:
|
||||
raise ValueError("Incorrect action count or missing reset")
|
||||
supplied = {i for i, action in enumerate(actions) if action is not None}
|
||||
if supplied != self.ready:
|
||||
raise ValueError("Actions must match the ready environments exactly")
|
||||
for index in sorted(self.ready):
|
||||
self._submit(index, {"op": "step", "actions": [actions[index]]})
|
||||
self.ready.clear()
|
||||
else:
|
||||
raise ValueError("Unknown operation")
|
||||
return self._collect()
|
||||
29
ai/strong/audit-search-budget.cjs
Normal file
29
ai/strong/audit-search-budget.cjs
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
// Paired public scenarios across continuation policies and nested search budgets.
|
||||
const fs = require('node:fs');
|
||||
const search = require('./search.cjs');
|
||||
const rows = fs.readFileSync(process.argv[2], 'utf8').trim().split('\n');
|
||||
const row = JSON.parse(rows[Number(process.argv[3])]);
|
||||
const continuation = process.argv[4],
|
||||
batch = process.argv[5];
|
||||
if (!['a', 'b'].includes(batch)) throw Error('Invalid batch');
|
||||
const { state, player } = row.request;
|
||||
const result = search.choose(state, player, {
|
||||
samples: 384,
|
||||
candidates: 6,
|
||||
geography: true,
|
||||
maxSteps: 2400,
|
||||
seed: `teacher-reliability-v1-${row.fixtureIndex}-${batch}`,
|
||||
continuation,
|
||||
includeSamples: true,
|
||||
});
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
fixtureIndex: row.fixtureIndex,
|
||||
cell: row.cell,
|
||||
round: state.round,
|
||||
continuation,
|
||||
batch,
|
||||
samples: 384,
|
||||
result,
|
||||
})
|
||||
);
|
||||
55
ai/strong/audit-search-budgets.py
Normal file
55
ai/strong/audit-search-budgets.py
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
"""HF diagnostic shard: repeat searches with shared scenarios across policies."""
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import itertools
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
players = int(os.environ['PLAYER_COUNT'])
|
||||
assert 2 <= players <= 6
|
||||
fixtures = Path('ai/strong/fixtures/teacher-reliability-v1.jsonl')
|
||||
rows = [json.loads(line) for line in fixtures.read_text().splitlines()]
|
||||
indices = [i for i, r in enumerate(rows) if r['cell'][0] == players]
|
||||
assert len(indices) == 12
|
||||
tasks = list(itertools.product(indices, ['mixed', 'economic', 'heuristic'], ['a', 'b']))
|
||||
|
||||
|
||||
def audit(task):
|
||||
index, policy, batch = task
|
||||
process = subprocess.run(['node', 'ai/strong/audit-search-budget.cjs', str(fixtures),
|
||||
str(index), policy, batch], capture_output=True, text=True, check=True)
|
||||
row = json.loads(process.stdout)
|
||||
assert row['cell'][0] == players and row['continuation'] == policy and row['batch'] == batch
|
||||
result = row['result']
|
||||
assert len(result['sampleOutcomes']) * 384 == result['evaluations']
|
||||
assert sum(v.count(None) for v in result['sampleOutcomes'].values()) == result['truncated']
|
||||
for k, v in result['sampleOutcomes'].items():
|
||||
assert len(v) == 384 and sum(x for x in v if x is not None) == result['values'][k]
|
||||
return row
|
||||
|
||||
|
||||
completed = []
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=24) as pool:
|
||||
futures = [pool.submit(audit, task) for task in tasks]
|
||||
for f in concurrent.futures.as_completed(futures):
|
||||
completed.append(f.result())
|
||||
print(json.dumps({'players': players, 'completed_searches': len(completed),
|
||||
'requested_searches': len(tasks)}), flush=True)
|
||||
completed.sort(key=lambda r: (r['fixtureIndex'], r['continuation'], r['batch']))
|
||||
output = Path(f'results-{players}p.jsonl')
|
||||
output.write_text(''.join(json.dumps(r) + '\n' for r in completed))
|
||||
manifest = {'players': players, 'positions': 12, 'searches': len(completed), 'samples': 384,
|
||||
'search_max_steps': 2400, 'fixture_sha256': hashlib.sha256(fixtures.read_bytes()).hexdigest(),
|
||||
'output_sha256': hashlib.sha256(output.read_bytes()).hexdigest(),
|
||||
'evaluations': sum(r['result']['evaluations'] for r in completed),
|
||||
'truncated': sum(r['result']['truncated'] for r in completed),
|
||||
'scope': 'Reused development positions; nested budgets and shared public scenarios; no strength claim.'}
|
||||
api = HfApi()
|
||||
api.upload_file(repo_id=os.environ['HF_MODEL_REPO'], path_or_fileobj=output,
|
||||
path_in_repo=f'runs/teacher-reliability-v2/{output.name}')
|
||||
api.upload_file(repo_id=os.environ['HF_MODEL_REPO'], path_or_fileobj=json.dumps(manifest, indent=2).encode(),
|
||||
path_in_repo=f'runs/teacher-reliability-v2/manifest-{players}p.json')
|
||||
print(json.dumps(manifest), flush=True)
|
||||
28
ai/strong/audit-search-target.cjs
Normal file
28
ai/strong/audit-search-target.cjs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
// Independent search batches on fixed development positions; no learning.
|
||||
const fs = require('node:fs');
|
||||
const search = require('./search.cjs');
|
||||
const c = require('../core.cjs');
|
||||
const rows = fs.readFileSync(process.argv[2], 'utf8').trim().split('\n');
|
||||
const row = JSON.parse(rows[Number(process.argv[3])]);
|
||||
const { state, player } = row.request;
|
||||
const batches = ['a', 'b'].map((batch) => {
|
||||
const result = search.choose(state, player, {
|
||||
samples: 48,
|
||||
candidates: 6,
|
||||
geography: true,
|
||||
maxSteps: 2400,
|
||||
seed: `teacher-reliability-v1-${row.fixtureIndex}-${batch}`,
|
||||
includeSamples: true,
|
||||
});
|
||||
return { batch, ...result };
|
||||
});
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
fixtureIndex: row.fixtureIndex,
|
||||
cell: row.cell,
|
||||
round: state.round,
|
||||
actions: c.candidates(state, player),
|
||||
samplePolicies: Array.from({ length: 48 }, (_, i) => (i % 2 ? 'heuristic' : 'economic')),
|
||||
batches,
|
||||
})
|
||||
);
|
||||
49
ai/strong/audit-search-targets.py
Normal file
49
ai/strong/audit-search-targets.py
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
"""HF-only diagnostic collection of independent teacher-search repetitions."""
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
fixtures = Path('ai/strong/fixtures/teacher-reliability-v1.jsonl')
|
||||
rows = fixtures.read_text().splitlines()
|
||||
assert len(rows) == 60
|
||||
|
||||
|
||||
def audit(index):
|
||||
result = subprocess.run(['node', 'ai/strong/audit-search-target.cjs', str(fixtures), str(index)],
|
||||
text=True, capture_output=True, check=True)
|
||||
row = json.loads(result.stdout)
|
||||
for batch in row['batches']:
|
||||
samples = batch['sampleOutcomes']
|
||||
assert all(len(v) == 48 for v in samples.values())
|
||||
assert sum(len(v) for v in samples.values()) == batch['evaluations']
|
||||
assert sum(v.count(None) for v in samples.values()) == batch['truncated']
|
||||
assert all(sum(x for x in v if x is not None) == batch['values'][k]
|
||||
for k, v in samples.items())
|
||||
return row
|
||||
|
||||
|
||||
output = Path('teacher-reliability-v1.jsonl')
|
||||
completed = []
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=24) as pool:
|
||||
futures = [pool.submit(audit, i) for i in range(len(rows))]
|
||||
for f in concurrent.futures.as_completed(futures):
|
||||
completed.append(f.result())
|
||||
print(json.dumps({'completed_positions': len(completed), 'requested_positions': len(rows)}), flush=True)
|
||||
completed.sort(key=lambda r: r['fixtureIndex'])
|
||||
output.write_text(''.join(json.dumps(r) + '\n' for r in completed))
|
||||
manifest = {'positions': len(completed), 'samples_per_batch': 48, 'batches_per_position': 2,
|
||||
'search_max_steps': 2400, 'fixture_sha256': hashlib.sha256(fixtures.read_bytes()).hexdigest(),
|
||||
'output_sha256': hashlib.sha256(output.read_bytes()).hexdigest(),
|
||||
'truncated': sum(b['truncated'] for r in completed for b in r['batches']),
|
||||
'evaluations': sum(b['evaluations'] for r in completed for b in r['batches']),
|
||||
'scope': 'Reused development fixtures; diagnostic only, no strength or calibration claim.'}
|
||||
api = HfApi()
|
||||
api.upload_file(repo_id=os.environ['HF_MODEL_REPO'], path_or_fileobj=output,
|
||||
path_in_repo='runs/teacher-reliability-v1/results.jsonl')
|
||||
api.upload_file(repo_id=os.environ['HF_MODEL_REPO'], path_or_fileobj=json.dumps(manifest, indent=2).encode(),
|
||||
path_in_repo='runs/teacher-reliability-v1/manifest.json')
|
||||
print(json.dumps(manifest), flush=True)
|
||||
111
ai/strong/audit-teacher-dataset.py
Normal file
111
ai/strong/audit-teacher-dataset.py
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
"""Read-only audit of immutable HF teacher shards before GPU training."""
|
||||
|
||||
import argparse
|
||||
from collections import Counter
|
||||
import gzip
|
||||
import json
|
||||
from pathlib import Path
|
||||
from huggingface_hub import hf_hub_download
|
||||
from teacher_contract import validate_game, validation_seeds
|
||||
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--revision", required=True)
|
||||
p.add_argument("--version", default="multiplayer-teacher-v1")
|
||||
p.add_argument("--output", required=True)
|
||||
a = p.parse_args()
|
||||
summary = {}
|
||||
metadata = []
|
||||
seen = set()
|
||||
for shard, n in enumerate(range(2, 7)):
|
||||
path = hf_hub_download(
|
||||
"coyotte508/powergrid-ai-training-v1",
|
||||
f"{a.version}/{a.version}-{shard}.jsonl.gz",
|
||||
repo_type="dataset",
|
||||
revision=a.revision,
|
||||
)
|
||||
stats = dict(
|
||||
games=0,
|
||||
positions=0,
|
||||
truncated=0,
|
||||
search_rollouts=0,
|
||||
search_rollouts_truncated=0,
|
||||
opponent_search_rollouts=0,
|
||||
opponent_search_rollouts_truncated=0,
|
||||
teacher_win_credit=0.0,
|
||||
disagreements=0,
|
||||
)
|
||||
cells = Counter()
|
||||
phases = Counter()
|
||||
opponents = {}
|
||||
with gzip.open(path, "rt") as source:
|
||||
for line in source:
|
||||
game = json.loads(line)
|
||||
validate_game(game)
|
||||
assert game["playerCount"] == n
|
||||
assert game["seed"] not in seen
|
||||
seen.add(game["seed"])
|
||||
stats["games"] += 1
|
||||
stats["truncated"] += game["truncated"]
|
||||
stats["positions"] += len(game["rows"])
|
||||
stats["search_rollouts"] += game["searchStats"]["evaluations"]
|
||||
stats["search_rollouts_truncated"] += game["searchStats"]["truncated"]
|
||||
opponent_search = game.get("opponentSearchStats", {})
|
||||
stats["opponent_search_rollouts"] += opponent_search.get("evaluations", 0)
|
||||
stats["opponent_search_rollouts_truncated"] += opponent_search.get(
|
||||
"truncated", 0
|
||||
)
|
||||
if game["truncated"]:
|
||||
continue
|
||||
assert game["rows"]
|
||||
seat = game["rows"][0]["seat"]
|
||||
win = game["value"][seat]
|
||||
stats["teacher_win_credit"] += win
|
||||
opponent = game.get(
|
||||
"opponent", ["economic", "heuristic", "rush"][game["id"] // (4 * n) % 3]
|
||||
)
|
||||
opp = opponents.setdefault(opponent, dict(games=0, win_credit=0.0))
|
||||
opp["games"] += 1
|
||||
opp["win_credit"] += win
|
||||
cells[(seat, game["variant"], game["sealed"])] += 1
|
||||
for row in game["rows"]:
|
||||
phases[row["phase"]] += 1
|
||||
stats["disagreements"] += not row["teacherAgrees"]
|
||||
metadata.append(
|
||||
{
|
||||
**{
|
||||
k: game[k] for k in ["seed", "playerCount", "variant", "sealed"]
|
||||
},
|
||||
"rows": [{"seat": seat}],
|
||||
}
|
||||
)
|
||||
assert stats["games"] == 240 and len(cells) == n * 4
|
||||
assert (
|
||||
stats["truncated"]
|
||||
== stats["search_rollouts_truncated"]
|
||||
== stats["opponent_search_rollouts_truncated"]
|
||||
== 0
|
||||
)
|
||||
summary[str(n)] = {
|
||||
**stats,
|
||||
"seat_rule_cells": len(cells),
|
||||
"phases": dict(phases),
|
||||
"opponents": opponents,
|
||||
}
|
||||
selected = validation_seeds(metadata)
|
||||
for n, stats in summary.items():
|
||||
stats["validation_games"] = sum(
|
||||
g["playerCount"] == int(n) and g["seed"] in selected for g in metadata
|
||||
)
|
||||
stats["training_games"] = sum(
|
||||
g["playerCount"] == int(n) and g["seed"] not in selected for g in metadata
|
||||
)
|
||||
report = dict(
|
||||
revision=a.revision,
|
||||
version=a.version,
|
||||
counts=summary,
|
||||
unique_games=len(seen),
|
||||
validated=True,
|
||||
scope="Teacher-generated development data; not held-out strength evidence",
|
||||
)
|
||||
Path(a.output).write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(json.dumps(report))
|
||||
61
ai/strong/audit-teacher-margins.py
Normal file
61
ai/strong/audit-teacher-margins.py
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
"""Measure ambiguity in held-out search labels; estimates are not true win values."""
|
||||
|
||||
import argparse
|
||||
from collections import defaultdict
|
||||
import gzip
|
||||
import json
|
||||
from pathlib import Path
|
||||
from teacher_contract import validation_seeds
|
||||
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("dataset_directory", type=Path)
|
||||
p.add_argument("--output", type=Path, required=True)
|
||||
a = p.parse_args()
|
||||
paths = sorted(a.dataset_directory.glob("*.jsonl.gz"))
|
||||
assert len(paths) == 5
|
||||
metadata = []
|
||||
for path in paths:
|
||||
with gzip.open(path, "rt") as source:
|
||||
for line in source:
|
||||
game = json.loads(line)
|
||||
metadata.append(
|
||||
{
|
||||
**{
|
||||
k: game[k] for k in ["seed", "playerCount", "variant", "sealed"]
|
||||
},
|
||||
"rows": [{"seat": r["seat"]} for r in game["rows"]],
|
||||
}
|
||||
)
|
||||
held_out = validation_seeds(metadata)
|
||||
groups = defaultdict(lambda: defaultdict(int))
|
||||
for path in paths:
|
||||
with gzip.open(path, "rt") as source:
|
||||
for line in source:
|
||||
game = json.loads(line)
|
||||
if game["seed"] not in held_out:
|
||||
continue
|
||||
for row in game["rows"]:
|
||||
for key in [
|
||||
str(game["playerCount"]),
|
||||
f"{game['playerCount']}/{row['phase']}",
|
||||
]:
|
||||
g = groups[key]
|
||||
g["positions"] += 1
|
||||
values = sorted([v for _, v in row["searchValues"]], reverse=True)
|
||||
if len(values) < 2:
|
||||
g["fewer_than_two_searched_candidates"] += 1
|
||||
continue
|
||||
g["search_comparisons"] += 1
|
||||
margin = values[0] - values[1]
|
||||
g["tied_top_estimates"] += margin < 1e-9
|
||||
g["top_gap_at_most_one_of_16_rollouts"] += margin <= 1 / 16 + 1e-9
|
||||
if not row["teacherAgrees"]:
|
||||
g["teacher_disagreements"] += 1
|
||||
g["disagreements_with_tied_top"] += margin < 1e-9
|
||||
report = {
|
||||
"scope": "Held-out teacher states; finite 16-rollout estimates, not calibrated confidence or true action quality.",
|
||||
"validation_games": len(held_out),
|
||||
"groups": dict(groups),
|
||||
}
|
||||
a.output.write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(json.dumps({k: v for k, v in groups.items() if "/" not in k}))
|
||||
19
ai/strong/benchmark-features.cjs
Normal file
19
ai/strong/benchmark-features.cjs
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
const c = require('../core.cjs'),
|
||||
f = require('./features.cjs'),
|
||||
eco = require('./economics.cjs'),
|
||||
{ createHash } = require('node:crypto');
|
||||
const h = createHash('sha256');
|
||||
let n = 0,
|
||||
t = performance.now();
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const g = c.start('features-bench-' + i, i % 2 ? 'original' : 'recharged', i < 2),
|
||||
rng = c.seedrandom('bench');
|
||||
while (!c.E.ended(g) && n < 5000) {
|
||||
const p = g.currentPlayers[0],
|
||||
x = f.encode(g, p);
|
||||
h.update(JSON.stringify(x));
|
||||
n++;
|
||||
c.E.move(g, eco.choose(g, p, rng).action, p);
|
||||
}
|
||||
}
|
||||
console.log(JSON.stringify({ states: n, seconds: (performance.now() - t) / 1000, hash: h.digest('hex') }));
|
||||
134
ai/strong/benchmark-serving.py
Normal file
134
ai/strong/benchmark-serving.py
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
"""Validate legal responses and time the complete persistent CPU worker."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import platform
|
||||
import numpy as np
|
||||
from search_scope import SCOPES
|
||||
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("model")
|
||||
p.add_argument("--search-scope", choices=SCOPES, default="all")
|
||||
p.add_argument("fixtures")
|
||||
p.add_argument("--output", required=True)
|
||||
p.add_argument("--search-samples", type=int, default=0)
|
||||
p.add_argument("--stride", type=int, default=1)
|
||||
p.add_argument("--geographic-search", action="store_true")
|
||||
args = p.parse_args()
|
||||
worker = subprocess.Popen(
|
||||
[
|
||||
sys.executable,
|
||||
str(Path(__file__).with_name("infer.py")),
|
||||
args.model,
|
||||
"--search-scope",
|
||||
args.search_scope,
|
||||
"--search-samples",
|
||||
str(args.search_samples),
|
||||
]
|
||||
+ (["--geographic-search"] if args.geographic_search else []),
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
text=True,
|
||||
bufsize=1,
|
||||
)
|
||||
latencies, inner = [], []
|
||||
search_latencies = []
|
||||
search_evaluations = 0
|
||||
search_truncations = 0
|
||||
by_phase = {}
|
||||
by_count = {}
|
||||
sha = None
|
||||
try:
|
||||
with open(args.fixtures) as source:
|
||||
for i, line in enumerate(source):
|
||||
if i % args.stride:
|
||||
continue
|
||||
fixture = json.loads(line)
|
||||
request = fixture["request"]
|
||||
start = time.perf_counter()
|
||||
worker.stdin.write(json.dumps(request) + "\n")
|
||||
worker.stdin.flush()
|
||||
result = json.loads(worker.stdout.readline())
|
||||
latencies.append(1000 * (time.perf_counter() - start))
|
||||
assert "error" not in result, result
|
||||
assert result["move"] in fixture["legal"], result
|
||||
assert result["requestId"] == request["requestId"]
|
||||
assert result["revision"] == request["revision"]
|
||||
assert result["schema"] in [3, 4]
|
||||
n = len(request["state"]["players"])
|
||||
assert len(result["winProbabilities"]) == n
|
||||
assert result["playerOrder"] == [
|
||||
(request["player"] + j) % n for j in range(n)
|
||||
]
|
||||
by_count.setdefault(str(n), []).append(latencies[-1])
|
||||
assert result["playerOrder"][0] == request["player"]
|
||||
assert abs(sum(result["winProbabilities"]) - 1) < 1e-5
|
||||
assert sha is None or sha == result["modelSha256"]
|
||||
sha = result["modelSha256"]
|
||||
inner.append(result["elapsedMs"])
|
||||
by_phase.setdefault(str(request["state"]["phase"]), []).append(
|
||||
latencies[-1]
|
||||
)
|
||||
search_evaluations += (result.get("search") or {}).get("evaluations", 0)
|
||||
search_truncations += (result.get("search") or {}).get("truncated", 0)
|
||||
if (result.get("search") or {}).get("evaluations", 0):
|
||||
search_latencies.append(latencies[-1])
|
||||
finally:
|
||||
worker.stdin.close()
|
||||
worker.wait(timeout=10)
|
||||
worker.stdout.close()
|
||||
cpu_info = Path("/proc/cpuinfo")
|
||||
processor_model = platform.processor()
|
||||
if cpu_info.exists():
|
||||
processor_model = next(
|
||||
(
|
||||
line.split(":", 1)[1].strip()
|
||||
for line in cpu_info.read_text().splitlines()
|
||||
if line.startswith("model name")
|
||||
),
|
||||
processor_model,
|
||||
)
|
||||
report = {
|
||||
"hostname": platform.node(),
|
||||
"processor_model": processor_model,
|
||||
"python_version": platform.python_version(),
|
||||
"positions": len(latencies),
|
||||
"by_player_count": {
|
||||
n: {"positions": len(xs), "p95_ms": float(np.percentile(xs, 95))}
|
||||
for n, xs in by_count.items()
|
||||
},
|
||||
"model_sha256": sha,
|
||||
"all_moves_legal": True,
|
||||
"search_samples": args.search_samples,
|
||||
"search_scope": args.search_scope,
|
||||
"geographic_search": args.geographic_search,
|
||||
"cold_start_ms": latencies[0],
|
||||
"warm_roundtrip_p50_ms": float(np.percentile(latencies[1:], 50)),
|
||||
"warm_roundtrip_p95_ms": float(np.percentile(latencies[1:], 95)),
|
||||
"worker_p95_ms": float(np.percentile(inner[1:], 95)),
|
||||
"max_roundtrip_ms": max(latencies),
|
||||
"search_decisions": len(search_latencies),
|
||||
"search_evaluations": search_evaluations,
|
||||
"search_truncated_rollouts": search_truncations,
|
||||
"search_roundtrip_p50_ms": float(np.percentile(search_latencies, 50))
|
||||
if search_latencies
|
||||
else None,
|
||||
"search_roundtrip_p95_ms": float(np.percentile(search_latencies, 95))
|
||||
if search_latencies
|
||||
else None,
|
||||
"by_phase": {
|
||||
phase: {
|
||||
"positions": len(times),
|
||||
"p50_ms": float(np.percentile(times, 50)),
|
||||
"p95_ms": float(np.percentile(times, 95)),
|
||||
"max_ms": max(times),
|
||||
}
|
||||
for phase, times in by_phase.items()
|
||||
},
|
||||
}
|
||||
Path(args.output).write_text(json.dumps(report, indent=2))
|
||||
print(json.dumps(report))
|
||||
219
ai/strong/bridge.cjs
Normal file
219
ai/strong/bridge.cjs
Normal file
|
|
@ -0,0 +1,219 @@
|
|||
const c = require('../core.cjs'),
|
||||
eco = require('./economics.cjs'),
|
||||
encoders = require('./encoders.cjs'),
|
||||
readline = require('node:readline');
|
||||
let envs = [],
|
||||
sequence = 0;
|
||||
const seed = process.env.SEED || 'strong-train';
|
||||
function searchMove(e, seat, options) {
|
||||
const result = require('./search.cjs').choose(e.g, seat, options);
|
||||
const role = e.roles[seat];
|
||||
const stats = (e.searchStats[role] ||= { decisions: 0, evaluations: 0, truncated: 0 });
|
||||
stats.decisions++;
|
||||
stats.evaluations += result.evaluations || 0;
|
||||
stats.truncated += result.truncated || 0;
|
||||
return result.action;
|
||||
}
|
||||
function applyBot(e, p) {
|
||||
const role = e.roles[p];
|
||||
if (role === 'legacy') {
|
||||
const old = Math.random;
|
||||
Math.random = e.rng;
|
||||
try {
|
||||
c.E.moveAI(e.g, p);
|
||||
} finally {
|
||||
Math.random = old;
|
||||
}
|
||||
} else if (role === 'search' || role === 'search_geo') {
|
||||
const legal = c.candidates(e.g, p),
|
||||
strategic = legal.length > 1 && legal.some((a) => ['ChoosePowerPlant', 'Bid', 'Build'].includes(a.name));
|
||||
c.E.move(
|
||||
e.g,
|
||||
strategic
|
||||
? searchMove(e, p, {
|
||||
samples: role === 'search_geo' ? 16 : 4,
|
||||
candidates: role === 'search_geo' ? 6 : 5,
|
||||
geography: role === 'search_geo',
|
||||
seed: 'arena-search-' + e.g.round + '-' + p + '-' + Math.floor(e.rng() * 1e9),
|
||||
})
|
||||
: eco.choose(e.g, p, e.rng).action,
|
||||
p
|
||||
);
|
||||
} else
|
||||
c.E.move(
|
||||
e.g,
|
||||
role === 'heuristic' ? c.heuristic(e.g, p, e.rng).action : eco.choose(e.g, p, e.rng, role).action,
|
||||
p
|
||||
);
|
||||
e.steps++;
|
||||
}
|
||||
function advance(e) {
|
||||
while (
|
||||
!c.E.ended(e.g) &&
|
||||
e.steps < 1600 &&
|
||||
!['learner', 'snapshot0', 'snapshot1', 'snapshot2'].includes(e.roles[e.g.currentPlayers[0]])
|
||||
)
|
||||
applyBot(e, e.g.currentPlayers[0]);
|
||||
}
|
||||
function observation(e) {
|
||||
if (c.E.ended(e.g) || e.steps >= 1600) return null;
|
||||
const seat = e.g.currentPlayers[0],
|
||||
x = encoders.forRevision(e.featureRevisions[e.roles[seat]]).encode(e.g, seat);
|
||||
delete x.moves;
|
||||
return {
|
||||
...x,
|
||||
episode: e.id,
|
||||
roles: e.roles,
|
||||
round: e.g.round,
|
||||
variant: e.g.options.variant,
|
||||
sealed: !!e.g.options.fastBid,
|
||||
playerCount: e.g.players.length,
|
||||
};
|
||||
}
|
||||
function reset(mode = 'mixed', arenaSeed, arenaId, featureRevisions = {}, playerCount = 3, trainingIndex, learnerSeat) {
|
||||
if (!Number.isInteger(playerCount) || playerCount < 2 || playerCount > 6) throw Error('Invalid player count');
|
||||
if (
|
||||
![
|
||||
'mixed',
|
||||
'mixed_search',
|
||||
'mixed_search_geo',
|
||||
'economic',
|
||||
'heuristic',
|
||||
'rush',
|
||||
'legacy',
|
||||
'selfplay',
|
||||
'snapshot0',
|
||||
'snapshot1',
|
||||
'snapshot2',
|
||||
'search',
|
||||
'search_geo',
|
||||
].includes(mode)
|
||||
)
|
||||
throw Error('Unknown opponent mode: ' + mode);
|
||||
const id = arenaSeed === undefined ? trainingIndex ?? sequence++ : arenaId,
|
||||
seat = learnerSeat ?? Math.floor(id / 4) % playerCount,
|
||||
kind = Math.floor(c.seedrandom(seed + '-opponents-' + id)() * 8);
|
||||
const opponent =
|
||||
mode === 'mixed' || mode === 'mixed_search' || mode === 'mixed_search_geo'
|
||||
? [
|
||||
'economic',
|
||||
'heuristic',
|
||||
'rush',
|
||||
mode === 'mixed_search_geo' ? 'search_geo' : mode === 'mixed_search' ? 'search' : 'legacy',
|
||||
'selfplay',
|
||||
'snapshot0',
|
||||
'snapshot1',
|
||||
'snapshot2',
|
||||
][kind]
|
||||
: mode;
|
||||
const roles =
|
||||
opponent === 'selfplay'
|
||||
? Array(playerCount).fill('learner')
|
||||
: Array.from({ length: playerCount }, (_, i) => (i === seat ? 'learner' : opponent));
|
||||
const gameSeed = arenaSeed === undefined ? seed + '-' + id : arenaSeed + '-' + Math.floor(id / (4 * playerCount));
|
||||
const e = {
|
||||
id,
|
||||
gameSeed,
|
||||
g: c.E.setup(
|
||||
playerCount,
|
||||
{ map: 'Germany', variant: id % 2 ? 'recharged' : 'original', fastBid: id % 4 < 2, showMoney: true },
|
||||
gameSeed
|
||||
),
|
||||
roles,
|
||||
rng: c.seedrandom(arenaSeed === undefined ? seed + '-bot-' + id : gameSeed + '-bot'),
|
||||
steps: 0,
|
||||
policyMoves: {},
|
||||
searchStats: {},
|
||||
featureRevisions,
|
||||
};
|
||||
advance(e);
|
||||
return e;
|
||||
}
|
||||
(async () => {
|
||||
for await (const line of readline.createInterface({ input: process.stdin })) {
|
||||
try {
|
||||
const q = JSON.parse(line),
|
||||
ended = [];
|
||||
if (q.op === 'reset') {
|
||||
const counts = q.playerCounts;
|
||||
if (
|
||||
counts &&
|
||||
(q.arenaSeed !== undefined ||
|
||||
!Array.isArray(counts) ||
|
||||
!counts.length ||
|
||||
new Set(counts).size !== counts.length ||
|
||||
counts.some((n) => !Number.isInteger(n) || n < 2 || n > 6))
|
||||
)
|
||||
throw Error('Mixed player counts require a valid training-only schedule');
|
||||
envs = Array.from({ length: q.n }, (_, i) => {
|
||||
const index = (q.offset || 0) + i;
|
||||
const count = counts ? counts[Math.floor(index / 4) % counts.length] : q.playerCount ?? 3;
|
||||
const seat = counts ? Math.floor(index / (4 * counts.length)) % count : undefined;
|
||||
return reset(
|
||||
q.mode,
|
||||
q.arenaSeed,
|
||||
index,
|
||||
q.featureRevisions,
|
||||
count,
|
||||
counts ? index : undefined,
|
||||
seat
|
||||
);
|
||||
});
|
||||
} else if (q.op === 'step')
|
||||
for (let i = 0; i < envs.length; i++) {
|
||||
const e = envs[i];
|
||||
if (q.actions[i] === null) continue;
|
||||
const seat = e.g.currentPlayers[0];
|
||||
const legal = c.candidates(e.g, seat),
|
||||
choice = q.actions[i];
|
||||
const strategic =
|
||||
legal.length > 1 && legal.some((a) => ['ChoosePowerPlant', 'Bid', 'Build'].includes(a.name));
|
||||
const index = typeof choice === 'object' ? choice.proposal : choice;
|
||||
const action =
|
||||
typeof choice === 'object' && strategic
|
||||
? searchMove(e, seat, {
|
||||
samples: choice.searchSamples,
|
||||
candidates: 6,
|
||||
extraCandidates: choice.disableSearchProposal ? [] : [index],
|
||||
geography: !!choice.geography,
|
||||
seed: 'arena-guided-' + e.id + '-' + e.steps,
|
||||
})
|
||||
: legal[index];
|
||||
c.E.move(e.g, action, seat);
|
||||
if (e.roles[seat] === 'learner') e.policyMoves[action.name] = (e.policyMoves[action.name] || 0) + 1;
|
||||
e.steps++;
|
||||
advance(e);
|
||||
if (c.E.ended(e.g) || e.steps >= 1600)
|
||||
ended.push({
|
||||
env: i,
|
||||
episode: e.id,
|
||||
gameSeed: e.gameSeed,
|
||||
truncated: !c.E.ended(e.g),
|
||||
value: c.E.ended(e.g) ? c.outcome(e.g) : Array(e.g.players.length).fill(0),
|
||||
playerCount: e.g.players.length,
|
||||
variant: e.g.options.variant,
|
||||
sealed: !!e.g.options.fastBid,
|
||||
steps: e.steps,
|
||||
roles: e.roles,
|
||||
policyMoves: e.policyMoves,
|
||||
searchStats: e.searchStats,
|
||||
final: {
|
||||
round: e.g.round,
|
||||
players: e.g.players.map((p) => ({
|
||||
cities: p.cities.length,
|
||||
powered: p.citiesPowered,
|
||||
money: p.money,
|
||||
capacity: c.capacity(p),
|
||||
plants: p.powerPlants.map((pp) => pp.number),
|
||||
})),
|
||||
},
|
||||
});
|
||||
}
|
||||
else throw Error('unknown op');
|
||||
console.log(JSON.stringify({ observations: envs.map(observation), ended }));
|
||||
} catch (err) {
|
||||
console.error(err.stack);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
})();
|
||||
92
ai/strong/check-export.py
Normal file
92
ai/strong/check-export.py
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
"""Check an exported policy against its checkpoint on real engine positions."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import numpy as np
|
||||
import onnxruntime as ort
|
||||
import torch
|
||||
from feature_contract import METADATA_KEY
|
||||
from model import policy_from_checkpoint, tensors
|
||||
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("checkpoint")
|
||||
p.add_argument("model")
|
||||
p.add_argument("fixtures")
|
||||
p.add_argument("--output", required=True)
|
||||
a = p.parse_args()
|
||||
torch.set_num_threads(1)
|
||||
checkpoint = torch.load(a.checkpoint, map_location="cpu", weights_only=True)
|
||||
net = policy_from_checkpoint(checkpoint).eval()
|
||||
options = ort.SessionOptions()
|
||||
options.intra_op_num_threads = 1
|
||||
session = ort.InferenceSession(a.model, options, providers=["CPUExecutionProvider"])
|
||||
revision = session.get_modelmeta().custom_metadata_map.get(METADATA_KEY, "3.0")
|
||||
assert revision == checkpoint.get("feature_revision", "3.0")
|
||||
worker = subprocess.Popen(
|
||||
["node", str(Path(__file__).with_name("worker.cjs"))],
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
text=True,
|
||||
)
|
||||
errors = [0.0, 0.0]
|
||||
count = 0
|
||||
route_counts = {}
|
||||
by_count = {}
|
||||
inactive_values_zero = True
|
||||
try:
|
||||
for line in Path(a.fixtures).read_text().splitlines():
|
||||
request = json.loads(line)["request"]
|
||||
request["featureRevision"] = revision
|
||||
worker.stdin.write(json.dumps(request) + "\n")
|
||||
worker.stdin.flush()
|
||||
row = json.loads(worker.stdout.readline())
|
||||
assert "error" not in row, row
|
||||
inputs = tensors([row], "cpu")
|
||||
with torch.inference_mode():
|
||||
expected = [x.numpy() for x in net(*inputs)]
|
||||
if checkpoint.get("architecture") == "rule_specialists":
|
||||
options = request["state"]["options"]
|
||||
use_sealed = options.get("variant") == "recharged" and bool(
|
||||
options.get("fastBid")
|
||||
)
|
||||
route = "recharged-sealed" if use_sealed else "default"
|
||||
route_counts[route] = route_counts.get(route, 0) + 1
|
||||
component = (
|
||||
net.recharged_sealed_policy if use_sealed else net.default_policy
|
||||
)
|
||||
component_outputs = [x.numpy() for x in component(*inputs)]
|
||||
for selected, correct in zip(expected, component_outputs):
|
||||
np.testing.assert_array_equal(selected, correct)
|
||||
actual = session.run(
|
||||
None, dict(zip(["state", "actions", "mask"], [x.numpy() for x in inputs]))
|
||||
)
|
||||
for i in range(2):
|
||||
errors[i] = max(errors[i], float(np.max(np.abs(expected[i] - actual[i]))))
|
||||
np.testing.assert_allclose(actual[i], expected[i], rtol=1e-4, atol=1e-5)
|
||||
n = len(request["state"]["players"])
|
||||
by_count[str(n)] = by_count.get(str(n), 0) + 1
|
||||
assert row["playerOrder"] == [(request["player"] + i) % n for i in range(n)]
|
||||
assert np.all(actual[1][:, n:] == 0)
|
||||
assert np.isfinite(actual[1]).all() and np.isclose(actual[1].sum(), 1)
|
||||
assert np.argmax(actual[0]) == np.argmax(expected[0])
|
||||
count += 1
|
||||
finally:
|
||||
worker.stdin.close()
|
||||
worker.wait(timeout=10)
|
||||
worker.stdout.close()
|
||||
report = {
|
||||
"positions": count,
|
||||
"by_player_count": by_count,
|
||||
"inactive_values_zero": inactive_values_zero,
|
||||
"feature_revision": revision,
|
||||
"model_sha256": hashlib.sha256(Path(a.model).read_bytes()).hexdigest(),
|
||||
"max_logit_error": errors[0],
|
||||
"max_value_error": errors[1],
|
||||
"all_actions_match": True,
|
||||
"specialist_route_counts": route_counts,
|
||||
}
|
||||
Path(a.output).write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(json.dumps(report))
|
||||
60
ai/strong/combine-arenas.py
Normal file
60
ai/strong/combine-arenas.py
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
"""Combine disjoint paired arena shards without treating seat repeats as independent."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
from arena_statistics import win_summary, search_summary, validate_pairs
|
||||
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("reports", nargs="+")
|
||||
p.add_argument("--output", required=True)
|
||||
a = p.parse_args()
|
||||
reports = [json.loads(Path(x).read_text()) for x in a.reports]
|
||||
keys = [
|
||||
"model_sha256",
|
||||
"model_feature_revision",
|
||||
"encoder_feature_revision",
|
||||
"opponent",
|
||||
"opponent_sha256",
|
||||
"opponent_feature_revision",
|
||||
"paired_seats",
|
||||
"candidate_search_samples",
|
||||
"candidate_geographic_search",
|
||||
"search_max_steps",
|
||||
]
|
||||
for report in reports:
|
||||
report.setdefault("candidate_search_scope", "all")
|
||||
report.setdefault("search_max_steps", 1200)
|
||||
report.setdefault("player_count", 3)
|
||||
report.setdefault("candidate_search_model_proposal", True)
|
||||
keys.extend(
|
||||
["candidate_search_scope", "player_count", "candidate_search_model_proposal"]
|
||||
)
|
||||
config = {k: reports[0][k] for k in keys}
|
||||
rows = []
|
||||
seen = set()
|
||||
for report in reports:
|
||||
assert {k: report[k] for k in keys} == config, "Incompatible arena settings"
|
||||
assert report["paired_seats"] and len(report["results"]) == report["games"]
|
||||
for row in report["results"]:
|
||||
key = (row["gameSeed"], row["variant"], row["sealed"], row["seat"])
|
||||
assert key not in seen, f"Duplicate match: {key}"
|
||||
seen.add(key)
|
||||
rows.append(row)
|
||||
validate_pairs(rows, config["player_count"])
|
||||
result = {
|
||||
**config,
|
||||
"sources": a.reports,
|
||||
**win_summary(rows),
|
||||
**search_summary(rows),
|
||||
"by_rules": [],
|
||||
"results": rows,
|
||||
}
|
||||
for variant in ["original", "recharged"]:
|
||||
for sealed in [False, True]:
|
||||
group = [r for r in rows if r["variant"] == variant and r["sealed"] == sealed]
|
||||
result["by_rules"].append(
|
||||
{"variant": variant, "sealed": sealed, **win_summary(group)}
|
||||
)
|
||||
Path(a.output).write_text(json.dumps(result, indent=2) + "\n")
|
||||
print(json.dumps({k: v for k, v in result.items() if k != "results"}))
|
||||
99
ai/strong/compose-specialists.py
Normal file
99
ai/strong/compose-specialists.py
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
"""CPU-only composition of frozen specialists; no training or gradients."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import torch
|
||||
from model import RuleSpecialists, policy_from_checkpoint
|
||||
from feature_contract import FEATURE_REVISION
|
||||
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("default_checkpoint")
|
||||
p.add_argument("sealed_checkpoint")
|
||||
p.add_argument("output")
|
||||
p.add_argument("--default-revision", required=True)
|
||||
p.add_argument("--sealed-revision", required=True)
|
||||
p.add_argument("--allow-uranium39-transfer", action="store_true")
|
||||
a = p.parse_args()
|
||||
torch.set_num_threads(1)
|
||||
components = []
|
||||
checkpoints = []
|
||||
for path, revision in [
|
||||
(a.default_checkpoint, a.default_revision),
|
||||
(a.sealed_checkpoint, a.sealed_revision),
|
||||
]:
|
||||
ck = torch.load(path, map_location="cpu", weights_only=True)
|
||||
source_features = ck.get("feature_revision", "3.0")
|
||||
if source_features != FEATURE_REVISION and not (
|
||||
source_features == "3.0" and a.allow_uranium39_transfer
|
||||
):
|
||||
raise ValueError(
|
||||
"Explicit authorization required for 3.0 to corrected-feature transfer"
|
||||
)
|
||||
assert ck.get("architecture", "policy") == "policy"
|
||||
checkpoints.append(ck)
|
||||
components.append(
|
||||
{
|
||||
"checkpoint_sha256": hashlib.sha256(Path(path).read_bytes()).hexdigest(),
|
||||
"repository_revision": revision,
|
||||
"source_feature_revision": source_features,
|
||||
"input_feature_revision": FEATURE_REVISION,
|
||||
}
|
||||
)
|
||||
args = {
|
||||
"default_strategic_only": checkpoints[0].get("strategic_only", False),
|
||||
"sealed_strategic_only": checkpoints[1].get("strategic_only", False),
|
||||
}
|
||||
net = RuleSpecialists(**args).eval()
|
||||
net.default_policy.load_state_dict(policy_from_checkpoint(checkpoints[0]).state_dict())
|
||||
net.recharged_sealed_policy.load_state_dict(
|
||||
policy_from_checkpoint(checkpoints[1]).state_dict()
|
||||
)
|
||||
out = Path(a.output)
|
||||
out.mkdir(parents=True, exist_ok=False)
|
||||
checkpoint = {
|
||||
"architecture": "rule_specialists",
|
||||
"model_args": args,
|
||||
"schema": 3,
|
||||
"state_dim": 738,
|
||||
"action_dim": 96,
|
||||
"feature_revision": FEATURE_REVISION,
|
||||
"components": components,
|
||||
"state_dict": net.state_dict(),
|
||||
}
|
||||
torch.save(checkpoint, out / "specialists.pt")
|
||||
(out / "composition.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"architecture": "rule_specialists",
|
||||
"default": "corrected A260 refinement update 40",
|
||||
"recharged_sealed": "B160 weights with explicit uranium-feature correction",
|
||||
"training": "none; frozen-weight composition",
|
||||
"components": components,
|
||||
},
|
||||
indent=2,
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
str(Path(__file__).with_name("export.py")),
|
||||
str(out / "specialists.pt"),
|
||||
str(out / "specialists.onnx"),
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"model": str(out / "specialists.onnx"),
|
||||
"sha256": hashlib.sha256(
|
||||
(out / "specialists.onnx").read_bytes()
|
||||
).hexdigest(),
|
||||
}
|
||||
)
|
||||
)
|
||||
23
ai/strong/diagnose-search-horizon.cjs
Normal file
23
ai/strong/diagnose-search-horizon.cjs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
// Diagnostic preload only: return the original decision, and retry capped searches separately.
|
||||
const fs = require('node:fs');
|
||||
const search = require('./search.cjs');
|
||||
const choose = search.choose;
|
||||
search.choose = function (g, seat, options) {
|
||||
const original = choose(g, seat, { ...options, maxSteps: 1200 });
|
||||
if (original.truncated) {
|
||||
const extended = choose(g, seat, { ...options, maxSteps: 2400 });
|
||||
const record = { seat, options, original, extended, state: g };
|
||||
fs.appendFileSync(process.env.SEARCH_DIAGNOSTIC_PATH, JSON.stringify(record) + '\n');
|
||||
console.error(
|
||||
JSON.stringify({
|
||||
diagnostic: 'search_horizon',
|
||||
seed: options.seed,
|
||||
original_truncated: original.truncated,
|
||||
extended_truncated: extended.truncated,
|
||||
original_index: original.index,
|
||||
extended_index: extended.index,
|
||||
})
|
||||
);
|
||||
}
|
||||
return original;
|
||||
};
|
||||
118
ai/strong/diagnose-search-horizon.py
Normal file
118
ai/strong/diagnose-search-horizon.py
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
"""Replay the one capped arena match without changing its actual policy decisions."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
from huggingface_hub import HfApi, hf_hub_download
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from infer import Model
|
||||
from pool import EnginePool
|
||||
|
||||
repo = "coyotte508/powergrid-ai-germany-v1"
|
||||
model = Model(
|
||||
hf_hub_download(
|
||||
repo,
|
||||
"runs/multiplayer-distillation-v2-hard/best.onnx",
|
||||
revision="ab34dd266010ded1c9a6c818c721e5505dd1ddeb",
|
||||
)
|
||||
)
|
||||
expected_file = hf_hub_download(
|
||||
repo,
|
||||
"runs/multiplayer-hard-e10-search48-search_geo-6p-probe-4/evaluation.json",
|
||||
revision=os.environ["REPORT_REVISION"],
|
||||
)
|
||||
expected = next(
|
||||
r
|
||||
for r in json.loads(Path(expected_file).read_text())["results"]
|
||||
if r["gameSeed"] == "multiplayer-search-strong-probe-v1-6p-5"
|
||||
and r["variant"] == "recharged"
|
||||
and not r["sealed"]
|
||||
and r["seat"] == 1
|
||||
)
|
||||
out = Path("ai/runs/search-horizon-diagnostic-v1")
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
os.environ["NODE_OPTIONS"] = "--require " + str(
|
||||
Path("ai/strong/diagnose-search-horizon.cjs").resolve()
|
||||
)
|
||||
os.environ["SEARCH_DIAGNOSTIC_PATH"] = str((out / "capped-searches.jsonl").resolve())
|
||||
pool = EnginePool(
|
||||
1, seed="multiplayer-search-strong-probe-v1-6p", script="ai/strong/bridge.cjs"
|
||||
)
|
||||
start = last = time.monotonic()
|
||||
try:
|
||||
current = pool.call(
|
||||
dict(
|
||||
op="reset",
|
||||
n=1,
|
||||
playerCount=6,
|
||||
offset=127,
|
||||
mode="search_geo",
|
||||
arenaSeed="multiplayer-search-strong-probe-v1-6p",
|
||||
featureRevisions={"learner": "4.0-multiplayer"},
|
||||
)
|
||||
)["observations"]
|
||||
ends = []
|
||||
while current[0] is not None:
|
||||
x = current[0]
|
||||
action, _ = model.predict(x["state"], x["actions"])
|
||||
reply = pool.call(
|
||||
dict(
|
||||
op="step",
|
||||
actions=[dict(proposal=action, searchSamples=48, geography=True)],
|
||||
)
|
||||
)
|
||||
current = reply["observations"]
|
||||
ends.extend(reply["ended"])
|
||||
if time.monotonic() - last >= 30:
|
||||
print(
|
||||
json.dumps(
|
||||
dict(
|
||||
stage="diagnostic_replay",
|
||||
seconds=time.monotonic() - start,
|
||||
round=x["round"],
|
||||
)
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
last = time.monotonic()
|
||||
finally:
|
||||
pool.close()
|
||||
assert len(ends) == 1
|
||||
actual = ends[0]
|
||||
keys = [
|
||||
"episode",
|
||||
"gameSeed",
|
||||
"truncated",
|
||||
"value",
|
||||
"playerCount",
|
||||
"variant",
|
||||
"sealed",
|
||||
"steps",
|
||||
"roles",
|
||||
"policyMoves",
|
||||
"searchStats",
|
||||
"final",
|
||||
]
|
||||
assert all(actual[k] == expected[k] for k in keys), (
|
||||
"Diagnostic replay diverged from original match"
|
||||
)
|
||||
captured = [
|
||||
json.loads(line)
|
||||
for line in (out / "capped-searches.jsonl").read_text().splitlines()
|
||||
]
|
||||
assert sum(r["original"]["truncated"] for r in captured) == 1
|
||||
report = dict(
|
||||
exact_terminal_replay=True,
|
||||
original=actual,
|
||||
captures=[{k: v for k, v in r.items() if k != "state"} for r in captured],
|
||||
seconds=time.monotonic() - start,
|
||||
)
|
||||
(out / "report.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
HfApi().upload_folder(
|
||||
repo_id=repo, folder_path=str(out), path_in_repo="runs/search-horizon-diagnostic-v1"
|
||||
)
|
||||
print(json.dumps({k: v for k, v in report.items() if k != "original"}), flush=True)
|
||||
366
ai/strong/distill.py
Normal file
366
ai/strong/distill.py
Normal file
|
|
@ -0,0 +1,366 @@
|
|||
"""HF GPU job: distill public-belief search, then measure actual playing strength."""
|
||||
|
||||
from collections import Counter
|
||||
import copy
|
||||
import gzip
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import random
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from huggingface_hub import HfApi, hf_hub_download
|
||||
|
||||
from model import Policy, tensors
|
||||
from model_v4 import MultiplayerPolicy
|
||||
from teacher_contract import validate_game, validation_seeds
|
||||
from distillation_targets import policy_targets
|
||||
from distill_data import source_count_weights, validate_initial_checkpoint
|
||||
from feature_contract import FEATURE_REVISION, embed_revision
|
||||
|
||||
architecture = os.getenv("ARCHITECTURE", "policy")
|
||||
multiplayer = architecture in ["multiplayer", "multiplayer_ordered"]
|
||||
ordered_players = architecture == "multiplayer_ordered"
|
||||
if multiplayer:
|
||||
FEATURE_REVISION = "4.0-multiplayer"
|
||||
if not os.getenv("DATA_REVISION"):
|
||||
raise ValueError("Pin DATA_REVISION for the multiplayer teacher dataset")
|
||||
state_dim, action_dim = (1149, 98) if multiplayer else (738, 96)
|
||||
player_counts = [2, 3, 4, 5, 6] if multiplayer else [3]
|
||||
|
||||
assert torch.cuda.is_available(), "Training must run on a GPU HF Job"
|
||||
torch.set_num_threads(2)
|
||||
seed = int(os.getenv("TRAIN_SEED", "310"))
|
||||
random.seed(seed)
|
||||
np.random.seed(seed)
|
||||
torch.manual_seed(seed)
|
||||
run = os.getenv("RUN_NAME", "search-distillation-v1")
|
||||
out = Path("ai/runs") / run
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
device = "cuda"
|
||||
net = (
|
||||
MultiplayerPolicy(ordered_players=ordered_players) if multiplayer else Policy()
|
||||
).to(device)
|
||||
initial_checkpoint = os.getenv("INIT_CHECKPOINT")
|
||||
initial_revision = os.getenv("INIT_REVISION")
|
||||
if bool(initial_checkpoint) != bool(initial_revision):
|
||||
raise ValueError("Pin both INIT_CHECKPOINT and INIT_REVISION")
|
||||
if initial_checkpoint:
|
||||
if len(initial_revision) != 40 or any(
|
||||
c not in "0123456789abcdef" for c in initial_revision
|
||||
):
|
||||
raise ValueError("INIT_REVISION must be an immutable commit")
|
||||
checkpoint = torch.load(
|
||||
hf_hub_download(
|
||||
os.environ["HF_MODEL_REPO"], initial_checkpoint, revision=initial_revision
|
||||
),
|
||||
map_location="cpu",
|
||||
weights_only=True,
|
||||
)
|
||||
validate_initial_checkpoint(
|
||||
checkpoint, architecture, FEATURE_REVISION, state_dim, action_dim
|
||||
)
|
||||
net.load_state_dict(checkpoint["state_dict"])
|
||||
train, validation = [], []
|
||||
dataset_revisions = []
|
||||
seen_games = set()
|
||||
complete_games = []
|
||||
version = os.getenv("DATA_VERSION", "search-teacher-v1")
|
||||
target_mode = os.getenv("TARGET_MODE", "hard")
|
||||
assert target_mode in ["hard", "soft"]
|
||||
sources = [(version, os.getenv("DATA_REVISION"))]
|
||||
replay_version, replay_revision = (
|
||||
os.getenv("REPLAY_DATA_VERSION"),
|
||||
os.getenv("REPLAY_DATA_REVISION"),
|
||||
)
|
||||
if bool(replay_version) != bool(replay_revision):
|
||||
raise ValueError("Pin both replay dataset version and revision")
|
||||
if replay_version:
|
||||
if len(replay_revision) != 40 or any(
|
||||
c not in "0123456789abcdef" for c in replay_revision
|
||||
):
|
||||
raise ValueError("Replay revision must be an immutable commit")
|
||||
sources.append((replay_version, replay_revision))
|
||||
for source_index, (source_version, source_revision) in enumerate(sources):
|
||||
for shard in range(int(os.getenv("SHARDS", "4"))):
|
||||
path = hf_hub_download(
|
||||
os.environ["HF_DATA_REPO"],
|
||||
f"{source_version}/{source_version}-{shard}.jsonl.gz",
|
||||
repo_type="dataset",
|
||||
revision=source_revision,
|
||||
)
|
||||
dataset_revisions.append(
|
||||
{
|
||||
"version": source_version,
|
||||
"shard": shard,
|
||||
"revision": Path(path).parents[1].name,
|
||||
}
|
||||
)
|
||||
with gzip.open(path, "rt") as source:
|
||||
for line in source:
|
||||
game = json.loads(line)
|
||||
if game.get("featureRevision", "3.0") != FEATURE_REVISION:
|
||||
raise ValueError(
|
||||
"Dataset uses a different feature revision; use its archived encoder or regenerate"
|
||||
)
|
||||
if multiplayer:
|
||||
validate_game(game)
|
||||
if game["seed"] in seen_games:
|
||||
raise ValueError("Duplicate teacher game")
|
||||
seen_games.add(game["seed"])
|
||||
if game["truncated"]:
|
||||
continue
|
||||
game["dataset_source"] = source_index
|
||||
for row in game["rows"]:
|
||||
row["dataset_source"] = source_index
|
||||
row["player_count"] = game.get("playerCount", 3)
|
||||
row["variant"] = game.get("variant")
|
||||
row["sealed"] = game.get("sealed")
|
||||
row["state"] = np.asarray(row["state"], np.float32)
|
||||
row["actions"] = np.asarray(row["actions"], np.float32)
|
||||
complete_games.append(game)
|
||||
held_out = (
|
||||
set().union(
|
||||
*(
|
||||
validation_seeds([g for g in complete_games if g["dataset_source"] == i])
|
||||
for i in range(len(sources))
|
||||
)
|
||||
)
|
||||
if multiplayer
|
||||
else {g["seed"] for g in complete_games if g["id"] % 5 == 0}
|
||||
)
|
||||
for game in complete_games:
|
||||
(validation if game["seed"] in held_out else train).extend(game["rows"])
|
||||
assert train and validation
|
||||
count_sizes = Counter(r["player_count"] for r in train)
|
||||
validation_sizes = Counter(r["player_count"] for r in validation)
|
||||
if multiplayer and (
|
||||
set(count_sizes) != set(player_counts)
|
||||
or set(validation_sizes) != set(player_counts)
|
||||
):
|
||||
raise ValueError("Every player count must appear in training and validation")
|
||||
balance_weights = source_count_weights(train, player_counts)
|
||||
source_count_weights(validation, player_counts)
|
||||
for row in train:
|
||||
row["balance_weight"] = balance_weights[
|
||||
(row["dataset_source"], row["player_count"])
|
||||
]
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"stage": "dataset_loaded",
|
||||
"train_counts": dict(count_sizes),
|
||||
"validation_counts": dict(validation_sizes),
|
||||
"teacher_sources": dataset_revisions,
|
||||
"train_source_counts": {
|
||||
f"{source}/{n}": count
|
||||
for (source, n), count in Counter(
|
||||
(r["dataset_source"], r["player_count"]) for r in train
|
||||
).items()
|
||||
},
|
||||
}
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
optimizer = torch.optim.AdamW(
|
||||
net.parameters(), lr=float(os.getenv("LR", ".0003")), weight_decay=1e-4
|
||||
)
|
||||
metrics = []
|
||||
best = -1
|
||||
batchsize = int(os.getenv("BATCH_SIZE", "256"))
|
||||
|
||||
|
||||
def export(name):
|
||||
torch.save(
|
||||
{
|
||||
"schema": 4 if multiplayer else 3,
|
||||
"architecture": architecture if multiplayer else "policy",
|
||||
"feature_revision": FEATURE_REVISION,
|
||||
"initial_checkpoint": initial_checkpoint,
|
||||
"initial_revision": initial_revision,
|
||||
"teacher_sources": dataset_revisions,
|
||||
"state_dim": state_dim,
|
||||
"action_dim": action_dim,
|
||||
"state_dict": {k: v.detach().cpu() for k, v in net.state_dict().items()},
|
||||
},
|
||||
out / f"{name}.pt",
|
||||
)
|
||||
clone = copy.deepcopy(net).cpu().eval()
|
||||
torch.onnx.export(
|
||||
clone,
|
||||
(
|
||||
torch.zeros(1, state_dim),
|
||||
torch.zeros(1, 8, action_dim),
|
||||
torch.ones(1, 8, dtype=torch.bool),
|
||||
),
|
||||
str(out / f"{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,
|
||||
)
|
||||
embed_revision(out / f"{name}.onnx", FEATURE_REVISION)
|
||||
|
||||
|
||||
def validate():
|
||||
correct, disagreement_correct, disagreements, count = 0, 0, 0, 0
|
||||
by_count = {
|
||||
n: {"positions": 0, "correct": 0, "disagreements": 0, "disagreement_correct": 0}
|
||||
for n in player_counts
|
||||
}
|
||||
with torch.no_grad():
|
||||
for k in range(0, len(validation), batchsize):
|
||||
rows = validation[k : k + batchsize]
|
||||
predicted = net(*tensors(rows, device))[0].argmax(-1).cpu().tolist()
|
||||
for row, chosen in zip(rows, predicted):
|
||||
group = by_count[row["player_count"]]
|
||||
group["positions"] += 1
|
||||
group["correct"] += chosen == row["target"]
|
||||
if not row["teacherAgrees"]:
|
||||
group["disagreements"] += 1
|
||||
group["disagreement_correct"] += chosen == row["target"]
|
||||
correct += chosen == row["target"]
|
||||
count += 1
|
||||
if not row["teacherAgrees"]:
|
||||
disagreements += 1
|
||||
disagreement_correct += chosen == row["target"]
|
||||
return {
|
||||
"positions": count,
|
||||
"by_player_count": by_count,
|
||||
"accuracy": correct / count,
|
||||
"search_disagreements": disagreements,
|
||||
"disagreement_accuracy": disagreement_correct / max(1, disagreements),
|
||||
}
|
||||
|
||||
|
||||
for epoch in range(int(os.getenv("EPOCHS", "30")) + 1):
|
||||
losses = []
|
||||
if epoch:
|
||||
net.train()
|
||||
random.shuffle(train)
|
||||
for k in range(0, len(train), batchsize):
|
||||
rows = train[k : k + batchsize]
|
||||
logits, value = net(*tensors(rows, device))
|
||||
targets = torch.from_numpy(
|
||||
policy_targets(rows, logits.shape[1], soft=target_mode == "soft")
|
||||
).to(device)
|
||||
weights = torch.tensor(
|
||||
[
|
||||
(
|
||||
1.0
|
||||
if r["teacherAgrees"]
|
||||
else float(os.getenv("DISAGREEMENT_WEIGHT", "3"))
|
||||
)
|
||||
* (r["balance_weight"])
|
||||
for r in rows
|
||||
],
|
||||
device=device,
|
||||
)
|
||||
ce = -(targets * logits.log_softmax(-1)).sum(-1)
|
||||
returns = torch.tensor([r["value"] for r in rows], device=device)
|
||||
value_error = ((value - returns) ** 2).sum(-1) / torch.tensor(
|
||||
[r["player_count"] for r in rows], device=device
|
||||
)
|
||||
balance = torch.tensor(
|
||||
[r["balance_weight"] for r in rows],
|
||||
device=device,
|
||||
)
|
||||
loss = (ce * weights).sum() / weights.sum() + 0.2 * (
|
||||
value_error * balance
|
||||
).sum() / balance.sum()
|
||||
optimizer.zero_grad()
|
||||
loss.backward()
|
||||
torch.nn.utils.clip_grad_norm_(net.parameters(), 1)
|
||||
optimizer.step()
|
||||
losses.append(float(loss.detach()))
|
||||
net.eval()
|
||||
metric = {
|
||||
"epoch": epoch,
|
||||
"loss": float(np.mean(losses)) if losses else None,
|
||||
"validation": validate(),
|
||||
}
|
||||
if epoch % 5 == 0:
|
||||
export("latest")
|
||||
results = {}
|
||||
for player_count in player_counts:
|
||||
for opponent in ["economic", "heuristic", "rush"]:
|
||||
result = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
"ai/strong/evaluate.py",
|
||||
str(out / "latest.onnx"),
|
||||
"--opponent",
|
||||
opponent,
|
||||
"--players",
|
||||
str(player_count),
|
||||
"--games",
|
||||
str(8 * player_count if multiplayer else 96),
|
||||
"--workers",
|
||||
"4",
|
||||
"--seed",
|
||||
f"multiplayer-distill-development-{player_count}-v1"
|
||||
if multiplayer
|
||||
else "search-distill-development-v1",
|
||||
"--output",
|
||||
str(out / f"{player_count}p-{opponent}.json"),
|
||||
],
|
||||
text=True,
|
||||
capture_output=True,
|
||||
check=True,
|
||||
)
|
||||
results[f"{player_count}p/{opponent}" if multiplayer else opponent] = (
|
||||
json.loads(result.stdout.strip().splitlines()[-1])
|
||||
)
|
||||
metric["arena"] = results
|
||||
score = np.mean(
|
||||
[
|
||||
(r["win_rate"] - 1 / r["player_count"]) / (1 - 1 / r["player_count"])
|
||||
if multiplayer
|
||||
else r["win_rate"]
|
||||
for r in results.values()
|
||||
]
|
||||
)
|
||||
if score > best:
|
||||
best = score
|
||||
export("best")
|
||||
metrics.append(metric)
|
||||
(out / "metrics.json").write_text(json.dumps(metrics, indent=2))
|
||||
(out / "schema.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"version": 4 if multiplayer else 3,
|
||||
"feature_revision": FEATURE_REVISION,
|
||||
"players": player_counts if multiplayer else 3,
|
||||
"training_positions_by_count": dict(count_sizes),
|
||||
"validation_positions_by_count": dict(validation_sizes),
|
||||
"split": "within each count/seat/rule cell, hold out 20% of whole games ranked by sha256(seed)"
|
||||
if multiplayer
|
||||
else "game id modulo 5",
|
||||
"map": "Germany",
|
||||
"run": run,
|
||||
"training_positions": len(train),
|
||||
"validation_positions": len(validation),
|
||||
"dataset_revisions": dataset_revisions,
|
||||
"dataset_version": version,
|
||||
"target_mode": target_mode,
|
||||
}
|
||||
)
|
||||
)
|
||||
HfApi().upload_folder(
|
||||
repo_id=os.environ["HF_MODEL_REPO"],
|
||||
folder_path=str(out),
|
||||
path_in_repo="runs/" + run,
|
||||
)
|
||||
else:
|
||||
metrics.append(metric)
|
||||
print(json.dumps(metric), flush=True)
|
||||
27
ai/strong/distill_data.py
Normal file
27
ai/strong/distill_data.py
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
"""Balance replay sources without changing their per-player-count coverage."""
|
||||
|
||||
from collections import Counter
|
||||
|
||||
|
||||
def source_count_weights(rows, player_counts):
|
||||
sizes = Counter((r.get("dataset_source", 0), r["player_count"]) for r in rows)
|
||||
sources = {source for source, _ in sizes}
|
||||
expected = {(source, n) for source in sources for n in player_counts}
|
||||
if not rows or set(sizes) != expected:
|
||||
raise ValueError("Every teacher source must cover every player count")
|
||||
return {key: len(rows) / (len(sizes) * size) for key, size in sizes.items()}
|
||||
|
||||
|
||||
def validate_initial_checkpoint(
|
||||
checkpoint, architecture, revision, state_dim, action_dim
|
||||
):
|
||||
expected = dict(
|
||||
architecture=architecture,
|
||||
feature_revision=revision,
|
||||
state_dim=state_dim,
|
||||
action_dim=action_dim,
|
||||
)
|
||||
if any(checkpoint.get(key) != value for key, value in expected.items()):
|
||||
raise ValueError(
|
||||
"Distillation warm start requires the exact architecture and feature contract"
|
||||
)
|
||||
24
ai/strong/distillation_targets.py
Normal file
24
ai/strong/distillation_targets.py
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
"""Targets retain uncertainty across sampled counterfactual search actions."""
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
def policy_targets(rows, candidates, soft=False):
|
||||
targets = np.zeros((len(rows), candidates), dtype=np.float32)
|
||||
for i, row in enumerate(rows):
|
||||
estimates = row.get("searchValues", [])
|
||||
if not soft or not estimates:
|
||||
targets[i, row["target"]] = 1
|
||||
continue
|
||||
indices = np.asarray([x[0] for x in estimates], dtype=np.int64)
|
||||
values = np.asarray([x[1] for x in estimates], dtype=np.float32)
|
||||
assert len(set(indices.tolist())) == len(indices)
|
||||
assert np.all((indices >= 0) & (indices < len(row["actions"])))
|
||||
prior = np.asarray(row["actions"], dtype=np.float32)[indices, 74]
|
||||
# When rollouts cannot distinguish the actions, retain the economic prior.
|
||||
scores = (
|
||||
prior * 2 if values.max() == values.min() else values * 8 + prior * 0.15
|
||||
)
|
||||
weights = np.exp(scores - scores.max())
|
||||
targets[i, indices] = weights / weights.sum()
|
||||
return targets
|
||||
199
ai/strong/economics-v3_0.cjs
Normal file
199
ai/strong/economics-v3_0.cjs
Normal file
|
|
@ -0,0 +1,199 @@
|
|||
// Frozen economic features for historical checkpoints.
|
||||
// Public-information economic calculations. Never inspect the hidden deck or sealed bids.
|
||||
const c = require('../core.cjs');
|
||||
const income = (g, n) => g.paymentTable[Math.max(0, Math.min(g.paymentTable.length - 1, n))];
|
||||
function replenishment(g, r, step = g.step) {
|
||||
return g[r + 'Resupply'][g.players.length - 2][step - 1];
|
||||
}
|
||||
function fuelVariants(pp) {
|
||||
const base = [0, 0, 0, 0];
|
||||
if (pp.type === 4) return Array.from({ length: pp.cost + 1 }, (_, coal) => [coal, pp.cost - coal, 0, 0]);
|
||||
if (pp.type < 4) base[pp.type] = pp.cost;
|
||||
return [base];
|
||||
}
|
||||
function plans(g, p, unused = false) {
|
||||
let result = [{ power: 0, used: [0, 0, 0, 0], plants: [] }];
|
||||
for (const pp of p.powerPlants) {
|
||||
if (unused && !p.powerPlantsNotUsed.includes(pp.number)) continue;
|
||||
const next = [...result];
|
||||
for (const prev of result)
|
||||
for (const need of fuelVariants(pp))
|
||||
next.push({
|
||||
power: prev.power + pp.citiesPowered,
|
||||
used: prev.used.map((x, i) => x + need[i]),
|
||||
plants: [...prev.plants, pp.number],
|
||||
});
|
||||
result = next;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function purchaseCost(g, p, used) {
|
||||
let cost = 0;
|
||||
for (let i = 0; i < 4; i++)
|
||||
for (let k = 0; k < Math.max(0, used[i] - p[c.RES[i] + 'Left']); k++) {
|
||||
if (k >= g[c.RES[i] + 'Market']) return Infinity;
|
||||
cost += c.resourcePrice(g, c.RES[i], k);
|
||||
}
|
||||
return cost;
|
||||
}
|
||||
function plan(g, p, target = p.cities.length, { buy = true, unused = false, budget = p.money, endgame = false } = {}) {
|
||||
let best = { power: 0, used: [0, 0, 0, 0], plants: [], cost: 0, score: -Infinity };
|
||||
for (const option of plans(g, p, unused)) {
|
||||
if (!buy && option.used.some((n, i) => n > p[c.RES[i] + 'Left'])) continue;
|
||||
const cost = buy ? purchaseCost(g, p, option.used) : 0;
|
||||
if (cost > budget) continue;
|
||||
const powered = Math.min(target, option.power + (unused ? p.citiesPowered : 0));
|
||||
const replacement = option.used.reduce((s, n, i) => s + n * c.resourcePrice(g, c.RES[i]), 0);
|
||||
const score = (endgame ? powered * 1000 : income(g, powered)) - cost - (buy ? 0 : replacement * 0.2);
|
||||
if (score > best.score) best = { ...option, powered, cost, score };
|
||||
}
|
||||
return best;
|
||||
}
|
||||
function demand(g, p) {
|
||||
return plan(g, p, Math.max(p.cities.length, Math.min(c.capacity(p), p.cities.length + 3))).used;
|
||||
}
|
||||
function futurePressure(g, r) {
|
||||
const i = c.RES.indexOf(r),
|
||||
needed = g.players.reduce((sum, p) => sum + demand(g, p)[i], 0);
|
||||
return needed - replenishment(g, r);
|
||||
}
|
||||
function context(g, seat) {
|
||||
const p = g.players[seat],
|
||||
cap = c.capacity(p),
|
||||
maxCities = Math.max(...g.players.map((x) => x.cities.length));
|
||||
const imminent = maxCities >= g.citiesToEndGame - 3;
|
||||
const target = Math.min(
|
||||
g.citiesToEndGame,
|
||||
Math.max(p.cities.length, Math.min(cap, p.cities.length + (p.cities.length ? 3 : 2)))
|
||||
);
|
||||
const fuel = plan(g, p, target, { budget: Math.max(0, p.money - (p.cities.length ? 0 : 10)), endgame: imminent });
|
||||
return { p, cap, maxCities, imminent, target, fuel };
|
||||
}
|
||||
function plantValue(g, p, pp) {
|
||||
const before = plan(g, p, 22),
|
||||
currentCap = c.capacity(p);
|
||||
let best = -Infinity;
|
||||
const portfolios =
|
||||
p.powerPlants.length < 3
|
||||
? [[...p.powerPlants, pp]]
|
||||
: p.powerPlants.map((_, i) => [...p.powerPlants.filter((x, j) => i !== j), pp]);
|
||||
for (const powerPlants of portfolios) {
|
||||
const after = plan(g, { ...p, powerPlants }, 22),
|
||||
gain = powerPlants.reduce((s, x) => s + x.citiesPowered, 0) - currentCap;
|
||||
const fuelSaving = before.cost - after.cost;
|
||||
const need = Math.max(0, p.cities.length + 3 - currentCap);
|
||||
const value = pp.number * 0.55 + gain * (need > 0 ? 10 : 6) + fuelSaving * 2;
|
||||
best = Math.max(best, value);
|
||||
}
|
||||
const reserve = p.cities.length === 0 ? 15 : Math.max(8, Math.min(35, p.cities.length * 1.5));
|
||||
return Math.max(0, Math.min(p.money - reserve, best));
|
||||
}
|
||||
function scores(g, seat, actions = c.candidates(g, seat), style = 'economic') {
|
||||
const x = context(g, seat),
|
||||
p = x.p;
|
||||
let production;
|
||||
if (g.phase === c.E.Phase.Bureaucracy)
|
||||
production = plan(g, p, p.cities.length, {
|
||||
buy: false,
|
||||
unused: true,
|
||||
endgame: Math.max(...g.players.map((p) => p.cities.length)) >= g.citiesToEndGame,
|
||||
});
|
||||
const building = g.phase === c.E.Phase.Building;
|
||||
const possible = building ? plan(g, p, p.cities.length + 1, { buy: false }).powered : 0;
|
||||
const availablePower = building ? plan(g, p, x.cap, { buy: false }).powered : 0;
|
||||
const opponentPower = building
|
||||
? Math.max(
|
||||
...g.players
|
||||
.filter((z) => z.id !== seat)
|
||||
.map((z) => plan(g, z, z.cities.length + 2, { buy: false }).powered)
|
||||
)
|
||||
: 0;
|
||||
const bidWorth = g.chosenPowerPlant ? plantValue(g, p, g.chosenPowerPlant) : 0;
|
||||
return actions.map((a) => {
|
||||
const d = a.data;
|
||||
switch (a.name) {
|
||||
case 'ChoosePowerPlant': {
|
||||
const pp = g.actualMarket.find((p) => p.number === d);
|
||||
const v = plantValue(g, p, pp);
|
||||
return v >= d ? 10 + (v - d) * 0.3 + pp.citiesPowered * 0.3 : -20;
|
||||
}
|
||||
case 'Bid': {
|
||||
const v = bidWorth;
|
||||
if (g.round === 1 && !actions.some((a) => a.name === 'Pass')) return -d;
|
||||
return d <= v ? (g.options.fastBid ? 10 - Math.abs(d - v) * 0.5 : 10 - d * 0.2) : -30 - d;
|
||||
}
|
||||
case 'DiscardPowerPlant': {
|
||||
const powerPlants = p.powerPlants.filter((pp) => pp.number !== d);
|
||||
const pp = plan(g, { ...p, powerPlants }, 22);
|
||||
return pp.power * 5 - pp.cost;
|
||||
}
|
||||
case 'BuyResource': {
|
||||
const i = c.RES.indexOf(d.resource),
|
||||
price = c.resourcePrice(g, d.resource);
|
||||
if (p[d.resource + 'Left'] < x.fuel.used[i]) return 30 - price;
|
||||
// Stock one extra round only when demand exceeds replenishment and today's price is low.
|
||||
const surplus = p[d.resource + 'Left'] - x.fuel.used[i],
|
||||
ownNeed = c.fuelDemand(g, p)[d.resource];
|
||||
if (
|
||||
style !== 'rush' &&
|
||||
ownNeed > 0 &&
|
||||
surplus < ownNeed &&
|
||||
price <= 2 &&
|
||||
p.money > 35 &&
|
||||
futurePressure(g, d.resource) > 0
|
||||
)
|
||||
return 4 - price;
|
||||
return -20;
|
||||
}
|
||||
case 'Build': {
|
||||
const next = p.cities.length + 1;
|
||||
if (p.money > 140 || g.round > 18) return 10 - d.price * 0.1;
|
||||
if (next >= g.citiesToEndGame && possible < opponentPower) return -30;
|
||||
if (next <= x.cap && (next <= availablePower || x.imminent)) return 25 - d.price * 0.35;
|
||||
if (style === 'rush' && p.money - d.price > 30) return 8 - d.price * 0.15;
|
||||
return -20;
|
||||
}
|
||||
case 'UsePowerPlant':
|
||||
return production.plants.includes(d.powerPlant) &&
|
||||
c.RES.every((r, i) => d.resourcesSpent.filter((x) => x === r).length <= production.used[i])
|
||||
? 20 +
|
||||
d.citiesPowered * 0.1 -
|
||||
d.resourcesSpent.reduce((s, r) => s + c.resourcePrice(g, r), 0) * 0.01
|
||||
: -10;
|
||||
case 'DiscardResources':
|
||||
return p[d + 'Left'] - x.fuel.used[c.RES.indexOf(d)];
|
||||
case 'Pass':
|
||||
return 0;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
});
|
||||
}
|
||||
function choose(g, seat, rng = () => 0.5, style = 'economic') {
|
||||
const actions = c.candidates(g, seat),
|
||||
values = scores(g, seat, actions, style);
|
||||
let index = 0,
|
||||
best = -Infinity;
|
||||
values.forEach((x, i) => {
|
||||
x += rng() * 0.001;
|
||||
if (x > best) {
|
||||
best = x;
|
||||
index = i;
|
||||
}
|
||||
});
|
||||
return { index, action: actions[index] };
|
||||
}
|
||||
module.exports = {
|
||||
income,
|
||||
replenishment,
|
||||
fuelVariants,
|
||||
plans,
|
||||
purchaseCost,
|
||||
plan,
|
||||
demand,
|
||||
futurePressure,
|
||||
context,
|
||||
plantValue,
|
||||
scores,
|
||||
choose,
|
||||
};
|
||||
210
ai/strong/economics.cjs
Normal file
210
ai/strong/economics.cjs
Normal file
|
|
@ -0,0 +1,210 @@
|
|||
// Public-information economic calculations. Never inspect the hidden deck or sealed bids.
|
||||
const c = require('../core.cjs');
|
||||
const income = (g, n) => g.paymentTable[Math.max(0, Math.min(g.paymentTable.length - 1, n))];
|
||||
function replenishment(g, r, step = g.step) {
|
||||
if (
|
||||
r === 'uranium' &&
|
||||
g.options.variant === 'recharged' &&
|
||||
['Germany', 'Italy'].includes(g.options.map) &&
|
||||
g.card39Bought
|
||||
)
|
||||
return 0;
|
||||
return g[r + 'Resupply'][g.players.length - 2][step - 1];
|
||||
}
|
||||
function fuelVariants(pp) {
|
||||
const base = [0, 0, 0, 0];
|
||||
if (pp.type === 4) return Array.from({ length: pp.cost + 1 }, (_, coal) => [coal, pp.cost - coal, 0, 0]);
|
||||
if (pp.type < 4) base[pp.type] = pp.cost;
|
||||
return [base];
|
||||
}
|
||||
function plans(g, p, unused = false) {
|
||||
let result = [{ power: 0, used: [0, 0, 0, 0], plants: [] }];
|
||||
for (const pp of p.powerPlants) {
|
||||
if (unused && !p.powerPlantsNotUsed.includes(pp.number)) continue;
|
||||
const next = [...result];
|
||||
for (const prev of result)
|
||||
for (const need of fuelVariants(pp))
|
||||
next.push({
|
||||
power: prev.power + pp.citiesPowered,
|
||||
used: prev.used.map((x, i) => x + need[i]),
|
||||
plants: [...prev.plants, pp.number],
|
||||
});
|
||||
result = next;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function purchaseCost(g, p, used) {
|
||||
let cost = 0;
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const resource = c.RES[i],
|
||||
needed = Math.max(0, used[i] - p[resource + 'Left']),
|
||||
count = g[resource + 'Market'],
|
||||
prices = g[resource + 'Prices'];
|
||||
for (let k = 0; k < needed; k++) {
|
||||
if (k >= count) return Infinity;
|
||||
cost += prices && count > k ? prices[prices.length - count + k] : 20;
|
||||
}
|
||||
}
|
||||
return cost;
|
||||
}
|
||||
function plan(g, p, target = p.cities.length, { buy = true, unused = false, budget = p.money, endgame = false } = {}) {
|
||||
let best = { power: 0, used: [0, 0, 0, 0], plants: [], cost: 0, score: -Infinity };
|
||||
for (const option of plans(g, p, unused)) {
|
||||
if (!buy && option.used.some((n, i) => n > p[c.RES[i] + 'Left'])) continue;
|
||||
const cost = buy ? purchaseCost(g, p, option.used) : 0;
|
||||
if (cost > budget) continue;
|
||||
const powered = Math.min(target, option.power + (unused ? p.citiesPowered : 0));
|
||||
const replacement = buy ? 0 : option.used.reduce((s, n, i) => s + n * c.resourcePrice(g, c.RES[i]), 0);
|
||||
const score = (endgame ? powered * 1000 : income(g, powered)) - cost - (buy ? 0 : replacement * 0.2);
|
||||
if (score > best.score) best = { ...option, powered, cost, score };
|
||||
}
|
||||
return best;
|
||||
}
|
||||
function demand(g, p) {
|
||||
return plan(g, p, Math.max(p.cities.length, Math.min(c.capacity(p), p.cities.length + 3))).used;
|
||||
}
|
||||
function futurePressure(g, r) {
|
||||
const i = c.RES.indexOf(r),
|
||||
needed = g.players.reduce((sum, p) => sum + demand(g, p)[i], 0);
|
||||
return needed - replenishment(g, r);
|
||||
}
|
||||
function context(g, seat) {
|
||||
const p = g.players[seat],
|
||||
cap = c.capacity(p),
|
||||
maxCities = Math.max(...g.players.map((x) => x.cities.length));
|
||||
const imminent = maxCities >= g.citiesToEndGame - 3;
|
||||
const target = Math.min(
|
||||
g.citiesToEndGame,
|
||||
Math.max(p.cities.length, Math.min(cap, p.cities.length + (p.cities.length ? 3 : 2)))
|
||||
);
|
||||
const fuel = plan(g, p, target, { budget: Math.max(0, p.money - (p.cities.length ? 0 : 10)), endgame: imminent });
|
||||
return { p, cap, maxCities, imminent, target, fuel };
|
||||
}
|
||||
function plantValue(g, p, pp) {
|
||||
const before = plan(g, p, 22),
|
||||
currentCap = c.capacity(p);
|
||||
let best = -Infinity;
|
||||
const portfolios =
|
||||
p.powerPlants.length < 3
|
||||
? [[...p.powerPlants, pp]]
|
||||
: p.powerPlants.map((_, i) => [...p.powerPlants.filter((x, j) => i !== j), pp]);
|
||||
for (const powerPlants of portfolios) {
|
||||
const after = plan(g, { ...p, powerPlants }, 22),
|
||||
gain = powerPlants.reduce((s, x) => s + x.citiesPowered, 0) - currentCap;
|
||||
const fuelSaving = before.cost - after.cost;
|
||||
const need = Math.max(0, p.cities.length + 3 - currentCap);
|
||||
const value = pp.number * 0.55 + gain * (need > 0 ? 10 : 6) + fuelSaving * 2;
|
||||
best = Math.max(best, value);
|
||||
}
|
||||
const reserve = p.cities.length === 0 ? 15 : Math.max(8, Math.min(35, p.cities.length * 1.5));
|
||||
return Math.max(0, Math.min(p.money - reserve, best));
|
||||
}
|
||||
function scores(g, seat, actions = c.candidates(g, seat), style = 'economic') {
|
||||
const x = context(g, seat),
|
||||
p = x.p;
|
||||
let production;
|
||||
if (g.phase === c.E.Phase.Bureaucracy)
|
||||
production = plan(g, p, p.cities.length, {
|
||||
buy: false,
|
||||
unused: true,
|
||||
endgame: Math.max(...g.players.map((p) => p.cities.length)) >= g.citiesToEndGame,
|
||||
});
|
||||
const building = g.phase === c.E.Phase.Building;
|
||||
const possible = building ? plan(g, p, p.cities.length + 1, { buy: false }).powered : 0;
|
||||
const availablePower = building ? plan(g, p, x.cap, { buy: false }).powered : 0;
|
||||
const opponentPower = building
|
||||
? Math.max(
|
||||
...g.players
|
||||
.filter((z) => z.id !== seat)
|
||||
.map((z) => plan(g, z, z.cities.length + 2, { buy: false }).powered)
|
||||
)
|
||||
: 0;
|
||||
const bidWorth = g.chosenPowerPlant ? plantValue(g, p, g.chosenPowerPlant) : 0;
|
||||
return actions.map((a) => {
|
||||
const d = a.data;
|
||||
switch (a.name) {
|
||||
case 'ChoosePowerPlant': {
|
||||
const pp = g.actualMarket.find((p) => p.number === d);
|
||||
const v = plantValue(g, p, pp);
|
||||
return v >= d ? 10 + (v - d) * 0.3 + pp.citiesPowered * 0.3 : -20;
|
||||
}
|
||||
case 'Bid': {
|
||||
const v = bidWorth;
|
||||
if (g.round === 1 && !actions.some((a) => a.name === 'Pass')) return -d;
|
||||
return d <= v ? (g.options.fastBid ? 10 - Math.abs(d - v) * 0.5 : 10 - d * 0.2) : -30 - d;
|
||||
}
|
||||
case 'DiscardPowerPlant': {
|
||||
const powerPlants = p.powerPlants.filter((pp) => pp.number !== d);
|
||||
const pp = plan(g, { ...p, powerPlants }, 22);
|
||||
return pp.power * 5 - pp.cost;
|
||||
}
|
||||
case 'BuyResource': {
|
||||
const i = c.RES.indexOf(d.resource),
|
||||
price = c.resourcePrice(g, d.resource);
|
||||
if (p[d.resource + 'Left'] < x.fuel.used[i]) return 30 - price;
|
||||
// Stock one extra round only when demand exceeds replenishment and today's price is low.
|
||||
const surplus = p[d.resource + 'Left'] - x.fuel.used[i],
|
||||
ownNeed = c.fuelDemand(g, p)[d.resource];
|
||||
if (
|
||||
style !== 'rush' &&
|
||||
ownNeed > 0 &&
|
||||
surplus < ownNeed &&
|
||||
price <= 2 &&
|
||||
p.money > 35 &&
|
||||
futurePressure(g, d.resource) > 0
|
||||
)
|
||||
return 4 - price;
|
||||
return -20;
|
||||
}
|
||||
case 'Build': {
|
||||
const next = p.cities.length + 1;
|
||||
if (p.money > 140 || g.round > 18) return 10 - d.price * 0.1;
|
||||
if (next >= g.citiesToEndGame && possible < opponentPower) return -30;
|
||||
if (next <= x.cap && (next <= availablePower || x.imminent)) return 25 - d.price * 0.35;
|
||||
if (style === 'rush' && p.money - d.price > 30) return 8 - d.price * 0.15;
|
||||
return -20;
|
||||
}
|
||||
case 'UsePowerPlant':
|
||||
return production.plants.includes(d.powerPlant) &&
|
||||
c.RES.every((r, i) => d.resourcesSpent.filter((x) => x === r).length <= production.used[i])
|
||||
? 20 +
|
||||
d.citiesPowered * 0.1 -
|
||||
d.resourcesSpent.reduce((s, r) => s + c.resourcePrice(g, r), 0) * 0.01
|
||||
: -10;
|
||||
case 'DiscardResources':
|
||||
return p[d + 'Left'] - x.fuel.used[c.RES.indexOf(d)];
|
||||
case 'Pass':
|
||||
return 0;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
});
|
||||
}
|
||||
function choose(g, seat, rng = () => 0.5, style = 'economic') {
|
||||
const actions = c.candidates(g, seat),
|
||||
values = scores(g, seat, actions, style);
|
||||
let index = 0,
|
||||
best = -Infinity;
|
||||
values.forEach((x, i) => {
|
||||
x += rng() * 0.001;
|
||||
if (x > best) {
|
||||
best = x;
|
||||
index = i;
|
||||
}
|
||||
});
|
||||
return { index, action: actions[index] };
|
||||
}
|
||||
module.exports = {
|
||||
income,
|
||||
replenishment,
|
||||
fuelVariants,
|
||||
plans,
|
||||
purchaseCost,
|
||||
plan,
|
||||
demand,
|
||||
futurePressure,
|
||||
context,
|
||||
plantValue,
|
||||
scores,
|
||||
choose,
|
||||
};
|
||||
8
ai/strong/encoders.cjs
Normal file
8
ai/strong/encoders.cjs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
const current = require('./features.cjs');
|
||||
function forRevision(revision = current.FEATURE_REVISION) {
|
||||
if (revision === current.FEATURE_REVISION) return current;
|
||||
if (revision === '4.0-multiplayer') return require('./features-v4.cjs');
|
||||
if (revision === '3.0') return require('./features-v3_0.cjs');
|
||||
throw Error('Unsupported feature revision: ' + revision);
|
||||
}
|
||||
module.exports = { forRevision };
|
||||
227
ai/strong/evaluate.py
Normal file
227
ai/strong/evaluate.py
Normal file
|
|
@ -0,0 +1,227 @@
|
|||
"""Independent CPU arena, with reserved seeds and per-rule results."""
|
||||
|
||||
import sys, argparse, json, time
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
import numpy as np
|
||||
from infer import Model
|
||||
from pool import EnginePool
|
||||
from async_pool import AsyncEnginePool
|
||||
from arena_statistics import win_summary, search_summary, validate_pairs
|
||||
from search_scope import SCOPES, search_enabled
|
||||
from feature_contract import FEATURE_REVISION, check_revision, model_revision
|
||||
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("model")
|
||||
p.add_argument("--players", type=int, choices=range(2, 7), default=3)
|
||||
p.add_argument("--deal-offset", type=int, default=0)
|
||||
p.add_argument("--search-scope", choices=SCOPES, default="all")
|
||||
p.add_argument(
|
||||
"--opponent",
|
||||
default="economic",
|
||||
choices=["economic", "heuristic", "rush", "legacy", "search", "search_geo"],
|
||||
)
|
||||
p.add_argument("--opponent-model", help="Frozen ONNX policy in every opponent seat")
|
||||
p.add_argument("--workers", type=int, default=4)
|
||||
p.add_argument(
|
||||
"--async-rollout",
|
||||
action="store_true",
|
||||
help="Advance ready games independently using one engine process per game",
|
||||
)
|
||||
p.add_argument("--geographic-search", action="store_true")
|
||||
p.add_argument(
|
||||
"--disable-search-proposal",
|
||||
action="store_true",
|
||||
help="Ablation: omit the model candidate from search; keep model actions outside search",
|
||||
)
|
||||
p.add_argument(
|
||||
"--search-samples",
|
||||
type=int,
|
||||
default=0,
|
||||
help="Public-belief search guided by the candidate model",
|
||||
)
|
||||
p.add_argument("--games", type=int, default=480)
|
||||
p.add_argument("--seed", default="strong-screening-v1")
|
||||
p.add_argument("--output", required=True)
|
||||
p.add_argument(
|
||||
"--allow-feature-transfer",
|
||||
action="store_true",
|
||||
help="Explicit research-only encoder transfer",
|
||||
)
|
||||
args = p.parse_args()
|
||||
if not 0 <= args.search_samples <= 64:
|
||||
p.error("--search-samples must be 0..64")
|
||||
if args.disable_search_proposal and not args.search_samples:
|
||||
p.error("--disable-search-proposal requires positive --search-samples")
|
||||
if args.geographic_search and not args.search_samples:
|
||||
p.error("--geographic-search requires positive --search-samples")
|
||||
search_max_steps = int(
|
||||
subprocess.check_output(
|
||||
[
|
||||
"node",
|
||||
"-e",
|
||||
"console.log(require('./ai/strong/search.cjs').DEFAULT_MAX_STEPS)",
|
||||
],
|
||||
text=True,
|
||||
)
|
||||
)
|
||||
model = Model(args.model)
|
||||
paired_size = 4 * args.players
|
||||
if args.games < paired_size or args.games % paired_size:
|
||||
p.error(
|
||||
f"--games must be a positive multiple of {paired_size} for paired rules and seats"
|
||||
)
|
||||
if args.deal_offset < 0:
|
||||
p.error("--deal-offset cannot be negative")
|
||||
opponent_model = Model(args.opponent_model) if args.opponent_model else None
|
||||
for actor in [model, opponent_model]:
|
||||
if actor and args.players != 3 and model_revision(actor) != "4.0-multiplayer":
|
||||
p.error("Non-three-player evaluation requires schema 4 for every model")
|
||||
if args.allow_feature_transfer and model_revision(model) == "4.0-multiplayer":
|
||||
p.error("Schema 4 cannot be transferred to a schema 3 encoder")
|
||||
pool_class = AsyncEnginePool if args.async_rollout else EnginePool
|
||||
engine_workers = args.games if args.async_rollout else min(args.workers, args.games)
|
||||
pool = pool_class(engine_workers, seed=args.seed, script="ai/strong/bridge.cjs")
|
||||
feature_revision = (
|
||||
FEATURE_REVISION if args.allow_feature_transfer else model_revision(model)
|
||||
)
|
||||
feature_revisions = (
|
||||
{} if args.allow_feature_transfer else {"learner": model_revision(model)}
|
||||
)
|
||||
if opponent_model and not args.allow_feature_transfer:
|
||||
feature_revisions["snapshot0"] = model_revision(opponent_model)
|
||||
try:
|
||||
current = pool.call(
|
||||
{
|
||||
"op": "reset",
|
||||
"n": args.games,
|
||||
"playerCount": args.players,
|
||||
"offset": args.deal_offset * paired_size,
|
||||
"mode": "snapshot0" if opponent_model else args.opponent,
|
||||
"arenaSeed": args.seed,
|
||||
"featureRevisions": feature_revisions,
|
||||
}
|
||||
)["observations"]
|
||||
except BaseException:
|
||||
pool.close()
|
||||
raise
|
||||
rows = []
|
||||
latency = []
|
||||
start = time.perf_counter()
|
||||
last_progress = start
|
||||
try:
|
||||
while any(x is not None for x in current):
|
||||
actions = []
|
||||
for x in current:
|
||||
if x is None:
|
||||
actions.append(None)
|
||||
continue
|
||||
t = time.perf_counter()
|
||||
actor = model if x["roles"][x["seat"]] == "learner" else opponent_model
|
||||
check_revision(
|
||||
actor, x.get("featureRevision", "3.0"), args.allow_feature_transfer
|
||||
)
|
||||
a, _ = actor.predict(x["state"], x["actions"])
|
||||
if actor is model:
|
||||
latency.append(1000 * (time.perf_counter() - t))
|
||||
actions.append(
|
||||
{
|
||||
"proposal": a,
|
||||
"searchSamples": args.search_samples,
|
||||
"geography": args.geographic_search,
|
||||
"disableSearchProposal": args.disable_search_proposal,
|
||||
}
|
||||
if actor is model
|
||||
and args.search_samples
|
||||
and search_enabled(args.search_scope, x["variant"], x["sealed"])
|
||||
else a
|
||||
)
|
||||
r = pool.call({"op": "step", "actions": actions})
|
||||
current = r["observations"]
|
||||
for e in r["ended"]:
|
||||
seat = e["roles"].index("learner")
|
||||
rows.append(
|
||||
{
|
||||
**e,
|
||||
"seat": seat,
|
||||
"variant": "recharged" if e["episode"] % 2 else "original",
|
||||
"sealed": e["episode"] % 4 < 2,
|
||||
"win": e["value"][seat],
|
||||
}
|
||||
)
|
||||
if time.perf_counter() - last_progress >= 30:
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"stage": "arena_progress",
|
||||
"completed_games": len(rows),
|
||||
"requested_games": args.games,
|
||||
"seconds": time.perf_counter() - start,
|
||||
"seed": args.seed,
|
||||
}
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
last_progress = time.perf_counter()
|
||||
finally:
|
||||
pool.close()
|
||||
validate_pairs(rows, args.players)
|
||||
report = {
|
||||
"async_rollout": args.async_rollout,
|
||||
"engine_workers": engine_workers,
|
||||
"player_count": args.players,
|
||||
"chance_win_rate": 1 / args.players,
|
||||
"deal_offset": args.deal_offset,
|
||||
"model": args.model,
|
||||
"model_sha256": model.sha256,
|
||||
"model_feature_revision": model_revision(model),
|
||||
"encoder_feature_revision": feature_revision,
|
||||
"opponent": args.opponent_model or args.opponent,
|
||||
"opponent_sha256": opponent_model.sha256 if opponent_model else None,
|
||||
"opponent_feature_revision": model_revision(opponent_model)
|
||||
if opponent_model
|
||||
else None,
|
||||
"paired_seats": True,
|
||||
"candidate_search_samples": args.search_samples,
|
||||
"search_max_steps": search_max_steps,
|
||||
"candidate_search_scope": args.search_scope,
|
||||
"candidate_geographic_search": args.geographic_search,
|
||||
"candidate_search_model_proposal": not args.disable_search_proposal,
|
||||
"seed": args.seed,
|
||||
"games": len(rows),
|
||||
"win_rate": float(np.mean([r["win"] for r in rows])),
|
||||
"truncated": sum(r["truncated"] for r in rows),
|
||||
"seconds": time.perf_counter() - start,
|
||||
"inference_p95_ms": float(np.percentile(latency, 95)),
|
||||
"by_rules": [
|
||||
{
|
||||
"variant": v,
|
||||
"sealed": s,
|
||||
"games": len([r for r in rows if r["variant"] == v and r["sealed"] == s]),
|
||||
"win_rate": float(
|
||||
np.mean(
|
||||
[r["win"] for r in rows if r["variant"] == v and r["sealed"] == s]
|
||||
)
|
||||
),
|
||||
}
|
||||
for v in ["original", "recharged"]
|
||||
for s in [False, True]
|
||||
],
|
||||
"results": rows,
|
||||
}
|
||||
report.update(win_summary(rows))
|
||||
report.update(search_summary(rows))
|
||||
for group in report["by_rules"]:
|
||||
group.update(
|
||||
win_summary(
|
||||
[
|
||||
r
|
||||
for r in rows
|
||||
if r["variant"] == group["variant"] and r["sealed"] == group["sealed"]
|
||||
]
|
||||
)
|
||||
)
|
||||
Path(args.output).write_text(json.dumps(report, indent=2))
|
||||
print(json.dumps({k: v for k, v in report.items() if k != "results"}))
|
||||
28782
ai/strong/experiments.json
Normal file
28782
ai/strong/experiments.json
Normal file
File diff suppressed because it is too large
Load diff
51
ai/strong/export.py
Normal file
51
ai/strong/export.py
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
"""CPU-only checkpoint conversion; no gradient updates."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import torch
|
||||
from model import policy_from_checkpoint
|
||||
from feature_contract import embed_revision
|
||||
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("checkpoint")
|
||||
p.add_argument("output")
|
||||
p.add_argument("--strategic-only", action="store_true")
|
||||
args = p.parse_args()
|
||||
torch.set_num_threads(1)
|
||||
checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=True)
|
||||
strategic_only = args.strategic_only or checkpoint.get("strategic_only", False)
|
||||
if args.strategic_only and checkpoint.get("architecture", "policy") != "policy":
|
||||
p.error("Strategic-only override requires a single policy")
|
||||
checkpoint["strategic_only"] = strategic_only
|
||||
net = policy_from_checkpoint(checkpoint).eval()
|
||||
torch.onnx.export(
|
||||
net,
|
||||
(
|
||||
torch.zeros(1, checkpoint.get("state_dim", 738)),
|
||||
torch.zeros(1, 8, checkpoint.get("action_dim", 96)),
|
||||
torch.ones(1, 8, dtype=torch.bool),
|
||||
),
|
||||
args.output,
|
||||
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,
|
||||
)
|
||||
embed_revision(args.output, checkpoint.get("feature_revision", "3.0"))
|
||||
Path(args.output + ".json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"source": args.checkpoint,
|
||||
"strategic_only": strategic_only,
|
||||
"schema": checkpoint.get("schema", 3),
|
||||
}
|
||||
)
|
||||
)
|
||||
26
ai/strong/feature_contract.py
Normal file
26
ai/strong/feature_contract.py
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
"""Keep checkpoints paired with the exact meaning of their input features."""
|
||||
|
||||
FEATURE_REVISION = "3.1-uranium39"
|
||||
METADATA_KEY = "powergrid.feature_revision"
|
||||
|
||||
|
||||
def model_revision(model):
|
||||
return model.session.get_modelmeta().custom_metadata_map.get(METADATA_KEY, "3.0")
|
||||
|
||||
|
||||
def check_revision(model, observed, allow_transfer=False):
|
||||
trained = model_revision(model)
|
||||
if trained != observed and not allow_transfer:
|
||||
raise ValueError(
|
||||
f"Feature revision mismatch: model {trained}, encoder {observed}"
|
||||
)
|
||||
|
||||
|
||||
def embed_revision(path, revision=FEATURE_REVISION):
|
||||
import onnx
|
||||
|
||||
model = onnx.load(str(path))
|
||||
props = {p.key: p.value for p in model.metadata_props}
|
||||
props[METADATA_KEY] = revision
|
||||
onnx.helper.set_model_props(model, props)
|
||||
onnx.save(model, str(path))
|
||||
84
ai/strong/features-v3_0.cjs
Normal file
84
ai/strong/features-v3_0.cjs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
// Frozen encoder for historical checkpoints; do not update its semantics.
|
||||
const c = require('../core.cjs'),
|
||||
eco = require('./economics-v3_0.cjs');
|
||||
const SCHEMA = 3;
|
||||
const spatial = require('./spatial.cjs');
|
||||
function observe(g, seat, geometry) {
|
||||
const state = c.observe(g, seat),
|
||||
order = [seat, (seat + 1) % 3, (seat + 2) % 3];
|
||||
for (const r of c.RES) {
|
||||
const supplies = g[r + 'Resupply'][g.players.length - 2];
|
||||
state.push(...supplies.map((n) => n / 12), c.resourcePrice(g, r) / 20);
|
||||
// Exact capped refill available now, and shared demand under full portfolio use.
|
||||
state.push(Math.min(g[r + 'Supply'], eco.replenishment(g, r), g[r + 'Prices'].length - g[r + 'Market']) / 24);
|
||||
}
|
||||
state.push(g.currentPlayers.length / 3, ...order.map((i) => +g.currentPlayers.includes(i)));
|
||||
for (const id of order) {
|
||||
const p = g.players[id],
|
||||
desired = eco.demand(g, p),
|
||||
fuelled = eco.plan(g, p, 22, { buy: false });
|
||||
state.push(
|
||||
c.capacity(p) / 22,
|
||||
fuelled.power / 22,
|
||||
...desired.map((n) => n / 12),
|
||||
...p.powerPlants.slice(0, 4).map((pp) => +p.powerPlantsNotUsed.includes(pp.number)),
|
||||
...Array(Math.max(0, 4 - p.powerPlants.length)).fill(0)
|
||||
);
|
||||
state.push(...Array.from({ length: 4 }, (_, i) => +(p.powerPlants[i]?.type === 6)));
|
||||
const rank = g.playerOrder.indexOf(id);
|
||||
state.push(rank / 2, (2 - rank) / 2, +!p.passed, +!p.skipAuction);
|
||||
for (const r of c.RES) {
|
||||
const i = c.RES.indexOf(r);
|
||||
state.push(Math.max(0, desired[i] - p[r + 'Left']) / 12);
|
||||
}
|
||||
}
|
||||
state.push(...g.paymentTable.slice(0, 23).map((n) => n / 200));
|
||||
if (!state.every(Number.isFinite)) throw Error('nonfinite strong observation');
|
||||
return [...state, ...spatial.stateFeatures(g, seat, geometry)];
|
||||
}
|
||||
function encode(g, seat) {
|
||||
const moves = c.candidates(g, seat),
|
||||
prior = eco.scores(g, seat, moves),
|
||||
p = g.players[seat];
|
||||
const best = Math.max(...prior);
|
||||
const geometry = spatial.territories(g, seat),
|
||||
worth = new Map(),
|
||||
ownDemand = eco.demand(g, p);
|
||||
const plantWorth = (pp) => {
|
||||
if (!worth.has(pp.number)) worth.set(pp.number, eco.plantValue(g, p, pp));
|
||||
return worth.get(pp.number);
|
||||
};
|
||||
const actions = moves.map((a, i) => {
|
||||
const pp = a.name === 'ChoosePowerPlant' ? g.actualMarket.find((p) => p.number === a.data) : g.chosenPowerPlant;
|
||||
const cost =
|
||||
a.name === 'BuyResource'
|
||||
? c.resourcePrice(g, a.data.resource)
|
||||
: a.name === 'Bid'
|
||||
? a.data
|
||||
: a.data?.price || 0;
|
||||
const extra = [
|
||||
Math.max(-10, Math.min(10, prior[i] / 10)),
|
||||
+(prior[i] === best),
|
||||
cost / Math.max(1, p.money),
|
||||
Math.max(0, p.money - cost) / 200,
|
||||
];
|
||||
if (pp) extra.push(plantWorth(pp) / 200, pp.citiesPowered / 8, pp.cost / 4);
|
||||
else extra.push(0, 0, 0);
|
||||
if (a.name === 'BuyResource') {
|
||||
const r = a.data.resource,
|
||||
j = c.RES.indexOf(r);
|
||||
extra.push(eco.replenishment(g, r) / 12, (ownDemand[j] - p[r + 'Left']) / 12);
|
||||
} else extra.push(0, 0);
|
||||
return [...c.actionFeatures(g, seat, a), ...extra, ...spatial.actionFeatures(g, seat, a, geometry)];
|
||||
});
|
||||
return {
|
||||
featureRevision: '3.0',
|
||||
state: observe(g, seat, geometry),
|
||||
actions,
|
||||
moves,
|
||||
prior: prior.map((x) => Math.max(-10, Math.min(10, x / 10))),
|
||||
teacher: prior.indexOf(best),
|
||||
seat,
|
||||
};
|
||||
}
|
||||
module.exports = { SCHEMA, observe, encode };
|
||||
175
ai/strong/features-v4.cjs
Normal file
175
ai/strong/features-v4.cjs
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
// Schema 4: fixed-size public observations for 2–6 players. Schema 3 stays frozen.
|
||||
const c = require('../core.cjs'),
|
||||
eco = require('./economics.cjs'),
|
||||
spatial = require('./spatial.cjs');
|
||||
const FEATURE_REVISION = '4.0-multiplayer',
|
||||
MAX_PLAYERS = 6;
|
||||
const pad = (xs, n) => [...xs, ...Array(Math.max(0, n - xs.length)).fill(0)];
|
||||
const plant = (p) =>
|
||||
p
|
||||
? [p.number / 50, p.cost / 4, p.citiesPowered / 8, ...Array.from({ length: 7 }, (_, i) => +(p.type === i))]
|
||||
: Array(10).fill(0);
|
||||
function assertScope(g, seat) {
|
||||
if (
|
||||
g.map.name !== 'Germany' ||
|
||||
g.players.length < 2 ||
|
||||
g.players.length > 6 ||
|
||||
g.options.randomizeMap ||
|
||||
g.options.chooseRegions ||
|
||||
g.options.chooseColors ||
|
||||
g.map.cities.some((x) => !c.CITIES.includes(x.name))
|
||||
)
|
||||
throw Error('Schema 4 supports automatic Germany games with 2–6 players');
|
||||
if (!Number.isInteger(seat) || seat < 0 || seat >= g.players.length) throw Error('Invalid observing seat');
|
||||
}
|
||||
function observe(g, seat, geometry = spatial.territories(g, seat)) {
|
||||
assertScope(g, seat);
|
||||
const n = g.players.length,
|
||||
order = Array.from({ length: n }, (_, i) => (seat + i) % n);
|
||||
const playerMask = pad(
|
||||
order.map(() => 1),
|
||||
MAX_PLAYERS
|
||||
);
|
||||
const global = [
|
||||
...Object.values(c.E.Phase).map((x) => +(x === g.phase)),
|
||||
g.round / 20,
|
||||
g.step / 3,
|
||||
+(g.options.variant === 'recharged'),
|
||||
+g.options.fastBid,
|
||||
n / 6,
|
||||
g.cardsLeft / 50,
|
||||
+g.nextCardWeak,
|
||||
(g.options.fastBid ? 0 : g.currentBid || 0) / 100,
|
||||
(g.minimunBid || 0) / 100,
|
||||
g.citiesToEndGame / 25,
|
||||
g.citiesToStep2 / 20,
|
||||
+!!g.card39Bought,
|
||||
g.currentPlayers.length / n,
|
||||
];
|
||||
for (const r of c.RES)
|
||||
global.push(
|
||||
g[r + 'Market'] / 24,
|
||||
g[r + 'Supply'] / 24,
|
||||
...pad(
|
||||
g[r + 'Prices'].map((x) => x / 20),
|
||||
24
|
||||
),
|
||||
...[1, 2, 3].map((step) => eco.replenishment(g, r, step) / 12),
|
||||
c.resourcePrice(g, r) / 20,
|
||||
Math.min(g[r + 'Supply'], eco.replenishment(g, r), g[r + 'Prices'].length - g[r + 'Market']) / 24
|
||||
);
|
||||
global.push(
|
||||
...pad(
|
||||
g.paymentTable.slice(0, 23).map((x) => x / 200),
|
||||
23
|
||||
)
|
||||
);
|
||||
for (let i = 0; i < 4; i++) global.push(...plant(g.actualMarket[i]), ...plant(g.futureMarket[i]));
|
||||
global.push(...plant(g.chosenPowerPlant));
|
||||
const players = order.map((id) => {
|
||||
const p = g.players[id],
|
||||
rank = g.playerOrder.indexOf(id),
|
||||
demand = eco.demand(g, p),
|
||||
fuel = eco.plan(g, p, 22, { buy: false });
|
||||
const row = [
|
||||
p.money / 500,
|
||||
p.cities.length / 22,
|
||||
p.housesLeft / 22,
|
||||
p.citiesPowered / 22,
|
||||
rank / (n - 1),
|
||||
(n - 1 - rank) / (n - 1),
|
||||
+p.skipAuction,
|
||||
+p.passed,
|
||||
+g.currentPlayers.includes(id),
|
||||
+(g.auctioningPlayer === id),
|
||||
(g.options.fastBid ? 0 : p.bid || 0) / 100,
|
||||
p.hybridCapacity / 24,
|
||||
c.capacity(p) / 22,
|
||||
fuel.power / 22,
|
||||
];
|
||||
for (const [j, r] of c.RES.entries())
|
||||
row.push(
|
||||
p[r + 'Left'] / 24,
|
||||
p[r + 'Capacity'] / 24,
|
||||
demand[j] / 12,
|
||||
Math.max(0, demand[j] - p[r + 'Left']) / 12
|
||||
);
|
||||
for (let i = 0; i < 4; i++)
|
||||
row.push(
|
||||
...plant(p.powerPlants[i]),
|
||||
+!!p.powerPlants[i] && +p.powerPlantsNotUsed.includes(p.powerPlants[i].number)
|
||||
);
|
||||
return row;
|
||||
});
|
||||
const playerWidth = players[0].length;
|
||||
while (players.length < MAX_PLAYERS) players.push(Array(playerWidth).fill(0));
|
||||
const cities = c.CITIES.flatMap((name) => [
|
||||
+g.map.cities.some((x) => x.name === name),
|
||||
...pad(
|
||||
order.map((id) => +g.players[id].cities.some((x) => x.name === name)),
|
||||
MAX_PLAYERS
|
||||
),
|
||||
]);
|
||||
const territory = [];
|
||||
for (const [groups, limit] of [
|
||||
[geometry.regions, 8],
|
||||
[geometry.islands, 4],
|
||||
])
|
||||
for (let i = 0; i < limit; i++) {
|
||||
const x = groups[i];
|
||||
territory.push(
|
||||
...(x
|
||||
? [
|
||||
1,
|
||||
x.size / 64,
|
||||
x.empty / 64,
|
||||
x.open / 64,
|
||||
x.totalFree / 128,
|
||||
...pad(
|
||||
x.owned.map((v) => v / 22),
|
||||
MAX_PLAYERS
|
||||
),
|
||||
]
|
||||
: Array(11).fill(0))
|
||||
);
|
||||
}
|
||||
territory.push((g.map.crossIslandSurcharge || 0) / 100);
|
||||
const state = [...playerMask, ...global, ...players.flat(), ...cities, ...territory];
|
||||
if (!state.every(Number.isFinite)) throw Error('Nonfinite schema 4 observation');
|
||||
return {
|
||||
state,
|
||||
playerMask,
|
||||
playerOrder: order,
|
||||
layout: { global: global.length, player: playerWidth, cities: cities.length, territory: territory.length },
|
||||
};
|
||||
}
|
||||
function encode(g, seat) {
|
||||
const geometry = spatial.territories(g, seat),
|
||||
observation = observe(g, seat, geometry);
|
||||
const moves = c.candidates(g, seat),
|
||||
raw = eco.scores(g, seat, moves),
|
||||
best = Math.max(...raw);
|
||||
const actions = moves.map((a, i) => {
|
||||
const geo = spatial.actionFeatures(g, seat, a, geometry),
|
||||
n = g.players.length;
|
||||
return [
|
||||
...c.actionFeatures(g, seat, a),
|
||||
Math.max(-10, Math.min(10, raw[i] / 10)),
|
||||
+(raw[i] === best),
|
||||
...pad(geo.slice(0, n), 6),
|
||||
...pad(geo.slice(n, 2 * n), 6),
|
||||
...pad(geo.slice(2 * n, 3 * n), 6),
|
||||
...geo.slice(3 * n),
|
||||
];
|
||||
});
|
||||
return {
|
||||
featureRevision: FEATURE_REVISION,
|
||||
...observation,
|
||||
actions,
|
||||
moves,
|
||||
prior: raw.map((x) => Math.max(-10, Math.min(10, x / 10))),
|
||||
teacher: raw.indexOf(best),
|
||||
seat,
|
||||
};
|
||||
}
|
||||
module.exports = { SCHEMA: 4, FEATURE_REVISION, MAX_PLAYERS, observe, encode };
|
||||
84
ai/strong/features.cjs
Normal file
84
ai/strong/features.cjs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
const c = require('../core.cjs'),
|
||||
eco = require('./economics.cjs');
|
||||
const SCHEMA = 3;
|
||||
const FEATURE_REVISION = '3.1-uranium39';
|
||||
const spatial = require('./spatial.cjs');
|
||||
function observe(g, seat, geometry) {
|
||||
const state = c.observe(g, seat),
|
||||
order = [seat, (seat + 1) % 3, (seat + 2) % 3];
|
||||
for (const r of c.RES) {
|
||||
const supplies = [1, 2, 3].map((step) => eco.replenishment(g, r, step));
|
||||
state.push(...supplies.map((n) => n / 12), c.resourcePrice(g, r) / 20);
|
||||
// Exact capped refill available now, and shared demand under full portfolio use.
|
||||
state.push(Math.min(g[r + 'Supply'], eco.replenishment(g, r), g[r + 'Prices'].length - g[r + 'Market']) / 24);
|
||||
}
|
||||
state.push(g.currentPlayers.length / 3, ...order.map((i) => +g.currentPlayers.includes(i)));
|
||||
for (const id of order) {
|
||||
const p = g.players[id],
|
||||
desired = eco.demand(g, p),
|
||||
fuelled = eco.plan(g, p, 22, { buy: false });
|
||||
state.push(
|
||||
c.capacity(p) / 22,
|
||||
fuelled.power / 22,
|
||||
...desired.map((n) => n / 12),
|
||||
...p.powerPlants.slice(0, 4).map((pp) => +p.powerPlantsNotUsed.includes(pp.number)),
|
||||
...Array(Math.max(0, 4 - p.powerPlants.length)).fill(0)
|
||||
);
|
||||
state.push(...Array.from({ length: 4 }, (_, i) => +(p.powerPlants[i]?.type === 6)));
|
||||
const rank = g.playerOrder.indexOf(id);
|
||||
state.push(rank / 2, (2 - rank) / 2, +!p.passed, +!p.skipAuction);
|
||||
for (const r of c.RES) {
|
||||
const i = c.RES.indexOf(r);
|
||||
state.push(Math.max(0, desired[i] - p[r + 'Left']) / 12);
|
||||
}
|
||||
}
|
||||
state.push(...g.paymentTable.slice(0, 23).map((n) => n / 200));
|
||||
if (!state.every(Number.isFinite)) throw Error('nonfinite strong observation');
|
||||
return [...state, ...spatial.stateFeatures(g, seat, geometry)];
|
||||
}
|
||||
function encode(g, seat) {
|
||||
const moves = c.candidates(g, seat),
|
||||
prior = eco.scores(g, seat, moves),
|
||||
p = g.players[seat];
|
||||
const best = Math.max(...prior);
|
||||
const geometry = spatial.territories(g, seat),
|
||||
worth = new Map(),
|
||||
ownDemand = eco.demand(g, p);
|
||||
const plantWorth = (pp) => {
|
||||
if (!worth.has(pp.number)) worth.set(pp.number, eco.plantValue(g, p, pp));
|
||||
return worth.get(pp.number);
|
||||
};
|
||||
const actions = moves.map((a, i) => {
|
||||
const pp = a.name === 'ChoosePowerPlant' ? g.actualMarket.find((p) => p.number === a.data) : g.chosenPowerPlant;
|
||||
const cost =
|
||||
a.name === 'BuyResource'
|
||||
? c.resourcePrice(g, a.data.resource)
|
||||
: a.name === 'Bid'
|
||||
? a.data
|
||||
: a.data?.price || 0;
|
||||
const extra = [
|
||||
Math.max(-10, Math.min(10, prior[i] / 10)),
|
||||
+(prior[i] === best),
|
||||
cost / Math.max(1, p.money),
|
||||
Math.max(0, p.money - cost) / 200,
|
||||
];
|
||||
if (pp) extra.push(plantWorth(pp) / 200, pp.citiesPowered / 8, pp.cost / 4);
|
||||
else extra.push(0, 0, 0);
|
||||
if (a.name === 'BuyResource') {
|
||||
const r = a.data.resource,
|
||||
j = c.RES.indexOf(r);
|
||||
extra.push(eco.replenishment(g, r) / 12, (ownDemand[j] - p[r + 'Left']) / 12);
|
||||
} else extra.push(0, 0);
|
||||
return [...c.actionFeatures(g, seat, a), ...extra, ...spatial.actionFeatures(g, seat, a, geometry)];
|
||||
});
|
||||
return {
|
||||
featureRevision: FEATURE_REVISION,
|
||||
state: observe(g, seat, geometry),
|
||||
actions,
|
||||
moves,
|
||||
prior: prior.map((x) => Math.max(-10, Math.min(10, x / 10))),
|
||||
teacher: prior.indexOf(best),
|
||||
seat,
|
||||
};
|
||||
}
|
||||
module.exports = { SCHEMA, FEATURE_REVISION, observe, encode };
|
||||
171
ai/strong/final-protocol-multiplayer.json
Normal file
171
ai/strong/final-protocol-multiplayer.json
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
{
|
||||
"status": "prepared; no selected candidate; final seeds unused",
|
||||
"seed_prefix": "strong-multiplayer-final-reserved-v1",
|
||||
"scope": {
|
||||
"map": "Germany",
|
||||
"players": [2, 3, 4, 5, 6],
|
||||
"variants": ["original", "recharged"],
|
||||
"auctions": ["open", "sealed"],
|
||||
"setup": "automatic"
|
||||
},
|
||||
"reason_for_new_protocol": "Scope expanded from three players to 2\u20136 before any final seeds were used. Preserve the original three-player minimum rates; scale other counts by the same fraction of improvement above equal-seat chance. Default-bot minimum stays 90% at every count.",
|
||||
"pairing": "Every independent deal is repeated in each candidate seat and all four rule combinations. Exactly 4*N matches per deal; disjoint integer deal offsets across shards.",
|
||||
"intervals": "95% seed-cluster bootstrap; resample deals, retaining their seat/rule repeats. Report each count/rule separately. Intervals are per comparison, not a simultaneous family-wide confidence guarantee.",
|
||||
"requirements": {
|
||||
"all_games_complete": true,
|
||||
"no_illegal_moves": true,
|
||||
"full_paired_deals": true,
|
||||
"each_count_overall_interval_lower_bound": "strictly above 1/N",
|
||||
"each_count_each_rule_interval_lower_bound": "strictly above 1/N",
|
||||
"search_rollout_counts": "required, with incomplete rollouts explicitly reported",
|
||||
"export_parity": "All 2553 multiplayer fixtures agree in legal action with checkpoint, finite value outputs, inactive slots zero",
|
||||
"serving": "All 2553 fixtures return legal moves with correct request/revision and player ordering; benchmark same selected model/search settings on actual AMD 8840U, with results for every count",
|
||||
"package": "Standalone extracted archive hashes and legal CPU responses verified"
|
||||
},
|
||||
"opponents": [
|
||||
{
|
||||
"name": "legacy",
|
||||
"independent_deals_per_count": 40,
|
||||
"counts": {
|
||||
"2": {
|
||||
"games": 320,
|
||||
"minimum_win_rate": 0.9
|
||||
},
|
||||
"3": {
|
||||
"games": 480,
|
||||
"minimum_win_rate": 0.9
|
||||
},
|
||||
"4": {
|
||||
"games": 640,
|
||||
"minimum_win_rate": 0.9
|
||||
},
|
||||
"5": {
|
||||
"games": 800,
|
||||
"minimum_win_rate": 0.9
|
||||
},
|
||||
"6": {
|
||||
"games": 960,
|
||||
"minimum_win_rate": 0.9
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "heuristic",
|
||||
"independent_deals_per_count": 40,
|
||||
"counts": {
|
||||
"2": {
|
||||
"games": 320,
|
||||
"minimum_win_rate": 0.775
|
||||
},
|
||||
"3": {
|
||||
"games": 480,
|
||||
"minimum_win_rate": 0.7000000000000001
|
||||
},
|
||||
"4": {
|
||||
"games": 640,
|
||||
"minimum_win_rate": 0.6625000000000001
|
||||
},
|
||||
"5": {
|
||||
"games": 800,
|
||||
"minimum_win_rate": 0.6400000000000001
|
||||
},
|
||||
"6": {
|
||||
"games": 960,
|
||||
"minimum_win_rate": 0.625
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "economic",
|
||||
"independent_deals_per_count": 40,
|
||||
"counts": {
|
||||
"2": {
|
||||
"games": 320,
|
||||
"minimum_win_rate": 0.6625
|
||||
},
|
||||
"3": {
|
||||
"games": 480,
|
||||
"minimum_win_rate": 0.55
|
||||
},
|
||||
"4": {
|
||||
"games": 640,
|
||||
"minimum_win_rate": 0.49375
|
||||
},
|
||||
"5": {
|
||||
"games": 800,
|
||||
"minimum_win_rate": 0.46
|
||||
},
|
||||
"6": {
|
||||
"games": 960,
|
||||
"minimum_win_rate": 0.4375
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "rush",
|
||||
"independent_deals_per_count": 40,
|
||||
"counts": {
|
||||
"2": {
|
||||
"games": 320,
|
||||
"minimum_win_rate": 0.625
|
||||
},
|
||||
"3": {
|
||||
"games": 480,
|
||||
"minimum_win_rate": 0.5
|
||||
},
|
||||
"4": {
|
||||
"games": 640,
|
||||
"minimum_win_rate": 0.4375
|
||||
},
|
||||
"5": {
|
||||
"games": 800,
|
||||
"minimum_win_rate": 0.4
|
||||
},
|
||||
"6": {
|
||||
"games": 960,
|
||||
"minimum_win_rate": 0.375
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "search_geo",
|
||||
"independent_deals_per_count": 80,
|
||||
"counts": {
|
||||
"2": {
|
||||
"games": 640,
|
||||
"minimum_win_rate": 0.55
|
||||
},
|
||||
"3": {
|
||||
"games": 960,
|
||||
"minimum_win_rate": 0.4
|
||||
},
|
||||
"4": {
|
||||
"games": 1280,
|
||||
"minimum_win_rate": 0.325
|
||||
},
|
||||
"5": {
|
||||
"games": 1600,
|
||||
"minimum_win_rate": 0.28
|
||||
},
|
||||
"6": {
|
||||
"games": 1920,
|
||||
"minimum_win_rate": 0.25
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "frozen_a260",
|
||||
"counts": {
|
||||
"3": {
|
||||
"games": 960,
|
||||
"minimum_win_rate": 0.4
|
||||
}
|
||||
},
|
||||
"independent_deals_per_count": 80,
|
||||
"model_path": "runs/strong-league-v2-a/best.onnx",
|
||||
"model_revision": "b38515c29e57826de05b55b645c29591e4a886bf",
|
||||
"model_sha256": "9b46db558669a0c3085412fe2544359eda55ed9f092dffb67bead6af3c409ecd"
|
||||
}
|
||||
],
|
||||
"failure_policy": "A failed gate remains a failure. Do not relax thresholds after seeing final results. New candidate requires a new reserved final seed prefix."
|
||||
}
|
||||
35
ai/strong/final-protocol.json
Normal file
35
ai/strong/final-protocol.json
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
{
|
||||
"status": "prepared; candidate not selected; final seeds unused",
|
||||
"seed_prefix": "strong-final-reserved-v1",
|
||||
"scope": "Germany, three players, automatic setup, original/Recharged, open/sealed",
|
||||
"pairing": "Each independent deal is repeated across all three candidate seats and all four rule combinations.",
|
||||
"intervals": "95% bootstrap intervals resample independent deals, retaining correlated seat and rule repeats. Intervals are per comparison, not a simultaneous family-wide confidence claim.",
|
||||
"requirements": {
|
||||
"all_games_complete": true,
|
||||
"no_illegal_moves": true,
|
||||
"no_missing_or_duplicate_paired_matches": true,
|
||||
"overall_interval_lower_bound_above": 0.3333333333333333,
|
||||
"each_rule_interval_lower_bound_above": 0.3333333333333333,
|
||||
"report_search_rollout_truncations": true,
|
||||
"export_action_parity": "All 427 fixture positions must agree with the training checkpoint.",
|
||||
"cpu_serving": "All 427 fixtures must return legal moves on the AMD 8840U; report cold, warm, search-only and phase-specific latency.",
|
||||
"package": "Verify file hashes and legal responses from the extracted standalone archive."
|
||||
},
|
||||
"opponents": [
|
||||
{ "name": "legacy", "games": 480, "minimum_win_rate": 0.9 },
|
||||
{ "name": "heuristic", "games": 480, "minimum_win_rate": 0.7 },
|
||||
{ "name": "economic", "games": 480, "minimum_win_rate": 0.55 },
|
||||
{ "name": "rush", "games": 480, "minimum_win_rate": 0.5 },
|
||||
{ "name": "search_geo", "games": 960, "minimum_win_rate": 0.4 },
|
||||
{
|
||||
"name": "frozen_a260",
|
||||
"games": 960,
|
||||
"minimum_win_rate": 0.4,
|
||||
"model_path": "runs/strong-league-v2-a/best.onnx",
|
||||
"model_revision": "b38515c29e57826de05b55b645c29591e4a886bf",
|
||||
"model_sha256": "9b46db558669a0c3085412fe2544359eda55ed9f092dffb67bead6af3c409ecd"
|
||||
}
|
||||
],
|
||||
"failure_policy": "A failed gate is reported as a failure; do not weaken thresholds after seeing final results. Any subsequent model selection uses new development evidence and a new final seed prefix.",
|
||||
"claim_limits": "These gates establish strength against the measured opponent suite, not expert-human strength, other maps/player counts, or calibrated analysis values."
|
||||
}
|
||||
555
ai/strong/fixtures/search-horizon-six-player.json
Normal file
555
ai/strong/fixtures/search-horizon-six-player.json
Normal file
|
|
@ -0,0 +1,555 @@
|
|||
{
|
||||
"seat": 1,
|
||||
"options": {
|
||||
"samples": 48,
|
||||
"candidates": 6,
|
||||
"extraCandidates": [39],
|
||||
"geography": true,
|
||||
"seed": "arena-guided-127-8"
|
||||
},
|
||||
"original": {
|
||||
"index": 0,
|
||||
"action": { "name": "Bid", "data": 12 },
|
||||
"evaluations": 240,
|
||||
"truncated": 1,
|
||||
"winEstimate": 0.16666666666666666,
|
||||
"values": { "0": 8, "1": 6, "2": 7, "19": 0, "39": 6 }
|
||||
},
|
||||
"extended": {
|
||||
"index": 0,
|
||||
"action": { "name": "Bid", "data": 12 },
|
||||
"evaluations": 240,
|
||||
"truncated": 0,
|
||||
"winEstimate": 0.16666666666666666,
|
||||
"values": { "0": 8, "1": 6, "2": 8, "19": 0, "39": 6 }
|
||||
},
|
||||
"state": {
|
||||
"map": {
|
||||
"name": "Germany",
|
||||
"cities": [
|
||||
{ "name": "Flensburg", "region": "green", "x": 37, "y": 427 },
|
||||
{ "name": "Kiel", "region": "green", "x": 106, "y": 392 },
|
||||
{ "name": "Hamburg", "region": "green", "x": 212, "y": 396 },
|
||||
{ "name": "Hannover", "region": "green", "x": 378, "y": 395 },
|
||||
{ "name": "Bremen", "region": "green", "x": 276, "y": 463 },
|
||||
{ "name": "Wilhelmshaven", "region": "green", "x": 211, "y": 521 },
|
||||
{ "name": "Cuxhaven", "region": "green", "x": 168, "y": 474 },
|
||||
{ "name": "Lubeck", "region": "brown", "x": 153, "y": 341 },
|
||||
{ "name": "Rostock", "region": "brown", "x": 128, "y": 256 },
|
||||
{ "name": "Schwerin", "region": "brown", "x": 217, "y": 297 },
|
||||
{ "name": "Stralsund", "region": "brown", "x": 210, "y": 126 },
|
||||
{ "name": "Magdeburg", "region": "brown", "x": 389, "y": 271 },
|
||||
{ "name": "Berlin", "region": "brown", "x": 355, "y": 170 },
|
||||
{ "name": "Frankfurt-O", "region": "brown", "x": 381, "y": 99 },
|
||||
{ "name": "Halle", "region": "yellow", "x": 493, "y": 259 },
|
||||
{ "name": "Leipzig", "region": "yellow", "x": 526, "y": 222 },
|
||||
{ "name": "Dresden", "region": "yellow", "x": 572, "y": 126 },
|
||||
{ "name": "Erfurt", "region": "yellow", "x": 567, "y": 309 },
|
||||
{ "name": "Fulda", "region": "yellow", "x": 628, "y": 398 },
|
||||
{ "name": "W\u00fcrzburg", "region": "yellow", "x": 735, "y": 386 },
|
||||
{ "name": "Nurnberg", "region": "yellow", "x": 780, "y": 309 },
|
||||
{ "name": "Aachen", "region": "cyan", "x": 614, "y": 654 },
|
||||
{ "name": "K\u00f6ln", "region": "cyan", "x": 590, "y": 589 },
|
||||
{ "name": "Trier", "region": "cyan", "x": 739, "y": 628 },
|
||||
{ "name": "Mainz", "region": "cyan", "x": 697, "y": 514 },
|
||||
{ "name": "Frankfurt-M", "region": "cyan", "x": 672, "y": 473 },
|
||||
{ "name": "Saarbr\u00fccken", "region": "cyan", "x": 818, "y": 568 },
|
||||
{ "name": "Mannheim", "region": "cyan", "x": 796, "y": 479 },
|
||||
{ "name": "Freiburg", "region": "purple", "x": 966, "y": 537 },
|
||||
{ "name": "Stuttgart", "region": "purple", "x": 884, "y": 458 },
|
||||
{ "name": "Konstanz", "region": "purple", "x": 1011, "y": 459 },
|
||||
{ "name": "Augsburg", "region": "purple", "x": 911, "y": 346 },
|
||||
{ "name": "Regensburg", "region": "purple", "x": 846, "y": 256 },
|
||||
{ "name": "M\u00fcnchen", "region": "purple", "x": 967, "y": 278 },
|
||||
{ "name": "Passau", "region": "purple", "x": 904, "y": 153 }
|
||||
],
|
||||
"connections": [
|
||||
{ "nodes": ["Flensburg", "Kiel"], "cost": 4 },
|
||||
{ "nodes": ["Kiel", "Hamburg"], "cost": 8 },
|
||||
{ "nodes": ["Kiel", "Lubeck"], "cost": 4 },
|
||||
{ "nodes": ["Hamburg", "Hannover"], "cost": 17 },
|
||||
{ "nodes": ["Hamburg", "Bremen"], "cost": 11 },
|
||||
{ "nodes": ["Hamburg", "Cuxhaven"], "cost": 11 },
|
||||
{ "nodes": ["Hamburg", "Lubeck"], "cost": 6 },
|
||||
{ "nodes": ["Hamburg", "Schwerin"], "cost": 8 },
|
||||
{ "nodes": ["Bremen", "Wilhelmshaven"], "cost": 11 },
|
||||
{ "nodes": ["Bremen", "Hannover"], "cost": 10 },
|
||||
{ "nodes": ["Bremen", "Cuxhaven"], "cost": 8 },
|
||||
{ "nodes": ["Hannover", "Schwerin"], "cost": 19 },
|
||||
{ "nodes": ["Hannover", "Magdeburg"], "cost": 15 },
|
||||
{ "nodes": ["Hannover", "Erfurt"], "cost": 19 },
|
||||
{ "nodes": ["Lubeck", "Schwerin"], "cost": 6 },
|
||||
{ "nodes": ["Schwerin", "Rostock"], "cost": 6 },
|
||||
{ "nodes": ["Schwerin", "Stralsund"], "cost": 19 },
|
||||
{ "nodes": ["Schwerin", "Berlin"], "cost": 18 },
|
||||
{ "nodes": ["Schwerin", "Magdeburg"], "cost": 16 },
|
||||
{ "nodes": ["Stralsund", "Rostock"], "cost": 19 },
|
||||
{ "nodes": ["Stralsund", "Berlin"], "cost": 15 },
|
||||
{ "nodes": ["Berlin", "Magdeburg"], "cost": 10 },
|
||||
{ "nodes": ["Berlin", "Frankfurt-O"], "cost": 6 },
|
||||
{ "nodes": ["Berlin", "Halle"], "cost": 17 },
|
||||
{ "nodes": ["Magdeburg", "Halle"], "cost": 11 },
|
||||
{ "nodes": ["Frankfurt-O", "Leipzig"], "cost": 21 },
|
||||
{ "nodes": ["Frankfurt-O", "Dresden"], "cost": 16 },
|
||||
{ "nodes": ["Halle", "Leipzig"], "cost": 0 },
|
||||
{ "nodes": ["Leipzig", "Dresden"], "cost": 13 },
|
||||
{ "nodes": ["Erfurt", "Halle"], "cost": 6 },
|
||||
{ "nodes": ["Erfurt", "Dresden"], "cost": 19 },
|
||||
{ "nodes": ["Erfurt", "Nurnberg"], "cost": 21 },
|
||||
{ "nodes": ["Erfurt", "Fulda"], "cost": 13 },
|
||||
{ "nodes": ["Fulda", "W\u00fcrzburg"], "cost": 11 },
|
||||
{ "nodes": ["Fulda", "Frankfurt-M"], "cost": 8 },
|
||||
{ "nodes": ["W\u00fcrzburg", "Nurnberg"], "cost": 8 },
|
||||
{ "nodes": ["W\u00fcrzburg", "Frankfurt-M"], "cost": 13 },
|
||||
{ "nodes": ["W\u00fcrzburg", "Mannheim"], "cost": 10 },
|
||||
{ "nodes": ["W\u00fcrzburg", "Stuttgart"], "cost": 12 },
|
||||
{ "nodes": ["W\u00fcrzburg", "Augsburg"], "cost": 19 },
|
||||
{ "nodes": ["Nurnberg", "Augsburg"], "cost": 18 },
|
||||
{ "nodes": ["Nurnberg", "Regensburg"], "cost": 12 },
|
||||
{ "nodes": ["Aachen", "K\u00f6ln"], "cost": 7 },
|
||||
{ "nodes": ["Aachen", "Trier"], "cost": 19 },
|
||||
{ "nodes": ["Trier", "K\u00f6ln"], "cost": 20 },
|
||||
{ "nodes": ["Trier", "Mainz"], "cost": 18 },
|
||||
{ "nodes": ["Trier", "Saarbr\u00fccken"], "cost": 11 },
|
||||
{ "nodes": ["Mainz", "Frankfurt-M"], "cost": 0 },
|
||||
{ "nodes": ["Mainz", "K\u00f6ln"], "cost": 21 },
|
||||
{ "nodes": ["Mainz", "Saarbr\u00fccken"], "cost": 10 },
|
||||
{ "nodes": ["Mainz", "Mannheim"], "cost": 11 },
|
||||
{ "nodes": ["Mannheim", "Saarbr\u00fccken"], "cost": 16 },
|
||||
{ "nodes": ["Mannheim", "Stuttgart"], "cost": 6 },
|
||||
{ "nodes": ["Stuttgart", "Saarbr\u00fccken"], "cost": 17 },
|
||||
{ "nodes": ["Stuttgart", "Freiburg"], "cost": 16 },
|
||||
{ "nodes": ["Stuttgart", "Konstanz"], "cost": 16 },
|
||||
{ "nodes": ["Stuttgart", "Augsburg"], "cost": 15 },
|
||||
{ "nodes": ["Konstanz", "Freiburg"], "cost": 14 },
|
||||
{ "nodes": ["Konstanz", "Augsburg"], "cost": 17 },
|
||||
{ "nodes": ["Regensburg", "Augsburg"], "cost": 13 },
|
||||
{ "nodes": ["Regensburg", "M\u00fcnchen"], "cost": 10 },
|
||||
{ "nodes": ["Regensburg", "Passau"], "cost": 12 },
|
||||
{ "nodes": ["Augsburg", "M\u00fcnchen"], "cost": 6 },
|
||||
{ "nodes": ["Passau", "M\u00fcnchen"], "cost": 14 }
|
||||
],
|
||||
"layout": "Landscape",
|
||||
"mapPosition": [20, 20],
|
||||
"mapSpecificRules": "Stop resupplying uranium after power plant 39 has been bought.",
|
||||
"viewBox": [1465, 860],
|
||||
"adjustRatio": [1, 1],
|
||||
"playerOrderPosition": [1160, 140],
|
||||
"cityCountPosition": [0, 0],
|
||||
"powerPlantMarketPosition": [745, 0],
|
||||
"actualMarketWidth": 430,
|
||||
"buttonsPosition": [1305, 0],
|
||||
"playerBoardsPosition": [1105, 200],
|
||||
"roundInfoPosition": [20, 590],
|
||||
"supplyPosition": [0, 720]
|
||||
},
|
||||
"players": [
|
||||
{
|
||||
"id": 0,
|
||||
"powerPlants": [],
|
||||
"coalCapacity": 0,
|
||||
"coalLeft": 0,
|
||||
"oilCapacity": 0,
|
||||
"oilLeft": 0,
|
||||
"garbageCapacity": 0,
|
||||
"garbageLeft": 0,
|
||||
"uraniumCapacity": 0,
|
||||
"uraniumLeft": 0,
|
||||
"hybridCapacity": 0,
|
||||
"hybridLeft": 0,
|
||||
"money": 50,
|
||||
"housesLeft": 22,
|
||||
"cities": [],
|
||||
"powerPlantsNotUsed": [],
|
||||
"availableMoves": null,
|
||||
"lastMove": { "name": "Pass", "data": true },
|
||||
"isDropped": false,
|
||||
"isAI": false,
|
||||
"bid": 7,
|
||||
"passed": true,
|
||||
"skipAuction": false,
|
||||
"citiesPowered": 0,
|
||||
"resourcesUsed": [],
|
||||
"totalIncome": 0,
|
||||
"totalSpentCities": 0,
|
||||
"totalSpentConnections": 0,
|
||||
"totalSpentPlants": 0,
|
||||
"totalSpentResources": 0,
|
||||
"usedFreeJump": false,
|
||||
"totalTimeUsed": 0
|
||||
},
|
||||
{
|
||||
"id": 1,
|
||||
"powerPlants": [],
|
||||
"coalCapacity": 0,
|
||||
"coalLeft": 0,
|
||||
"oilCapacity": 0,
|
||||
"oilLeft": 0,
|
||||
"garbageCapacity": 0,
|
||||
"garbageLeft": 0,
|
||||
"uraniumCapacity": 0,
|
||||
"uraniumLeft": 0,
|
||||
"hybridCapacity": 0,
|
||||
"hybridLeft": 0,
|
||||
"money": 50,
|
||||
"housesLeft": 22,
|
||||
"cities": [],
|
||||
"powerPlantsNotUsed": [],
|
||||
"availableMoves": {
|
||||
"Bid": [
|
||||
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
|
||||
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50
|
||||
],
|
||||
"Pass": [true]
|
||||
},
|
||||
"lastMove": { "name": "Bid", "data": 8 },
|
||||
"isDropped": false,
|
||||
"isAI": false,
|
||||
"bid": 8,
|
||||
"passed": false,
|
||||
"skipAuction": false,
|
||||
"citiesPowered": 0,
|
||||
"resourcesUsed": [],
|
||||
"totalIncome": 0,
|
||||
"totalSpentCities": 0,
|
||||
"totalSpentConnections": 0,
|
||||
"totalSpentPlants": 0,
|
||||
"totalSpentResources": 0,
|
||||
"usedFreeJump": false,
|
||||
"totalTimeUsed": 0
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"powerPlants": [],
|
||||
"coalCapacity": 0,
|
||||
"coalLeft": 0,
|
||||
"oilCapacity": 0,
|
||||
"oilLeft": 0,
|
||||
"garbageCapacity": 0,
|
||||
"garbageLeft": 0,
|
||||
"uraniumCapacity": 0,
|
||||
"uraniumLeft": 0,
|
||||
"hybridCapacity": 0,
|
||||
"hybridLeft": 0,
|
||||
"money": 50,
|
||||
"housesLeft": 22,
|
||||
"cities": [],
|
||||
"powerPlantsNotUsed": [],
|
||||
"availableMoves": null,
|
||||
"lastMove": { "name": "Bid", "data": 11 },
|
||||
"isDropped": false,
|
||||
"isAI": false,
|
||||
"bid": 11,
|
||||
"passed": false,
|
||||
"skipAuction": false,
|
||||
"citiesPowered": 0,
|
||||
"resourcesUsed": [],
|
||||
"totalIncome": 0,
|
||||
"totalSpentCities": 0,
|
||||
"totalSpentConnections": 0,
|
||||
"totalSpentPlants": 0,
|
||||
"totalSpentResources": 0,
|
||||
"usedFreeJump": false,
|
||||
"totalTimeUsed": 0
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"powerPlants": [],
|
||||
"coalCapacity": 0,
|
||||
"coalLeft": 0,
|
||||
"oilCapacity": 0,
|
||||
"oilLeft": 0,
|
||||
"garbageCapacity": 0,
|
||||
"garbageLeft": 0,
|
||||
"uraniumCapacity": 0,
|
||||
"uraniumLeft": 0,
|
||||
"hybridCapacity": 0,
|
||||
"hybridLeft": 0,
|
||||
"money": 50,
|
||||
"housesLeft": 22,
|
||||
"cities": [],
|
||||
"powerPlantsNotUsed": [],
|
||||
"availableMoves": null,
|
||||
"lastMove": { "name": "Pass", "data": true },
|
||||
"isDropped": false,
|
||||
"isAI": false,
|
||||
"bid": 0,
|
||||
"passed": true,
|
||||
"skipAuction": false,
|
||||
"citiesPowered": 0,
|
||||
"resourcesUsed": [],
|
||||
"totalIncome": 0,
|
||||
"totalSpentCities": 0,
|
||||
"totalSpentConnections": 0,
|
||||
"totalSpentPlants": 0,
|
||||
"totalSpentResources": 0,
|
||||
"usedFreeJump": false,
|
||||
"totalTimeUsed": 0
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"powerPlants": [],
|
||||
"coalCapacity": 0,
|
||||
"coalLeft": 0,
|
||||
"oilCapacity": 0,
|
||||
"oilLeft": 0,
|
||||
"garbageCapacity": 0,
|
||||
"garbageLeft": 0,
|
||||
"uraniumCapacity": 0,
|
||||
"uraniumLeft": 0,
|
||||
"hybridCapacity": 0,
|
||||
"hybridLeft": 0,
|
||||
"money": 50,
|
||||
"housesLeft": 22,
|
||||
"cities": [],
|
||||
"powerPlantsNotUsed": [],
|
||||
"availableMoves": null,
|
||||
"lastMove": { "name": "Pass", "data": true },
|
||||
"isDropped": false,
|
||||
"isAI": false,
|
||||
"bid": 0,
|
||||
"passed": true,
|
||||
"skipAuction": false,
|
||||
"citiesPowered": 0,
|
||||
"resourcesUsed": [],
|
||||
"totalIncome": 0,
|
||||
"totalSpentCities": 0,
|
||||
"totalSpentConnections": 0,
|
||||
"totalSpentPlants": 0,
|
||||
"totalSpentResources": 0,
|
||||
"usedFreeJump": false,
|
||||
"totalTimeUsed": 0
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"powerPlants": [],
|
||||
"coalCapacity": 0,
|
||||
"coalLeft": 0,
|
||||
"oilCapacity": 0,
|
||||
"oilLeft": 0,
|
||||
"garbageCapacity": 0,
|
||||
"garbageLeft": 0,
|
||||
"uraniumCapacity": 0,
|
||||
"uraniumLeft": 0,
|
||||
"hybridCapacity": 0,
|
||||
"hybridLeft": 0,
|
||||
"money": 50,
|
||||
"housesLeft": 22,
|
||||
"cities": [],
|
||||
"powerPlantsNotUsed": [],
|
||||
"availableMoves": null,
|
||||
"lastMove": { "name": "Pass", "data": true },
|
||||
"isDropped": false,
|
||||
"isAI": false,
|
||||
"bid": 0,
|
||||
"passed": true,
|
||||
"skipAuction": false,
|
||||
"citiesPowered": 0,
|
||||
"resourcesUsed": [],
|
||||
"totalIncome": 0,
|
||||
"totalSpentCities": 0,
|
||||
"totalSpentConnections": 0,
|
||||
"totalSpentPlants": 0,
|
||||
"totalSpentResources": 0,
|
||||
"usedFreeJump": false,
|
||||
"totalTimeUsed": 0
|
||||
}
|
||||
],
|
||||
"playerOrder": [0, 1, 2, 3, 4, 5],
|
||||
"currentPlayers": [1],
|
||||
"powerPlantsDeck": [
|
||||
{ "number": 12, "type": 4, "cost": 2, "citiesPowered": 2 },
|
||||
{ "number": 26, "type": 1, "cost": 2, "citiesPowered": 5 },
|
||||
{ "number": 42, "type": 0, "cost": 2, "citiesPowered": 6 },
|
||||
{ "number": 37, "type": 5, "cost": 0, "citiesPowered": 4 },
|
||||
{ "number": 34, "type": 3, "cost": 1, "citiesPowered": 5 },
|
||||
{ "number": 46, "type": 4, "cost": 3, "citiesPowered": 7 },
|
||||
{ "number": 14, "type": 2, "cost": 2, "citiesPowered": 2 },
|
||||
{ "number": 27, "type": 5, "cost": 0, "citiesPowered": 3 },
|
||||
{ "number": 25, "type": 0, "cost": 2, "citiesPowered": 5 },
|
||||
{ "number": 29, "type": 4, "cost": 1, "citiesPowered": 4 },
|
||||
{ "number": 33, "type": 5, "cost": 0, "citiesPowered": 4 },
|
||||
{ "number": 19, "type": 2, "cost": 2, "citiesPowered": 3 },
|
||||
{ "number": 15, "type": 0, "cost": 2, "citiesPowered": 3 },
|
||||
{ "number": 24, "type": 2, "cost": 2, "citiesPowered": 4 },
|
||||
{ "number": 30, "type": 2, "cost": 3, "citiesPowered": 6 },
|
||||
{ "number": 16, "type": 1, "cost": 2, "citiesPowered": 3 },
|
||||
{ "number": 31, "type": 0, "cost": 3, "citiesPowered": 6 },
|
||||
{ "number": 23, "type": 3, "cost": 1, "citiesPowered": 3 },
|
||||
{ "number": 35, "type": 1, "cost": 1, "citiesPowered": 5 },
|
||||
{ "number": 17, "type": 3, "cost": 1, "citiesPowered": 2 },
|
||||
{ "number": 39, "type": 3, "cost": 1, "citiesPowered": 6 },
|
||||
{ "number": 50, "type": 6, "cost": 0, "citiesPowered": 6 },
|
||||
{ "number": 20, "type": 0, "cost": 3, "citiesPowered": 5 },
|
||||
{ "number": 44, "type": 5, "cost": 0, "citiesPowered": 5 },
|
||||
{ "number": 40, "type": 1, "cost": 2, "citiesPowered": 6 },
|
||||
{ "number": 36, "type": 0, "cost": 3, "citiesPowered": 7 },
|
||||
{ "number": 18, "type": 5, "cost": 0, "citiesPowered": 2 },
|
||||
{ "number": 3, "type": 1, "cost": 2, "citiesPowered": 1 },
|
||||
{ "number": 22, "type": 5, "cost": 0, "citiesPowered": 2 },
|
||||
{ "number": 38, "type": 2, "cost": 3, "citiesPowered": 7 },
|
||||
{ "number": 21, "type": 4, "cost": 2, "citiesPowered": 4 },
|
||||
{ "number": 32, "type": 1, "cost": 3, "citiesPowered": 6 },
|
||||
{ "number": 28, "type": 3, "cost": 1, "citiesPowered": 4 },
|
||||
{ "number": 7, "type": 1, "cost": 3, "citiesPowered": 2 },
|
||||
{ "number": 99, "type": 7, "cost": 0, "citiesPowered": 6 }
|
||||
],
|
||||
"coalSupply": 0,
|
||||
"oilSupply": 6,
|
||||
"garbageSupply": 15,
|
||||
"uraniumSupply": 10,
|
||||
"coalResupply": [
|
||||
[3, 4, 3],
|
||||
[4, 5, 3],
|
||||
[5, 6, 4],
|
||||
[5, 7, 5],
|
||||
[7, 9, 6]
|
||||
],
|
||||
"oilResupply": [
|
||||
[2, 2, 4],
|
||||
[2, 3, 4],
|
||||
[3, 4, 5],
|
||||
[4, 5, 6],
|
||||
[5, 6, 7]
|
||||
],
|
||||
"garbageResupply": [
|
||||
[1, 2, 3],
|
||||
[1, 2, 3],
|
||||
[2, 3, 4],
|
||||
[3, 3, 5],
|
||||
[3, 5, 6]
|
||||
],
|
||||
"uraniumResupply": [
|
||||
[1, 1, 1],
|
||||
[1, 1, 1],
|
||||
[1, 2, 2],
|
||||
[2, 3, 2],
|
||||
[2, 3, 3]
|
||||
],
|
||||
"coalMarket": 24,
|
||||
"oilMarket": 18,
|
||||
"garbageMarket": 9,
|
||||
"uraniumMarket": 2,
|
||||
"coalPrices": [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8],
|
||||
"oilPrices": [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8],
|
||||
"garbagePrices": [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8],
|
||||
"uraniumPrices": [1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16],
|
||||
"actualMarket": [
|
||||
{ "number": 4, "type": 0, "cost": 2, "citiesPowered": 1 },
|
||||
{ "number": 5, "type": 4, "cost": 2, "citiesPowered": 1 },
|
||||
{ "number": 6, "type": 2, "cost": 1, "citiesPowered": 1 },
|
||||
{ "number": 8, "type": 0, "cost": 3, "citiesPowered": 2 }
|
||||
],
|
||||
"futureMarket": [
|
||||
{ "number": 9, "type": 1, "cost": 1, "citiesPowered": 1 },
|
||||
{ "number": 10, "type": 0, "cost": 2, "citiesPowered": 2 },
|
||||
{ "number": 11, "type": 3, "cost": 1, "citiesPowered": 2 },
|
||||
{ "number": 13, "type": 5, "cost": 0, "citiesPowered": 1 }
|
||||
],
|
||||
"chosenPowerPlant": { "number": 6, "type": 2, "cost": 1, "citiesPowered": 1 },
|
||||
"currentBid": 11,
|
||||
"highestBidders": [],
|
||||
"auctioningPlayer": 0,
|
||||
"step": 1,
|
||||
"phase": "Auction",
|
||||
"options": {
|
||||
"fastBid": false,
|
||||
"map": "Germany",
|
||||
"variant": "recharged",
|
||||
"showMoney": true,
|
||||
"useNewRechargedSetup": true,
|
||||
"trackTotalSpent": true,
|
||||
"chooseRegions": false,
|
||||
"chooseColors": false
|
||||
},
|
||||
"log": [
|
||||
{ "type": "event", "event": "Game Start!" },
|
||||
{
|
||||
"type": "move",
|
||||
"player": 0,
|
||||
"move": { "name": "ChoosePowerPlant", "data": 6 },
|
||||
"simple": "undefined chooses Power Plant 6 to initiate an auction.",
|
||||
"pretty": "<span style=\"background-color: limegreen; font-weight: bold; padding: 0 3px;\">undefined</span> chooses Power Plant <b>6</b> to initiate an auction."
|
||||
},
|
||||
{
|
||||
"type": "move",
|
||||
"player": 0,
|
||||
"move": { "name": "Bid", "data": 7 },
|
||||
"simple": "undefined bids $7.",
|
||||
"pretty": "<span style=\"background-color: limegreen; font-weight: bold; padding: 0 3px;\">undefined</span> bids <span style=\"color: green\">$7</span>."
|
||||
},
|
||||
{
|
||||
"type": "move",
|
||||
"player": 1,
|
||||
"move": { "name": "Bid", "data": 8 },
|
||||
"simple": "undefined bids $8.",
|
||||
"pretty": "<span style=\"background-color: mediumorchid; font-weight: bold; padding: 0 3px;\">undefined</span> bids <span style=\"color: green\">$8</span>."
|
||||
},
|
||||
{
|
||||
"type": "move",
|
||||
"player": 2,
|
||||
"move": { "name": "Bid", "data": 11 },
|
||||
"simple": "undefined bids $11.",
|
||||
"pretty": "<span style=\"background-color: red; font-weight: bold; padding: 0 3px;\">undefined</span> bids <span style=\"color: green\">$11</span>."
|
||||
},
|
||||
{
|
||||
"type": "move",
|
||||
"player": 3,
|
||||
"move": { "name": "Pass", "data": true },
|
||||
"simple": "undefined passes.",
|
||||
"pretty": "<span style=\"background-color: dodgerblue; font-weight: bold; padding: 0 3px;\">undefined</span> passes."
|
||||
},
|
||||
{
|
||||
"type": "move",
|
||||
"player": 4,
|
||||
"move": { "name": "Pass", "data": true },
|
||||
"simple": "undefined passes.",
|
||||
"pretty": "<span style=\"background-color: yellow; font-weight: bold; padding: 0 3px;\">undefined</span> passes."
|
||||
},
|
||||
{
|
||||
"type": "move",
|
||||
"player": 5,
|
||||
"move": { "name": "Pass", "data": true },
|
||||
"simple": "undefined passes.",
|
||||
"pretty": "<span style=\"background-color: brown; font-weight: bold; padding: 0 3px;\">undefined</span> passes."
|
||||
},
|
||||
{
|
||||
"type": "move",
|
||||
"player": 0,
|
||||
"move": { "name": "Pass", "data": true },
|
||||
"simple": "undefined passes.",
|
||||
"pretty": "<span style=\"background-color: limegreen; font-weight: bold; padding: 0 3px;\">undefined</span> passes."
|
||||
}
|
||||
],
|
||||
"hiddenLog": [],
|
||||
"seed": "multiplayer-search-strong-probe-v1-6p-5",
|
||||
"round": 1,
|
||||
"newTurn": true,
|
||||
"auctionSkips": 0,
|
||||
"citiesToStep2": 6,
|
||||
"citiesToEndGame": 14,
|
||||
"resourceResupply": ["[7, 5, 3, 2]", "[9, 6, 5, 3]", "[6, 7, 6, 3]"],
|
||||
"paymentTable": [
|
||||
10, 22, 33, 44, 54, 64, 73, 82, 90, 98, 105, 112, 118, 124, 129, 134, 138, 142, 145, 148, 150, 150
|
||||
],
|
||||
"variant": "recharged",
|
||||
"minimunBid": 6,
|
||||
"plantDiscountActive": true,
|
||||
"discardSmallestPlant": false,
|
||||
"cardsLeft": 35,
|
||||
"nextCardWeak": true,
|
||||
"card39Bought": false,
|
||||
"knownPowerPlantDeck": [
|
||||
{ "number": 4, "type": 0, "cost": 2, "citiesPowered": 1 },
|
||||
{ "number": 5, "type": 4, "cost": 2, "citiesPowered": 1 },
|
||||
{ "number": 6, "type": 2, "cost": 1, "citiesPowered": 1 },
|
||||
{ "number": 8, "type": 0, "cost": 3, "citiesPowered": 2 },
|
||||
{ "number": 9, "type": 1, "cost": 1, "citiesPowered": 1 },
|
||||
{ "number": 10, "type": 0, "cost": 2, "citiesPowered": 2 },
|
||||
{ "number": 11, "type": 3, "cost": 1, "citiesPowered": 2 },
|
||||
{ "number": 13, "type": 5, "cost": 0, "citiesPowered": 1 }
|
||||
],
|
||||
"knownPowerPlantDeckStep3": []
|
||||
},
|
||||
"provenance": "HF search-horizon-diagnostic-v1; exact replay of six-player arena deal 5, Recharged/open, seat 1, decision arena-guided-127-8."
|
||||
}
|
||||
84
ai/strong/generate-search-data.py
Normal file
84
ai/strong/generate-search-data.py
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
"""HF CPU job: independent games produce a versioned, private teacher shard."""
|
||||
|
||||
import concurrent.futures
|
||||
import gzip
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
shard = int(os.environ["SHARD"])
|
||||
games = int(os.getenv("GAMES", "128"))
|
||||
version = os.getenv("DATA_VERSION", "search-teacher-v1")
|
||||
output = Path(f"{version}-{shard}.jsonl.gz")
|
||||
counts = {
|
||||
"games": 0,
|
||||
"positions": 0,
|
||||
"teacher_disagreements": 0,
|
||||
"truncated": 0,
|
||||
"search_rollouts": 0,
|
||||
"search_rollouts_truncated": 0,
|
||||
"opponent_search_rollouts": 0,
|
||||
"opponent_search_rollouts_truncated": 0,
|
||||
}
|
||||
|
||||
|
||||
def generate(game):
|
||||
result = subprocess.run(
|
||||
["node", "ai/strong/search-teacher.cjs", str(game)],
|
||||
text=True,
|
||||
capture_output=True,
|
||||
check=True,
|
||||
)
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(
|
||||
int(os.getenv("DATA_WORKERS", "24"))
|
||||
) as pool:
|
||||
futures = [pool.submit(generate, shard * games + i) for i in range(games)]
|
||||
with gzip.open(output, "wt") as stream:
|
||||
for future in concurrent.futures.as_completed(futures):
|
||||
game = future.result()
|
||||
counts["games"] += 1
|
||||
counts["truncated"] += game["truncated"]
|
||||
counts["search_rollouts"] += game["searchStats"]["evaluations"]
|
||||
counts["search_rollouts_truncated"] += game["searchStats"]["truncated"]
|
||||
counts["opponent_search_rollouts"] += game.get(
|
||||
"opponentSearchStats", {}
|
||||
).get("evaluations", 0)
|
||||
counts["opponent_search_rollouts_truncated"] += game.get(
|
||||
"opponentSearchStats", {}
|
||||
).get("truncated", 0)
|
||||
# Keep truncated metadata, but never turn incomplete outcomes into targets.
|
||||
if game["truncated"]:
|
||||
game["rows"] = []
|
||||
counts["positions"] += len(game["rows"])
|
||||
counts["teacher_disagreements"] += sum(
|
||||
not r["teacherAgrees"] for r in game["rows"]
|
||||
)
|
||||
stream.write(json.dumps(game, separators=(",", ":")) + "\n")
|
||||
print(json.dumps({"shard": shard, **counts}), flush=True)
|
||||
api = HfApi()
|
||||
repo = os.environ["HF_DATA_REPO"]
|
||||
api.upload_file(
|
||||
repo_id=repo,
|
||||
repo_type="dataset",
|
||||
path_or_fileobj=str(output),
|
||||
path_in_repo=version + "/" + output.name,
|
||||
)
|
||||
api.upload_file(
|
||||
repo_id=repo,
|
||||
repo_type="dataset",
|
||||
path_or_fileobj=json.dumps(
|
||||
{
|
||||
"shard": shard,
|
||||
"schema": 4 if os.getenv("FEATURE_REVISION") == "4.0-multiplayer" else 3,
|
||||
"feature_revision": os.getenv("FEATURE_REVISION", "3.1-uranium39"),
|
||||
"player_count": int(os.getenv("PLAYER_COUNT", "3")),
|
||||
**counts,
|
||||
}
|
||||
).encode(),
|
||||
path_in_repo=f"{version}/shard-{shard}-metrics.json",
|
||||
)
|
||||
42
ai/strong/geographic-proposals.cjs
Normal file
42
ai/strong/geographic-proposals.cjs
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
// Proposal diversity only: the rules engine and rollout outcomes choose the move.
|
||||
const graph = require('./public-graph.cjs');
|
||||
const cache = new WeakMap();
|
||||
function distances(map, topology) {
|
||||
if (cache.has(map)) return cache.get(map);
|
||||
const n = topology.nodes.length,
|
||||
matrix = Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => (i === j ? 0 : Infinity)));
|
||||
for (const edge of topology.edges) {
|
||||
matrix[edge.a][edge.b] = Math.min(matrix[edge.a][edge.b], edge.cost);
|
||||
matrix[edge.b][edge.a] = Math.min(matrix[edge.b][edge.a], edge.cost);
|
||||
}
|
||||
for (let k = 0; k < n; k++)
|
||||
for (let i = 0; i < n; i++)
|
||||
for (let j = 0; j < n; j++) matrix[i][j] = Math.min(matrix[i][j], matrix[i][k] + matrix[k][j]);
|
||||
cache.set(map, matrix);
|
||||
return matrix;
|
||||
}
|
||||
function rank(g, seat, actions) {
|
||||
const topology = graph.encode(g, seat),
|
||||
matrix = distances(g.map, topology),
|
||||
index = new Map(topology.nodes.map((n, i) => [n.name, i])),
|
||||
open = topology.nodes
|
||||
.map((node, i) => ({ node, i }))
|
||||
.filter(({ node }) => node.openSlots > 0 && !node.owners[0]);
|
||||
return actions
|
||||
.flatMap((action, i) => {
|
||||
if (action.name !== 'Build') return [];
|
||||
const at = index.get(action.data.name),
|
||||
node = topology.nodes[at],
|
||||
growth = open
|
||||
.filter(({ i }) => i !== at)
|
||||
.map(({ i }) => matrix[at][i])
|
||||
.filter(Number.isFinite)
|
||||
.sort((a, b) => a - b)
|
||||
.slice(0, 3);
|
||||
const score =
|
||||
action.data.price + (growth.length ? growth.reduce((a, b) => a + b, 0) / growth.length : 1000);
|
||||
return [{ index: i, region: node.region, island: node.island, score }];
|
||||
})
|
||||
.sort((a, b) => a.score - b.score || a.index - b.index);
|
||||
}
|
||||
module.exports = { rank };
|
||||
86
ai/strong/infer.py
Normal file
86
ai/strong/infer.py
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
"""Persistent CPU ONNX worker for versioned public-information states."""
|
||||
|
||||
import sys, json, argparse, time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from infer import Model, Node
|
||||
from feature_contract import check_revision, model_revision
|
||||
from search_scope import SCOPES, search_enabled
|
||||
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("model")
|
||||
p.add_argument("--search-scope", choices=SCOPES, default="all")
|
||||
p.add_argument("--search-samples", type=int, default=0)
|
||||
p.add_argument("--geographic-search", action="store_true")
|
||||
args = p.parse_args()
|
||||
if not 0 <= args.search_samples <= 64:
|
||||
p.error("--search-samples must be 0..64")
|
||||
if args.geographic_search and not args.search_samples:
|
||||
p.error("--geographic-search requires positive --search-samples")
|
||||
model = Model(args.model)
|
||||
node = Node("strong/worker.cjs")
|
||||
try:
|
||||
for line in sys.stdin:
|
||||
q = {}
|
||||
try:
|
||||
obj = json.loads(line)
|
||||
if not isinstance(obj, dict):
|
||||
raise ValueError("Expected object")
|
||||
q = obj
|
||||
start = time.perf_counter()
|
||||
r = node.call({**q, "op": "rank", "featureRevision": model_revision(model)})
|
||||
if "error" in r:
|
||||
raise ValueError(r["error"])
|
||||
check_revision(model, r.get("featureRevision", "3.0"))
|
||||
index, values = model.predict(r["state"], r["actions"])
|
||||
search = None
|
||||
if args.search_samples and search_enabled(
|
||||
args.search_scope,
|
||||
q["state"]["options"].get("variant"),
|
||||
q["state"]["options"].get("fastBid"),
|
||||
):
|
||||
search = node.call(
|
||||
{
|
||||
**q,
|
||||
"op": "search",
|
||||
"proposal": index,
|
||||
"samples": args.search_samples,
|
||||
"featureRevision": model_revision(model),
|
||||
"geography": args.geographic_search,
|
||||
}
|
||||
)
|
||||
if "error" in search:
|
||||
raise ValueError(search["error"])
|
||||
index = search["index"]
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"requestId": q.get("requestId"),
|
||||
"revision": q.get("revision"),
|
||||
"move": r["moves"][index],
|
||||
"winProbabilities": values[: len(r["playerOrder"])],
|
||||
"valueStatus": "uncalibrated-training-opponents",
|
||||
"playerOrder": r["playerOrder"],
|
||||
"schema": r["schema"],
|
||||
"featureRevision": r["featureRevision"],
|
||||
"search": {
|
||||
k: v
|
||||
for k, v in search.items()
|
||||
if k in ["evaluations", "truncated", "winEstimate"]
|
||||
}
|
||||
if search
|
||||
else None,
|
||||
"modelSha256": model.sha256,
|
||||
"elapsedMs": 1000 * (time.perf_counter() - start),
|
||||
}
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
except Exception as e:
|
||||
print(
|
||||
json.dumps({"requestId": q.get("requestId"), "error": str(e)}),
|
||||
flush=True,
|
||||
)
|
||||
finally:
|
||||
node.close()
|
||||
19
ai/strong/launch-a.sh
Normal file
19
ai/strong/launch-a.sh
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
hf jobs run --detach --flavor a10g-large --timeout 3h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--env RUN_NAME=strong-league-v2-a --env TRAIN_SEED=201 --env LR=.0001 --env ENTROPY=.01 --env ANCHOR=.01 --env UPDATES=300 --env EVAL_EVERY=20 \
|
||||
--env ENVS=128 --env WORKERS=8 --env BATCH_SIZE=512 --env ROLLOUT_SAMPLES=8000 \
|
||||
--label project=powergrid-ai --label stage=strong-league-v2-a \
|
||||
-- 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\",\"strong-source-v3.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python -u ai/strong/train.py
|
||||
'
|
||||
24
ai/strong/launch-arena.sh
Normal file
24
ai/strong/launch-arena.sh
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
# name model-path revision opponent samples geography games seed
|
||||
extra_env=()
|
||||
if [[ -n "${OPPONENT_MODEL_PATH:-}" ]]; then
|
||||
extra_env+=(--env "OPPONENT_MODEL_PATH=$OPPONENT_MODEL_PATH" --env "OPPONENT_MODEL_REVISION=${OPPONENT_MODEL_REVISION:?pin opponent revision}")
|
||||
fi
|
||||
hf jobs run --detach --flavor cpu-performance --timeout 3h \
|
||||
--secrets HF_TOKEN "${extra_env[@]}" \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 --env SEARCH_SCOPE="${SEARCH_SCOPE:-all}" \
|
||||
--env RUN_NAME="${1:?name}" --env MODEL_PATH="${2:?model path}" --env MODEL_REVISION="${3:?revision}" \
|
||||
--env OPPONENT="${4:?opponent}" --env SEARCH_SAMPLES="${5:?samples}" --env GEOGRAPHY="${6:?geography}" \
|
||||
--env GAMES="${7:?games}" --env EVAL_SEED="${8:?seed}" --env WORKERS=24 \
|
||||
--label project=powergrid-ai --label stage="$1" \
|
||||
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
|
||||
set -euo pipefail
|
||||
python -m pip install --quiet --timeout 120 --retries 5 huggingface_hub==2.0.0 onnxruntime==1.30.0 numpy==2.4.6
|
||||
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\",\"strong-source-v15.tgz\",repo_type=\"dataset\", revision=\"5346157377b6ba0c716b6bf3c7b434cc3696fb1d\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
python -u ai/strong/arena-job.py
|
||||
'
|
||||
19
ai/strong/launch-b.sh
Normal file
19
ai/strong/launch-b.sh
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
hf jobs run --detach --flavor l4x1 --timeout 3h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--env RUN_NAME=strong-league-v2-b --env TRAIN_SEED=202 --env LR=.0003 --env ENTROPY=.01 --env ANCHOR=.01 --env UPDATES=300 --env EVAL_EVERY=20 \
|
||||
--env ENVS=128 --env WORKERS=4 --env BATCH_SIZE=512 --env ROLLOUT_SAMPLES=8000 \
|
||||
--label project=powergrid-ai --label stage=strong-league-v2-b \
|
||||
-- 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\",\"strong-source-v3.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python -u ai/strong/train.py
|
||||
'
|
||||
19
ai/strong/launch-c.sh
Normal file
19
ai/strong/launch-c.sh
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
hf jobs run --detach --flavor h200 --timeout 3h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--env RUN_NAME=strong-league-v2-c --env TRAIN_SEED=203 --env LR=.0001 --env ENTROPY=.025 --env ANCHOR=.003 --env UPDATES=300 --env EVAL_EVERY=20 \
|
||||
--env ENVS=128 --env WORKERS=12 --env BATCH_SIZE=512 --env ROLLOUT_SAMPLES=8000 \
|
||||
--label project=powergrid-ai --label stage=strong-league-v2-c \
|
||||
-- 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\",\"strong-source-v3.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python -u ai/strong/train.py
|
||||
'
|
||||
19
ai/strong/launch-d.sh
Normal file
19
ai/strong/launch-d.sh
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
hf jobs run --detach --flavor a10g-large --timeout 3h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--env RUN_NAME=strong-league-v2-d --env TRAIN_SEED=204 --env LR=.0003 --env ENTROPY=.025 --env ANCHOR=.003 --env UPDATES=300 --env EVAL_EVERY=20 \
|
||||
--env ENVS=128 --env WORKERS=8 --env BATCH_SIZE=512 --env ROLLOUT_SAMPLES=8000 \
|
||||
--label project=powergrid-ai --label stage=strong-league-v2-d \
|
||||
-- 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\",\"strong-source-v3.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python -u ai/strong/train.py
|
||||
'
|
||||
21
ai/strong/launch-distill-v2.sh
Normal file
21
ai/strong/launch-distill-v2.sh
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
mode=${1:-hard}
|
||||
[[ "$mode" == hard || "$mode" == soft ]]
|
||||
hf jobs run --detach --flavor a10g-large --timeout 2h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_DATA_REPO=coyotte508/powergrid-ai-training-v1 \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--env RUN_NAME="search-distillation-v2-$mode" --env TARGET_MODE="$mode" --env TRAIN_SEED=310 --env EPOCHS=20 --env DATA_VERSION=search-teacher-v2 --env SHARDS=8 --env DISAGREEMENT_WEIGHT=2 \
|
||||
--label project=powergrid-ai --label stage="search-distillation-v2-$mode" \
|
||||
-- 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\",\"strong-source-v7.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python -u ai/strong/distill.py
|
||||
'
|
||||
21
ai/strong/launch-distill-v3.sh
Normal file
21
ai/strong/launch-distill-v3.sh
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
mode=${1:-hard}
|
||||
[[ "$mode" == hard || "$mode" == soft ]]
|
||||
hf jobs run --detach --flavor a10g-large --timeout 2h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_DATA_REPO=coyotte508/powergrid-ai-training-v1 \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--env RUN_NAME="search-distillation-v3-$mode" --env TARGET_MODE="$mode" --env TRAIN_SEED=310 --env EPOCHS=20 --env DATA_VERSION=search-teacher-v3 --env SHARDS=8 --env DISAGREEMENT_WEIGHT=2 \
|
||||
--label project=powergrid-ai --label stage="search-distillation-v3-$mode" \
|
||||
-- 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\",\"strong-source-v8.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python -u ai/strong/distill.py
|
||||
'
|
||||
19
ai/strong/launch-distill.sh
Normal file
19
ai/strong/launch-distill.sh
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
hf jobs run --detach --flavor a10g-large --timeout 2h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_DATA_REPO=coyotte508/powergrid-ai-training-v1 \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--env RUN_NAME=search-distillation-v1 --env TRAIN_SEED=310 --env EPOCHS=30 \
|
||||
--label project=powergrid-ai --label stage=search-distillation-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\",\"strong-source-v5.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python -u ai/strong/distill.py
|
||||
'
|
||||
149
ai/strong/launch-final.py
Normal file
149
ai/strong/launch-final.py
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
"""Launch or resume one frozen final evaluation plan; default is a dry run."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("candidate")
|
||||
p.add_argument("--protocol", default="ai/strong/final-protocol.json")
|
||||
p.add_argument("--launch", action="store_true")
|
||||
a = p.parse_args()
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
protocol = json.loads(Path(a.protocol).read_text())
|
||||
candidate = json.loads(Path(a.candidate).read_text())
|
||||
plan = []
|
||||
prefix = protocol["seed_prefix"]
|
||||
multiplayer = isinstance(protocol.get("scope"), dict)
|
||||
launcher = (
|
||||
"ai/strong/launch-multiplayer-arena.sh"
|
||||
if multiplayer
|
||||
else "ai/strong/launch-arena.sh"
|
||||
)
|
||||
for opponent in protocol["opponents"]:
|
||||
counts = opponent["counts"] if multiplayer else {"3": {"games": opponent["games"]}}
|
||||
for count, spec in counts.items():
|
||||
n = int(count)
|
||||
shard_games = 4 * n * 4
|
||||
assert spec["games"] % shard_games == 0
|
||||
for shard in range(spec["games"] // shard_games):
|
||||
plan.append(
|
||||
{
|
||||
"name": f"{prefix}-{opponent['name']}-{n}p-{shard:02}"
|
||||
if multiplayer
|
||||
else f"{prefix}-{opponent['name']}-{shard:02}",
|
||||
"seed": f"{prefix}-{n}p" if multiplayer else f"{prefix}-{shard}",
|
||||
"player_count": n,
|
||||
"deal_offset": shard * 4 if multiplayer else 0,
|
||||
"opponent": opponent,
|
||||
"games": shard_games,
|
||||
}
|
||||
)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"candidate": candidate,
|
||||
"jobs": len(plan),
|
||||
"games": sum(x["games"] for x in plan),
|
||||
"launch": a.launch,
|
||||
}
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
if not a.launch:
|
||||
raise SystemExit(0)
|
||||
if candidate.get("status") != "selected":
|
||||
raise ValueError("Select and freeze the candidate before spending final seeds")
|
||||
if multiplayer and candidate.get("feature_revision") != "4.0-multiplayer":
|
||||
raise ValueError("Multiplayer final requires a schema-4 candidate")
|
||||
from huggingface_hub import hf_hub_download
|
||||
|
||||
model = Path(
|
||||
hf_hub_download(
|
||||
"coyotte508/powergrid-ai-germany-v1",
|
||||
candidate["model_path"],
|
||||
revision=candidate["model_revision"],
|
||||
)
|
||||
)
|
||||
assert hashlib.sha256(model.read_bytes()).hexdigest() == candidate["model_sha256"]
|
||||
manifest_path = root / "ai/strong/experiments.json"
|
||||
manifest = json.loads(manifest_path.read_text())
|
||||
launcher_sha256 = hashlib.sha256((root / launcher).read_bytes()).hexdigest()
|
||||
fingerprint = hashlib.sha256(
|
||||
json.dumps(
|
||||
{
|
||||
"candidate": candidate,
|
||||
"protocol": protocol,
|
||||
"launcher_sha256": launcher_sha256,
|
||||
},
|
||||
sort_keys=True,
|
||||
).encode()
|
||||
).hexdigest()
|
||||
run = manifest.setdefault("final_runs", {}).setdefault(
|
||||
prefix,
|
||||
{
|
||||
"fingerprint": fingerprint,
|
||||
"launcher_sha256": launcher_sha256,
|
||||
"candidate": candidate,
|
||||
"protocol": protocol,
|
||||
"jobs": {},
|
||||
},
|
||||
)
|
||||
if run["fingerprint"] != fingerprint:
|
||||
raise ValueError(
|
||||
"Final seeds were already assigned to a different candidate or protocol"
|
||||
)
|
||||
manifest["final_seed_prefix_used"] = True
|
||||
manifest_path.write_text(json.dumps(manifest, indent=4) + "\n")
|
||||
for item in plan:
|
||||
if item["name"] in run["jobs"]:
|
||||
print("Already dispatched", item["name"], run["jobs"][item["name"]], flush=True)
|
||||
continue
|
||||
opponent = item["opponent"]
|
||||
env = os.environ.copy()
|
||||
env.pop("OPPONENT_MODEL_PATH", None)
|
||||
env.pop("OPPONENT_MODEL_REVISION", None)
|
||||
env["SEARCH_SCOPE"] = candidate.get("search_scope", "all")
|
||||
env["DISABLE_SEARCH_PROPOSAL"] = "0"
|
||||
if multiplayer:
|
||||
env["ASYNC_ARENA"] = "1"
|
||||
env["PLAYER_COUNT"] = str(item["player_count"])
|
||||
env["DEAL_OFFSET"] = str(item["deal_offset"])
|
||||
if "model_path" in opponent:
|
||||
env.update(
|
||||
OPPONENT_MODEL_PATH=opponent["model_path"],
|
||||
OPPONENT_MODEL_REVISION=opponent["model_revision"],
|
||||
)
|
||||
result = subprocess.run(
|
||||
[
|
||||
"bash",
|
||||
launcher,
|
||||
item["name"],
|
||||
candidate["model_path"],
|
||||
candidate["model_revision"],
|
||||
"economic" if "model_path" in opponent else opponent["name"],
|
||||
str(candidate["search_samples"]),
|
||||
str(int(candidate["geographic_search"])),
|
||||
str(item["games"]),
|
||||
item["seed"],
|
||||
],
|
||||
cwd=root,
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
ids = re.findall(r"\b[0-9a-f]{24}\b", result.stdout)
|
||||
if not ids:
|
||||
raise RuntimeError(
|
||||
"Launch response was ambiguous; inspect HF job labels before retrying: "
|
||||
+ result.stdout
|
||||
)
|
||||
run["jobs"][item["name"]] = ids[-1]
|
||||
manifest["jobs"][item["name"]] = ids[-1]
|
||||
manifest_path.write_text(json.dumps(manifest, indent=4) + "\n")
|
||||
print(item["name"], ids[-1], flush=True)
|
||||
18
ai/strong/launch-guided-b160-16.sh
Normal file
18
ai/strong/launch-guided-b160-16.sh
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
hf jobs run --detach --flavor cpu-performance --timeout 2h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--label project=powergrid-ai --label stage=b160-guided-16-screening \
|
||||
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
|
||||
set -euo pipefail
|
||||
python -m pip install --quiet huggingface_hub 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\",\"strong-source-v6.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
python -c "from huggingface_hub import hf_hub_download; hf_hub_download(\"coyotte508/powergrid-ai-germany-v1\",\"runs/strong-league-v2-b/best.onnx\",revision=\"55e2354f08c8088edd1f6634e1bb7d903dbfaf94\",local_dir=\"models\")"
|
||||
python ai/strong/evaluate.py models/runs/strong-league-v2-b/best.onnx --opponent search --search-samples 16 --games 96 --workers 24 --seed strong-search-screening-v1 --output evaluation.json
|
||||
python -c "import os;from huggingface_hub import HfApi;HfApi().upload_file(repo_id=os.environ[\"HF_MODEL_REPO\"],path_or_fileobj=\"evaluation.json\",path_in_repo=\"runs/b160-guided-16-screening/evaluation.json\")"
|
||||
'
|
||||
18
ai/strong/launch-guided-b160-48.sh
Normal file
18
ai/strong/launch-guided-b160-48.sh
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
hf jobs run --detach --flavor cpu-performance --timeout 2h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--label project=powergrid-ai --label stage=b160-guided-48-screening \
|
||||
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
|
||||
set -euo pipefail
|
||||
python -m pip install --quiet huggingface_hub 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\",\"strong-source-v6.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
python -c "from huggingface_hub import hf_hub_download; hf_hub_download(\"coyotte508/powergrid-ai-germany-v1\",\"runs/strong-league-v2-b/best.onnx\",revision=\"55e2354f08c8088edd1f6634e1bb7d903dbfaf94\",local_dir=\"models\")"
|
||||
python ai/strong/evaluate.py models/runs/strong-league-v2-b/best.onnx --opponent search --search-samples 48 --games 96 --workers 24 --seed strong-search-screening-v1 --output evaluation.json
|
||||
python -c "import os;from huggingface_hub import HfApi;HfApi().upload_file(repo_id=os.environ[\"HF_MODEL_REPO\"],path_or_fileobj=\"evaluation.json\",path_in_repo=\"runs/b160-guided-48-screening/evaluation.json\")"
|
||||
'
|
||||
18
ai/strong/launch-guided-evaluation.sh
Normal file
18
ai/strong/launch-guided-evaluation.sh
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
hf jobs run --detach --flavor cpu-performance --timeout 2h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--label project=powergrid-ai --label stage=b20-guided-search-screening \
|
||||
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
|
||||
set -euo pipefail
|
||||
python -m pip install --quiet huggingface_hub 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\",\"strong-source-v6.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
python -c "from huggingface_hub import hf_hub_download; hf_hub_download(\"coyotte508/powergrid-ai-germany-v1\",\"runs/strong-league-v2-b/best.onnx\",revision=\"f9dfad5bde9862bc41aa42d77d9622621d70e8ce\",local_dir=\"models\")"
|
||||
python ai/strong/evaluate.py models/runs/strong-league-v2-b/best.onnx --opponent search --search-samples 16 --games 96 --workers 24 --seed strong-search-screening-v1 --output evaluation.json
|
||||
python -c "import os;from huggingface_hub import HfApi;HfApi().upload_file(repo_id=os.environ[\"HF_MODEL_REPO\"],path_or_fileobj=\"evaluation.json\",path_in_repo=\"runs/b20-guided-search-screening/evaluation.json\")"
|
||||
'
|
||||
39
ai/strong/launch-league-admission-v1.sh
Normal file
39
ai/strong/launch-league-admission-v1.sh
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
#!/usr/bin/env bash
|
||||
# Controlled league-admission comparison; optimization runs only on HF Jobs.
|
||||
set -euo pipefail
|
||||
checkpoint=${1:?Supply selected ordered-model checkpoint path}
|
||||
revision=${2:?Pin its immutable model repository commit}
|
||||
run=${3:?Supply a unique refinement run name}
|
||||
[[ "$revision" =~ ^[0-9a-f]{40}$ ]]
|
||||
[[ "$checkpoint" == runs/*/best.pt ]]
|
||||
[[ "$run" =~ ^[a-zA-Z0-9_-]+$ ]]
|
||||
admission=${SNAPSHOT_ADMISSION:?Choose best or periodic_anchor}
|
||||
[[ "$admission" == best || "$admission" == periodic_anchor ]]
|
||||
hf jobs run --detach --flavor "${HF_FLAVOR:-cpu-performance}" --timeout "${JOB_TIMEOUT:-8h}" \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--env INIT_CHECKPOINT="$checkpoint" --env INIT_REVISION="$revision" --env ANCHOR_POLICY=initial \
|
||||
--env ARCHITECTURE=multiplayer_ordered --env MIX_PLAYER_COUNTS=1 --env OPPONENT_MODE="${OPPONENT_MODE:-mixed_search_geo}" \
|
||||
--env RUN_NAME="$run" --env TRAIN_SEED="${TRAIN_SEED:-9021}" \
|
||||
--env ASYNC_ROLLOUT="${ASYNC_ROLLOUT:-1}" --env TRAIN_DEVICE="${TRAIN_DEVICE:-cpu}" --env TORCH_THREADS="${TORCH_THREADS:-4}" \
|
||||
--env SNAPSHOT_ADMISSION="$admission" --env SNAPSHOT_INTERVAL=5 \
|
||||
--env LR=.00005 --env ENTROPY=.005 --env ANCHOR=.03 \
|
||||
--env UPDATES="${UPDATES:-20}" --env EVAL_EVERY=10 \
|
||||
--env ENVS=240 --env WORKERS="${WORKERS:-240}" --env BATCH_SIZE=512 \
|
||||
--label project=powergrid-ai --label stage="$run" \
|
||||
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
|
||||
set -euo pipefail
|
||||
python -m pip install --quiet --timeout 120 --retries 5 huggingface_hub==2.0.0 onnx==1.20.1 onnxruntime==1.30.0
|
||||
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\",\"strong-source-v34.tgz\",repo_type=\"dataset\",revision=\"2c273f96562d0cc2f8c05a2735d8c0492ab77fd8\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python ai/strong/test_teacher_contract.py
|
||||
python ai/strong/test_model_v4.py
|
||||
python ai/strong/test_snapshot_league.py
|
||||
python ai/strong/test_multiplayer_bridge.py
|
||||
python ai/strong/test_async_pool.py
|
||||
python -u ai/strong/train.py
|
||||
'
|
||||
35
ai/strong/launch-multiplayer-arena.sh
Normal file
35
ai/strong/launch-multiplayer-arena.sh
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
# name model-path revision opponent samples geography games seed
|
||||
case "${4:?opponent}" in
|
||||
economic|heuristic|rush|legacy|search|search_geo) ;;
|
||||
*) echo "Unsupported opponent mode; use OPPONENT_MODEL_PATH for a frozen model" >&2; exit 2 ;;
|
||||
esac
|
||||
if [[ "${6:?geography}" == 1 ]] && ! [[ "${5:?samples}" =~ ^[1-9][0-9]*$ ]]; then
|
||||
echo "Candidate geographic search requires a positive sample budget; opponent search_geo is configured separately" >&2
|
||||
exit 2
|
||||
fi
|
||||
extra_env=()
|
||||
if [[ -n "${OPPONENT_MODEL_PATH:-}" ]]; then
|
||||
extra_env+=(--env "OPPONENT_MODEL_PATH=$OPPONENT_MODEL_PATH" --env "OPPONENT_MODEL_REVISION=${OPPONENT_MODEL_REVISION:?pin opponent revision}")
|
||||
fi
|
||||
hf jobs run --detach --flavor cpu-performance --timeout 3h \
|
||||
--secrets HF_TOKEN "${extra_env[@]}" \
|
||||
--env ASYNC_ARENA="${ASYNC_ARENA:-1}" \
|
||||
--env DISABLE_SEARCH_PROPOSAL="${DISABLE_SEARCH_PROPOSAL:-0}" \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 --env SEARCH_SCOPE="${SEARCH_SCOPE:-all}" \
|
||||
--env RUN_NAME="${1:?name}" --env MODEL_PATH="${2:?model path}" --env MODEL_REVISION="${3:?revision}" \
|
||||
--env OPPONENT="${4:?opponent}" --env SEARCH_SAMPLES="${5:?samples}" --env GEOGRAPHY="${6:?geography}" \
|
||||
--env PLAYER_COUNT="${PLAYER_COUNT:?Specify player count}" --env DEAL_OFFSET="${DEAL_OFFSET:-0}" \
|
||||
--env GAMES="${7:?games}" --env EVAL_SEED="${8:?seed}" --env WORKERS=24 \
|
||||
--label project=powergrid-ai --label stage="$1" \
|
||||
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
|
||||
set -euo pipefail
|
||||
python -m pip install --quiet --timeout 120 --retries 5 huggingface_hub==2.0.0 onnxruntime==1.30.0 numpy==2.4.6
|
||||
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\",\"strong-source-v32.tgz\",repo_type=\"dataset\", revision=\"37465b08df007221665d796448aea57e6828257e\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
python -u ai/strong/arena-job.py
|
||||
'
|
||||
24
ai/strong/launch-multiplayer-distill-v2.sh
Normal file
24
ai/strong/launch-multiplayer-distill-v2.sh
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
revision=${1:?Pin completed dataset revision}
|
||||
mode=${2:-soft}
|
||||
[[ "$mode" == hard || "$mode" == soft ]]
|
||||
hf jobs run --detach --flavor "${HF_FLAVOR:-a10g-large}" --timeout 3h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_DATA_REPO=coyotte508/powergrid-ai-training-v1 \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--env RUN_NAME="multiplayer-distillation-v2-$mode" --env TARGET_MODE="$mode" --env TRAIN_SEED=622 --env ARCHITECTURE=multiplayer_ordered --env DATA_REVISION="$revision" --env EPOCHS=20 --env DATA_VERSION=multiplayer-teacher-v1 --env SHARDS=5 --env DISAGREEMENT_WEIGHT=2 \
|
||||
--label project=powergrid-ai --label stage="multiplayer-distillation-v2-$mode" \
|
||||
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
|
||||
set -euo pipefail
|
||||
python -m pip install --quiet --timeout 120 --retries 5 huggingface_hub==2.0.0 onnx==1.20.1 onnxruntime==1.30.0
|
||||
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\",\"strong-source-v20.tgz\",repo_type=\"dataset\",revision=\"c259cc1664fe39565bdbdd5d64789c9825a62692\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python ai/strong/test_teacher_contract.py
|
||||
python ai/strong/test_model_v4.py
|
||||
python -u ai/strong/distill.py
|
||||
'
|
||||
24
ai/strong/launch-multiplayer-distill.sh
Normal file
24
ai/strong/launch-multiplayer-distill.sh
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
revision=${1:?Pin completed dataset revision}
|
||||
mode=${2:-soft}
|
||||
[[ "$mode" == hard || "$mode" == soft ]]
|
||||
hf jobs run --detach --flavor "${HF_FLAVOR:-a10g-large}" --timeout 3h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_DATA_REPO=coyotte508/powergrid-ai-training-v1 \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--env RUN_NAME="multiplayer-distillation-v1-$mode" --env TARGET_MODE="$mode" --env TRAIN_SEED=622 --env ARCHITECTURE=multiplayer --env DATA_REVISION="$revision" --env EPOCHS=20 --env DATA_VERSION=multiplayer-teacher-v1 --env SHARDS=5 --env DISAGREEMENT_WEIGHT=2 \
|
||||
--label project=powergrid-ai --label stage="multiplayer-distillation-v1-$mode" \
|
||||
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
|
||||
set -euo pipefail
|
||||
python -m pip install --quiet --timeout 120 --retries 5 huggingface_hub==2.0.0 onnx==1.20.1 onnxruntime==1.30.0
|
||||
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\",\"strong-source-v18.tgz\",repo_type=\"dataset\",revision=\"49cc1bb94678e6ede37b606ae1ce9a8cb2018c1d\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python ai/strong/test_teacher_contract.py
|
||||
python ai/strong/test_model_v4.py
|
||||
python -u ai/strong/distill.py
|
||||
'
|
||||
21
ai/strong/launch-multiplayer-pipeline.sh
Normal file
21
ai/strong/launch-multiplayer-pipeline.sh
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
hf jobs run --detach --flavor a10g-large --timeout 3h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--env RUN_NAME=multiplayer-pipeline-v1 --env TRAIN_SEED=621 --env LR=.00005 --env ENTROPY=.005 --env ANCHOR=.03 --env UPDATES=10 --env EVAL_EVERY=5 --env ARCHITECTURE=multiplayer --env OPPONENT_MODE=mixed_search \
|
||||
--env ENVS=120 --env WORKERS=10 --env BATCH_SIZE=512 \
|
||||
--label project=powergrid-ai --label stage=multiplayer-pipeline-v1 \
|
||||
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
|
||||
set -euo pipefail
|
||||
python -m pip install --quiet --timeout 120 --retries 5 huggingface_hub==2.0.0 onnx==1.20.1
|
||||
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\",\"strong-source-v16.tgz\",repo_type=\"dataset\",revision=\"6064b1683379153e0a5dbca24903d41a972cbe0a\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs ai/strong/test-v4.cjs
|
||||
python ai/strong/test_model_v4.py
|
||||
python ai/strong/test_multiplayer_bridge.py
|
||||
python -u ai/strong/train.py
|
||||
'
|
||||
35
ai/strong/launch-multiplayer-refine-v1.sh
Normal file
35
ai/strong/launch-multiplayer-refine-v1.sh
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
#!/usr/bin/env bash
|
||||
# Warm-start balanced 2–6 player PPO after independent teacher-model screening.
|
||||
set -euo pipefail
|
||||
checkpoint=${1:?Supply selected ordered-model checkpoint path}
|
||||
revision=${2:?Pin its immutable model repository commit}
|
||||
run=${3:?Supply a unique refinement run name}
|
||||
[[ "$revision" =~ ^[0-9a-f]{40}$ ]]
|
||||
[[ "$checkpoint" == runs/*/best.pt ]]
|
||||
[[ "$run" =~ ^[a-zA-Z0-9_-]+$ ]]
|
||||
hf jobs run --detach --flavor "${HF_FLAVOR:-h200}" --timeout "${JOB_TIMEOUT:-12h}" \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--env INIT_CHECKPOINT="$checkpoint" --env INIT_REVISION="$revision" --env ANCHOR_POLICY=initial \
|
||||
--env ARCHITECTURE=multiplayer_ordered --env MIX_PLAYER_COUNTS=1 --env OPPONENT_MODE="${OPPONENT_MODE:-mixed_search}" \
|
||||
--env RUN_NAME="$run" --env TRAIN_SEED="${TRAIN_SEED:-623}" \
|
||||
--env ASYNC_ROLLOUT="${ASYNC_ROLLOUT:-0}" --env TRAIN_DEVICE="${TRAIN_DEVICE:-cuda}" --env TORCH_THREADS="${TORCH_THREADS:-2}" \
|
||||
--env LR=.00005 --env ENTROPY=.005 --env ANCHOR=.03 \
|
||||
--env UPDATES="${UPDATES:-80}" --env EVAL_EVERY=10 \
|
||||
--env ENVS=240 --env WORKERS="${WORKERS:-16}" --env BATCH_SIZE=512 \
|
||||
--label project=powergrid-ai --label stage="$run" \
|
||||
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
|
||||
set -euo pipefail
|
||||
python -m pip install --quiet --timeout 120 --retries 5 huggingface_hub==2.0.0 onnx==1.20.1 onnxruntime==1.30.0
|
||||
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\",\"strong-source-v26.tgz\",repo_type=\"dataset\",revision=\"80fcc719b64b13fe1592e206712b68f94ef19951\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python ai/strong/test_teacher_contract.py
|
||||
python ai/strong/test_model_v4.py
|
||||
python ai/strong/test_multiplayer_bridge.py
|
||||
python ai/strong/test_async_pool.py
|
||||
python -u ai/strong/train.py
|
||||
'
|
||||
22
ai/strong/launch-multiplayer-teacher.sh
Normal file
22
ai/strong/launch-multiplayer-teacher.sh
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
players=${1:?Specify player count 2–6}
|
||||
[[ "$players" =~ ^[2-6]$ ]]
|
||||
shard=$((players - 2))
|
||||
[[ "$shard" =~ ^[0-9]+$ ]]
|
||||
hf jobs run --detach --flavor cpu-performance --timeout 3h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_DATA_REPO=coyotte508/powergrid-ai-training-v1 \
|
||||
--env SHARD="$shard" --env GAMES=240 --env DATA_WORKERS=24 --env SEARCH_SAMPLES=16 --env GEOGRAPHY=1 --env FEATURE_REVISION=4.0-multiplayer --env PLAYER_COUNT="$players" --env DATA_VERSION=multiplayer-teacher-v1 --env INCLUDE_ALL_PHASES=1 \
|
||||
--label project=powergrid-ai --label stage="multiplayer-teacher-v1-$shard" \
|
||||
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
|
||||
set -euo pipefail
|
||||
python -m pip install --quiet --timeout 120 --retries 5 huggingface_hub==2.0.0
|
||||
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\",\"strong-source-v17.tgz\",repo_type=\"dataset\",revision=\"36c3d6b2f8545bd3551fc571a8cb6cb45a8f88b1\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python -u ai/strong/generate-search-data.py
|
||||
'
|
||||
19
ai/strong/launch-population.sh
Normal file
19
ai/strong/launch-population.sh
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
hf jobs run --detach --flavor l4x4 --timeout 3h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--env RUN_NAME=strong-league-v1 --env UPDATES=300 --env EVAL_EVERY=20 \
|
||||
--env ENVS=128 --env WORKERS=8 --env BATCH_SIZE=512 --env ROLLOUT_SAMPLES=8000 \
|
||||
--label project=powergrid-ai --label stage=strong-league-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\",\"strong-source-v2.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python -u ai/strong/population.py
|
||||
'
|
||||
20
ai/strong/launch-refine-a260.sh
Normal file
20
ai/strong/launch-refine-a260.sh
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
hf jobs run --detach --flavor a10g-large --timeout 4h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--env INIT_CHECKPOINT=runs/strong-league-v2-a/best.pt --env INIT_REVISION=b38515c29e57826de05b55b645c29591e4a886bf --env ANCHOR_POLICY=initial --env ALLOW_URANIUM39_TRANSFER=1 \
|
||||
--env RUN_NAME=strong-refine-a260-v1 --env TRAIN_SEED=412 --env LR=.00005 --env ENTROPY=.005 --env ANCHOR=.03 --env UPDATES=80 --env EVAL_EVERY=10 \
|
||||
--env ENVS=128 --env WORKERS=8 --env BATCH_SIZE=512 \
|
||||
--label project=powergrid-ai --label stage=strong-refine-a260-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\",\"strong-source-v12.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python -u ai/strong/train.py
|
||||
'
|
||||
20
ai/strong/launch-refine-full.sh
Normal file
20
ai/strong/launch-refine-full.sh
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
hf jobs run --detach --flavor a10g-large --timeout 4h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--env INIT_CHECKPOINT=runs/search-distillation-v3-soft/best.pt --env INIT_REVISION=45a839c001fce2fe3dd9b1f5c7a523db8ceee890 --env ANCHOR_POLICY=initial \
|
||||
--env RUN_NAME=strong-refine-v1-full --env TRAIN_SEED=410 --env LR=.0001 --env ENTROPY=.005 --env ANCHOR=.03 --env UPDATES=120 --env EVAL_EVERY=10 \
|
||||
--env ENVS=128 --env WORKERS=8 --env BATCH_SIZE=512 \
|
||||
--label project=powergrid-ai --label stage=strong-refine-v1-full \
|
||||
-- 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\",\"strong-source-v10.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python -u ai/strong/train.py
|
||||
'
|
||||
20
ai/strong/launch-refine-search.sh
Normal file
20
ai/strong/launch-refine-search.sh
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
hf jobs run --detach --flavor h200 --timeout 4h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--env INIT_CHECKPOINT=runs/search-distillation-v3-soft/best.pt --env INIT_REVISION=45a839c001fce2fe3dd9b1f5c7a523db8ceee890 --env ANCHOR_POLICY=initial --env OPPONENT_MODE=mixed_search --env STRATEGIC_ONLY=1 \
|
||||
--env RUN_NAME=strong-refine-v1-search --env TRAIN_SEED=411 --env LR=.00005 --env ENTROPY=.005 --env ANCHOR=.05 --env UPDATES=80 --env EVAL_EVERY=10 \
|
||||
--env ENVS=128 --env WORKERS=20 --env BATCH_SIZE=512 \
|
||||
--label project=powergrid-ai --label stage=strong-refine-v1-search \
|
||||
-- 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\",\"strong-source-v10.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python -u ai/strong/train.py
|
||||
'
|
||||
20
ai/strong/launch-search-data-v2.sh
Normal file
20
ai/strong/launch-search-data-v2.sh
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
shard=${1:?Specify numeric shard}
|
||||
[[ "$shard" =~ ^[0-9]+$ ]]
|
||||
hf jobs run --detach --flavor cpu-performance --timeout 2h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_DATA_REPO=coyotte508/powergrid-ai-training-v1 \
|
||||
--env SHARD="$shard" --env GAMES=256 --env DATA_WORKERS=24 --env SEARCH_SAMPLES=12 --env DATA_VERSION=search-teacher-v2 --env INCLUDE_ALL_PHASES=1 \
|
||||
--label project=powergrid-ai --label stage="search-teacher-v2-$shard" \
|
||||
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
|
||||
set -euo pipefail
|
||||
python -m pip install --quiet huggingface_hub
|
||||
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\",\"strong-source-v6.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python -u ai/strong/generate-search-data.py
|
||||
'
|
||||
20
ai/strong/launch-search-data-v3.sh
Normal file
20
ai/strong/launch-search-data-v3.sh
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
shard=${1:?Specify numeric shard}
|
||||
[[ "$shard" =~ ^[0-9]+$ ]]
|
||||
hf jobs run --detach --flavor cpu-performance --timeout 2h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_DATA_REPO=coyotte508/powergrid-ai-training-v1 \
|
||||
--env SHARD="$shard" --env GAMES=256 --env DATA_WORKERS=24 --env SEARCH_SAMPLES=12 --env DATA_VERSION=search-teacher-v3 --env INCLUDE_ALL_PHASES=1 \
|
||||
--label project=powergrid-ai --label stage="search-teacher-v3-$shard" \
|
||||
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
|
||||
set -euo pipefail
|
||||
python -m pip install --quiet huggingface_hub
|
||||
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\",\"strong-source-v8.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python -u ai/strong/generate-search-data.py
|
||||
'
|
||||
20
ai/strong/launch-search-data.sh
Normal file
20
ai/strong/launch-search-data.sh
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
shard=${1:?Specify numeric shard}
|
||||
[[ "$shard" =~ ^[0-9]+$ ]]
|
||||
hf jobs run --detach --flavor cpu-performance --timeout 2h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_DATA_REPO=coyotte508/powergrid-ai-training-v1 \
|
||||
--env SHARD="$shard" --env GAMES=128 --env DATA_WORKERS=24 --env SEARCH_SAMPLES=4 \
|
||||
--label project=powergrid-ai --label stage="search-teacher-v1-$shard" \
|
||||
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
|
||||
set -euo pipefail
|
||||
python -m pip install --quiet huggingface_hub
|
||||
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\",\"strong-source-v4.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python -u ai/strong/generate-search-data.py
|
||||
'
|
||||
18
ai/strong/launch-search-evaluation.sh
Normal file
18
ai/strong/launch-search-evaluation.sh
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
hf jobs run --detach --flavor cpu-performance --timeout 2h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--label project=powergrid-ai --label stage=b20-search-screening \
|
||||
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
|
||||
set -euo pipefail
|
||||
python -m pip install --quiet huggingface_hub 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\",\"strong-source-v4.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
python -c "from huggingface_hub import hf_hub_download; hf_hub_download(\"coyotte508/powergrid-ai-germany-v1\",\"runs/strong-league-v2-b/best.onnx\",revision=\"f9dfad5bde9862bc41aa42d77d9622621d70e8ce\",local_dir=\"models\")"
|
||||
python ai/strong/evaluate.py models/runs/strong-league-v2-b/best.onnx --opponent search --games 240 --workers 24 --seed strong-search-screening-v1 --output evaluation.json
|
||||
python -c "import os;from huggingface_hub import HfApi;HfApi().upload_file(repo_id=os.environ[\"HF_MODEL_REPO\"],path_or_fileobj=\"evaluation.json\",path_in_repo=\"runs/b20-search-screening/evaluation.json\")"
|
||||
'
|
||||
19
ai/strong/launch-search.sh
Normal file
19
ai/strong/launch-search.sh
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
hf jobs run --detach --flavor cpu-performance --timeout 2h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--env RUN_NAME=search-reference-v1 --env UPDATES=2 --env EVAL_EVERY=10 \
|
||||
--env ENVS=32 --env WORKERS=4 --env BATCH_SIZE=1024 --env ROLLOUT_SAMPLES=8000 \
|
||||
--label project=powergrid-ai --label stage=search-reference-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\",\"search-source-v1.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python -u ai/strong/search-benchmark.py
|
||||
'
|
||||
19
ai/strong/launch-smoke.sh
Normal file
19
ai/strong/launch-smoke.sh
Normal file
|
|
@ -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=strong-smoke-v1 --env UPDATES=2 --env EVAL_EVERY=10 \
|
||||
--env ENVS=32 --env WORKERS=4 --env BATCH_SIZE=1024 --env ROLLOUT_SAMPLES=8000 \
|
||||
--label project=powergrid-ai --label stage=strong-smoke-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\",\"strong-source-v1.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python -u ai/strong/train.py
|
||||
'
|
||||
29
ai/strong/launch-strong-replay-distill.sh
Normal file
29
ai/strong/launch-strong-replay-distill.sh
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
revision=${1:?Pin audited stronger-opponent dataset revision}
|
||||
mode=${2:-hard}
|
||||
[[ "$revision" =~ ^[0-9a-f]{40}$ ]]
|
||||
[[ "$mode" == hard || "$mode" == soft ]]
|
||||
hf jobs run --detach --flavor "${HF_FLAVOR:-a10g-large}" --timeout "${JOB_TIMEOUT:-4h}" \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_DATA_REPO=coyotte508/powergrid-ai-training-v1 \
|
||||
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--env RUN_NAME="${RUN_NAME:-multiplayer-distillation-strong-replay-v1-$mode}" --env TARGET_MODE="$mode" --env TRAIN_SEED=622 --env ARCHITECTURE=multiplayer_ordered --env DATA_REVISION="$revision" --env EPOCHS="${EPOCHS:-15}" --env LR="${LR:-0.00005}" --env DATA_VERSION="${DATA_VERSION:-multiplayer-teacher-v2-strong-repaired}" --env SHARDS=5 --env DISAGREEMENT_WEIGHT=2 \
|
||||
--env INIT_CHECKPOINT=runs/multiplayer-distillation-v2-hard/best.pt --env INIT_REVISION=ab34dd266010ded1c9a6c818c721e5505dd1ddeb \
|
||||
--env REPLAY_DATA_VERSION=multiplayer-teacher-v1 --env REPLAY_DATA_REVISION=082ca1456736940ee32c96db3ad1bc4e4d0b206b \
|
||||
--label project=powergrid-ai --label stage="multiplayer-distillation-strong-replay-$mode" \
|
||||
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
|
||||
set -euo pipefail
|
||||
python -m pip install --quiet --timeout 120 --retries 5 huggingface_hub==2.0.0 onnx==1.20.1 onnxruntime==1.30.0
|
||||
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\",\"strong-source-v30.tgz\",repo_type=\"dataset\",revision=\"508bc42027cae5bfeea01228b48069c8287b332a\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python ai/strong/test_teacher_contract.py
|
||||
python ai/strong/test_model_v4.py
|
||||
python ai/strong/test_distill_data.py
|
||||
python ai/strong/audit-teacher-dataset.py --revision "$DATA_REVISION" --version "$DATA_VERSION" --output /tmp/strong-teacher-audit.json
|
||||
python -u ai/strong/distill.py
|
||||
'
|
||||
28
ai/strong/launch-strong-teacher.sh
Normal file
28
ai/strong/launch-strong-teacher.sh
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
players=${1:?Specify player count 2–6}
|
||||
[[ "$players" =~ ^[2-6]$ ]]
|
||||
shard=$((players - 2))
|
||||
version=${DATA_VERSION:-multiplayer-teacher-v2-strong-pilot}
|
||||
games=${GAMES:-24}
|
||||
[[ "$version" =~ ^[a-zA-Z0-9_-]+$ ]]
|
||||
[[ "$games" =~ ^[0-9]+$ ]]
|
||||
(( games >= 8 * players && games % (4 * players) == 0 ))
|
||||
[[ "$shard" =~ ^[0-9]+$ ]]
|
||||
hf jobs run --detach --flavor cpu-performance --timeout "${JOB_TIMEOUT:-6h}" \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_DATA_REPO=coyotte508/powergrid-ai-training-v1 \
|
||||
--env TEACHER_OPPONENTS=search_geo --env OPPONENT_SEARCH_SAMPLES=16 \
|
||||
--env SHARD="$shard" --env GAMES="$games" --env DATA_WORKERS=24 --env SEARCH_SAMPLES=48 --env GEOGRAPHY=1 --env FEATURE_REVISION=4.0-multiplayer --env PLAYER_COUNT="$players" --env DATA_VERSION="$version" --env INCLUDE_ALL_PHASES=1 \
|
||||
--label project=powergrid-ai --label stage="$version-$shard" \
|
||||
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
|
||||
set -euo pipefail
|
||||
python -m pip install --quiet --timeout 120 --retries 5 huggingface_hub==2.0.0
|
||||
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\",\"strong-source-v29.tgz\",repo_type=\"dataset\",revision=\"a30fdb26474d2d78a4803f396c8888f9d974a371\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python -u ai/strong/generate-search-data.py
|
||||
'
|
||||
18
ai/strong/launch-teacher-reliability-v2.sh
Normal file
18
ai/strong/launch-teacher-reliability-v2.sh
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
players=${1:?Specify player count 2–6}
|
||||
[[ "$players" =~ ^[2-6]$ ]]
|
||||
hf jobs run --detach --flavor cpu-performance --timeout 6h \
|
||||
--secrets HF_TOKEN --env PLAYER_COUNT="$players" --env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--label project=powergrid-ai --label stage="teacher-reliability-v2-${players}p" \
|
||||
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
|
||||
set -euo pipefail
|
||||
python -m pip install --quiet --timeout 120 --retries 5 huggingface_hub==2.0.0
|
||||
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\",\"strong-source-v36.tgz\",repo_type=\"dataset\",revision=\"d07e072058ee877112d609280980fc806ee8ce28\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/strong/test-search-samples.cjs ai/strong/test-search-horizon.cjs
|
||||
python -u ai/strong/audit-search-budgets.py
|
||||
'
|
||||
16
ai/strong/launch-teacher-reliability.sh
Normal file
16
ai/strong/launch-teacher-reliability.sh
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
hf jobs run --detach --flavor cpu-performance --timeout 3h \
|
||||
--secrets HF_TOKEN --env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
|
||||
--label project=powergrid-ai --label stage=teacher-reliability-v1 \
|
||||
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
|
||||
set -euo pipefail
|
||||
python -m pip install --quiet --timeout 120 --retries 5 huggingface_hub==2.0.0
|
||||
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\",\"strong-source-v35.tgz\",repo_type=\"dataset\",revision=\"aee5febe0ea0c60988f76a937521e87956544526\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/strong/test-search-samples.cjs ai/strong/test-search-horizon.cjs
|
||||
python -u ai/strong/audit-search-targets.py
|
||||
'
|
||||
23
ai/strong/launch-teacher-repair.sh
Normal file
23
ai/strong/launch-teacher-repair.sh
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
revision=${1:?Pin completed original stronger-opponent dataset revision}
|
||||
[[ "$revision" =~ ^[0-9a-f]{40}$ ]]
|
||||
hf jobs run --detach --flavor cpu-performance --timeout 3h \
|
||||
--secrets HF_TOKEN \
|
||||
--env HF_DATA_REPO=coyotte508/powergrid-ai-training-v1 \
|
||||
--env REPAIR_INPUT_REVISION="$revision" \
|
||||
--env REPAIR_INPUT_VERSION=multiplayer-teacher-v2-strong \
|
||||
--env REPAIR_OUTPUT_VERSION=multiplayer-teacher-v2-strong-repaired \
|
||||
--env DATA_WORKERS=24 \
|
||||
--label project=powergrid-ai --label stage=strong-teacher-horizon-repair \
|
||||
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
|
||||
set -euo pipefail
|
||||
python -m pip install --quiet --timeout 120 --retries 5 huggingface_hub==2.0.0
|
||||
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\",\"strong-source-v33.tgz\",repo_type=\"dataset\",revision=\"be9262485a29f38dd5c7f0f8442909d70bb98b94\");tarfile.open(p).extractall(\"/workspace\")"
|
||||
cd /workspace
|
||||
node --test ai/test.cjs ai/strong/test.cjs
|
||||
python -u ai/strong/repair-teacher-dataset.py
|
||||
'
|
||||
96
ai/strong/league-admission-protocol-v1.json
Normal file
96
ai/strong/league-admission-protocol-v1.json
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
{
|
||||
"purpose": "Development comparison of snapshot admission policies; not final qualification.",
|
||||
"training_source_revision": "2c273f96562d0cc2f8c05a2735d8c0492ab77fd8",
|
||||
"arms": {
|
||||
"best": {
|
||||
"run": "multiplayer-league-admission-v1-best",
|
||||
"job_id": "6abdef75404719ba37616230"
|
||||
},
|
||||
"periodic_anchor": {
|
||||
"run": "multiplayer-league-admission-v1-periodic-anchor",
|
||||
"job_id": "6abdef76fbc85ba68235f6a0"
|
||||
}
|
||||
},
|
||||
"checkpoint_updates": [9, 19],
|
||||
"primary_checkpoint_update": 19,
|
||||
"checkpoint_selection": "Use latest at each scheduled update, never internal best. Pin the immutable repository revision and checkpoint/export hashes before launching each screen.",
|
||||
"scope": {
|
||||
"map": "Germany",
|
||||
"players": [2, 3, 4, 5, 6],
|
||||
"variants": ["original", "recharged"],
|
||||
"auctions": ["open", "sealed"]
|
||||
},
|
||||
"arena_source_revision": "37465b08df007221665d796448aea57e6828257e",
|
||||
"candidate_search_samples": 0,
|
||||
"candidate_geography": 0,
|
||||
"search_max_steps": 2400,
|
||||
"seed_template": "multiplayer-screening-paired-v1-{players}p",
|
||||
"deal_offsets": [
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
|
||||
30, 31, 32, 33, 34, 35, 36, 37, 38, 39
|
||||
],
|
||||
"matches_per_deal": "All candidate seats and all four rule combinations.",
|
||||
"screens": [
|
||||
{
|
||||
"players": 2,
|
||||
"opponent": "economic",
|
||||
"games": 320
|
||||
},
|
||||
{
|
||||
"players": 3,
|
||||
"opponent": "economic",
|
||||
"games": 480
|
||||
},
|
||||
{
|
||||
"players": 4,
|
||||
"opponent": "economic",
|
||||
"games": 640
|
||||
},
|
||||
{
|
||||
"players": 5,
|
||||
"opponent": "economic",
|
||||
"games": 800
|
||||
},
|
||||
{
|
||||
"players": 6,
|
||||
"opponent": "economic",
|
||||
"games": 960
|
||||
},
|
||||
{
|
||||
"players": 3,
|
||||
"opponent": "a260",
|
||||
"games": 480,
|
||||
"model_path": "runs/strong-league-v2-a/best.onnx",
|
||||
"revision": "b38515c29e57826de05b55b645c29591e4a886bf",
|
||||
"sha256": "9b46db558669a0c3085412fe2544359eda55ed9f092dffb67bead6af3c409ecd"
|
||||
}
|
||||
],
|
||||
"total_games": 14720,
|
||||
"validation": [
|
||||
"2553-fixture checkpoint/export comparison, including strict numerical tolerances; record failures and do not qualify failing exports.",
|
||||
"Exact candidate and opponent hashes, counts, seed sets, unique seat/rule/deal keys and paired completeness.",
|
||||
"Zero actual-game truncations, illegal actions and search truncations; explicit search diagnostics.",
|
||||
"Inspect training metrics for both arms: completed games, truncation, admission mode and actual snapshot updates."
|
||||
],
|
||||
"comparisons": {
|
||||
"primary": "periodic_anchor minus best at update19, separately for each opponent/player count; no pooled win rate across counts.",
|
||||
"secondary": [
|
||||
"Same comparison at update9.",
|
||||
"Each arm versus starting H200 update29 on the same held-out deals.",
|
||||
"Separate original/open, original/sealed, recharged/open and recharged/sealed results for every count/opponent."
|
||||
],
|
||||
"pairing_key": ["gameSeed", "variant", "sealed", "seat"],
|
||||
"bootstrap_unit": "gameSeed, retaining all seats and rule repeats",
|
||||
"bootstrap_replicates": 20000,
|
||||
"bootstrap_seed": 623,
|
||||
"interval": 0.95
|
||||
},
|
||||
"interpretation": [
|
||||
"A single training seed is a pilot and cannot establish robustness across training randomness.",
|
||||
"Async scheduling does not guarantee identical training trajectories despite matched configuration.",
|
||||
"Intervals are marginal exploratory intervals, not simultaneous family-wide confidence bounds.",
|
||||
"These development seeds have been used for previous checkpoint screening; they are not the reserved final test.",
|
||||
"Report all scheduled checkpoints and comparisons, including regressions. Do not silently select the best subgroup.",
|
||||
"No automatic promotion or deployment. Final strength, serving and export gates remain unchanged. Strong search-opponent follow-up requires evidence from these screens."
|
||||
]
|
||||
}
|
||||
86
ai/strong/model.py
Normal file
86
ai/strong/model.py
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
import numpy as np
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
|
||||
class Policy(nn.Module):
|
||||
def __init__(self, sd=738, ad=96, width=384, strategic_only=False):
|
||||
super().__init__()
|
||||
self.strategic_only = strategic_only
|
||||
self.state = nn.Sequential(
|
||||
nn.Linear(sd, width),
|
||||
nn.LayerNorm(width),
|
||||
nn.SiLU(),
|
||||
nn.Linear(width, width),
|
||||
nn.SiLU(),
|
||||
)
|
||||
self.action = nn.Sequential(nn.Linear(ad, 128), nn.SiLU())
|
||||
self.score = nn.Sequential(
|
||||
nn.Linear(width + 128, 256), nn.SiLU(), nn.Linear(256, 1)
|
||||
)
|
||||
self.value = nn.Sequential(nn.Linear(width, 128), nn.SiLU(), nn.Linear(128, 3))
|
||||
nn.init.zeros_(self.score[-1].weight)
|
||||
nn.init.zeros_(self.score[-1].bias)
|
||||
|
||||
def forward(self, state, actions, mask):
|
||||
s = self.state(state)
|
||||
a = self.action(actions)
|
||||
residual = self.score(
|
||||
torch.cat((s[:, None, :].expand(-1, a.shape[1], -1), a), -1)
|
||||
).squeeze(-1)
|
||||
if self.strategic_only:
|
||||
strategic = (
|
||||
(actions[:, :, 0] + actions[:, :, 1] + actions[:, :, 5]) > 0
|
||||
) & mask
|
||||
residual = residual * strategic.any(dim=1, keepdim=True)
|
||||
# Start from a competent public-information policy; learn corrections.
|
||||
logits = actions[:, :, 74] * 2 + residual
|
||||
return logits.masked_fill(~mask, -1e9), self.value(s).softmax(-1)
|
||||
|
||||
|
||||
def tensors(rows, device):
|
||||
n = len(rows)
|
||||
m = max(len(r["actions"]) for r in rows)
|
||||
ad = len(rows[0]["actions"][0])
|
||||
state = np.asarray([r["state"] for r in rows], np.float32)
|
||||
actions = np.zeros((n, m, ad), np.float32)
|
||||
mask = np.zeros((n, m), bool)
|
||||
for i, r in enumerate(rows):
|
||||
actions[i, : len(r["actions"])] = r["actions"]
|
||||
mask[i, : len(r["actions"])] = True
|
||||
return tuple(torch.from_numpy(a).to(device) for a in [state, actions, mask])
|
||||
|
||||
|
||||
class RuleSpecialists(nn.Module):
|
||||
"""Fixed specialists selected only by the public schema-3 rule flags."""
|
||||
|
||||
def __init__(self, default_strategic_only=False, sealed_strategic_only=False):
|
||||
super().__init__()
|
||||
self.default_policy = Policy(strategic_only=default_strategic_only)
|
||||
self.recharged_sealed_policy = Policy(strategic_only=sealed_strategic_only)
|
||||
|
||||
def forward(self, state, actions, mask):
|
||||
regular = self.default_policy(state, actions, mask)
|
||||
sealed = self.recharged_sealed_policy(state, actions, mask)
|
||||
# Eight phase flags, round, step, Recharged flag, sealed-auction flag.
|
||||
use_sealed = ((state[:, 10] > 0.5) & (state[:, 11] > 0.5))[:, None]
|
||||
return tuple(torch.where(use_sealed, b, a) for a, b in zip(regular, sealed))
|
||||
|
||||
|
||||
def policy_from_checkpoint(checkpoint):
|
||||
architecture = checkpoint.get("architecture", "policy")
|
||||
if architecture in ["multiplayer", "multiplayer_ordered"]:
|
||||
from model_v4 import MultiplayerPolicy
|
||||
|
||||
args = dict(checkpoint.get("model_args", {}))
|
||||
if architecture == "multiplayer_ordered":
|
||||
args["ordered_players"] = True
|
||||
net = MultiplayerPolicy(**args)
|
||||
elif architecture == "rule_specialists":
|
||||
net = RuleSpecialists(**checkpoint["model_args"])
|
||||
elif architecture == "policy":
|
||||
net = Policy(strategic_only=checkpoint.get("strategic_only", False))
|
||||
else:
|
||||
raise ValueError(f"Unsupported architecture: {architecture}")
|
||||
net.load_state_dict(checkpoint["state_dict"])
|
||||
return net
|
||||
56
ai/strong/model_v4.py
Normal file
56
ai/strong/model_v4.py
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
"""Six-slot public-state policy; inactive players have exactly zero value mass."""
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
|
||||
class MultiplayerPolicy(nn.Module):
|
||||
def __init__(self, width=384, ordered_players=False):
|
||||
super().__init__()
|
||||
self.ordered_players = ordered_players
|
||||
self.player = nn.Sequential(nn.Linear(74, 128), nn.LayerNorm(128), nn.SiLU())
|
||||
# Global context, city ownership and territory occupancy retain seat order.
|
||||
self.context = nn.Sequential(
|
||||
nn.Linear(258 + 308 + 133 + (896 if ordered_players else 256) + 6, width),
|
||||
nn.LayerNorm(width),
|
||||
nn.SiLU(),
|
||||
nn.Linear(width, width),
|
||||
nn.SiLU(),
|
||||
)
|
||||
self.action = nn.Sequential(nn.Linear(98, 128), nn.SiLU())
|
||||
self.score = nn.Sequential(
|
||||
nn.Linear(width + 128, 256), nn.SiLU(), nn.Linear(256, 1)
|
||||
)
|
||||
self.value = nn.Sequential(
|
||||
nn.Linear(width + 128, 128), nn.SiLU(), nn.Linear(128, 1)
|
||||
)
|
||||
nn.init.zeros_(self.score[-1].weight)
|
||||
nn.init.zeros_(self.score[-1].bias)
|
||||
|
||||
def forward(self, state, actions, mask):
|
||||
active = state[:, :6] > 0.5
|
||||
p = self.player(state[:, 264:708].reshape(-1, 6, 74))
|
||||
pooled = (p * active[:, :, None]).sum(1) / active.sum(1, keepdim=True).clamp(
|
||||
min=1
|
||||
)
|
||||
# Keep holdings attached to the same relative seats used by city ownership
|
||||
# and action territory features. The mean alone loses those associations.
|
||||
player_context = (
|
||||
(p * active[:, :, None]).flatten(1) if self.ordered_players else p[:, 0]
|
||||
)
|
||||
s = self.context(
|
||||
torch.cat(
|
||||
(state[:, 6:264], state[:, 708:], player_context, pooled, state[:, :6]),
|
||||
-1,
|
||||
)
|
||||
)
|
||||
a = self.action(actions)
|
||||
logits = actions[:, :, 74] * 2 + self.score(
|
||||
torch.cat((s[:, None].expand(-1, a.shape[1], -1), a), -1)
|
||||
).squeeze(-1)
|
||||
values = self.value(torch.cat((s[:, None].expand(-1, 6, -1), p), -1)).squeeze(
|
||||
-1
|
||||
)
|
||||
return logits.masked_fill(~mask, -1e9), values.masked_fill(
|
||||
~active, -1e9
|
||||
).softmax(-1)
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue