Skip to content

[WIP] [rl] Split the batcher into a metadata half and a bytes half - #6302

Draft
wwwjn wants to merge 1 commit into
wwwjn/data-plane/2-slim-groupfrom
wwwjn/data-plane/3-batcher-split
Draft

wwwjn wants to merge 1 commit into
wwwjn/data-plane/2-slim-groupfrom
wwwjn/data-plane/3-batcher-split

Conversation

@wwwjn

@wwwjn wwwjn commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Human note:

  • Split the current batcher batching to be plan-> pack two stages. Plan stage only use the length and information, not the actual data.
image

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.

# PR Independent? Needs
0 RDMA object for microbatches and prompts (#5862) yes -
1 Rollout workers compute and record each group's rollouts (#6301) yes - (stacked on 0 for merge order only)
2 Split the batcher into a metadata half and a bytes half (#6302, this PR) yes 0 (its batcher code)
3 Trainer DP replica leaders pack their own microbatches from the plan (#6303) no 1, 2
4 Rollout groups reach the trainer by RDMA handle (#6323) no 3
5 Read the next step's rollout groups during the optimizer step (#6324) no 3 (stacked on 4 for merge order only)
6 Prompt image files share the rollout worker's torch transport pool (#6334) no 4 (stacked on 5 for merge order only)

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

  1. add_group builds every training sample of a group at once (build_from_group): it copies the token arrays, then filters.
  2. At P groups the batcher plans microbatches over sample lengths, packs them, and takes the global token counts from the packed tensors.
  3. So planning, which needs only lengths, is tied to the bytes: whoever plans holds every array of the step.
  4. Cost: the plan cannot move away from the bytes, but [WIP] [rl] Trainer DP replica leaders read their rollouts from the rollout workers and pack them #6303 wants a small plan and the bytes sent once, to the trainer. With score centering at k=32 and 4K completions, a group is 17.3 MB of arrays, 313 MB per rank per step.

Solution

  1. trainer/training_sample_builder.py: rollout_to_training_sample_specs picks each sample's turns from lengths and returns TrainingSampleSpecs (num_tokens, per-depth loss and routing token counts, versions, image metadata).
  2. plan_training_samples(rollout_group) replaces build_from_group (deleted with TrainingSampleGroup): same filters, metric keys and values, reading only lengths and which completion logprobs are finite.
  3. 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.
  4. trainer/batcher.py: add_group keeps 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.
  5. The token layout is written twice (_SampleSpecInProgress, _build_training_sample), so _pack_planned raises ValueError if a packed length or loss/routing count differs from the specs (the loss divides by their sums).
  6. Unchanged: TrainerStepBatch, the filters, the prefix checks' messages, the plan (FFD/LPT/zig-zag), the packed microbatches, metrics, losses, controller and trainer.
before:  add_group: build samples -> accumulate;    at P groups: plan samples -> pack -> counts from tensors
after:   add_group: plan_training_samples -> keep specs + group;   at P groups: plan specs -> build_training_samples per group -> pack

Results

T1 pair, #6301 -> this PR, then swapped: Qwen3-0.6B alphabet sort, 256 prompts x 4, 4 A100s per run, main af04091d6 + #6269 on both sides, medians over steps 4-12
  batcher CPU per step         1.67 -> 2.11 s; 1.62 -> 2.14 s
  batcher GC per step          36 -> 571 ms; 36 -> 611 ms
  batcher_add_group per call   5.6 -> 5.3 ms; 5.6 -> 5.5 ms
  trainer waits for a batch    10.4 -> 11.1 ms; 10.7 -> 10.3 ms
correctness: parent vs this PR batcher on the same groups, 1,032 microbatches, every TrainerStepBatch field identical; loss bitwise (NOTE)

NOTE:

  • Rebased onto main 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.
  • After review, MicrobatchPacker, StepPlan (now TrainingBatchPlan) and RolloutTurnLengths moved 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.
  • The T1 pair and the harness ran before the rebase, on earlier versions of this stack (T1 on main af04091d6, same hot-path work), on one host only.
  • The prefix check that reads token values now runs only on built rollouts, so it skips a rollout whose every sample a filter drops (the parent checked it). The length-only check runs in the spec walk, on the same rollouts as the parent's.

Test plan

  • pytest tests/rl/unit_tests/cpu: 793 passed, 8 skipped, 4 failed (parent: 779 passed). The 4 also fail on main 076f2e88b (770 passed): recipe tests whose torch_checkpointing.storage.fsspec_storage import fails in the local env.
  • test_packing_raises_when_a_sample_disagrees_with_its_spec: _pack_planned catches 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 each build_training_samples call are [3, 2, 1]. Fails without the per-group build.
  • test_building_a_rollout_that_breaks_split_prompt_raises (new test_training_sample_spec.py, 8 tests): a broken prompt prefix raises at build time. Fails without the call in rollout_to_training_samples.

@wwwjn

wwwjn commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @wwwjn's task in 4m 16s —— View job


Needs discussion: the batcher split is correct on its own, but whether to land this prep layer ahead of #6303 is a maintainer call, and there are a few small fixes. Review

@claude claude Bot 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.

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

  1. 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 in rollout_to_training_samples + _build_training_sample (arrays). The MTP counts are a third copy of get_mtp_token_counts. pack_planned catches any drift loudly, but the description should say this plainly.
  2. torchtitan/rl/rollout/finished_group.py:208 -- the 0-row views keep the full arrays alive (inline comment).
  3. torchtitan/rl/trainer/training_sample_builder.py:526 -- the training_sample_specs=None default 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_tokens returns prompt_prefix_len, and len(turn.completion_token_ids) returns 0. A filter added to decide that reads them would drop data without an error. pack_planned covers overrides of rollout_to_training_sample_specs, but not decide filters. 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 only loss_token_counts[0] > 0 for the filter. That would delete the MTP math in to_training_sample_spec, the routing counts in the spec, and the count checks in pack_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 are max(n - d, 0); num_response_tokens subtracts a completion that starts at index 0. These match the packed target_mask = loss_mask & isfinite(logprobs). The loss_token_counts[0] > 0 filter is equivalent to the deleted _has_valid_loss_token.
  • I traced rollout_to_training_samples for a dropped middle sample: previous keeps growing as chunks and is cut at the next prefix break, so the last sample's prefix is correct (also covered by rollout 6 in test_training_sample_spec.py).
  • _pack_one_training_batch: every id in plan.trainable_group_ids has specs and a _split_groups entry, and RolloutTurnID keys are unique per sample.
  • The test ports in test_async_controller.py, test_batcher.py, test_rdma_microbatch.py and test_cp_images.py are 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.

Comment thread torchtitan/rl/rollout/finished_group.py Outdated
replace(
turn,
# A 0-row view; it pickles as an empty array.
**{name: array[:0] for name, array in arrays.items()},

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.

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:

Suggested change
**{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()
},

Comment on lines +526 to +531
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,
)

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 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 = (

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.

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.

Comment thread torchtitan/rl/trainer/batcher.py Outdated
Comment on lines +404 to +408
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]
] = {}

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.

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:

The per-group free still works: drop the entry's group after materialize.

@wwwjn
wwwjn force-pushed the wwwjn/data-plane/3-batcher-split branch from 4f556a8 to 45a787e Compare November 20, 2026 22:29
@wwwjn

wwwjn commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @wwwjn's task in 2m 51s —— View job


Needs discussion: the earlier fixes are in; whether to land this prep layer ahead of #6303 is still a maintainer call, and three small items are new. Review

@claude claude Bot 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.

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.py 0-row views (the split was removed).
  • Resolved: the training_sample_specs=None default (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_prefixes now runs on every rollout in add_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 decide test).
  • Still open: "Human note: TODO (Jiani)" is a placeholder. The human-written summary must be filled in before merge.

Must fix

  1. torchtitan/rl/trainer/training_sample_builder.py:429 -- the rename deleted explanatory comments on checks whose logic is unchanged, and an unresolved TODO(async-rl) (inline comment).

Should consider

  • torchtitan/rl/trainer/training_sample_builder.py:544 -- the image_data lookup and replace(image, data=...) do nothing in this PR. They belong in #6303 (inline comment).
  • torchtitan/rl/rollout/types.py:477 -- check_prompt_prefixes returns 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_prefixes against the deleted in-builder check. The chunk walk compares delta[0] with the same token as training_samples[-1].token_ids[prompt_prefix_len] did, and it fires under the same condition (prompt_prefix_len < previous_len).
  • rollout_to_training_samples and _build_training_sample: the first turn's loss_mask zeros 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 old zeros_like of get_mtp_token_counts output (a sum over a bool tensor). The routing count max(n - d, 0) matches roll_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 by add_group's rollout_group argument 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.

Comment on lines 429 to 438
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"
)

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 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 ... above min_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.

Comment on lines +543 to +548
# 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
}

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.

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.

Comment thread torchtitan/rl/rollout/types.py Outdated
Comment on lines +477 to +478
if prompt_prefix_len > previous_len:
return

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.

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:

Suggested change
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.

@wwwjn
wwwjn force-pushed the wwwjn/data-plane/3-batcher-split branch from 45a787e to 63fe53a Compare November 20, 2026 22:47
@wwwjn

wwwjn commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @wwwjn's task in 1m 27s —— View job


Needs discussion: the three items from the last review are fixed; the human-written summary and whether to land this ahead of #6303 are still open. Review

@claude claude Bot 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.

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 in training_sample_builder.py. The policy-age comment in batcher.py and the packer TODO above MicrobatchPacker are also restored.
  • Resolved: the leftover image_data lookup is gone. _build_training_sample uses spec.images, and the docstring sentence about it is dropped.
  • Resolved: check_prompt_prefixes raises 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

  1. 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 holds prompt_prefix_len when prompt_prefix_len < previous_len. Its condition and message match the builder's own prompt_prefix_len > prev_len raise. The builder's raise can no longer fire through the batcher, but it still guards direct callers of rollout_to_training_sample_specs.
  • Specs only start at turn 0 or at a prefix break, because spec_in_progress is None only there. So the prefix that rollout_to_training_samples captures at a spec's first turn is always the cut previous, including when an earlier spec in the same rollout was dropped.
  • The new .tolist() calls in pack_planned and rollout_turn_lengths run 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.

@wwwjn
wwwjn force-pushed the wwwjn/data-plane/3-batcher-split branch from 27ba59e to b2b34eb Compare November 25, 2026 00:21
@wwwjn

wwwjn commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @wwwjn's task in 1m 6s —— View job


Needs discussion: the restack onto the updated #6301 adds no new problems, and the human-written summary and the call on landing this ahead of #6303 are still open. Review

@claude claude Bot 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.

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

  1. 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.

@wwwjn
wwwjn force-pushed the wwwjn/data-plane/3-batcher-split branch from b2b34eb to d148fc6 Compare November 30, 2026 19:58
@wwwjn
wwwjn force-pushed the wwwjn/data-plane/3-batcher-split branch from d148fc6 to 196c0d9 Compare November 30, 2026 20:29
Comment thread torchtitan/rl/rollout/types.py Outdated


@dataclass(frozen=True, slots=True)
class RolloutTurnLengths:

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.

Rename something to be RolloutTurnMetadata?

Comment thread torchtitan/rl/trainer/batcher.py Outdated


@dataclass(frozen=True, slots=True)
class StepPlan:

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.

Bad name

And this data structure is confusing...



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

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.

_SampleSpecInProgress

Comment thread torchtitan/rl/trainer/batcher.py Outdated
# 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:

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.

Why we need this packer???

@wwwjn
wwwjn force-pushed the wwwjn/data-plane/3-batcher-split branch from 196c0d9 to 26b57b0 Compare November 30, 2026 20:52
@wwwjn

wwwjn commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @wwwjn's task in 4m 24s —— View job


Needs discussion: the rebased head is correct and the moves to #6303 are clean. Three mechanical items are left, plus a maintainer call on landing this ahead of #6303 given the batcher GC rise per step. Review

@claude claude Bot 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.

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 _SpecInProgress to _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

  1. 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).
  2. tests/rl/unit_tests/cpu/test_rollout_utils.py:33 -- a redundant _check_prompt_prefixes call is the only reason the test imports that private name (inline comment).
  3. training_sample_builder.py:139 -- apply @wwwjn's _SampleSpecInProgress rename (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 -- _decide only 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 RolloutGroup after build_from_group. Now it keeps every trainable group alive until the step, including each turn's prompt_messages (the full conversation), completion_message, env_messages and metrics. 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.py to training_batch_builder.py and the batcher_* trace spans. This PR adds batcher_plan and batcher_build_training_samples. Which one rebases on the other?
Details
  • Traced _SpecInProgress.to_training_sample_spec against _build_training_sample after this rebase. Completion starts, the depth-d loss count (max(end - max(start, d+1), 0) minus non-finite offsets at or after first), and max(n - d, 0) routing all match the packed target_mask. The base no longer has the empty-completion continue. A 1-turn empty completion gives loss_token_counts[0] == 0, so the no-valid-loss filter drops it.
  • _pack_one_training_batch: every taken trainable group has specs in assignments, and samples_by_id.pop consumes each sample exactly once.
  • Overlap search: gh pr list --search for "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.

Comment thread torchtitan/rl/trainer/batcher.py Outdated
Comment on lines +1283 to +1285
# 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.

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.

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:

Suggested change
# 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.

Comment on lines +28 to +35
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)

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.

_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):

Suggested change
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)

Comment on lines +643 to +663
_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]]

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.

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, not rollout.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 at prompt_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.

Comment on lines +168 to +174
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,
)

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.

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.

@wwwjn
wwwjn force-pushed the wwwjn/data-plane/3-batcher-split branch from 26b57b0 to e8fe290 Compare November 30, 2026 21:23
@wwwjn

wwwjn commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

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

@claude claude Bot 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.

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:

  • _SpecInProgress is renamed to _SampleSpecInProgress.
  • The packer TODO is back above _pack_training_samples (batcher.py:2046 in the diff).
  • test_rollout_utils.py no longer imports _check_prompt_prefixes.
  • The _decide test 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_prefixes call and the private import in test_rollout_utils.py are gone.
  • Resolved: @wwwjn's _SampleSpecInProgress rename is applied.
  • Resolved: _decide in test_training_sample_spec.py is deleted.
  • Still open (should consider): fold the "too few" check into the rollout_to_training_samples walk 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_groups returns only the trainable RolloutGroups, and _pack_one_training_batch drops each one after build_training_samples. The only other live reference is add_group's argument, which holds the group that triggered the step. This matches [3, 2, 1] in test_the_step_trigger_frees_each_groups_arrays_before_the_next_is_built.
  • build_training_samples returns samples in spec order, so the samples_by_id keyed by RolloutTurnID in _pack_one_training_batch maps 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_samples or TrainingSampleGroup in torchtitan/, tests/ or docs/.
  • Overlap search: gh pr list --search for "batcher" and "training_sample_builder". It found #6423 (above), this stack (#6301, #6303, #6323, #6324, #6334), #6283 and #5475 (also touches training_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.

@wwwjn
wwwjn added this pull request to stack #6467 December 1, 2026 16:52
@wwwjn
wwwjn removed this pull request from stack #6467 December 1, 2026 21:17
@wwwjn
wwwjn added this pull request to stack #6471 December 1, 2026 21:18
@wwwjn
wwwjn force-pushed the wwwjn/data-plane/3-batcher-split branch from e8fe290 to 8ab03d2 Compare December 1, 2026 22:50
@wwwjn wwwjn changed the title [rl] Split the batcher into a metadata half and a bytes half [WIP] [rl] Split the batcher into a metadata half and a bytes half Dec 1, 2026
@wwwjn

wwwjn commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

from claude: Rebased onto #6301's new head 6e2d4ba, where each rollout worker records its own groups (recorder_lines is gone, so nothing here carries recorder lines anymore). Built on the latest heads of this stack. RL CPU suite: same 4 local env failures as before; 10-step bitwise run with one validation: all non-timing TensorBoard tags and the recorded rollouts match #5862. @claude review

@claude

claude Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @wwwjn's task in 1m 33s —— View job


Needs discussion: the restack onto #6301 6e2d4ba adds no new problems; still open are the maintainer call on landing this ahead of #6303 and the order with the #6423 rename. Review

@claude claude Bot 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.

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:

  • _SampleSpecInProgress and its count math
  • the length-only "too many" check in the spec walk
  • _check_prompt_prefixes at the start of rollout_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_samples walk 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: the rewards comprehension 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_specs in test_batcher.py, and test_multiturn_images.py now uses the shared rollout_to_training_samples helper.
  • Overlap search: gh pr list --search for "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.

@wwwjn
wwwjn force-pushed the wwwjn/data-plane/3-batcher-split branch from 8ab03d2 to f30bacc Compare December 2, 2026 00:07

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

1 participant