Repository navigation
[data] Compute valid-token counts during collation - #4398
Conversation
## Summary `Trainer.train_step` scanned every microbatch's labels for `IGNORE_INDEX` on the host, before the batch was moved to the device. That put a full CPU pass over the labels of every microbatch on the training loop's critical path, once per optimizer step. Collators already materialize the labels while building the batch, and they run in the Grain prefetch thread, so the count is effectively free there. `TextCollator` and `MultiModalCollator` now return their inputs as a `BatchInputsWithMetadata`, a dict subclass carrying `num_valid_tokens` alongside the model kwargs, which keeps the existing two-value batch interface intact. The trainer reads the count through `get_batch_num_valid_tokens`, which falls back to a local label scan for batches that do not carry it. `FluxCollator` deliberately does not attach a count. Flux labels are raw image tensors rather than token targets, and `FluxTrainer.train_step` computes its own count from the encoded latents after the image encoder runs. Those batches keep taking the fallback path, exactly as before. Numerics are unchanged: the count is the same integer, reduced the same way. The only difference is that `local_valid_tokens` accumulates as a Python `int` and is materialized once as a device tensor for the data-parallel all-reduce, instead of accumulating in a host tensor that was copied to the device. ## Test plan - `pytest -q tests/unit_tests/cpu/components tests/unit_tests/cpu/test_trainer.py tests/unit_tests/cpu/test_validate.py tests/unit_tests/cpu/test_packed_vision.py tests/unit_tests/cpu/test_chat_dataset.py tests/unit_tests/cpu/test_dataset_checkpointing.py tests/unit_tests/cpu/test_mm_dataset_checkpointing.py tests/unit_tests/cpu/test_dataset_flux.py` -- 150 passed - New coverage: `TextCollator` and `MultiModalCollator` attach the count, a collator without token labels leaves it unset, `get_batch_num_valid_tokens` falls back to a label scan, and batches out of `GrainDataLoader` carry the count end to end. - `pre-commit run --files <changed files>`
fegin
left a comment
There was a problem hiding this comment.
cc., @jinsooihm to review too
| """Use a pipeline-provided token count, falling back to a local label scan.""" | ||
| num_valid_tokens = getattr(input_dict, "num_valid_tokens", None) | ||
| if num_valid_tokens is not None: | ||
| return num_valid_tokens |
There was a problem hiding this comment.
Will the num_valid_tokens get passed into the model forward()? If yes, this may cause issues for some models. If no errors will occurs, it is better to keep the input_dict as what the models expect.
There was a problem hiding this comment.
Also, it feels a little awkward that input_dict contains num_valid_tokens which is an information about the labels, but does not actually contain the labels.
There was a problem hiding this comment.
I think we should put labels in input_dict, why not?
tianyu-l
left a comment
There was a problem hiding this comment.
23 ms in the PP2 case for dsv3-671B with 32 microbatches.
How much would it give us, from 92.29%?
| with sl.log_trace_span("fetching_batch"): | ||
| input_dict, labels = next(data_iterator) | ||
| local_valid_tokens += (labels != IGNORE_INDEX).sum() | ||
| local_valid_tokens += get_batch_num_valid_tokens( |
There was a problem hiding this comment.
Comment 1: compared with having a standalone util function + dataclass, I'd rather just making it a default field for (text) dataloader.
Comment 2: Instead of loading all microbatches -> compute global_valid_tokens -> start training, I think @felipemello1 wants the capability of "train-microbatch-as-you-go" without knowing exact loss scale, and later adjust the gradient. I didn't embrace the idea, but maybe it'd become absolute necessary. Anyway that's another direction.
There was a problem hiding this comment.
re 1. Agree that making this a default field is nicer .
re 2. Current approach is divide the gradient before accumulation. The other approach is divide after accumulation. I think both works, I don't see the clear benefit of second approach tho.
There was a problem hiding this comment.
Second approach allows overlapping. Today we do:
[load data 1] [load data 2] [load data 3]
[train batch 1] [train batch 2] [train batch 3]Instead, we could do:
[load data 1] [load data 2] [load data 3]
[train batch 1] [train batch 2] [train batch 3]For pretraining, its not a big deal. We prefetch the data. Perhaps for multimodal it makes a difference?
But, for RL, this is a major bottleneck.
Here, "load data N" is actually generating it on the fly. So its very slow. In some settings, we can easily do >100 grad acc steps per train step. Waiting for all 100 batches being ready so we can start training means the trainer stays idle for a long time unnecessarily.
The "prefetch" equivalent is higher off policy, which is undesirable in RL.
Let me know if that makes sense
There was a problem hiding this comment.
per offline discussion, I agree overlapping is needed for RL training.
Let's do that in another PR? This PR would be just moving the valid token counting to dataloader.
There was a problem hiding this comment.
Agree that overlapping deserves another PR.
Step time is ~10s, so this is ~0.2% for this case. |
Review feedback on #4398: drop the `BatchInputsWithMetadata` dict subclass and the `get_batch_num_valid_tokens` helper, and make the count an ordinary field of the batch dict that the text and multimodal collators always populate. `decoder.preprocess_inputs` pops only `input`/`labels` and forwards every remaining key as `**extra_kwargs` to the model, so a plain field would reach `forward()` (and CP sharding, and SPMD annotation) on the way. The consumers therefore pop it: `Trainer.train_step`, `Validator`, and the forge and torchft experiment trainers, all of which read the batch before the model sees it. That answers the question on the original review -- nothing extra reaches `forward()`, and the dict handed to the model is exactly what it expects. The validator now uses the popped count instead of its own device-side label scan, and builds its reduction tensor once like the trainer does. `Trainer.train_step` is annotated with the `TrainerBatch` alias, since the old `dict[str, torch.Tensor]` no longer describes a dict holding an int. The field is required rather than optional: a batch that reaches the trainer or validator without it raises `KeyError` instead of silently rescanning. `FluxCollator` does not set it and is unaffected -- Flux labels are image tensors, and Flux has its own trainer and validator that compute their own counts. ## Test plan - `pytest -q tests/unit_tests/cpu --ignore=tests/unit_tests/cpu/test_torch_checkpointing.py` -- 773 passed, 1 skipped. The one failure, `test_lora.py::test_lora_forward`, is a pre-existing Inductor flex-CPU error that reproduces on a clean tree. - `pre-commit run --files <changed files>`
Surveyed, not merged -- two 80B captures are mid-flight and folding in 64 commits would make any new failure ambiguous. This records the analysis so the merge is cheap later. Diverged at 6ee6d5d (2026-08-30), upstream tip 966befc. ZERO upstream commits touch experiments/ezpz, so there are no conflicts in our own code. The risk is entirely in core files we import from. Of those, components/loss.py matters most: we import BaseLoss, CrossEntropyLoss, ChunkedLossWrapper and IGNORE_INDEX, all four still present, with one method renamed (typecheck_forward -> spmd_typecheck). zloss.py overrides only __init__ and __call__, so it does not inherit that rename -- checked rather than assumed, since a preserved name with a changed contract is the dangerous case, not a deleted one. Corrects my earlier risk ranking. I called pytorch#4328 (refactor max_context_length) the highest risk; that was wrong. max_context_length is UNCHANGED upstream -- same field, same default, plus a validation guard. The PR changes seq_len in model specs and registries, not the --training.max-context-length flag we pass. The single seam is agpt/config_registry.py:291, where our own agpt(seq_len=...) assigns cfg.training.max_context_length. The real risks, ordered: pytorch#4398 (valid-token counts move into collation -- that is the gradient-accumulation path), then the checkpoint cluster (pytorch#4187/pytorch#4188/pytorch#4197/pytorch#4270/pytorch#4474, which we subclass and where pinned clones have already broken on optim-statedict changes), then pytorch#4382 (Adam first-step state). Includes a merge order: smoke at 2N, then a resume from a real checkpoint, a seeded loss/grad_norm comparison, and config_registry.py:291 by inspection.
Summary
Trainer.train_stepscanned every microbatch's labels forIGNORE_INDEXon the host, before the batch was moved to the device. That put a full CPU pass over the labels of every microbatch on the training loop's critical path, once per optimizer step.Collators already materialize the labels while building the batch, and they run in the Grain prefetch thread, so the count is effectively free there.
TextCollatorandMultiModalCollatornow setnum_valid_tokensas an ordinary field of the batch dict, which keeps the existing two-value batch interface intact.The consumers pop the field before the batch reaches the model:
Trainer.train_step,Validator, and the forge and torchft experiment trainers. Popping matters becausedecoder.preprocess_inputspops onlyinput/labelsand forwards every remaining key as**extra_kwargstomodel()— so leaving the field in place would send it intoforward(), and into CP sharding and SPMD annotation on the way. With the pop, the dict the model receives is exactly what it expects.Two knock-on cleanups: the validator now uses the popped count instead of its own device-side label scan and builds its reduction tensor once like the trainer, and
Trainer.train_stepis annotated with theTrainerBatchalias, sincedict[str, torch.Tensor]no longer describes a dict holding an int.FluxCollatordoes not set the field. Flux labels are raw image tensors rather than token targets, and Flux has its own trainer and validator that compute their own counts, so it is unaffected.Behavior change
The field is required, not optional. A batch reaching the core trainer or validator without it raises
KeyErrorrather than silently rescanning the labels. That is a breaking change for out-of-tree dataloaders, but it fails loudly.Popping mutates the caller's dict, which is consistent with the existing in-place
input_dict[key] = value.to(device). Grain yields a fresh dict per batch, so this is safe here; a dataloader that recycles batch dicts would break on the second read.Numerics
Unchanged. The count is the same integer, reduced the same way. The only difference is that
local_valid_tokensaccumulates as a Pythonintand is materialized once as a device tensor for the data-parallel all-reduce, instead of accumulating in a host tensor that was then copied to the device.Test plan
773 passed, 1 skipped. The single failure,
test_lora.py::test_lora_forward, is a pre-existing Inductor flex-CPU error that reproduces on a clean tree.New coverage:
TextCollatorandMultiModalCollatorpopulate the field, and batches out ofGrainDataLoadercarry it end to end. Trainer, validator, and invalid-loss fixtures were updated to supply it — including three that reused a single dict object across microbatches, which the pop exposed.pre-commit run --files <changed files>is clean.Review notes
Second commit addresses the feedback from @fegin, @jinsooihm and @tianyu-l: the
BatchInputsWithMetadatadict subclass and theget_batch_num_valid_tokenshelper are gone, replaced by the plain default field.