Add search supervision, paired arenas and CPU-guided inference

This commit is contained in:
coyotte508 2026-09-30 16:31:52 +02:00
commit 822e1307d6
25 changed files with 835 additions and 24 deletions

1
.gitignore vendored
View file

@ -13,4 +13,5 @@ ai/.venv/
source-bundle/
ai/__pycache__/
ai/strong/__pycache__/
serving-bundle/

View file

@ -39,7 +39,11 @@ 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 = [{**request, "n": n} for n in self.sizes]
requests = []
offset = 0
for n in self.sizes:
requests.append({**request, "n": n, "offset": offset})
offset += n
else:
requests = []
offset = 0

View file

@ -24,6 +24,14 @@ PPO collects complete episodes against a mixture of fixed bots, self-play and fr
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 continue. 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.
## Evidence required before declaring strength
- Robust gains over the economic, corrected-heuristic, rush, and frozen neural opponents—not just the default bot.
@ -37,3 +45,9 @@ A separate rollout-search opponent uses the engine's public-information scenario
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.

View file

@ -0,0 +1,27 @@
"""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

View file

@ -0,0 +1,70 @@
"""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 numpy as np
p = argparse.ArgumentParser()
p.add_argument("model")
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)
args = p.parse_args()
worker = subprocess.Popen(
[
sys.executable,
str(Path(__file__).with_name("infer.py")),
args.model,
"--search-samples",
str(args.search_samples),
],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True,
bufsize=1,
)
latencies, inner = [], []
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"] == 3
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"])
finally:
worker.stdin.close()
worker.wait(timeout=10)
worker.stdout.close()
report = {
"positions": len(latencies),
"model_sha256": sha,
"all_moves_legal": True,
"search_samples": args.search_samples,
"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)),
}
Path(args.output).write_text(json.dumps(report, indent=2))
print(json.dumps(report))

View file

@ -15,6 +15,20 @@ function applyBot(e, p) {
} finally {
Math.random = old;
}
} else if (role === 'search') {
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
? require('./search.cjs').choose(e.g, p, {
samples: 4,
candidates: 5,
seed: 'arena-search-' + e.g.round + '-' + p + '-' + Math.floor(e.rng() * 1e9),
}).action
: eco.choose(e.g, p, e.rng).action,
p
);
} else
c.E.move(
e.g,
@ -38,8 +52,8 @@ function observation(e) {
delete x.moves;
return { ...x, episode: e.id, roles: e.roles, round: e.g.round };
}
function reset(mode = 'mixed') {
const id = sequence++,
function reset(mode = 'mixed', arenaSeed, arenaId) {
const id = arenaSeed === undefined ? sequence++ : arenaId,
seat = Math.floor(id / 4) % 3,
kind = Math.floor(c.seedrandom(seed + '-opponents-' + id)() * 8);
const opponent =
@ -50,11 +64,13 @@ function reset(mode = 'mixed') {
opponent === 'selfplay'
? ['learner', 'learner', 'learner']
: Array.from({ length: 3 }, (_, i) => (i === seat ? 'learner' : opponent));
const gameSeed = arenaSeed === undefined ? seed + '-' + id : arenaSeed + '-' + Math.floor(id / 12);
const e = {
id,
g: c.start(seed + '-' + id, id % 2 ? 'recharged' : 'original', id % 4 < 2),
gameSeed,
g: c.start(gameSeed, id % 2 ? 'recharged' : 'original', id % 4 < 2),
roles,
rng: c.seedrandom(seed + '-bot-' + id),
rng: c.seedrandom(arenaSeed === undefined ? seed + '-bot-' + id : gameSeed + '-bot'),
steps: 0,
};
advance(e);
@ -65,19 +81,35 @@ function reset(mode = 'mixed') {
try {
const q = JSON.parse(line),
ended = [];
if (q.op === 'reset') envs = Array.from({ length: q.n }, () => reset(q.mode));
if (q.op === 'reset')
envs = Array.from({ length: q.n }, (_, i) => reset(q.mode, q.arenaSeed, (q.offset || 0) + i));
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);
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
? require('./search.cjs').choose(e.g, seat, {
samples: choice.searchSamples,
candidates: 6,
extraCandidates: [index],
seed: 'arena-guided-' + e.id + '-' + e.steps,
}).action
: legal[index];
c.E.move(e.g, action, seat);
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) : [0, 0, 0],
steps: e.steps,

205
ai/strong/distill.py Normal file
View file

@ -0,0 +1,205 @@
"""HF GPU job: distill public-belief search, then measure actual playing strength."""
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 distillation_targets import policy_targets
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 = Policy().to(device)
train, validation = [], []
dataset_revisions = []
version = os.getenv("DATA_VERSION", "search-teacher-v1")
target_mode = os.getenv("TARGET_MODE", "hard")
assert target_mode in ["hard", "soft"]
for shard in range(int(os.getenv("SHARDS", "4"))):
path = hf_hub_download(
os.environ["HF_DATA_REPO"],
f"{version}/{version}-{shard}.jsonl.gz",
repo_type="dataset",
)
dataset_revisions.append({"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["truncated"]:
continue
# Keep whole games together, never split positions from one game.
target = validation if game["id"] % 5 == 0 else train
for row in game["rows"]:
row["state"] = np.asarray(row["state"], np.float32)
row["actions"] = np.asarray(row["actions"], np.float32)
target.append(row)
assert train and validation
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": 3,
"state_dim": 738,
"action_dim": 96,
"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, 738),
torch.zeros(1, 8, 96),
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,
)
def validate():
correct, disagreement_correct, disagreements, count = 0, 0, 0, 0
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):
correct += chosen == row["target"]
count += 1
if not row["teacherAgrees"]:
disagreements += 1
disagreement_correct += chosen == row["target"]
return {
"positions": 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"))
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)
loss = (ce * weights).sum() / weights.sum() + 0.2 * (
(value - returns) ** 2
).mean()
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 opponent in ["economic", "heuristic", "rush"]:
result = subprocess.run(
[
sys.executable,
"ai/strong/evaluate.py",
str(out / "latest.onnx"),
"--opponent",
opponent,
"--games",
"96",
"--workers",
"4",
"--seed",
"search-distill-development-v1",
"--output",
str(out / f"{opponent}.json"),
],
text=True,
capture_output=True,
check=True,
)
results[opponent] = json.loads(result.stdout)
metric["arena"] = results
score = np.mean([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": 3,
"players": 3,
"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)

View 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

View file

@ -7,23 +7,42 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import numpy as np
from infer import Model
from pool import EnginePool
from arena_statistics import win_summary
p = argparse.ArgumentParser()
p.add_argument("model")
p.add_argument(
"--opponent",
default="economic",
choices=["economic", "heuristic", "rush", "legacy"],
choices=["economic", "heuristic", "rush", "legacy", "search"],
)
p.add_argument("--opponent-model", help="Frozen ONNX policy in both opponent seats")
p.add_argument("--workers", type=int, default=4)
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)
args = p.parse_args()
if not 0 <= args.search_samples <= 64:
p.error("--search-samples must be 0..64")
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"
]
if args.games < 12 or args.games % 12:
p.error("--games must be a positive multiple of 12 for paired rules and seats")
opponent_model = Model(args.opponent_model) if args.opponent_model else None
pool = EnginePool(args.workers, seed=args.seed, script="ai/strong/bridge.cjs")
current = pool.call(
{
"op": "reset",
"n": args.games,
"mode": "snapshot0" if opponent_model else args.opponent,
"arenaSeed": args.seed,
}
)["observations"]
rows = []
latency = []
start = time.perf_counter()
@ -35,9 +54,15 @@ try:
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)
actor = model if x["roles"][x["seat"]] == "learner" else opponent_model
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}
if actor is model and args.search_samples
else a
)
r = pool.call({"op": "step", "actions": actions})
current = r["observations"]
for e in r["ended"]:
@ -56,7 +81,10 @@ finally:
report = {
"model": args.model,
"model_sha256": model.sha256,
"opponent": args.opponent,
"opponent": args.opponent_model or args.opponent,
"opponent_sha256": opponent_model.sha256 if opponent_model else None,
"paired_seats": True,
"candidate_search_samples": args.search_samples,
"seed": args.seed,
"games": len(rows),
"win_rate": float(np.mean([r["win"] for r in rows])),
@ -79,5 +107,16 @@ report = {
],
"results": rows,
}
report.update(win_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"}))

View file

@ -9,7 +9,22 @@
"strong-league-v2-b": "6abd146afbc85ba68235b28d",
"strong-league-v2-c": "6abd15cafbc85ba68235b347",
"strong-league-v2-d": "6abd15ca404719ba376134e5",
"search-reference-v1": "6abd1314404719ba376133b5"
"search-reference-v1": "6abd1314404719ba376133b5",
"search-teacher-v1-0": "6abd187efbc85ba68235b480",
"search-teacher-v1-1": "6abd187ffbc85ba68235b482",
"search-teacher-v1-2": "6abd187f404719ba376135cd",
"search-teacher-v1-3": "6abd1880404719ba376135cf",
"b20-search-screening": "6abd18bb404719ba376135d8",
"search-distillation-v1": "6abd1992404719ba376135ec",
"search-teacher-v2-0": "6abd1c1a404719ba3761362b",
"search-teacher-v2-1": "6abd1c1b404719ba3761362d",
"search-teacher-v2-2": "6abd1c1cfbc85ba68235b51d",
"search-teacher-v2-3": "6abd1c1dfbc85ba68235b51f",
"search-teacher-v2-4": "6abd1c1d404719ba3761362f",
"search-teacher-v2-5": "6abd1c1e404719ba37613631",
"search-teacher-v2-6": "6abd1c1f404719ba37613633",
"search-teacher-v2-7": "6abd1c20404719ba37613635",
"b20-guided-search-screening": "6abd1c21fbc85ba68235b521"
},
"cancelled_while_queued": [
"6abd128efbc85ba68235b1a6",
@ -18,5 +33,25 @@
"6abd146bfbc85ba68235b28f"
],
"heldout_final_seed_prefix": "strong-final-reserved-v1",
"final_seed_prefix_used": false
"final_seed_prefix_used": false,
"search_teacher_source": {
"archive": "strong-source-v4.tgz",
"commit": "76d8631d933163a9731319a59341e9e4251dfd2d"
},
"distillation_source": {
"archive": "strong-source-v5.tgz",
"commit": "ab52f6ec30783174b97882b24fe61063f8fbf116"
},
"expanded_teacher_source": {
"archive": "strong-source-v6.tgz",
"commit": "cc79acffc12ad4cc1daffbad20b024d2e1f4fe98"
},
"stopped_for_sustained_regression": [
"6abd15cafbc85ba68235b347",
"6abd15ca404719ba376134e5"
],
"all_phase_distillation_source": {
"archive": "strong-source-v7.tgz",
"commit": "0862207a0f62cb75edfd0e6ecbc472cdc190bcd0"
}
}

39
ai/strong/export.py Normal file
View file

@ -0,0 +1,39 @@
"""CPU-only checkpoint conversion; no gradient updates."""
import argparse
import json
from pathlib import Path
import torch
from model import Policy
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)
net = Policy(strategic_only=strategic_only).eval()
net.load_state_dict(checkpoint["state_dict"])
torch.onnx.export(
net,
(torch.zeros(1, 738), torch.zeros(1, 8, 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,
)
Path(args.output + ".json").write_text(
json.dumps(
{"source": args.checkpoint, "strategic_only": strategic_only, "schema": 3}
)
)

View file

@ -0,0 +1,59 @@
"""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}
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"]
# 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": 3, **counts}).encode(),
path_in_repo=f"{version}/shard-{shard}-metrics.json",
)

View file

@ -8,7 +8,10 @@ from infer import Model, Node
p = argparse.ArgumentParser()
p.add_argument("model")
p.add_argument("--search-samples", type=int, default=0)
args = p.parse_args()
if not 0 <= args.search_samples <= 64:
p.error("--search-samples must be 0..64")
model = Model(args.model)
node = Node("strong/worker.cjs")
try:
@ -20,10 +23,23 @@ try:
raise ValueError("Expected object")
q = obj
start = time.perf_counter()
r = node.call(q)
r = node.call({**q, "op": "rank"})
if "error" in r:
raise ValueError(r["error"])
index, values = model.predict(r["state"], r["actions"])
search = None
if args.search_samples:
search = node.call(
{
**q,
"op": "search",
"proposal": index,
"samples": args.search_samples,
}
)
if "error" in search:
raise ValueError(search["error"])
index = search["index"]
print(
json.dumps(
{
@ -34,6 +50,13 @@ try:
"valueStatus": "uncalibrated-training-opponents",
"playerOrder": r["playerOrder"],
"schema": 3,
"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),
}

View 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
'

View 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
'

View 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\")"
'

View 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
'

View 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
'

View 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\")"
'

View file

@ -4,8 +4,9 @@ from torch import nn
class Policy(nn.Module):
def __init__(self, sd=738, ad=96, width=384):
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),
@ -27,6 +28,11 @@ class Policy(nn.Module):
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)

View file

@ -0,0 +1,65 @@
// Generate public-belief search supervision; learning itself runs in HF Jobs.
const c = require('../core.cjs'),
eco = require('./economics.cjs'),
search = require('./search.cjs'),
features = require('./features.cjs');
const id = Number(process.argv[2] || 0),
seed = (process.env.DATA_VERSION || 'search-teacher-v1') + '-' + id,
g = c.start(seed, id % 2 ? 'recharged' : 'original', id % 4 < 2),
seat = Math.floor(id / 4) % 3,
rng = c.seedrandom(seed + '-choices'),
samples = Number(process.env.SEARCH_SAMPLES || 4),
rows = [];
let steps = 0;
while (!c.E.ended(g) && steps < 1600) {
const p = g.currentPlayers[0],
legal = c.candidates(g, p),
strategic = legal.length > 1 && legal.some((a) => ['ChoosePowerPlant', 'Bid', 'Build'].includes(a.name));
let action;
if (p === seat && strategic) {
const result = search.choose(g, p, { samples, candidates: 5, seed: seed + '-decision-' + steps });
action = result.action;
if (result.evaluations && !result.truncated) {
const x = features.encode(g, p);
rows.push({
state: x.state,
actions: x.actions,
target: result.index,
searchValues: Object.entries(result.values).map(([index, total]) => [Number(index), total / samples]),
teacherAgrees: result.index === x.teacher,
phase: g.phase,
round: g.round,
seat,
});
}
} else {
const opponent = ['economic', 'heuristic', 'rush'][Math.floor(id / 12) % 3];
action =
p !== seat && opponent === 'heuristic'
? c.heuristic(g, p, rng).action
: eco.choose(g, p, rng, p === seat ? 'economic' : opponent).action;
if (p === seat && legal.length > 1 && process.env.INCLUDE_ALL_PHASES === '1') {
const x = features.encode(g, p),
target = x.moves.findIndex((a) => JSON.stringify(a) === JSON.stringify(action));
if (target < 0) throw Error('Teacher selected an unrepresented action');
rows.push({
state: x.state,
actions: x.actions,
target,
searchValues: [],
teacherAgrees: true,
phase: g.phase,
round: g.round,
seat,
});
}
}
c.E.move(g, action, p);
steps++;
}
const truncated = !c.E.ended(g),
value = truncated ? [0, 0, 0] : c.outcome(g),
relativeValue = Array.from({ length: 3 }, (_, i) => value[(seat + i) % 3]);
console.log(
JSON.stringify({ id, seed, steps, truncated, value, rows: rows.map((r) => ({ ...r, value: relativeValue })) })
);

View file

@ -15,9 +15,15 @@ function shortlist(g, seat, limit = 5) {
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 } = {}) {
function choose(
g,
seat,
{ samples = 6, candidates = 5, seed = 'public-search', maxSteps = 1200, extraCandidates = [] } = {}
) {
const actions = c.candidates(g, seat),
options = shortlist(g, seat, candidates);
options = [...new Set([...shortlist(g, seat, candidates), ...extraCandidates])];
if (options.some((i) => !Number.isInteger(i) || i < 0 || i >= actions.length))
throw Error('Invalid search proposal');
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,

View file

@ -0,0 +1,20 @@
const c = require('../core.cjs'),
eco = require('./economics.cjs');
for (let game = 0; game < 4; game++) {
const g = c.start('strong-serving-' + game, game % 2 ? 'recharged' : 'original', game < 2),
rng = c.seedrandom('strong-serving-ties-' + game);
let step = 0;
while (!c.E.ended(g) && step < 1600) {
const player = g.currentPlayers[0];
if (step % 4 === 0)
console.log(
JSON.stringify({
request: { state: g, player, requestId: `${game}-${step}`, revision: step },
legal: c.candidates(g, player),
})
);
c.E.move(g, eco.choose(g, player, rng).action, player);
step++;
}
if (!c.E.ended(g)) throw Error('Fixture game did not finish');
}

View file

@ -68,14 +68,22 @@ test('search choices do not change with hidden deck order or sealed bid amounts'
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 });
const options = {
samples: 2,
candidates: 3,
seed: 'same-belief',
maxSteps: 700,
extraCandidates: [c.candidates(g, p).length - 1],
};
const first = search.choose(g, p, options);
g.powerPlantsDeck.reverse();
g.seed = 'different-private-seed';
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 });
const second = search.choose(g, p, options);
assert.equal(first.index, second.index);
assert.deepEqual(first.values, second.values);
});

View file

@ -8,6 +8,24 @@ const f = require('./features.cjs'),
p = q.player;
if (!Number.isInteger(p) || !g.currentPlayers.includes(p)) throw Error('Player cannot act');
const x = f.encode(g, p);
if (q.op === 'search') {
if (!Number.isInteger(q.proposal) || q.proposal < 0 || q.proposal >= x.moves.length)
throw Error('Invalid search proposal');
if (!Number.isInteger(q.samples) || q.samples < 1 || q.samples > 64)
throw Error('Search samples must be 1..64');
const strategic =
x.moves.length > 1 && x.moves.some((a) => ['ChoosePowerPlant', 'Bid', 'Build'].includes(a.name));
const result = strategic
? require('./search.cjs').choose(g, p, {
samples: q.samples,
candidates: 6,
extraCandidates: [q.proposal],
seed: 'serving-' + (q.requestId || 'public'),
})
: { index: q.proposal, action: x.moves[q.proposal], evaluations: 0 };
console.log(JSON.stringify(result));
continue;
}
console.log(JSON.stringify({ ...x, playerOrder: [p, (p + 1) % 3, (p + 2) % 3] }));
} catch (e) {
console.log(JSON.stringify({ error: e.message }));