Skip to content

[data] Share microbatch assembly between pretraining and RL - #6427

Open
tianyu-l wants to merge 1 commit into
training-batch-builderfrom
shared-microbatch-assembly
Open

tianyu-l wants to merge 1 commit into
training-batch-builderfrom
shared-microbatch-assembly

Conversation

@tianyu-l

Copy link
Copy Markdown
Contributor

Summary (human-written)

Why

Pretraining and RL build the same TokenizedTrainingMicrobatch in three copies: TextCollator, MultiModalCollator.collate_text and RL's TrainingBatchBuilder._pack_training_samples each concatenate their rows' per-token fields, pad the microbatch tail (positions 0, 1, ... modulo max_context_length, padding mask True, field-specific fill values) and compute the MTP token counts. They already drifted: RL's loss-token count is [1] without MTP layers, the others' a scalar. This is the first step of sharing batch preparation between RL and pretraining; the next shares the multimodal path (image transport and M-RoPE from explicit placeholder spans), so RL and SFT recipes configure images the same way.

Example (num_tokens 6, max_context_length 8):

rows      input_ids [[5, 6], [7]]   labels [[6, -100], [8]]   positions [[0, 1], [0]]
packed -> input_ids [5, 6, 7, 0, 0, 0]          labels [6, -100, 8, -100, -100, -100]
          positions [0, 1, 0, 0, 1, 2]          padding_mask [F, F, F, T, T, T]

What changed

  • components/data/padding.py (next to append_padded_segment, already shared): pack_microbatch_fields concatenates each field's segments into one buffer of its final size and pads the tail; get_microbatch_token_counts wraps get_mtp_token_counts, with the loss count a scalar without MTP layers.
  • TextCollator, MultiModalCollator.collate_text and TrainingBatchBuilder._pack_training_samples call them, each with its own fields, fill values and pinning. TextCollator still writes each field once, into a page-locked buffer (no extra copy on the pretraining path); the other two stay unpinned as before.
  • RL's loss-token count without MTP layers becomes a scalar, as pretraining's already is. Its consumers read it with reshape(-1)[0] or check ndim (controller.py's perf metrics now use reshape(-1)[0]); three test assertions and one test fake follow.

Not shared (they change which samples are packed together): bin packing and DP-rank assignment.

Numerics

Bitwise equal loss and grad_norm before (#6423) vs after, 10 steps, seed 42, deterministic:

Path Config GPUs Result
Pretraining, TextCollator llama3 debug model, flex attention 1 GB300 bitwise equal (scripts/loss_compare.py --assert-equal, grad_norm from TensorBoard)
SFT, MultiModalCollator Muse Glimmer debugmodel_mm, flex attention 1 GB300 bitwise equal
RL, TrainingBatchBuilder rl_grpo_qwen3_0_6b_varlen_batch_invariant, trainer TP 2 + vLLM TP 2 4 GB300 bitwise equal loss/mean, grad_norm, coefficient_l1, logprob_diff; same TensorBoard tags

(Flex attention for the pretraining runs: varlen attention isn't bitwise reproducible on this host.)

Testing

  • pytest tests/rl/unit_tests/cpu tests/unit_tests/cpu/components/data tests/unit_tests/cpu/test_trainer.py: 1,136 passed, 7 skipped.
  • Net +35 lines: the two helpers' docstrings and example; the three call sites shrink.

Known issues / follow-ups

TextCollator, MultiModalCollator and RL's TrainingBatchBuilder each concatenated their
rows' per-token fields, padded the microbatch tail (positions 0, 1, ... modulo
max_context_length, padding mask True, field-specific fill values) and computed the
MTP token counts, in three copies. pack_microbatch_fields and
get_microbatch_token_counts (components/data/padding.py, next to append_padded_segment)
now do it for all three; each caller keeps its own fields, fill values and pinning
(TextCollator still writes each field once, into a page-locked buffer).

RL's loss-token count becomes a scalar without MTP layers, as pretraining's already is;
its consumers read it with reshape(-1)[0] or check ndim.
@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Nov 28, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 28, 2026
@tianyu-l
tianyu-l added this pull request to stack #6396 November 28, 2026 05:02
@tianyu-l

Copy link
Copy Markdown
Contributor Author

@claude review

@github-actions
github-actions Bot requested a review from pzhan9 November 28, 2026 05:02
@claude

claude Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the items before merging: 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: Approve -- please address the items below before merging -- a clean dedup of three microbatch tail-padding copies. I found no numerics or consumer breakage. The remaining items are small, local edits.

What this PR does. TextCollator, MultiModalCollator.collate_text and RL's TrainingBatchBuilder._pack_training_samples each concatenated per-token fields and padded the microbatch tail. They now all call pack_microbatch_fields, which allocates each field at its final size and writes it once. Loss-token counts now come from a single helper, so RL's no-MTP count becomes a scalar tensor(N) instead of tensor([N]), matching pretraining.

Example. RL call site, before -> after:

# before: pad tail by hand, np.concatenate, from_numpy, then get_mtp_token_counts -> loss counts shape (1,)
pad_len = num_tokens_per_rank - sum(sample_lens); packed_fields[key].append(pad(key, pad_len)); ...
# after: one call; loss counts shape () without MTP
packed = pack_microbatch_fields(packed_fields, num_tokens=..., max_context_length=self.seq_len,
                                fill_values=pad_values, dtypes=_DTYPES, pin_memory=False)

Must fix

  1. The "Summary (human-written)" section of the PR description is empty. Please fill it in.
  2. torchtitan/components/data/padding.py:101 -- get_microbatch_token_counts only wraps get_mtp_token_counts to add the squeeze. Move the squeeze into get_mtp_token_counts and delete the wrapper (inline comment).

Should consider

  • torchtitan/components/data/packing.py:209-216 (not in the diff): the row packer has a fourth copy of the same tail fill (input_ids 0, labels IGNORE_INDEX, positions arange % max_context_length, padding_mask True). It is in numpy and builds a TextSequence, so pack_microbatch_fields may not fit it as is. Still, the "three copies" framing leaves this one out. Either fold it in here or note it as a follow-up.
Details
  • Consumers of the scalar count. These all handle both shapes: policy_gradient._normalize (ndim == 0 branch), training_batch_builder.py:660 (reshape(-1)[0]), controller.py:1649 (reshape(-1)[0]), TrainingEngine.forward_backward (torch.as_tensor), and Monarch RDMA (_TensorRef keeps shape; view(-1) works on 0-d). With MTP, MTPCrossEntropyLoss still gets the (1 + num_mtp_layers,) vector it requires.
  • Bitwise equality is plausible. Fill values, positions (arange % max_context_length) and padding mask are unchanged on all three paths. RL's float64 -> float32 logprob cast moves from np.concatenate(dtype=float32) to a per-segment torch.as_tensor(dtype=float32); both round to nearest. Pinning is unchanged: pinned for TextCollator, unpinned for the other two. Multimodal positions and input_ids are now forced to int64, which the dataset already produces (mm_datasets.py:118,658).
  • Error handling. RL's assert pad_len >= 0 becomes a ValueError. That is fine.

Not verified: the GPU bitwise loss comparisons in the description. I also couldn't run the CPU tests in this job because pytest needed approval. A maintainer still needs to review, since this touches the shared data path.

Comment on lines +101 to +118
def get_microbatch_token_counts(
*,
target_mask: torch.Tensor,
positions: torch.Tensor,
padding_mask: torch.Tensor,
num_mtp_layers: int,
) -> tuple[torch.Tensor, torch.Tensor]:
"""A microbatch's ``(loss_token_counts, routing_token_counts)``: `get_mtp_token_counts`,
with the loss count a scalar without MTP layers."""
loss_token_counts, routing_token_counts = get_mtp_token_counts(
target_mask=target_mask,
positions=positions,
padding_mask=padding_mask,
num_mtp_layers=num_mtp_layers,
)
if num_mtp_layers == 0:
loss_token_counts = loss_token_counts[0]
return loss_token_counts, routing_token_counts

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 wraps get_mtp_token_counts only to add the 0-MTP squeeze. Put the squeeze in get_mtp_token_counts itself (torchtitan/models/common/mtp.py:91) and delete this wrapper. The other callers are fine with that: graph_trainer/precompile_main.py:251 reads only routing_token_counts, and test_loss.py uses only num_mtp_layers >= 1. The scalar-vs-vector contract then lives in the function that builds the counts, so no builder can drift from it again (the RL [1] drift this PR fixes came from callers each applying the squeeze themselves). It also keeps the MTP import out of padding.py, whose docstring is about token packing. About -17 lines.

    loss_token_counts_tensor = torch.stack(loss_token_counts)
    if num_mtp_layers == 0:
        # Without MTP the loss count is a scalar, as non-MTP losses expect.
        loss_token_counts_tensor = loss_token_counts_tensor[0]
    return loss_token_counts_tensor, torch.stack(routing_token_counts)

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/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant