Repository navigation
[RLlib] - APPO improvements part 1: learner pipeline performance improvements. - #59544
Conversation
Signed-off-by: simonsays1980 <[email protected]>
Signed-off-by: simonsays1980 <[email protected]>
Signed-off-by: simonsays1980 <[email protected]>
…er setups with incomplete batches. Signed-off-by: simonsays1980 <[email protected]>
…arner setups with asynchronous batches. Signed-off-by: simonsays1980 <[email protected]>
…earner queue of APPO. Signed-off-by: simonsays1980 <[email protected]>
Signed-off-by: simonsays1980 <[email protected]>
Signed-off-by: simonsays1980 <[email protected]>
There was a problem hiding this comment.
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.
dea286f to
56528a6
Compare
pseudo-rnd-thoughts
left a comment
There was a problem hiding this comment.
Overall looks great. Large picture questions
- Could we have some tests for all three queue types for functionality at minimum
- Do we want a protocol or abstract class for the queues to run unnecessary empty function definitions?
|
|
||
| def __len__(self) -> int: | ||
| """Return current number of items in buffer.""" | ||
| with self._write_lock: |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
Add full raise error
| # If the queue is full, the consumer will wake soon anyway. | ||
| pass | ||
|
|
||
| def run(self) -> None: |
There was a problem hiding this comment.
What is this function for?
…ll improvements of Learner dataflow in IMPALA/APPO. Signed-off-by: simonsays1980 <[email protected]>
3d7d65d to
9e722f4
Compare
There was a problem hiding this comment.
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
ray/rllib/algorithms/appo/utils.py
Lines 163 to 170 in 9e722f4
rllib/core/learner/utils.py#L162-L170
ray/rllib/core/learner/utils.py
Lines 162 to 170 in 9e722f4
Signed-off-by: simonsays1980 <[email protected]>
Valid points @pseudo-rnd-thoughts. Let me answer to them separately:
|
Signed-off-by: simonsays1980 <[email protected]>
Signed-off-by: simonsays1980 <[email protected]>
Signed-off-by: simonsays1980 <[email protected]>
| 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 |
There was a problem hiding this comment.
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)
| learner_state[COMPONENT_RL_MODULE] | ||
| ) | ||
| try: | ||
| if (_last_num_updates % 0xFF) == 0: |
There was a problem hiding this comment.
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.
Signed-off-by: simonsays1980 <[email protected]>
| # 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.") |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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. |
Signed-off-by: simonsays1980 <[email protected]>
| ) | ||
| try: | ||
| if (self.learner._submitted_updates & ~0xFF) != ( | ||
| self._learner_submitted_updates - BATCHES_PER_AGGREGATION |
There was a problem hiding this comment.
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.
Signed-off-by: simonsays1980 <[email protected]>
| if (self.learner._submitted_updates & ~0xFF) != ( | ||
| self.learner._submitted_updates - BATCHES_PER_AGGREGATION | ||
| & ~0xFF | ||
| ): |
There was a problem hiding this comment.
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).
Signed-off-by: simonsays1980 <[email protected]>
…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]>
## 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]>
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]>
…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]>
…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]>
…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]>
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
LearnerThreadwas adequewhich is unblocking. As a result, theLearnerwasn'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).Learnerand_LearnerThreadshared the_num_updates_lockandmetrics._threading_lock(RLock). Every update both threads contended on the same lock. Every 20 updates occasionally both threads contended on the other shared lock.update()wrote a global_CURRENT_GLOBAL_TIMESTEPSand the_LearnerThreadhad to read it later. Rapid calls toupdate()could overwrite this before the thread consumes it, i.e. timesteps can mismatch the batch actually trained._num_updateswithout 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.pin_memory=Falseand there was no explicit stream handoff; any implicit sync may land inside of the learner update timing.TrainingData.solve_refs()was called synchronously insideLearnerGroup.update()before queuing which cost sometimes around ~25% of time in some calls. Extends the window where producer/learner can drift.queue.Queueanddeque(and optionallyCircularBuffer).task_done/join()semantics don't exist fordeque, correctness relies on polling and manual drops. There was no bounded, blocking handoff to pace producers. This was brittle under load.stopflag but no sentinel was enqueued, if it was blocked/polling the shutdown could hang or increment counters after a stop.DistributedDataParallelgradient 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
Learnerdictates pace through blocking queues (Learnerdoesget(), producer doesput). That avoids busy polling (no CPU burn). Faster reloading through quick returns fromLearner.update()with no results ready. Avoids learner starving - bigger queues allow for frequent producer burstiness._LearnerThreadincrements a private counter and on exactly thebroadcast_intervalth update fires an event (_agg_event). The producer simplywaits for the event andclears it (no lock fight). Furthermore, the_LearnerThreadnow reduces metrics and returns them through an out-queue from which theLearnerpicks them up and returns them to the main process. All of these measures reduce thread contention to an absolute minimum.Learnerenqueues a tuple(batch, timesteps)so the_LearnerThreadconsumes the correct timesteps atomically. This also reduces communication and boilerplate.Learner.update()to return faster in asynchronous calls._STOP_SENTINELthrough the learner queue; don't rely anymore on a boolean alone. And calltask_done()on realqueue.Queue(if not usingCircularBuffer). Furthermore unification of buffer/queue API insideLearner.DistributedDataParallelhooks-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:
use_circular_buffer=Trueonly when producing is expensive/irregular (it lets the learner keep iterating over buffered data, similar tonum_epochs > 1but in cycles). Otherwise, prefer the simple queue. Recommended defaults:simple_queue_size=32forAPPO;IMPALAkeeps a smallerlearner_queue_size=3.broadcast_intervalwhile metrics were reduced every fixed 20 updates. The new design unifies these:broadcast_intervalnow controls both weight sync and metrics reduction. In practice, ~10 balances steady flow with acceptable off-policy lag._LearnerThreadapplies updates quickly, so overall throughput is often producer-bound. To feed it well, increasenum_env_runnersand/ornum_envs_per_env_runner.Next steps
This PR improves dataflow focused on the learner(s). The next steps are:
AggregatorActorsEnvRunners andLearners._GPULoaderThreadsor_LearnerThreadinstead of theLearner's main thread.Tests
APPO in this PR was tested on the following (multi-agent) environments:
CartPole-v1ALE:Pong-v5Footsies(see https://github.com/chasemcd/FootsiesGym)CartPole-v1This PR improves performance significantly for high-producer scenarios like
CartPole-v1. All tests used:broadcast_interval=10use_circular_buffer=Falsenum_aggregator_actors_per_learner=3num_env_runners=num_learners x 32episodes_to_numpy=Falsenum_gpus_per_learner=1ALE:Pong-v5All tests used:
broadcast_interval=10use_circular_buffer=Falsenum_aggregator_actors_per_learner=6num_env_runners=num_learners x 32episodes_to_numpy=True(FrameStackconnector with 4 frames)num_gpus_per_learner=1