Repository navigation
EMo causal pools for mid-training (on #916) - #948
Conversation
…o far Port of the MaxText `emo_causal_pool` (AkshitaB/maxtext@7b2380e). The whole-document pool lets a document's first tokens route inside a pool chosen with its later tokens, which they don't have at inference. With `EmoRouterConfig.causal_pool` the pool totals are per-document prefix sums (`ops.doc_prefix_sum`) instead of `doc_sum_scatter`, so a document's first token keeps its own top experts and its last token gets the whole-document pool. Off by default; the default path is unchanged. MultimodalLM now hands EMO routers its attention documents (`example_ids`, or `document_ids` when set: the text stage's EOS + 8K-chunk segments, packed vision examples) as `emo_segment_ids`, instead of letting the LM derive documents from EOS, which packed examples and chunk boundaries don't carry.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a9c05af8fa
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if example_ids is not None and self._has_emo_routers(): | ||
| # EMO pools follow the attention documents (packed examples, or the text stage's | ||
| # EOS + chunk segments), not EOS alone: packed examples need not end in EOS. | ||
| kwargs["emo_segment_ids"] = segment_ids_from_example_ids(example_ids.to(device)) |
There was a problem hiding this comment.
Keep sibling branches out of each other's EMo pools
When a packed example contains multiple sibling branches, subsegment_ids makes the attention mask isolate those branches, but this assigns every token with the same example_id to one EMo segment. In causal mode, a later branch therefore accumulates router scores from earlier siblings that it cannot attend to; in non-causal mode, every branch uses scores from all siblings. This breaks branch isolation for packed multi-annotation training, so the pool segmentation must account for sibling branches or reject this packing mode when EMo is active.
Useful? React with 👍 / 👎.
| if self.emo.causal_pool: | ||
| document_scores = ops.doc_prefix_sum(scores, segment_ids) | ||
| keep = ops.pool_keep_mask(document_scores, self._pool_sizes(segment_ids)) |
There was a problem hiding this comment.
Preserve prefix scores during cached decoding
With a restrictive evaluation pool, cached generation does not implement the causal policy used here: TransformerGenerationModule sends the full prompt only for prefill and then calls the model with generated[:, -1:], so doc_prefix_sum sees only the current token on every decode step. Expert selection therefore differs from uncached generation, which recomputes the full document prefix, even though GenerationConfig.use_cache defaults to true. The router needs persistent per-document score sums during cached decoding, or causal EMo must explicitly disable that path.
Useful? React with 👍 / 👎.
| min_document_expert_pool: int | ||
| max_document_expert_pool: int | ||
| eval_document_expert_pool: Optional[int] = None | ||
| causal_pool: bool = False |
There was a problem hiding this comment.
Propagate causal pools through MaxText conversion
When a checkpoint with causal_pool=True is converted through nn/maxtext/config.py, _emo_spec() records only the EOS and pool sizes, and MaxTextModelConfig.overrides() never emits MaxText's emo_causal_pool setting. The resulting MaxText run silently reverts to whole-document routing despite loading a causal-pool OLMo configuration, changing training and evaluation behavior; the conversion should preserve this field or reject causal configurations.
Useful? React with 👍 / 👎.
…916) (#949) Follow-up to #948, found while dry-running the EMo causal-pool hero run (Run 2's config with `HERO256K_EMO=causal`). ## Problem With `recipe.parent_checkpoint` (an alignment checkpoint), `_build_model` takes the multimodal model, routers included, from the **parent's** config. - The parent's LM carries alignment's routing, which has EMo off. - The stage's text config is consulted only for runtime fields (recompute, EP scratch sharing). - So a text stage built with EMo on still trained with EMo off. In the dry run, every router showed `emo=None` despite `HERO256K_EMO=causal`. ## Change `_build_model` copies each routed block's `emo` from the stage's text config (`None` or an `EmoRouterConfig`), matching blocks by the same pairing it already uses for the EP fields. Existing runs are unchanged: Runs 1–7 have EMo off in both their text configs and their parents. ## Tests `test_mixed_stage_routers_take_the_text_stage_emo`, parametrized: - Text EMo off gives `emo=None`. - Text EMo with causal pools gives causal EMo with the text config's pool sizes on every routed block. `src/test/internal/vision_midtraining_test.py`: 98 passed. Ruff, isort and black are clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Follow-up to #948, from Akshita's review of it. ## Problem `ops.doc_prefix_sum` computes each token's per-document running sum the way MaxText `emo_causal_pool` does: - One cumsum over the whole row. - Each document then subtracts the total before its start. In float32 that subtraction loses precision late in a long row, because both terms are large there. Akshita's check against exact per-document sums at 256K found: - The pool changed for 0.25% of tokens. - The selected top-16 changed for 0.035%. - All were near-ties, and none were a document's first tokens. ## Change `doc_prefix_sum` accumulates in float64 and returns `per_token`'s dtype (fp32 scores in the router). Nothing else changes, and whole-document EMo (`doc_sum_scatter`) is untouched. **Cost (estimated, not measured):** at 256K tokens × 512 experts, the float64 cumsum and its gathered copy are about 1 GiB each, compared with 0.5 GiB in float32. They're freed right after the pool mask is built, once per MoE layer. Time-wise it's a memory-bound scan, small next to the pool mask's two argsorts. I haven't measured it on GPU yet; the next run that turns causal pools on will show the step-time effect. ## Tests New `test_doc_prefix_sum_is_exact_over_long_rows`: - Setup: a 262,144-token row with 32 experts and documents of 1–4,096 tokens. The prefix sums must match exact per-document float64 cumsums to 1e-6, and the pool masks (P=8) must agree on more than 99.99% of tokens. - With the float32 cumsum, the test fails: 66.7% of the sums are off by more than 1e-6, with a max error of 8.9e-4, and the pool changes for 0.10% of tokens. That's consistent with Akshita's 0.25% at 512 experts. - `emo_router_v2_test.py` + `emo_document_pool_test.py`: 17 passed, 5 skipped (GPU-only). Black and ruff are clean. ## Not affecting the running job The EMo causal-pool hero run (`olmoe3-810m-cx2-mm-hero-mt-lc-256k-emocausal-lm1e4`) keeps float32, the same as MaxText. This applies to later runs only. MaxText's `emo_causal_pool` has the same float32 cumsum and may want the same change, so the two implementations stay in step. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Stacked on #916. This prepares an ablation PT asked for: Run 2 (the "Ablation 2" config, row 34 of the midtraining results sheet: 256K,
lm1e-4alignment parent, MT+ with agentic data, vision v6), rerun with EMo turned on with causal pools during mid-training instead of EMo off. The hero recipe currently runs every downstream stage with EMo off.Why
From Akshita's write-up and MaxText work (oe-planning #86–#88, #97):
Causal pools haven't been tested in mid-training yet, which is what this run is for. The bar is "no regression against Run 2" on our evals. PT runs the modularity checks on the checkpoint.
What changes
1.
EmoRouterConfig.causal_poolOff by default; the default path is unchanged. This is the same rule as the MaxText
emo_causal_poolflag (AkshitaB/maxtext@7b2380e):csum_end - csum_before(whole document) becomescsum - csum_before: the sum of the document's scores up to and including each token, in fp32 on the softmax scores. Here that'sops.doc_prefix_sum, used in place ofops.doc_sum_scatter.document_pool_keep_maskprofiling kernel is bypassed.2. EMo document boundaries in
MultimodalLM(no MaxText counterpart)segment_ids_from_eos). That matched attention in text pretraining.MultimodalLMnow passes its attention documents toTransformer._prepare_inputsasemo_segment_ids. These come fromexample_ids, ordocument_idswhen set: the text stage's EOS + 8K-chunk segments. A padding run counts as one document.Transformercallers are unchanged.Pool sizes: same as pretraining
When a stage keeps EMo (
apply_stage_routing(use_emo=True)in scaling-ladders), it reuses the source checkpoint's router config unchanged. I checked both source checkpoints (olmo35-small-hero-20260907/emo/14Tandolmo35-small-14t-plus600bdecay-20261008-emo/step870229):min_document_expert_pool=16,max_document_expert_pool=512: each document draws one pool size P uniformly from 16–512, independently in each MoE layer. Each token picks its 16 experts from inside its pool.eval_document_expert_pool=512: eval and HF export use all experts, so EMo (causal or not) is a no-op for our standard evals. Only PT's modularity checks use small pools.The {32, 64, 256} sizes (probabilities 1/8, 1/8, 3/4) in the write-up are MaxText's tiny-model "r3" recipe. The write-up finds those sizes aren't special.
Tests
src/test/nn/moe/emo_router_v2_test.py. The two router tests mirror MaxText'sEmoEvalPoolsTestcases:pool_keep_maskcall.test_causal_pool_ignores_later_tokenstest_causal_pool_ignores_later_tokens)test_causal_pool_first_token_keeps_its_own_top_expertstest_doc_prefix_sum_matches_per_document_cumsumdoc_sum_scattertest_multimodal_emo_segments_follow_example_idsexample_ids, including the padding runDifferences from MaxText's tests:
Results (CPU):
emo_router_v2_test.py+emo_document_pool_test.py): 16 passed, 5 skipped (GPU-only kernel tests).src/test/nn/vision/multimodal_test.py: 46 passed.data/multimodal/*andmultimodal_train_module.py).Not in this PR / next
use_emo=Trueandcausal_pool=True(Some fixes/improvements around synchronous bookkeeping operations #83 follow-up).🤖 Generated with Claude Code