Repository navigation
[RLlib] Fix MultiAgentEpisode declaring termination when a new agent joins as the last known agent terminates - #66913
Conversation
There was a problem hiding this comment.
Code Review
This pull request ensures that newly observed agents in the current step are considered when determining if a multi-agent episode should terminate, preventing premature termination when a new agent joins as another terminates. A unit test was added to verify this behavior. The review feedback suggests optimizing the termination check by using dictionary key views to avoid intermediate set allocations.
| if all(aid in set(agents_done) for aid in self.agent_ids): | ||
| # this episode as terminated. Agents observed for the first time in this step | ||
| # count as well: they are only added to `self.agent_episodes` further below. | ||
| if all(aid in agents_done for aid in self.agent_ids | set(observations)): |
There was a problem hiding this comment.
We can optimize this check by using dictionary key views directly instead of constructing intermediate sets. Since self.agent_episodes and observations are both dictionaries, their .keys() views support set operations (like union |) in Python 3. Using self.agent_episodes.keys() | observations.keys() avoids calling the self.agent_ids property (which creates a new set) and calling set(observations) (which creates another set), reducing unnecessary object allocations in add_env_step, which is called at every environment step.
| if all(aid in agents_done for aid in self.agent_ids | set(observations)): | |
| if all(aid in agents_done for aid in self.agent_episodes.keys() | observations.keys()): |
There was a problem hiding this comment.
Applied in a090655: the check now uses self.agent_episodes.keys() | observations.keys(), which avoids the two temporary sets. Behavior is the same, since agent_ids is set(self.agent_episodes.keys()). test_multi_agent_episode.py (19) and test_multi_agent_env_runner.py (5) pass.
WiemKhlifi
left a comment
There was a problem hiding this comment.
Thanks for the contribution, LGTM. The fix matches what I had locally, and I already checked the fix against my custom environment.
One suggestion for the test: a fix that only checks observations.keys() passes both cases here but would end the episode on any step where no agent observes.
This case catches it and passes on this branch:
def test_add_env_step_without_observations_keeps_episode_open(self):
# A step in which the only live agent does not observe must not end the episode.
episode = MultiAgentEpisode(agent_module_ids={"a0": "p"})
episode.add_env_reset(observations={"a0": np.zeros(1)}, infos={"a0": {}})
episode.add_env_step(
observations={},
actions={"a0": 0},
rewards={},
terminateds={"__all__": False},
truncateds={"__all__": False},
)
self.assertFalse(episode.is_done)Guards against a Case 2 check that only considers agents observed in the current step, which would end the episode whenever no agent observes. Suggested-by review on ray-project#66913. Signed-off-by: Akshaay <[email protected]>
|
This pull request has been automatically marked as stale because it has not had 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. |
…67863) ## Why are these changes needed? When every agent is done after `MultiAgentEpisode.add_env_step()`, the "Case 2" block sets `self.is_terminated = True` regardless of *why* the agents are done. A fully truncated episode (the common time-limit case, `truncateds={"__all__": True}`) is therefore reported as **both** terminated and truncated: ```python e = MultiAgentEpisode(observations=[{"a": 0, "b": 0}]) e.add_env_step(..., terminateds={"__all__": False}, truncateds={"a": True, "b": True, "__all__": True}) e.is_terminated, e.is_truncated # (True, True) on master ``` Because `add_env_step()` sets each agent's flag as `terminateds.get(agent_id) or self.is_terminated`, the wrong flag also reaches every agent's `SingleAgentEpisode`. Training code that reads it then treats time-limit truncations as true terminal states and does not bootstrap the value of the last observation: - `AddOneTsToEpisodesAndTruncate` (PPO/GAE value targets) reads `sa_episode.is_terminated`. - `MultiAgentEpisodeReplayBuffer` reads `ma_episode.is_terminated` before the truncated flag, so the last transition of every agent gets `TERMINATEDS=True, TRUNCATEDS=False`. This change makes Case 2 declare the episode terminated only if at least one agent terminated (at this or a prior timestep), and truncated if all agents were only truncated. Episodes that mix terminated and truncated agents still count as terminated, as the existing comment describes, and the `__all__` handling (Case 1) is unchanged. This was flagged in #67627, which fixes `get_truncateds()["__all__"]` but leaves this block alone. With both PRs merged, `get_terminateds()` and `get_truncateds()` are correct for fully truncated episodes. ## Not a duplicate - #67627 fixes only `get_truncateds()` returning `is_terminated` for `"__all__"`. It points out this bug but doesn't change it. - #66913 changes *which* agents the Case 2 check considers (agents joining in the same step). It doesn't change *what* Case 2 decides. The two PRs edit the same lines, so whichever merges second needs a small rebase. - No open issue covers this. ## Known limitation (out of scope) In the mixed case (one agent terminated and another truncated at the same step, without `__all__`), the episode is terminated and that flag is still propagated to the truncated agent's `SingleAgentEpisode`. That's existing behavior, and changing the propagation could interact with #66913's newcomer handling, so I left it for a follow-up. ## Testing Added `test_add_env_step_all_agents_done_terminated_vs_truncated`. It covers: all agents truncated with and without `__all__`; agents truncated at different timesteps; mixed terminated/truncated at the same step and across steps; and all agents terminated. It fails on master (`AssertionError: True is not false`) and passes with this change. `ray.init()` in the test class's `setUpClass` hangs on my local macOS machine, so I ran the `TestMultiAgentEpisode` cases through `unittest` with `ray.init` stubbed out (the episode tests don't use Ray; I excluded the env-runner test): ``` TestMultiAgentEpisode (18 tests): Ran 18 tests ... OK pytest python/ray/rllib/utils/replay_buffers/tests/test_multi_agent_episode_buffer.py \ python/ray/rllib/utils/replay_buffers/tests/test_multi_agent_prio_episode_buffer.py 7 passed pre-commit run --files <changed files>: passed ``` CI runs the full test file, including the env-runner test. ## AI assistance AI assistance (Claude Code) was used to find the issue, write the fix and the test, and draft this description. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Mark Towers <[email protected]> Co-authored-by: Mark Towers <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
…joins as the last known agent terminates self.agent_ids (== self.agent_episodes.keys()) is read before newly observed agents are added to self.agent_episodes in add_env_step(), so a brand-new agent's first observation arriving on the same env step that finishes off all previously registered agents was invisible to the Case 2 check. This made the episode terminate even though the env reported terminateds["__all__"] = False and the new agent is alive. Exclude agents observed for the first time this step (and not themselves terminated/truncated) from the Case 2 'all known agents done' check. Signed-off-by: Akshaay <[email protected]>
…eproduction as the test Count agents observed in this step in the Case 2 check, as suggested by the issue reporter, instead of tracking newly joined live agents separately. Behavior is unchanged. The regression test now uses the reporter's reproduction, and the "newcomer already done" case uses __all__=False so it exercises Case 2 rather than passing through the __all__ check. Signed-off-by: Akshaay <[email protected]>
…check Use self.agent_episodes.keys() | observations.keys() instead of the self.agent_ids property and set(observations), as suggested by gemini-code-assist on this PR. Dict key views support set union directly, so this skips two intermediate set allocations without changing behavior. Signed-off-by: Akshaay <[email protected]>
Guards against a Case 2 check that only considers agents observed in the current step, which would end the episode whenever no agent observes. Suggested-by review on ray-project#66913. Signed-off-by: Akshaay <[email protected]>
f3e88a0 to
14b6002
Compare
Description
MultiAgentEpisode.add_env_step()declares the episode terminated when a new agent's first observation arrives on the same step that the last registered agent terminates, even though the env reportsterminateds["__all__"] = False. The "Case 2" check (all agents done) only looks atself.agent_ids, and the newcomer is added toself.agent_episodeslater in the same method, so it can't keep the episode open. Its observation is discarded, and withbatch_mode="truncate_episodes"theMultiAgentEnvRunnerthen steps the still-live env with an empty action dict.This applies the fix @WiemKhlifi suggested in #66781: count agents observed in this step in the Case 2 check. Following review, it uses the dicts' key views to avoid building temporary sets:
A newcomer that's already terminated or truncated on its first observation is in
agents_done, so an episode where every agent is done still terminates as before.Related issues
Fixes #66781
Additional information
Tests.
test_add_env_step_new_agent_joining_as_last_agent_terminatesinrllib/env/tests/test_multi_agent_episode.pyhas two cases:assertFalse(episode.is_terminated); with this change it passes, withagent_ids == {"a0", "a1"}and__all__False.__all__=False. The episode must still terminate. This catches an over-broad fix that skips Case 2 whenever a new agent appears; I checked that such a variant fails it.Run against the Ray 2.59.0 wheel (with torch) with this branch's
multi_agent_episode.py: 24 passed (19 + 5) on this branch, and on master only the new test fails.black(22.10.0) andruff(0.8.4) are clean on both files.Not a duplicate. No other PR references #66781 or changes this check (
gh pr list --state open --search "66781 in:body"and an area search onMultiAgentEpisodetermination). @WiemKhlifi offered to open a PR in the issue, and @mayankdas2005 asked to take it on 2026-10-08; neither has opened one. @WiemKhlifi, if you'd rather submit your own, I'm happy to close this one.AI assistance. AI assistance was used to write this change and its test. I reviewed every changed line and ran the tests above.