Repository navigation
[config] Read max_context_length from the model config - #5779
Conversation
|
@claude review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The context length now has a single owner, the model config. Every value the training path reads stays the same, and what's left are small local edits. This PR touches core (trainer.py, training_engine.py, BaseModel), so a maintainer still needs to review it.
What this PR does. It removes TrainingConfig.max_context_length and the check that it equals the model's length. max_context_length moves from Decoder.Config to BaseModel.Config. The trainer, engine, validator, RL controller, torchft and GraphTrainer now read model.max_context_length. The max_context_length argument of preprocess_inputs / _get_attention_metadata is gone: the decoder uses self.config.max_context_length instead. Flux flavors now take seq_len.
Example.
# before: the same number twice, kept equal by validate_model_training_config
model = build_model_config("debugmodel", seq_len=2048, parallelism=p)
TrainingConfig(max_context_length=model.max_context_length, ...)
# after
model = build_model_config("debugmodel", seq_len=2048, parallelism=p)
TrainingConfig(...) # data, attention metadata, flops and the RL batcher read model.max_context_lengthNumerics: create_varlen_metadata_for_document reads max_context_length only when max_num_documents is set. So the callers that used to pass nothing (_get_attention_metadata(positions) in tests, scripts and RL parity) get the same metadata as before. The engine path gets the same number it used to read from training.
Must fix
- PR description: the "Summary (human-written)" section is empty. The author needs to fill it in.
tests/unit_tests/cpu/recipes/test_debug_config_defaults.py:161andtests/unit_tests/cpu/test_integration_test_definitions.py:194-- after the rename, each of these asserts repeats the line next to it. Delete them.
Should consider
torchtitan/models/flux/flavors.py:582-- make Fluxseq_lenrequired and drop the per-flavor defaults. They have no in-repo code consumer, and they let a rebuild that omitsseq_len(as the README's MXFP8 example does) quietly get a length that doesn't match the dataset geometry.torchtitan/experiments/graph_trainer/tests/test_trace_module.py:2319-- rebuild the model config withseq_len=128instead of changingconfig.model.max_context_length, which leaves the RoPE length stale.torchtitan_recipes/rl/search_r1.py:419andalphabet_sort.rl_grpo_qwen3_6_27b_varlen_perf-- both are one-line fixes that can go in this PR. For search_r1, passseq_len=4096tobuild_rl_model_configs. For the 27B recipe, setnum_tokens_per_microbatch_per_dp_rank=seq_lenwhen it replacesconfig.trainer; its 2048 budget comes from the 9B base recipe while the model is 65536.
Details
- Callsite audit: there are no remaining
training.max_context_lengthreferences in.py,.md,.sh,.yaml,.tomlor.jsonfiles. EveryBaseModel.Configsubclass sets the field: the decoders through their flavors, Flux through the newseq_len, the HF backend inload_hf_config(its__init__override skips the generated required-field init), and the test fakes. - Callers left out of the description's 220-recipe check: the
configure_dist_moe_fsdp2_ep2users (intests/models/deepseek_v3.pyandtests/graph_trainer/b200.py) build the model withseq_len=128, so removingtraining.max_context_length = 128there is safe.test_bitwise_deterministicbuilds withseq_len=SEQ_LEN.muse_spark_debugmodel_ultradata_lora_sftbuilds withseq_len=32_768. - PP/CP/TP: every pipeline stage shares one model config, so
self.config.max_context_lengthis the same on all stages. The RL SP divisibility check now reads the model length, which is what the trainer actually uses. - The
TrainingConfig(max_context_length=0)validation is gone and nothing replaces it. A 0 still fails loudly (modulo / divmod by zero in the batcher, the Flux collator and positions), so I'm not asking to add a check back.
Not verified: GPU tests (GraphTrainer trace and bitwise tests, integration configs).
| ) -> None: | ||
| config = config_factory() | ||
| assert config.training.max_context_length == DEFAULT_DEBUG_MODEL_SEQ_LEN | ||
| assert config.model.max_context_length == DEFAULT_DEBUG_MODEL_SEQ_LEN |
There was a problem hiding this comment.
After the rename this line is the same as the assert on the next line, so it checks nothing new. Delete it.
| assert config.model.max_context_length == DEFAULT_DEBUG_MODEL_SEQ_LEN |
|
|
||
| assert config.model.max_context_length == 2048 | ||
| assert config.training.max_context_length == 2048 | ||
| assert config.model.max_context_length == 2048 |
There was a problem hiding this comment.
Same as the line above: once there is only one length, this assert repeats line 193. Delete it.
| assert config.model.max_context_length == 2048 |
| converters: list[ModelConfigConverter.Config] | None = None, | ||
| *, | ||
| parallelism: ParallelismConfig, | ||
| seq_len: int | None = None, |
There was a problem hiding this comment.
Consider making seq_len: int required and keeping MODEL_FLAVORS as plain factories. Every in-repo caller already passes seq_len (both recipes, _enable_mxfp8, and the state-dict-adapter test), so the defaults have no code consumer. The tuple also means something different from the decoders' tuple: there the second element is the flavor's upper bound, which build_model_config checks against. Here it is one recipe's dataset geometry.
The default is risky because Flux's length is derived from img_size and the T5 length. A caller that rebuilds the model without seq_len, as the README's custom-MXFP8 example does (torchtitan/models/flux/README.md:94), quietly gets 768/512. If the token budget still divides evenly by that length, FluxCollator builds a different number of rows per microbatch and nothing raises. With seq_len required, the README example passes seq_len=config.model.max_context_length like _enable_mxfp8, and the defaults and their comment go away.
| config = graph_trainer_llama3_debugmodel_varlen() | ||
| config.dump_folder = dump_folder | ||
| config.training.max_context_length = 128 | ||
| config.model.max_context_length = 128 |
There was a problem hiding this comment.
This changes a model config after it has been built. Only the top-level max_context_length becomes 128. The RoPE config (ComplexRoPE.Config(max_context_length=seq_len) in llama3/flavors.py) keeps the length the recipe was built with, so the test runs on a model whose fields disagree. It's harmless today because a larger RoPE cache is fine, but now that the model owns the length, rebuild it instead, e.g. config.model = build_graph_llama3_model_config("debugmodel", seq_len=128, attn_backend="varlen", parallelism=config.parallelism) (or let graph_trainer_llama3_debugmodel_varlen take seq_len).
| @@ -419,7 +417,6 @@ def rl_grpo_muse_glimmer_30b_search_r1() -> Controller.Config: | |||
| training=TrainingConfig( | |||
| disable_accelerator_graphs=True, | |||
| num_tokens_per_microbatch_per_dp_rank=4096, | |||
There was a problem hiding this comment.
This recipe already failed at startup before this PR (model 16384 vs. training 4096). After this PR it still fails, now at the batcher's 4096 % 16384 check. The 4096 token budget and the old training length both point to the intended value. Passing seq_len=4096 to build_rl_model_configs(...) above fixes it in one line. It also caps the generator's vLLM max_model_len at 4096, which is all the trainer could use anyway. If the 16384 rollout length is what was intended, raise the token budget to 16384 instead. Either way, it seems better to fix it here than to leave a recipe that can't run.
b2434e8 to
58ba145
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The force-push resolves the earlier test and RL recipe items. One new problem: the GraphTrainer trace test now fails at construction. That fix and the human-written summary are both small local edits. This PR touches core (trainer.py, training_engine.py, BaseModel), so a maintainer still needs to review it.
What changed since the last review (b2434e8 -> 58ba145).
- Resolved: the duplicate asserts in
test_debug_config_defaults.pyandtest_integration_test_definitions.pyare deleted. - Resolved:
search_r1.rl_grpo_muse_glimmer_30b_search_r1builds the model withseq_len=4096, andrl_grpo_qwen3_6_27b_varlen_perfsetsnum_tokens_per_microbatch_per_dp_rank=seq_len(65536). The description now lists both. - Changed, but now broken:
test_trace_module.pyrebuilds the model atseq_len=128instead of changing the built config (see Must fix 2). - Still open (should consider): Flux
build_model_configkeeps optionalseq_lenwith per-flavor defaults (torchtitan/models/flux/flavors.py:583).
Example.
config = graph_trainer_llama3_debugmodel_varlen() # local_compile.regions == []
config.model = build_model_config("debugmodel", seq_len=128, attn_backend="varlen", ...)
# -> Llama3Model.Config default: regions == ["loss", "fused_binary_activation", "rope"]
GraphTrainer(config) # ValueError: set model.local_compile.regions = []Must fix
- PR description: the "Summary (human-written)" section is still empty. The author needs to write it.
torchtitan/experiments/graph_trainer/tests/test_trace_module.py:2318-- the rebuilt model skipsto_graph_trainer_config, solocal_compile.regionsis non-empty again andGraphTrainingEngineraises. This is my earlier suggestion's fault. Fix: letgraph_trainer_llama3_debugmodel_varlentakeseq_lenand call it with 128 (suggestion inline).
Details
graph_trainer.llama3.build_model_config(graph_trainer/llama3/flavors.py) runsdisable_inplace_wgrad_accumbut doesn't resetlocal_compile.to_graph_trainer_config(graph_trainer/configs.py:349-357) does both, and every other GraphTrainer recipe goes through it. Passingseq_lenthrough the recipe keeps that single path. It also keeps the recipe'smax_num_documents = 64and CP load balancer unchanged, since those live on the dataloader and parallelism configs.- I couldn't diff against b2434e8 directly (the shallow checkout can't fetch it). I compared the earlier findings with HEAD and re-read the RL recipe and test hunks.
Not verified: I didn't run the GPU trace test. The failure comes from reading trainer.py:69 and the config defaults.
| config = graph_trainer_llama3_debugmodel_varlen() | ||
| config.dump_folder = dump_folder | ||
| config.training.max_context_length = 128 | ||
| config.model = build_model_config( | ||
| "debugmodel", | ||
| seq_len=128, | ||
| attn_backend="varlen", | ||
| parallelism=config.parallelism, | ||
| ) |
There was a problem hiding this comment.
My last review suggested this rebuild, and it breaks the test. The recipe's model goes through to_graph_trainer_config, which sets local_compile = LocalCompileConfig() (graph_trainer/configs.py:356). graph_trainer.llama3.build_model_config skips that step. It copies the fields of a Llama3Model.Config, whose default local_compile.regions is ["loss", "fused_binary_activation", "rope"] (models/llama3/model.py:88). So GraphTrainer(config) below raises in GraphTrainingEngine.__init__ (graph_trainer/trainer.py:69, "GraphTrainer traces the whole step into one graph; set model.local_compile.regions = []").
Smallest fix: give the recipe a length parameter and build the model at 128 there. Change graph_trainer_llama3_debugmodel_varlen(seq_len: int | None = DEFAULT_DEBUG_MODEL_SEQ_LEN) to pass it to llama3_debugmodel_varlen_attn(seq_len=seq_len) (torchtitan_recipes/tests/graph_trainer/llama3.py:65-67). Then call it here and drop the new import at line 2304:
| config = graph_trainer_llama3_debugmodel_varlen() | |
| config.dump_folder = dump_folder | |
| config.training.max_context_length = 128 | |
| config.model = build_model_config( | |
| "debugmodel", | |
| seq_len=128, | |
| attn_backend="varlen", | |
| parallelism=config.parallelism, | |
| ) | |
| config = graph_trainer_llama3_debugmodel_varlen(seq_len=128) | |
| config.dump_folder = dump_folder |
|
@claude review again |
58ba145 to
d4b8e44
Compare
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. The GraphTrainer trace test is fixed. The only must-fix left is the human-written summary. This PR touches core (trainer.py, training_engine.py, BaseModel), so a maintainer still needs to review it.
What changed since the last review (58ba145 -> d4b8e44).
- Resolved:
graph_trainer_llama3_debugmodel_varlennow takesseq_len(torchtitan_recipes/tests/graph_trainer/llama3.py:68-72) and passes it tollama3_debugmodel_varlen_attn, matching the signature of its sibling recipes._trace_llama3_step_codecalls it withseq_len=128(test_trace_module.py:2315). The model goes throughto_graph_trainer_configagain, solocal_compile.regionsis[]andGraphTrainingEngineno longer raises. RoPE,model.max_context_lengthand thepositions % config.model.max_context_lengthat line 2350 all use 128. The recipe still setsmax_num_documents = 64and the HeadTail CP load balancer. - Still open (should consider, not blocking): Flux
build_model_configkeeps an optionalseq_lenwith per-flavor defaults (torchtitan/models/flux/flavors.py:583). See the earlier inline comment.
Example.
# before (58ba145): rebuilt model skipped to_graph_trainer_config
config.model = build_model_config("debugmodel", seq_len=128, ...) # regions non-empty -> ValueError
# after (d4b8e44)
config = graph_trainer_llama3_debugmodel_varlen(seq_len=128) # regions == [], all lengths 128Must fix
- PR description: the "Summary (human-written)" section is still the template placeholder. The author needs to fill it in.
Not verified: I didn't run the GPU trace test. The fix was checked by reading the recipe chain and to_graph_trainer_config.
d4b8e44 to
f0b2f68
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. Since the last review the only code change is a comment clarification in Flux. The one must-fix left is the human-written summary. This PR touches core (trainer.py, training_engine.py, BaseModel), so a maintainer still needs to review it.
What changed since the last review (d4b8e44 -> f0b2f68).
- Changed: the
MODEL_FLAVORScomment intorchtitan/models/flux/flavors.py:568-570now says the Flux lengths are "defaults, not caps", unlike the decoders' capability lengths. That covers the earlier point that the tuple means something different here. - Still resolved at HEAD: the GraphTrainer trace test builds through
graph_trainer_llama3_debugmodel_varlen(seq_len=128)(test_trace_module.py:2315).search_r1builds the 30B model withseq_len=4096.rl_grpo_qwen3_6_27b_varlen_perfsetsnum_tokens_per_microbatch_per_dp_rank=seq_len. The duplicate asserts are gone. - Still open (should consider, not blocking): Flux
build_model_configkeeps an optionalseq_lenwith per-flavor defaults (flavors.py:583). The new comment documents that behavior, but the risk is still there. The custom-MXFP8 example intorchtitan/models/flux/README.md:94rebuilds the model withoutseq_len, so it quietly gets 768/512 instead of the recipe's length. You can fix it by makingseq_lenrequired, or by having the README passseq_len=config.model.max_context_lengththe way_enable_mxfp8does.
Example.
# README custom-MXFP8 path at HEAD
config = flux_recipe(...) # model.max_context_length = recipe's _flux_seq_len(...)
config.model = build_model_config(flavor, converters=[...], parallelism=...)
# -> max_context_length falls back to the flavor default, not the recipe's lengthMust fix
- PR description: the "Summary (human-written)" section is still the template placeholder. The author needs to fill it in.
Details
- I couldn't diff against d4b8e44 directly (the shallow checkout doesn't have it). I compared the full diff at HEAD with the earlier review findings. The diff stat (78 files, +91/-210) matches the PR metadata.
- The repo has no remaining
training.max_context_lengthreads. The othermax_context_length=keyword uses (dataset build context, rollouter, attention, batcher) are notTrainingConfigfields.
Not verified: GPU tests (GraphTrainer trace and bitwise tests, integration configs).
f0b2f68 to
729aab9
Compare
The model config already carries max_context_length, and validation forced training.max_context_length to equal it. Declare the field on BaseModel.Config, delete TrainingConfig.max_context_length and the equality check, and have the trainer, engine, validator, RL controller and recipes read model.max_context_length. preprocess_inputs no longer takes it; the decoder reads its own config. Flux flavors get a default length like the decoders do, and the HF backend sets the field in load_hf_config.
729aab9 to
66c0ec7
Compare
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
this approach, and what you checked yourself. -->
## Why
The Real PG integration suite (`8 GPU Integration (Real PG - full suite
- features)`) and the ROCm integration suite have failed the `sft` loss
check on main since #5757 (`899480301`; `a87db08ea` before it passed):
```
[sft] AssertionError: 7.889825820922852 != 7.887711524963379 : loss mismatch at step 1 # A10G
[sft] AssertionError: 7.890093803405762 != 7.887524604797363 : loss mismatch at step 1 # MI350X
```
#5757 renders `bos_token`/`eos_token` in Hugging Face chat templates, an
intended change to the SFT token stream. It regenerated
`tests/assets/losses/fake_pg/a10g/sft.txt` but not the real-PG A10G and
MI350X goldens.
## What changed
- `tests/assets/losses/real_pg/a10g/sft.txt` and
`tests/assets/losses/real_pg/mi350x/sft.txt`: steps 1-10 regenerated;
headers unchanged.
## Numerics
The new values are the full-precision TensorBoard metrics of the failing
main runs' baseline training (the same values `loss_compare.py
--export-result` writes), read with `scripts/loss_compare.py`'s own
extraction from the uploaded `integration-8gpu-features-outputs`
artifacts:
- A10G: run 41746280593 (`e6ca6d861`). Step 1 matches the log's baseline
(7.889825820922852, grad_norm 4.189799785614014).
- MI350X: the ROCm run on `73c4ebdac`. Step 1 matches the log's baseline
(7.890093803405762, grad_norm 4.189815998077393).
The commits between #5757 and those runs (#5572, #5787, #5776, #5774,
#5779, #5741, #5786) do not change SFT numerics.
## Testing
- CI: Real PG (`ciflow/real-pg`) and ROCm (`ciflow/rocm`) integration
suites.
- A manual `export_results` run of the integration workflow for `sft` on
main (run 41760303504) exported a real-PG A10G golden identical to this
one.
- `Multi-GPU Unit Tests` fails here with the `_VisionEncoder ...
named_preserve_dtype_params` error that is also on main; #5795 fixes it.
This PR was AI-assisted.
Conflicts resolved so main's new behavior and this PR's sum-then-scale design both hold: - #4819 (FLOPs per input batch): the graphable forward/backward returns (loss, metrics) and forward_backward builds ForwardBackwardResult with num_flops; kept, with this PR's single-argument _run_forward_backward. The core, GraphTrainer and TorchFT trainers keep main's FLOPs reduction and this PR's loss logging (sums divided by the step's loss tokens). TorchFT averages FLOPs over the replicas when ft_pg is set, also without DP or CP. - #5779 (max_context_length from the model config): preprocess_inputs drops max_context_length and keeps aux_loss_denominators. - #5563 (ChunkedLossWrapper keeps caller FSDP policies): main's chunked loop, without the count argument. test_chunked_loss_fsdp.py: losses are sums; the test divides gradients once by the loss tokens before comparing, as optim_step does. - #5757/#5796 (SFT data change): sft.txt goldens taken from main; regenerated from CI next.
Stacked on #5835. ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Why GraphTrainer already runs Muse Glimmer in its integration tests, but nothing checks its numerics against eager, so a GraphTrainer change could silently alter Muse Glimmer's loss. The vision flavor (`debugmodel_mm`) also fails deep in tracing with a data-dependent-shape error instead of a clear message. **Example.** ```python to_graph_trainer_config(muse_glimmer_debugmodel_mm(), GraphTrainerMuseGlimmerModel.Config) # Before: fails during make_fx with a data-dependent-shape error # After: ValueError at config time: GraphTrainer MuseGlimmer supports # text-only flavors; got a vision encoder. ``` ## What changed - `graph_trainer/muse_glimmer/model.py`: the config rejects a vision encoder with `ValueError`, like Kimi K3, Kimi K2.7, and Qwen3.5 earlier in this stack. - Bitwise harness classes for Varlen and FlexAttention; a FlexAttention test recipe; 4-GPU numerics configs (FSDP2 + TP2); README row. ## Numerics Eager FSDP2 vs GraphTrainer, seed 42, deterministic, `scripts/loss_compare.py --assert-equal`. Measured on base `0f3481537`. Rebasing onto `d0ab95e46` changed only recipe field names in this diff (#5776, #5779); re-verification on the new base is in progress. | Config | GPUs | Result | | --- | --- | --- | | `debugmodel`, FlexAttention, FSDP2 + TP2, 20 steps | 4x GB300 | loss and grad_norm bitwise identical | | `debugmodel`, PP2 Interleaved1F1B, 10 steps | 2x GB300 | loss and grad_norm bitwise identical | The 4-GPU comparison uses FlexAttention. FA4's Varlen backward is not deterministic for full causal attention on Blackwell, so two Varlen eager runs with FSDP2 + TP2 already differ in grad_norm at step 1. ## Testing - `test_bitwise_deterministic.py::TestMuseGlimmerBitwiseDeterministic` and `TestMuseGlimmerFlexAttnBitwiseDeterministic` (1 GPU): eager vs aot_fx_trace, trace vs precompile, and `numerics_changing_optim` run-to-run produce bitwise identical loss, model hash, and gradient hash. - `test_numerics.py::test_dense_muse_glimmer_aot_fx_trace_vs_eager` (4 GPUs): the FSDP2 + TP2 row above. - The PP row was run locally; it is not a CI test. ## Known issues / follow-ups - CP is not covered. - Next in the stack: Muse Spark (in progress).
Stacked on #5774, which is stacked on #5776 (GitHub stack: this PR's base is #5774's branch).
Summary (human-written)
Right now we have both
model.max_context_lengthandtraining.max_context_length. The latter is redundant. This PR consolidates them.Why
The context length is set twice: once on the model config (
build_model_config(..., seq_len=...)) and once astraining.max_context_length.validate_model_training_configthen requires the two to be equal, so every recipe repeats the model's value:The model owns its context length: it sizes the RoPE cache and attention metadata, and RL serves it with vLLM
max_model_len = model.max_context_length. A second copy inTrainingConfigadds nothing but a way to get it wrong.What changed
max_context_length: intis declared onBaseModel.Config(it was onDecoder.Config).TrainingConfig.max_context_lengthand the equality check invalidate_model_training_configare deleted.model.max_context_length.preprocess_inputsno longer takesmax_context_length: the decoder readsself.config.max_context_lengthwhen it builds attention metadata. The engine, validator and GraphTrainer stop passing it.MODEL_FLAVORSentries become(factory, default_len), like the decoders, andbuild_model_configtakesseq_len. The defaults (768 / 512 / 512) are the_flux_seq_len(img_size, t5_len)of the shipped recipes, which still pass it explicitly.load_hf_configalso setsmax_context_length; itsmax_seq_len(aliased to HFmax_position_embeddings) is unchanged.search_r1.rl_grpo_muse_glimmer_30b_search_r1: the model is built withseq_len=4096(it defaulted to 16384; training was 4096).alphabet_sort.rl_grpo_qwen3_6_27b_varlen_perf:num_tokens_per_microbatch_per_dp_rank = seq_len(65536). Its 2048 came from the 9B base recipe, while the recipe builds a 65536-length model.max_context_length=removed from everyTrainingConfig(...)in recipes and tests;config.training.max_context_lengthreads becomeconfig.model.max_context_length.User-facing changes
training.max_context_lengthbuild_model_config(..., seq_len=...)and readmodel.max_context_lengthtrainer.training.max_context_lengthtrainer.model.max_context_lengthmodel.preprocess_inputs(..., max_context_length=...)build_model_config(flavor, parallelism=...)seq_len(defaults per flavor)Numerics
No computation change: every value the training path reads is the same number as before. I built every zero-argument recipe in
torchtitan_recipes(220) on the base commit and on this branch:model.max_context_lengthhere equals the oldtraining.max_context_lengthfor all of them except the two RL recipes above, which could not run on main.Testing
tests/unit_tests/cpu,tests/rl/unit_tests/cpu, GraphTrainer, torchft and HF-backend tests): same results as the base commit. The remaining failures also fail there on this aarch64 host (LoRA, Qwen3.5 MRoPE x3).TrainingConfig(max_context_length=0)validation case is deleted with the field. No new tests: the recipe build check above covers the move.This PR was AI-assisted.