Repository navigation
[rl] RolloutTurn and TrainingSample per-token fields as numpy arrays (2/2) - #5274
Conversation
6ae9327 to
3fbb763
Compare
|
|
||
|
|
||
| @dataclass(kw_only=True, slots=True) | ||
| class _OpenSample: |
There was a problem hiding this comment.
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)
|
@claude review this PR and find a better name than |
|
Claude finished @tianyu-l's task in 2m 11s —— View job PR review +
|
dc7d15a to
70834dd
Compare
b2db38f to
237962e
Compare
…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.
…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.
05f3b39 to
0720cfe
Compare
TLDR:
RolloutTurn's andTrainingSample'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
RolloutTurnandTrainingSamplekeep their per-token fields as Python lists:prompt_delta_token_ids,completion_token_idsandcompletion_logprobs, thentoken_ids,loss_mask,logprobsandadvantage.torch.tensor(list)when the last group arrives, on the trainer's critical path.Solution
RolloutTurn: numpy (int32tokens,float32logprobs).split_promptandTokenEnvOutput.next_prompt_delta_token_idsreturn arrays;RolloutWorkerand the Verifiers rollouter store completions withnp.asarray.TrainingSample: numpy in the batcher's packed dtypes (int64,bool,float32,float32).rollout_to_training_sampleskeeps its loop: a private_SampleInProgresscollects the turns' arrays and concatenates them once per field. A sample is finished when the next one opens.np.concatenate(..., dtype=...)) and wraps it withtorch.from_numpy, which shares the memory.build_from_groupinasyncio.to_thread, likeadd_training_samplesalready is.TrainingMicrobatch, the trainer, and the builder's filters and metrics.Results
You may ask:
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.RolloutTurn? It halves the bytes crossing Monarch (vocabularies fit in 31 bits). The builder concatenates intoint64, which is what the trainer uses.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:
RolloutTurnorTrainingSampleby hand (custom rollouters,rollout_to_training_samplesoverrides) 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 (wheretorch.catwould promote the batch to float64), and raises on int or float to bool.log_logprobswrites float32 values:-0.1is written as-0.10000000149011612.Test plan
pytest tests/rl/unit_tests/cpu(verifiers 0.3.1 installed): 444 passed, 5 skipped. The same 2test_verifiers_terminal_bench.pyfailures as main (they still read the renamedtrain_dataset).TokenEnv+RolloutWorkeron 618 rollouts (18 edge cases) andVerifiersRollouter.trace_to_rollout_turnson 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.