Repository navigation
Conversation
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.
|
@claude review |
There was a problem hiding this comment.
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
- The "Summary (human-written)" section of the PR description is empty. Please fill it in.
torchtitan/components/data/padding.py:101--get_microbatch_token_countsonly wrapsget_mtp_token_countsto add the squeeze. Move the squeeze intoget_mtp_token_countsand 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, labelsIGNORE_INDEX, positionsarange % max_context_length, padding_mask True). It is in numpy and builds aTextSequence, sopack_microbatch_fieldsmay 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 == 0branch),training_batch_builder.py:660(reshape(-1)[0]),controller.py:1649(reshape(-1)[0]),TrainingEngine.forward_backward(torch.as_tensor), and Monarch RDMA (_TensorRefkeepsshape;view(-1)works on 0-d). With MTP,MTPCrossEntropyLossstill 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 fromnp.concatenate(dtype=float32)to a per-segmenttorch.as_tensor(dtype=float32); both round to nearest. Pinning is unchanged: pinned forTextCollator, 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 >= 0becomes aValueError. 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.
| 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 |
There was a problem hiding this comment.
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)
Summary (human-written)
Why
Pretraining and RL build the same
TokenizedTrainingMicrobatchin three copies:TextCollator,MultiModalCollator.collate_textand RL'sTrainingBatchBuilder._pack_training_sampleseach concatenate their rows' per-token fields, pad the microbatch tail (positions0, 1, ...modulomax_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):
What changed
components/data/padding.py(next toappend_padded_segment, already shared):pack_microbatch_fieldsconcatenates each field's segments into one buffer of its final size and pads the tail;get_microbatch_token_countswrapsget_mtp_token_counts, with the loss count a scalar without MTP layers.TextCollator,MultiModalCollator.collate_textandTrainingBatchBuilder._pack_training_samplescall them, each with its own fields, fill values and pinning.TextCollatorstill writes each field once, into a page-locked buffer (no extra copy on the pretraining path); the other two stay unpinned as before.reshape(-1)[0]or checkndim(controller.py's perf metrics now usereshape(-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
lossandgrad_normbefore (#6423) vs after, 10 steps, seed 42, deterministic:TextCollatorscripts/loss_compare.py --assert-equal, grad_norm from TensorBoard)MultiModalCollatordebugmodel_mm, flex attentionTrainingBatchBuilderrl_grpo_qwen3_0_6b_varlen_batch_invariant, trainer TP 2 + vLLM TP 2loss/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.Known issues / follow-ups