Repository navigation
Refactor post dataloading process - #4116
Conversation
| def preprocess_inputs( | ||
| self, | ||
| input_dict: dict[str, torch.Tensor], | ||
| labels: torch.Tensor, |
There was a problem hiding this comment.
why don't we put labels into input_dict?
(Yes we can change dataloader behavior)
There was a problem hiding this comment.
Maybe this can be done in a separate PR?
| input_dict: "dict[str, torch.Tensor]", | ||
| labels: "torch.Tensor", |
There was a problem hiding this comment.
why putting types as str?
| """ | ||
|
|
||
| # Per-input SPMD layouts; single source of truth for input parallelization. | ||
| input_sharding: "dict[str, SpmdLayout] | None" = None |
There was a problem hiding this comment.
why do we need this? A Module already have input sharding https://github.com/pytorch/torchtitan/blob/main/torchtitan/protocols/module.py#L59
There was a problem hiding this comment.
Yes, then should we just use one of in_src_sharding or in_dst_sharding? It feels a little hacky since ShardingConfig is defining redistribution contract.
There was a problem hiding this comment.
Actually, we'll remove src / dst so it becomes a static contract. Even if we don't, it's clear that we should use src?
There was a problem hiding this comment.
My concern is that if we use ShardingConfig, then it would be used to set up redistribution by Module.parallelize() and this could behave weirdly when PP is applied? Wouldn't this make the second PP stage to impose ShardingConfig on the activation passed from the previous stage?
There was a problem hiding this comment.
I didn't complete get it.
- we will REMOVE one of src / dst, so that module boundary does NOT have redistribute
- since you are still doing CP sharding from outside, different PP stages should have the SAME input sharding?
There was a problem hiding this comment.
Suppose model.forward(x, ...) and we set ShardingConfig on the model on x to be R on TP. If we do sequence parallel, then it would become sharded on TP after token embedding and fed to layers.
If we apply PP, then wouldn't PP stage 2 expect the first positional argument to be R on TP from the above ShardingConfig, but the layer that gets called right away, without token embedding, inside forward expect shard on TP?
| ).preprocess_inputs(input_dict, labels) | ||
|
|
||
| if self.parallel_dims.cp_enabled: | ||
| dims = cp_shard_dims(input_sharding) if input_sharding else None |
There was a problem hiding this comment.
is this used anywhere else? If not let's not create another API; instead you could pass input_sharding into the prepare_context_parallel_input (which eventually should be put into dataloder?)
There was a problem hiding this comment.
I don't think we should create this file / function. We will deprecate all backends other than spmd_types.
| @@ -646,59 +648,32 @@ def batch_generator( | |||
| def post_dataloading_process( | |||
There was a problem hiding this comment.
What's the plan with this function? My original thought is that we should kill it entirely. Is this your goal?
This would allow multimodal models to annotate spmd_types for additional inputs such as pixel_values with a simple configuration.
Right now you are still annotating spmd_types outside preprocess_inputs, so I don't see how it makes things different for multimodal models.
There was a problem hiding this comment.
Main difference would be not having to annotate explicitly inside model forward like how it is done in
https://github.com/pytorch/torchtitan/pull/4079/changes#diff-de024fcd87b762920e1b5c44bdd9759cfe65bcd766dc0b1d40205e235fb9c538R182-R190
For removing post_dataloading_process entirely, I think we need to discuss more, as in your comment in
https://github.com/pytorch/torchtitan/pull/3559/changes#r3763932589
There was a problem hiding this comment.
I'm not sure I'm convinced, would love to see an integration for multimodal (maybe after that Kimi PR is landed)
There was a problem hiding this comment.
Hmm, yes. I do not see a nice way to take out annotation out of forward for multimodal. The reason is the below inside Kimi forward:
torchtitan/torchtitan/models/kimi_k2_7/model.py
Lines 182 to 189 in 9a71152
I think we can still call annotate_multimodal_input_spmd_types outside forward and the context, but it seems like a semantically wrong thing to do.
One way for now would be to just let those special case annotations to be handled in the model forward, while move the post_dataloading_process logic to be owned by model's preprocess_inputs.
Perhaps it can be cleaned up a little more if we write a multimodal trainer that calls vision encoder part separately from decoder.
There was a problem hiding this comment.
Thanks. For now it feels to me that
- model should own
preprocess_inputsbecause each model can do different things - so we should refactor
post_dataloading_processtomodel.preprocess_inputs
WDYT?
There was a problem hiding this comment.
Yes, I agree. I am making the changes and will let you know when I think it is ready to review.
I also think that it is fine to call the annotate_multimodal_input_spmd_types outside of multimodal_context, since spmd.set_current_mesh(local_axes=("dp",)) is used to just not enforce the global spmd typechecking on DP. So it is fine to annotate DP to be V outside as long as we do not operate on those inputs.
This would be more of an aesthetics choice on whether annotating all the inputs should be done in preprocess_inputs or some there and some in forward.
I personally think it would be better to collect them at one place before forward, although it functionally would not really matter if type checking is off when PP is on.
6b9b4c3 to
08a86f2
Compare
| @@ -119,56 +134,86 @@ def prepare_context_parallel_input( | |||
| device: torch.device, | |||
| load_balancer_type: str | None = "headtail", | |||
| ptrr_mask_key: str | None = None, | |||
| input_sharding: dict[str, SpmdLayout] | None = None, | |||
There was a problem hiding this comment.
Should we change the arguments to:
inputs: dict[str, Any], input_shardings: dict[str, SpmdLayout | None], cp_mesh: DeviceMesh, device: ...
There was a problem hiding this comment.
inputs.keys() == input_shardings.keys()
There was a problem hiding this comment.
I made it so that preprocess_inputs take in a single input_dict with labels and extra_kwargs folded in so internally, everything information is passed around as a single dict. We can change the dataloader behavior later.
| once per microbatch on the PP path, so token accounting matches the | ||
| batch stream. | ||
|
|
||
| The 4th element (``local_ntokens``) is a transitional workaround; see |
There was a problem hiding this comment.
This statement is confusing. Can we say The 4th returned value of model.preprocess_inputs ...
| CP-shard, then SPMD-wrap. Returns ``(inputs, labels, extra_kwargs, | ||
| local_ntokens)``. | ||
|
|
||
| TODO(return-type): the 4th element (local token count) is a transitional |
There was a problem hiding this comment.
Same here, 4th element is confusing. 4th return value is more clear.
tianyu-l
left a comment
There was a problem hiding this comment.
make sure https://github.com/pytorch/torchtitan/blob/main/torchtitan/experiments/rl/actors/trainer.py works with new design as well
take a look at https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/flux/trainer.py as well to see if we can unify some code with core Trainer by moving some preprocessing to FLUX model
| Analogous to ``full_dtensor.parallelize_inputs()`` but for the | ||
| ``spmd_types`` path. | ||
| """ | ||
| def spmd_layout_to_dtensor_placements( |
There was a problem hiding this comment.
I'm not sure you need this. Does spmd_types not having any util for it? @pianpwk
There was a problem hiding this comment.
could you take a look at
torchtitan/torchtitan/protocols/sharding.py
Line 129 in b64d3f6
unfold_dp_axis + spmd.spmd_type_to_dtensor_placement should work
| """ | ||
| dims: dict[str, int] = {} | ||
| for name, layout in input_sharding.items(): | ||
| cp_dim = layout.shard_dim(MeshAxisName.CP) |
There was a problem hiding this comment.
Is the .shard_dim API only used here? If so, maybe not worth introducing.
| logger.info("Applied Context Parallel (forward wrapping) to the model") | ||
|
|
||
|
|
||
| def cp_shard_dims(input_sharding: dict[str, SpmdLayout]) -> dict[str, int]: |
There was a problem hiding this comment.
| def cp_shard_dims(input_sharding: dict[str, SpmdLayout]) -> dict[str, int]: | |
| def _cp_shard_dims(input_sharding: dict[str, SpmdLayout]) -> dict[str, int]: |
if only used in this file
| labels = input_dict.pop("labels") | ||
| return inputs, labels, input_dict, local_ntokens | ||
|
|
||
| def _build_forward_inputs( |
| buffer_device = kwargs.get("buffer_device") | ||
| self.init_states(buffer_device=buffer_device) | ||
|
|
||
| def preprocess_inputs( |
There was a problem hiding this comment.
move this to decoder; we may still define the interface here -- but need justification
There was a problem hiding this comment.
I only left the interface and moved the logic to decoder.
| "Could not find rotary_emb in the model. Please check the model structure." | ||
| ) | ||
|
|
||
| def _build_forward_inputs( |
There was a problem hiding this comment.
try inherit decoder -- if not possible, just duplicate code
| if layout is None: | ||
| untyped.append(name) | ||
| continue | ||
| spmd.assert_type(value, layout.per_axis_spmd_types()) |
There was a problem hiding this comment.
nit: could also assert with per-axis-types + partition spec I think
8200edb to
00370da
Compare
| @sl.log_trace_span("post_dataloading_process") | ||
| def post_dataloading_process( | ||
| @sl.log_trace_span("preprocess_inputs") | ||
| def _prepare_batch( |
There was a problem hiding this comment.
can we not define this function?
There was a problem hiding this comment.
I think the code would look cleaner with this helper because the body is pretty long, and it is called at two places.
There was a problem hiding this comment.
I didn't get it. The function is extremely short, what is pretty long? Could you please show the change with this indirection removed?
There was a problem hiding this comment.
I removed it. I think it will become a lot cleaner after the TODO on typing model_parts to be BaseModel and making dataloader emits labels in the input dictionary.
| input_dict: dict[str, torch.Tensor], | ||
| *, | ||
| parallel_dims: ParallelDims, | ||
| device: torch.device, |
| untyped.append(name) | ||
| continue | ||
| spmd.assert_type(value, layout.per_axis_spmd_types()) | ||
| if untyped: |
There was a problem hiding this comment.
can you just raise in the for loop?
There was a problem hiding this comment.
Well, doing this would tell the user every missing annotation.
There was a problem hiding this comment.
don't put test under torchtitan/
| multimodal_type = { | ||
| MeshAxisName.DP: spmd.V, | ||
| MeshAxisName.TP: spmd.I, | ||
| def multimodal_input_sharding() -> dict[str, SpmdLayout]: |
There was a problem hiding this comment.
is this not shareable by all multimodal models?
There was a problem hiding this comment.
Almost. Qwen35 has mrope_positions. But in forward, positions and mrope_positions are never used together. I think we can
- remove the separate
mrope_positionsfrom theforwardinput signature preprocess_inputsbuild the mask usingpositionspreprocess_inputsputs the result ofrope_positions = mrope_positions if mrope_positions is not None else positionsintoinput_dictwhich goes intoforward?
Then, every multimodal models would have the same input signature.
There was a problem hiding this comment.
we can give it a try and let @shuhuayu and I take a look
There was a problem hiding this comment.
i am ok with unifying with other vlms in terms of forward apis. looks clean to me.
| config.vision_adapter.build() if config.vision_adapter is not None else None | ||
| ) | ||
|
|
||
| def preprocess_inputs( |
There was a problem hiding this comment.
can we define a multimodel base to share this function?
There was a problem hiding this comment.
Currently, Muse Glimmer and Kimi does the same thing but I am planning to enable CP by doing something different in preprocess_inputs for Muse Glimmer. Also Qwen does something different already.
58006e4 to
16fb1cc
Compare
fegin
left a comment
There was a problem hiding this comment.
Thanks for the nice refactor.
| # (context_parallel.api -> models.common -> decoder). | ||
| from torchtitan.distributed.context_parallel.api import ( | ||
| prepare_context_parallel_input, | ||
| ) |
| from torchtitan.distributed.spmd_types import annotate_input_spmd_types | ||
| from torchtitan.models.common.attention import FlexAttention, VarlenAttention | ||
| from torchtitan.models.common.decoder import Decoder | ||
| from torchtitan.models.common.attention import FlexAttention |
There was a problem hiding this comment.
Do we still use this in Trainer?
There was a problem hiding this comment.
It is used in __post_init__
| if parallel_dims.cp_enabled: | ||
| batch = prepare_context_parallel_input( | ||
| batch, | ||
| input_sharding, | ||
| parallel_dims.get_mesh("cp"), | ||
| parallelism.context_parallel_load_balancer, | ||
| parallelism.context_parallel_ptrr_mask_key, | ||
| ) |
There was a problem hiding this comment.
This is a good place to do prepare_context_parallel_input as how do we shard the mask is also affected by the CP kernel.
…inputs Rework how decoder models declare and apply the SPMD layout of their forward inputs, and collapse the input pipeline into a single overridable method. SpmdLayout / input sharding: - SpmdLayout carries per-axis SPMD types plus an optional PartitionSpec, so a tensor dim sharded by multiple mesh axes (e.g. DP+CP token sharding) has an explicit, ordered layout. per_axis_spmd_types() stays a helper for redistribute; annotate_input_spmd_types asserts with the raw (axis_types, partition_spec) so multi-axis and higher-rank inputs validate correctly. - Context-parallel shard dims are derived from the layout (_cp_shard_dims), removing per-model CP wiring. Drop the unused spmd_layout_to_dtensor_placements path. preprocess_inputs: - Remove the _build_forward_inputs and input_sharding() hooks. BaseModel.preprocess_inputs has no meaningful default (it raises NotImplementedError); models on the standard trainer/validator path -- Decoder, HFTransformerModel, Qwen35Model, KimiK25Model, MuseGlimmerModel -- each inline their own (mask building, CP-shard, SPMD-wrap, pop) with no super()-chaining, while bespoke-pipeline models (e.g. Flux) never call it. - Qwen3.5 folds mrope_positions into the single positions input and asserts RoPE positions at the boundary; its GatedDeltaNet cu_seqlens annotation stays inline under the spmd_types branch (skipped when the batch has no varlen deltanet metadata). MRoPE positions fold to (tokens, 3), so they are given a rank-matching layout that replicates the trailing component axis instead of the 1D token layout. - Consolidate identical multimodal input sharding into common/multimodal.py and vision_encoder_sharding.py. Tests drive the real preprocess_inputs via a single-rank ParallelDims, and the spmd_types error message no longer references the removed hooks.
16fb1cc to
0837eef
Compare
0837eef to
9648ccd
Compare
…helper 21 commits behind upstream/main. Merged into a scratch clone (../tt-sync82) rather than the production one, because three optcmp arms are mid-chain with 7 links queued on afterany: each released link re-reads the working tree at launch, so landing this now would have later links training on different code than earlier ones and silently break comparability of the +10B measurement in progress. The merge is clean -- zero conflicts across 127 files -- and agpt is fine: all three optcmp configs build, and SpmdLayout (removed by pytorch#4265) turns out to appear in ezpz only in comments and as a local variable name. ezpz/moe does not build. pytorch#4300 rewrote models/utils.py and removed get_moe_model_nparams_and_flops, which moe/model.py imports at :30 and calls at :344. It is a port rather than a rename: the replacement get_nparams_and_active_nparams takes (model, *, modules_excluded...) and returns (nparams, active_nparams), dropping flops, which are now composed separately via quadratic_attention_flops_per_token. deepseek_v3's get_deepseek_v3_nparams_and_flops is the reference pattern. Landing plan is unchanged: finish the +10B run, then merge, then 2N smoke, with pytorch#4116 (post-dataloading refactor) checked against BlendCorpus specifically since that is where the token-unit fold bugs have lived.
…oved the hook Upstream pytorch#4116 deleted Trainer.post_dataloading_process and moved the work onto the model as BaseModel.preprocess_inputs. EzpzValidator called the deleted method, so validation would have raised AttributeError on the first validation step -- after startup, mid-run. The new contract differs in shape, not just name: labels go INSIDE the input dict rather than as a positional arg, and parallel_dims/parallelism are passed explicitly. Both are already attributes of the base Validator, so no plumbing was needed. Mirrors the non-PP branch of torchtitan/components/validate.py. Worth noting how this was nearly missed: the sync-82 trial merge tested config imports and pronounced only ezpz/moe broken. Config imports never touch the validator. What found it was importing EVERY ezpz module -- 75 of 79 now import, and the 4 failures are pre-existing RL deps (monarch, renderers, the vLLM-only actors path), unrelated to this sync.
sync79_smoke.pbs is stale and would abort in flag parsing: it passes --training.seq-len and --training.local-batch-size, neither of which exists after pytorch#4121 renamed them to max-context-length and num-tokens-per-microbatch-per-dp-rank. Running it against a clean merge would have produced three VOID arms and read as a merge failure. Adds an explicit validator import gate alongside the two config gates. The config gates cannot catch pytorch#4116: EzpzValidator called the deleted Trainer.post_dataloading_process, and importing a config_registry never touches the validator, so the trial merge pronounced only moe broken. Result on the merged tree (job 12474288, 6m39s, Exit_status=0): all three import gates OK, and agpt2b / agpt2b-tp2 / moe_10b_2b_sdpa each rc=0 with 20 real steps, losses 12.88->7.18, 12.89->6.93, 12.92->7.04.
266 non-merge commits, 185 under experiments/ezpz/. Leads with the optimizer comparison finishing: Mano 2.43889 vs AdamW 2.51357 at 23.59B tokens, both arms to the training.steps=6000 ceiling with rc=0 and zero NaN/inf. Includes the full 250-step binned gap table and states plainly that the last two windows reverse because they straddle a transient in the Mano arm -- fitting a crossover through the tail fits a detour, so the monotone stretch is 2750-5500. The SophiaG section is the substantive change to what was believed. "3/3" was three forks of one checkpoint; a fourth arm from random init with the seed pinned diverged anyway, which also closes out data order since dataloader.seed was already 42 everywhere. The new result is that pre-onset noise is not a precursor: the original ran 17.9% above grad_norm 2.0 for 1,027 steps before blowing up, the fresh one ran 1,529 steps at 0.0% and blew up regardless. It then escaped completely and has held ~1,730 steps since. Sync 82 is written up with the detail that matters for next time: the trial merge in a scratch clone found the moe break and MISSED the validator break, because config-import gates never touch the validator and pytorch#4116's removal raises at validation time rather than at import. Importing all 79 ezpz modules is what found it. Closes with two method notes, both from errors made repeatedly this period: bin before characterizing (the fresh SophiaG arm got three different characterizations in three readings, every optimistic one wrong), and empty output from a still-running job is not a no-op.
Update Aug 18
BaseModeldefinespreprocess_inputsand_build_forward_inputs.preprocess_inputsdoes the following:_build_forward_inputswhich also returnsinput_sharding, an information on how to shard the tensor inputs.input_shardinginput_shardingon the tensorslocal_ntokenscounted after CP sharding and before dtensorizinglabels.Trainer's
post_dataloading_processis replaced with_prepare_batchfor now to countntokens_seen. This can be removed after dtensor support is removed, so thelocal_ntokenscan be counted outside ofpreprocess_inputs.When a model has additional inputs to CP shard/annotate, one can override
_build_forward_inputsas in Kimi.The above recipe can handle most of the type annotation except Qwen3.5, which annotates
cu_seq_qinsideVarlenMetadata. In such cases one can overridepreprocess_inputs.Remark
This could allow CP in multimodal models (assuming the decoder part allows CP like Muse Glimmer)
by building a index tensor in
_build_forward_inputsthat indicates for each token position, which vision encoder output it should get. Then we CP shard this tensor in the same way as tokens, and scatter it insideforward.Remove decoder specific logic in `Trainer.post_dataloading_process` to be configurable.- Each model defines
- Each model defines
preprocess_inputsas a function inBaseModel.preprocess_inputs. This reads the input batch given from the dataloader and produces additional input that the model needs, such as attention masks.input_sharding: dict[str, SpmdLayout]inBaseModel.Configthat is used to give correct DTensor or spmd_types for each argument in themodel.forward.prepare_context_parallel_inputis also generalized to infer frominput_shardingon which inputs and which dimension to CP shard.This would allow multimodal models to annotate spmd_types for additional inputs such as
pixel_valueswith a simple configuration.<\del>
Test Plan
python -m tests.integration_tests.run_tests <output_dir> --test_suit models --ngpu 8runs without error.