Generalize league rollouts and PPO targets to 2–6 players
This commit is contained in:
parent
8bab029c23
commit
6967682bdd
5 changed files with 227 additions and 61 deletions
|
|
@ -40,7 +40,7 @@ class EnginePool:
|
|||
raise ValueError("Need at least one environment per worker")
|
||||
self.sizes = [n // workers + (i < n % workers) for i in range(workers)]
|
||||
requests = []
|
||||
offset = 0
|
||||
offset = request.get("offset", 0)
|
||||
for n in self.sizes:
|
||||
requests.append({**request, "n": n, "offset": offset})
|
||||
offset += n
|
||||
|
|
|
|||
|
|
@ -67,9 +67,11 @@ function observation(e) {
|
|||
round: e.g.round,
|
||||
variant: e.g.options.variant,
|
||||
sealed: !!e.g.options.fastBid,
|
||||
playerCount: e.g.players.length,
|
||||
};
|
||||
}
|
||||
function reset(mode = 'mixed', arenaSeed, arenaId, featureRevisions = {}) {
|
||||
function reset(mode = 'mixed', arenaSeed, arenaId, featureRevisions = {}, playerCount = 3) {
|
||||
if (!Number.isInteger(playerCount) || playerCount < 2 || playerCount > 6) throw Error('Invalid player count');
|
||||
if (
|
||||
![
|
||||
'mixed',
|
||||
|
|
@ -88,7 +90,7 @@ function reset(mode = 'mixed', arenaSeed, arenaId, featureRevisions = {}) {
|
|||
)
|
||||
throw Error('Unknown opponent mode: ' + mode);
|
||||
const id = arenaSeed === undefined ? sequence++ : arenaId,
|
||||
seat = Math.floor(id / 4) % 3,
|
||||
seat = Math.floor(id / 4) % playerCount,
|
||||
kind = Math.floor(c.seedrandom(seed + '-opponents-' + id)() * 8);
|
||||
const opponent =
|
||||
mode === 'mixed' || mode === 'mixed_search'
|
||||
|
|
@ -105,13 +107,17 @@ function reset(mode = 'mixed', arenaSeed, arenaId, featureRevisions = {}) {
|
|||
: mode;
|
||||
const roles =
|
||||
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);
|
||||
? Array(playerCount).fill('learner')
|
||||
: Array.from({ length: playerCount }, (_, i) => (i === seat ? 'learner' : opponent));
|
||||
const gameSeed = arenaSeed === undefined ? seed + '-' + id : arenaSeed + '-' + Math.floor(id / (4 * playerCount));
|
||||
const e = {
|
||||
id,
|
||||
gameSeed,
|
||||
g: c.start(gameSeed, id % 2 ? 'recharged' : 'original', id % 4 < 2),
|
||||
g: c.E.setup(
|
||||
playerCount,
|
||||
{ map: 'Germany', variant: id % 2 ? 'recharged' : 'original', fastBid: id % 4 < 2, showMoney: true },
|
||||
gameSeed
|
||||
),
|
||||
roles,
|
||||
rng: c.seedrandom(arenaSeed === undefined ? seed + '-bot-' + id : gameSeed + '-bot'),
|
||||
steps: 0,
|
||||
|
|
@ -129,7 +135,7 @@ function reset(mode = 'mixed', arenaSeed, arenaId, featureRevisions = {}) {
|
|||
ended = [];
|
||||
if (q.op === 'reset')
|
||||
envs = Array.from({ length: q.n }, (_, i) =>
|
||||
reset(q.mode, q.arenaSeed, (q.offset || 0) + i, q.featureRevisions)
|
||||
reset(q.mode, q.arenaSeed, (q.offset || 0) + i, q.featureRevisions, q.playerCount ?? 3)
|
||||
);
|
||||
else if (q.op === 'step')
|
||||
for (let i = 0; i < envs.length; i++) {
|
||||
|
|
@ -161,7 +167,10 @@ function reset(mode = 'mixed', arenaSeed, arenaId, featureRevisions = {}) {
|
|||
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],
|
||||
value: c.E.ended(e.g) ? c.outcome(e.g) : Array(e.g.players.length).fill(0),
|
||||
playerCount: e.g.players.length,
|
||||
variant: e.g.options.variant,
|
||||
sealed: !!e.g.options.fastBid,
|
||||
steps: e.steps,
|
||||
roles: e.roles,
|
||||
policyMoves: e.policyMoves,
|
||||
|
|
|
|||
17
ai/strong/multiplayer.py
Normal file
17
ai/strong/multiplayer.py
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
"""Shared schema-4 training contracts, also exercised without gradient training."""
|
||||
|
||||
FEATURE_REVISION = "4.0-multiplayer"
|
||||
PLAYER_COUNTS = (2, 3, 4, 5, 6)
|
||||
ROLE_REVISIONS = {
|
||||
role: FEATURE_REVISION
|
||||
for role in ("learner", "snapshot0", "snapshot1", "snapshot2")
|
||||
}
|
||||
|
||||
|
||||
def rotate_outcome(outcome, seat):
|
||||
n = len(outcome)
|
||||
if n not in PLAYER_COUNTS or not 0 <= seat < n:
|
||||
raise ValueError("Invalid terminal outcome shape or seat")
|
||||
if abs(sum(outcome) - 1) > 1e-6 or any(x < 0 for x in outcome):
|
||||
raise ValueError("Expected complete terminal win credits")
|
||||
return [outcome[(seat + j) % n] for j in range(n)] + [0.0] * (6 - n)
|
||||
63
ai/strong/test_multiplayer_bridge.py
Normal file
63
ai/strong/test_multiplayer_bridge.py
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
"""Complete real engine episodes through the exact training subprocess protocol."""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from pool import EnginePool
|
||||
from multiplayer import ROLE_REVISIONS, rotate_outcome
|
||||
|
||||
|
||||
class BridgeTests(unittest.TestCase):
|
||||
def test_complete_paired_counts_and_rotate_terminal_targets(self):
|
||||
pool = EnginePool(3, seed="multiplayer-protocol", script="ai/strong/bridge.cjs")
|
||||
try:
|
||||
for n in range(2, 7):
|
||||
current = pool.call(
|
||||
{
|
||||
"op": "reset",
|
||||
"n": 4 * n,
|
||||
"mode": "selfplay",
|
||||
"playerCount": n,
|
||||
"featureRevisions": ROLE_REVISIONS,
|
||||
"arenaSeed": f"protocol-{n}",
|
||||
"offset": 4 * n,
|
||||
}
|
||||
)["observations"]
|
||||
ends = []
|
||||
seats = set()
|
||||
for _ in range(1800):
|
||||
for row in current:
|
||||
if row:
|
||||
self.assertEqual(row["playerCount"], n)
|
||||
self.assertEqual(row["featureRevision"], "4.0-multiplayer")
|
||||
seats.add(row["seat"])
|
||||
reply = pool.call(
|
||||
{
|
||||
"op": "step",
|
||||
"actions": [r["teacher"] if r else None for r in current],
|
||||
}
|
||||
)
|
||||
ends.extend(reply["ended"])
|
||||
current = reply["observations"]
|
||||
if all(r is None for r in current):
|
||||
break
|
||||
self.assertEqual(len(ends), 4 * n)
|
||||
self.assertEqual(seats, set(range(n)))
|
||||
self.assertEqual({e["episode"] for e in ends}, set(range(4 * n, 8 * n)))
|
||||
self.assertEqual({e["gameSeed"] for e in ends}, {f"protocol-{n}-1"})
|
||||
for e in ends:
|
||||
self.assertFalse(e["truncated"])
|
||||
self.assertEqual(len(e["roles"]), n)
|
||||
for seat in range(n):
|
||||
rotated = rotate_outcome(e["value"], seat)
|
||||
self.assertEqual(rotated[0], e["value"][seat])
|
||||
self.assertEqual(rotated[n:], [0.0] * (6 - n))
|
||||
self.assertAlmostEqual(sum(rotated), 1)
|
||||
finally:
|
||||
pool.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -10,10 +10,19 @@ import numpy as np
|
|||
import torch
|
||||
from torch.distributions import Categorical
|
||||
from model import Policy, tensors
|
||||
from model_v4 import MultiplayerPolicy
|
||||
from multiplayer import ROLE_REVISIONS, rotate_outcome
|
||||
from pool import EnginePool
|
||||
from huggingface_hub import HfApi, hf_hub_download
|
||||
from feature_contract import FEATURE_REVISION, embed_revision
|
||||
|
||||
multiplayer = os.getenv("ARCHITECTURE") == "multiplayer"
|
||||
if multiplayer:
|
||||
FEATURE_REVISION = "4.0-multiplayer"
|
||||
state_dim, action_dim = (1149, 98) if multiplayer else (738, 96)
|
||||
player_counts = [2, 3, 4, 5, 6] if multiplayer else [3]
|
||||
feature_revisions = ROLE_REVISIONS if multiplayer else {}
|
||||
|
||||
seed = int(os.getenv("TRAIN_SEED", "101"))
|
||||
random.seed(seed)
|
||||
np.random.seed(seed)
|
||||
|
|
@ -60,7 +69,11 @@ strategic_only = (
|
|||
)
|
||||
== "1"
|
||||
)
|
||||
net = Policy(strategic_only=strategic_only).to(device)
|
||||
if multiplayer and strategic_only:
|
||||
raise ValueError("Strategic-only schema-3 routing cannot be used with schema 4")
|
||||
net = (
|
||||
MultiplayerPolicy() if multiplayer else Policy(strategic_only=strategic_only)
|
||||
).to(device)
|
||||
if checkpoint:
|
||||
net.load_state_dict(checkpoint["state_dict"])
|
||||
initial_anchor = (
|
||||
|
|
@ -88,9 +101,10 @@ update = -1
|
|||
def save(name, export=False):
|
||||
torch.save(
|
||||
{
|
||||
"state_dim": 738,
|
||||
"action_dim": 96,
|
||||
"schema": 3,
|
||||
"state_dim": state_dim,
|
||||
"action_dim": action_dim,
|
||||
"schema": 4 if multiplayer else 3,
|
||||
"architecture": "multiplayer" if multiplayer else "policy",
|
||||
"feature_revision": FEATURE_REVISION,
|
||||
"strategic_only": strategic_only,
|
||||
"update": update,
|
||||
|
|
@ -108,8 +122,8 @@ def save(name, export=False):
|
|||
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 / (name + ".onnx")),
|
||||
|
|
@ -125,16 +139,16 @@ def save(name, export=False):
|
|||
opset_version=17,
|
||||
dynamo=False,
|
||||
)
|
||||
embed_revision(out / (name + ".onnx"))
|
||||
embed_revision(out / (name + ".onnx"), FEATURE_REVISION)
|
||||
(out / "metrics.json").write_text(json.dumps(metrics, indent=2))
|
||||
(out / "schema.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"version": 3,
|
||||
"version": 4 if multiplayer else 3,
|
||||
"feature_revision": FEATURE_REVISION,
|
||||
"state_dim": 738,
|
||||
"action_dim": 96,
|
||||
"players": 3,
|
||||
"state_dim": state_dim,
|
||||
"action_dim": action_dim,
|
||||
"players": player_counts if multiplayer else 3,
|
||||
"map": "Germany",
|
||||
"information": "all money public, sealed bids/deck/queued plans excluded",
|
||||
"run": run,
|
||||
|
|
@ -160,34 +174,71 @@ 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),
|
||||
}
|
||||
for player_count in player_counts:
|
||||
for mode in ["economic", "heuristic", "rush", "legacy"]:
|
||||
current = pool.call(
|
||||
{
|
||||
"op": "reset",
|
||||
"n": 8 * player_count if multiplayer else 96,
|
||||
"mode": mode,
|
||||
"playerCount": player_count,
|
||||
"featureRevisions": feature_revisions,
|
||||
**(
|
||||
{"arenaSeed": f"multiplayer-development-{player_count}-v1"}
|
||||
if multiplayer
|
||||
else {}
|
||||
),
|
||||
}
|
||||
)["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[f"{player_count}p/{mode}" if multiplayer else mode] = {
|
||||
"player_count": player_count,
|
||||
"by_rule": {
|
||||
f"{variant}/{sealed}": {
|
||||
"games": len(group),
|
||||
"win": float(
|
||||
np.mean(
|
||||
[
|
||||
e["value"][e["roles"].index("learner")]
|
||||
for e in group
|
||||
]
|
||||
)
|
||||
),
|
||||
}
|
||||
for variant in ["original", "recharged"]
|
||||
for sealed in [False, True]
|
||||
if (
|
||||
group := [
|
||||
e
|
||||
for e in ends
|
||||
if e["variant"] == variant and e["sealed"] == sealed
|
||||
]
|
||||
)
|
||||
},
|
||||
"win": float(np.mean(wins)),
|
||||
"truncated": sum(e["truncated"] for e in ends),
|
||||
"games": len(ends),
|
||||
}
|
||||
finally:
|
||||
pool.close()
|
||||
print(
|
||||
|
|
@ -199,6 +250,22 @@ def evaluate(update):
|
|||
return result
|
||||
|
||||
|
||||
def selection_score(evaluation):
|
||||
if not multiplayer:
|
||||
return float(
|
||||
np.mean([evaluation[x]["win"] for x in ["economic", "heuristic", "rush"]])
|
||||
)
|
||||
return float(
|
||||
np.mean(
|
||||
[
|
||||
(v["win"] - 1 / v["player_count"]) / (1 - 1 / v["player_count"])
|
||||
for k, v in evaluation.items()
|
||||
if not k.endswith("/legacy")
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
try:
|
||||
print(
|
||||
json.dumps(
|
||||
|
|
@ -212,18 +279,22 @@ try:
|
|||
),
|
||||
flush=True,
|
||||
)
|
||||
if initial_checkpoint:
|
||||
if initial_checkpoint or multiplayer:
|
||||
net.eval()
|
||||
evaluation = evaluate(-1)
|
||||
metrics.append({"stage": "evaluation", "update": -1, **evaluation})
|
||||
best = float(
|
||||
np.mean([evaluation[x]["win"] for x in ["economic", "heuristic", "rush"]])
|
||||
)
|
||||
best = selection_score(evaluation)
|
||||
save("best", export=True)
|
||||
for update in range(updates):
|
||||
start = time.perf_counter()
|
||||
current = rollout.call(
|
||||
{"op": "reset", "n": nenv, "mode": os.getenv("OPPONENT_MODE", "mixed")}
|
||||
{
|
||||
"op": "reset",
|
||||
"n": nenv,
|
||||
"mode": os.getenv("OPPONENT_MODE", "mixed"),
|
||||
"playerCount": player_counts[update % len(player_counts)],
|
||||
"featureRevisions": feature_revisions,
|
||||
}
|
||||
)["observations"]
|
||||
pending = [[] for _ in range(nenv)]
|
||||
batch = []
|
||||
|
|
@ -235,7 +306,7 @@ try:
|
|||
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)
|
||||
values = [[0.0] * (6 if multiplayer else 3)] * len(rows)
|
||||
roles = {r["roles"][r["seat"]] for r in rows}
|
||||
for role in roles:
|
||||
indices = [
|
||||
|
|
@ -281,9 +352,11 @@ try:
|
|||
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["value"] = (
|
||||
rotate_outcome(end["value"], r["seat"])
|
||||
if multiplayer
|
||||
else [end["value"][(r["seat"] + j) % 3] for j in range(3)]
|
||||
)
|
||||
r["advantage"] = r["value"][0] - r["oldvalue"]
|
||||
batch.append(r)
|
||||
pending[end["env"]] = []
|
||||
|
|
@ -322,7 +395,12 @@ try:
|
|||
)
|
||||
loss = (
|
||||
pg
|
||||
+ 0.5 * ((value - target) ** 2).mean()
|
||||
+ 0.5
|
||||
* (
|
||||
(((value - target) ** 2).sum(-1) / x[0][:, :6].sum(-1)).mean()
|
||||
if multiplayer
|
||||
else ((value - target) ** 2).mean()
|
||||
)
|
||||
- float(os.getenv("ENTROPY", ".01")) * dist.entropy().mean()
|
||||
+ float(os.getenv("ANCHOR", ".01")) * kl
|
||||
)
|
||||
|
|
@ -336,6 +414,7 @@ try:
|
|||
"run": run,
|
||||
"update": update,
|
||||
"episodes": len(endings),
|
||||
"player_count": player_counts[update % len(player_counts)],
|
||||
"truncated": sum(x["truncated"] for x in endings),
|
||||
"samples": len(batch),
|
||||
"rollout_seconds": rollout_seconds,
|
||||
|
|
@ -360,9 +439,7 @@ try:
|
|||
net.eval()
|
||||
evaluation = evaluate(update)
|
||||
metrics.append({"stage": "evaluation", "update": update, **evaluation})
|
||||
score = np.mean(
|
||||
[evaluation[x]["win"] for x in ["economic", "heuristic", "rush"]]
|
||||
)
|
||||
score = selection_score(evaluation)
|
||||
if score > best:
|
||||
best = score
|
||||
snapshots.append(copy.deepcopy(net).eval())
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue