Skip to content

EMo causal pools for mid-training (on #916) - #948

Merged
jason718 merged 2 commits into
jasonr/olmo35-mixed-midtrainingfrom
jasonr/emo-causal-pool
Nov 7, 2026
Merged

jason718 merged 2 commits into
jasonr/olmo35-mixed-midtrainingfrom
jasonr/emo-causal-pool

Conversation

@jason718

@jason718 jason718 commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

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-4 alignment 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):

  • Whole-document EMo picks each document's pool from router scores summed over the entire document, future tokens included. A document's first tokens are therefore routed with information they won't have at inference.
  • The cost in her tests:
    • First-16-token loss is 1.3–1.9 nats worse.
    • On a bare prompt, the model ends the document immediately in 13 of 16 cases.
  • Causal pools fix this and keep modularity on her tiny-model decay (step 9,499):
Decay First-16 CE (all experts) Own 64-expert pool CE Bare prompt ends immediately
EMo off 3.33 2.135 0/16
EMo on 5.20 2.092 13/16
Causal 3.34 2.067 0/16

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_pool

Off by default; the default path is unchanged. This is the same rule as the MaxText emo_causal_pool flag (AkshitaB/maxtext@7b2380e):

  • MaxText's csum_end - csum_before (whole document) becomes csum - csum_before: the sum of the document's scores up to and including each token, in fp32 on the softmax scores. Here that's ops.doc_prefix_sum, used in place of ops.doc_sum_scatter.
  • Each token's pool is the top-P experts by those sums. A document's first token keeps its own top experts, the pool narrows as the document goes on, and the last token's pool equals the whole-document pool.
  • In causal mode the env-gated fused document_pool_keep_mask profiling kernel is bypassed.

2. EMo document boundaries in MultimodalLM (no MaxText counterpart)

  • Until now the LM derived EMo documents from EOS tokens (segment_ids_from_eos). That matched attention in text pretraining.
  • In mixed mid-training batches, attention documents aren't EOS-delimited:
    • The text side is 32 unrelated 8K chunks per 256K instance, with no EOS at chunk ends.
    • Packed vision examples need not end in EOS.
  • Without this change, a pool would span unrelated chunks or examples.
  • MultimodalLM now passes its attention documents to Transformer._prepare_inputs as emo_segment_ids. These come from example_ids, or document_ids when set: the text stage's EOS + 8K-chunk segments. A padding run counts as one document.
  • Pools therefore restart exactly where attention and KDA state restart.
  • Nothing is passed when the LM has no EMo routers, and plain Transformer callers 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/14T and olmo35-small-14t-plus600bdecay-20261008-emo/step870229):

  • 512 routed experts, top-k 16.
  • 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.
    • P = 16: every token in the document uses the same 16 experts.
    • P = 512: no restriction.
  • 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's EmoEvalPoolsTest cases:

  • Same setup: router weight = identity so expert logits are given directly; pools sampled in [2, 8] of 8 experts.
  • Same documents: 6 + 10 tokens in row 0 and 16 tokens in row 1.
  • The pool mask is read from the router's pool_keep_mask call.
Test Checks
test_causal_pool_ignores_later_tokens Noise added to tokens 9 onward leaves the pool masks of tokens 0–8 unchanged and changes later ones (as MaxText's test_causal_pool_ignores_later_tokens)
test_causal_pool_first_token_keeps_its_own_top_experts Each document's first token keeps exactly its own top-P logits, and its last token's mask equals the whole-document one (as MaxText's test of the same name)
test_doc_prefix_sum_matches_per_document_cumsum Prefix sums match a brute-force per-document cumsum over 4 segment layouts, and the last token of each document matches doc_sum_scatter
test_multimodal_emo_segments_follow_example_ids Document numbering from example_ids, including the padding run

Differences from MaxText's tests:

  • Segment ids are 0-based, as OLMo-core's are.
  • The seed is chosen so every first-token pool actually restricts its document (pools of 3, 7 and 6 experts). The test asserts this, so it can't pass trivially with a full pool.

Results (CPU):

  • EMo tests (emo_router_v2_test.py + emo_document_pool_test.py): 16 passed, 5 skipped (GPU-only kernel tests).
  • With causal mode disabled in the router, both causal tests fail, as they should.
  • src/test/nn/vision/multimodal_test.py: 46 passed.
  • isort, black and ruff are clean. mypy reports nothing in the changed files (the 9 errors it prints are pre-existing, in data/multimodal/* and multimodal_train_module.py).

Not in this PR / next

  • The scaling-ladders switch that runs Run 2's config with use_emo=True and causal_pool=True (Some fixes/improvements around synchronous bookkeeping operations #83 follow-up).
  • A GPU smoke run: loss at Run 2's start, and the step-time overhead of EMo routing compared with Run 2.
  • The full run: 64 GPUs for about 2 days, pending compute from Taira. Checkpoints go to PT for modularity checks.

🤖 Generated with Claude Code

…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.
@jason718
jason718 marked this pull request as ready for review November 7, 2026 07:08
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-07T07:11:21.852284Z a9c05af Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@jason718
jason718 merged commit 58885dc into jasonr/olmo35-mixed-midtraining Nov 7, 2026
1 check passed
@jason718
jason718 deleted the jasonr/emo-causal-pool branch November 7, 2026 07:08

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +1084 to +1087
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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Comment on lines +98 to +100
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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

jason718 added a commit that referenced this pull request Nov 7, 2026
…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)
jason718 added a commit that referenced this pull request Nov 7, 2026
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant