Fix fuel teacher and launch economic-policy league training
This commit is contained in:
parent
e8c83925fb
commit
1c7645b594
30 changed files with 1759 additions and 14 deletions
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,
|
||||
};
|
||||
31
ai/core.cjs
31
ai/core.cjs
|
|
@ -105,7 +105,7 @@ function actionFeatures(g, seat, a) {
|
|||
: a.name === 'UsePowerPlant'
|
||||
? p.powerPlants.find((x) => x.number === d.powerPlant)
|
||||
: g.chosenPowerPlant;
|
||||
const cost = a.name === 'Bid' ? d : d?.price || 0;
|
||||
const cost = a.name === 'Bid' ? d : a.name === 'BuyResource' ? resourcePrice(g, d.resource) : d?.price || 0;
|
||||
return [
|
||||
...onehot(a.name, TYPES),
|
||||
cost / 500,
|
||||
|
|
@ -117,6 +117,11 @@ function actionFeatures(g, seat, a) {
|
|||
...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;
|
||||
|
|
@ -126,7 +131,7 @@ function fuelDemand(g, p) {
|
|||
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 (pp.type === 4) resource = resourcePrice(g, 'coal') <= resourcePrice(g, 'oil') ? 'coal' : 'oil';
|
||||
if (resource) need[resource] += pp.cost;
|
||||
}
|
||||
return need;
|
||||
|
|
@ -134,7 +139,11 @@ function fuelDemand(g, p) {
|
|||
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)
|
||||
(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);
|
||||
|
|
@ -168,10 +177,10 @@ function heuristicScore(g, seat, a) {
|
|||
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
|
||||
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': {
|
||||
|
|
@ -183,9 +192,7 @@ function heuristicScore(g, seat, a) {
|
|||
}
|
||||
case 'UsePowerPlant':
|
||||
return (
|
||||
40 +
|
||||
(d.citiesPowered || 0) * 5 -
|
||||
(d.resourcesSpent || []).reduce((n, r) => n + (g[r + 'Prices']?.[0] || 8), 0)
|
||||
40 + (d.citiesPowered || 0) * 5 - (d.resourcesSpent || []).reduce((n, r) => n + resourcePrice(g, r), 0)
|
||||
);
|
||||
case 'Pass':
|
||||
return 0;
|
||||
|
|
@ -236,4 +243,8 @@ module.exports = {
|
|||
outcome,
|
||||
start,
|
||||
seedrandom,
|
||||
resourcePrice,
|
||||
fuelDemand,
|
||||
fuelCost,
|
||||
capacity,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
const c = require('./core.cjs'),
|
||||
const c = require('./core-v2.cjs'),
|
||||
readline = require('node:readline');
|
||||
(async () => {
|
||||
for await (const line of readline.createInterface({ input: process.stdin })) {
|
||||
|
|
|
|||
|
|
@ -7,11 +7,11 @@ from concurrent.futures import ThreadPoolExecutor
|
|||
|
||||
|
||||
class EnginePool:
|
||||
def __init__(self, workers=1, seed="rollout-v1"):
|
||||
def __init__(self, workers=1, seed="rollout-v1", script="ai/bridge.cjs"):
|
||||
self.executor = ThreadPoolExecutor(workers)
|
||||
self.processes = [
|
||||
subprocess.Popen(
|
||||
["node", "ai/bridge.cjs"],
|
||||
["node", script],
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
text=True,
|
||||
|
|
@ -39,7 +39,7 @@ class EnginePool:
|
|||
if n < workers:
|
||||
raise ValueError("Need at least one environment per worker")
|
||||
self.sizes = [n // workers + (i < n % workers) for i in range(workers)]
|
||||
requests = [{"op": "reset", "n": n} for n in self.sizes]
|
||||
requests = [{**request, "n": n} for n in self.sizes]
|
||||
else:
|
||||
requests = []
|
||||
offset = 0
|
||||
|
|
|
|||
39
ai/strong/README.md
Normal file
39
ai/strong/README.md
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
# 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.
|
||||
|
||||
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.
|
||||
|
||||
## 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.
|
||||
1
ai/strong/benchmark-features.cjs
Normal file
1
ai/strong/benchmark-features.cjs
Normal file
|
|
@ -0,0 +1 @@
|
|||
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')}));
|
||||
94
ai/strong/bridge.cjs
Normal file
94
ai/strong/bridge.cjs
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
const c = require('../core.cjs'),
|
||||
eco = require('./economics.cjs'),
|
||||
f = require('./features.cjs'),
|
||||
readline = require('node:readline');
|
||||
let envs = [],
|
||||
sequence = 0;
|
||||
const seed = process.env.SEED || 'strong-train';
|
||||
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
|
||||
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 = f.encode(e.g, seat);
|
||||
delete x.moves;
|
||||
return { ...x, episode: e.id, roles: e.roles, round: e.g.round };
|
||||
}
|
||||
function reset(mode = 'mixed') {
|
||||
const id = sequence++,
|
||||
seat = Math.floor(id / 4) % 3,
|
||||
kind = Math.floor(c.seedrandom(seed + '-opponents-' + id)() * 8);
|
||||
const opponent =
|
||||
mode === 'mixed'
|
||||
? ['economic', 'heuristic', 'rush', 'legacy', 'selfplay', 'snapshot0', 'snapshot1', 'snapshot2'][kind]
|
||||
: mode;
|
||||
const roles =
|
||||
opponent === 'selfplay'
|
||||
? ['learner', 'learner', 'learner']
|
||||
: Array.from({ length: 3 }, (_, i) => (i === seat ? 'learner' : opponent));
|
||||
const e = {
|
||||
id,
|
||||
g: c.start(seed + '-' + id, id % 2 ? 'recharged' : 'original', id % 4 < 2),
|
||||
roles,
|
||||
rng: c.seedrandom(seed + '-bot-' + id),
|
||||
steps: 0,
|
||||
};
|
||||
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') envs = Array.from({ length: q.n }, () => reset(q.mode));
|
||||
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];
|
||||
c.E.move(e.g, c.candidates(e.g, seat)[q.actions[i]], seat);
|
||||
e.steps++;
|
||||
advance(e);
|
||||
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) : [0, 0, 0],
|
||||
steps: e.steps,
|
||||
roles: e.roles,
|
||||
});
|
||||
}
|
||||
else throw Error('unknown op');
|
||||
console.log(JSON.stringify({ observations: envs.map(observation), ended }));
|
||||
} catch (err) {
|
||||
console.error(err.stack);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
})();
|
||||
198
ai/strong/economics.cjs
Normal file
198
ai/strong/economics.cjs
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
// 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,
|
||||
};
|
||||
83
ai/strong/evaluate.py
Normal file
83
ai/strong/evaluate.py
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
"""Independent CPU arena, with reserved seeds and per-rule results."""
|
||||
|
||||
import sys, argparse, json, time
|
||||
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
|
||||
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("model")
|
||||
p.add_argument(
|
||||
"--opponent",
|
||||
default="economic",
|
||||
choices=["economic", "heuristic", "rush", "legacy"],
|
||||
)
|
||||
p.add_argument("--games", type=int, default=480)
|
||||
p.add_argument("--seed", default="strong-screening-v1")
|
||||
p.add_argument("--output", required=True)
|
||||
args = p.parse_args()
|
||||
model = Model(args.model)
|
||||
pool = EnginePool(4, seed=args.seed, script="ai/strong/bridge.cjs")
|
||||
current = pool.call({"op": "reset", "n": args.games, "mode": args.opponent})[
|
||||
"observations"
|
||||
]
|
||||
rows = []
|
||||
latency = []
|
||||
start = time.perf_counter()
|
||||
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()
|
||||
a, _ = model.predict(x["state"], x["actions"])
|
||||
latency.append(1000 * (time.perf_counter() - t))
|
||||
actions.append(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],
|
||||
}
|
||||
)
|
||||
finally:
|
||||
pool.close()
|
||||
report = {
|
||||
"model": args.model,
|
||||
"model_sha256": model.sha256,
|
||||
"opponent": args.opponent,
|
||||
"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,
|
||||
}
|
||||
Path(args.output).write_text(json.dumps(report, indent=2))
|
||||
print(json.dumps({k: v for k, v in report.items() if k != "results"}))
|
||||
22
ai/strong/experiments.json
Normal file
22
ai/strong/experiments.json
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
{
|
||||
"goal": "Strong play beyond the default bot; ongoing",
|
||||
"source_archive": "strong-source-v3.tgz",
|
||||
"source_dataset_commit": "d43f77890c221bdcf232d06e14fe02ec8f59cf54",
|
||||
"model_repo": "coyotte508/powergrid-ai-germany-v1",
|
||||
"jobs": {
|
||||
"strong-smoke-v1": "6abd11a4fbc85ba68235b126",
|
||||
"strong-league-v2-a": "6abd15cafbc85ba68235b345",
|
||||
"strong-league-v2-b": "6abd146afbc85ba68235b28d",
|
||||
"strong-league-v2-c": "6abd15cafbc85ba68235b347",
|
||||
"strong-league-v2-d": "6abd15ca404719ba376134e5",
|
||||
"search-reference-v1": "6abd1314404719ba376133b5"
|
||||
},
|
||||
"cancelled_while_queued": [
|
||||
"6abd128efbc85ba68235b1a6",
|
||||
"6abd146b404719ba37613448",
|
||||
"6abd146bfbc85ba68235b291",
|
||||
"6abd146bfbc85ba68235b28f"
|
||||
],
|
||||
"heldout_final_seed_prefix": "strong-final-reserved-v1",
|
||||
"final_seed_prefix_used": false
|
||||
}
|
||||
82
ai/strong/features.cjs
Normal file
82
ai/strong/features.cjs
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
const c = require('../core.cjs'),
|
||||
eco = require('./economics.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 {
|
||||
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 };
|
||||
49
ai/strong/infer.py
Normal file
49
ai/strong/infer.py
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
"""Persistent CPU ONNX worker for schema 3 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
|
||||
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("model")
|
||||
args = p.parse_args()
|
||||
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)
|
||||
if "error" in r:
|
||||
raise ValueError(r["error"])
|
||||
index, values = model.predict(r["state"], r["actions"])
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"requestId": q.get("requestId"),
|
||||
"revision": q.get("revision"),
|
||||
"move": r["moves"][index],
|
||||
"winProbabilities": values,
|
||||
"valueStatus": "uncalibrated-training-opponents",
|
||||
"playerOrder": r["playerOrder"],
|
||||
"schema": 3,
|
||||
"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
|
||||
'
|
||||
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
|
||||
'
|
||||
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
|
||||
'
|
||||
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
|
||||
'
|
||||
45
ai/strong/model.py
Normal file
45
ai/strong/model.py
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import numpy as np
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
|
||||
class Policy(nn.Module):
|
||||
def __init__(self, sd=738, ad=96, width=384):
|
||||
super().__init__()
|
||||
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)
|
||||
# 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])
|
||||
32
ai/strong/population.py
Normal file
32
ai/strong/population.py
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
"""Independent learners on four GPUs; each learns against a frozen-policy league."""
|
||||
|
||||
import os, subprocess, json
|
||||
|
||||
configs = [
|
||||
("a", "0.0001", ".01", ".01"),
|
||||
("b", "0.0003", ".01", ".01"),
|
||||
("c", "0.0001", ".025", ".003"),
|
||||
("d", "0.0003", ".025", ".003"),
|
||||
]
|
||||
processes = []
|
||||
for i, (name, lr, entropy, anchor) in enumerate(configs):
|
||||
env = {
|
||||
**os.environ,
|
||||
"CUDA_VISIBLE_DEVICES": str(i),
|
||||
"RUN_NAME": "strong-league-v1-" + name,
|
||||
"TRAIN_SEED": str(201 + i),
|
||||
"LR": lr,
|
||||
"ENTROPY": entropy,
|
||||
"ANCHOR": anchor,
|
||||
}
|
||||
processes.append(
|
||||
(name, subprocess.Popen(["python", "-u", "ai/strong/train.py"], env=env))
|
||||
)
|
||||
failed = []
|
||||
for name, p in processes:
|
||||
code = p.wait()
|
||||
if code:
|
||||
failed.append({"learner": name, "exit": code})
|
||||
print(json.dumps({"population_completed": not failed, "failures": failed}), flush=True)
|
||||
if failed:
|
||||
raise SystemExit(1)
|
||||
53
ai/strong/public-graph.cjs
Normal file
53
ai/strong/public-graph.cjs
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
// Explicit map topology for multi-map policy work. Only public game fields are read.
|
||||
function encode(g, seat) {
|
||||
const order = Array.from({ length: g.players.length }, (_, i) => (seat + i) % g.players.length);
|
||||
const cities = [...g.map.cities].sort((a, b) => a.name.localeCompare(b.name));
|
||||
const index = new Map(cities.map((c, i) => [c.name, i]));
|
||||
const regions = [...new Set(cities.map((c) => c.region || 'main'))].sort(),
|
||||
islands = [...new Set(cities.map((c) => c.island || 'main'))].sort();
|
||||
const nodes = cities.map((city) => {
|
||||
const owners = order.map((id) => +g.players[id].cities.some((c) => c.name === city.name)),
|
||||
occupied = owners.reduce((a, b) => a + b, 0);
|
||||
const capacity = city.singleOccupancy ? 1 : city.slotCosts?.length ?? 3,
|
||||
slots = city.singleOccupancy ? 1 : city.stepSlots?.[g.step - 1] ?? g.step;
|
||||
const permanentBlocked = !!g.blockedCities?.includes(city.name),
|
||||
available = !permanentBlocked && !(city.transregional && g.step < 2);
|
||||
return {
|
||||
name: city.name,
|
||||
region: regions.indexOf(city.region || 'main'),
|
||||
island: islands.indexOf(city.island || 'main'),
|
||||
owners,
|
||||
openSlots: available ? Math.max(0, Math.min(capacity, slots) - occupied) : 0,
|
||||
futureSlots: permanentBlocked ? 0 : Math.max(0, capacity - occupied),
|
||||
slotCosts: city.slotCosts || [10, 15, 20],
|
||||
stepSlots: city.stepSlots || [1, 2, 3],
|
||||
transregional: !!city.transregional,
|
||||
nuclearBanned: !!g.map.noUraniumRegions?.includes(city.region),
|
||||
blocked: permanentBlocked,
|
||||
};
|
||||
});
|
||||
const edges = g.map.connections
|
||||
.filter((e) => e.nodes.every((n) => index.has(n)))
|
||||
.map((e) => ({ a: index.get(e.nodes[0]), b: index.get(e.nodes[1]), cost: e.cost }));
|
||||
return {
|
||||
nodes,
|
||||
edges,
|
||||
regions,
|
||||
islands,
|
||||
crossIslandSurcharge: g.map.crossIslandSurcharge || 0,
|
||||
playerOrder: order.map((id) => g.playerOrder.indexOf(id)),
|
||||
currentPlayers: order.map((id) => g.currentPlayers.includes(id)),
|
||||
players: order.map((id) => ({
|
||||
cities: g.players[id].cities.length,
|
||||
money: g.players[id].money,
|
||||
powerPlants: g.players[id].powerPlants.map((p) => ({
|
||||
number: p.number,
|
||||
type: p.type,
|
||||
cost: p.cost,
|
||||
citiesPowered: p.citiesPowered,
|
||||
})),
|
||||
fuel: ['coal', 'oil', 'garbage', 'uranium'].map((r) => g.players[id][r + 'Left']),
|
||||
})),
|
||||
};
|
||||
}
|
||||
module.exports = { encode };
|
||||
40
ai/strong/search-benchmark.py
Normal file
40
ai/strong/search-benchmark.py
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import os, json, subprocess, concurrent.futures
|
||||
from pathlib import Path
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
|
||||
def run(pair):
|
||||
seed, opponent = pair
|
||||
result = subprocess.run(
|
||||
["node", "ai/strong/tournament.cjs", "search", opponent],
|
||||
env={**os.environ, "SEEDS": "1", "SEED_START": str(seed)},
|
||||
text=True,
|
||||
capture_output=True,
|
||||
check=True,
|
||||
)
|
||||
report = json.loads(result.stdout)
|
||||
print(
|
||||
json.dumps({"seed": seed, "opponent": opponent, "win": report["win"]}),
|
||||
flush=True,
|
||||
)
|
||||
return report
|
||||
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(24) as pool:
|
||||
reports = list(
|
||||
pool.map(
|
||||
run,
|
||||
[
|
||||
(seed, opponent)
|
||||
for seed in range(20)
|
||||
for opponent in ["economic", "heuristic"]
|
||||
],
|
||||
)
|
||||
)
|
||||
p = Path("search-evaluation.json")
|
||||
p.write_text(json.dumps(reports))
|
||||
HfApi().upload_file(
|
||||
repo_id=os.environ["HF_MODEL_REPO"],
|
||||
path_or_fileobj=str(p),
|
||||
path_in_repo="runs/search-reference-v1/evaluation.json",
|
||||
)
|
||||
53
ai/strong/search.cjs
Normal file
53
ai/strong/search.cjs
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
// Public-belief rollout search. The live draw pile and sealed bids are never replayed.
|
||||
const c = require('../core.cjs'),
|
||||
eco = require('./economics.cjs');
|
||||
const { createAnalysisScenario } = require('../../engine/dist/src/analysis.js');
|
||||
function shortlist(g, seat, limit = 5) {
|
||||
const a = c.candidates(g, seat),
|
||||
v = eco.scores(g, seat, a),
|
||||
indices = [...a.keys()].sort((i, j) => v[j] - v[i]);
|
||||
const chosen = new Set(indices.slice(0, Math.max(1, limit - 2)));
|
||||
const pass = a.findIndex((x) => x.name === 'Pass');
|
||||
if (pass >= 0) chosen.add(pass);
|
||||
chosen.add(c.heuristic(g, seat).index);
|
||||
// A sampled middle bid helps find strategic bids not selected by the greedy prior.
|
||||
const bids = indices.filter((i) => a[i].name === 'Bid');
|
||||
if (bids.length > 4) chosen.add(bids[Math.floor(bids.length / 2)]);
|
||||
return [...chosen].slice(0, limit);
|
||||
}
|
||||
function choose(g, seat, { samples = 6, candidates = 5, seed = 'public-search', maxSteps = 1200 } = {}) {
|
||||
const actions = c.candidates(g, seat),
|
||||
options = shortlist(g, seat, candidates);
|
||||
if (options.length === 1) return { index: options[0], action: actions[options[0]], evaluations: 0 };
|
||||
const totals = Object.fromEntries(options.map((i) => [i, 0]));
|
||||
let evaluations = 0,
|
||||
truncated = 0;
|
||||
for (let sample = 0; sample < samples; sample++) {
|
||||
const scenario = createAnalysisScenario(g, { player: seat, seed: seed + '-' + sample });
|
||||
for (const index of options) {
|
||||
const sim = structuredClone(scenario),
|
||||
rng = c.seedrandom(seed + '-rollout-' + sample);
|
||||
c.E.move(sim, structuredClone(actions[index]), seat);
|
||||
let step = 0;
|
||||
while (!c.E.ended(sim) && step++ < maxSteps) {
|
||||
const p = sim.currentPlayers[0];
|
||||
const move = sample % 2 ? c.heuristic(sim, p, rng).action : eco.choose(sim, p, rng).action;
|
||||
c.E.move(sim, move, p);
|
||||
}
|
||||
if (c.E.ended(sim)) totals[index] += c.outcome(sim)[seat];
|
||||
else truncated++;
|
||||
evaluations++;
|
||||
}
|
||||
}
|
||||
const prior = eco.scores(g, seat, actions);
|
||||
const index = options.sort((a, b) => totals[b] - totals[a] || prior[b] - prior[a])[0];
|
||||
return {
|
||||
index,
|
||||
action: actions[index],
|
||||
evaluations,
|
||||
truncated,
|
||||
winEstimate: totals[index] / samples,
|
||||
values: totals,
|
||||
};
|
||||
}
|
||||
module.exports = { choose, shortlist };
|
||||
78
ai/strong/spatial.cjs
Normal file
78
ai/strong/spatial.cjs
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
// Map-derived territory features. Region and island labels come from the engine.
|
||||
function orderAfterBuild(g, seat) {
|
||||
return g.players
|
||||
.map((p) => ({
|
||||
id: p.id,
|
||||
cities: p.cities.length + (p.id === seat ? 1 : 0),
|
||||
plant: Math.max(0, ...p.powerPlants.map((x) => x.number)),
|
||||
}))
|
||||
.sort((a, b) => b.cities - a.cities || b.plant - a.plant)
|
||||
.map((p) => p.id);
|
||||
}
|
||||
function territories(g, seat) {
|
||||
const order = Array.from({ length: g.players.length }, (_, i) => (seat + i) % g.players.length);
|
||||
const groups = (key) =>
|
||||
[...new Set(g.map.cities.map((c) => c[key] || 'main'))].sort().map((name) => {
|
||||
const cities = g.map.cities.filter((c) => (c[key] || 'main') === name);
|
||||
let empty = 0,
|
||||
open = 0,
|
||||
totalFree = 0;
|
||||
for (const city of cities) {
|
||||
const occupied = g.players.filter((p) => p.cities.some((c) => c.name === city.name)).length;
|
||||
const slots = city.singleOccupancy ? 1 : city.stepSlots?.[g.step - 1] ?? g.step,
|
||||
capacity = city.singleOccupancy ? 1 : city.slotCosts?.length ?? 3;
|
||||
const blocked = g.blockedCities?.includes(city.name) || (city.transregional && g.step < 2);
|
||||
empty += +(!occupied && !blocked);
|
||||
open += blocked ? 0 : Math.max(0, Math.min(slots, capacity) - occupied);
|
||||
totalFree += blocked ? 0 : Math.max(0, capacity - occupied);
|
||||
}
|
||||
return {
|
||||
name,
|
||||
size: cities.length,
|
||||
empty,
|
||||
open,
|
||||
totalFree,
|
||||
owned: order.map(
|
||||
(id) => g.players[id].cities.filter((c) => cities.some((x) => x.name === c.name)).length
|
||||
),
|
||||
};
|
||||
});
|
||||
return { regions: groups('region'), islands: groups('island') };
|
||||
}
|
||||
function stateFeatures(g, seat, context) {
|
||||
const t = context || territories(g, seat),
|
||||
v = [];
|
||||
for (const [groups, max] of [
|
||||
[t.regions, 8],
|
||||
[t.islands, 4],
|
||||
])
|
||||
for (let i = 0; i < max; i++) {
|
||||
const x = groups[i];
|
||||
v.push(
|
||||
...(x
|
||||
? [x.size / 64, x.empty / 64, x.open / 64, x.totalFree / 128, ...x.owned.map((n) => n / 22)]
|
||||
: Array(4 + g.players.length).fill(0))
|
||||
);
|
||||
}
|
||||
v.push((g.map.crossIslandSurcharge || 0) / 100);
|
||||
return v;
|
||||
}
|
||||
function actionFeatures(g, seat, action, context) {
|
||||
const order = Array.from({ length: g.players.length }, (_, i) => (seat + i) % g.players.length),
|
||||
newOrder = orderAfterBuild(g, seat);
|
||||
if (action.name !== 'Build') return Array(4 + 3 * g.players.length).fill(0);
|
||||
const city = g.map.cities.find((c) => c.name === action.data.name),
|
||||
t = context || territories(g, seat),
|
||||
region = t.regions.find((x) => x.name === (city.region || 'main')),
|
||||
island = t.islands.find((x) => x.name === (city.island || 'main'));
|
||||
return [
|
||||
...order.map((id) => newOrder.indexOf(id) / Math.max(1, g.players.length - 1)),
|
||||
...region.owned.map((n) => n / 22),
|
||||
...island.owned.map((n) => n / 22),
|
||||
region.open / 64,
|
||||
island.open / 64,
|
||||
+(island.owned[0] === 0),
|
||||
g.map.connections.filter((e) => e.nodes.includes(city.name)).length / 8,
|
||||
];
|
||||
}
|
||||
module.exports = { territories, stateFeatures, actionFeatures, orderAfterBuild };
|
||||
95
ai/strong/test.cjs
Normal file
95
ai/strong/test.cjs
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
const test = require('node:test'),
|
||||
assert = require('node:assert/strict'),
|
||||
c = require('../core.cjs'),
|
||||
f = require('./features.cjs'),
|
||||
spatial = require('./spatial.cjs'),
|
||||
eco = require('./economics.cjs');
|
||||
test('restock, acting players, holdings and cities are observable; sealed values are not', () => {
|
||||
const g = c.start('information', 'recharged', true),
|
||||
seat = g.currentPlayers[0],
|
||||
original = f.encode(g, seat);
|
||||
g.players[(seat + 1) % 3].bid = 999;
|
||||
g.currentBid = 999;
|
||||
g.powerPlantsDeck.reverse();
|
||||
g.seed = 'secret';
|
||||
assert.deepEqual(f.encode(g, seat), original);
|
||||
g.coalResupply[1][0]++;
|
||||
assert.notDeepEqual(f.observe(g, seat), original.state);
|
||||
const before = f.observe(g, seat);
|
||||
g.players[(seat + 1) % 3].cities.push({ name: g.map.cities[0].name, position: 0 });
|
||||
assert.notDeepEqual(f.observe(g, seat), before);
|
||||
assert.equal(original.state.length, 738);
|
||||
assert.ok(original.actions.every((a) => a.length === 96 && a.every(Number.isFinite)));
|
||||
});
|
||||
test('UK/Ireland tracks opponent presence and empty slots on both islands', () => {
|
||||
const g = c.E.setup(3, { map: 'UK & Ireland' }, 'islands'),
|
||||
gb = g.map.cities.find((c) => c.island === 'gb'),
|
||||
ie = g.map.cities.find((c) => c.island === 'ie');
|
||||
const initial = spatial.territories(g, 0);
|
||||
g.players[1].cities.push({ name: gb.name, position: 0 });
|
||||
let t = spatial.territories(g, 0);
|
||||
assert.equal(t.islands.find((x) => x.name === 'gb').owned[1], 1);
|
||||
assert.equal(t.islands.find((x) => x.name === 'ie').owned[1], 0);
|
||||
g.players[1].cities.push({ name: ie.name, position: 0 });
|
||||
t = spatial.territories(g, 0);
|
||||
assert.ok(t.islands.every((x) => x.owned[1] === 1));
|
||||
for (const island of t.islands) {
|
||||
const old = initial.islands.find((x) => x.name === island.name);
|
||||
assert.equal(island.empty, old.empty - 1);
|
||||
assert.equal(island.open, old.open - 1);
|
||||
}
|
||||
});
|
||||
test('projected order uses cities and highest-plant tie break', () => {
|
||||
const g = c.start('order');
|
||||
g.players[0].cities = [{ name: 'a' }];
|
||||
g.players[1].cities = [{ name: 'b' }, { name: 'c' }];
|
||||
g.players[0].powerPlants = [{ number: 20 }];
|
||||
g.players[1].powerPlants = [{ number: 10 }];
|
||||
assert.equal(spatial.orderAfterBuild(g, 0)[0], 0);
|
||||
});
|
||||
test('economic production consumes a feasible fuel combination and completes games', () => {
|
||||
for (let i = 0; i < 12; i++) {
|
||||
const g = c.start('strong-legal-' + i, i % 2 ? 'recharged' : 'original', i % 4 < 2),
|
||||
rng = c.seedrandom('tie' + i);
|
||||
let steps = 0;
|
||||
while (!c.E.ended(g) && steps++ < 1800) {
|
||||
const p = g.currentPlayers[0],
|
||||
x = eco.choose(g, p, rng);
|
||||
assert.ok(Number.isFinite(eco.scores(g, p, [x.action])[0]));
|
||||
c.E.move(g, x.action, p);
|
||||
}
|
||||
assert.ok(c.E.ended(g));
|
||||
}
|
||||
});
|
||||
|
||||
test('search choices do not change with hidden deck order or sealed bid amounts', () => {
|
||||
const search = require('./search.cjs'),
|
||||
g = c.start('search-info', 'original', true);
|
||||
let p = g.currentPlayers[0];
|
||||
c.E.move(g, c.candidates(g, p)[0], p);
|
||||
p = g.currentPlayers[0];
|
||||
const first = search.choose(g, p, { samples: 2, candidates: 3, seed: 'same-belief', maxSteps: 700 });
|
||||
g.powerPlantsDeck.reverse();
|
||||
g.players.forEach((x, i) => {
|
||||
if (i !== p) x.bid = 123;
|
||||
});
|
||||
g.currentBid = 456;
|
||||
g.hiddenLog = [{ secret: 'not observable' }];
|
||||
const second = search.choose(g, p, { samples: 2, candidates: 3, seed: 'same-belief', maxSteps: 700 });
|
||||
assert.equal(first.index, second.index);
|
||||
assert.deepEqual(first.values, second.values);
|
||||
});
|
||||
|
||||
test('public topology preserves map edges, ownership and island crossing rule', () => {
|
||||
const graph = require('./public-graph.cjs');
|
||||
for (const map of ['Germany', 'UK & Ireland', 'USA', 'France']) {
|
||||
const g = c.E.setup(3, { map }, 'graph');
|
||||
const x = graph.encode(g, 0);
|
||||
assert.equal(x.nodes.length, g.map.cities.length);
|
||||
assert.ok(x.edges.every((e) => e.a >= 0 && e.b >= 0 && e.cost >= 0));
|
||||
g.seed = 'private';
|
||||
g.powerPlantsDeck.reverse();
|
||||
g.players[1].bid = 999;
|
||||
assert.deepEqual(graph.encode(g, 0), x);
|
||||
}
|
||||
});
|
||||
74
ai/strong/tournament.cjs
Normal file
74
ai/strong/tournament.cjs
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
const c = require('../core.cjs'),
|
||||
eco = require('./economics.cjs'),
|
||||
search = require('./search.cjs');
|
||||
const seeds = +(process.env.SEEDS || 20),
|
||||
candidate = process.argv[2] || 'economic',
|
||||
opponent = process.argv[3] || 'heuristic';
|
||||
function play(g, p, type, rng) {
|
||||
if (type === 'search') {
|
||||
const legal = c.candidates(g, p),
|
||||
strategic = legal.length > 1 && legal.some((a) => ['ChoosePowerPlant', 'Bid', 'Build'].includes(a.name));
|
||||
return c.E.move(
|
||||
g,
|
||||
strategic
|
||||
? search.choose(g, p, {
|
||||
samples: 4,
|
||||
candidates: 5,
|
||||
seed: 'search-' + g.round + '-' + p + '-' + Math.floor(rng() * 1e9),
|
||||
}).action
|
||||
: eco.choose(g, p, rng).action,
|
||||
p
|
||||
);
|
||||
}
|
||||
if (type === 'legacy') {
|
||||
const old = Math.random;
|
||||
Math.random = rng;
|
||||
try {
|
||||
return c.E.moveAI(g, p);
|
||||
} finally {
|
||||
Math.random = old;
|
||||
}
|
||||
}
|
||||
return c.E.move(g, type === 'heuristic' ? c.heuristic(g, p, rng).action : eco.choose(g, p, rng, type).action, p);
|
||||
}
|
||||
let results = [];
|
||||
for (const variant of ['original', 'recharged'])
|
||||
for (const sealed of [false, true]) {
|
||||
for (let seed = +(process.env.SEED_START || 0); seed < +(process.env.SEED_START || 0) + seeds; seed++)
|
||||
for (let seat = 0; seat < 3; seat++) {
|
||||
let g = c.start('strong-dev-' + seed, variant, sealed),
|
||||
rng = c.seedrandom('strong-' + seed),
|
||||
steps = 0;
|
||||
while (!c.E.ended(g) && steps++ < 1600) {
|
||||
const p = g.currentPlayers[0];
|
||||
g = play(g, p, p === seat ? candidate : opponent, rng);
|
||||
}
|
||||
results.push({
|
||||
variant,
|
||||
sealed,
|
||||
seed,
|
||||
seat,
|
||||
steps,
|
||||
truncated: !c.E.ended(g),
|
||||
win: c.E.ended(g) ? c.outcome(g)[seat] : 0,
|
||||
});
|
||||
}
|
||||
const rows = results.filter((r) => r.variant === variant && r.sealed === sealed);
|
||||
console.error(
|
||||
JSON.stringify({
|
||||
variant,
|
||||
sealed,
|
||||
win: rows.reduce((s, r) => s + r.win, 0) / rows.length,
|
||||
truncated: rows.filter((r) => r.truncated).length,
|
||||
})
|
||||
);
|
||||
}
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
candidate,
|
||||
opponent,
|
||||
seeds,
|
||||
win: results.reduce((s, r) => s + r.win, 0) / results.length,
|
||||
results,
|
||||
})
|
||||
);
|
||||
287
ai/strong/train.py
Normal file
287
ai/strong/train.py
Normal file
|
|
@ -0,0 +1,287 @@
|
|||
"""Complete-episode PPO against a mixture of economic bots and self-play.
|
||||
All optimization runs on HF Jobs. No unfinished episodes cross policy updates.
|
||||
"""
|
||||
|
||||
import os, sys, json, time, random, copy
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
import numpy as np
|
||||
import torch
|
||||
from torch.distributions import Categorical
|
||||
from model import Policy, tensors
|
||||
from pool import EnginePool
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
seed = int(os.getenv("TRAIN_SEED", "101"))
|
||||
random.seed(seed)
|
||||
np.random.seed(seed)
|
||||
torch.manual_seed(seed)
|
||||
torch.set_num_threads(2)
|
||||
device = "cuda"
|
||||
assert torch.cuda.is_available(), "Training must run on a GPU HF Job"
|
||||
net = Policy().to(device)
|
||||
optimizer = torch.optim.AdamW(
|
||||
net.parameters(), lr=float(os.getenv("LR", "0.00015")), weight_decay=1e-5
|
||||
)
|
||||
run = os.getenv("RUN_NAME", "strong-smoke")
|
||||
out = Path("ai/runs") / run
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
workers = int(os.getenv("WORKERS", "4"))
|
||||
nenv = int(os.getenv("ENVS", "64"))
|
||||
batchsize = int(os.getenv("BATCH_SIZE", "512"))
|
||||
updates = int(os.getenv("UPDATES", "10"))
|
||||
rollout = EnginePool(
|
||||
workers, seed=f"strong-train-{seed}", script="ai/strong/bridge.cjs"
|
||||
)
|
||||
snapshots = [copy.deepcopy(net).eval()]
|
||||
metrics = []
|
||||
best = -1
|
||||
|
||||
|
||||
def save(name, export=False):
|
||||
torch.save(
|
||||
{
|
||||
"state_dim": 738,
|
||||
"action_dim": 96,
|
||||
"schema": 3,
|
||||
"state_dict": {k: v.detach().cpu() for k, v in net.state_dict().items()},
|
||||
},
|
||||
out / (name + ".pt"),
|
||||
)
|
||||
if export:
|
||||
clone = copy.deepcopy(net).cpu().eval()
|
||||
torch.onnx.export(
|
||||
clone,
|
||||
(
|
||||
torch.zeros(1, 738),
|
||||
torch.zeros(1, 8, 96),
|
||||
torch.ones(1, 8, dtype=torch.bool),
|
||||
),
|
||||
str(out / (name + ".onnx")),
|
||||
input_names=["state", "actions", "mask"],
|
||||
output_names=["logits", "value"],
|
||||
dynamic_axes={
|
||||
"state": {0: "batch"},
|
||||
"actions": {0: "batch", 1: "candidates"},
|
||||
"mask": {0: "batch", 1: "candidates"},
|
||||
"logits": {0: "batch", 1: "candidates"},
|
||||
"value": {0: "batch"},
|
||||
},
|
||||
opset_version=17,
|
||||
dynamo=False,
|
||||
)
|
||||
(out / "metrics.json").write_text(json.dumps(metrics, indent=2))
|
||||
(out / "schema.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"version": 3,
|
||||
"state_dim": 738,
|
||||
"action_dim": 96,
|
||||
"players": 3,
|
||||
"map": "Germany",
|
||||
"information": "all money public, sealed bids/deck/queued plans excluded",
|
||||
"run": run,
|
||||
"seed": seed,
|
||||
}
|
||||
)
|
||||
)
|
||||
HfApi().upload_folder(
|
||||
repo_id=os.environ["HF_MODEL_REPO"],
|
||||
folder_path=str(out),
|
||||
path_in_repo="runs/" + run,
|
||||
ignore_patterns=["*.tmp"],
|
||||
)
|
||||
|
||||
|
||||
def evaluate(update):
|
||||
pool = EnginePool(4, seed="strong-development-v1", script="ai/strong/bridge.cjs")
|
||||
result = {}
|
||||
try:
|
||||
for mode in ["economic", "heuristic", "rush", "legacy"]:
|
||||
current = pool.call({"op": "reset", "n": 96, "mode": mode})["observations"]
|
||||
ends = []
|
||||
while any(x is not None for x in current):
|
||||
live = [i for i, x in enumerate(current) if x is not None]
|
||||
rows = [current[i] for i in live]
|
||||
with torch.no_grad():
|
||||
logits, _ = net(*tensors(rows, device))
|
||||
chosen = logits.argmax(-1).cpu().tolist()
|
||||
actions = [None] * len(current)
|
||||
for i, a in zip(live, chosen):
|
||||
actions[i] = a
|
||||
r = pool.call({"op": "step", "actions": actions})
|
||||
current = r["observations"]
|
||||
ends.extend(r["ended"])
|
||||
wins = [
|
||||
sum(
|
||||
e["value"][i]
|
||||
for i, role in enumerate(e["roles"])
|
||||
if role == "learner"
|
||||
)
|
||||
for e in ends
|
||||
]
|
||||
result[mode] = {
|
||||
"win": float(np.mean(wins)),
|
||||
"truncated": sum(e["truncated"] for e in ends),
|
||||
"games": len(ends),
|
||||
}
|
||||
finally:
|
||||
pool.close()
|
||||
print(
|
||||
json.dumps(
|
||||
{"stage": "evaluation", "run": run, "update": update, "results": result}
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
try:
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"run": run,
|
||||
"parameters": sum(p.numel() for p in net.parameters()),
|
||||
"workers": workers,
|
||||
"envs": nenv,
|
||||
"gpu": torch.cuda.get_device_name(),
|
||||
}
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
for update in range(updates):
|
||||
start = time.perf_counter()
|
||||
current = rollout.call({"op": "reset", "n": nenv, "mode": "mixed"})[
|
||||
"observations"
|
||||
]
|
||||
pending = [[] for _ in range(nenv)]
|
||||
batch = []
|
||||
endings = []
|
||||
decisions = 0
|
||||
net.eval()
|
||||
while any(x is not None for x in current):
|
||||
live = [i for i, x in enumerate(current) if x is not None]
|
||||
rows = [current[i] for i in live]
|
||||
choice = [0] * len(rows)
|
||||
logps = [0.0] * len(rows)
|
||||
values = [[0.0, 0.0, 0.0]] * len(rows)
|
||||
roles = {r["roles"][r["seat"]] for r in rows}
|
||||
for role in roles:
|
||||
indices = [
|
||||
j for j, r in enumerate(rows) if r["roles"][r["seat"]] == role
|
||||
]
|
||||
actor = (
|
||||
net
|
||||
if role == "learner"
|
||||
else snapshots[int(role[-1]) % len(snapshots)]
|
||||
)
|
||||
with torch.no_grad():
|
||||
logits, vs = actor(*tensors([rows[j] for j in indices], device))
|
||||
distribution = Categorical(logits=logits)
|
||||
selected = (
|
||||
distribution.sample()
|
||||
if role == "learner"
|
||||
else logits.argmax(-1)
|
||||
)
|
||||
logs = distribution.log_prob(selected).cpu().tolist()
|
||||
vals = vs.cpu().tolist()
|
||||
selected = selected.cpu().tolist()
|
||||
for j, a, lp, v in zip(indices, selected, logs, vals):
|
||||
choice[j] = a
|
||||
logps[j] = lp
|
||||
values[j] = v
|
||||
actions = [None] * nenv
|
||||
for j, i in enumerate(live):
|
||||
actions[i] = choice[j]
|
||||
if current[i]["roles"][current[i]["seat"]] != "learner":
|
||||
continue
|
||||
pending[i].append(
|
||||
{
|
||||
**current[i],
|
||||
"choice": choice[j],
|
||||
"oldlogp": logps[j],
|
||||
"oldvalue": values[j][0],
|
||||
}
|
||||
)
|
||||
decisions += 1
|
||||
reply = rollout.call({"op": "step", "actions": actions})
|
||||
current = reply["observations"]
|
||||
for end in reply["ended"]:
|
||||
endings.append(end)
|
||||
if not end["truncated"]:
|
||||
for r in pending[end["env"]]:
|
||||
r["value"] = [
|
||||
end["value"][(r["seat"] + j) % 3] for j in range(3)
|
||||
]
|
||||
r["advantage"] = r["value"][0] - r["oldvalue"]
|
||||
batch.append(r)
|
||||
pending[end["env"]] = []
|
||||
rollout_seconds = time.perf_counter() - start
|
||||
if not batch:
|
||||
raise RuntimeError("No completed training episodes")
|
||||
advantages = np.array([r["advantage"] for r in batch])
|
||||
mean = advantages.mean()
|
||||
std = advantages.std() + 1e-6
|
||||
losses = []
|
||||
net.train()
|
||||
for epoch in range(3):
|
||||
random.shuffle(batch)
|
||||
for k in range(0, len(batch), batchsize):
|
||||
rows = batch[k : k + batchsize]
|
||||
x = tensors(rows, device)
|
||||
logits, value = net(*x)
|
||||
dist = Categorical(logits=logits)
|
||||
act = torch.tensor([r["choice"] for r in rows], device=device)
|
||||
old = torch.tensor([r["oldlogp"] for r in rows], device=device)
|
||||
adv = torch.tensor(
|
||||
[(r["advantage"] - mean) / std for r in rows],
|
||||
device=device,
|
||||
dtype=torch.float32,
|
||||
)
|
||||
target = torch.tensor([r["value"] for r in rows], device=device)
|
||||
ratio = (dist.log_prob(act) - old).exp()
|
||||
pg = -torch.minimum(ratio * adv, ratio.clamp(0.8, 1.2) * adv).mean()
|
||||
anchor = (x[1][:, :, 74] * 2).masked_fill(~x[2], -1e9).softmax(-1)
|
||||
kl = torch.nn.functional.kl_div(
|
||||
logits.log_softmax(-1), anchor, reduction="batchmean"
|
||||
)
|
||||
loss = (
|
||||
pg
|
||||
+ 0.5 * ((value - target) ** 2).mean()
|
||||
- float(os.getenv("ENTROPY", ".01")) * dist.entropy().mean()
|
||||
+ float(os.getenv("ANCHOR", ".01")) * kl
|
||||
)
|
||||
optimizer.zero_grad()
|
||||
loss.backward()
|
||||
torch.nn.utils.clip_grad_norm_(net.parameters(), 1)
|
||||
optimizer.step()
|
||||
losses.append(float(loss.detach()))
|
||||
metric = {
|
||||
"stage": "train",
|
||||
"run": run,
|
||||
"update": update,
|
||||
"episodes": len(endings),
|
||||
"truncated": sum(x["truncated"] for x in endings),
|
||||
"samples": len(batch),
|
||||
"rollout_seconds": rollout_seconds,
|
||||
"seconds": time.perf_counter() - start,
|
||||
"loss": float(np.mean(losses)),
|
||||
}
|
||||
metrics.append(metric)
|
||||
print(json.dumps(metric), flush=True)
|
||||
if update % int(os.getenv("EVAL_EVERY", "10")) == 0 or update == updates - 1:
|
||||
net.eval()
|
||||
evaluation = evaluate(update)
|
||||
metrics.append({"stage": "evaluation", "update": update, **evaluation})
|
||||
score = np.mean(
|
||||
[evaluation[x]["win"] for x in ["economic", "heuristic", "rush"]]
|
||||
)
|
||||
if score > best:
|
||||
best = score
|
||||
snapshots.append(copy.deepcopy(net).eval())
|
||||
snapshots = snapshots[-3:]
|
||||
save("best", export=True)
|
||||
save("latest", export=True)
|
||||
finally:
|
||||
rollout.close()
|
||||
16
ai/strong/worker.cjs
Normal file
16
ai/strong/worker.cjs
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
const f = require('./features.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');
|
||||
const x = f.encode(g, p);
|
||||
console.log(JSON.stringify({ ...x, playerOrder: [p, (p + 1) % 3, (p + 2) % 3] }));
|
||||
} catch (e) {
|
||||
console.log(JSON.stringify({ error: e.message }));
|
||||
}
|
||||
}
|
||||
})();
|
||||
21
ai/test.cjs
21
ai/test.cjs
|
|
@ -79,3 +79,24 @@ test('Recharged replacement cities have distinct action features', () => {
|
|||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('fuel purchase teacher uses actual market price and buys required fuel', () => {
|
||||
let g = c.start('fuel-regression'),
|
||||
rng = c.seedrandom('fuel');
|
||||
while (g.phase !== c.E.Phase.Resources) {
|
||||
const p = g.currentPlayers[0];
|
||||
g = c.E.move(g, c.heuristic(g, p, rng).action, p);
|
||||
}
|
||||
const p = g.currentPlayers[0],
|
||||
candidate = c.candidates(g, p).find((a) => a.name === 'BuyResource');
|
||||
assert.ok(candidate, 'a fuel-burning plant must need resources');
|
||||
assert.equal(candidate.data.price, undefined, 'engine deliberately omits price');
|
||||
assert.equal(c.heuristic(g, p, rng).action.name, 'BuyResource');
|
||||
const before = g.players[p].money,
|
||||
price = c.resourcePrice(g, candidate.data.resource);
|
||||
assert.ok(Number.isFinite(price) && price > 0);
|
||||
assert.equal(c.actionFeatures(g, p, candidate)[10], price / 500);
|
||||
g = c.E.move(g, candidate, p);
|
||||
assert.equal(before - g.players[p].money, price);
|
||||
assert.equal(c.resourcePrice(g, 'uranium'), 14);
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue