Skip to content

Add the OLMoDDP hooks a multimodal wrapper needs, inert by default - #886

Merged
jason718 merged 1 commit into
visionfrom
jasonr/native-olmo-ddp-runtime-on-vision
Oct 5, 2026
Merged

jason718 merged 1 commit into
visionfrom
jasonr/native-olmo-ddp-runtime-on-vision

Conversation

@jason718

@jason718 jason718 commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The optional hooks a wrapper model (a multimodal model with a vision encoder and connector around the OLMoDDP LM) needs from the text runtime. Every hook defaults to today's path, so text-only training is unchanged. Rustin's runtime rework from #868 is not carried.

63 source lines in three shared files, plus tests:

File Hook Default
nn/ddp/model.py forward(input_embeddings=None, router_loss_div_factor=None) None: embeds input_ids and uses loss_div_factor for the routers, as today
nn/ddp/model.py apply_dp(root_module=None): DDP-wrap and bf16-cast an outer module that contains the LM None: wraps self, as today
train/train_module/transformer/ddp_train_module.py _is_olmo_ddp_compatible (wrappers opt in with _olmo_ddp_compatible = True); _batch_auxiliary_loss_kwargs; _optimizer_state_dict_for_load / _after_load around the direct checkpoint load same check for OLMoDDPModel; {}; identity
train/train_module/transformer/config.py _build_train_module builds OLMoDDPTrainModule, as today

internal/experiment.py is not touched: the vision-alignment recipe (#889) has its own main()/train().

What to review (text team)

  1. OLMoDDPModel.forward: with both new arguments None, is the path unchanged? (The input_embeddings branch, and overriding all_block_kwargs["loss_div_factor"] for the routers.)
  2. apply_dp(root_module=...): OK to run DDP and the bf16 cast on a module that contains the LM?
  3. load_state_dict_direct: are the two identity hooks next to the QK-expansion logic an acceptable extension point?

Tests: src/test/nn/ddp/model_hooks_test.py, src/test/train/train_module/transformer/ddp_train_module_hooks_test.py (5 tests; each hook equals the default path when omitted).

Text-neutrality gates (against the text team's pin b5db31dbd = #885, and against vision + #885)

Gate Result
1. Allow-list diff of shared code vs vision only the three files above
2. Resolved config of the text mid-training recipe (scaling-ladders midtraining.py, Caleb's overrides) identical to vision+#885; vs the pin the only difference is the pre-existing model.n_extra_vocab = 0 key from vision
3. The pin's own unit tests run against this source (CPU) identical on pin / vision+#885 / hooks+#885: 668 passed, 1,427 skipped, 2 failed (checkpoint_test.py::*remote_s3_dir, NoCredentialsError: no AWS credentials on the dev box; the pin fails the same way)
3. The pin's own GPU tests against this source (A100) identical on pin / vision+#885 / hooks+#885: 164 passed, 9 xfailed, 1 failed (routed_experts_v2_test.py::test_no_ep_routed_core_matches_naive_reference, needs TransformerEngine, absent locally; the pin fails the same way)
4. Golden forward/backward on the real 8T weights (A100, no TE/flash_4; loss+z-loss, router losses, gradients) PASSED, bitwise-identical forward (loss 2.900310, CE 2.899298, z-loss 1.0116e-3, logits SHA 2dcb9544…, all 96 router metrics equal to a pin dump), eager and compiled (compiled: loss 2.900429, logits 79d0f9eb… on both trees). Gradients: max rel-L2 1.0e-1 vs the pin's own cross-process spread of 1.19e-1 (the KDA/SDPA backward uses atomics and kernel selection differs across processes, so the pin was dumped 6 times to measure its spread). Same result for vision+#885 vs the pin.
5. Seeded 100-step text A/B on 8 B300 (holmes), text recipe on the 8T checkpoint done (pin x2 as noise floor, hooks+#885 x1; 100 steps, 8 B300, text recipe on the 8T checkpoint, W&B ai2-llm/olmo35-multimodal group olmo35-text-ab). Step-1 CE 1.6068751 vs pins 1.6068819 (the two pins are bit-identical; relative diff 4e-6, see the compiled note below); step-1 grad norm 4,199,863.5 = pin1 (pin2: 4,199,086); max CE difference vs pin1 over 100 steps 5.4e-4 vs the pins' own spread 5.9e-4; final CE 1.48504 vs 1.48496 / 1.48473; 0 skipped steps; LR identical; throughput 94.5k vs 93.9k / 94.0k TPS per device (+0.6%); GPU active/reserved memory identical (192.6 / 193.0 GiB); identical W&B key sets. Step-100 checkpoints: identical 1,662 keys, shapes and dtypes.
4b. Same on a B300 with the production kernels (TE, grouped GEMM, flash_4, kernel_fun), full stack (#886 + #889 rebuild + #885) vs the pin eager: bitwise-identical forward (pin vs pin is bitwise too), 96 router metrics equal, grads max rel-L2 9.1e-3 vs the pin's floor 1.3e-2. Compiled: loss 2.900474 vs 2.900569 (diff 9.5e-5), logits rel-L2 7.1e-3, 6 of 96 router load-imbalance counts differ by 1–3 tokens; a compiled pin-vs-pin floor is being measured to attribute this (torch.compile fusions differ when the Python differs, even if the math is the same).
3b. The pin's GPU tests on a B300 against the full stack identical to the pin: 283 passed, 40 xfailed, 0 failed

Pre-existing differences that come from vision itself, not from this PR: model.n_extra_vocab in the resolved config; two extra speed-monitor metrics.

Test plan

🤖 Generated with Claude Code

@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: 80d401aae2

ℹ️ 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 thread src/olmo_core/train/callbacks/wandb.py Outdated
wandb_dir = self.trainer.work_dir / "wandb"
wandb_dir.mkdir(parents=True, exist_ok=True)
init_kwargs: Dict[str, Any] = {}
if self.auto_resume and self.run_id is not None:

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 Honor explicit W&B run IDs

When a user sets run_id to resume a legacy run but leaves auto_resume at its default False, this condition omits the ID and resume policy from wandb.init, so W&B creates a new run and then overwrites self.run_id. That contradicts the documented purpose of run_id and makes the stated legacy-checkpoint recovery path ineffective unless users discover the additional, undocumented flag requirement.

Useful? React with 👍 / 👎.

@jason718 jason718 self-assigned this Sep 28, 2026
@jason718
jason718 force-pushed the jasonr/native-olmo-ddp-runtime-on-vision branch from 80d401a to cc7696c Compare September 30, 2026 04:19
@jason718 jason718 changed the title Add native OLMoDDP training and expert-parallel runtime (#868 rebased onto vision) Add the OLMoDDP hooks a multimodal wrapper needs, inert by default (replaces the #868 copy) Sep 30, 2026

@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: cc7696cd6f

ℹ️ 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".

else:
batch_num_tokens_for_loss = batch_num_tokens_for_loss.clamp_min(1)

auxiliary_loss_kwargs = self._batch_auxiliary_loss_kwargs(batch)

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 Apply auxiliary loss kwargs in pipeline mode

When a wrapper overrides this hook (for example, to supply router_loss_div_factor) and is configured with pipeline parallelism, train_batch only computes and forwards the kwargs in the non-PP branch. The PP branch calls run_pipeline(..., **model_kwargs) without them, and the PP eval branch similarly drops them, so routed-expert auxiliary losses use the ordinary loss divisor rather than the wrapper's intended whole-batch divisor.

Useful? React with 👍 / 👎.

if name.endswith((".q_norm.weight", ".k_norm.weight")) and param.ndim == 2
}
expansions = prepare_qk_expansion(sd_to_load, metadata, gain_shapes)
sd_to_load = self._optimizer_state_dict_for_load(sd_to_load, checkpoint_keys)

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 Adapt optimizer keys before Q/K expansion

When a subclass uses the new adapter to rename optimizer keys for a legacy checkpoint and enables expand_shared_qk_norm_on_load, the expansion runs before the adapter changes the state-dict keys. prepare_qk_expansion therefore cannot find the legacy checkpoint metadata for the current Q/K keys; after the rename, the checkpoint loader is asked to load the old shared vector into the full per-head destination and fails on the shape mismatch. Run the key adaptation (and map the gain-shape names) before preparing the expansion.

Useful? React with 👍 / 👎.

@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: 299e4429ce

ℹ️ 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".

# this with explicit dtype ownership so FP8 state, optimizer main params,
# and normal model params are not coupled to a blanket module cast.
self.to(self._training_dtype)
module.to(self._training_dtype)

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 Avoid casting root-wrapper weights without matching image inputs

When root_module is the intended multimodal wrapper, this converts its vision encoder and connector from their configured FP32 weights to BF16 as well as converting the LM. OLMoDDPTrainModule deliberately uses no autocast, while MultimodalLM.forward only moves images to the device and the repository's multimodal collator produces FP32 image tensors. A batch containing images therefore reaches the first vision Linear with FP32 activations and BF16 weights and fails with a dtype-mismatch error. Cast the image inputs (or use autocast), or limit this conversion to the OLMo model rather than the complete root module.

Useful? React with 👍 / 👎.

@jason718
jason718 force-pushed the jasonr/native-olmo-ddp-runtime-on-vision branch from 299e442 to 2cc6777 Compare October 2, 2026 07:13
jason718 added a commit that referenced this pull request Oct 2, 2026
A MultimodalLM around an OLMoDDPModel that opts into OLMoDDPTrainModule through the #886
hooks: embeddings go in through `input_embeddings`, router auxiliary losses get their own
divisor, apply_dp wraps the whole model, and the weighted response-only loss (plus the LM's
z-loss) is computed from the response logits. Text-only batches defer to the LM's plain loss.
For recurrent LMs (Kimi Delta Attention) packed examples are isolated through document
boundaries derived from example_ids instead of attention masks; pixels are cast to the vision
tower's dtype. The router token mask of #868 is not carried (documented).
jason718 added a commit that referenced this pull request Oct 2, 2026
The train module uses the #886 hooks for per-batch auxiliary-loss divisors, native-text
checkpoint key aliasing, frozen-parameter save/restore, fresh-component deferral on
masters-only loads and Q/K-gain expansion; frozen expert weights under expert parallelism are
not supported (the recipe runs EP1). Callbacks: component initialization (SigLIP tower,
image-token rows), W&B auto-resume, Beaker config on resumed runs, metric overwrite,
evaluator dedupe, permanent-checkpoint retention, and the multimodal evaluator config.
@jason718
jason718 changed the base branch from vision to jasonr/multimodal-data-infra October 2, 2026 07:13
@jason718
jason718 force-pushed the jasonr/multimodal-data-infra branch from 4dcf8c7 to ccce7bb Compare October 2, 2026 17:55
@jason718
jason718 force-pushed the jasonr/native-olmo-ddp-runtime-on-vision branch from 2cc6777 to eae829e Compare October 2, 2026 17:55
jason718 added a commit that referenced this pull request Oct 2, 2026
A MultimodalLM around an OLMoDDPModel that opts into OLMoDDPTrainModule through the #886
hooks: embeddings go in through `input_embeddings`, router auxiliary losses get their own
divisor, apply_dp wraps the whole model, and the weighted response-only loss (plus the LM's
z-loss) is computed from the response logits. Text-only batches defer to the LM's plain loss.
For recurrent LMs (Kimi Delta Attention) packed examples are isolated through document
boundaries derived from example_ids instead of attention masks; pixels are cast to the vision
tower's dtype. The router token mask of #868 is not carried (documented).
jason718 added a commit that referenced this pull request Oct 2, 2026
The train module uses the #886 hooks for per-batch auxiliary-loss divisors, native-text
checkpoint key aliasing, frozen-parameter save/restore, fresh-component deferral on
masters-only loads and Q/K-gain expansion; frozen expert weights under expert parallelism are
not supported (the recipe runs EP1). Callbacks: component initialization (SigLIP tower,
image-token rows), W&B auto-resume, Beaker config on resumed runs, metric overwrite,
evaluator dedupe, permanent-checkpoint retention, and the multimodal evaluator config.

@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: eae829e09f

ℹ️ 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".

z_loss_multiplier: Optional[float] = None,
loss_div_factor: Optional[Union[torch.Tensor, float]] = None,
return_logits: Optional[bool] = None,
input_embeddings: Optional[torch.Tensor] = None,

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 Forward multimodal masks through the DDP model

When the new input_embeddings path is used by MultimodalLM, its or_mask, and_mask, flex_attn_block_mask, position_ids, and drop_mask are passed to this method as **kwargs. _prepare_inputs() does not consume those keys, and this forward never adds them to all_block_kwargs as Transformer.forward() does, so they are silently discarded. Image-token bidirectional attention, packed-example isolation, custom RoPE positions, and response dropout therefore run as ordinary causal/default attention in DDP multimodal training.

Useful? React with 👍 / 👎.

@jason718
jason718 force-pushed the jasonr/multimodal-data-infra branch from ccce7bb to 0075fa4 Compare October 2, 2026 22:12
@jason718
jason718 force-pushed the jasonr/native-olmo-ddp-runtime-on-vision branch from eae829e to df9e404 Compare October 2, 2026 22:12
jason718 added a commit that referenced this pull request Oct 2, 2026
A MultimodalLM around an OLMoDDPModel that opts into OLMoDDPTrainModule through the #886
hooks: embeddings go in through `input_embeddings`, router auxiliary losses get their own
divisor, apply_dp wraps the whole model, and the weighted response-only loss (plus the LM's
z-loss) is computed from the response logits. Text-only batches defer to the LM's plain loss.
For recurrent LMs (Kimi Delta Attention) packed examples are isolated through document
boundaries derived from example_ids instead of attention masks; pixels are cast to the vision
tower's dtype. The router token mask of #868 is not carried (documented).
jason718 added a commit that referenced this pull request Oct 2, 2026
The train module uses the #886 hooks for per-batch auxiliary-loss divisors, native-text
checkpoint key aliasing, frozen-parameter save/restore, fresh-component deferral on
masters-only loads and Q/K-gain expansion; frozen expert weights under expert parallelism are
not supported (the recipe runs EP1). Callbacks: component initialization (SigLIP tower,
image-token rows), W&B auto-resume, Beaker config on resumed runs, metric overwrite,
evaluator dedupe, permanent-checkpoint retention, and the multimodal evaluator config.

@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: df9e40497b

ℹ️ 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 822 to 824
ddp_model = MultiGroupDistributedDataParallel(
module=self,
module=module,
dim=0, # for scatter/gather

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 LM lifecycle hooks when wrapping the root module

When root_module is a multimodal wrapper, this makes the returned MultiGroupDistributedDataParallel forward missing attributes to the wrapper rather than the nested OLMoDDPModel. OLMoDDPTrainModule subsequently calls lifecycle methods such as post_batch, compute_auxiliary_metrics, post_optim_step, and refresh_rowwise_fp8_cache on each model part; MultimodalLM does not expose those methods (they exist on lm), so the intended root-wrapper path fails during initialization or its first training batch. Keep the model part's lifecycle interface bound to the nested LM, or proxy those methods through the root wrapper.

Useful? React with 👍 / 👎.

@jason718
jason718 force-pushed the jasonr/multimodal-data-infra branch from 0075fa4 to 956d17b Compare October 3, 2026 03:28
@jason718
jason718 force-pushed the jasonr/native-olmo-ddp-runtime-on-vision branch from df9e404 to 5b6775e Compare October 3, 2026 03:28
jason718 added a commit that referenced this pull request Oct 3, 2026
A MultimodalLM around an OLMoDDPModel that opts into OLMoDDPTrainModule through the #886
hooks: embeddings go in through `input_embeddings`, router auxiliary losses get their own
divisor, apply_dp wraps the whole model, and the weighted response-only loss (plus the LM's
z-loss) is computed from the response logits. Text-only batches defer to the LM's plain loss.
For recurrent LMs (Kimi Delta Attention) packed examples are isolated through document
boundaries derived from example_ids instead of attention masks; pixels are cast to the vision
tower's dtype. The router token mask of #868 is not carried (documented).
jason718 added a commit that referenced this pull request Oct 3, 2026
The train module uses the #886 hooks for per-batch auxiliary-loss divisors, native-text
checkpoint key aliasing, frozen-parameter save/restore, fresh-component deferral on
masters-only loads and Q/K-gain expansion; frozen expert weights under expert parallelism are
not supported (the recipe runs EP1). Callbacks: component initialization (SigLIP tower,
image-token rows), W&B auto-resume, Beaker config on resumed runs, metric overwrite,
evaluator dedupe, permanent-checkpoint retention, and the multimodal evaluator config.
Base automatically changed from jasonr/multimodal-data-infra to vision October 5, 2026 18:17
@jason718
jason718 force-pushed the jasonr/native-olmo-ddp-runtime-on-vision branch from 5b6775e to cedefb4 Compare October 5, 2026 18:26
jason718 added a commit that referenced this pull request Oct 5, 2026
A MultimodalLM around an OLMoDDPModel that opts into OLMoDDPTrainModule through the #886
hooks: embeddings go in through `input_embeddings`, router auxiliary losses get their own
divisor, apply_dp wraps the whole model, and the weighted response-only loss (plus the LM's
z-loss) is computed from the response logits. Text-only batches defer to the LM's plain loss.
For recurrent LMs (Kimi Delta Attention) packed examples are isolated through document
boundaries derived from example_ids instead of attention masks; pixels are cast to the vision
tower's dtype. The router token mask of #868 is not carried (documented).
jason718 added a commit that referenced this pull request Oct 5, 2026
The train module uses the #886 hooks for per-batch auxiliary-loss divisors, native-text
checkpoint key aliasing, frozen-parameter save/restore, fresh-component deferral on
masters-only loads and Q/K-gain expansion; frozen expert weights under expert parallelism are
not supported (the recipe runs EP1). Callbacks: component initialization (SigLIP tower,
image-token rows), W&B auto-resume, Beaker config on resumed runs, metric overwrite,
evaluator dedupe, permanent-checkpoint retention, and the multimodal evaluator config.
@jason718
jason718 force-pushed the jasonr/native-olmo-ddp-runtime-on-vision branch from cedefb4 to 8d8fa9b Compare October 5, 2026 19:44
jason718 added a commit that referenced this pull request Oct 5, 2026
A MultimodalLM around an OLMoDDPModel that opts into OLMoDDPTrainModule through the #886
hooks: embeddings go in through `input_embeddings`, router auxiliary losses get their own
divisor, apply_dp wraps the whole model, and the weighted response-only loss (plus the LM's
z-loss) is computed from the response logits. Text-only batches defer to the LM's plain loss.
For recurrent LMs (Kimi Delta Attention) packed examples are isolated through document
boundaries derived from example_ids instead of attention masks; pixels are cast to the vision
tower's dtype. The router token mask of #868 is not carried (documented).
jason718 added a commit that referenced this pull request Oct 5, 2026
The train module uses the #886 hooks for per-batch auxiliary-loss divisors, native-text
checkpoint key aliasing, frozen-parameter save/restore, fresh-component deferral on
masters-only loads and Q/K-gain expansion; frozen expert weights under expert parallelism are
not supported (the recipe runs EP1). Callbacks: component initialization (SigLIP tower,
image-token rows), W&B auto-resume, Beaker config on resumed runs, metric overwrite,
evaluator dedupe, permanent-checkpoint retention, and the multimodal evaluator config.
@jason718 jason718 changed the title Add the OLMoDDP hooks a multimodal wrapper needs, inert by default (replaces the #868 copy) Add the OLMoDDP hooks a multimodal wrapper needs, inert by default Oct 5, 2026
@jason718
jason718 merged commit 181eaf3 into vision Oct 5, 2026
1 check passed
@jason718
jason718 deleted the jasonr/native-olmo-ddp-runtime-on-vision branch October 5, 2026 19:44
jason718 added a commit that referenced this pull request Oct 5, 2026
A MultimodalLM around an OLMoDDPModel that opts into OLMoDDPTrainModule through the #886
hooks: embeddings go in through `input_embeddings`, router auxiliary losses get their own
divisor, apply_dp wraps the whole model, and the weighted response-only loss (plus the LM's
z-loss) is computed from the response logits. Text-only batches defer to the LM's plain loss.
For recurrent LMs (Kimi Delta Attention) packed examples are isolated through document
boundaries derived from example_ids instead of attention masks; pixels are cast to the vision
tower's dtype. The router token mask of #868 is not carried (documented).
jason718 added a commit that referenced this pull request Oct 5, 2026
The train module uses the #886 hooks for per-batch auxiliary-loss divisors, native-text
checkpoint key aliasing, frozen-parameter save/restore, fresh-component deferral on
masters-only loads and Q/K-gain expansion; frozen expert weights under expert parallelism are
not supported (the recipe runs EP1). Callbacks: component initialization (SigLIP tower,
image-token rows), W&B auto-resume, Beaker config on resumed runs, metric overwrite,
evaluator dedupe, permanent-checkpoint retention, and the multimodal evaluator config.
jason718 added a commit that referenced this pull request Oct 21, 2026
…ing (#910)

## Summary

PR 1 of 4 for moving the Molmo2 stage-1 reproduction from the long-lived
`vision` branch onto `main` in reviewable pieces (follows `[1/n]` #692).
This one is the **model side only**: no data pipeline, no train module,
no scripts. Everything is opt-in; existing `Transformer` / `OLMo`
configs behave exactly as before.

## What is in this PR, how each piece is used, and why it has to be here

### 1. HF Molmo2 loader (`nn/vision/molmo2_loader.py`)
- **What:** converts a released HuggingFace Molmo2 checkpoint (4B / 8B)
into a `MultimodalLM` state dict (fused QKV and gated-MLP splitting, the
base/extra embedding split, the patch-embedding flatten order), and
derives a `MultimodalLMConfig` from an HF config
(`molmo2_config_from_hf_config`).
- **How it is used:** (a) **correctness oracle**: every parity and
generation test loads the released weights through it and compares
against the HF reference model, which is the only way to *prove* our
architecture is Molmo2 and not merely Molmo2-shaped; (b)
`MultimodalLMConfig.molmo2_4B()/molmo2_8B()`, the factories stage 1
trains from, are asserted equal to the HF-derived config
(`molmo2_native_config_test`), so a launch needs no HF access; (c)
`Molmo2-Stage1.py --init_from=molmo2` (continue from the released
checkpoint) goes through the converter.
- **Why here:** the model is only trustworthy once it matches HF
numerically; landing the model without the thing that verifies it would
leave #911-#913 building on unverified code.

### 2. FlexAttention backend (`nn/attention/backend.py`, plus the dense
`or_mask` / `and_mask` path)
- **What:** an attention backend that expresses Molmo2's mask (causal,
image tokens attending bidirectionally to each other, and isolation
between the branches/examples packed into one sequence) as a fused
kernel built from per-token vectors, instead of materialising a `(B, 1,
S, S)` boolean mask.
- **How it is used:** stage 1 packs several annotations per image into
one sequence, so every training step needs this mask. `Molmo2-Stage1.py`
sets `USE_FLEX_ATTN = True` (about +8% MFU over the dense `torch`
backend, per the script). The dense masks stay as the CPU / inference
path and as the oracle: `flex_backend_test` checks flex against dense
for causal / or / and / both, MHA and GQA, and
`test_packed_examples_are_isolated` checks packed examples don't leak
into each other (dense and flex).
- **Why here:** the mask semantics are part of the model definition (HF
Molmo2 attends bidirectionally over image tokens; getting this wrong
silently changes logits, see the bidirectional-vs-causal parity numbers
below), and `MultimodalLM.forward` is where the mask gets built.

### 3. Split-vocab embedding (`nn/embedding.py`,
`TransformerConfig.n_extra_vocab`)
- **What:** an embedding table split into a base block and a small
"extra" block (Molmo2's 128 image-special tokens) held as two
parameters, with an LM head that spans only the base vocab and can be
tied to the base block.
- **How it is used:** HF Molmo2 stores `wte.embedding` and
`wte.new_embedding` separately, so the loader maps them one-to-one onto
`embeddings.weight` / `embeddings.extra_weight`. Stage 1 sets
`freeze_base_embeddings=True`: it keeps the pretrained vocabulary fixed
while learning the new image tokens. With one fused table that is a
partial-row freeze, which `requires_grad` cannot express; with the split
it is `embeddings.weight.requires_grad_(False)`. It also gives the head
the base width structurally (extra tokens are inputs, never targets),
which replaced an earlier logit-masking mechanism that I deleted as dead
code in this PR.
- **Why here:** it changes the model's parameter layout, and the loader
(above) and every checkpoint conversion depend on that layout, so it
cannot come later without re-doing the loader.

### Smaller opt-in pieces the model needs
`response_logits_only` (compute logits only at response positions, used
by the train module to save memory), `masked_dropout` (Molmo2's
`response_residual_dropout`: 10% residual dropout on response tokens
only), `RoPE position_ids` (packed branches share an overlapping
position range), and ViT / connector activation checkpointing and
compile hooks.

## Why this PR is fundamental

Everything else in the series imports from it, so it must land first:

| PR | What it takes from this one |
|---|---|
| #911 train module | wraps `MultimodalLM`; calls
`response_logits_only`, `masked_dropout`, the flex backend, the ViT /
connector AC and compile hooks |
| #912 data core | special-token ids (`molmo2_tokens`) and the sequence
layout (`position_ids`, sub-segments, image-token spans) that
`MultimodalLM.forward` consumes |
| #913 stage-1 recipe | `MultimodalLMConfig.molmo2_4B/8B`,
`n_extra_vocab` + `freeze_base_embeddings`, the loader for
`--init_from=molmo2` |

It also defines the numerical contract (parity with released Molmo2)
that the later PRs are checked against, and it is the only PR whose
correctness can be validated without data or a trainer. It is safe to
merge first: all defaults are unchanged and text-side behaviour is
bit-identical to `main` (see below).

## Series: all PRs

Linear stack. Each PR is cut fresh from `main` (not cherry-picked from
`vision`), so every diff shows only its own change; the base is
retargeted to `main` as parents land.

| # | PR | Contents | Touches |
|---|---|---|---|
| 1/4 | #910 Model **← this PR** | Molmo2 HF loader, image processor,
flex attention, split-vocab embedding, `MultimodalLM` extensions | `nn/`
|
| 2/4 | #911 Train infrastructure | `MultimodalTransformerTrainModule`,
`PerGroupScheduler`, weighted CE, unsharded-export callback | `train/`,
`optim/`, `nn/functional`, `distributed/` |
| 3/4 | #912 Data core | sequence builder / branch packing, collator,
mixture loader, SFT formatter, PixMo-Cap | `data/multimodal` (core) |
| 4/4 | #913 Stage-1 recipe | stage-1 datasets, mixtures,
`Molmo2-Stage1.py` | `data/multimodal` (datasets), `scripts/` |

**Not yet opened (planned follow-ups):**
- *AC-RNG follow-up*: make activation-checkpoint RNG replay cover
`ResidualStream.masked_dropout`. It has to sit on top of #906, which
rewrites the same lines, so it waits for #906.
- *Stage 2* (`Molmo2-Stage2.py`, the `image_only_v9` mixture,
multi-image datasets, `compare_sft_example.py`): stays on `vision` until
this series lands, then follows as its own PR(s).
- *Alignment / OLMoDDP multimodal layers* (#886, #889, #902, #903,
currently targeting `vision`): rebased on top once `vision` is synced to
`main`.

## Does this change anything on `main` / the text side?

No intended text-side change. What was checked:

- **Diff audit of every pre-existing file the series modifies**
(`nn/transformer/{model,block,config}`, `nn/attention`, `nn/lm_head`,
`nn/residual_stream`, `nn/rope`, `nn/ddp/block`,
`train/callbacks/speed_monitor`, `optim`, `distributed`). All remaining
edits add optional arguments that default to the old behaviour
(`masked_dropout=0`, `n_extra_vocab=0`, `response_logits_only=False`,
`position_ids=None`, `or_mask/and_mask=None`, ...). The audit also found
two edits that *did* alter text behaviour; both were removed from the
series: a reroute of FSDP2 gradient clipping in `TransformerTrainModule`
(text FSDP2 models would have left the torchtitan path), and new
"examples per second" metrics in `SpeedMonitorCallback` on text runs
(now emitted only for batches carrying `example_ids`).
- **Bit-for-bit comparison, `main` vs the series tip**, same seeds, CPU:
`state_dict` keys and values, eval logits, loss, and every parameter
gradient are identical (SHA-256 over the bytes) for `olmo2_1M` in eval,
train, and train with `dropout=0.1`, and for a qwen3-style `llama_like`
model with `qk_norm`.
- **Existing (non-multimodal) test suites, run on `main` and on the tip
of this series** (`src/test/{nn,train,optim,data,distributed}`, CPU):
`main` 1175 passed / 8 failed; series tip 1204 passed / 8 failed. The 8
failures are identical on both and are environment issues (S3/network:
`mixes_test` x3, S3 checkpoint tests x4; and
`test_logprobs_match_after_roundtrip[gemma3]`). Nothing that passed on
`main` fails on the series.
- `mypy src/` (CI config, `<1.4`), ruff, black, isort all clean.
- **Not covered:** text GPU/distributed paths (FSDP2, TP, CP, flash
kernels) can't run on a CPU box. The GPU smoke below exercises FSDP2 on
the multimodal path only, so text-side GPU CI remains the gap.

## Left out on purpose

- Activation-checkpoint RNG replay for `masked_dropout` (`ac_rng_test`,
`_dropout_is_active`). It touches the same lines as #906, which fixes
the general case. I'll send a small follow-up on top of #906 so
`ResidualStream.masked_dropout` also counts. Until then `masked_dropout`
is inert by default but not AC-safe.
- Two tests that need the data package
(`test_packed_examples_are_isolated`,
`molmo2_training_logits_parity_test`) move to PR 3.

## Testing

**CPU:** `src/test/nn/vision`, `flex_backend_test`, `embedding_test`,
`lm_head_test`, `residual_stream_test`: pass (the one failure,
`parity_test::test_clip_parity`, is this dev box's `transformers`
version; it passes on the Beaker image). `mypy src/` (CI config), ruff,
black, isort clean.

**GPU logit parity vs HF Molmo2 (Beaker, 1 GPU, bf16, 146 passed / 5
skipped / 0 failed):** max |diff| vs the HF reference. Two runs on
different hardware:
[A100](https://beaker.org/ex/01M47FK4ES7M0QY3BA2HDSS9TG) (on
`987a5dbeb`, before the last trims) and
[B300](https://beaker.org/ex/01M48RE6ZHWSD6CKGK216EVPA4) (on
`3dd8281e4`, the current tip of #913). bf16 kernels differ across
hardware, so the diffs move a little; the two A100-era runs agree to
every printed digit with each other, i.e. the trims did not change
numerics.

| check | 4B (A100 / B300) | 8B (A100 / B300) |
|---|---|---|
| token embedding | 0.0 / 0.0 | 0.0 / 0.0 |
| LM-only last-token logits | 0.203 / 0.188 | 0.250 / 0.250 |
| full pipeline (ViT + connector + splice + LM) logits | 0.156 / 0.156 |
0.188 / 0.375 |
| vision tower layers 18 and 24 | 1.5e-3 / 2.3e-3 | 4.9e-4 / 8.5e-4 |

Argmax matches HF in every case; the weighted training loss and
all-response logits match for both models; bidirectional image attention
matches HF (0.25 vs 1.3 if left causal, i.e. the mask matters and is
correct). Also passing on GPU: generation parity, FlexAttention vs dense
masks, packed-example isolation, the multimodal train module.
**Skipped: Molmo2-O-7B** (all 5 variants): per-layer YaRN attention
scaling is not implemented in `MultimodalLM` (known, deferred), so O-7B
is *not* verified by this series.

**GPU training smoke (8x GPU, FSDP2)** on the tip of #913:
[`mm-trim2-gpu-smoke`](https://beaker.org/ex/01M48RF37WG2Y6HWK05T7XKY5C)
(B300): 30 steps of `Molmo2-Stage1.py`, CE 3.23 -> 2.57, grad norm 24.2
-> 7.7, checkpoint and unsharded export written. Earlier runs of
previous commits (A100-class nodes) went 3.24 -> 2.61.
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