Repository navigation
Conversation
|
@claude review |
There was a problem hiding this comment.
Verdict: Needs discussion -- On its own this PR changes no numerics, but it adds about 575 lines of production code and makes the batcher ~37 ms per step slower at T1. All of its value comes from #6303, so the maintainers need to agree to land the prep layer separately. There are also a few concrete fixes below.
What this PR does. add_group now splits each group into a summary (0-row arrays plus turn_lengths) and its arrays. decide computes TrainingSampleSpecs from lengths only, and FFD/LPT plans over those specs. At the step trigger, each trainable group is joined back, materialize builds the planned samples, and MicrobatchPacker.pack_planned packs them. It raises if a packed microbatch's counts differ from the sum of its specs' counts.
Example. One rollout, prompt [1,2], completion [3,4,5], logprob of 4 is NaN:
before: add_group -> TrainingSample(token_ids=[1,2,3,4,5], ...) -> at P groups: pack -> counts read from the packed tensors
after: add_group -> spec(num_tokens=5, loss_token_counts=(2,), routing_token_counts=(4,))
at P groups: plan over specs -> join -> materialize -> pack_planned asserts packed counts == (2,), (4,)
Must fix
- The PR description: "Human note: TODO (Jiani)" is still a placeholder, and the human-written summary has to be filled in before merge. The description also says "one walk ... There is no second walk to keep in step", which is not accurate. The token layout is encoded twice: once in
_SpecInProgress(lengths) and again inrollout_to_training_samples+_build_training_sample(arrays). The MTP counts are a third copy ofget_mtp_token_counts.pack_plannedcatches any drift loudly, but the description should say this plainly. torchtitan/rl/rollout/finished_group.py:208-- the 0-row views keep the full arrays alive (inline comment).torchtitan/rl/trainer/training_sample_builder.py:526-- thetraining_sample_specs=Nonedefault is used only by tests (inline comment).
Should consider
torchtitan/rl/trainer/batcher.py:404-- pending state is kept in two containers, and the join happens in the same process; keep the original group instead (inline comment).torchtitan/rl/trainer/training_sample_builder.py:565-- the token-reuse prefix check no longer runs on filtered groups or samples (inline comment).training_sample_builder.py:223-- on a summary turn, array-derived values are silently 0:turn.num_prompt_tokensreturnsprompt_prefix_len, andlen(turn.completion_token_ids)returns 0. A filter added todecidethat reads them would drop data without an error.pack_plannedcovers overrides ofrollout_to_training_sample_specs, but notdecidefilters. If #6303 keeps this representation, consider a summary turn type without the array fields, so that reading them raises.
Questions
- In #6303, could the trainer compute the per-depth MTP counts from its packed microbatches and reduce them across DP ranks (one
[1 + num_mtp_layers]int64 all-reduce per step)? The batcher would then compute onlyloss_token_counts[0] > 0for the filter. That would delete the MTP math into_training_sample_spec, the routing counts in the spec, and the count checks inpack_planned.
Details
- I checked the spec counting against
MicrobatchPacker.pack+get_mtp_token_counts. A loss token at depth d is a completion token at index >= d + 1 with a finite logprob; routing tokens aremax(n - d, 0);num_response_tokenssubtracts a completion that starts at index 0. These match the packedtarget_mask = loss_mask & isfinite(logprobs). Theloss_token_counts[0] > 0filter is equivalent to the deleted_has_valid_loss_token. - I traced
rollout_to_training_samplesfor a dropped middle sample:previouskeeps growing as chunks and is cut at the next prefix break, so the last sample's prefix is correct (also covered by rollout 6 intest_training_sample_spec.py). _pack_one_training_batch: every id inplan.trainable_group_idshas specs and a_split_groupsentry, andRolloutTurnIDkeys are unique per sample.- The test ports in
test_async_controller.py,test_batcher.py,test_rdma_microbatch.pyandtest_cp_images.pyare mechanical. I skimmed them.
Not verified: the GPU bitwise loss and grad_norm runs, and the timing numbers (from an earlier version, per the PR). A maintainer still needs to review.
| replace( | ||
| turn, | ||
| # A 0-row view; it pickles as an empty array. | ||
| **{name: array[:0] for name, array in arrays.items()}, |
There was a problem hiding this comment.
array[:0] is a view, so its .base is the full array. Inside a process the "summary without bytes" still keeps every byte of the group alive. Pickling copies only the 0 rows, so the wire format is fine, but anything that holds a summary in-process (a colocated actor, a cache of summaries, a future batcher that keeps summaries longer than arrays) holds all the arrays too. That contradicts the RolloutGroupSummary docstring. A fresh empty array costs the same and holds nothing:
| **{name: array[:0] for name, array in arrays.items()}, | |
| # An empty array with the same dtype and trailing shape; not a view, so it | |
| # does not keep the full array alive. | |
| **{ | |
| name: np.empty((0, *array.shape[1:]), dtype=array.dtype) | |
| for name, array in arrays.items() | |
| }, |
| if training_sample_specs is None: | ||
| training_sample_specs = self.rollout_to_training_sample_specs( | ||
| rollout, | ||
| tuple(rollout_turn_lengths(turn) for turn in rollout.turns), | ||
| num_mtp_layers=0, | ||
| ) |
There was a problem hiding this comment.
The training_sample_specs=None branch has no production caller. materialize always passes specs, and only tests use the default (test_rollout_utils.py:35, test_rollout_worker.py:308, test_multiturn_images.py:221, test_training_sample_spec.py:234). It also hardcodes num_mtp_layers=0, which is only correct because the counts are never read on this path. Make training_sample_specs required and keyword-only, and move the "every spec of the full rollout" helper into the tests (for example next to the rollout_to_training_samples alias in test_rollout_utils.py). After that, rollout_turn_lengths only has the in-module caller in split_rollout_group and can become _rollout_turn_lengths.
| # (2, [9, 3]). Catches a full prompt stored as the delta. Not when a changed | ||
| # image starts the delta: `split_prompt` ends the prefix at it, and its | ||
| # placeholder tokens equal the previous image's. | ||
| could_reuse_one_more = ( |
There was a problem hiding this comment.
Before this PR, build_from_group ran the token-reuse prefix check on every rollout of every group. Now it only runs on turns up to the last planned spec of a trainable group. So a malformed rollout (a full prompt stored as the delta) passes silently when its group is zero-std or untrainable, when its samples are dropped (no valid loss token, or oversized), or when the bad turn comes after the last kept sample. The PR description says the check "now raises at the step trigger"; it should also say the check may not run at all. If the check is meant to catch rollout-producer bugs, consider running it where every rollout still has its arrays. The worker in #6303 is the natural place, since it splits anyway.
| self._groups_for_next_batch: list[TrainingSampleSpecGroup] = [] | ||
| # The summary and arrays of each accumulated group with specs, until its step is packed. | ||
| self._split_groups: dict[ | ||
| int, tuple[RolloutGroupSummary, RolloutGroupArrays] | ||
| ] = {} |
There was a problem hiding this comment.
Each pending group's state now lives in two containers that have to stay in sync: _groups_for_next_batch holds the spec groups, and _split_groups holds their (summary, arrays) keyed by id. In this PR the batcher splits a group and then joins it back in the same process, so the summary is only needed for decide. Keeping the original rollout_group next to its spec group, for example list[tuple[TrainingSampleSpecGroup, RolloutGroup | None]], would:
- drop the second dict,
- remove the join from the step path (about 10 ms per step at T1, by the PR's numbers),
- leave
join_rollout_groupwith no production caller until [WIP] [rl] Trainer DP replica leaders read their rollouts from the rollout workers and pack them #6303 needs it on the trainer.
The per-group free still works: drop the entry's group after materialize.
4f556a8 to
45a787e
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Needs discussion -- The fixes from the earlier review are in, and the split now makes the batcher +11 ms per T1 step instead of +37 ms. Whether to land this prep layer ahead of #6303 is still a maintainer call: it adds ~508 net production lines, and its value comes from #6303. Three small new items are listed below.
What changed since the last review. The summary/arrays split and join are gone. add_group keeps each trainable RolloutGroup next to its TrainingSampleSpecGroup. decide gets the full group plus rollout_turn_lengths of each rollout. The step trigger materializes one group at a time and packs with pack_planned.
Example.
before: add_group -> build_from_group (samples) ... at P groups: FFD/LPT over samples -> pack -> counts from tensors
after: add_group -> check_prompt_prefixes + decide (specs) -> keep (specs, group)
at P groups: FFD/LPT over specs -> counts summed from specs
-> materialize group by group -> pack_planned (raises if counts != specs' sums)
Earlier items
- Resolved:
finished_group.py0-row views (the split was removed). - Resolved: the
training_sample_specs=Nonedefault (now required and keyword-only). - Resolved: the two pending containers (now one list of
(spec group, group | None)). - Resolved: the prefix check skipping filtered groups (
check_prompt_prefixesnow runs on every rollout inadd_group). - Resolved: the description now says plainly that the layout is written twice.
- Answered in the description: the all-reduce question and the summary turn type (the latter is covered by the emptied-arrays
decidetest). - Still open: "Human note: TODO (Jiani)" is a placeholder. The human-written summary must be filled in before merge.
Must fix
torchtitan/rl/trainer/training_sample_builder.py:429-- the rename deleted explanatory comments on checks whose logic is unchanged, and an unresolvedTODO(async-rl)(inline comment).
Should consider
torchtitan/rl/trainer/training_sample_builder.py:544-- theimage_datalookup andreplace(image, data=...)do nothing in this PR. They belong in #6303 (inline comment).torchtitan/rl/rollout/types.py:477--check_prompt_prefixesreturns silently for a prefix that is too long. It could raise, so that both prefix checks run on every rollout (inline comment).
Details
- Traced
check_prompt_prefixesagainst the deleted in-builder check. The chunk walk comparesdelta[0]with the same token astraining_samples[-1].token_ids[prompt_prefix_len]did, and it fires under the same condition (prompt_prefix_len < previous_len). rollout_to_training_samplesand_build_training_sample: the first turn'sloss_maskzeros cover prefix + delta, and later turns cover only their delta.previous = [sample.token_ids]after a sample's last turn equals that turn's prompt + completion, because the sample's turns extend one another.- The plan's global counts are
torch.int64, the same dtype as the oldzeros_likeofget_mtp_token_countsoutput (asumover a bool tensor). The routing countmax(n - d, 0)matchesroll_mtp_sequence's same-document check with per-sample padding masked. - The step trigger frees each taken group after
materialize. The group that triggers the step is still referenced byadd_group'srollout_groupargument until the call returns. That does not matter at this size.
Not verified: the GPU bitwise runs and the timing numbers. A maintainer still needs to review.
| for turn_idx, (rollout_turn, lengths) in enumerate( | ||
| zip(rollout.turns, turn_lengths, strict=True) | ||
| ): | ||
| if lengths.num_completion_tokens == 0: | ||
| if len(rollout.turns) == 1: | ||
|
|
||
| continue | ||
|
|
||
| # empty rollouts should only happen when initial prompt is too long | ||
| raise ValueError( | ||
| f"rollout {rollout.group_id}/rollout={rollout.rollout_id}: " | ||
| f"non-final turn {turn_idx} has no completion" | ||
| ) |
There was a problem hiding this comment.
The rename to specs also deleted comments on checks whose logic did not change. These were the comments explaining non-obvious behavior, and one was an open TODO:
# Skip if no completion ... We keep these rollouts for debugging. # TODO(async-rl): confirm this signal actually reaches the rollout_recorder.(the TODO is dropped without being resolved)# empty rollouts should only happen when initial prompt is too long# Too many: e.g. prev = [0, 1, 2, 3] has 4 tokens; a turn can't reuse 6.(line 442)# Delta images sit in the delta, at full-prompt positions; an offset inside the delta ... would put image embeddings on other tokens.(line 448)# The full prompt's images: ... an image swapped in place (equal placeholder tokens) shortens the prefix too.(line 462)# True when this prompt continues the previous one ...; False when the env edited history -> open a new training_sample (branch).(line 472)- in
batcher.py,# Trainer computes policy_age from these at consume time ...abovemin_policy_versions
Deleting them is a drive-by change, and the next reader loses the reasons behind the checks. Please restore them next to the same checks, renaming "training_sample" to "sample" where needed.
| # Each image file from the rollout, not from the specs (see `TrainingSampleSpec.images`). | ||
| image_data = { | ||
| image.hash_value: image.data | ||
| for turn in rollout.turns | ||
| for image in turn.prompt_delta_images | ||
| } |
There was a problem hiding this comment.
In this PR, decide gets the full group, and slim_rollout_group keeps each image's data. So spec.images already holds the same PromptImage objects with their bytes. The image_data dict, the image_data parameter of _build_training_sample, and replace(image, data=image_data[image.hash_value]) at line 671 just rebuild equal objects. They are left over from the summary version, and their consumer is #6303. Use images=spec.images here, and drop the second sentence of the TrainingSampleSpec.images docstring. #6303 can add the lookup back in the PR that empties the image data.
| if prompt_prefix_len > previous_len: | ||
| return |
There was a problem hiding this comment.
This check now runs on every rollout so that a malformed rollout raises even in a zero-std or untrainable group. But the other direction of the same malformation, a turn that reuses more tokens than the previous turn has, returns silently here. The builder only raises for it on rollouts that get past the filters. So the full prompt stored as the delta is caught everywhere, but a prefix that is too long is still caught only for trained rollouts. Raising here gives one place where both prefix-length checks run on every rollout:
| if prompt_prefix_len > previous_len: | |
| return | |
| if prompt_prefix_len > previous_len: | |
| raise ValueError( | |
| f"rollout {rollout.group_id}/rollout={rollout.rollout_id}: turn {turn_id} " | |
| f"reuses {prompt_prefix_len} tokens, but the previous turn has only " | |
| f"{previous_len}; build it with `split_prompt`" | |
| ) |
(and update the docstring sentence at line 468). The builder's raise can stay as the guard for its own prev_len walk.
45a787e to
63fe53a
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Needs discussion -- All three items from the last review are fixed. Two things are still open: the maintainers have to decide whether to land this prep layer (+11 ms per T1 step, ~508 net production lines) separately from #6303, and the human-written summary is still a placeholder.
What changed since the last review. The deleted comments and the TODO(async-rl) are back next to their checks. materialize now passes images=spec.images directly. check_prompt_prefixes now raises in both directions (a prefix that is too long, and one that could reuse more), so both checks run on every rollout in add_group.
Example. A turn that stores prompt_prefix_len=6 after a previous turn of 4 tokens, in a zero-std group:
last review: check_prompt_prefixes returns; decide drops the group -> no error
now: check_prompt_prefixes raises ValueError("... reuses 6 tokens, but the previous turn has only 4 ...")
Earlier items
- Resolved: the comments the rename deleted, and the unresolved
TODO(async-rl), are restored intraining_sample_builder.py. The policy-age comment inbatcher.pyand the packer TODO aboveMicrobatchPackerare also restored. - Resolved: the leftover
image_datalookup is gone._build_training_sampleusesspec.images, and the docstring sentence about it is dropped. - Resolved:
check_prompt_prefixesraises for a prefix that is too long, and its docstring now covers both cases. - Still open: "Human note: TODO (Jiani)" is a placeholder. The human-written summary must be filled in before merge.
- Still open (maintainer call): whether to land this ahead of #6303 or fold it in. The PR's answer is to merge the two back to back.
Must fix
- PR description: fill in the human-written summary (see above).
No new problems in this revision.
Details
- Traced the two-direction
check_prompt_prefixes. The too-long raise comes before the chunk walk, so the walk always finds the chunk that holdsprompt_prefix_lenwhenprompt_prefix_len < previous_len. Its condition and message match the builder's ownprompt_prefix_len > prev_lenraise. The builder's raise can no longer fire through the batcher, but it still guards direct callers ofrollout_to_training_sample_specs. - Specs only start at turn 0 or at a prefix break, because
spec_in_progressisNoneonly there. So theprefixthatrollout_to_training_samplescaptures at a spec's first turn is always the cutprevious, including when an earlier spec in the same rollout was dropped. - The new
.tolist()calls inpack_plannedandrollout_turn_lengthsrun on CPU tensors and arrays in the batcher process, not in the training step.
Not verified: the GPU bitwise run (on 45a787e08, per the description) and the timing numbers; I could not run the CPU tests in this environment. A maintainer still needs to review.
63fe53a to
c2808aa
Compare
c2808aa to
8eb72bd
Compare
27ba59e to
b2b34eb
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Needs discussion -- This push restacks the same four commits onto the updated #6301 and adds no new problems. Two items are still open: the human-written summary, and the maintainers' call on whether to land this before #6303.
What changed since the last review. All four commits (cbb10bf, 9307fa3, c4c887d, b2b34eb) were re-pushed at 00:18 UTC onto the new base e286df2 ("the encoder runs in the workers for validation groups too"). The PR diff is still +1676/-605 over 12 files. At HEAD, the spec walk's "too many" check is still at training_sample_builder.py:451, and rollout_to_training_samples still calls check_prompt_prefixes at :559. The base change does not touch the batcher path: validation groups are collected in _collect_validation_rollouts and never reach add_group.
Example. This is unchanged from the last review. Turn 0 stores prompt_prefix_len=2000 with a 4-token delta, and max_context_length=2048:
main / HEAD: spec walk -> ValueError("... turn 0 reuses 2000 tokens, but the previous turn has only 0 ...")
Earlier items
- Still open: "Human note: TODO (Jiani)" is a placeholder. The human-written summary must be filled in before merge.
- Still open (maintainer call): land this ahead of #6303 (back to back, per the description), or fold it into #6303.
Must fix
- PR description: fill in the human-written summary.
No new problems in this revision.
Not verified: the previous head isn't in this shallow checkout, so I checked the restack against the last review's findings and line numbers, not with a commit-by-commit diff. I didn't run the GPU bitwise run or the CPU tests. A maintainer still needs to review.
b2b34eb to
d148fc6
Compare
d148fc6 to
196c0d9
Compare
|
|
||
|
|
||
| @dataclass(frozen=True, slots=True) | ||
| class RolloutTurnLengths: |
There was a problem hiding this comment.
Rename something to be RolloutTurnMetadata?
|
|
||
|
|
||
| @dataclass(frozen=True, slots=True) | ||
| class StepPlan: |
There was a problem hiding this comment.
Bad name
And this data structure is confusing...
|
|
||
|
|
||
| @dataclass(kw_only=True, slots=True) | ||
| class _SpecInProgress: |
There was a problem hiding this comment.
_SampleSpecInProgress
| # TODO(async-rl): make packing pluggable -- a `Packer` protocol on `Batcher.Config` (e.g. `TextPacker`) | ||
| # so callers swap logic per modality, and move the image path (`_pack_image_inputs`, the | ||
| # `images` branches) into an image packer. | ||
| class MicrobatchPacker: |
There was a problem hiding this comment.
Why we need this packer???
196c0d9 to
26b57b0
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Needs discussion -- The squashed head is correct, and moving MicrobatchPacker, StepPlan and RolloutTurnLengths out to #6303 is clean. What's left is a maintainer call: on its own, this PR now costs the batcher +0.44-0.52 s of CPU and +0.54-0.58 s of GC per step. Three mechanical items are also below.
What changed since the last review. The stack was rebased onto main 076f2e88b and squashed. MicrobatchPacker, StepPlan and RolloutTurnLengths moved to #6303. The spec walk now reads len(...) and np.isfinite(completion_logprobs) from the turn directly, and _pack_planned is a Batcher method. check_prompt_prefixes is now the private _check_prompt_prefixes in the builder. The methods are renamed plan_training_samples / build_training_samples.
Example.
add_group(g): plan_training_samples(g) -> specs (lengths only) -> keep (specs, g)
at P groups: FFD/LPT over specs; global counts = sum of spec counts
for g in id order: build_training_samples(specs_g, g); drop g
_pack_planned: raises if a packed length/count != its specs'
Earlier items
- Resolved: the human note is filled in.
- Resolved (moved to #6303): @wwwjn's comments on
RolloutTurnLengths,StepPlan, and "why we need this packer". - Still open: @wwwjn's rename of
_SpecInProgressto_SampleSpecInProgress(training_sample_builder.py:139) is not applied. - Still open (maintainer call): land this ahead of #6303, or fold it into #6303.
Must fix
torchtitan/rl/trainer/batcher.py:1283-- the packer TODO is left dangling at the end of the module; move it back above_pack_training_samples(inline comment).tests/rl/unit_tests/cpu/test_rollout_utils.py:33-- a redundant_check_prompt_prefixescall is the only reason the test imports that private name (inline comment).training_sample_builder.py:139-- apply @wwwjn's_SampleSpecInProgressrename (see above).
Should consider
training_sample_builder.py:643-- fold the "too few" check into the build walk and delete the second chunk walk, about -45 lines (inline comment).test_training_sample_spec.py:168--_decideonly forwards, and keeps a deleted method's name (inline comment).
Questions
- Where does the GC rise (36 -> 571-611 ms per step) come from? Unverified hypothesis: before this PR the batcher dropped each
RolloutGroupafterbuild_from_group. Now it keeps every trainable group alive until the step, including each turn'sprompt_messages(the full conversation),completion_message,env_messagesandmetrics. Those are all GC-tracked containers. If that is the cause, the cost is in this PR alone. That matters for the maintainers' decision on landing it ahead of #6303. - #6423 (@tianyu-l) renames
batcher.pytotraining_batch_builder.pyand thebatcher_*trace spans. This PR addsbatcher_planandbatcher_build_training_samples. Which one rebases on the other?
Details
- Traced
_SpecInProgress.to_training_sample_specagainst_build_training_sampleafter this rebase. Completion starts, the depth-d loss count (max(end - max(start, d+1), 0)minus non-finite offsets at or afterfirst), andmax(n - d, 0)routing all match the packedtarget_mask. The base no longer has the empty-completioncontinue. A 1-turn empty completion givesloss_token_counts[0] == 0, so the no-valid-loss filter drops it. _pack_one_training_batch: every taken trainable group has specs inassignments, andsamples_by_id.popconsumes each sample exactly once.- Overlap search:
gh pr list --searchfor "batcher", "training_sample_builder" and "TrainingSampleSpec". Found #6423 (rename, above) and this stack (#6301, #6303, #6323, #6324, #6334).
Not verified: the GPU bitwise run and the T1 timings (which the description says were measured before the rebase). A maintainer still needs to review.
| # TODO(async-rl): make packing pluggable -- a `Packer` protocol on `Batcher.Config` (e.g. `TextPacker`) | ||
| # so callers swap logic per modality, and move the image path (`_pack_image_inputs`, the | ||
| # `images` branches) into an image packer. |
There was a problem hiding this comment.
This TODO is left over from moving MicrobatchPacker to #6303. In the base it sat above _pack_training_samples, which this PR doesn't move. At the end of the module it is attached to nothing, so readers lose the link to _pack_training_samples, _pack_image_inputs and the images branches it is about. Delete it here and put it back above def _pack_training_samples (line 994), unchanged:
| # TODO(async-rl): make packing pluggable -- a `Packer` protocol on `Batcher.Config` (e.g. `TextPacker`) | |
| # so callers swap logic per modality, and move the image path (`_pack_image_inputs`, the | |
| # `images` branches) into an image packer. |
| def rollout_to_training_samples(rollout: Rollout) -> list[TrainingSample]: | ||
| """Every training sample of a full rollout, as the batcher makes them: check its prompt | ||
| prefixes, plan its specs from its lengths, then build them from its arrays. The builder's | ||
| config only filters groups, so a default builder builds the same samples.""" | ||
| builder = TrainingSampleBuilder.Config().build() | ||
| _check_prompt_prefixes(rollout) | ||
| specs = builder.rollout_to_training_sample_specs(rollout, num_mtp_layers=0) | ||
| return builder.rollout_to_training_samples(rollout, training_sample_specs=specs) |
There was a problem hiding this comment.
_check_prompt_prefixes(rollout) here does nothing new: rollout_to_training_samples calls it first (training_sample_builder.py:643) whenever the specs are non-empty, and they are non-empty for any rollout with a turn. The "too many" case also raises earlier, in the spec walk, with the same split_prompt message the tests match. The call is the only reason the test imports the module's private _check_prompt_prefixes, which CLAUDE.md's naming rule disallows. The docstring also describes it as a step the batcher takes, and it isn't one. Drop the call, and drop the import at line 19 and the mention in the module docstring (line 8):
| def rollout_to_training_samples(rollout: Rollout) -> list[TrainingSample]: | |
| """Every training sample of a full rollout, as the batcher makes them: check its prompt | |
| prefixes, plan its specs from its lengths, then build them from its arrays. The builder's | |
| config only filters groups, so a default builder builds the same samples.""" | |
| builder = TrainingSampleBuilder.Config().build() | |
| _check_prompt_prefixes(rollout) | |
| specs = builder.rollout_to_training_sample_specs(rollout, num_mtp_layers=0) | |
| return builder.rollout_to_training_samples(rollout, training_sample_specs=specs) | |
| def rollout_to_training_samples(rollout: Rollout) -> list[TrainingSample]: | |
| """Every training sample of a full rollout, as the batcher makes them: plan its specs from | |
| its lengths, then build them from its arrays (which checks its prompt prefixes). The | |
| builder's config only filters groups, so a default builder builds the same samples.""" | |
| builder = TrainingSampleBuilder.Config().build() | |
| specs = builder.rollout_to_training_sample_specs(rollout, num_mtp_layers=0) | |
| return builder.rollout_to_training_samples(rollout, training_sample_specs=specs) |
| _check_prompt_prefixes(rollout) | ||
| specs_by_first_turn_id: dict[int, list[tuple[int, TrainingSampleSpec]]] = {} | ||
| for position, spec in enumerate(training_sample_specs): | ||
| specs_by_first_turn_id.setdefault(spec.rollout_id.turn_id, []).append( | ||
| (position, spec) | ||
| ) | ||
| last_turn_id = max(spec.last_turn_id for spec in training_sample_specs) | ||
| samples_by_position: dict[int, TrainingSample] = {} | ||
| # (position, spec, its first turn's shared prefix) until the spec's last turn. | ||
| in_progress: list[tuple[int, TrainingSampleSpec, list[np.ndarray]]] = [] | ||
| # The previous turn's prompt + completion, as chunks; joined only where the prefix breaks. | ||
| previous: list[np.ndarray] = [] | ||
| previous_len = 0 | ||
| for turn_id, turn in enumerate(rollout.turns[: last_turn_id + 1]): | ||
| prompt_prefix_len = turn.prompt_prefix_len | ||
| delta = turn.prompt_delta_token_ids | ||
| if prompt_prefix_len < previous_len: | ||
| previous_token_ids = ( | ||
| previous[0] if len(previous) == 1 else np.concatenate(previous) | ||
| ) | ||
| previous = [previous_token_ids[:prompt_prefix_len]] |
There was a problem hiding this comment.
Should consider: the file now has two walks that carry "the previous turn's prompt + completion as chunks, cut at a prefix break". One is in _check_prompt_prefixes (line 243) and one is here. This walk already has previous_token_ids at every break (prompt_prefix_len < previous_len), which is the only place the "too few" check fires. The spec walk already raises the "too many" case. So folding the check in here would delete the second walk, about 45 lines:
- walk
rollout.turns, notrollout.turns[: last_turn_id + 1], so turns after the last kept sample are still checked, as on main; - at the break, raise if
len(delta) > 0 and delta[0] == previous_token_ids[prompt_prefix_len]and no delta placeholder starts atprompt_prefix_len, moving_check_prompt_prefixes's docstring here as the comment; - delete
_check_prompt_prefixes.
The extra concatenations at breaks after the last kept turn cost what main paid, since main concatenated every sample.
| def _decide( | ||
| builder: TrainingSampleBuilder, group: RolloutGroup, *, num_mtp_layers: int = 0 | ||
| ) -> TrainingSampleSpecGroup: | ||
| return builder.plan_training_samples( | ||
| rollout_group=group, | ||
| num_mtp_layers=num_mtp_layers, | ||
| ) |
There was a problem hiding this comment.
Should consider: _decide only forwards to plan_training_samples and keeps the name of the deleted decide method. Call builder.plan_training_samples(rollout_group=..., num_mtp_layers=...) at its 3 call sites and delete the helper.
26b57b0 to
e8fe290
Compare
|
@claude review again |
|
Claude finished @wwwjn's task in 1m 40s —— View job Needs discussion: the last review's three must-fix items are fixed and this push adds no new problems. Still open: a maintainer call on landing this before #6303 (it raises the batcher's CPU and GC per step on its own), and the order with the #6423 rename. Review |
There was a problem hiding this comment.
Verdict: Needs discussion -- All three must-fix items from the last review are fixed, and this push adds no new problems. What's left is for the maintainers: whether to land this ahead of #6303, given that on its own it makes the batcher slower per step, and how it orders with the #6423 rename.
What changed since the last review. One squashed force-push, e8fe290:
_SpecInProgressis renamed to_SampleSpecInProgress.- The packer TODO is back above
_pack_training_samples(batcher.py:2046in the diff). test_rollout_utils.pyno longer imports_check_prompt_prefixes.- The
_decidetest helper is gone.
The production logic matches what I traced last time.
Example. This is unchanged from the last review:
add_group(g): plan_training_samples(g) -> specs (lengths only) -> keep (specs, g)
at P groups: FFD/LPT over specs; global counts = sum of spec counts
for g in id order: build_training_samples(specs_g, g); drop g
_pack_planned: raises if a packed length/count != its specs'
Earlier items
- Resolved: the dangling packer TODO is moved back above
_pack_training_samples. - Resolved: the redundant
_check_prompt_prefixescall and the private import intest_rollout_utils.pyare gone. - Resolved: @wwwjn's
_SampleSpecInProgressrename is applied. - Resolved:
_decideintest_training_sample_spec.pyis deleted. - Still open (should consider): fold the "too few" check into the
rollout_to_training_sampleswalk and delete the second chunk walk in_check_prompt_prefixes(about -45 lines). - Still open (maintainer call): land this ahead of #6303, or fold it into #6303. On its own, the batcher's CPU per step rises 0.44-0.52 s and its GC per step goes from 36 ms to 571-611 ms (per the description). The cause of the GC rise is still not explained. Unverified: it may come from keeping each trainable
RolloutGroup(messages, metrics) alive until the step. - Still open (coordination): #6423 (Batcher -> TrainingBatchBuilder rename) is still open and touches the same file and trace spans (
batcher_plan,batcher_build_training_samples,batcher_pack). Someone needs to decide which one rebases on the other.
Details
- Freeing:
_take_groupsreturns only the trainableRolloutGroups, and_pack_one_training_batchdrops each one afterbuild_training_samples. The only other live reference isadd_group's argument, which holds the group that triggered the step. This matches[3, 2, 1]intest_the_step_trigger_frees_each_groups_arrays_before_the_next_is_built. build_training_samplesreturns samples in spec order, so thesamples_by_idkeyed byRolloutTurnIDin_pack_one_training_batchmaps each spec to its sample exactly once.- I found no non-ASCII characters in the added lines, and no leftover references to
build_from_group,add_training_samplesorTrainingSampleGroupintorchtitan/,tests/ordocs/. - Overlap search:
gh pr list --searchfor "batcher" and "training_sample_builder". It found #6423 (above), this stack (#6301, #6303, #6323, #6324, #6334), #6283 and #5475 (also touchestraining_sample_builder.py).
Not verified: the GPU bitwise run and the T1 timings (measured before the rebase, per the description). I didn't run the CPU tests. A maintainer still needs to review.
e8fe290 to
8ab03d2
Compare
|
from claude: Rebased onto #6301's new head 6e2d4ba, where each rollout worker records its own groups ( |
There was a problem hiding this comment.
Verdict: Needs discussion -- The restack onto #6301 6e2d4ba adds no new problems. The maintainers still have to decide whether to land this ahead of #6303, since on its own it makes the batcher slower per step. It also still needs to be ordered against the #6423 rename.
What changed since the last review. One squashed commit, 8ab03d2, on the new base, where each rollout worker records its own groups. The diff is now +1392/-515 over 11 files. Nothing in it reads recorder_lines, and there are no leftover references to it, build_from_group, add_training_samples or TrainingSampleGroup in torchtitan/, tests/ or docs/. The production logic in batcher.py and training_sample_builder.py matches what I traced last time:
_SampleSpecInProgressand its count math- the length-only "too many" check in the spec walk
_check_prompt_prefixesat the start ofrollout_to_training_samples- building one group at a time, then
_pack_planned's count checks
Example. Same as the last review:
add_group(g): plan_training_samples(g) -> specs (lengths only) -> keep (specs, g)
at P groups: FFD/LPT over specs; global counts = sum of spec counts
for g in id order: build_training_samples(specs_g, g); drop g
_pack_planned: raises if a packed length/count != its specs'
Earlier items
- Still open (maintainer call): land this ahead of #6303, or fold it into #6303. Per the description, on its own it raises the batcher's CPU per step by 0.44-0.52 s and its GC per step from 36 ms to 571-611 ms. The cause of the GC rise is still not explained. Unverified: keeping each trainable
RolloutGroup(messages, metrics) alive until the step. - Still open (coordination): #6423 (Batcher -> TrainingBatchBuilder) is still open and touches the same file and trace spans (
batcher_plan,batcher_build_training_samples,batcher_pack). - Still open (should consider): fold the "too few" check into the
rollout_to_training_sampleswalk and delete the second chunk walk in_check_prompt_prefixes(about -45 lines).
No new problems in this revision.
Details
training_sample_builder.py:363: therewardscomprehension is re-wrapped, but this is not a drive-by. The base line is 89 characters, so ufmt/black (88) forces the wrap whenever the file is touched.- Test changes since the last review are mechanical:
_spec/_make_specsintest_batcher.py, andtest_multiturn_images.pynow uses the sharedrollout_to_training_sampleshelper. - Overlap search:
gh pr list --searchfor "batcher" and "training_sample_builder". Found #6423 (above), this stack (#6269, #6301, #6303, #6324, #6334, #6469, #5862), #6283 and #5475.
Not verified: the previous head isn't in this shallow checkout, so I checked the restack against the last review's trace, not with a commit-by-commit diff. I did not run the bitwise run, the CPU suite or the timings. A maintainer still needs to review.
8ab03d2 to
f30bacc
Compare
Human note:
plan-> packtwo stages. Plan stage only use the length and information, not the actual data.TLDR: The batcher now decides which samples train and plans the step from lengths only, and touches the arrays only to build and pack planned samples, so #6303 can move packing to the trainer. Alone it is not a speedup: at T1 the batcher's CPU per step rises 0.44-0.52 s, while
batcher_add_group(5.3-5.6 ms per call) and the trainer's wait for a batch (10.3-11.1 ms) stay flat. Loss is bitwise identical.Merge bottom-up. #6303 follows right after and brings the batcher's CPU and GC below the parent's (1.2 s, 32 ms).
Problem
add_groupbuilds every training sample of a group at once (build_from_group): it copies the token arrays, then filters.Solution
trainer/training_sample_builder.py:rollout_to_training_sample_specspicks each sample's turns from lengths and returnsTrainingSampleSpecs (num_tokens, per-depth loss and routing token counts, versions, image metadata).plan_training_samples(rollout_group)replacesbuild_from_group(deleted withTrainingSampleGroup): same filters, metric keys and values, reading only lengths and which completion logprobs are finite.rollout_to_training_samples(rollout, *, training_sample_specs)runs_check_prompt_prefixes(rollout)(private in this file), then builds only the given specs' samples;build_training_samples(specs, rollout_group)calls it per rollout.trainer/batcher.py:add_groupkeeps trainable groups with their specs; the step trigger plans and sums global counts from specs, then builds the samples of one group at a time and drops it._SampleSpecInProgress,_build_training_sample), so_pack_plannedraisesValueErrorif a packed length or loss/routing count differs from the specs (the loss divides by their sums).TrainerStepBatch, the filters, the prefix checks' messages, the plan (FFD/LPT/zig-zag), the packed microbatches, metrics, losses, controller and trainer.Results
NOTE:
076f2e88b, squashed to one commit. On this head: the CPU suite,pre-commit, and bitwise vs main (rl_grpo_qwen3_0_6b_varlen_batch_invariant, seed 42, deterministic, 10 steps, trainer TP 2 + one generator TP 2): 62/62 shared non-timing TensorBoard tags equal at every step.MicrobatchPacker,StepPlan(nowTrainingBatchPlan) andRolloutTurnLengthsmoved to [WIP] [rl] Trainer DP replica leaders read their rollouts from the rollout workers and pack them #6303, which uses them first. The T1 pair and the harness ran with them in this PR; the plan, samples and packing are the same code.af04091d6, same hot-path work), on one host only.Test plan
pytest tests/rl/unit_tests/cpu: 793 passed, 8 skipped, 4 failed (parent: 779 passed). The 4 also fail on main076f2e88b(770 passed): recipe tests whosetorch_checkpointing.storage.fsspec_storageimport fails in the local env.test_packing_raises_when_a_sample_disagrees_with_its_spec:_pack_plannedcatches one extra masked token, or one extra token in a full microbatch. Fails without the checks.test_the_step_trigger_frees_each_groups_arrays_before_the_next_is_built: live group arrays at eachbuild_training_samplescall are[3, 2, 1]. Fails without the per-group build.test_building_a_rollout_that_breaks_split_prompt_raises(newtest_training_sample_spec.py, 8 tests): a broken prompt prefix raises at build time. Fails without the call inrollout_to_training_samples.