Skip to content

Parallel self-play workers for paper training - #3

Merged
dev0Guy merged 4 commits into
mainfrom
parallel-selfplay
Nov 25, 2026
Merged

dev0Guy merged 4 commits into
mainfrom
parallel-selfplay

Conversation

@dev0Guy

@dev0Guy dev0Guy commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner
  • paper/train.py: --workers N (0 = all cores but one) runs self-play episodes in parallel processes; training stays on --device (e.g. cuda).
  • Each episode's MCTS RNG comes from its own seed → identical results for any worker count (checked: 1 vs 3 workers give the same log; ~3–10× faster per iteration).
  • 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:

  • Add configurable parallel self-play workers to accelerate CPU-bound MCTS while keeping model training on the selected device.
  • Make episode search randomness independently seeded so training results remain consistent across worker counts.

Enhancements:

  • Improve worker-process environment setup and provide CPU/GPU fast-run guidance for paper training.

Documentation:

  • Document parallel self-play usage, resource tuning, and worker-count reproducibility.

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>
@sourcery-ai

sourcery-ai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

API

Expose --workers as the self-play process-count option, with zero selecting the available CPU cores minus one.

  • paper/train.py L147-148

Implementation

Run 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.

  • paper/ptrmcts.py L34, L43-49
  • paper/train.py L79-115, L195-207 (+2 small edits)

Documentation

Document CPU-parallel self-play and a GPU-backed fast-training configuration, including worker-count guidance.

  • paper/README.md L63-78

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread paper/train.py Outdated

# 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)

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 · 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`.

Comment thread paper/train.py
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.

Comment thread paper/train.py
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 · 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.

Comment thread paper/train.py
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`.

Comment thread paper/README.md
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.

Comment thread paper/train.py
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 · 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.

dev0Guy and others added 3 commits November 25, 2026 13:46
…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>
@dev0Guy
dev0Guy merged commit 20029cc into main Nov 25, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant