Skip to content

[rl] RolloutTurn and TrainingSample per-token fields as numpy arrays (2/2) - #5274

Merged
felipemello1 merged 9 commits into
mainfrom
felipemello1/multiturn/2-training-sample-tensors
Oct 12, 2026
Merged

felipemello1 merged 9 commits into
mainfrom
felipemello1/multiturn/2-training-sample-tensors

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

TLDR: RolloutTurn's and TrainingSample's per-token fields become numpy arrays instead of Python lists. A chess group crosses Monarch from the rollout worker to the controller in 0.05 s instead of 0.33 s, the GC stops walking every token, building a group's samples takes 0.01 s instead of 0.21 s, and packing a batch takes 0.28 s instead of 6.88 s (16 synthetic 60-ply chess groups). Packed training batches are bitwise identical. Stacked on the delta-prompt PR.

Problem

  1. RolloutTurn and TrainingSample keep their per-token fields as Python lists: prompt_delta_token_ids, completion_token_ids and completion_logprobs, then token_ids, loss_mask, logprobs and advantage.
  2. Every finished group crosses a process: Monarch pickles it from the rollout worker to the controller, one Python int at a time.
  3. The controller holds them: the batcher keeps a whole batch of samples until the last group arrives, and every full GC walks every entry. In a 35B chess self-play run, the controller's full GCs grew from 1.25 to 2.7 s per step as games grew from 8.5 to 11.3 plies.
  4. The pack converts all those lists with torch.tensor(list) when the last group arrives, on the trainer's critical path.

Solution

  1. RolloutTurn: numpy (int32 tokens, float32 logprobs). split_prompt and TokenEnvOutput.next_prompt_delta_token_ids return arrays; RolloutWorker and the Verifiers rollouter store completions with np.asarray.
  2. TrainingSample: numpy in the batcher's packed dtypes (int64, bool, float32, float32).
  3. rollout_to_training_samples keeps its loop: a private _SampleInProgress collects the turns' arrays and concatenates them once per field. A sample is finished when the next one opens.
  4. The pack concatenates each field once into its packed dtype (np.concatenate(..., dtype=...)) and wraps it with torch.from_numpy, which shares the memory.
  5. The controller runs build_from_group in asyncio.to_thread, like add_training_samples already is.
  6. Unchanged: TrainingMicrobatch, the trainer, and the builder's filters and metrics.

Results

CPU, real RolloutTurn / TrainingSampleBuilder / Batcher, groups built as the default Rollouter builds them.
One group: 16 rollouts x 60 turns (120-ply chess)          before (lists)   after (numpy)
  pickle                                                     17.3 MB          11.3 MB
  Monarch flatten + unflatten                                0.33 s           0.05 s
  full GC added by 4 held groups                             +50 ms           +1 ms
  build_from_group                                           0.21 s           0.01 s
Terminal-Bench-shaped group (16 x 45 turns, ~94K context): pickle 13.1 -> 9.0 MB, Monarch 0.25 -> 0.03 s, build 0.20 -> 0.01 s

16 groups, main (lists everywhere) -> this PR                main             this PR
  60 plies: pack (the call that completes the batch)         6.88 s           0.28 s
  20 plies: pack                                             2.80 s           0.16 s
  60 plies: full-GC time added by 15 held groups of samples  0.081 s          ~0
  60 plies: build per group (now in a thread)                0.091 s          0.010 s
packed TrainingMicrobatch, 78 batches x 3 packings, 658 branch samples:        bitwise identical

You may ask:

  • Why numpy and not torch tensors? Both stop the GC walk. But Monarch pickles each torch storage separately with torch.save, which is slow for the thousands of small per-turn arrays in a group. Numpy pickles as raw bytes. With host data in numpy, the only conversion to torch is the batcher's pack.
  • Why int32 tokens in RolloutTurn? It halves the bytes crossing Monarch (vocabularies fit in 31 bits). The builder concatenates into int64, which is what the trainer uses.
  • Why not gc.freeze() per step? It bounds the pauses, but it leaks any reference cycle that existed before the freeze, and it leaves the Monarch and pack costs.

NOTE:

  • Code that builds RolloutTurn or TrainingSample by hand (custom rollouters, rollout_to_training_samples overrides) must pass numpy arrays. The repo has none outside the builders, the rollouters and the tests.
  • np.concatenate(dtype=...) in the pack casts float64 logprobs to float32 (where torch.cat would promote the batch to float64), and raises on int or float to bool.
  • log_logprobs writes float32 values: -0.1 is written as -0.10000000149011612.

Test plan

  • pytest tests/rl/unit_tests/cpu (verifiers 0.3.1 installed): 444 passed, 5 skipped. The same 2 test_verifiers_terminal_bench.py failures as main (they still read the renamed train_dataset).
  • Same data as main, end to end: the real TokenEnv + RolloutWorker on 618 rollouts (18 edge cases) and VerifiersRollouter.trace_to_rollout_turns on 4,000 random message trees. Every rebuilt prompt, turn, training sample, rollout metric and packed microbatch tensor (with dtypes) is identical to main. Turns match the generator's inputs and outputs, and every packed segment matches its sample.
  • Bitwise check: the same random groups packed on main and on this branch.

@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Oct 11, 2026
@felipemello1
felipemello1 added this pull request to stack #5275 October 11, 2026 05:30
@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 force-pushed the felipemello1/multiturn/2-training-sample-tensors branch from 6ae9327 to 3fbb763 Compare October 11, 2026 05:43


@dataclass(kw_only=True, slots=True)
class _OpenSample:

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.

The name is somewhat ambiguous -- can we be more specific? to achieve clear meaning like

  • sample under construction
  • WIP sample
  • sample being built (by the sample builder)

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review this PR

and find a better name than _OpenSample

@claude

claude Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 11s —— View job


PR review + _OpenSample rename

  • Read the PR diff against felipemello1/multiturn/1-delta-prompts
  • Review the batcher, builder, controller and types changes
  • Pick a better name for _OpenSample and commit it locally
  • Push: rejected by repo rules (GH013: Required status check "Meta CLA Check" is expected). The bot can't push to this branch. The change is a 3-line rename; the patch is below for @felipemello1 to apply.
  • Lint/tests: I wasn't allowed to run pytest or pre-commit in this environment. The rename is mechanical: the three references are the only ones in the repo, and the new docstring lines are under the 120-char flake8 limit.

Name for _OpenSample -> _TrainingSampleInProgress

It names the type it turns into (TrainingSample), and "in progress" says the sample is still being built while turns are appended. That is the "sample under construction / sample being built" meaning you asked for. The type's docstring also says who builds it now:

 @dataclass(kw_only=True, slots=True)
-class _OpenSample:
-    """A training_sample while turns are appended to it: per-token Python lists (cheap appends),
-    converted to tensors once by `to_training_sample`."""
+class _TrainingSampleInProgress:
+    """A training_sample still being built by `rollout_to_training_samples`, while turns are appended
+    to it: per-token Python lists (cheap appends), converted to tensors once by `to_training_sample`."""
@@
-        training_samples: list[_OpenSample] = []
+        training_samples: list[_TrainingSampleInProgress] = []
@@
-                    _OpenSample(
+                    _TrainingSampleInProgress(

Other names I considered: _PartialTrainingSample (could read as "a truncated sample") and _TrainingSampleDraft. _SampleUnderConstruction also works, but it drops the "Training" link to the output type.

Apply rename →


Review

Overall this looks correct and well scoped. I found no blocking issues. Notes, most important first:

1. The dtype contract is only stated in comments (types.py:96-103, batcher.py:667-702).
After 3fbb763 dropped the cast, _pack_training_samples sends each sample's tensor straight into torch.cat next to pads built with _DTYPES[key]. torch.cat promotes types instead of failing. So if a rollout_to_training_samples override returns float64 logprobs or int32 token_ids, the packed TrainingMicrobatch silently changes dtype: float64 generator_logprobs/advantages reach the loss. The old torch.tensor(..., dtype=_DTYPES[key]) made that impossible. The PR says no such override exists in the repo, and this is the documented extension point, so a hard assert would be speculative. But the contract is easy to break silently. A cheap way to make it explicit: have rollout_to_training_samples's docstring say "must return tensors in long/bool/float32/float32". Or check the dtype once in build_from_group, which is the user-overridable boundary, rather than in the pack.

2. Empty pad tensors per sample (batcher.py:689).
Without per_sample_pad_multiple (the default), pad(key, 0) still allocates five 0-length tensors per sample and doubles the torch.cat inputs. It's cheap next to the old cost, but guarding it is trivial:

for key in keys:
    packed_fields[key].append(sample[key])
    if sample_len > unpadded_len:
        packed_fields[key].append(pad(key, sample_len - unpadded_len))

3. asyncio.to_thread(build_from_group, ...) (controller.py:1040).
I checked that this is safe. Only the single batcher loop calls build_from_group, so calls never overlap. The builder keeps no mutable state besides config. The rollout_group has already been taken out of the buffer, so nothing else is touching it. The new comment ("turning a group's samples into tensors walks every token") is accurate. As the PR notes, the per-group cost goes up (0.073 -> 0.195 s at 60 plies). That's fine because it's off the loop now. If it grows, the extra cost is mostly the torch.tensor(list) calls, and building each field with one torch.tensor over pre-sized lists already is the cheap path.

4. The builder still aliases the previous sample's list (training_sample_builder.py:247-249).
prev_prompt_and_completion is the previous sample's token_ids list itself, not a copy. That's still correct: the only read before the next mutation is the slice [:prompt_prefix_len], which copies. Just noting it because the list/tensor split now makes the type of prev_prompt_and_completion depend on being inside _TrainingSampleInProgress.

5. Tests.

  • pytest.approx on the .tolist() float comparisons is right, since values now go through float32.
  • There's no test asserting the output dtypes of rollout_to_training_samples or of the packed microbatch. One line in test_single_turn_packs_one_training_sample would lock in the contract from point 1, e.g. assert training_sample.logprobs.dtype == torch.float32.
  • A small _pack_training_samples test with per_sample_pad_multiple set would cover the new torch.arange(sample_len) >= unpadded_len padding-mask path. I didn't check whether test_batcher.py already covers it.

6. Nits

  • types.py:96: token_ids: torch.Tensor # long has both a trailing comment and a docstring. You could put the dtype in the docstring instead ("""[L] long: packed prompt + ...""") to match how TrainingMicrobatch uses only # [T].
  • The controller TODO is now narrowed to RolloutTurn. Good, it matches what's still a list.

@felipemello1
felipemello1 force-pushed the felipemello1/multiturn/2-training-sample-tensors branch 5 times, most recently from dc7d15a to 70834dd Compare October 11, 2026 23:03
@felipemello1 felipemello1 changed the title [rl] TrainingSample per-token fields as tensors (no GC walk, torch.cat packing) (2/2) [rl] TrainingSample per-token fields as numpy arrays (no GC walk, one concat per field) (2/2) Oct 11, 2026
@felipemello1
felipemello1 force-pushed the felipemello1/multiturn/2-training-sample-tensors branch from b2db38f to 237962e Compare October 12, 2026 00:20
@felipemello1 felipemello1 changed the title [rl] TrainingSample per-token fields as numpy arrays (no GC walk, one concat per field) (2/2) [rl] RolloutTurn and TrainingSample per-token fields as numpy arrays (2/2) Oct 12, 2026
Base automatically changed from felipemello1/multiturn/1-delta-prompts to main October 12, 2026 03:37
Felipe Mello added 7 commits October 11, 2026 23:37
…t packing)

TrainingSample kept token_ids / loss_mask / logprobs / advantage as Python lists. The batcher holds
a whole batch of them, so every full GC in the controller walked 4 x L entries per sample, and the
pack converted them all with torch.tensor(list) when the last group arrived.

Fields are now tensors in the batcher's packed dtypes (long, bool, float32, float32), built once per
sample at the end of rollout_to_training_samples; the controller runs build_from_group in a thread;
the pack is torch.cat. Packed training batches are bitwise identical. On 16 chess-sized groups
(60 plies): pack 5.58 -> 0.42 s, GC time added by the held samples 0.230 -> 0.006 s.
…to its packed dtype

A custom rollout_to_training_samples override that returns, e.g., an int64 loss_mask no longer
changes the packed dtypes (a no-op for the builder's samples). One test still assigned lists.
The controller's GC TODO now names only RolloutTurn: TrainingSample's per-token fields are
tensors. The pack no longer casts each slice to its packed dtype: the builder already produces
those dtypes, and a float loss_mask fails in the builder's filter before reaching the pack. The pad
block keeps main's two length lines. TrainingSample's docstring states the GC saving precisely
(4 objects per sample instead of 4 x L list entries). The new rollouter test reads token_ids as a
tensor.
Review ask: the name now says the sample is still being built, not that it is open.
TrainingSample lists why its fields are tensors (GC, torch.cat without a cast); _SampleInProgress
says lists while building, tensors once at the end; the controller comment says why the build runs
in a thread.
The GC does not track numpy arrays (it does track tensors), and np.asarray builds them from lists
faster than torch.tensor: build_from_group on a 120-ply chess group (16 samples, 1.63M tokens) takes
218 ms instead of 321 ms, and the pack 0.24 s instead of 0.42 s on 16 60-ply groups. RolloutTurn's
per-token fields become numpy in the turn-tree follow-up, so host data stays numpy until the
trainer's tensors.

The batcher concatenates each field once into its packed dtype and wraps it with torch.from_numpy,
which shares the memory. np.concatenate(dtype=...) casts float64 to float32 but raises on int or
float to bool. Packed microbatches are bitwise unchanged.
RolloutTurn's prompt_delta_token_ids, completion_token_ids and completion_logprobs become numpy
arrays (int32, int32, float32). A group crosses Monarch from the rollout worker to the controller,
which pickles numpy as raw bytes, and the GC does not track numpy arrays. On a synthetic 120-ply
chess group (16 rollouts x 60 turns): pickle 17.3 -> 11.3 MB, Monarch flatten + unflatten
0.33 -> 0.05 s, full GC with 4 groups held +50 ms -> +1 ms, build_from_group 0.21 -> 0.01 s.

- split_prompt returns the delta as an int32 array, and so does TokenEnvOutput.next_prompt_delta_token_ids.
- RolloutWorker and the Verifiers rollouter store completions with np.asarray.
- _SampleInProgress holds the turns' numpy chunks and concatenates them once. A sample is finished
  when the next one opens, and the prefix check reads its token_ids.
- The recorder writes .tolist(); emptiness checks use len(), since numpy arrays have no truth value.
- The controller's TODO about RolloutTurn's lists is done.

Packed microbatches are bitwise unchanged.
Felipe Mello added 2 commits October 11, 2026 23:37
…open, clearer docstrings

The builder's variable matches its class (sample_in_progress), and finishing a sample and opening the
next are two flat steps. Docstrings say why numpy (raw-byte pickling, no GC walk, no conversion when
building a sample) and what _SampleInProgress holds. Emptiness checks read len(...) == 0. The
controller's to_thread comment no longer claims the build walks every token. ufmt-formatted: the
repo's pre-commit exclude 'build' skips training_sample_builder.py.
@felipemello1
felipemello1 force-pushed the felipemello1/multiturn/2-training-sample-tensors branch from 05f3b39 to 0720cfe Compare October 12, 2026 03:37
@felipemello1
felipemello1 merged commit c637737 into main Oct 12, 2026
@felipemello1
felipemello1 deleted the felipemello1/multiturn/2-training-sample-tensors branch October 12, 2026 03:38
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