Skip to content

[RLlib] Sync newly cloned self-play module weights immediately - #67103

Open
lindicaphxag-tech wants to merge 6 commits into
ray-project:masterfrom
lindicaphxag-tech:fix/rllib-selfplay-sync-new-module-weights-61960
Open

lindicaphxag-tech wants to merge 6 commits into
ray-project:masterfrom
lindicaphxag-tech:fix/rllib-selfplay-sync-new-module-weights-61960

Conversation

@lindicaphxag-tech

@lindicaphxag-tech lindicaphxag-tech commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #61960. Newly created self-play opponents are initialized by Algorithm.add_module() on EnvRunners, while the intended cloned weights come from the existing source policy. Activating a new policy mapping before installing those source weights can route episodes to default-initialized opponents.

Mechanism

  • Correct provenance: snapshot the existing source module state before add_module(), rather than reading the new module's default state afterward.
  • First-install semantics: publish a module-specific COMPONENT_RL_MODULE payload without WEIGHTS_SEQ_NO, because the global sequence gate may skip an uninitialized module whose EnvRunner already holds the current global version.
  • Atomic per-runner order: one foreach_env_runner callback installs weights with set_state() and only then activates policy_mapping_fn and policies_to_train. Two separate calls could hit different healthy runner sets during recovery.
  • Initial league parity: apply the same install-before-map contract to the first three league clones as to later opponents.
  • This is a scoped self-play initialization/order fix, not a claim of a general distributed transaction protocol or complete recovery-state synchronization.

Regression coverage

  • Callback regression uses distinct source and default-initialized new-module states, captures the published source state, and executes the callback to assert actual set_state → mapping order.
  • First-league initialization regression verifies all three cloned opponents receive the forced module-only state before mapping activation.
  • Production-method regression invokes MultiAgentEnvRunner.set_state() on a lightweight mock: an equal-sequence update is skipped, whereas a module-only unversioned update is applied without changing the global version.
  • Independent native RLlib/fork tests provide additional focused evidence; upstream integration remains the acceptance gate.

Validation (2026-10-23; current head)

  • Head: 7795d644673b4a4ed4d407fd9e7b0ca981e9606b.
  • DCO and Cursor Bugbot: passed.
  • Buildkite Release #111931 and ReadTheDocs #4616219: passed.
  • Buildkite Microcheck #56950: failed. Failing shard/step logs are not available through this integration; the cause has not been attributed to code or infrastructure. Not merge-ready on CI evidence.
  • A separate fork experiment identified a possible EnvRunner recovery configuration issue; that candidate change is not included in this upstream PR and is not claimed as fixed here.

@lindicaphxag-tech
lindicaphxag-tech marked this pull request as ready for review October 16, 2026 04:06
@lindicaphxag-tech
lindicaphxag-tech requested a review from a team as a code owner October 16, 2026 04:06

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request ensures that newly cloned opponent modules in the self-play league-based callback have their weights synchronized immediately to prevent playing with stale weights, and adds a unit test to verify this. The review feedback correctly identifies that sync_weights must explicitly specify from_worker_or_learner_group=algorithm.learner_group and inference_only=True to avoid propagating default/random weights from the local EnvRunner, and suggests updating the test assertion accordingly.

Copy link
Copy Markdown
Contributor Author

Addressed the review feedback. The new module is now synchronized explicitly from algorithm.learner_group with inference_only=True, avoiding the local EnvRunner's newly initialized weights as the sync source. Updated the regression assertion to require both arguments.

@cursor cursor 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.

Stale Bugbot comment from a previous run.

Copy link
Copy Markdown
Contributor Author

Addressed the review feedback in the latest commit. The cloned module is now synchronized directly through EnvRunner.set_state() with a module-only state that intentionally omits WEIGHTS_SEQ_NO, so the first initialization cannot be discarded by the global sequence gate. The regression test now verifies the forced state path and object-store reference. This keeps the fix scoped to newly cloned self-play modules without changing global weight-version semantics.

@cursor cursor 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.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit e383e4c. Configure here.

@ray-gardener ray-gardener Bot added rllib RLlib related issues community-contribution Contributed by the community labels Oct 16, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. The latest commit addresses the synchronization-source and sequence-gate concerns: the newly cloned module is initialized from the learner-side state, then pushed through the module-only EnvRunner state path without WEIGHTS_SEQ_NO, so first initialization cannot be discarded by an already-current global sequence number. The regression test covers this forced initialization path. Please re-review the latest commit when convenient.

@lindicaphxag-tech
lindicaphxag-tech force-pushed the fix/rllib-selfplay-sync-new-module-weights-61960 branch from f0bed32 to 9b632d8 Compare October 17, 2026 13:40
@lindicaphxag-tech
lindicaphxag-tech force-pushed the fix/rllib-selfplay-sync-new-module-weights-61960 branch from 9b632d8 to 9ba8e0d Compare October 17, 2026 13:40

Copy link
Copy Markdown
Contributor Author

CI/review follow-up on the latest single-commit head 9ba8e0d19946a14582f840791afc0e805e5f9073: I squashed the earlier incremental history without changing the final source/test tree, and the DCO check now passes. Buildkite Release #111155 and ReadTheDocs #4587374 pass, but the exact-head Buildkite Microcheck #56475 reports failure. I could not retrieve the failing step logs from this integration, so I am not assuming whether the failure is caused by the change or infrastructure. Could a maintainer please point me to the failing job/trace or advise whether a rerun is appropriate? The scoped invariants are still learner-sourced clone state, forced first install without WEIGHTS_SEQ_NO, and mapping update after state sync.

Copy link
Copy Markdown
Contributor Author

I strengthened the callback regression so it executes the mocked foreach_env_runner callbacks synchronously and asserts the actual event order (set_state before multi_agent mapping), rather than only checking the order of mock calls. I also formatted the new test import and wrapped the new comments. Current head is 29fa5e5d2a01b90b0bb7ceb4a1b51e4e7ade1f4f; DCO and Release pass, while Microcheck #56519 is pending. The older failed run is not being treated as an infrastructure flake; I’ll use the exact-head result before drawing conclusions.

Copy link
Copy Markdown
Contributor Author

Follow-up on the latest two-file PR head 4444ffc (one replacement commit, DCO now success):

I audited the first-time self-play initialization branch as well as the later-clone path. The original sync_weights(policies=[...]) in first initialization uses the default asynchronous path; in the current implementation foreach_actor_async_fetch_ready fetches previous results before dispatching the new weight update. So neither an ordinary sync_weights() call nor simply passing a timeout can establish that the newly dispatched initialization completed before the callback publishes the policy mapping. The global WEIGHTS_SEQ_NO filter can also reject a first module installation when an EnvRunner is already at that sequence.

The two branches now share one synchronous, module-only EnvRunner.set_state install for either the three initial clones or a later new opponent; the mapping change is applied afterward. This uses the same force-update contract as the existing later-clone fix and does not change Learner/global version mechanics. The native test now covers initial cloning, source weights and installation-before-mapping order in addition to the existing subsequent-clone tests.

Source-driven CPU regression: Success, independent fork CI PR #6: executes the production SelfPlayLeagueBasedCallback.on_train_result and MultiAgentEnvRunner.set_state method bodies with a delayed asynchronous weight-publish schedule. The previous official PR head 36945af allows first-mapping publication before installation; the new head installs all three clones before the mapping. This is not a live multi-actor timing or training-performance claim.

The final source tree was preserved exactly while squashing the two incrementals into a correctly author-matched Signed-off-by: Zhibo Zhang <[email protected]> commit to clear the Ray DCO gate. Buildkite Microcheck for this latest head is still pending; I won't label it merge-ready until that result and review are resolved.

Copy link
Copy Markdown
Contributor Author

CI status update for exact current PR head 4444ffcd555d2cc211f7b6e3bfb13a9d16fea918: DCO, Release and docs checks passed, but Buildkite Microcheck #56887 has now finalized Failure. I cannot read the individual failing job/trace via the available Buildkite access; I am not classifying it as an infrastructure flake or a code regression without those logs.

As independent positive evidence, fork GitHub Actions #39815603690 completed successfully. It executes the production method bodies of SelfPlayLeagueBasedCallback.on_train_result, EnvRunnerGroup.foreach_env_runner and MultiAgentEnvRunner.set_state with deterministic local/remote actor objects. Both runners install initial opponent weights before policy-mapping publication; an unchanged pre-fix snapshot reproduces the wrong ordering. It does not replace the full Ray multi-actor tests.

Could a maintainer identify the failing Microcheck job and its first actionable traceback (or advise whether a rerun is appropriate)? I'd prefer fixing that exact blocker rather than broadening a two-file production/test diff or repeatedly pushing blind CI changes. No additional upstream commit is needed just to reference this evidence.

Copy link
Copy Markdown
Contributor Author

Updated official head: 639c812 (2-file, DCO-passing single signed commit). This supersedes the earlier two-foreach-call version while retaining its weight-source and first-install semantics.

Source audit found an additional race in the earlier design: EnvRunnerGroup.foreach_env_runner reselects healthy remote actors on each call. If a remote runner recovers between (1) install cloned weights and (2) publish the new policy mapping, it may be in the second healthy set but not the first, so it could receive a mapping that references uninstalled opponent weights. The earlier ordering test with a fixed actor set could not exclude this.

The candidate now uses one synchronous callback per EnvRunner, calling set_state(module-only weights) immediately before config.multi_agent(mapping) on the same runner. This enforces the needed per-runner order across worker-health changes and removes one separate dispatch. It does not claim atomic rollout publication across the entire cluster.

Evidence: passing CPU red/green GitHub Actions #39820293020, fork-only source/health-change test #7. The fixture executes the actual SelfPlayLeagueBasedCallback.on_train_result, EnvRunnerGroup.foreach_env_runner, and MultiAgentEnvRunner.set_state bodies. With remote2 recovering after the first dispatch, the unchanged previous PR head 4444ffc gives remote2 a mapping without clone weights; the new per-runner callback cannot do so. It checks Ruff, compilation and original-vs-patched method execution. No live Ray cluster incident or full integration-test pass is claimed.

Review scope: the improvement over 4444ffc is only +12/−15 lines in the callback and +2/−1 lines in existing native tests; the more elaborate recovered-actor regression remains on the fork, keeping this official PR's Diff focused. Ray current commit.

Current checks: DCO and Release success; new exact-head Microcheck #56891 pending. The previous head's Microcheck #56887 failed but its failing job trace isn't available through my connection, so I am not guessing whether this new patch addresses that failure. I'd appreciate the failing job/trace if #56891 also fails and a maintainer re-review of the per-runner activation contract.

Clone the existing behavior policy's state, not the default weights of a
newly added local opponent. For both initial and later opponents, install
source weights and publish the mapping in one synchronous per-runner call,
including when the remote healthy set changes between separate dispatches.
Native regression tests model a fresh module with different default weights,
reject accidental weight substitution, and check first-init/mapping order.

Signed-off-by: Zhibo Zhang <[email protected]>
@lindicaphxag-tech
lindicaphxag-tech force-pushed the fix/rllib-selfplay-sync-new-module-weights-61960 branch from 639c812 to 7795d64 Compare October 23, 2026 04:51

lindicaphxag-tech commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Native regression fixed on current PR head 7795d64 (still two changed files, one correctly signed commit; DCO and Release now pass).

An actual RLlib pytest run exposed a production correctness regression that source-extracted ordering tests missed: on the later-clone path, algorithm.add_module() creates a new local module with default parameters, but the previous implementation built module_states from multi_rl_module[new_mod_id].get_state() instead of the existing source behavior policy. This could publish random/uninitialized weights despite the learner clone receiving the correct source state.

The fix snapshots source_module_state = multi_rl_module[module_id].get_state() before adding the new opponent, and uses that exact snapshot for both the learner state and the synchronous per-EnvRunner initialization. The native test now deliberately makes the newly created module's default weights different and asserts its get_state() is never read for cloning.

Reproducible native red/green: passing fork CI #39902396461, with a released Ray 2.59.0 binary wheel as the native extension/runtime and the candidate callback/test files overlaid in a fresh runner: 4/4 native tests passed. Replacing only the callback with the unchanged previous official head 639c812 makes the same clone-source test fail as expected (attempted read of the default-initialized module). The separate source-extracted actor-recovery and Ruff CI also passed. These test environments are not a full same-revision Ray 3.0 build or live multi-actor training run.

The current upstream head's new Buildkite Microcheck #56950 is pending; earlier Microchecks failed, and their private job trace remains unavailable to me, so I am not claiming the patch eliminates every CI failure. If #56950 fails, could a maintainer please point to the first actionable failing job/log for a focused fix?

Stronger real-Ray-actor follow-up (2026-10-23): GitHub Actions #39903425393 — Success, fork-only script. This goes beyond source-extracted simulation: the test starts an actual local Ray cluster, two real remote actors, the released native _raylet extension, the actual FaultTolerantActorManager healthy-actor filter, and production EnvRunnerGroup.foreach_env_runner, MultiAgentEnvRunner.set_state, and SelfPlayLeagueBasedCallback.on_train_result. With remote2 deliberately marked unhealthy for the first dispatch and healthy before the second, the unchanged two-call official PR snapshot 4444ffc demonstrably gives remote2 the new mapping without copied opponent weights. On current candidate 7795d64, activation is per-runner within one RPC; remote1 installs the correct clone before activation, while remote2 correctly has neither weights nor the new mapping. This is a genuine Ray Actor RPC test, but the unhealthy→healthy transition is controlled in the test (not a simulated process crash/restart), policy modules contain deterministic scalar weights, and the wheel runtime is Ray 2.59.0 rather than a same-commit Ray 3.0 source build. It does not prove RL reward improvement or full Buildkite compatibility.

pseudo-rnd-thoughts pushed a commit that referenced this pull request Nov 4, 2026
…ts, bounded game-server startup (#67594)

Before this PR:
- The `learning_tests_appo_footsies_*` postmerge tests time out often.
Each Learner update takes `4096 * num_env_runners` = 81,920 env steps at
`lr=1e-4`, but the game server answers one env step per 60 FPS frame
(~57 steps/s per EnvRunner). The policy gets its first gradient update
after ~3 minutes, and the target network never updates. Against the
frozen copy the training win rate stays at 0.5, so the test passes only
when a 10-episode eval happens to exceed 0.8 (e.g. eval 0.81 at training
win rate 0.49).
- `MixManagerCallback` initializes each new frozen opponent with
`Algorithm.set_state()`. The EnvRunners skip those weights because the
weights version doesn't change (#67131 fixes that in the Learner). The
training EnvRunners therefore play the opponent's random init, while
evaluation uses the real copy.
- If a game server never gets ready,
`FootsiesBinary.start_game_server()` polls forever (no deadline, no
liveness check, no gRPC timeout), and setup hangs until the 900 s
timeout. In a stress test, 3 of 240 concurrent server starts never got
ready.

After this PR:
- 2048 env steps per Learner update, minibatches of 256, `lr=5e-4`,
`target_network_update_freq=0.5`.
- `MixManagerCallback` pushes the copied weights to all (eval)
EnvRunners. An eval round without a decisive episode no longer raises a
`KeyError`.
- The game server gets 120 s to get ready (5 s gRPC timeouts, process
liveness check); otherwise it's killed and relaunched, up to 3 times.

Validation on Anyscale (nightly image + this PR's three files, no
#67131), each seed the CI test's args in a fresh driver with a 900 s cap
including startup:

| CI target | hardware | passed | wall time |
|---|---|---|---|
| `learning_tests_appo_footsies_single_gpu` | 4×L4, 48 vCPU | 10/10 |
174–419 s |
| `learning_tests_appo_footsies_multi_gpu` | 4×L4, 48 vCPU | 10/10 |
239–422 s |
| `learning_tests_appo_footsies_single_gpu_no_aggregator_actors` | 4×L4,
48 vCPU | 10/10 | 174–418 s |
| `multi_gpu` args, 2 Learners on 2 nodes (1×L4 each) + CPU EnvRunner
nodes | 4 nodes | 10/10 | 217–357 s |

Stock master on a 1×L4 node passed 1 of 1 attempt by eval luck, and
`+#67131` alone failed in 1,500 s. A 4 h run on the 4-node cluster kept
Learner, aggregator, EnvRunner and Algorithm memory flat. The
game-server launcher fix started 360/360 servers in a stress test,
relaunching one server twice. `pre-commit run --files` passes on all
three files.

Not a duplicate: no open PR touches the footsies example. #67131 fixes
the weights-version root cause in `Learner.set_state`, and #67103 only
fixes the league-based self-play callback; this PR doesn't depend on
either.

AI assistance (Claude Code) was used for the investigation, the
experiments and the change.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Artur Niederfahrenhorst <[email protected]>
Signed-off-by: Artur Niederfahrenhorst <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

Keeping this scoped two-file self-play correctness patch active while the upstream Microcheck blocker is triaged. The current signed head 7795d64 still installs source-policy weights on each EnvRunner before publishing the new mapping, including initial clones. The independent native regression for this head passed 4/4 tests (linked in the PR description); it does not replace upstream integration CI.

Could a maintainer identify the first actionable failing step/traceback in Microcheck #56950, or confirm whether a targeted rerun is appropriate? I will keep changes focused on that result rather than expanding scope or guessing at CI failures.

@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Nov 18, 2026
@lindicaphxag-tech

Copy link
Copy Markdown
Contributor Author

Converting this to draft. The blocker has been Buildkite Microcheck on every head since 10-17 (#56475, #56887, #56891, #56950), and its failing job traceback is not accessible from this account, so each revision after the first has been pushed without knowing which step failed. That is not a healthy loop: it produced a native RLlib regression on one head that source-extracted tests missed, which I caught and fixed, but the current head 7795d64 is unverified against upstream integration CI.

What is settled: the diff is two files, DCO and Release pass, the fix is per-EnvRunner installation of source-policy weights before publishing the new mapping, and there is a reproducible red/green on the fork (4/4 native tests, real Ray-actor recovery case). What is not settled: Ray appears to require a maintainer present at the pilot stage, and no maintainer has responded in 6 weeks, so leaving this as an open merge request just adds queue noise.

Keeping it as a draft rather than closing, because the technical record is worth keeping. If a maintainer can share the first actionable Microcheck failure, I will rebase onto current main and finish it; otherwise it stays parked.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community rllib RLlib related issues unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

1 participant