Repository navigation
Parallel self-play workers for paper training - #3
Conversation
Self-play episodes run in --workers processes (CPU MCTS); gradient updates stay on --device. Per-episode search RNG is seeded from the episode seed, so results are identical for any worker count. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Reviewer's GuideAPIExpose
ImplementationRun each self-play episode with its own seeded MCTS RNG in worker processes, load the current model weights, and collect episode results before training continues.
DocumentationDocument CPU-parallel self-play and a GPU-backed fast-training configuration, including worker-count guidance.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 6 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="paper/train.py" line_range="195" />
<code_context>
# 2-3. self-play + training ------------------------------------------------
- mcts = MCTS(net, ENV_KW, device, sims=args.sims, gamma=args.gamma, reward_scale=args.reward_scale, rng=rng)
+ workers = args.workers or max(1, (os.cpu_count() or 2) - 1)
+ pool = (mp.get_context("spawn").Pool(workers, _worker_init, (args.d_model, 1)) if workers > 1 else None)
+ if pool is None:
</code_context>
<issue_to_address>
**Excess workers exhaust resources**
When `--workers 0` resolves to more workers than episodes or the host can support, `workers` is set from the host CPU count and `Pool` starts every process; each initializes PyTorch, an environment, and a model, so surplus workers waste startup time and memory and can exhaust process or memory limits before self-play completes.
Cap the resolved worker count by the episode count and available resources.
Also at `paper/train.py:196`.
</issue_to_address>
### Comment 2
<location path="paper/train.py" line_range="204" />
<code_context>
- 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]
rets, slow = [], []
- for _ in range(args.episodes):
</code_context>
<issue_to_address>
**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.
</issue_to_address>
### Comment 3
<location path="paper/train.py" line_range="204" />
<code_context>
- 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]
rets, slow = [], []
- for _ in range(args.episodes):
</code_context>
<issue_to_address>
**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.
</issue_to_address>
### Comment 4
<location path="paper/train.py" line_range="147" />
<code_context>
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,
+ help="parallel self-play processes (0 = all cores but one); results do not depend on it")
ap.add_argument("--device", default="cpu")
</code_context>
<issue_to_address>
**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`.
</issue_to_address>
### Comment 5
<location path="paper/README.md" line_range="69" />
<code_context>
+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).
+
+ zig build lib -Doptimize=ReleaseFast
</code_context>
<issue_to_address>
**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.
</issue_to_address>
### Comment 6
<location path="paper/train.py" line_range="204" />
<code_context>
- 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]
rets, slow = [], []
- for _ in range(args.episodes):
</code_context>
<issue_to_address>
**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.
</issue_to_address>|
|
||
| # 2-3. self-play + training ------------------------------------------------ | ||
| mcts = MCTS(net, ENV_KW, device, sims=args.sims, gamma=args.gamma, reward_scale=args.reward_scale, rng=rng) | ||
| workers = args.workers or max(1, (os.cpu_count() or 2) - 1) |
There was a problem hiding this comment.
🟡 Medium · Excess workers exhaust resources
When --workers 0 resolves to more workers than episodes or the host can support, workers is set from the host CPU count and Pool starts every process; each initializes PyTorch, an environment, and a model, so surplus workers waste startup time and memory and can exhaust process or memory limits before self-play completes.
Cap the resolved worker count by the episode count and available resources.
Also at paper/train.py:196.
Prompt for AI agents
In `paper/train.py` at line 195:
**Excess workers exhaust resources**
When `--workers 0` resolves to more workers than episodes or the host can support, `workers` is set from the host CPU count and `Pool` starts every process; each initializes PyTorch, an environment, and a model, so surplus workers waste startup time and memory and can exhaust process or memory limits before self-play completes.
Cap the resolved worker count by the episode count and available resources.
Also at `paper/train.py:196`.| 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] |
There was a problem hiding this comment.
🟡 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.| 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] |
There was a problem hiding this comment.
🟡 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.| 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, |
There was a problem hiding this comment.
⚪ 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`.| 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). |
There was a problem hiding this comment.
⚪ 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.| 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] |
There was a problem hiding this comment.
🟡 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.…nd in spawned workers) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
paper/train.py:--workers N(0 = all cores but one) runs self-play episodes in parallel processes; training stays on--device(e.g. cuda).paper/README.md: fast-run section for GPU / many-core machines.Note: runs differ from older checkpoints with the same
--seed(RNG is now per episode).🤖 Generated with Claude Code
Summary by Sourcery
Enable reproducible parallel self-play training across multiple CPU workers while retaining device-based gradient updates.
New Features:
Enhancements:
Documentation: