Repository navigation
Always Pre-Split Microbatches for PP - #3856
Conversation
Summary: - Have PP training and validation dataloaders emit pipeline microbatches directly. - Group dataloader-produced microbatches into pre-split args/kwargs/targets for torch.distributed.pipelining schedule.step/eval. - Remove the PP+Varlen guard and switch the GPT-OSS PP integration test back to the default varlen config. - Update copied PP train paths in TorchFT and Forge to use the pre-split schedule API. Motivation: TorchTitan previously built a full local batch and relied on torch.distributed.pipelining to split it. That does not work for batch-dependent non-tensor metadata such as varlen attention metadata. Owning the split at the dataloader/trainer boundary lets TorchTitan generate block masks and varlen metadata per pipeline microbatch before calling the PP schedule. Test Plan: - python -m py_compile torchtitan/trainer.py torchtitan/components/validate.py torchtitan/models/common/decoder.py torchtitan/models/gpt_oss/config_registry.py tests/integration_tests/models.py torchtitan/experiments/torchft/trainer.py torchtitan/experiments/forge/engine.py torchtitan/experiments/forge/example_train.py - SKIP=pyrefly-check pre-commit run --files torchtitan/trainer.py torchtitan/components/validate.py torchtitan/models/common/decoder.py torchtitan/models/gpt_oss/config_registry.py tests/integration_tests/models.py torchtitan/experiments/torchft/trainer.py torchtitan/experiments/forge/engine.py torchtitan/experiments/forge/example_train.py - python tests/integration_tests/run_tests.py <output_dir> --test_suite models --test_name gpt_oss_pp+fsdp+ep+sacop --ngpu 8 --no-parallel - NGPU=2 LOG_RANK=0,1 ./run_train.sh --module gpt_oss --config gpt_oss_debugmodel --parallelism.pipeline_parallel_degree 2 --parallelism.pipeline_parallel_schedule 1F1B --training.steps 1 --validator.enable --validator.steps 1 [ghstack-poisoned]
Summary: - Have PP training and validation dataloaders emit pipeline microbatches directly. - Group dataloader-produced microbatches inline into pre-split args/kwargs/targets for torch.distributed.pipelining schedule.step/eval. - Remove the PP+Varlen guard and switch the GPT-OSS PP integration test back to the default varlen config. - Update copied PP train paths in TorchFT and Forge to use the pre-split schedule API. Motivation: TorchTitan previously built a full local batch and relied on torch.distributed.pipelining to split it. That does not work for batch-dependent non-tensor metadata such as varlen attention metadata. Owning the split at the dataloader/trainer boundary lets TorchTitan generate block masks and varlen metadata per pipeline microbatch before calling the PP schedule. Test Plan: - python -m py_compile torchtitan/trainer.py torchtitan/components/validate.py torchtitan/models/common/decoder.py torchtitan/models/gpt_oss/config_registry.py tests/integration_tests/models.py torchtitan/experiments/torchft/trainer.py torchtitan/experiments/forge/engine.py torchtitan/experiments/forge/example_train.py - pre-commit run --files torchtitan/trainer.py torchtitan/components/validate.py torchtitan/models/common/decoder.py torchtitan/models/gpt_oss/config_registry.py tests/integration_tests/models.py torchtitan/experiments/torchft/trainer.py torchtitan/experiments/forge/engine.py torchtitan/experiments/forge/example_train.py - python -m tests.integration_tests.run_tests <output_dir> --test_suite models --test_name gpt_oss_pp+fsdp+ep+sacop --ngpu 8 - NGPU=2 LOG_RANK=0,1 ./run_train.sh --dump_folder <output_dir> --module gpt_oss --config gpt_oss_debugmodel --parallelism.pipeline_parallel_degree 2 --parallelism.pipeline_parallel_schedule 1F1B --training.steps 1 --validator.enable --validator.steps 1 [ghstack-poisoned]
Summary: - Have PP training and validation dataloaders emit pipeline microbatches directly. - Group dataloader-produced microbatches inline into pre-split args/kwargs/targets for torch.distributed.pipelining schedule.step/eval. - Remove the PP+Varlen guard and switch the GPT-OSS PP integration test back to the default varlen config. - Update copied PP train paths in TorchFT and Forge to use the pre-split schedule API. Motivation: TorchTitan previously built a full local batch and relied on torch.distributed.pipelining to split it. That does not work for batch-dependent non-tensor metadata such as varlen attention metadata. Owning the split at the dataloader/trainer boundary lets TorchTitan generate block masks and varlen metadata per pipeline microbatch before calling the PP schedule. Test Plan: - python -m py_compile torchtitan/trainer.py torchtitan/components/validate.py torchtitan/models/common/decoder.py torchtitan/models/gpt_oss/config_registry.py tests/integration_tests/models.py torchtitan/experiments/torchft/trainer.py torchtitan/experiments/forge/engine.py torchtitan/experiments/forge/example_train.py - pre-commit run --files torchtitan/trainer.py torchtitan/components/validate.py torchtitan/models/common/decoder.py torchtitan/models/gpt_oss/config_registry.py tests/integration_tests/models.py torchtitan/experiments/torchft/trainer.py torchtitan/experiments/forge/engine.py torchtitan/experiments/forge/example_train.py - python -m tests.integration_tests.run_tests <output_dir> --test_suite models --test_name gpt_oss_pp+fsdp+ep+sacop --ngpu 8 - NGPU=2 LOG_RANK=0,1 ./run_train.sh --dump_folder <output_dir> --module gpt_oss --config gpt_oss_debugmodel --parallelism.pipeline_parallel_degree 2 --parallelism.pipeline_parallel_schedule 1F1B --training.steps 1 --validator.enable --validator.steps 1 ghstack-source-id: e45a042 Pull Request resolved: #3856
Summary: - Have PP training and validation dataloaders emit pipeline microbatches directly. - Group dataloader-produced microbatches inline into pre-split args/kwargs/targets for torch.distributed.pipelining schedule.step/eval. - Remove the PP+Varlen guard and switch the GPT-OSS PP integration test back to the default varlen config. - Update copied PP train paths in TorchFT and Forge to use the pre-split schedule API. Motivation: TorchTitan previously built a full local batch and relied on torch.distributed.pipelining to split it. That does not work for batch-dependent non-tensor metadata such as varlen attention metadata. Owning the split at the dataloader/trainer boundary lets TorchTitan generate block masks and varlen metadata per pipeline microbatch before calling the PP schedule. Test Plan: - python -m py_compile torchtitan/trainer.py torchtitan/components/validate.py torchtitan/models/common/decoder.py torchtitan/models/gpt_oss/config_registry.py tests/integration_tests/models.py torchtitan/experiments/torchft/trainer.py torchtitan/experiments/forge/engine.py torchtitan/experiments/forge/example_train.py - pre-commit run --files torchtitan/trainer.py torchtitan/components/validate.py torchtitan/models/common/decoder.py torchtitan/models/gpt_oss/config_registry.py tests/integration_tests/models.py torchtitan/experiments/torchft/trainer.py torchtitan/experiments/forge/engine.py torchtitan/experiments/forge/example_train.py - python -m tests.integration_tests.run_tests <output_dir> --test_suite models --test_name gpt_oss_pp+fsdp+ep+sacop --ngpu 8 - NGPU=2 LOG_RANK=0,1 ./run_train.sh --dump_folder <output_dir> --module gpt_oss --config gpt_oss_debugmodel --parallelism.pipeline_parallel_degree 2 --parallelism.pipeline_parallel_schedule 1F1B --training.steps 1 --validator.enable --validator.steps 1 [ghstack-poisoned]
Summary: - Have PP training and validation dataloaders emit pipeline microbatches directly. - Group dataloader-produced microbatches inline into pre-split args/kwargs/targets for torch.distributed.pipelining schedule.step/eval. - Remove the PP+Varlen guard and switch the GPT-OSS PP integration test back to the default varlen config. - Update copied PP train paths in TorchFT and Forge to use the pre-split schedule API. Motivation: TorchTitan previously built a full local batch and relied on torch.distributed.pipelining to split it. That does not work for batch-dependent non-tensor metadata such as varlen attention metadata. Owning the split at the dataloader/trainer boundary lets TorchTitan generate block masks and varlen metadata per pipeline microbatch before calling the PP schedule. Test Plan: - python -m py_compile torchtitan/trainer.py torchtitan/components/validate.py torchtitan/models/common/decoder.py torchtitan/models/gpt_oss/config_registry.py tests/integration_tests/models.py torchtitan/experiments/torchft/trainer.py torchtitan/experiments/forge/engine.py torchtitan/experiments/forge/example_train.py - pre-commit run --files torchtitan/trainer.py torchtitan/components/validate.py torchtitan/models/common/decoder.py torchtitan/models/gpt_oss/config_registry.py tests/integration_tests/models.py torchtitan/experiments/torchft/trainer.py torchtitan/experiments/forge/engine.py torchtitan/experiments/forge/example_train.py - python -m tests.integration_tests.run_tests <output_dir> --test_suite models --test_name gpt_oss_pp+fsdp+ep+sacop --ngpu 8 - NGPU=2 LOG_RANK=0,1 ./run_train.sh --dump_folder <output_dir> --module gpt_oss --config gpt_oss_debugmodel --parallelism.pipeline_parallel_degree 2 --parallelism.pipeline_parallel_schedule 1F1B --training.steps 1 --validator.enable --validator.steps 1 ghstack-source-id: e45a042 Pull Request resolved: #3856
Summary: - Have PP training and validation dataloaders emit pipeline microbatches directly. - Keep PP execution in the existing forward_backward_step/eval flow while passing pre-split args/kwargs/targets to torch.distributed.pipelining. - Remove the PP+Varlen guard and switch the GPT-OSS PP integration test back to the default varlen config. - Update copied PP train paths in TorchFT and Forge to use the pre-split schedule API with the same structure-preserving pattern. Motivation: TorchTitan previously built a full local batch and relied on torch.distributed.pipelining to split it. That does not work for batch-dependent non-tensor metadata such as varlen attention metadata. Owning the split at the dataloader/trainer boundary lets TorchTitan generate block masks and varlen metadata per pipeline microbatch before calling the PP schedule. Test Plan: - python -m py_compile torchtitan/trainer.py torchtitan/components/validate.py torchtitan/models/common/decoder.py torchtitan/models/gpt_oss/config_registry.py tests/integration_tests/models.py torchtitan/experiments/torchft/trainer.py torchtitan/experiments/forge/engine.py torchtitan/experiments/forge/example_train.py - pre-commit run --files torchtitan/trainer.py torchtitan/components/validate.py torchtitan/models/common/decoder.py torchtitan/models/gpt_oss/config_registry.py tests/integration_tests/models.py torchtitan/experiments/torchft/trainer.py torchtitan/experiments/forge/engine.py torchtitan/experiments/forge/example_train.py - python -m tests.integration_tests.run_tests <output_dir> --test_suite models --test_name gpt_oss_pp+fsdp+ep+sacop --ngpu 8 - NGPU=2 LOG_RANK=0,1 ./run_train.sh --dump_folder <output_dir> --module gpt_oss --config gpt_oss_debugmodel --parallelism.pipeline_parallel_degree 2 --parallelism.pipeline_parallel_schedule 1F1B --training.steps 1 --validator.enable --validator.steps 1 [ghstack-poisoned]
Summary: - Have PP training and validation dataloaders emit pipeline microbatches directly. - Keep PP execution in the existing forward_backward_step/eval flow while passing pre-split args/kwargs/targets to torch.distributed.pipelining. - Remove the PP+Varlen guard and switch the GPT-OSS PP integration test back to the default varlen config. - Update copied PP train paths in TorchFT and Forge to use the pre-split schedule API with the same structure-preserving pattern. Motivation: TorchTitan previously built a full local batch and relied on torch.distributed.pipelining to split it. That does not work for batch-dependent non-tensor metadata such as varlen attention metadata. Owning the split at the dataloader/trainer boundary lets TorchTitan generate block masks and varlen metadata per pipeline microbatch before calling the PP schedule. Test Plan: - python -m py_compile torchtitan/trainer.py torchtitan/components/validate.py torchtitan/models/common/decoder.py torchtitan/models/gpt_oss/config_registry.py tests/integration_tests/models.py torchtitan/experiments/torchft/trainer.py torchtitan/experiments/forge/engine.py torchtitan/experiments/forge/example_train.py - pre-commit run --files torchtitan/trainer.py torchtitan/components/validate.py torchtitan/models/common/decoder.py torchtitan/models/gpt_oss/config_registry.py tests/integration_tests/models.py torchtitan/experiments/torchft/trainer.py torchtitan/experiments/forge/engine.py torchtitan/experiments/forge/example_train.py - python -m tests.integration_tests.run_tests <output_dir> --test_suite models --test_name gpt_oss_pp+fsdp+ep+sacop --ngpu 8 - NGPU=2 LOG_RANK=0,1 ./run_train.sh --dump_folder <output_dir> --module gpt_oss --config gpt_oss_debugmodel --parallelism.pipeline_parallel_degree 2 --parallelism.pipeline_parallel_schedule 1F1B --training.steps 1 --validator.enable --validator.steps 1 ghstack-source-id: 51a5e12 Pull Request resolved: #3856
Summary: - Have PP training and validation dataloaders emit pipeline microbatches directly. - Keep PP execution in the existing forward_backward_step/eval flow while passing pre-split args/kwargs/targets to torch.distributed.pipelining. - Remove the PP+Varlen guard and switch the GPT-OSS PP integration test back to the default varlen config. - Update copied PP train paths in TorchFT and Forge to use the pre-split schedule API with the same structure-preserving pattern. Motivation: TorchTitan previously built a full local batch and relied on torch.distributed.pipelining to split it. That does not work for batch-dependent non-tensor metadata such as varlen attention metadata. Owning the split at the dataloader/trainer boundary lets TorchTitan generate block masks and varlen metadata per pipeline microbatch before calling the PP schedule. Test Plan: - python -m py_compile torchtitan/trainer.py torchtitan/components/validate.py torchtitan/models/common/decoder.py torchtitan/models/gpt_oss/config_registry.py tests/integration_tests/models.py torchtitan/experiments/torchft/trainer.py torchtitan/experiments/forge/engine.py torchtitan/experiments/forge/example_train.py - pre-commit run --files torchtitan/trainer.py torchtitan/components/validate.py torchtitan/models/common/decoder.py torchtitan/models/gpt_oss/config_registry.py tests/integration_tests/models.py torchtitan/experiments/torchft/trainer.py torchtitan/experiments/forge/engine.py torchtitan/experiments/forge/example_train.py - python -m tests.integration_tests.run_tests <output_dir> --test_suite models --test_name gpt_oss_pp+fsdp+ep+sacop --ngpu 8 - NGPU=2 LOG_RANK=0,1 ./run_train.sh --dump_folder <output_dir> --module gpt_oss --config gpt_oss_debugmodel --parallelism.pipeline_parallel_degree 2 --parallelism.pipeline_parallel_schedule 1F1B --training.steps 1 --validator.enable --validator.steps 1 [ghstack-poisoned]
Summary: - Have PP training and validation dataloaders emit pipeline microbatches directly. - Keep PP execution in the existing forward_backward_step/eval flow while passing pre-split args/kwargs/targets to torch.distributed.pipelining. - Remove the PP+Varlen guard and switch the GPT-OSS PP integration test back to the default varlen config. - Update copied PP train paths in TorchFT and Forge to use the pre-split schedule API with the same structure-preserving pattern. Motivation: TorchTitan previously built a full local batch and relied on torch.distributed.pipelining to split it. That does not work for batch-dependent non-tensor metadata such as varlen attention metadata. Owning the split at the dataloader/trainer boundary lets TorchTitan generate block masks and varlen metadata per pipeline microbatch before calling the PP schedule. Test Plan: - python -m py_compile torchtitan/trainer.py torchtitan/components/validate.py torchtitan/models/common/decoder.py torchtitan/models/gpt_oss/config_registry.py tests/integration_tests/models.py torchtitan/experiments/torchft/trainer.py torchtitan/experiments/forge/engine.py torchtitan/experiments/forge/example_train.py - pre-commit run --files torchtitan/trainer.py torchtitan/components/validate.py torchtitan/models/common/decoder.py torchtitan/models/gpt_oss/config_registry.py tests/integration_tests/models.py torchtitan/experiments/torchft/trainer.py torchtitan/experiments/forge/engine.py torchtitan/experiments/forge/example_train.py - python -m tests.integration_tests.run_tests <output_dir> --test_suite models --test_name gpt_oss_pp+fsdp+ep+sacop --ngpu 8 - NGPU=2 LOG_RANK=0,1 ./run_train.sh --dump_folder <output_dir> --module gpt_oss --config gpt_oss_debugmodel --parallelism.pipeline_parallel_degree 2 --parallelism.pipeline_parallel_schedule 1F1B --training.steps 1 --validator.enable --validator.steps 1 ghstack-source-id: 51a5e12 Pull Request resolved: #3856
| if parallel_dims.pp_enabled: | ||
| assert isinstance(input_dict, list) | ||
| assert isinstance(labels, list) | ||
| for mb_input_dict in input_dict: | ||
| for k, v in mb_input_dict.items(): | ||
| if isinstance(v, torch.Tensor): | ||
| mb_input_dict[k] = v.to(self.device) | ||
| labels = [mb_labels.to(self.device) for mb_labels in labels] | ||
| else: | ||
| assert isinstance(input_dict, dict) | ||
| assert isinstance(labels, torch.Tensor) | ||
| # Move tensors to GPU | ||
| for k, v in input_dict.items(): | ||
| if isinstance(v, torch.Tensor): | ||
| input_dict[k] = v.to(self.device) | ||
| labels = labels.to(self.device) |
There was a problem hiding this comment.
We cannot use PP with gradient accumulation after this PR, right? If so, do we error out somewhere if users try to use them together?
There was a problem hiding this comment.
Using pp with gradient accumulation doesn't make sense. PP is already doing gradient accumulation. So we can disable gradient accumulation for pp.
There was a problem hiding this comment.
I don't think that's true. See previous discussions in #1733
Conclusion is that we should continue to support gradient accumulation + PP.
There was a problem hiding this comment.
The main change / challenge in this PR is to properly differentiate PP microbatching vs. gradient accumulation microbatching, from UX / config perspective.
E.g. a simple way is to let user specify "local microbatch size"
- without PP it's the
local_batch_sizetoday, which is used together withglobal_batch_sizeto determine number of grad accum steps - with PP, it's the local microbatch size, whose product with num PP microbatches * num grad accum steps would have to equal
global_batch_size.
There was a problem hiding this comment.
Kept PP microbatching distinct from gradient accumulation. Each local batch is
split into num_pipeline_parallel_microbatches, and each gradient-accumulation
iteration invokes the PP schedule once with that group. The config docs now
state both batch-size relationships, and the combined path passed the 2-GPU
test plus a bitwise-identical 10-step loss and grad-norm comparison.
| if parallel_dims.pp_enabled: | ||
| assert isinstance(input_dict, list) | ||
| assert isinstance(labels, list) | ||
| for mb_input_dict in input_dict: | ||
| for k, v in mb_input_dict.items(): | ||
| if isinstance(v, torch.Tensor): | ||
| mb_input_dict[k] = v.to(self.device) | ||
| labels = [mb_labels.to(self.device) for mb_labels in labels] | ||
| else: | ||
| assert isinstance(input_dict, dict) | ||
| assert isinstance(labels, torch.Tensor) | ||
| # Move tensors to GPU | ||
| for k, v in input_dict.items(): | ||
| if isinstance(v, torch.Tensor): | ||
| input_dict[k] = v.to(self.device) | ||
| labels = labels.to(self.device) |
There was a problem hiding this comment.
I don't think that's true. See previous discussions in #1733
Conclusion is that we should continue to support gradient accumulation + PP.
| num_microbatches = ( | ||
| self.config.training.local_batch_size | ||
| // self.config.parallelism.pipeline_parallel_microbatch_size | ||
| if parallel_dims.pp_enabled | ||
| else 1 | ||
| ) |
There was a problem hiding this comment.
This is computed twice in constructor and here
There was a problem hiding this comment.
Computed num_pipeline_parallel_microbatches once during trainer construction
and reused the cached value for dataloader checkpoint cadence and training.
| local_valid_tokens += (labels != IGNORE_INDEX).sum() | ||
| microbatches.append((input_dict, labels)) | ||
| for _ in range(self.gradient_accumulation_steps): | ||
| if parallel_dims.pp_enabled: |
There was a problem hiding this comment.
it feels to me this can be improved -- two pieces of code seem almost identical
There was a problem hiding this comment.
Collapsed the duplicated PP and non-PP fetch branches into one loop. Each
gradient-accumulation iteration now builds one microbatch group whose size is
one without PP or num_pipeline_parallel_microbatches with PP.
| if parallel_dims.pp_enabled: | ||
| assert isinstance(input_dict, list) | ||
| assert isinstance(labels, list) | ||
| for mb_input_dict in input_dict: | ||
| for k, v in mb_input_dict.items(): | ||
| if isinstance(v, torch.Tensor): | ||
| mb_input_dict[k] = v.to(self.device) | ||
| labels = [mb_labels.to(self.device) for mb_labels in labels] | ||
| else: | ||
| assert isinstance(input_dict, dict) | ||
| assert isinstance(labels, torch.Tensor) | ||
| # Move tensors to GPU | ||
| for k, v in input_dict.items(): | ||
| if isinstance(v, torch.Tensor): | ||
| input_dict[k] = v.to(self.device) | ||
| labels = labels.to(self.device) |
There was a problem hiding this comment.
The main change / challenge in this PR is to properly differentiate PP microbatching vs. gradient accumulation microbatching, from UX / config perspective.
E.g. a simple way is to let user specify "local microbatch size"
- without PP it's the
local_batch_sizetoday, which is used together withglobal_batch_sizeto determine number of grad accum steps - with PP, it's the local microbatch size, whose product with num PP microbatches * num grad accum steps would have to equal
global_batch_size.
|
synced with @sanketpurandare, he will support both PP + grad accum in this PR first. After that I will remove batch dim, and @jinsooihm can also work on refactoring |
[ghstack-poisoned]
Summary: - Have PP training and validation dataloaders emit pipeline microbatches directly. - Keep PP microbatching distinct from gradient accumulation and pass pre-split args, kwargs, and targets through the upstream schedule API. - Remove the PP+Varlen guard while retaining the newer Flex+CP coverage. - Keep GraphTrainer, TorchFT, and Forge aligned with the core training path. Motivation: TorchTitan previously built a full local batch and relied on torch.distributed.pipelining to split it. That does not work for batch-dependent non-tensor metadata such as varlen attention metadata. Owning the split at the dataloader/trainer boundary lets TorchTitan generate masks and metadata per pipeline microbatch while preserving independent gradient accumulation. Test Plan: - pre-commit run on all changed review files, including pyrefly - pytest -q torchtitan/experiments/graph_trainer/tests/test_graph_pp_runner.py -x - 2-GPU GPT-OSS Varlen PP with 8 PP microbatches, 2 gradient accumulation steps, and validation - 2-GPU GraphPP Interleaved1F1B with 8 PP microbatches and 2 gradient accumulation steps - 10-step deterministic before/after comparison: bitwise-identical loss and grad_norm ghstack-source-id: 693422b Pull Request resolved: #3856
| tokenizer=self.tokenizer, | ||
| seq_len=config.training.seq_len, | ||
| local_batch_size=config.training.local_batch_size, | ||
| local_batch_size=( |
There was a problem hiding this comment.
seems confusing, maybe should rename dataloader.local_batch_size to microbatch_size? although we'd kill this arg soon anyway
There was a problem hiding this comment.
Pulled the conditional into a dataloader_batch_size local before the build
call. I kept the shared local_batch_size constructor keyword unchanged because
all dataloader implementations use it and, as noted, it is going away; renaming
that contract here would create unrelated churn.
| def pp_forward_backward_step( | ||
| self, | ||
| *, | ||
| input_dict_mbs: list[dict[str, torch.Tensor]], | ||
| label_mbs: list[torch.Tensor], | ||
| global_valid_tokens: float, | ||
| ) -> torch.Tensor: |
There was a problem hiding this comment.
I feel it's fine to not have this function, to avoid
- asymmetric code structure between PP and non-PP
- giving new names like
input_dict_mbs
There was a problem hiding this comment.
Kept the extracted method because it directly addressed @fegin 's earlier
request in
#3856 (comment). The PP
branch owns list-typed preprocessing and schedule construction, while the non-PP
path remains linear. I did not inline it because that would reverse the earlier
requested structure.
| # Collect all microbatches on CPU and count total valid tokens | ||
| # Here we assume the inputs/labels are on GPU | ||
| microbatches = [] | ||
| batch_groups: list[list[tuple[dict[str, torch.Tensor], torch.Tensor]]] = [] |
There was a problem hiding this comment.
name too general, can we achieve clear semantics that
- batch_groups is containing the list of microbatches for each optimizer step
- each batch_group contains the microbatches for each fwd-bwd step
There was a problem hiding this comment.
Renamed batch_groups to microbatch_groups and each batch_group to
microbatches across core, TorchFT, and Forge. The comment now states that all
groups form one optimizer step and each group feeds one forward-backward call.
| input_dict=step_input_dict, | ||
| labels=step_labels, |
There was a problem hiding this comment.
above you called it batch_group, here it's step_X, need to be consistent
There was a problem hiding this comment.
Renamed step_input_dict and step_labels to fwd_bwd_input_dict and
fwd_bwd_labels across all three paths, matching the unit represented by each
microbatches group.
[ghstack-poisoned]
| This value is used to compute the total number of microbatches by dividing local_batch_size with | ||
| pipeline_parallel_microbatch_size. | ||
| The global training batch size must be evenly divisible by pipeline_parallel_microbatch_size. | ||
| `training.local_batch_size` must be evenly divisible by this value. |
There was a problem hiding this comment.
shall we assert this in post init?
There was a problem hiding this comment.
Added the cross-field check to Trainer.Config.__post_init__, where both config values are available after CLI overrides. It now raises ValueError for a non-positive pipeline microbatch size and for PP configurations where the local batch size is not evenly divisible. Added an end-to-end config parsing test for the divisibility check.
| if parallel_dims.pp_enabled: | ||
| fwd_bwd_input_dict = input_dict_mbs | ||
| fwd_bwd_labels = label_mbs | ||
| else: | ||
| assert len(input_dict_mbs) == len(label_mbs) == 1 | ||
| fwd_bwd_input_dict = input_dict_mbs[0] | ||
| fwd_bwd_labels = label_mbs[0] |
There was a problem hiding this comment.
can we just pass in input_dict_mbs and label_mbs into forward_backward_step? and assert length == 1 inside forward_backward_step when PP off?
There was a problem hiding this comment.
Kept the one-element unwrap at the train_step boundary. Moving it into forward_backward_step would change the existing non-PP contract from a dict/tensor pair to lists; direct callers such as GraphTrainer use the current contract, and the adjacent thread established this method as an integration API. A list-only contract should be an intentional API migration rather than a callsite cleanup in this PR.
Summary: - Have PP training and validation dataloaders emit pipeline microbatches directly. - Keep PP microbatching distinct from gradient accumulation and pass pre-split args, kwargs, and targets through the upstream schedule API. - Make optimizer-step and forward-backward microbatch grouping explicit across core, TorchFT, and Forge. - Validate pipeline microbatch sizing before trainer initialization. - Remove the PP+Varlen guard while retaining the newer Flex+CP coverage. Motivation: TorchTitan previously built a full local batch and relied on torch.distributed.pipelining to split it. That does not work for batch-dependent non-tensor metadata such as varlen attention metadata. Owning the split at the dataloader/trainer boundary lets TorchTitan generate masks and metadata per pipeline microbatch while preserving independent gradient accumulation. Checking the size relationship after CLI overrides makes invalid PP configurations fail before runtime schedule construction. Test Plan: - pre-commit run on all changed review files, including pyrefly - pytest -q tests/unit_tests/test_config_manager.py::TestConfigManager::test_pipeline_microbatch_size_must_divide_local_batch_size - pytest -q tests/unit_tests/test_invalid_loss.py -x - pytest -q torchtitan/experiments/graph_trainer/tests/test_graph_pp_runner.py -x - 2-GPU GPT-OSS Varlen PP with 8 PP microbatches, 2 gradient accumulation steps, and validation - 2-GPU GraphPP Interleaved1F1B with 8 PP microbatches and 2 gradient accumulation steps - 10-step deterministic before/after comparison: bitwise-identical loss and grad_norm ghstack-source-id: 0e13f48 Pull Request resolved: #3856
[ghstack-poisoned]
Summary: - Have PP training and validation dataloaders emit pipeline microbatches directly. - Keep PP microbatching distinct from gradient accumulation and pass pre-split args, kwargs, and targets through the upstream schedule API. - Make optimizer-step and forward-backward microbatch grouping explicit across core, TorchFT, and Forge. - Validate pipeline microbatch sizing before trainer initialization. - Remove the PP+Varlen guard while retaining the newer Flex+CP coverage. Motivation: TorchTitan previously built a full local batch and relied on torch.distributed.pipelining to split it. That does not work for batch-dependent non-tensor metadata such as varlen attention metadata. Owning the split at the dataloader/trainer boundary lets TorchTitan generate masks and metadata per pipeline microbatch while preserving independent gradient accumulation. Checking the size relationship after CLI overrides makes invalid PP configurations fail before runtime schedule construction. Test Plan: - pre-commit run on all changed review files, including pyrefly - pytest -q tests/unit_tests/test_config_manager.py::TestConfigManager::test_pipeline_microbatch_size_must_divide_local_batch_size - pytest -q tests/unit_tests/test_invalid_loss.py -x - pytest -q torchtitan/experiments/graph_trainer/tests/test_graph_pp_runner.py -x - 2-GPU GPT-OSS Varlen PP with 8 PP microbatches, 2 gradient accumulation steps, and validation - 2-GPU GraphPP Interleaved1F1B with 8 PP microbatches and 2 gradient accumulation steps - 10-step deterministic before/after comparison: bitwise-identical loss and grad_norm ghstack-source-id: 6cc1f52 Pull Request resolved: #3856
[ghstack-poisoned]
Summary: - Have PP training and validation dataloaders emit pipeline microbatches directly. - Keep PP microbatching distinct from gradient accumulation and pass pre-split args, kwargs, and targets through the upstream schedule API. - Make optimizer-step and forward-backward microbatch grouping explicit across core, TorchFT, and Forge. - Validate pipeline microbatch sizing before trainer initialization. - Remove the PP+Varlen guard while retaining the newer Flex+CP coverage. Motivation: TorchTitan previously built a full local batch and relied on torch.distributed.pipelining to split it. That does not work for batch-dependent non-tensor metadata such as varlen attention metadata. Owning the split at the dataloader/trainer boundary lets TorchTitan generate masks and metadata per pipeline microbatch while preserving independent gradient accumulation. Checking the size relationship after CLI overrides makes invalid PP configurations fail before runtime schedule construction. Test Plan: - pre-commit run on all changed review files, including pyrefly - pytest -q tests/unit_tests/test_config_manager.py::TestConfigManager::test_pipeline_microbatch_size_must_divide_local_batch_size - pytest -q tests/unit_tests/test_invalid_loss.py -x - pytest -q torchtitan/experiments/graph_trainer/tests/test_graph_pp_runner.py -x - 2-GPU GPT-OSS Varlen PP with 8 PP microbatches, 2 gradient accumulation steps, and validation - 2-GPU GraphPP Interleaved1F1B with 8 PP microbatches and 2 gradient accumulation steps - 10-step deterministic before/after comparison: bitwise-identical loss and grad_norm ghstack-source-id: a4b3770 Pull Request resolved: #3856
Per review: drop Qwen35AttentionMaskInputs and the in-forward conversion. Qwen35Model.get_attention_masks now returns the flex BlockMask paired directly with the VarlenMetadata, built in place, and the composite field is renamed full_attention -> quadratic_attention. This relies on pytorch#3856 (the trainer pre-splits pipeline microbatches and builds masks per microbatch): before it lands, a prebuilt VarlenMetadata does not survive the schedule-side kwarg split, so this must land after pytorch#3856. The cu_seq_q clone in GatedDeltaNet.forward stays load-bearing either way: microbatches still interleave under 1F1B, so FLA's single-entry identity cache is still evicted between a microbatch's forward and its selective-AC recompute.
One conflict + one required replay (this sync was not inert): - CONFLICT experiments/torchft/trainer.py: complementary dataloader kwargs (ours: training_steps/global_batch_size/parallel_dims; upstream pytorch#3856: local_batch_size -> dataloader_batch_size). Resolved keeping both. - REPLAY pytorch#3856 'Always Pre-Split Microbatches for PP' onto ezpz/trainer.py: it builds its own dataloader, so it needed the same PP microbatch-size logic or PP would feed full-size batches. Training dataloader only; the validator path keeps local_batch_size (matches upstream). - No replay for pytorch#3558 mxfp8 (SM100+CUDA+compile only -> inapplicable on XPU; adds an opt-in config fn only), kimi_k2_7, other models, or the 8 CI-only commits.
First-ever ezpz PP test (job 12472451, agpt-2b 2N PP=2) fails at step 0 with 'assert isinstance(input_dict, list)' (torchtitan/trainer.py:742). Upstream's PP contract passes the whole microbatch LIST to forward_backward_step so the pipeline schedule drives the stages; ezpz/trainer.py.train_step has no pp_enabled branch and loops microbatches one dict at a time (correct for gradient accumulation, wrong for PP). NOT a regression from the pytorch#3856 replay -- that fixed the dataloader batch SIZE only; the trainer's iteration contract was never PP-aware. Confirmed pre-existing: no pipeline_parallel_degree>1 anywhere in experiments/ezpz. Documented the shape of the fix (a pp_enabled branch passing the list through) rather than implementing it -- no current workload uses PP.
…nc, 50/50 saga Audited the 2026-08-03 entry against the jobs actually run this session; three workstreams were missing entirely. - lm-eval downstream sweep (12472403/07): added the full 9-task x 3-arm table. This is a real finding, not a footnote -- the three arms are downstream-INDISTINGUISHABLE at 2B/10B tokens and the faint trend runs against the val-loss ordering (edu-100 edges arc_easy/openbookqa/mmlu_stem/hellaswag). Qualifies the data-mix verdict: 75/25 is a val-loss win, downstream-neutral. Also notes the enabling work (no lm_eval existed on Sunspot; built venvs/sunspot-lm-eval on the frameworks module without clobbering XPU torch). - Pipeline parallelism: ezpz/trainer.py had NO pp_enabled branch (pre-existing gap, never exercised). Fixed by mirroring the base Trainer; non-PP regression arm passes 20/20 steps so it is a no-op for production. PP=2 now reaches torch's own schedule and fails one layer deeper on a microbatch-count mismatch, still being localized. - 73rd upstream sync (11 commits): had a real conflict + the pytorch#3856 PP replay; the entry previously mentioned only the 72nd. - 50/50 arm: recorded that it took 4 attempts, all infrastructure (transient ezpz_setup failure masquerading as a data-source error; two dcp_save crashes on the tegu project-quota hard cap that df could not show), and the mix_ab.sh hardening that came out of it.
Per review: drop Qwen35AttentionMaskInputs and the in-forward conversion. Qwen35Model.get_attention_masks now returns the flex BlockMask paired directly with the VarlenMetadata, built in place, and the composite field is renamed full_attention -> quadratic_attention. This relies on pytorch#3856 (the trainer pre-splits pipeline microbatches and builds masks per microbatch): before it lands, a prebuilt VarlenMetadata does not survive the schedule-side kwarg split, so this must land after pytorch#3856. The cu_seq_q clone in GatedDeltaNet.forward stays load-bearing either way: microbatches still interleave under 1F1B, so FLA's single-entry identity cache is still evicted between a microbatch's forward and its selective-AC recompute.
… attention (#3984) Follow-up to #3801 (merged), split out per @tianyu-l's review there. ## Summary Under the flex attention backend, the `BlockMask` document-isolates only the quadratic full-attention layers (1 in 4). `GatedDeltaNet` is a recurrence, so it needs document *offsets* rather than a mask. It previously received no document info at all, meaning its conv and recurrent state ran across packed-document boundaries as one continuous stream. This was pre-existing behavior on main (surfaced by @shuhuayu's review on #3801). Per review, `Qwen35Model.get_attention_masks` returns a flat mask dict (the gpt_oss pattern): `{"quadratic_attention": BlockMask (flex) or VarlenMetadata (varlen), "deltanet": VarlenMetadata}`; each transformer block picks its entry by `attn_mask_key` set at init, so `GatedDeltaNet` and `Qwen35Attention` keep their natural signatures with no per-module mask dispatch. `AttentionMasksType`'s mapping arm widens to `Mapping[str, BlockMask | VarlenMetadata | None]` (`Mapping` keeps value types covariant so gpt_oss's `dict[str, BlockMask]` still typechecks, and a `None` value marks an unused mask), which removes the `bad-override` suppression. For configs with no full-attention layer the dict fills `quadratic_attention: None`; a maskless (`None`) GatedDeltaNet forward stays legal: the TitanRL inference wrapper's forward calls every layer with `attention_masks=None` (`experiments/rl/models/vllm_wrapper.py`), and #3957's Qwen3.5 unified RL path builds hybrid Qwen3.5 on it -- request boundaries there are tracked by its vLLM paged-state GDN adapter, not by varlen offsets. Context-parallel mask sharding raises a clear error on non-BlockMask values (CP+varlen was already unsupported, now loud). Pipeline safety comes from #3856: the trainer pre-splits microbatches and builds the mask dict per microbatch. `GatedDeltaNet.forward` also clones `cu_seq_q` once per invocation. FLA's `tensor_cache` is keyed by tensor identity and holds only a few entries (one in fla 0.5.0, a 4-entry deque in 0.5.1+); under pipeline parallelism another microbatch's forward evicts the entry between a microbatch's forward and its selective-AC recompute, so the recompute runs the varlen index helpers that the original forward skipped as cache hits. Selective AC pairs saved-op invocations by index, and the shifted ledger fails hard: ``` RuntimeError: aten.slice.Tensor invocation index 4 encountered during backward but not found in storage. ``` A fresh tensor per forward keeps forward and recompute on the same cache-miss path. Without PP the divergence is benign (a recompute can only hit where its forward missed), which is why the non-PP varlen SAC CI entry never tripped this. Note for reviewers: this intentionally changes flex-path numerics for packed data. DeltaNet state now resets at document boundaries where it previously bled across them. Known limitation (pre-existing, documented TODO): a model config with no full-attention layers gets no masks, so no DeltaNet resets (the trainer only builds masks when `model_config.first_attention` is Flex/Varlen). ## Testing - CPU unit tests: the flex composite carries the BlockMask plus the packed document offsets (plain `VarlenMetadata` under varlen); GatedDeltaNet under the composite matches stitched per-document forwards; and a cache-key invariant test (fresh `cu_seqlens` per DeltaNet forward) that is red without the clone. Deltanet suite: 6 passed on one H100. - 8x H100 red/green for the clone on the `qwen3_5_moe_fsdp+tp+ep+pp` CI entry shape (pp2 / dp_shard2 / tp2 / ep4, selective AC), on the post-#3856 pre-split flow with `torch==2.14.0.dev20260731+cu130`: without the clone, step-1 backward fails with the ledger error above; with it, 10/10 steps complete. - 4x H100, flex backend, dp_shard=2 / tp=2, selective AC, 10 steps: green. - 4x H100 regression: the `qwen3_5_fsdp+tp+varlen_attn+per_op_sac` CI entry still passes 10 steps. - New with #3856: varlen + PP + SAC (pp2 / dp_shard2 / tp2) completes 10/10 steps on 8x H100 -- the first pipelined run of the GatedDeltaNet varlen path (previously hard-blocked by the PP+Varlen guard). - Note on torch versions: the pre-split `step(arg_mbs=...)` API that #3856 relies on landed in `torch==2.14.0.dev20260731+cu130`, but plain `pip install --pre torch torchvision` currently resolves torch back to `dev20260729` (torchvision `dev20260731` pins it), which fails all PP entries with `Expecting N arg_mbs but got 1` -- the current main 8-GPU CI failure. The PP runs above force the July 31 torch wheel.
torchtitan's Trainer is the black box. Trainer.__init__ owns the whole build (parallel dims, model, optimizer, PP schedule, checkpointer) and forward_backward_step hides the PP/non-PP split (pytorch/torchtitan#3856), so TitanTrainer adds nothing to construction: it translates the shared loop's StepRunner protocol onto that machinery. miles builds the config tree from its args (config.py), supplies the RL loss as torchtitan's loss_fn (loss.py), stands in for the dataloader and checkpointer (components.py), and installs three feature-detected torch backports (compat.py) that each become a no-op once the pinned torch carries the upstream form. Everything torchtitan re-exports is imported through torchtitan, never torch. Weights reach the engines through weight_bridge.hf_weights: the trainer's shards become HF-named full tensors through the model's own state_dict_adapter, reassembled across dp/tp/ep and, when the protocol's placement asks for it, completed across pipeline stages one tensor at a time. Multimodal towers the trainer never holds are streamed from the checkpoint files (checkpoint_towers.py). Tensors go out in the dtype the engine holds, not the fp32 masters. A pipeline schedule runs a real forward and backward over microbatch 0 to infer its stage shapes, on every eval-to-train switch. Anything consumed per call (routing replay queues) is shifted by one microbatch; routing_replay.py bypasses that initialization window and reshards the replay like the sequence it describes. A tied-embedding checkpoint is refused under PP: torchtitan would train a separate lm_head the HF export has no tensor to ship into. Supported: tp, pp, cp (headtail balancer), ep, dp-replicate, activation checkpointing, MoE with R3, colocated and disaggregated rollout, fully-async, every transport, a reference model. Not yet: LoRA, optimizers other than adam. The FSDP argument parser is generalized over its dataclass so the torchtitan arguments extend it instead of restating the common options; the e2e harness resolves --train-backend by name so a third backend is not treated as Megatron; the Dockerfile pins the torchtitan checkout.
torchtitan's Trainer is the black box. Trainer.__init__ owns the whole build (parallel dims, model, optimizer, PP schedule, checkpointer) and forward_backward_step hides the PP/non-PP split (pytorch/torchtitan#3856), so TitanTrainer adds nothing to construction: it translates the shared loop's StepRunner protocol onto that machinery. miles builds the config tree from its args (config.py), supplies the RL loss as torchtitan's loss_fn (loss.py), stands in for the dataloader and checkpointer (components.py), and installs three feature-detected torch backports (compat.py) that each become a no-op once the pinned torch carries the upstream form. Everything torchtitan re-exports is imported through torchtitan, never torch. Weights reach the engines through weight_bridge.hf_weights: the trainer's shards become HF-named full tensors through the model's own state_dict_adapter, reassembled across dp/tp/ep and, when the protocol's placement asks for it, completed across pipeline stages one tensor at a time. Multimodal towers the trainer never holds are streamed from the checkpoint files (checkpoint_towers.py). Tensors go out in the dtype the engine holds, not the fp32 masters. A pipeline schedule runs a real forward and backward over microbatch 0 to infer its stage shapes, on every eval-to-train switch. Anything consumed per call (routing replay queues) is shifted by one microbatch; routing_replay.py bypasses that initialization window and reshards the replay like the sequence it describes. A tied-embedding checkpoint is refused under PP: torchtitan would train a separate lm_head the HF export has no tensor to ship into. Supported: tp, pp, cp (headtail balancer), ep, dp-replicate, activation checkpointing, MoE with R3, colocated and disaggregated rollout, fully-async, every transport, a reference model. Not yet: LoRA, optimizers other than adam. The FSDP argument parser is generalized over its dataclass so the torchtitan arguments extend it instead of restating the common options; the e2e harness resolves --train-backend by name so a third backend is not treated as Megatron; the Dockerfile pins the torchtitan checkout. Importing the package costs nothing: its __init__ is empty, so the arguments and the parallel-state mapping are readable on a machine without torchtitan (the CPU CI stage is one), and config.py -- the first module that does import torchtitan -- installs compat itself. The config test skips when torchtitan is absent.
torchtitan's Trainer is the black box. Trainer.__init__ owns the whole build (parallel dims, model, optimizer, PP schedule, checkpointer) and forward_backward_step hides the PP/non-PP split (pytorch/torchtitan#3856), so TitanTrainer adds nothing to construction: it translates the shared loop's StepRunner protocol onto that machinery. miles builds the config tree from its args (config.py), supplies the RL loss as torchtitan's loss_fn (loss.py), stands in for the dataloader and checkpointer (components.py), and installs three feature-detected torch backports (compat.py) that each become a no-op once the pinned torch carries the upstream form. Everything torchtitan re-exports is imported through torchtitan, never torch. Weights reach the engines through weight_bridge.hf_weights: the trainer's shards become HF-named full tensors through the model's own state_dict_adapter, reassembled across dp/tp/ep and, when the protocol's placement asks for it, completed across pipeline stages one tensor at a time. Multimodal towers the trainer never holds are streamed from the checkpoint files (checkpoint_towers.py). Tensors go out in the dtype the engine holds, not the fp32 masters. A pipeline schedule runs a real forward and backward over microbatch 0 to infer its stage shapes, on every eval-to-train switch. Anything consumed per call (routing replay queues) is shifted by one microbatch; routing_replay.py bypasses that initialization window and reshards the replay like the sequence it describes. A tied-embedding checkpoint is refused under PP: torchtitan would train a separate lm_head the HF export has no tensor to ship into. Supported: tp, pp, cp (headtail balancer), ep, dp-replicate, activation checkpointing, MoE with R3, colocated and disaggregated rollout, fully-async, every transport, a reference model. Not yet: LoRA, optimizers other than adam. The FSDP argument parser is generalized over its dataclass so the torchtitan arguments extend it instead of restating the common options; the e2e harness resolves --train-backend by name so a third backend is not treated as Megatron; the Dockerfile pins the torchtitan checkout. Importing the package costs nothing: its __init__ is empty, so the arguments and the parallel-state mapping are readable on a machine without torchtitan (the CPU CI stage is one), and config.py -- the first module that does import torchtitan -- installs compat itself. The config test skips when torchtitan is absent.
torchtitan's Trainer is the black box. Trainer.__init__ owns the whole build (parallel dims, model, optimizer, PP schedule, checkpointer) and forward_backward_step hides the PP/non-PP split (pytorch/torchtitan#3856), so TitanTrainer adds nothing to construction: it translates the shared loop's StepRunner protocol onto that machinery. miles builds the config tree from its args (config.py), supplies the RL loss as torchtitan's loss_fn (loss.py), stands in for the dataloader and checkpointer (components.py), and installs three feature-detected torch backports (compat.py) that each become a no-op once the pinned torch carries the upstream form. Everything torchtitan re-exports is imported through torchtitan, never torch. Weights reach the engines through weight_bridge.hf_weights: the trainer's shards become HF-named full tensors through the model's own state_dict_adapter, reassembled across dp/tp/ep and, when the protocol's placement asks for it, completed across pipeline stages one tensor at a time. Multimodal towers the trainer never holds are streamed from the checkpoint files (checkpoint_towers.py). Tensors go out in the dtype the engine holds, not the fp32 masters. A pipeline schedule runs a real forward and backward over microbatch 0 to infer its stage shapes, on every eval-to-train switch. Anything consumed per call (routing replay queues) is shifted by one microbatch; routing_replay.py bypasses that initialization window and reshards the replay like the sequence it describes. A tied-embedding checkpoint is refused under PP: torchtitan would train a separate lm_head the HF export has no tensor to ship into. Supported: tp, pp, cp (headtail balancer), ep, dp-replicate, activation checkpointing, MoE with R3, colocated and disaggregated rollout, fully-async, every transport, a reference model. Not yet: LoRA, optimizers other than adam. The FSDP argument parser is generalized over its dataclass so the torchtitan arguments extend it instead of restating the common options; the e2e harness resolves --train-backend by name so a third backend is not treated as Megatron; the Dockerfile pins the torchtitan checkout. Importing the package costs nothing: its __init__ is empty, so the arguments and the parallel-state mapping are readable on a machine without torchtitan (the CPU CI stage is one), and config.py -- the first module that does import torchtitan -- installs compat itself. The config test skips when torchtitan is absent.
Stack from ghstack (oldest at bottom):
Summary:
Motivation:
TorchTitan previously built a full local batch and relied on torch.distributed.pipelining to split it. That does not work for batch-dependent non-tensor metadata such as varlen attention metadata. Owning the split at the dataloader/trainer boundary lets TorchTitan generate block masks and varlen metadata per pipeline microbatch before calling the PP schedule.
Test Plan: