Decouple optional league admission from heuristic checkpoint selection

This commit is contained in:
coyotte508 2026-10-01 07:26:20 +02:00
commit dabc9e2703
3 changed files with 84 additions and 4 deletions

View file

@ -0,0 +1,32 @@
"""Frozen PPO opponents, with admission independent of model selection when requested."""
import copy
class SnapshotLeague:
def __init__(self, net, admission="best", interval=10):
if admission not in {"best", "periodic_anchor"}:
raise ValueError("Unknown snapshot admission policy")
if interval < 1:
raise ValueError("Snapshot interval must be positive")
self.admission = admission
self.interval = interval
self.actors = [self._freeze(net)]
self.updates = [-1]
@staticmethod
def _freeze(net):
actor = copy.deepcopy(net).eval()
actor.requires_grad_(False)
return actor
def admit(self, net, update, improved=False):
due = improved if self.admission == "best" else (update + 1) % self.interval == 0
if not due or update in self.updates:
return False
self.actors.append(self._freeze(net))
self.updates.append(update)
if len(self.actors) > 3:
indices = [-3, -2, -1] if self.admission == "best" else [0, -2, -1]
self.actors = [self.actors[i] for i in indices]
self.updates = [self.updates[i] for i in indices]
return True

View file

@ -0,0 +1,37 @@
import unittest
import torch
from snapshot_league import SnapshotLeague
class LeagueTests(unittest.TestCase):
def test_periodic_admission_survives_flat_selection_and_preserves_anchor(self):
net = torch.nn.Linear(1, 1)
league = SnapshotLeague(net, "periodic_anchor", 2)
original = net.weight.detach().clone()
for update in range(8):
with torch.no_grad():
net.weight.add_(1)
league.admit(net, update, improved=False)
self.assertEqual(league.updates, [-1, 5, 7])
torch.testing.assert_close(league.actors[0].weight, original)
torch.testing.assert_close(league.actors[1].weight, original + 6)
torch.testing.assert_close(league.actors[2].weight, original + 8)
self.assertFalse(league.admit(net, 7))
self.assertTrue(all(not a.training and not a.weight.requires_grad for a in league.actors))
def test_legacy_admission_keeps_last_three_improvements(self):
net = torch.nn.Linear(1, 1)
league = SnapshotLeague(net)
self.assertFalse(league.admit(net, 0, improved=False))
for u in [9, 19, 29]:
self.assertTrue(league.admit(net, u, improved=True))
self.assertEqual(league.updates, [9, 19, 29])
def test_invalid_configuration_is_rejected(self):
for mode, interval in [('unknown', 10), ('best', 0)]:
with self.assertRaises(ValueError):
SnapshotLeague(torch.nn.Linear(1, 1), mode, interval)
if __name__ == '__main__':
unittest.main()

View file

@ -14,6 +14,7 @@ from model_v4 import MultiplayerPolicy
from multiplayer import ROLE_REVISIONS, rotate_outcome, balance_training_rows
from pool import EnginePool
from arena_statistics import search_summary
from snapshot_league import SnapshotLeague
from huggingface_hub import HfApi, hf_hub_download
from feature_contract import FEATURE_REVISION, embed_revision
@ -106,10 +107,14 @@ if async_rollout:
if workers != nenv:
raise ValueError("Async rollout requires WORKERS == ENVS")
rollout_class = AsyncEnginePool
league = SnapshotLeague(
net,
os.getenv("SNAPSHOT_ADMISSION", "best"),
int(os.getenv("SNAPSHOT_INTERVAL", "10")),
)
rollout = rollout_class(
workers, seed=f"strong-train-{seed}", script="ai/strong/bridge.cjs"
)
snapshots = [copy.deepcopy(net).eval()]
metrics = []
best = -1
update = -1
@ -128,6 +133,9 @@ def save(name, export=False):
"mixed_player_counts": mix_player_counts,
"training_device": device,
"async_rollout": async_rollout,
"snapshot_admission": league.admission,
"snapshot_interval": league.interval,
"snapshot_updates": league.updates,
"initial_checkpoint": initial_checkpoint,
"initial_revision": initial_revision,
"initial_feature_revision": checkpoint.get("feature_revision", "3.0")
@ -349,7 +357,7 @@ try:
actor = (
net
if role == "learner"
else snapshots[int(role[-1]) % len(snapshots)]
else league.actors[int(role[-1]) % len(league.actors)]
)
with torch.no_grad():
logits, vs = actor(*tensors([rows[j] for j in indices], device))
@ -536,6 +544,9 @@ try:
group["wins"] += ending["value"][ending["roles"].index("learner")]
group["truncated"] += ending["truncated"]
metric["training_opponents"] = opponent_outcomes
metric["snapshot_updates"] = list(league.updates)
if league.admission == "periodic_anchor":
league.admit(net, update)
metric.update(search_summary(endings))
metrics.append(metric)
print(json.dumps(metric), flush=True)
@ -548,8 +559,8 @@ try:
score = selection_score(evaluation)
if score > best:
best = score
snapshots.append(copy.deepcopy(net).eval())
snapshots = snapshots[-3:]
if league.admission == "best":
league.admit(net, update, improved=True)
save("best", export=True)
save("latest", export=True)
finally: