Skip to content

[rl] Controller GC: freeze the setup heap, fold generator metrics per rollout and group - #5290

Merged
felipemello1 merged 3 commits into
pytorch:mainfrom
felipemello1:rl/controller-gc-heap
Oct 12, 2026
Merged

felipemello1 merged 3 commits into
pytorch:mainfrom
felipemello1:rl/controller-gc-heap

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

TLDR: Every full garbage collection in the RL controller walks every object the collector tracks. After setup that's ~1M objects that never die, plus 16 generator-metric records per generation that a Verifiers rollout keeps until it ends. This PR freezes the setup objects out of the collector and folds each rollout's generator metrics into one Mean and one Max per key. In a local multi-turn run, the longest GC pause drops from 0.98 s to 0.06 s, and GC time from 1.63 to 0.57 s per minute.

Problem

  1. Full collections walk the whole heap. CPython runs one whenever the objects that survived into the oldest generation grow by 25%. It visits every tracked object (dicts, lists, class instances) in the process.
  2. Setup leaves ~1M objects behind. After setup the controller holds the modules it imported (torch, vLLM, Verifiers), configs, the dataset and actor handles. They live until exit, and each full collection rescans them: 0.4-0.7 s on an H100 host.
  3. Each generation adds 16 metric records. The generator returns 8 metrics, each as a Mean and a Max record, so 48 tracked objects. The Verifiers GenerationServer keeps all of them until the rollout ends.
  4. The group copies them again. compute_rollout_metrics puts every turn's records into the group's metrics, which live until the step is logged.
  5. Cost: in an agentic run with ~2,000 rollouts in flight, ~24 turns each, a full collection paused the controller for 4.7-8.6 s, adding up to 12-37 s of GC per step.
                          before                                   after
setup objects (~1M)       rescanned by every full collection      frozen: never scanned again
in-flight rollout         16 records x turns                       16 records
finished group            16 records x turns x rollouts            16 records

Solution

  1. Controller.run() calls the new GarbageCollector.freeze(reason) before starting its loops: a full collection, then gc.freeze(). The setup objects move to a generation the collector never scans.
  2. New metrics.fold(metrics) merges the Mean, Max, Min and Sum records that share a key into one record per type. MetricsProcessor reduces the result to the same numbers.
  3. GenerationServer folds each generation's metrics into the rollout's. compute_rollout_metrics folds the turns' generator metrics.
  4. Unchanged: every logged value, up to float rounding of the sums.

Results
The real loop on 2 H100s: Qwen3-0.6B, trainer on one GPU and one generator on the other. A Verifiers env runs 12-turn episodes of fake tool output, so no sandboxes are needed. 64 rollouts per step, ~320 in flight, 30 steps per arm. The census thread logs per-generation GC time and object counts every 30 s.

                                       main          this PR
GC time                                1.63 s/min    0.57 s/min
longest pause                          0.98 s        0.06 s
full collections (count, mean pause)   7, 0.77 s     10, 0.04 s
objects the collector scans            1.37M         47K
step time                              12.3 s        13.0 s   (run-to-run noise; GC isn't the bottleneck at this scale)

You may ask:

  • Why not disable the GC, or raise its thresholds? Disabling it leaks every reference cycle. Higher thresholds make collections rarer but no shorter, and each one still walks the setup objects.
  • Why freeze in run() and not in train.py? Launchers that build the Controller themselves call setup_async() and run() without going through train.main().
  • Why fold, not make Metric cheaper (__slots__)? Slots would save one object of the three per record. Folding makes a rollout's record count stop growing with its turns.

NOTE: not run at the ~2,000-rollouts-in-flight scale of the agentic run above, and that run's heap was never inventoried. How much of its 4.7-8.6 s these two changes remove is an estimate.
NOTE: a Verifiers rollout whose episode raises before pop_generation_metadata still leaves its metadata in GenerationServer. After folding that's ~20 objects per failed rollout.

Test plan

pytest tests/rl/unit_tests/cpu/test_metrics.py::TestFold tests/rl/unit_tests/cpu/test_verifiers.py::test_generation_server_forwards_token_request  # fail without the fix
pytest tests/rl/unit_tests/cpu   # 434 passed (main 432); the 2 failures in test_verifiers_terminal_bench.py also fail on main

… rollout and group

A full collection walks every object the GC tracks in the controller. Two kinds dominated:
- ~1M objects alive after setup (imports, configs, the dataset), which never die;
- 18 generator Metric records per generation, which the Verifiers GenerationServer kept
  for the whole rollout and compute_rollout_metrics copied into the group's metrics.

Controller.run() now calls gc.collect() + gc.freeze() before its loops. A new m.fold merges
the Mean/Max/Min/Sum records that share a key into one record per type; MetricsProcessor
reduces the result to the same numbers. GenerationServer and compute_rollout_metrics fold
generator metrics.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 11, 2026
@felipemello1
felipemello1 marked this pull request as ready for review October 11, 2026 23:33
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 11, 2026

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

inline comments

Comment thread torchtitan/rl/controller.py Outdated
Comment on lines +779 to +782
# Setup objects (modules, configs, dataset, actor handles) live until exit. Freeze them
# so full GCs skip them: ~1M objects, ~0.5 s per full GC (Python 3.12, x86).
gc.collect()
gc.freeze()

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.

instead, to unify things a bit, could we call / add to this API?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

reply from claude: Done. Added GarbageCollector.freeze(reason) next to collect: a full collect, then gc.freeze(), with the time logged like collect. The controller calls it now. I didn't give the controller a scheduled GarbageCollector like the trainer has, because its __init__ calls gc.disable() and the controller makes garbage on every request. Happy to switch if that's what you meant.



def fold(metrics: Iterable[Metric]) -> list[Metric]:
"""Merge the `Mean`, `Max`, `Min` and `Sum` records that share a key into one record per type.

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.

document the motivation here

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

reply from claude: Added a short "Why" to the docstring. Each generate call returns 16 records. Without folding, a multi-turn rollout keeps every turn's records until the step is logged, and every full GC walks them: ~180K of the ~220K objects added after setup, at 12 turns and ~320 rollouts in flight.

Felipe Mello added 2 commits October 11, 2026 17:39
- GarbageCollector.freeze(reason): full collection, then gc.freeze(); the controller calls it
  instead of gc directly.
- fold's docstring says why it exists: unfolded, multi-turn rollouts hold every turn's
  generator records until the step is logged.
@felipemello1
felipemello1 merged commit 155e2d1 into pytorch:main Oct 12, 2026
@felipemello1
felipemello1 deleted the rl/controller-gc-heap branch October 12, 2026 03:40
wwwjn added a commit that referenced this pull request Oct 12, 2026
#5290 added test_compute_rollout_metrics_folds_generator_metrics with
RolloutTurn(prompt_token_ids=...), but #5273/#5274 had replaced that field
with prompt_prefix_len / prompt_delta_token_ids and made the per-token fields
numpy arrays, so the test fails on main with a TypeError.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants