Skip to content

[config] Read max_context_length from the model config - #5779

Merged
tianyu-l merged 1 commit into
mainfrom
model-max-context-length
Nov 4, 2026
Merged

tianyu-l merged 1 commit into
mainfrom
model-max-context-length

Conversation

@tianyu-l

@tianyu-l tianyu-l commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

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_length and training.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 as training.max_context_length. validate_model_training_config then requires the two to be equal, so every recipe repeats the model's value:

model_config = build_model_config("debugmodel", seq_len=2048, parallelism=parallelism)
Trainer.Config(
    model=model_config,
    training=TrainingConfig(
        max_context_length=model_config.max_context_length,  # must equal the model's
        ...
    ),
)

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 in TrainingConfig adds nothing but a way to get it wrong.

What changed

  • max_context_length: int is declared on BaseModel.Config (it was on Decoder.Config). TrainingConfig.max_context_length and the equality check in validate_model_training_config are deleted.
  • The trainer, training engine, validator, RL controller (batcher and SP divisibility check), torchft and GraphTrainer read model.max_context_length.
  • preprocess_inputs no longer takes max_context_length: the decoder reads self.config.max_context_length when it builds attention metadata. The engine, validator and GraphTrainer stop passing it.
  • Flux: MODEL_FLAVORS entries become (factory, default_len), like the decoders, and build_model_config takes seq_len. The defaults (768 / 512 / 512) are the _flux_seq_len(img_size, t5_len) of the shipped recipes, which still pass it explicitly.
  • HF backend (experiment): load_hf_config also sets max_context_length; its max_seq_len (aliased to HF max_position_embeddings) is unchanged.
  • Two RL recipes set different model and training lengths, so they already failed at RL trainer startup on main (the equality check). They now take the length the deleted training value recorded, and their token budgets are multiples of it:
    • search_r1.rl_grpo_muse_glimmer_30b_search_r1: the model is built with seq_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.
  • Mechanical, skimmable: max_context_length= removed from every TrainingConfig(...) in recipes and tests; config.training.max_context_length reads become config.model.max_context_length.

User-facing changes

Before After
training.max_context_length removed; set the model length with build_model_config(..., seq_len=...) and read model.max_context_length
RL: trainer.training.max_context_length trainer.model.max_context_length
model.preprocess_inputs(..., max_context_length=...) argument removed
Flux build_model_config(flavor, parallelism=...) also takes 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_length here equals the old training.max_context_length for all of them except the two RL recipes above, which could not run on main.

Testing

  • CPU suites (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).
  • Tests that asserted the old field or kwarg are updated; the 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.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 3, 2026
@tianyu-l
tianyu-l added this pull request to stack #5780 November 3, 2026 19:18
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 3, 2026
@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 5m 7s —— View job


Approve -- please address the items in the review before merging: review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_length

Numerics: 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

  1. PR description: the "Summary (human-written)" section is empty. The author needs to fill it in.
  2. tests/unit_tests/cpu/recipes/test_debug_config_defaults.py:161 and tests/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 Flux seq_len required and drop the per-flavor defaults. They have no in-repo code consumer, and they let a rebuild that omits seq_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 with seq_len=128 instead of changing config.model.max_context_length, which leaves the RoPE length stale.
  • torchtitan_recipes/rl/search_r1.py:419 and alphabet_sort.rl_grpo_qwen3_6_27b_varlen_perf -- both are one-line fixes that can go in this PR. For search_r1, pass seq_len=4096 to build_rl_model_configs. For the 27B recipe, set num_tokens_per_microbatch_per_dp_rank=seq_len when it replaces config.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_length references in .py, .md, .sh, .yaml, .toml or .json files. Every BaseModel.Config subclass sets the field: the decoders through their flavors, Flux through the new seq_len, the HF backend in load_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_ep2 users (in tests/models/deepseek_v3.py and tests/graph_trainer/b200.py) build the model with seq_len=128, so removing training.max_context_length = 128 there is safe. test_bitwise_deterministic builds with seq_len=SEQ_LEN. muse_spark_debugmodel_ultradata_lora_sft builds with seq_len=32_768.
  • PP/CP/TP: every pipeline stage shares one model config, so self.config.max_context_length is 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After the rename this line is the same as the assert on the next line, so it checks nothing new. Delete it.

Suggested change
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as the line above: once there is only one length, this assert repeats line 193. Delete it.

Suggested change
assert config.model.max_context_length == 2048

converters: list[ModelConfigConverter.Config] | None = None,
*,
parallelism: ParallelismConfig,
seq_len: int | None = None,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@tianyu-l
tianyu-l force-pushed the model-max-context-length branch from b2434e8 to 58ba145 Compare November 3, 2026 19:31
@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 35s —— View job


Approve -- please address the items in the review before merging: review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.py and test_integration_test_definitions.py are deleted.
  • Resolved: search_r1.rl_grpo_muse_glimmer_30b_search_r1 builds the model with seq_len=4096, and rl_grpo_qwen3_6_27b_varlen_perf sets num_tokens_per_microbatch_per_dp_rank=seq_len (65536). The description now lists both.
  • Changed, but now broken: test_trace_module.py rebuilds the model at seq_len=128 instead of changing the built config (see Must fix 2).
  • Still open (should consider): Flux build_model_config keeps optional seq_len with 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

  1. PR description: the "Summary (human-written)" section is still empty. The author needs to write it.
  2. torchtitan/experiments/graph_trainer/tests/test_trace_module.py:2318 -- the rebuilt model skips to_graph_trainer_config, so local_compile.regions is non-empty again and GraphTrainingEngine raises. This is my earlier suggestion's fault. Fix: let graph_trainer_llama3_debugmodel_varlen take seq_len and call it with 128 (suggestion inline).
Details
  • graph_trainer.llama3.build_model_config (graph_trainer/llama3/flavors.py) runs disable_inplace_wgrad_accum but doesn't reset local_compile. to_graph_trainer_config (graph_trainer/configs.py:349-357) does both, and every other GraphTrainer recipe goes through it. Passing seq_len through the recipe keeps that single path. It also keeps the recipe's max_num_documents = 64 and 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.

Comment on lines +2316 to +2323
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,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
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

@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@tianyu-l
tianyu-l force-pushed the model-max-context-length branch from 58ba145 to d4b8e44 Compare November 3, 2026 19:37
@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 22s —— View job


Approve -- please write the human-written summary before merging: review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_varlen now takes seq_len (torchtitan_recipes/tests/graph_trainer/llama3.py:68-72) and passes it to llama3_debugmodel_varlen_attn, matching the signature of its sibling recipes. _trace_llama3_step_code calls it with seq_len=128 (test_trace_module.py:2315). The model goes through to_graph_trainer_config again, so local_compile.regions is [] and GraphTrainingEngine no longer raises. RoPE, model.max_context_length and the positions % config.model.max_context_length at line 2350 all use 128. The recipe still sets max_num_documents = 64 and the HeadTail CP load balancer.
  • Still open (should consider, not blocking): Flux build_model_config keeps an optional seq_len with 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 128

Must fix

  1. 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.

@tianyu-l
tianyu-l force-pushed the model-max-context-length branch from d4b8e44 to f0b2f68 Compare November 3, 2026 21:44
@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 2s —— View job


Approve -- please write the human-written summary before merging: review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_FLAVORS comment in torchtitan/models/flux/flavors.py:568-570 now 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_r1 builds the 30B model with seq_len=4096. rl_grpo_qwen3_6_27b_varlen_perf sets num_tokens_per_microbatch_per_dp_rank=seq_len. The duplicate asserts are gone.
  • Still open (should consider, not blocking): Flux build_model_config keeps an optional seq_len with per-flavor defaults (flavors.py:583). The new comment documents that behavior, but the risk is still there. The custom-MXFP8 example in torchtitan/models/flux/README.md:94 rebuilds the model without seq_len, so it quietly gets 768/512 instead of the recipe's length. You can fix it by making seq_len required, or by having the README pass seq_len=config.model.max_context_length the way _enable_mxfp8 does.

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 length

Must fix

  1. 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_length reads. The other max_context_length= keyword uses (dataset build context, rollouter, attention, batcher) are not TrainingConfig fields.

Not verified: GPU tests (GraphTrainer trace and bitwise tests, integration configs).

@tianyu-l
tianyu-l marked this pull request as ready for review November 3, 2026 23:04
@pytorch-bot pytorch-bot Bot added the ciflow/b200 Trigger B200 CI label Nov 3, 2026
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 3, 2026
@github-actions
github-actions Bot requested a review from pzhan9 November 3, 2026 23:04

@d4l3k d4l3k left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm from ft side

@tianyu-l
tianyu-l force-pushed the model-max-context-length branch from f0b2f68 to 729aab9 Compare November 4, 2026 00:22
Base automatically changed from preserve-dtype-params to main November 4, 2026 00:25
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.
@tianyu-l
tianyu-l force-pushed the model-max-context-length branch from 729aab9 to 66c0ec7 Compare November 4, 2026 00:25
@tianyu-l
tianyu-l merged commit e2b5988 into main Nov 4, 2026
@tianyu-l
tianyu-l deleted the model-max-context-length branch November 4, 2026 00:25
tianyu-l added a commit that referenced this pull request Nov 4, 2026
## 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.
felipemello1 pushed a commit that referenced this pull request Nov 5, 2026
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.
felipemello1 pushed a commit that referenced this pull request Nov 5, 2026
…config, Trainer takes precision

Main moved max_context_length from TrainingConfig to the model config (#5779) and dtypes into a
root-owned PrecisionConfig (#5776). The test now passes the recipe's precision to Trainer.
2 GPUs: 1 passed (87 s).
SherlockNoMad added a commit that referenced this pull request Nov 9, 2026
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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants