Extend multiplayer evaluation, distillation and CPU serving with independent gates
This commit is contained in:
parent
f318df73ef
commit
4110d727eb
16 changed files with 656 additions and 78 deletions
|
|
@ -14,6 +14,10 @@ command = [
|
|||
sys.executable,
|
||||
"ai/strong/evaluate.py",
|
||||
model,
|
||||
"--players",
|
||||
os.getenv("PLAYER_COUNT", "3"),
|
||||
"--deal-offset",
|
||||
os.getenv("DEAL_OFFSET", "0"),
|
||||
"--opponent",
|
||||
os.environ.get("OPPONENT", "search_geo"),
|
||||
"--games",
|
||||
|
|
|
|||
|
|
@ -39,3 +39,36 @@ def search_summary(rows):
|
|||
for key in target:
|
||||
target[key] += stats[key]
|
||||
return {"search_rollouts_reported": True, "search_stats": totals}
|
||||
|
||||
|
||||
def validate_pairs(rows, players):
|
||||
"""Reject missing seats/rules and malformed outcomes, including in old reports."""
|
||||
if players not in range(2, 7) or not rows:
|
||||
raise ValueError("Expected nonempty 2–6 player arena")
|
||||
expected = {
|
||||
(seat, variant, sealed)
|
||||
for seat in range(players)
|
||||
for variant in ["original", "recharged"]
|
||||
for sealed in [False, True]
|
||||
}
|
||||
deals = {}
|
||||
for row in rows:
|
||||
if row.get("playerCount", players) != players:
|
||||
raise ValueError("Mixed player counts")
|
||||
key = (row["seat"], row["variant"], row["sealed"])
|
||||
seen = deals.setdefault(row["gameSeed"], set())
|
||||
if key in seen or key not in expected:
|
||||
raise ValueError("Duplicate or invalid paired match")
|
||||
seen.add(key)
|
||||
if len(row["value"]) != players or len(row["roles"]) != players:
|
||||
raise ValueError("Wrong terminal vector or role count")
|
||||
if row["roles"].count("learner") != 1 or row["roles"][row["seat"]] != "learner":
|
||||
raise ValueError("Wrong candidate seat")
|
||||
if any(not np.isfinite(v) or v < 0 or v > 1 for v in row["value"]):
|
||||
raise ValueError("Invalid terminal credits")
|
||||
if not row["truncated"] and not np.isclose(sum(row["value"]), 1):
|
||||
raise ValueError("Terminal credits must sum to one")
|
||||
if row["win"] != row["value"][row["seat"]]:
|
||||
raise ValueError("Candidate win differs from terminal credit")
|
||||
if any(seen != expected for seen in deals.values()):
|
||||
raise ValueError("Incomplete paired deal")
|
||||
|
|
|
|||
|
|
@ -40,6 +40,7 @@ search_latencies = []
|
|||
search_evaluations = 0
|
||||
search_truncations = 0
|
||||
by_phase = {}
|
||||
by_count = {}
|
||||
sha = None
|
||||
try:
|
||||
with open(args.fixtures) as source:
|
||||
|
|
@ -57,7 +58,13 @@ try:
|
|||
assert result["move"] in fixture["legal"], result
|
||||
assert result["requestId"] == request["requestId"]
|
||||
assert result["revision"] == request["revision"]
|
||||
assert result["schema"] == 3
|
||||
assert result["schema"] in [3, 4]
|
||||
n = len(request["state"]["players"])
|
||||
assert len(result["winProbabilities"]) == n
|
||||
assert result["playerOrder"] == [
|
||||
(request["player"] + j) % n for j in range(n)
|
||||
]
|
||||
by_count.setdefault(str(n), []).append(latencies[-1])
|
||||
assert result["playerOrder"][0] == request["player"]
|
||||
assert abs(sum(result["winProbabilities"]) - 1) < 1e-5
|
||||
assert sha is None or sha == result["modelSha256"]
|
||||
|
|
@ -90,6 +97,10 @@ report = {
|
|||
"processor_model": processor_model,
|
||||
"python_version": platform.python_version(),
|
||||
"positions": len(latencies),
|
||||
"by_player_count": {
|
||||
n: {"positions": len(xs), "p95_ms": float(np.percentile(xs, 95))}
|
||||
for n, xs in by_count.items()
|
||||
},
|
||||
"model_sha256": sha,
|
||||
"all_moves_legal": True,
|
||||
"search_samples": args.search_samples,
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
from arena_statistics import win_summary, search_summary
|
||||
from arena_statistics import win_summary, search_summary, validate_pairs
|
||||
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("reports", nargs="+")
|
||||
|
|
@ -23,7 +23,8 @@ keys = [
|
|||
]
|
||||
for report in reports:
|
||||
report.setdefault("candidate_search_scope", "all")
|
||||
keys.append("candidate_search_scope")
|
||||
report.setdefault("player_count", 3)
|
||||
keys.extend(["candidate_search_scope", "player_count"])
|
||||
config = {k: reports[0][k] for k in keys}
|
||||
rows = []
|
||||
seen = set()
|
||||
|
|
@ -35,8 +36,7 @@ for report in reports:
|
|||
assert key not in seen, f"Duplicate match: {key}"
|
||||
seen.add(key)
|
||||
rows.append(row)
|
||||
for deal in {r["gameSeed"] for r in rows}:
|
||||
assert sum(r["gameSeed"] == deal for r in rows) == 12, "Incomplete paired deal"
|
||||
validate_pairs(rows, config["player_count"])
|
||||
result = {
|
||||
**config,
|
||||
"sources": a.reports,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
"""HF GPU job: distill public-belief search, then measure actual playing strength."""
|
||||
|
||||
from collections import Counter
|
||||
import copy
|
||||
import gzip
|
||||
import json
|
||||
|
|
@ -14,9 +15,19 @@ import torch
|
|||
from huggingface_hub import HfApi, hf_hub_download
|
||||
|
||||
from model import Policy, tensors
|
||||
from model_v4 import MultiplayerPolicy
|
||||
from teacher_contract import validate_game, validation_seeds
|
||||
from distillation_targets import policy_targets
|
||||
from feature_contract import FEATURE_REVISION, embed_revision
|
||||
|
||||
multiplayer = os.getenv("ARCHITECTURE") == "multiplayer"
|
||||
if multiplayer:
|
||||
FEATURE_REVISION = "4.0-multiplayer"
|
||||
if not os.getenv("DATA_REVISION"):
|
||||
raise ValueError("Pin DATA_REVISION for the multiplayer teacher dataset")
|
||||
state_dim, action_dim = (1149, 98) if multiplayer else (738, 96)
|
||||
player_counts = [2, 3, 4, 5, 6] if multiplayer else [3]
|
||||
|
||||
assert torch.cuda.is_available(), "Training must run on a GPU HF Job"
|
||||
torch.set_num_threads(2)
|
||||
seed = int(os.getenv("TRAIN_SEED", "310"))
|
||||
|
|
@ -27,9 +38,11 @@ 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)
|
||||
net = (MultiplayerPolicy() if multiplayer else Policy()).to(device)
|
||||
train, validation = [], []
|
||||
dataset_revisions = []
|
||||
seen_games = set()
|
||||
complete_games = []
|
||||
version = os.getenv("DATA_VERSION", "search-teacher-v1")
|
||||
target_mode = os.getenv("TARGET_MODE", "hard")
|
||||
assert target_mode in ["hard", "soft"]
|
||||
|
|
@ -38,6 +51,7 @@ for shard in range(int(os.getenv("SHARDS", "4"))):
|
|||
os.environ["HF_DATA_REPO"],
|
||||
f"{version}/{version}-{shard}.jsonl.gz",
|
||||
repo_type="dataset",
|
||||
revision=os.getenv("DATA_REVISION"),
|
||||
)
|
||||
dataset_revisions.append({"shard": shard, "revision": Path(path).parents[1].name})
|
||||
with gzip.open(path, "rt") as source:
|
||||
|
|
@ -47,15 +61,45 @@ for shard in range(int(os.getenv("SHARDS", "4"))):
|
|||
raise ValueError(
|
||||
"Dataset uses a different feature revision; use its archived encoder or regenerate"
|
||||
)
|
||||
if multiplayer:
|
||||
validate_game(game)
|
||||
if game["seed"] in seen_games:
|
||||
raise ValueError("Duplicate teacher game")
|
||||
seen_games.add(game["seed"])
|
||||
if game["truncated"]:
|
||||
continue
|
||||
# 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["player_count"] = game.get("playerCount", 3)
|
||||
row["variant"] = game.get("variant")
|
||||
row["sealed"] = game.get("sealed")
|
||||
row["state"] = np.asarray(row["state"], np.float32)
|
||||
row["actions"] = np.asarray(row["actions"], np.float32)
|
||||
target.append(row)
|
||||
complete_games.append(game)
|
||||
held_out = (
|
||||
validation_seeds(complete_games)
|
||||
if multiplayer
|
||||
else {g["seed"] for g in complete_games if g["id"] % 5 == 0}
|
||||
)
|
||||
for game in complete_games:
|
||||
(validation if game["seed"] in held_out else train).extend(game["rows"])
|
||||
assert train and validation
|
||||
count_sizes = Counter(r["player_count"] for r in train)
|
||||
validation_sizes = Counter(r["player_count"] for r in validation)
|
||||
if multiplayer and (
|
||||
set(count_sizes) != set(player_counts)
|
||||
or set(validation_sizes) != set(player_counts)
|
||||
):
|
||||
raise ValueError("Every player count must appear in training and validation")
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"stage": "dataset_loaded",
|
||||
"train_counts": dict(count_sizes),
|
||||
"validation_counts": dict(validation_sizes),
|
||||
}
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
optimizer = torch.optim.AdamW(
|
||||
net.parameters(), lr=float(os.getenv("LR", ".0003")), weight_decay=1e-4
|
||||
)
|
||||
|
|
@ -67,10 +111,11 @@ batchsize = int(os.getenv("BATCH_SIZE", "256"))
|
|||
def export(name):
|
||||
torch.save(
|
||||
{
|
||||
"schema": 3,
|
||||
"schema": 4 if multiplayer else 3,
|
||||
"architecture": "multiplayer" if multiplayer else "policy",
|
||||
"feature_revision": FEATURE_REVISION,
|
||||
"state_dim": 738,
|
||||
"action_dim": 96,
|
||||
"state_dim": state_dim,
|
||||
"action_dim": action_dim,
|
||||
"state_dict": {k: v.detach().cpu() for k, v in net.state_dict().items()},
|
||||
},
|
||||
out / f"{name}.pt",
|
||||
|
|
@ -79,8 +124,8 @@ def export(name):
|
|||
torch.onnx.export(
|
||||
clone,
|
||||
(
|
||||
torch.zeros(1, 738),
|
||||
torch.zeros(1, 8, 96),
|
||||
torch.zeros(1, state_dim),
|
||||
torch.zeros(1, 8, action_dim),
|
||||
torch.ones(1, 8, dtype=torch.bool),
|
||||
),
|
||||
str(out / f"{name}.onnx"),
|
||||
|
|
@ -96,16 +141,26 @@ def export(name):
|
|||
opset_version=17,
|
||||
dynamo=False,
|
||||
)
|
||||
embed_revision(out / f"{name}.onnx")
|
||||
embed_revision(out / f"{name}.onnx", FEATURE_REVISION)
|
||||
|
||||
|
||||
def validate():
|
||||
correct, disagreement_correct, disagreements, count = 0, 0, 0, 0
|
||||
by_count = {
|
||||
n: {"positions": 0, "correct": 0, "disagreements": 0, "disagreement_correct": 0}
|
||||
for n in player_counts
|
||||
}
|
||||
with torch.no_grad():
|
||||
for k in range(0, len(validation), batchsize):
|
||||
rows = validation[k : k + batchsize]
|
||||
predicted = net(*tensors(rows, device))[0].argmax(-1).cpu().tolist()
|
||||
for row, chosen in zip(rows, predicted):
|
||||
group = by_count[row["player_count"]]
|
||||
group["positions"] += 1
|
||||
group["correct"] += chosen == row["target"]
|
||||
if not row["teacherAgrees"]:
|
||||
group["disagreements"] += 1
|
||||
group["disagreement_correct"] += chosen == row["target"]
|
||||
correct += chosen == row["target"]
|
||||
count += 1
|
||||
if not row["teacherAgrees"]:
|
||||
|
|
@ -113,6 +168,7 @@ def validate():
|
|||
disagreement_correct += chosen == row["target"]
|
||||
return {
|
||||
"positions": count,
|
||||
"by_player_count": by_count,
|
||||
"accuracy": correct / count,
|
||||
"search_disagreements": disagreements,
|
||||
"disagreement_accuracy": disagreement_correct / max(1, disagreements),
|
||||
|
|
@ -132,18 +188,38 @@ for epoch in range(int(os.getenv("EPOCHS", "30")) + 1):
|
|||
).to(device)
|
||||
weights = torch.tensor(
|
||||
[
|
||||
1.0
|
||||
if r["teacherAgrees"]
|
||||
else float(os.getenv("DISAGREEMENT_WEIGHT", "3"))
|
||||
(
|
||||
1.0
|
||||
if r["teacherAgrees"]
|
||||
else float(os.getenv("DISAGREEMENT_WEIGHT", "3"))
|
||||
)
|
||||
* (
|
||||
len(train)
|
||||
/ (len(player_counts) * count_sizes[r["player_count"]])
|
||||
if multiplayer
|
||||
else 1.0
|
||||
)
|
||||
for r in rows
|
||||
],
|
||||
device=device,
|
||||
)
|
||||
ce = -(targets * logits.log_softmax(-1)).sum(-1)
|
||||
returns = torch.tensor([r["value"] for r in rows], device=device)
|
||||
value_error = ((value - returns) ** 2).sum(-1) / torch.tensor(
|
||||
[r["player_count"] for r in rows], device=device
|
||||
)
|
||||
balance = torch.tensor(
|
||||
[
|
||||
len(train) / (len(player_counts) * count_sizes[r["player_count"]])
|
||||
if multiplayer
|
||||
else 1.0
|
||||
for r in rows
|
||||
],
|
||||
device=device,
|
||||
)
|
||||
loss = (ce * weights).sum() / weights.sum() + 0.2 * (
|
||||
(value - returns) ** 2
|
||||
).mean()
|
||||
value_error * balance
|
||||
).sum() / balance.sum()
|
||||
optimizer.zero_grad()
|
||||
loss.backward()
|
||||
torch.nn.utils.clip_grad_norm_(net.parameters(), 1)
|
||||
|
|
@ -158,30 +234,44 @@ for epoch in range(int(os.getenv("EPOCHS", "30")) + 1):
|
|||
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)
|
||||
for player_count in player_counts:
|
||||
for opponent in ["economic", "heuristic", "rush"]:
|
||||
result = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
"ai/strong/evaluate.py",
|
||||
str(out / "latest.onnx"),
|
||||
"--opponent",
|
||||
opponent,
|
||||
"--players",
|
||||
str(player_count),
|
||||
"--games",
|
||||
str(8 * player_count if multiplayer else 96),
|
||||
"--workers",
|
||||
"4",
|
||||
"--seed",
|
||||
f"multiplayer-distill-development-{player_count}-v1"
|
||||
if multiplayer
|
||||
else "search-distill-development-v1",
|
||||
"--output",
|
||||
str(out / f"{player_count}p-{opponent}.json"),
|
||||
],
|
||||
text=True,
|
||||
capture_output=True,
|
||||
check=True,
|
||||
)
|
||||
results[f"{player_count}p/{opponent}" if multiplayer else opponent] = (
|
||||
json.loads(result.stdout.strip().splitlines()[-1])
|
||||
)
|
||||
metric["arena"] = results
|
||||
score = np.mean([r["win_rate"] for r in results.values()])
|
||||
score = np.mean(
|
||||
[
|
||||
(r["win_rate"] - 1 / r["player_count"]) / (1 - 1 / r["player_count"])
|
||||
if multiplayer
|
||||
else r["win_rate"]
|
||||
for r in results.values()
|
||||
]
|
||||
)
|
||||
if score > best:
|
||||
best = score
|
||||
export("best")
|
||||
|
|
@ -190,9 +280,14 @@ for epoch in range(int(os.getenv("EPOCHS", "30")) + 1):
|
|||
(out / "schema.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"version": 3,
|
||||
"version": 4 if multiplayer else 3,
|
||||
"feature_revision": FEATURE_REVISION,
|
||||
"players": 3,
|
||||
"players": player_counts if multiplayer else 3,
|
||||
"training_positions_by_count": dict(count_sizes),
|
||||
"validation_positions_by_count": dict(validation_sizes),
|
||||
"split": "within each count/seat/rule cell, hold out 20% of whole games ranked by sha256(seed)"
|
||||
if multiplayer
|
||||
else "game id modulo 5",
|
||||
"map": "Germany",
|
||||
"run": run,
|
||||
"training_positions": len(train),
|
||||
|
|
|
|||
|
|
@ -7,19 +7,21 @@ 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, search_summary
|
||||
from arena_statistics import win_summary, search_summary, validate_pairs
|
||||
from search_scope import SCOPES, search_enabled
|
||||
from feature_contract import FEATURE_REVISION, check_revision, model_revision
|
||||
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("model")
|
||||
p.add_argument("--players", type=int, choices=range(2, 7), default=3)
|
||||
p.add_argument("--deal-offset", type=int, default=0)
|
||||
p.add_argument("--search-scope", choices=SCOPES, default="all")
|
||||
p.add_argument(
|
||||
"--opponent",
|
||||
default="economic",
|
||||
choices=["economic", "heuristic", "rush", "legacy", "search", "search_geo"],
|
||||
)
|
||||
p.add_argument("--opponent-model", help="Frozen ONNX policy in both opponent seats")
|
||||
p.add_argument("--opponent-model", help="Frozen ONNX policy in every opponent seat")
|
||||
p.add_argument("--workers", type=int, default=4)
|
||||
p.add_argument("--geographic-search", action="store_true")
|
||||
p.add_argument(
|
||||
|
|
@ -42,10 +44,22 @@ if not 0 <= args.search_samples <= 64:
|
|||
if args.geographic_search and not args.search_samples:
|
||||
p.error("--geographic-search requires positive --search-samples")
|
||||
model = Model(args.model)
|
||||
if args.games < 12 or args.games % 12:
|
||||
p.error("--games must be a positive multiple of 12 for paired rules and seats")
|
||||
paired_size = 4 * args.players
|
||||
if args.games < paired_size or args.games % paired_size:
|
||||
p.error(
|
||||
f"--games must be a positive multiple of {paired_size} for paired rules and seats"
|
||||
)
|
||||
if args.deal_offset < 0:
|
||||
p.error("--deal-offset cannot be negative")
|
||||
opponent_model = Model(args.opponent_model) if args.opponent_model else None
|
||||
pool = EnginePool(args.workers, seed=args.seed, script="ai/strong/bridge.cjs")
|
||||
for actor in [model, opponent_model]:
|
||||
if actor and args.players != 3 and model_revision(actor) != "4.0-multiplayer":
|
||||
p.error("Non-three-player evaluation requires schema 4 for every model")
|
||||
if args.allow_feature_transfer and model_revision(model) == "4.0-multiplayer":
|
||||
p.error("Schema 4 cannot be transferred to a schema 3 encoder")
|
||||
pool = EnginePool(
|
||||
min(args.workers, args.games), seed=args.seed, script="ai/strong/bridge.cjs"
|
||||
)
|
||||
feature_revision = (
|
||||
FEATURE_REVISION if args.allow_feature_transfer else model_revision(model)
|
||||
)
|
||||
|
|
@ -59,6 +73,8 @@ try:
|
|||
{
|
||||
"op": "reset",
|
||||
"n": args.games,
|
||||
"playerCount": args.players,
|
||||
"offset": args.deal_offset * paired_size,
|
||||
"mode": "snapshot0" if opponent_model else args.opponent,
|
||||
"arenaSeed": args.seed,
|
||||
"featureRevisions": feature_revisions,
|
||||
|
|
@ -126,7 +142,11 @@ try:
|
|||
last_progress = time.perf_counter()
|
||||
finally:
|
||||
pool.close()
|
||||
validate_pairs(rows, args.players)
|
||||
report = {
|
||||
"player_count": args.players,
|
||||
"chance_win_rate": 1 / args.players,
|
||||
"deal_offset": args.deal_offset,
|
||||
"model": args.model,
|
||||
"model_sha256": model.sha256,
|
||||
"model_feature_revision": model_revision(model),
|
||||
|
|
|
|||
|
|
@ -21,7 +21,11 @@ checkpoint["strategic_only"] = strategic_only
|
|||
net = policy_from_checkpoint(checkpoint).eval()
|
||||
torch.onnx.export(
|
||||
net,
|
||||
(torch.zeros(1, 738), torch.zeros(1, 8, 96), torch.ones(1, 8, dtype=torch.bool)),
|
||||
(
|
||||
torch.zeros(1, checkpoint.get("state_dim", 738)),
|
||||
torch.zeros(1, 8, checkpoint.get("action_dim", 96)),
|
||||
torch.ones(1, 8, dtype=torch.bool),
|
||||
),
|
||||
args.output,
|
||||
input_names=["state", "actions", "mask"],
|
||||
output_names=["logits", "value"],
|
||||
|
|
@ -38,6 +42,10 @@ torch.onnx.export(
|
|||
embed_revision(args.output, checkpoint.get("feature_revision", "3.0"))
|
||||
Path(args.output + ".json").write_text(
|
||||
json.dumps(
|
||||
{"source": args.checkpoint, "strategic_only": strategic_only, "schema": 3}
|
||||
{
|
||||
"source": args.checkpoint,
|
||||
"strategic_only": strategic_only,
|
||||
"schema": checkpoint.get("schema", 3),
|
||||
}
|
||||
)
|
||||
)
|
||||
|
|
|
|||
183
ai/strong/final-protocol-multiplayer.json
Normal file
183
ai/strong/final-protocol-multiplayer.json
Normal file
|
|
@ -0,0 +1,183 @@
|
|||
{
|
||||
"status": "prepared; no selected candidate; final seeds unused",
|
||||
"seed_prefix": "strong-multiplayer-final-reserved-v1",
|
||||
"scope": {
|
||||
"map": "Germany",
|
||||
"players": [
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6
|
||||
],
|
||||
"variants": [
|
||||
"original",
|
||||
"recharged"
|
||||
],
|
||||
"auctions": [
|
||||
"open",
|
||||
"sealed"
|
||||
],
|
||||
"setup": "automatic"
|
||||
},
|
||||
"reason_for_new_protocol": "Scope expanded from three players to 2\u20136 before any final seeds were used. Preserve the original three-player minimum rates; scale other counts by the same fraction of improvement above equal-seat chance. Default-bot minimum stays 90% at every count.",
|
||||
"pairing": "Every independent deal is repeated in each candidate seat and all four rule combinations. Exactly 4*N matches per deal; disjoint integer deal offsets across shards.",
|
||||
"intervals": "95% seed-cluster bootstrap; resample deals, retaining their seat/rule repeats. Report each count/rule separately. Intervals are per comparison, not a simultaneous family-wide confidence guarantee.",
|
||||
"requirements": {
|
||||
"all_games_complete": true,
|
||||
"no_illegal_moves": true,
|
||||
"full_paired_deals": true,
|
||||
"each_count_overall_interval_lower_bound": "strictly above 1/N",
|
||||
"each_count_each_rule_interval_lower_bound": "strictly above 1/N",
|
||||
"search_rollout_counts": "required, with incomplete rollouts explicitly reported",
|
||||
"export_parity": "All 2553 multiplayer fixtures agree in legal action with checkpoint, finite value outputs, inactive slots zero",
|
||||
"serving": "All 2553 fixtures return legal moves with correct request/revision and player ordering; benchmark same selected model/search settings on actual AMD 8840U, with results for every count",
|
||||
"package": "Standalone extracted archive hashes and legal CPU responses verified"
|
||||
},
|
||||
"opponents": [
|
||||
{
|
||||
"name": "legacy",
|
||||
"independent_deals_per_count": 40,
|
||||
"counts": {
|
||||
"2": {
|
||||
"games": 320,
|
||||
"minimum_win_rate": 0.9
|
||||
},
|
||||
"3": {
|
||||
"games": 480,
|
||||
"minimum_win_rate": 0.9
|
||||
},
|
||||
"4": {
|
||||
"games": 640,
|
||||
"minimum_win_rate": 0.9
|
||||
},
|
||||
"5": {
|
||||
"games": 800,
|
||||
"minimum_win_rate": 0.9
|
||||
},
|
||||
"6": {
|
||||
"games": 960,
|
||||
"minimum_win_rate": 0.9
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "heuristic",
|
||||
"independent_deals_per_count": 40,
|
||||
"counts": {
|
||||
"2": {
|
||||
"games": 320,
|
||||
"minimum_win_rate": 0.775
|
||||
},
|
||||
"3": {
|
||||
"games": 480,
|
||||
"minimum_win_rate": 0.7000000000000001
|
||||
},
|
||||
"4": {
|
||||
"games": 640,
|
||||
"minimum_win_rate": 0.6625000000000001
|
||||
},
|
||||
"5": {
|
||||
"games": 800,
|
||||
"minimum_win_rate": 0.6400000000000001
|
||||
},
|
||||
"6": {
|
||||
"games": 960,
|
||||
"minimum_win_rate": 0.625
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "economic",
|
||||
"independent_deals_per_count": 40,
|
||||
"counts": {
|
||||
"2": {
|
||||
"games": 320,
|
||||
"minimum_win_rate": 0.6625
|
||||
},
|
||||
"3": {
|
||||
"games": 480,
|
||||
"minimum_win_rate": 0.55
|
||||
},
|
||||
"4": {
|
||||
"games": 640,
|
||||
"minimum_win_rate": 0.49375
|
||||
},
|
||||
"5": {
|
||||
"games": 800,
|
||||
"minimum_win_rate": 0.46
|
||||
},
|
||||
"6": {
|
||||
"games": 960,
|
||||
"minimum_win_rate": 0.4375
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "rush",
|
||||
"independent_deals_per_count": 40,
|
||||
"counts": {
|
||||
"2": {
|
||||
"games": 320,
|
||||
"minimum_win_rate": 0.625
|
||||
},
|
||||
"3": {
|
||||
"games": 480,
|
||||
"minimum_win_rate": 0.5
|
||||
},
|
||||
"4": {
|
||||
"games": 640,
|
||||
"minimum_win_rate": 0.4375
|
||||
},
|
||||
"5": {
|
||||
"games": 800,
|
||||
"minimum_win_rate": 0.4
|
||||
},
|
||||
"6": {
|
||||
"games": 960,
|
||||
"minimum_win_rate": 0.375
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "search_geo",
|
||||
"independent_deals_per_count": 80,
|
||||
"counts": {
|
||||
"2": {
|
||||
"games": 640,
|
||||
"minimum_win_rate": 0.55
|
||||
},
|
||||
"3": {
|
||||
"games": 960,
|
||||
"minimum_win_rate": 0.4
|
||||
},
|
||||
"4": {
|
||||
"games": 1280,
|
||||
"minimum_win_rate": 0.325
|
||||
},
|
||||
"5": {
|
||||
"games": 1600,
|
||||
"minimum_win_rate": 0.28
|
||||
},
|
||||
"6": {
|
||||
"games": 1920,
|
||||
"minimum_win_rate": 0.25
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "frozen_a260",
|
||||
"counts": {
|
||||
"3": {
|
||||
"games": 960,
|
||||
"minimum_win_rate": 0.4
|
||||
}
|
||||
},
|
||||
"independent_deals_per_count": 80,
|
||||
"model_path": "runs/strong-league-v2-a/best.onnx",
|
||||
"model_revision": "b38515c29e57826de05b55b645c29591e4a886bf",
|
||||
"model_sha256": "9b46db558669a0c3085412fe2544359eda55ed9f092dffb67bead6af3c409ecd"
|
||||
}
|
||||
],
|
||||
"failure_policy": "A failed gate remains a failure. Do not relax thresholds after seeing final results. New candidate requires a new reserved final seed prefix."
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
"""Persistent CPU ONNX worker for schema 3 public-information states."""
|
||||
"""Persistent CPU ONNX worker for versioned public-information states."""
|
||||
|
||||
import sys, json, argparse, time
|
||||
from pathlib import Path
|
||||
|
|
@ -59,10 +59,10 @@ try:
|
|||
"requestId": q.get("requestId"),
|
||||
"revision": q.get("revision"),
|
||||
"move": r["moves"][index],
|
||||
"winProbabilities": values,
|
||||
"winProbabilities": values[: len(r["playerOrder"])],
|
||||
"valueStatus": "uncalibrated-training-opponents",
|
||||
"playerOrder": r["playerOrder"],
|
||||
"schema": 3,
|
||||
"schema": r["schema"],
|
||||
"featureRevision": r["featureRevision"],
|
||||
"search": {
|
||||
k: v
|
||||
|
|
|
|||
|
|
@ -26,8 +26,9 @@ root = Path(__file__).resolve().parents[2]
|
|||
model = Path(a.model).resolve()
|
||||
session = ort.InferenceSession(str(model), providers=["CPUExecutionProvider"])
|
||||
revision = session.get_modelmeta().custom_metadata_map.get(METADATA_KEY, "3.0")
|
||||
if revision not in ["3.0", "3.1-uranium39"]:
|
||||
if revision not in ["3.0", "3.1-uranium39", "4.0-multiplayer"]:
|
||||
raise ValueError("Unknown feature revision")
|
||||
multiplayer = revision == "4.0-multiplayer"
|
||||
out = Path(a.output).resolve()
|
||||
out.mkdir(parents=True, exist_ok=False)
|
||||
sha = lambda p: hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
|
|
@ -43,6 +44,7 @@ with tempfile.TemporaryDirectory() as tmp:
|
|||
"search_scope.py",
|
||||
"features.cjs",
|
||||
"features-v3_0.cjs",
|
||||
"features-v4.cjs",
|
||||
"economics.cjs",
|
||||
"economics-v3_0.cjs",
|
||||
"spatial.cjs",
|
||||
|
|
@ -79,13 +81,15 @@ os.execv(sys.executable, command)
|
|||
(bundle / "START.txt").write_text(
|
||||
"Powergrid CPU research worker\n\nRequires Node.js 24 and Python 3.11 or 3.12.\nCreate a virtual environment and install: pip install -r ai/requirements-serve.txt\nRun the frozen configuration from any directory: python /path/to/package/serve.py\nEquivalent direct command: "
|
||||
+ command
|
||||
+ "\n\nSend one JSON object per line with requestId, revision, player (seat index), and state (engine game state). Keep the process alive between requests. Each response proposes one atomic move. The platform must check the game revision and validate the move through the authoritative engine before committing it. Errors must not be committed as moves.\n\nScope: Germany, three players, automatic setup; original/Recharged and open/sealed auctions. Other players’ money is intentionally visible. Hidden deck order and sealed bids are excluded from policy inputs and search beliefs. Value outputs are uncalibrated training-opponent estimates, not objective player-analysis scores.\n\nThis archive makes no strength claim by itself. Consult the accompanying measured evaluations. No production routing is installed.\n"
|
||||
+ "\n\nSend one JSON object per line with requestId, revision, player (seat index), and state (engine game state). Keep the process alive between requests. Each response proposes one atomic move. The platform must check the game revision and validate the move through the authoritative engine before committing it. Errors must not be committed as moves.\n\nScope: Germany, "
|
||||
+ ("2–6 players" if multiplayer else "three players")
|
||||
+ ", automatic setup; original/Recharged and open/sealed auctions. Other players’ money is intentionally visible. Hidden deck order and sealed bids are excluded from policy inputs and search beliefs. Value outputs are uncalibrated training-opponent estimates, not objective player-analysis scores.\n\nThis archive makes no strength claim by itself. Consult the accompanying measured evaluations. No production routing is installed.\n"
|
||||
)
|
||||
manifest = {
|
||||
"model_sha256": sha(model),
|
||||
"model_repository_revision": a.model_revision,
|
||||
"feature_revision": revision,
|
||||
"schema": 3,
|
||||
"schema": 4 if multiplayer else 3,
|
||||
"engine_revision": "365fc519903fa2b4e8c593eed6cc5f5f77b5332a",
|
||||
"runtime_git_revision": subprocess.check_output(
|
||||
["git", "rev-parse", "HEAD"], cwd=root, text=True
|
||||
|
|
@ -100,7 +104,7 @@ os.execv(sys.executable, command)
|
|||
"geographic_search": a.geographic_search,
|
||||
"scope": {
|
||||
"map": "Germany",
|
||||
"players": 3,
|
||||
"players": [2, 3, 4, 5, 6] if multiplayer else 3,
|
||||
"automatic_setup": True,
|
||||
"variants": ["original", "recharged"],
|
||||
"auctions": ["open", "sealed"],
|
||||
|
|
|
|||
|
|
@ -1,20 +1,26 @@
|
|||
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++;
|
||||
const counts = process.env.MULTIPLAYER === '1' ? [2, 3, 4, 5, 6] : [3];
|
||||
for (const n of counts)
|
||||
for (let game = 0; game < 4; game++) {
|
||||
const g = c.E.setup(
|
||||
n,
|
||||
{ map: 'Germany', variant: game % 2 ? 'recharged' : 'original', fastBid: game < 2, showMoney: true },
|
||||
'strong-serving-' + game
|
||||
),
|
||||
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: `${n}p-${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');
|
||||
}
|
||||
if (!c.E.ended(g)) throw Error('Fixture game did not finish');
|
||||
}
|
||||
|
|
|
|||
79
ai/strong/teacher_contract.py
Normal file
79
ai/strong/teacher_contract.py
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
"""Validation and independent-game splitting for schema-4 search supervision."""
|
||||
|
||||
import hashlib
|
||||
import numpy as np
|
||||
from multiplayer import FEATURE_REVISION, PLAYER_COUNTS, rotate_outcome
|
||||
|
||||
|
||||
def validation_game(seed):
|
||||
return int.from_bytes(hashlib.sha256(seed.encode()).digest()[:8], "big") % 5 == 0
|
||||
|
||||
|
||||
def validate_game(game):
|
||||
n = game["playerCount"]
|
||||
if game["featureRevision"] != FEATURE_REVISION or n not in PLAYER_COUNTS:
|
||||
raise ValueError("Wrong teacher feature revision or player count")
|
||||
if game["variant"] not in ["original", "recharged"] or not isinstance(
|
||||
game["sealed"], bool
|
||||
):
|
||||
raise ValueError("Missing teacher rules")
|
||||
if not isinstance(game["seed"], str) or not game["seed"]:
|
||||
raise ValueError("Missing independent game seed")
|
||||
if game["truncated"]:
|
||||
if game["rows"]:
|
||||
raise ValueError("Truncated episodes cannot carry training targets")
|
||||
return
|
||||
if len(game["value"]) != n:
|
||||
raise ValueError("Wrong terminal vector length")
|
||||
for row in game["rows"]:
|
||||
state = np.asarray(row["state"])
|
||||
actions = np.asarray(row["actions"])
|
||||
if (
|
||||
state.shape != (1149,)
|
||||
or actions.ndim != 2
|
||||
or actions.shape[1] != 98
|
||||
or not len(actions)
|
||||
):
|
||||
raise ValueError("Wrong teacher feature dimensions")
|
||||
if not np.isfinite(state).all() or not np.isfinite(actions).all():
|
||||
raise ValueError("Nonfinite teacher features")
|
||||
if state[:6].tolist() != [1] * n + [0] * (6 - n):
|
||||
raise ValueError("Wrong active-player mask")
|
||||
if not 0 <= row["target"] < len(actions):
|
||||
raise ValueError("Teacher target is not a candidate")
|
||||
if row["value"] != rotate_outcome(game["value"], row["seat"]):
|
||||
raise ValueError("Value target does not match the observing seat")
|
||||
seen = set()
|
||||
for index, value in row["searchValues"]:
|
||||
if (
|
||||
index in seen
|
||||
or not 0 <= index < len(actions)
|
||||
or not np.isfinite(value)
|
||||
or not 0 <= value <= 1
|
||||
):
|
||||
raise ValueError("Invalid search estimate")
|
||||
seen.add(index)
|
||||
|
||||
|
||||
def validation_seeds(games):
|
||||
"""Hold out whole games in every count/seat/rule cell, by stable seed rank."""
|
||||
groups = {}
|
||||
seen = set()
|
||||
for game in games:
|
||||
if game["seed"] in seen:
|
||||
raise ValueError("Duplicate independent game seed")
|
||||
seen.add(game["seed"])
|
||||
seat = game["rows"][0]["seat"] if game["rows"] else None
|
||||
if seat is None or any(row["seat"] != seat for row in game["rows"]):
|
||||
raise ValueError("Expected one teacher seat per game")
|
||||
key = (game["playerCount"], seat, game["variant"], game["sealed"])
|
||||
groups.setdefault(key, []).append(game["seed"])
|
||||
selected = set()
|
||||
for seeds in groups.values():
|
||||
if len(seeds) < 2:
|
||||
raise ValueError(
|
||||
"Each teacher seat/rule cell needs train and validation games"
|
||||
)
|
||||
seeds.sort(key=lambda seed: hashlib.sha256(seed.encode()).digest())
|
||||
selected.update(seeds[: max(1, round(len(seeds) * 0.2))])
|
||||
return selected
|
||||
47
ai/strong/test_arena_statistics.py
Normal file
47
ai/strong/test_arena_statistics.py
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import copy
|
||||
import unittest
|
||||
from arena_statistics import validate_pairs
|
||||
|
||||
|
||||
def rows_for(n):
|
||||
return [
|
||||
dict(
|
||||
gameSeed="test",
|
||||
seat=s,
|
||||
variant=v,
|
||||
sealed=b,
|
||||
playerCount=n,
|
||||
roles=["learner" if i == s else "economic" for i in range(n)],
|
||||
value=[1.0 if i == 0 else 0.0 for i in range(n)],
|
||||
win=float(s == 0),
|
||||
truncated=False,
|
||||
)
|
||||
for s in range(n)
|
||||
for v in ["original", "recharged"]
|
||||
for b in [False, True]
|
||||
]
|
||||
|
||||
|
||||
class PairingTests(unittest.TestCase):
|
||||
def test_every_count_and_rejection_of_malformed_evidence(self):
|
||||
for n in range(2, 7):
|
||||
rows = rows_for(n)
|
||||
validate_pairs(rows, n)
|
||||
cases = [rows[:-1], rows + [rows[0]]]
|
||||
for field, value in [
|
||||
("playerCount", 7),
|
||||
("seat", n),
|
||||
("value", [1]),
|
||||
("win", 0.5),
|
||||
("roles", ["learner"] * n),
|
||||
]:
|
||||
broken = copy.deepcopy(rows)
|
||||
broken[0][field] = value
|
||||
cases.append(broken)
|
||||
for broken in cases:
|
||||
with self.assertRaises(ValueError):
|
||||
validate_pairs(broken, n)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
80
ai/strong/test_teacher_contract.py
Normal file
80
ai/strong/test_teacher_contract.py
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
import copy
|
||||
import unittest
|
||||
from teacher_contract import validate_game, validation_game, validation_seeds
|
||||
from multiplayer import rotate_outcome
|
||||
|
||||
|
||||
class TeacherContractTests(unittest.TestCase):
|
||||
def test_player_rotation_and_invalid_targets(self):
|
||||
for n in range(2, 7):
|
||||
for seat in range(n):
|
||||
value = [0.0] * n
|
||||
value[n - 1] = 1.0
|
||||
game = dict(
|
||||
playerCount=n,
|
||||
featureRevision="4.0-multiplayer",
|
||||
variant="original",
|
||||
sealed=True,
|
||||
seed=f"{n}-{seat}",
|
||||
truncated=False,
|
||||
value=value,
|
||||
rows=[
|
||||
dict(
|
||||
state=[1] * n + [0] * (1149 - n),
|
||||
actions=[[0.0] * 98],
|
||||
target=0,
|
||||
seat=seat,
|
||||
value=rotate_outcome(value, seat),
|
||||
searchValues=[[0, 0.5]],
|
||||
)
|
||||
],
|
||||
)
|
||||
validate_game(game)
|
||||
broken = copy.deepcopy(game)
|
||||
broken["rows"][0]["value"] = [0.0] * 6
|
||||
with self.assertRaises(ValueError):
|
||||
validate_game(broken)
|
||||
broken = copy.deepcopy(game)
|
||||
broken["rows"][0]["target"] = 1
|
||||
with self.assertRaises(ValueError):
|
||||
validate_game(broken)
|
||||
broken = copy.deepcopy(game)
|
||||
broken["truncated"] = True
|
||||
with self.assertRaises(ValueError):
|
||||
validate_game(broken)
|
||||
|
||||
def test_split_does_not_exclude_a_five_player_seat_or_rule(self):
|
||||
cells = {
|
||||
(i // 4 % 5, i % 4)
|
||||
for i in range(960)
|
||||
if validation_game(f"multiplayer-teacher-v1-5p-{i}")
|
||||
}
|
||||
self.assertEqual(len(cells), 20)
|
||||
|
||||
def test_stratified_split_covers_every_real_shard_cell(self):
|
||||
games = [
|
||||
dict(
|
||||
seed=f"multiplayer-teacher-v1-{n}p-{i}",
|
||||
playerCount=n,
|
||||
variant="recharged" if i % 2 else "original",
|
||||
sealed=i % 4 < 2,
|
||||
rows=[dict(seat=i // 4 % n)],
|
||||
)
|
||||
for n in range(2, 7)
|
||||
for i in range((n - 2) * 240, (n - 1) * 240)
|
||||
]
|
||||
selected = validation_seeds(games)
|
||||
key = lambda g: (
|
||||
g["playerCount"],
|
||||
g["rows"][0]["seat"],
|
||||
g["variant"],
|
||||
g["sealed"],
|
||||
)
|
||||
expected = {key(g) for g in games}
|
||||
self.assertEqual({key(g) for g in games if g["seed"] in selected}, expected)
|
||||
self.assertEqual({key(g) for g in games if g["seed"] not in selected}, expected)
|
||||
self.assertEqual(selected, validation_seeds(list(reversed(games))))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -435,7 +435,9 @@ try:
|
|||
metric["training_opponents"] = opponent_outcomes
|
||||
metrics.append(metric)
|
||||
print(json.dumps(metric), flush=True)
|
||||
if update % int(os.getenv("EVAL_EVERY", "10")) == 0 or update == updates - 1:
|
||||
if (update + int(multiplayer)) % int(
|
||||
os.getenv("EVAL_EVERY", "10")
|
||||
) == 0 or update == updates - 1:
|
||||
net.eval()
|
||||
evaluation = evaluate(update)
|
||||
metrics.append({"stage": "evaluation", "update": update, **evaluation})
|
||||
|
|
|
|||
|
|
@ -27,7 +27,13 @@ const encoders = require('./encoders.cjs'),
|
|||
console.log(JSON.stringify(result));
|
||||
continue;
|
||||
}
|
||||
console.log(JSON.stringify({ ...x, playerOrder: [p, (p + 1) % 3, (p + 2) % 3] }));
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
...x,
|
||||
playerOrder: Array.from({ length: g.players.length }, (_, i) => (p + i) % g.players.length),
|
||||
schema: encoders.forRevision(q.featureRevision).SCHEMA,
|
||||
})
|
||||
);
|
||||
} catch (e) {
|
||||
console.log(JSON.stringify({ error: e.message }));
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue