Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions paper/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,22 @@ The engine cannot be cloned. Each simulation therefore restores the root state w

All randomness is seeded from `--seed`. Training episode e uses seed `seed·10⁶ + e`.

## Running fast (GPU / many-core machine)

Self-play MCTS evaluates one state at a time and replays the engine on the
CPU, so it is CPU-bound; `--workers N` runs self-play episodes in N parallel
processes (`0` = all cores but one). Gradient updates run on `--device`.
Each episode's search randomness comes from its own seed, so the result is
identical for any number of workers (checked: 1 vs 3 workers give the same log).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ Low · Worker-count logs differ

When runs using different worker counts take different time per iteration, the per-iteration record includes sec, computed from wall-clock time, so runs with different worker counts normally produce different log entries even when their training results match. The README’s “same log” claim is therefore not true for the complete log.

Clarify that reproducibility applies to training results, excluding timing fields, or omit timing from the compared log.

Prompt for AI agents
In `paper/README.md` at line 69:

**Worker-count logs differ**

When runs using different worker counts take different time per iteration, the per-iteration record includes `sec`, computed from wall-clock time, so runs with different worker counts normally produce different log entries even when their training results match. The README’s “same log” claim is therefore not true for the complete log.

Clarify that reproducibility applies to training results, excluding timing fields, or omit timing from the compared log.


zig build lib -Doptimize=ReleaseFast
PYTHONPATH=python:paper python paper/train.py --device cuda --workers 0 \
--episodes 32 --sims 64 --batch 512 --updates 200 --iters 50 --out paper/out/ptr.pt

Use `--episodes` that is a multiple of the worker count. Bigger `--batch` /
`--updates` / `--d-model` use the GPU more; more `--episodes` / `--sims` use
the CPU cores more.

## Evaluation and seeds

Every policy runs on the same seeds: `10¹²`, `10¹² + 1`, … These never overlap with training seeds. Two things are checked, not assumed:
Expand Down
10 changes: 8 additions & 2 deletions paper/ptrmcts.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import hashlib
import math
import os
import sys
import tempfile
from dataclasses import dataclass, field

Expand All @@ -39,8 +40,13 @@
import torch.nn as nn
import torch.nn.functional as F

from sched_env import SchedEnv
from sched_env import _lib
# find python/sched_env without PYTHONPATH (also in spawned worker processes)
_PY = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "python")
if _PY not in sys.path:
sys.path.insert(0, _PY)

from sched_env import SchedEnv # noqa: E402
from sched_env import _lib # noqa: E402

# Environment used in the paper experiments. Small enough for MCTS on a CPU.
ENV_KW = dict(
Expand Down
66 changes: 54 additions & 12 deletions paper/train.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import argparse
import collections
import json
import multiprocessing as mp
import os
import random
import time
from pathlib import Path
Expand Down Expand Up @@ -74,6 +76,43 @@ def train_step(net, opt, batch, device, value_coef):
return pl.item(), vl.item()


# ----------------------------------------------------------------------------- parallel self-play
# Each self-play episode is independent given the network weights, so they run
# in worker processes (CPU, one thread each: MCTS evaluates one state at a time,
# which a GPU does not speed up). Training stays on --device. Every episode's
# search randomness comes from its own seed, so results do not depend on the
# number of workers.

_W: dict = {}


def _worker_init(d_model: int, threads: int):
torch.set_num_threads(threads)
env = make_env()
_W["env"] = env
_W["net"] = PointerNet.for_env(env, d=d_model).eval()


def self_play_episode(job):
"""(state_dict or None, seed, args dict) -> (samples, stats, return).
Runs in a worker (or in-process when state_dict is None and _W is set)."""
state, seed, a = job
if state is not None:
_W["net"].load_state_dict(state)
env, net = _W["env"], _W["net"]
rng = np.random.default_rng([a["seed"], seed])
mcts = MCTS(net, ENV_KW, "cpu", sims=a["sims"], gamma=a["gamma"], reward_scale=a["reward_scale"], rng=rng)

def choose(obs, mask, prefix, expect, step):
counts = mcts.search(seed, prefix, expect, noise=True)
pi = counts / counts.sum()
act = int(rng.choice(len(pi), p=pi)) if step < a["explore_steps"] else int(np.argmax(counts))
return act, pi

with torch.no_grad():
return run_episode(env, seed, choose, a["gamma"], a["reward_scale"])


def fit(net, opt, buffer, args, device, rng):
if len(buffer) < args.batch:
return float("nan"), float("nan")
Expand Down Expand Up @@ -105,6 +144,8 @@ def main():
ap.add_argument("--reward-scale", type=float, default=10.0)
ap.add_argument("--d-model", type=int, default=128)
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--workers", type=int, default=1,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ Low · Negative worker counts are accepted

When --workers is negative, workers retains the negative value, and the workers > 1 branch is skipped, so training runs serially and reports a negative worker count instead of rejecting the option.

Validate --workers as nonnegative in argparse before resolving the worker count.

Also at paper/train.py:195.

Prompt for AI agents
In `paper/train.py` at line 147:

**Negative worker counts are accepted**

When `--workers` is negative, `workers` retains the negative value, and the `workers > 1` branch is skipped, so training runs serially and reports a negative worker count instead of rejecting the option.

Validate `--workers` as nonnegative in argparse before resolving the worker count.

Also at `paper/train.py:195`.

help="parallel self-play processes (0 = all cores but one); results do not depend on it")
ap.add_argument("--device", default="cpu")
ap.add_argument("--out", default="paper/out/ptr.pt")
args = ap.parse_args()
Expand Down Expand Up @@ -151,21 +192,19 @@ def teacher(obs, mask, prefix, expect, step):
buffer.extend(data)

# 2-3. self-play + training ------------------------------------------------
mcts = MCTS(net, ENV_KW, device, sims=args.sims, gamma=args.gamma, reward_scale=args.reward_scale, rng=rng)
cpus = len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else (os.cpu_count() or 2)
workers = args.workers or max(1, cpus - 1) # affinity: only the CPUs SLURM/taskset gave us
pool = (mp.get_context("spawn").Pool(workers, _worker_init, (args.d_model, 1)) if workers > 1 else None)
if pool is None:
_worker_init(args.d_model, torch.get_num_threads())
print(f"self-play: {workers} worker(s), training on {device}")
for it in range(args.iters):
t0 = time.time()
net.eval()
state = {k: v.detach().cpu() for k, v in net.state_dict().items()}
jobs = [(state, next(seeds), vars(args)) for _ in range(args.episodes)]
results = pool.map(self_play_episode, jobs) if pool else [self_play_episode(j) for j in jobs]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Self-play hangs after worker exits

When a worker exits abruptly while processing an episode, pool.map waits for the in-flight task's result, but the pool does not requeue it after replacing the worker, so the iteration never reaches its checkpoint write.

Use a dispatch and recovery strategy that detects lost tasks and retries them or fails the iteration.

Prompt for AI agents
In `paper/train.py` at line 204:

**Self-play hangs after worker exits**

When a worker exits abruptly while processing an episode, `pool.map` waits for the in-flight task's result, but the pool does not requeue it after replacing the worker, so the iteration never reaches its checkpoint write.

Use a dispatch and recovery strategy that detects lost tasks and retries them or fails the iteration.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Large iterations exhaust memory

When A single iteration's episodes produce substantially more samples than --buffer can retain, pool.map materializes every episode's samples in results before they are added to the bounded replay buffer, and the list remains referenced after buffer.extend. For an iteration producing far more samples than --buffer holds, memory grows with all episode outputs instead of the buffer limit, so training can run out of memory.

Consume episode results incrementally and release each result after extending the replay buffer.

Prompt for AI agents
In `paper/train.py` at line 204:

**Large iterations exhaust memory**

When A single iteration's episodes produce substantially more samples than `--buffer` can retain, `pool.map` materializes every episode's samples in `results` before they are added to the bounded replay buffer, and the list remains referenced after `buffer.extend`. For an iteration producing far more samples than `--buffer` holds, memory grows with all episode outputs instead of the buffer limit, so training can run out of memory.

Consume episode results incrementally and release each result after extending the replay buffer.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Worker regressions go unnoticed

When parallel self-play is added or later changed, the pool dispatch to self_play_episode and its serial fallback have no test coverage, so worker startup, result equivalence, or reproducibility regressions pass unnoticed.

Add an automated test that exercises parallel self-play and checks its results against the serial path.

Prompt for AI agents
In `paper/train.py` at line 204:

**Worker regressions go unnoticed**

When parallel self-play is added or later changed, the pool dispatch to `self_play_episode` and its serial fallback have no test coverage, so worker startup, result equivalence, or reproducibility regressions pass unnoticed.

Add an automated test that exercises parallel self-play and checks its results against the serial path.

From CLAUDE.md L29-31:

- Every behavior change needs a test; integration tests in tests/. Engine
  semantics: add a hand-worked case to tests/scenario_test.zig; the
  `property:` test there checks against a naive reference simulator.

rets, slow = [], []
for _ in range(args.episodes):
seed = next(seeds)

def choose(obs, mask, prefix, expect, step, seed=seed):
counts = mcts.search(seed, prefix, expect, noise=True)
pi = counts / counts.sum()
a = int(rng.choice(len(pi), p=pi)) if step < args.explore_steps else int(np.argmax(counts))
return a, pi

d, stats, ret = run_episode(env, seed, choose, args.gamma, args.reward_scale)
for d, stats, ret in results:
buffer.extend(d)
rets.append(ret)
slow.append(-ret / max(1, stats["placed"]))
Expand All @@ -177,6 +216,9 @@ def choose(obs, mask, prefix, expect, step, seed=seed):
print(json.dumps(rec))
ck = {"model": net.state_dict(), "d_model": args.d_model, "env": ENV_KW, "args": vars(args), "log": log}
atomic_write(out, lambda p: torch.save(ck, p))
if pool:
pool.close()
pool.join()
print("saved", out)


Expand Down
Loading