Skip to content

[RLlib] - APPO improvements part 1: learner pipeline performance improvements. - #59544

Merged
simonsays1980 merged 26 commits into
ray-project:masterfrom
simonsays1980:appo-improvements-part-1
Dec 23, 2025
Merged

simonsays1980 merged 26 commits into
ray-project:masterfrom
simonsays1980:appo-improvements-part-1

Conversation

@simonsays1980

@simonsays1980 simonsays1980 commented Dec 18, 2025 •

Copy link
Copy Markdown
Contributor

Description

APPO targets high-throughput RL and relies on asynchrony - via actor parallelism and multi-threading. In our tests, the local-learner setup (num_learners=0) underperformed, prompting a deeper investigation into root causes and improvements as follows.

Causes

  • Producer-driven + weak backpressure: The data-flow was producer-driven. There was no bounded, blocking handoff to pace producers. The in-queue for the LearnerThread was a deque which is unblocking. As a result, the Learner wasn't setting the pace (sawtooth throughput and stalls at 20-update barrier, i.e. learner starved; furthermore: CPU-waste and hot GIL when polling from empty queues).
  • Thread contention at multiple places: Learner and _LearnerThread shared the _num_updates_lock and metrics._threading_lock (RLock). Every update both threads contended on the same lock. Every 20 updates occasionally both threads contended on the other shared lock.
  • Global timesteps, race condition: update() wrote a global _CURRENT_GLOBAL_TIMESTEPS and the _LearnerThread had to read it later. Rapid calls to update() could overwrite this before the thread consumes it, i.e. timesteps can mismatch the batch actually trained.
  • Aggregation race + spurious reduces: The "every 20-updates" path checked a copy of _num_updates without synchronization, then reset it at >=20 - but without any threading event/condition to align the producer with the consumer. This returned often {} or reduce at odd times.
  • No pinned memory or stream handoff: GPU-copies used pin_memory=False and there was no explicit stream handoff; any implicit sync may land inside of the learner update timing.
  • Reference resolving on producer's hot path: TrainingData.solve_refs() was called synchronously inside LearnerGroup.update() before queuing which cost sometimes around ~25% of time in some calls. Extends the window where producer/learner can drift.
  • Mixed queue semantics + missing task semantics: The code mixed queue.Queue and deque (and optionally CircularBuffer). task_done/join() semantics don't exist for deque, correctness relies on polling and manual drops. There was no bounded, blocking handoff to pace producers. This was brittle under load.
  • No clean stop path: The thread used a stop flag but no sentinel was enqueued, if it was blocked/polling the shutdown could hang or increment counters after a stop.
  • Complete multi-learner stalling: In multi-learner setups with multi-agent policies asynchronous batches (i.e. batches with different combinations of policies) led to stalls in Torch's DistributedDataParallel gradient asynchronous synchronization. One rank computed gradients for a policy not existent on the other rank(s) and waited indefinitely for synched gradients.

Improvements by this PR

  • Consumer-driven: Learner dictates pace through blocking queues (Learner does get(), producer does put). That avoids busy polling (no CPU burn). Faster reloading through quick returns from Learner.update() with no results ready. Avoids learner starving - bigger queues allow for frequent producer burstiness.
  • Edge-triggered aggregation: Only _LearnerThread increments a private counter and on exactly the broadcast_intervalth update fires an event (_agg_event). The producer simply waits for the event and clears it (no lock fight). Furthermore, the _LearnerThread now reduces metrics and returns them through an out-queue from which the Learner picks them up and returns them to the main process. All of these measures reduce thread contention to an absolute minimum.
  • Pass meta-data with batch: The Learner enqueues a tuple (batch, timesteps) so the _LearnerThread consumes the correct timesteps atomically. This also reduces communication and boilerplate.
  • (Optional) Deferral of reference resolving: Post-solve references in Learner.update() to return faster in asynchronous calls.
  • Clean stop + consistent semantics: Use a _STOP_SENTINEL through the learner queue; don't rely anymore on a boolean alone. And call task_done() on real queue.Queue (if not using CircularBuffer). Furthermore unification of buffer/queue API inside Learner.
  • Safe-guarding multi-agent multi-learner training: Manual synchronization of gradients replaces Torch's DistributedDataParallel hooks-based synchronization for multi-learner multi-agent setups. Gradients on each rank are zero-padded and synched after all gradients have been computed.

Related issues

Additional information

Because this PR reshapes the data flow, a few tuning tips are useful:

  • Circular buffer vs. simple queue. The old CircularBuffer prevented learner starvation but its push/pop are slower. The new consumer-driven pipeline is generally more efficient - assuming producers are reasonably fast and the learner queue isn’t tiny. Use use_circular_buffer=True only when producing is expensive/irregular (it lets the learner keep iterating over buffered data, similar to num_epochs > 1 but in cycles). Otherwise, prefer the simple queue. Recommended defaults: simple_queue_size=32 for APPO; IMPALA keeps a smaller learner_queue_size=3.
  • Unified interval: broadcast & metrics reduction. Previously, weights were synced by broadcast_interval while metrics were reduced every fixed 20 updates. The new design unifies these: broadcast_interval now controls both weight sync and metrics reduction. In practice, ~10 balances steady flow with acceptable off-policy lag.
  • Scale producers to match a fast learner. The _LearnerThread applies updates quickly, so overall throughput is often producer-bound. To feed it well, increase num_env_runners and/or num_envs_per_env_runner.

Next steps

This PR improves dataflow focused on the learner(s). The next steps are:

  • To increase throughput in AggregatorActors
  • To improve dataflow in IMPALA's main thread.
  • To boost performance in loss calculation.
  • To check, asynchronous calls to EnvRunners and Learners.
  • To test resolving references in either _GPULoaderThreads or _LearnerThread instead of the Learner's main thread.

Tests

APPO in this PR was tested on the following (multi-agent) environments:

CartPole-v1

This PR improves performance significantly for high-producer scenarios like CartPole-v1. All tests used:

  • broadcast_interval=10
  • use_circular_buffer=False
  • num_aggregator_actors_per_learner=3
  • num_env_runners=num_learners x 32
  • episodes_to_numpy=False
  • num_gpus_per_learner=1
image (3)

ALE:Pong-v5

All tests used:

  • broadcast_interval=10
  • use_circular_buffer=False
  • num_aggregator_actors_per_learner=6
  • num_env_runners=num_learners x 32
  • episodes_to_numpy=True (FrameStack connector with 4 frames)
  • num_gpus_per_learner=1
image

@simonsays1980
simonsays1980 requested a review from a team as a code owner December 18, 2025 11:45

@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 introduces significant performance improvements to the APPO learner pipeline by refactoring the data flow to be consumer-driven, reducing thread contention, and improving GPU utilization. The changes are well-documented and address several key bottlenecks. My review focuses on ensuring the new implementation is robust and fully realizes the stated performance goals. I've identified a few areas for improvement, including a potential configuration issue, a remaining busy-wait loop, and some code cleanup opportunities.

Comment thread rllib/algorithms/appo/appo_learner.py Resolved
Comment thread rllib/algorithms/appo/utils.py Resolved
@simonsays1980 simonsays1980 added rllib RLlib related issues rllib-algorithms An RLlib algorithm/Trainer is not learning. rllib-multi-agent labels Dec 18, 2025
Comment thread rllib/algorithms/appo/appo_learner.py Resolved
Comment thread rllib/algorithms/appo/utils.py Resolved
Comment thread rllib/algorithms/appo/utils.py Resolved
@simonsays1980
simonsays1980 force-pushed the appo-improvements-part-1 branch from dea286f to 56528a6 Compare December 18, 2025 12:42
Comment thread rllib/algorithms/appo/utils.py Resolved

@pseudo-rnd-thoughts pseudo-rnd-thoughts left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Overall looks great. Large picture questions

  1. Could we have some tests for all three queue types for functionality at minimum
  2. Do we want a protocol or abstract class for the queues to run unnecessary empty function definitions?

Comment thread rllib/algorithms/appo/appo_learner.py Resolved
Comment thread rllib/algorithms/appo/utils.py Resolved
Comment thread rllib/algorithms/appo/utils.py Resolved
Comment thread rllib/algorithms/appo/utils.py Resolved
Comment thread rllib/algorithms/appo/utils.py Resolved
Comment thread rllib/algorithms/appo/utils.py Outdated

def __len__(self) -> int:
"""Return current number of items in buffer."""
with self._write_lock:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Should this rely on read_lock as well which will pop an item

def _to_device_safe(self, batch):
try:
return batch.to_device(self._device, pin_memory=True)
except RuntimeError as e:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Add warning as otherwise we will have no idea that an error occurs

msg = str(e)
if "only dense CPU tensors can be pinned" in msg or "pin_memory" in msg:
return batch.to_device(self._device, pin_memory=False)
raise

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Add full raise error

# If the queue is full, the consumer will wake soon anyway.
pass

def run(self) -> None:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What is this function for?

…ll improvements of Learner dataflow in IMPALA/APPO.

Signed-off-by: simonsays1980 <[email protected]>
@simonsays1980
simonsays1980 force-pushed the appo-improvements-part-1 branch from 3d7d65d to 9e722f4 Compare December 18, 2025 18:54

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

Bug: Race condition in CircularBuffer.get with multiple consumers

The while len(self) == 0 check at line 165 is performed without holding the lock, then the lock is acquired at line 169 to sample. If multiple consumers exist, one thread could exit the while loop seeing items available, but before acquiring the lock another thread could consume all items. This would cause self._rng.choice(list(self._indices)) to fail with a ValueError because the sequence would be empty.

rllib/algorithms/appo/utils.py#L163-L170

# Only initially, the buffer may be empty -> Just wait for some time.
with TimerAndPrometheusLogger(self._metrics_circular_buffer_get_time):
while len(self) == 0:
time.sleep(0.0001)
# Sample a random buffer index.
with self._lock:
idx = self._rng.choice(list(self._indices))

rllib/core/learner/utils.py#L162-L170

"""
# Only initially, the buffer may be empty -> Just wait for some time.
with TimerAndPrometheusLogger(self._metrics_circular_buffer_get_time):
while len(self) == 0:
time.sleep(0.0001)
# Sample a random buffer index.
with self._lock:
idx = self._rng.choice(list(self._indices))

Fix in Cursor Fix in Web


@simonsays1980

Copy link
Copy Markdown
Contributor Author

Overall looks great. Large picture questions

  1. Could we have some tests for all three queue types for functionality at minimum
  2. Do we want a protocol or abstract class for the queues to run unnecessary empty function definitions?

Valid points @pseudo-rnd-thoughts. Let me answer to them separately:

  1. Yes, we should definitely test the queue types (right now there is only the CircularBuffer left the others were from testing). I would do this in a follow-up PR unless you have a very good idea how to test the buffer.
  2. That would be best, but the circular buffer is very specific and holds a deque. Queue would be the class I would like to have as base because I introduced task_done(), etc. such that we have the same interface like Queue does. Queue itself has however no abstract base class.

global _CURRENT_GLOBAL_TIMESTEPS
_CURRENT_GLOBAL_TIMESTEPS = timesteps or {}
# Set the update kwargs passed in the main thread for use in the learner thread.
self._update_kwargs = kwargs

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Race condition with shared _update_kwargs between threads

The _update_kwargs is assigned in the main thread at line 215 and read by _LearnerThread at line 526. If update() is called rapidly, _update_kwargs can be overwritten before the learner thread processes the corresponding batch, causing kwargs to mismatch the batch actually trained. This is the same pattern as the race condition with _CURRENT_GLOBAL_TIMESTEPS that this PR aimed to fix. The kwargs should be passed through the queue alongside the batch and timesteps.

Additional Locations (1)

Fix in Cursor Fix in Web

learner_state[COMPONENT_RL_MODULE]
)
try:
if (_last_num_updates % 0xFF) == 0:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Modulo condition prevents queue size logging

The condition (_last_num_updates % 0xFF) == 0 will almost never be true. At this point, _last_num_updates equals BATCHES_PER_AGGREGATION (typically 10 from broadcast_interval), and 10 % 255 = 10 ≠ 0. This means the learner state queue size logging block never executes. The intention was likely to log periodically, perhaps using a cumulative counter or a bitwise AND (& 0xFF) pattern like line 238.

Fix in Cursor Fix in Web

# Remove any old learner state in the queue.
self.learner._learner_state_queue.get_nowait()
except queue.Empty:
logger.warning("No old learner state to remove from the queue.")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Warning logged incorrectly for normal empty queue state

When attempting to remove an old learner state from _learner_state_queue before adding a new one, a warning is logged if the queue is empty. However, an empty queue is the expected/normal case (no old state to remove), not an error condition. This causes spurious warning messages to appear frequently during normal operation, polluting logs and potentially obscuring real issues.

Fix in Cursor Fix in Web

@pseudo-rnd-thoughts pseudo-rnd-thoughts left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The PR looks great, the comments sense to always answer my question about the code whenever I have it.

I'm going to approve but could you look at my three comments and confirm that the training agent return performance is preserved? You've demonstrated that the throughput significantly improves and I don't see a reason why the agent's return performance would be affected but ML is weird so I want to check

@simonsays1980

Copy link
Copy Markdown
Contributor Author

The PR looks great, the comments sense to always answer my question about the code whenever I have it.

I'm going to approve but could you look at my three comments and confirm that the training agent return performance is preserved? You've demonstrated that the throughput significantly improves and I don't see a reason why the agent's return performance would be affected but ML is weird so I want to check

@pseudo-rnd-thoughts Good point and thanks for checking in on returns for multi-learner setups. I see more a random pattern in that some runs do converge and others do not - this is the same for master and this pr as well as single- and multi-learner setups.

)
try:
if (self.learner._submitted_updates & ~0xFF) != (
self._learner_submitted_updates - BATCHES_PER_AGGREGATION

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Undefined attribute _learner_submitted_updates causes AttributeError

The code references self._learner_submitted_updates in _LearnerThread.step(), but this attribute is never defined on the _LearnerThread class. Looking at line 563, the code correctly accesses self.learner._submitted_updates (via the learner reference), but line 564 incorrectly uses self._learner_submitted_updates. This will cause an AttributeError at runtime when the aggregation condition is evaluated, crashing the learner thread during multi-learner training.

Fix in Cursor Fix in Web

Signed-off-by: simonsays1980 <[email protected]>
if (self.learner._submitted_updates & ~0xFF) != (
self.learner._submitted_updates - BATCHES_PER_AGGREGATION
& ~0xFF
):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Operator precedence bug causes excessive logging

Due to Python operator precedence, - binds tighter than &, so self.learner._submitted_updates - BATCHES_PER_AGGREGATION & ~0xFF is parsed as self.learner._submitted_updates - (BATCHES_PER_AGGREGATION & ~0xFF). Since BATCHES_PER_AGGREGATION (typically 10) & ~0xFF equals 0, the condition becomes (updates & ~0xFF) != updates, which is True 255 out of 256 times. The intended check for crossing a 256-update boundary requires parentheses: ((updates - BATCHES_PER_AGGREGATION) & ~0xFF).

Fix in Cursor Fix in Web

Signed-off-by: simonsays1980 <[email protected]>

@pseudo-rnd-thoughts pseudo-rnd-thoughts left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@simonsays1980
simonsays1980 merged commit 7ae70c5 into ray-project:master Dec 23, 2025
AYou0207 pushed a commit to AYou0207/ray that referenced this pull request Jan 13, 2026
…ovements. (ray-project#59544)

## Description
APPO targets high-throughput RL and relies on asynchrony - via actor
parallelism and multi-threading. In our tests, the local-learner setup
(num_learners=0) underperformed, prompting a deeper investigation into
root causes and improvements as follows.

### Causes
- __Producer-driven + weak backpressure:__ The data-flow was
producer-driven. There was no bounded, blocking handoff to pace
producers. The in-queue for the `LearnerThread` was a `deque` which is
unblocking. As a result, the `Learner` wasn't setting the pace (sawtooth
throughput and stalls at 20-update barrier, i.e. learner starved;
furthermore: CPU-waste and hot GIL when polling from empty queues).
- __Thread contention at multiple places:__ `Learner` and
`_LearnerThread` shared the `_num_updates_lock` and
`metrics._threading_lock` (`RLock`). Every update both threads contended
on the same lock. Every 20 updates occasionally both threads contended
on the other shared lock.
- __Global timesteps, race condition:__ `update()` wrote a global
`_CURRENT_GLOBAL_TIMESTEPS` and the `_LearnerThread` had to read it
later. Rapid calls to `update()` could overwrite this before the thread
consumes it, i.e. timesteps can mismatch the batch actually trained.
- __Aggregation race + spurious reduces:__ The "every 20-updates" path
checked a copy of `_num_updates` without synchronization, then reset it
at `>=20` - but without any threading event/condition to align the
producer with the consumer. This returned often `{}` or reduce at odd
times.
- __No pinned memory or stream handoff:__ GPU-copies used
`pin_memory=False` and there was no explicit stream handoff; any
implicit sync may land inside of the learner update timing.
- __Reference resolving on producer's hot path:__
`TrainingData.solve_refs()` was called synchronously inside
`LearnerGroup.update()` before queuing which cost sometimes around ~25%
of time in some calls. Extends the window where producer/learner can
drift.
- __Mixed queue semantics + missing task semantics:__ The code mixed
`queue.Queue` and `deque` (and optionally `CircularBuffer`).
`task_done`/`join()` semantics don't exist for `deque`, correctness
relies on polling and manual drops. There was no bounded, blocking
handoff to pace producers. This was brittle under load.
- __No clean stop path:__ The thread used a `stop` flag but no sentinel
was enqueued, if it was blocked/polling the shutdown could hang or
increment counters after a stop.
- __Complete multi-learner stalling:__ In multi-learner setups with
__multi-agent__ policies asynchronous batches (i.e. batches with
different combinations of policies) led to stalls in Torch's
`DistributedDataParallel` gradient asynchronous synchronization. One
rank computed gradients for a policy not existent on the other rank(s)
and waited indefinitely for synched gradients.

### Improvements by this PR
- __Consumer-driven:__ `Learner` dictates pace through blocking queues
(`Learner` does `get()`, producer does `put`). That avoids busy polling
(no CPU burn). Faster reloading through quick returns from
`Learner.update()` with no results ready. Avoids learner starving -
bigger queues allow for frequent producer burstiness.
- __Edge-triggered aggregation:__ Only `_LearnerThread` increments a
private counter and on __exactly__ the `broadcast_interval`th update
fires an __event__ (`_agg_event`). The producer simply `wait`s for the
event and `clear`s it (no lock fight). Furthermore, the `_LearnerThread`
now reduces metrics and returns them through an out-queue from which the
`Learner` picks them up and returns them to the main process. All of
these measures reduce thread contention to an absolute minimum.
- __Pass meta-data with batch:__ The `Learner` enqueues a tuple `(batch,
timesteps)` so the `_LearnerThread` consumes the correct timesteps
atomically. This also reduces communication and boilerplate.
- __(Optional) Deferral of reference resolving:__ Post-solve references
in `Learner.update()` to return faster in asynchronous calls.
- __Clean stop + consistent semantics:__ Use a `_STOP_SENTINEL` through
the learner queue; don't rely anymore on a boolean alone. And call
`task_done()` on real `queue.Queue` (if not using `CircularBuffer`).
Furthermore unification of buffer/queue API inside `Learner`.
- __Safe-guarding multi-agent multi-learner training:__ Manual
synchronization of gradients replaces Torch's `DistributedDataParallel`
hooks-based synchronization for multi-learner multi-agent setups.
Gradients on each rank are zero-padded and synched after all gradients
have been computed.

## Related issues

## Additional information
Because this PR reshapes the data flow, a few tuning tips are useful:

- Circular buffer vs. simple queue. The old CircularBuffer prevented
learner starvation but its push/pop are slower. The new consumer-driven
pipeline is generally more efficient - assuming producers are reasonably
fast and the learner queue isn’t tiny. Use `use_circular_buffer=True`
only when producing is expensive/irregular (it lets the learner keep
iterating over buffered data, similar to `num_epochs > 1` but in
cycles). Otherwise, prefer the simple queue. Recommended defaults:
`simple_queue_size=32` for `APPO`; `IMPALA` keeps a smaller
`learner_queue_size=3`.
- Unified interval: broadcast & metrics reduction. Previously, weights
were synced by `broadcast_interval` while metrics were reduced every
fixed 20 updates. The new design unifies these: `broadcast_interval` now
controls both weight sync and metrics reduction. In practice, ~10
balances steady flow with acceptable off-policy lag.
- Scale producers to match a fast learner. The `_LearnerThread` applies
updates quickly, so overall throughput is often producer-bound. To feed
it well, increase `num_env_runners` and/or `num_envs_per_env_runner`.

### Next steps
This PR improves dataflow focused on the learner(s). The next steps are:
- To increase throughput in `AggregatorActors`
- To improve dataflow in IMPALA's main thread.
- To boost performance in loss calculation.
- To check, asynchronous calls to `EnvRunner`s and `Learner`s.
- To test resolving references in either `_GPULoaderThreads` or
`_LearnerThread` instead of the `Learner`'s main thread.

### Tests
APPO in this PR was tested on the following (multi-agent) environments:
- `CartPole-v1`
- `ALE:Pong-v5`
- `Footsies` (see https://github.com/chasemcd/FootsiesGym)

#### `CartPole-v1`
This PR improves performance significantly for high-producer scenarios
like `CartPole-v1`. All tests used:
- `broadcast_interval=10`
- `use_circular_buffer=False`
- `num_aggregator_actors_per_learner=3`
- `num_env_runners=num_learners x 32`
- `episodes_to_numpy=False`
- `num_gpus_per_learner=1`

<img width="757" height="404" alt="image (3)"
src="https://github.com/user-attachments/assets/3beee428-d4c0-42f4-811d-61d81de484c2"
/>

#### `ALE:Pong-v5`
All tests used:
- `broadcast_interval=10`
- `use_circular_buffer=False`
- `num_aggregator_actors_per_learner=6`
- `num_env_runners=num_learners x 32`
- `episodes_to_numpy=True` (`FrameStack` connector with 4 frames)
- `num_gpus_per_learner=1`

<img width="676" height="366" alt="image"
src="https://github.com/user-attachments/assets/43d08a87-0cc1-4902-8150-adc1c3203be6"
/>

---------

Signed-off-by: simonsays1980 <[email protected]>
Signed-off-by: jasonwrwang <[email protected]>
simonsays1980 pushed a commit that referenced this pull request Jan 15, 2026
## Description
Introduced in #59544, we added
many optimisations for IMPALA / APPO learner.
One of these optimisations is to minimise the time thread locked from
the queue.
Using `queue.get_nowait()` will raise an exception if the queue has no
data. Therefore, we wrap the request in a try/except.
Currently, when this exception occurs then we log a warning but
reviewing the training logs this actually causes a massive amount of
spam.

This PR, therefore, removes the warning with an associated comment to
explain why we use a `pass` instead.

---------

Signed-off-by: Mark Towers <[email protected]>
Co-authored-by: Mark Towers <[email protected]>
pseudo-rnd-thoughts pushed a commit that referenced this pull request Oct 26, 2026
Before this PR: With APPO's circular buffer
(`circular_buffer_iterations_per_batch` K > 1, default 2), the
`_LearnerThread` runs up to K updates per `IMPALALearner.update()` call.
It put one reduced result on an unbounded queue per update, while
`update()` collected one per call, so K-1 results per cycle were never
collected. Whenever the Learner is faster than sampling (e.g. a GPU
Learner):
- the Learner's memory grows without bound (+540 MiB/h on an L4
Learner);
- the Algorithm's `NUM_*_TRAINED_LIFETIME` counters advance at 1/K,
which also slows APPO's target-network updates by K;
- the learner metrics the Algorithm reports fall further and further
behind.

Introduced by #59544 (Ray 2.54).

After this PR: The results queue holds at most one result, and the
learner thread only reduces once `update()` collected the previous one.
Until then, metrics keep accumulating in the Learner's `MetricsLogger`,
so the next result covers all updates and nothing is lost.

**Tests**
- New `test_learner_thread_results_with_circular_buffer` (APPO, K=2,
stubbed gradient update): fails on master (4 results queued after 8
updates), passes with this PR.
- `python -m pytest
python/ray/rllib/algorithms/appo/tests/test_appo_learner.py`: 3 passed.
Run against the Ray 2.58.0 wheel with this PR's `impala_learner.py`,
which matches master's apart from docstrings.
- Multi-agent APPO on 1x L4 (30 EnvRunners, 20 to 90 minute runs on
Anyscale): the queue stays at 1 instead of passing 10,000 after 20
minutes, and the trained-steps counters and target-network updates match
ground truth.

No existing issue or PR covers this; I searched open issues and PRs for
the learner results queue and the circular buffer. Found while
investigating a user report of APPO Learner memory growth. AI assistance
(Claude Code) was used for the investigation, the change and the tests.

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

---------

Signed-off-by: Artur Niederfahrenhorst <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
pseudo-rnd-thoughts pushed a commit that referenced this pull request Oct 26, 2026
…n the learner thread (#67300)

Before this PR: `_LearnerThread.step()` called
`torch.distributed.barrier()` before and after every aggregation, i.e.
after every learner update with the default `broadcast_interval=1`. Ray
Train initializes a process group even for `num_learners=1`, so with a
GPU Learner each barrier is an NCCL all-reduce, and each one leaks ~160
bytes of host memory (NCCL 2.27.5, torch 2.10). The Learner's memory
grew by ~0.35 KB per update, ~20 MiB/h at 17 updates/s. Introduced by
#59544 (Ray 2.54).

After this PR: The learner thread no longer calls barriers. Fetching the
module state only reads the local Learner's parameters, and DDP's
gradient all-reduce already keeps the Learners in lockstep.

**Tests**
- New `test_learner_thread_does_not_call_barrier_per_update` (IMPALA,
stubbed gradient update and `torch.distributed`): fails on master
(barrier called 10 times for 5 updates), passes with this PR.
- `python -m pytest
python/ray/rllib/algorithms/impala/tests/test_impala.py`: 4 passed. Run
against the Ray 2.58.0 wheel with this PR's `impala_learner.py`, which
matches master's apart from docstrings.
- Multi-agent APPO on 1x L4 (30 EnvRunners, 90 minute runs on Anyscale,
all with the results-queue fix from #67299): Learner memory grew 592 to
626 bytes per update in 7 runs with the barriers, and 236 to 289 bytes
per update in 4 runs without. memray attributes the difference to
`ncclAllReduce` called from `barrier()`. The remaining growth is a Ray
Core bug, #67297.
- 2-Learner APPO (gloo, local): the Learners stay in lockstep without
the barriers.

No existing issue or PR covers this; I searched open issues and PRs for
the learner thread's barriers. Found while investigating a user report
of APPO Learner memory growth. AI assistance (Claude Code) was used for
the investigation, the change and the tests.

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

---------

Signed-off-by: Artur Niederfahrenhorst <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
justinyeh1995 pushed a commit to justinyeh1995/ray that referenced this pull request Oct 28, 2026
…oject#67299)

Before this PR: With APPO's circular buffer
(`circular_buffer_iterations_per_batch` K > 1, default 2), the
`_LearnerThread` runs up to K updates per `IMPALALearner.update()` call.
It put one reduced result on an unbounded queue per update, while
`update()` collected one per call, so K-1 results per cycle were never
collected. Whenever the Learner is faster than sampling (e.g. a GPU
Learner):
- the Learner's memory grows without bound (+540 MiB/h on an L4
Learner);
- the Algorithm's `NUM_*_TRAINED_LIFETIME` counters advance at 1/K,
which also slows APPO's target-network updates by K;
- the learner metrics the Algorithm reports fall further and further
behind.

Introduced by ray-project#59544 (Ray 2.54).

After this PR: The results queue holds at most one result, and the
learner thread only reduces once `update()` collected the previous one.
Until then, metrics keep accumulating in the Learner's `MetricsLogger`,
so the next result covers all updates and nothing is lost.

**Tests**
- New `test_learner_thread_results_with_circular_buffer` (APPO, K=2,
stubbed gradient update): fails on master (4 results queued after 8
updates), passes with this PR.
- `python -m pytest
python/ray/rllib/algorithms/appo/tests/test_appo_learner.py`: 3 passed.
Run against the Ray 2.58.0 wheel with this PR's `impala_learner.py`,
which matches master's apart from docstrings.
- Multi-agent APPO on 1x L4 (30 EnvRunners, 20 to 90 minute runs on
Anyscale): the queue stays at 1 instead of passing 10,000 after 20
minutes, and the trained-steps counters and target-network updates match
ground truth.

No existing issue or PR covers this; I searched open issues and PRs for
the learner results queue and the circular buffer. Found while
investigating a user report of APPO Learner memory growth. AI assistance
(Claude Code) was used for the investigation, the change and the tests.

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

---------

Signed-off-by: Artur Niederfahrenhorst <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
justinyeh1995 pushed a commit to justinyeh1995/ray that referenced this pull request Oct 28, 2026
…n the learner thread (ray-project#67300)

Before this PR: `_LearnerThread.step()` called
`torch.distributed.barrier()` before and after every aggregation, i.e.
after every learner update with the default `broadcast_interval=1`. Ray
Train initializes a process group even for `num_learners=1`, so with a
GPU Learner each barrier is an NCCL all-reduce, and each one leaks ~160
bytes of host memory (NCCL 2.27.5, torch 2.10). The Learner's memory
grew by ~0.35 KB per update, ~20 MiB/h at 17 updates/s. Introduced by
ray-project#59544 (Ray 2.54).

After this PR: The learner thread no longer calls barriers. Fetching the
module state only reads the local Learner's parameters, and DDP's
gradient all-reduce already keeps the Learners in lockstep.

**Tests**
- New `test_learner_thread_does_not_call_barrier_per_update` (IMPALA,
stubbed gradient update and `torch.distributed`): fails on master
(barrier called 10 times for 5 updates), passes with this PR.
- `python -m pytest
python/ray/rllib/algorithms/impala/tests/test_impala.py`: 4 passed. Run
against the Ray 2.58.0 wheel with this PR's `impala_learner.py`, which
matches master's apart from docstrings.
- Multi-agent APPO on 1x L4 (30 EnvRunners, 90 minute runs on Anyscale,
all with the results-queue fix from ray-project#67299): Learner memory grew 592 to
626 bytes per update in 7 runs with the barriers, and 236 to 289 bytes
per update in 4 runs without. memray attributes the difference to
`ncclAllReduce` called from `barrier()`. The remaining growth is a Ray
Core bug, ray-project#67297.
- 2-Learner APPO (gloo, local): the Learners stay in lockstep without
the barriers.

No existing issue or PR covers this; I searched open issues and PRs for
the learner thread's barriers. Found while investigating a user report
of APPO Learner memory growth. AI assistance (Claude Code) was used for
the investigation, the change and the tests.

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

---------

Signed-off-by: Artur Niederfahrenhorst <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go add ONLY when ready to merge, run all tests rllib RLlib related issues rllib-algorithms An RLlib algorithm/Trainer is not learning.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants