Skip to content

[Multimodal 1/4] HF Molmo2 loader, flex attention, split-vocab embedding - #910

Merged
jason718 merged 10 commits into
mainfrom
jasonr/molmo2-model-loader
Oct 21, 2026
Merged

jason718 merged 10 commits into
mainfrom
jasonr/molmo2-model-loader

Conversation

@jason718

@jason718 jason718 commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

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 [Multimodal 2/4] Multimodal train module, PerGroupScheduler, weighted CE #911-[Multimodal 4/7] Stage-1 recipe: datasets, mixtures, and Molmo2-Stage1.py #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):

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

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 (on 987a5dbeb, before the last trims) and B300 (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 (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.

🤖 Generated with Claude Code

…ab embedding

Model-side half of the Molmo2 stage-1 reproduction, split out of the `vision`
branch ([2/n] after #692):

- nn/vision: Molmo2 HF checkpoint loader, image processor, special tokens, and
  MultimodalLM changes (bidirectional image-token attention, explicit RoPE
  position_ids, sub-segment attention isolation).
- nn/attention: FlexAttention backend with or-mask / sub-segment masks.
- nn: SplitVocabEmbedding + TransformerConfig.n_extra_vocab, LMHead
  response_logits_only, ResidualStream masked_dropout, RoPE position_ids.
- distributed/utils: reduce_distributed_failure_flag.
- Logit-parity, generation and unit tests.

Activation-checkpoint RNG handling for masked_dropout is intentionally left to
a follow-up on top of #906.
@jason718 jason718 self-assigned this Oct 5, 2026
@jason718 jason718 changed the title [Molmo2 1/4] Native Molmo2 model: HF loader, flex attention, split-vocab embedding [Multimodal 1/4] Native multimodal model: HF loader, flex attention, split-vocab embedding Oct 5, 2026
@jason718 jason718 changed the title [Multimodal 1/4] Native multimodal model: HF loader, flex attention, split-vocab embedding [Multimodal 1/4] Multimodal model support: HF Molmo2 loader, flex attention, split-vocab embedding Oct 6, 2026
…age preprocessor to the data PR, share HF-load test helpers
@jason718 jason718 changed the title [Multimodal 1/4] Multimodal model support: HF Molmo2 loader, flex attention, split-vocab embedding [Multimodal 1/4] Multimodal support: HF Molmo2 loader, flex attention, split-vocab embedding Oct 6, 2026
@jason718
jason718 marked this pull request as ready for review October 6, 2026 14:28
@jason718 jason718 changed the title [Multimodal 1/4] Multimodal support: HF Molmo2 loader, flex attention, split-vocab embedding [Multimodal 1/4] HF Molmo2 loader, flex attention, split-vocab embedding Oct 6, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-20T06:23:23.654497Z 88be43e New commits
ℹ️ 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 requested a review from AkshitaB October 6, 2026 14:33

@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: 310f6b31b8

ℹ️ 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/nn/rope.py
Comment on lines +580 to +581
pos_idx = position_ids.to(torch.long)
sin_sel = pos_sin.index_select(0, pos_idx.reshape(-1)).view(*pos_idx.shape, -1)

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 Size RoPE buffers from explicit positions

When position_ids contain absolute offsets larger than the current sequence length (for example, processing a chunk with positions [1024, 1025]), the buffer above is only generated to k_len, so this index_select raises an out-of-range error. Size the generated RoPE cache from position_ids.max() + 1 (and validate supplied buffers) before gathering.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Not changing this. position_ids here are within-example positions (packed branches start at 0 and overlap), so they are always below the sequence length, and the code comment states the constraint. Sizing the cache from position_ids.max() would force a host sync on every forward. If you'd rather have a friendlier error than an index error for out-of-contract inputs, I can add a validation in a debug path.

Comment thread src/olmo_core/nn/vision/multimodal.py Outdated

# Compute LM token embeddings with any configured scale / norm.
h = self.lm.embeddings(input_ids)
use_flex_attn = os.environ.get("OLMO2_FLEX_ATTN") == "1"

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 Select Flex masking from the actual LM backend

If OLMO2_FLEX_ATTN=1 is set while this model's LM is configured with the torch backend (or Flex falls back to torch on a CPU-only host), this branch suppresses the dense or_mask/and_mask construction below and passes only a Flex BlockMask, which the torch backend never receives. Image tokens then attend causally and packed branches are not isolated, silently changing multimodal results; derive this choice from the instantiated attention backend or fall back to dense masks.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 09c0b1a. Mask construction now follows the LM's actual attention backend (any block backed by FlexAttentionBackend) instead of reading OLMO2_FLEX_ATTN, so a torch-backend model always gets the dense or_mask/and_mask. Added test_masks_follow_the_actual_backend_not_the_environment, run with the env var set and unset.

Comment thread src/olmo_core/nn/vision/multimodal.py Outdated
Comment on lines +455 to +461
if self.training and self._masked_residual_dropout > 0.0:
if loss_masks is None:
raise ValueError(
"`loss_masks` is required when the LM uses `masked_dropout` "
"(response_residual_dropout)"
)
drop_mask = (loss_masks > 0).to(dtype=torch.bool)

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 Move the residual-dropout mask to the model device

During training with masked_dropout, callers may provide the usual CPU loss_masks while the model moves input_ids to CUDA internally. This creates a CPU drop_mask; unlike the other masks, Transformer.forward forwards it unchanged, and ResidualStream._masked_dropout then combines it with CUDA activations, causing a device-mismatch error. Move this mask to device before passing it to the LM.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 09c0b1a: drop_mask is now moved to the model device together with input_ids.

Comment on lines +75 to +78
flat_mask = response_mask.view(-1)
h = h.view(-1, h.shape[-1])[flat_mask]
if labels is not None:
labels = labels.view(-1)[flat_mask]

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 Preserve batch structure for unreduced response losses

With response_logits_only=True and loss_reduction="none", this compacts all selected positions across the batch, but _finalize_loss() still reshapes the resulting loss to (B, -1). Unequal response-token counts per example—which is normal for packed or variable-length responses—therefore either raise a reshape error or assign losses to the wrong example when the total happens to be divisible by B.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 09c0b1a, by rejecting the combination: with response_logits_only=True and loss_reduction="none" both heads now raise a ValueError explaining that the selected positions are flattened across the batch, so no (B, S) layout exists. Nothing needs the unreduced form (the train module computes its weighted loss outside the head). Test added for both head types.

@AkshitaB AkshitaB 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.

Found three issues at commit 310f6b31b87d63df861806a851d530175fae2fac:

  1. [P1] Backend/environment mismatch silently drops attention masks — multimodal.py:472. With OLMO2_FLEX_ATTN=1 and a configured torch backend, the model creates only a Flex block mask, which that backend ignores. Packed-example isolation and bidirectional image attention disappear silently. Reproduced on a tiny multimodal model: supplying example_ids produces exactly the unmasked logits when the environment variable is set; without it, the isolation mask changes the logits. Select mask construction from the actual backend, or reject incompatible settings.

  2. [P2] Response-only logits break unreduced loss — lm_head.py:75–78. Selection flattens responses across examples, but _finalize_loss() still reshapes losses to (B, -1). With two examples selecting three tokens total, response_logits_only=True and loss_reduction="none" raise RuntimeError: shape '[2, -1]' is invalid for input of size 3. Even divisible totals can misrepresent example boundaries. Preserve the selected-token layout when finalizing losses.

  3. [P2] Forced vision kernels regress CPU training with attention dropout — sdpa.py:14. Disabling the math backend unconditionally makes existing vision configurations with nonzero attention_dropout fail on CPU. Reproduced with CPU tensors of shape (1, 2, 4, 8) and dropout_p=0.1: ordinary SDPA succeeds; the new wrapper raises RuntimeError: No available kernel. Aborting execution. Retain a fallback for unsupported devices/configurations.

Validation: 39 focused tests passed across embedding_test.py, residual_stream_test.py, flex_backend_test.py, and multimodal_test.py. All three issues were reproduced separately on CPU with PyTorch 2.10.0. GPU/distributed behavior was not tested.

… unreduced loss with response_logits_only, keep default SDPA kernels off CUDA, move drop_mask to device; fix response-only loss test reference

@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: 09c0b1a626

ℹ️ 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 +134 to +138
self.embeddings: nn.Module
if n_extra_vocab > 0:
self.embeddings = SplitVocabEmbedding(
vocab_size, n_extra_vocab, d_model, dtype=dtype, device=init_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 Add a tensor-parallel plan for split embeddings

When n_extra_vocab > 0 and Transformer.apply_tp() is called, this custom module is passed directly to RowwiseParallel. PyTorch's implementation only accepts nn.Linear or nn.Embedding and raises NotImplementedError for other module types, while SplitVocabEmbedding subclasses only nn.Module; consequently the new Molmo configurations cannot be tensor-parallelized. Provide a custom plan that shards both vocabulary parameters, or make apply_tp() handle this module separately. PyTorch's RowwiseParallel implementation

Useful? React with 👍 / 👎.

Comment on lines +485 to +486
if response_mask is not None:
response_mask = move_to_device(response_mask, self.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 Shard the response mask with context-parallel inputs

When context parallelism is active and response_logits_only=True, _prepare_inputs() shards input_ids, labels, and the resulting hidden sequence, but this newly added response_mask is only moved to the device and remains at the original (B, S) size. _select_hidden_for_logits() then indexes a local (B, S/CP, D) hidden tensor with a full-length flattened mask, causing a shape error (or incompatible DTensor operation) before the LM projection. The response mask needs to go through the same CP load-balancer transformation as labels, or this combination should be rejected explicitly.

Useful? React with 👍 / 👎.

Comment thread src/olmo_core/nn/vision/multimodal.py Outdated
Comment on lines +478 to +480
use_flex_attn = any(
isinstance(getattr(m, "backend", None), FlexAttentionBackend) for m in self.lm.modules()
)

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 Preserve masks for mixed attention backends

When a transformer uses block overrides with both FlexAttention and torch attention, any(...) selects the flex-only path for the entire model. This prevents construction of or_mask and and_mask; the prebuilt flex mask is consumed only by FlexAttention blocks, so every torch-backed block silently falls back to plain causal attention and loses image bidirectionality and example/subsegment isolation. Mask representation needs to be selected per block/backend, or heterogeneous backends must be rejected.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 88be43e, thanks. MultimodalLM.forward now raises OLMoConfigurationError when FlexAttention is mixed with any other backend across blocks (the flex block mask and the dense or/and masks are mutually exclusive, so non-flex blocks would lose isolation and image bidirectionality). Test added: test_mixed_flex_and_torch_backends_are_rejected. I chose rejecting over building both mask types since no config in this series mixes backends.

…ernel, no logits comparison for fused_linear

@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

if images is not None:

P1 Badge Run vision collectives on every distributed rank

When distributed ranks receive different local modalities, a rank with images=None skips this branch while an image-bearing rank enters _encode_images()'s all_reduce and the later barrier; meanwhile the text-only rank proceeds to the LM's FSDP collectives. Because the public API explicitly permits images=None, a mixed text/image step can hang or fail with mismatched collectives unless every rank is forced to participate or the model explicitly requires synchronized dummy image inputs.

ℹ️ 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 +383 to +390
if microbatch <= 0 or T <= microbatch:
features = self._vit_forward_features(images.reshape(B * T, N, -1))
features = features.reshape(B, T * features.shape[1], features.shape[-1])
else:
parts: List[torch.Tensor] = []
for start in range(0, T, microbatch):
end = min(start + microbatch, T)
chunk = images[:, start:end].reshape(B * (end - start), N, -1)

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 Enforce the crop limit across the flattened batch

When B > 1, VIT_CROP_MICROBATCH does not actually bound the number of crops passed to a ViT forward: each chunk contains B * (end - start) crops, and the no-chunk path passes B * T. Thus a configured limit of 16 can still process 32, 64, or more crops at once and defeat the memory-control mechanism, potentially causing the OOM it is intended to prevent; chunk the flattened B * T crop axis instead.

Useful? React with 👍 / 👎.

Comment on lines +75 to +78
flat_mask = response_mask.view(-1)
h = h.view(-1, h.shape[-1])[flat_mask]
if labels is not None:
labels = labels.view(-1)[flat_mask]

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 Shard response masks with tensor-parallel LM heads

With tensor parallelism and response_logits_only=True, LMHead.apply_tp() shards labels and, depending on the head, the sequence dimension of h, but it does not include response_mask in PrepareModuleInput. The full (B, S) mask is therefore flattened here and used against a local (B, S/TP, ...) tensor (or against locally sharded labels), causing a boolean-index shape error during TP training; shard the mask alongside labels before selection or reject this combination.

Useful? React with 👍 / 👎.

Comment on lines +573 to +575
flex_attn_block_mask = FlexAttentionBackend.build_block_mask_from_vectors(
**flex_mask_kwargs
)

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 Preserve sliding windows in prebuilt Flex masks

For a multimodal LM whose FlexAttention blocks use sliding-window attention, this prebuilt mask is always created with the helper's default window_size=(-1, -1) and then reused verbatim by every block. FlexAttentionBackend.forward() bypasses its own per-block self.window_size whenever this mask is supplied, so text tokens silently receive full causal context instead of the configured window; build masks per distinct window or avoid the prebuilt-mask path for sliding-window models.

Useful? React with 👍 / 👎.

Comment on lines +135 to +138
if n_extra_vocab > 0:
self.embeddings = SplitVocabEmbedding(
vocab_size, n_extra_vocab, d_model, dtype=dtype, device=init_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.

P2 Badge Include extra vocabulary rows in parameter accounting

When n_extra_vocab > 0, this allocates n_extra_vocab * d_model additional parameters, but TransformerConfig.num_params and num_active_params still account for only vocab_size * d_model. Model-size estimates therefore underreport every split-vocabulary model, while the runtime num_non_embedding_params also misclassifies the extra table because it subtracts only embeddings.weight; update the accounting helpers to treat both embedding blocks consistently.

Useful? React with 👍 / 👎.

@jason718

Copy link
Copy Markdown
Contributor Author

@AkshitaB thanks, all three were real and are fixed in 09c0b1a (with test fixes in b6f0895 and 8b09bc1):

  1. Backend/env mismatch: mask representation now follows the LM's actual attention backend, not OLMO2_FLEX_ATTN. Regression test runs with the env var both set and unset on a torch-backend model.
  2. Response-only logits + unreduced loss: both LM heads now raise a clear ValueError for response_logits_only=True with loss_reduction="none"; test added.
  3. Vision SDPA on CPU with dropout: the flash/efficient restriction now applies only to CUDA tensors; CPU keeps PyTorch's default kernel selection. Test added with your repro shape ((1, 2, 4, 8), dropout_p=0.1).

While fixing these I also found that test_lm_head_response_logits_only was wrong for the fused variant (bias head, logits requested), so I fixed that test. Ready for another look.

@jason718
jason718 requested a review from AkshitaB October 16, 2026 03:32

@AkshitaB AkshitaB 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.

Reviewed commit 8b09bc171174f09d67541925a4233a69b09b0817. All three findings from the previous review are addressed, but one masking issue remains:

[P2] Mixed attention backends still lose isolation — multimodal.py:479–481. Using any(...) selects Flex-only masks whenever even one block uses FlexAttention. Torch-backed blocks then receive no dense masks, losing packed-example isolation and image bidirectionality. Build masks for both backend types or explicitly reject mixed configurations.

A CPU reproduction with a two-block model confirmed the issue: changing the first packed example changed the second example's logits by a maximum absolute difference of 0.205 with mixed backends, versus 0.0 with all-Torch backends. The reproduction installed the eager-capable Flex backend directly because the model builder falls back to Torch on CPU. This confirms the existing mixed-backend review comment.

The original fixes were verified:

  • Mask selection now follows the instantiated backend instead of the environment variable.
  • Both LM heads explicitly reject response-only unreduced loss.
  • CPU vision attention retains default kernel selection, supporting dropout.

Validation: 49 passed, 11 skipped across the focused embedding, residual-stream, FlexAttention, multimodal, and LM-head tests. GPU/distributed execution remains unverified.

@jason718

Copy link
Copy Markdown
Contributor Author

@AkshitaB thanks for the repro. The mixed-backend case is fixed in 88be43e by rejecting it explicitly (clear OLMoConfigurationError, with a regression test). Building both mask types would need the flex and dense paths to be made mutually safe per block, and nothing in this series mixes backends, so a hard error seemed the safer contract. Ready for another look.

@jason718
jason718 requested a review from AkshitaB October 20, 2026 06:31
@jason718
jason718 merged commit 3fb0bef into main Oct 21, 2026
23 of 25 checks passed
@jason718
jason718 deleted the jasonr/molmo2-model-loader branch October 21, 2026 03:45
jason718 added a commit that referenced this pull request Oct 22, 2026
… CE (#911)

## Summary

PR 2 of 4 for moving the Molmo2 stage-1 reproduction from the long-lived
`vision` branch onto `main` in reviewable pieces. #910 (the model) is
merged; this PR is the **training-loop machinery** for it. No data
pipeline and no scripts here (those are #912 and #913).

- `MultimodalTransformerTrainModule`: trains `MultimodalLM` with a
per-token weighted loss, optimizer param groups for LM / vision tower /
connector, and DDP / FSDP / HSDP over the composite model. It subclasses
`TransformerTrainModule` and reuses its state-dict, microbatch-context,
grad-clip and forward helpers; `train_batch` is its own because the
batch format and loss differ.
- `weighted_cross_entropy_loss` (`nn.functional`): CE with a per-token
float weight, as in mm_olmo.
- `PerGroupScheduler`: a different LR schedule per optimizer param group
(e.g. connector vs LM warmup).
- `SpeedMonitorCallback`: examples/second (only for batches carrying
`example_ids`) and optional `extra_flops_per_batch` from the train
module.

Everything is opt-in; existing train modules behave exactly as before.
Two small guards in already-merged code come with it: `MultimodalLM`
rejects sliding-window FlexAttention layers (the shared flex mask has no
window), and `TransformerConfig` rejects `n_extra_vocab` on every
non-default transformer type.

### Loss normalisation and metrics
Each rank divides its weighted CE sum by the **global** weight divisor
(global weight sum over DP world size), so gradients and the logged CE /
Z-loss equal `sum_r ce_r / global_weight` even when ranks have different
numbers of response tokens. Only an all-zero batch falls back to a
divisor of 1, so fractional weights normalise exactly. With a
`SkipStepOptimizer` the reduced loss and grad norm are handed to the
optimizer, as in the base module.

## Series: all PRs

Linear stack, each PR cut fresh from `main`; the base is retargeted to
`main` as parents land.

| # | PR | Contents | Status |
|---|---|---|---|
| 1/4 | #910 Model | Molmo2 HF loader, flex attention, split-vocab
embedding, `MultimodalLM` | merged |
| 2/4 | #911 Train module **← this PR** |
`MultimodalTransformerTrainModule`, `PerGroupScheduler`, weighted CE,
`SpeedMonitorCallback` additions | review |
| 3/4 | #912 Data core | image preprocessor, sequence builder / branch
packing, collator, mixture loader, SFT formatter, PixMo-Cap | draft |
| 4/4 | #913 Stage-1 recipe | stage-1 datasets, mixtures,
`Molmo2-Stage1.py`, unsharded-export callback | draft |

**Follow-ups, not yet opened:** activation-checkpoint RNG replay for
`ResidualStream.masked_dropout` (sits on top of #906); stage 2
(`Molmo2-Stage2.py`, `image_only_v9`, multi-image datasets), which stays
on `vision` until this series lands; the alignment / OLMoDDP layers,
rebased once `vision` is synced to `main`.

## Why this is a separate PR

- Different review concern from #910: optimizer param groups, FSDP/DDP
wrapping of a composite model, loss reduction. That is `train/`
territory, not model numerics.
- Unit-testable on CPU without any data, and reusable by any multimodal
model.
- It depends on #910 only for the `MultimodalLM` type, and #912 does not
depend on it, so the two can be reviewed in parallel.

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

No intended text-side change.
- **Diff audit:** the only lines this PR *removes* from existing files
are an `__all__` entry and the `n_extra_vocab` check (now stricter;
nothing on `main` sets it). Everything else is additive: new functions,
a new scheduler, and `SpeedMonitorCallback` logic that only triggers for
batches with `example_ids` or a train module defining
`extra_flops_per_batch`, which text modules don't.
- `SpeedMonitorCallback` for text runs: no new metrics, same FLOPs.
- `mypy src/` (CI config), ruff, black, isort are clean.
- Not covered: text GPU / distributed paths (FSDP2, TP, CP) can't run on
a CPU box; CI's GPU jobs are the check there.

## Review notes

Earlier review findings are fixed in this PR: skip-step bookkeeping,
exact fractional-weight normalisation, globally weighted metrics, plus
rejections for sliding-window flex, non-default `n_extra_vocab`, and DDP
with gradient accumulation (torch 2.10's composable `replicate` has no
`no_sync`, so every microbatch would all-reduce; stage 1 uses FSDP).
Deliberately not here: the unsharded-export callback and the
non-finite-loss collective. The callback moved to #913, its only user,
and the `Trainer` already raises on a non-finite CE loss when metrics
are reduced.
`MultimodalLM.forward(images=None)` is only safe single-rank or when
every rank passes `None`; `MultimodalCollator` always emits an `images`
tensor (a dummy crop for text-only batches), so ranks stay aligned.

## Testing

CPU: the train-module tests (response residual dropout with dense and
response-only logits, fractional-weight invariance of gradient and
metric, skip-step bookkeeping), weighted-CE tests, embedding /
multimodal tests for the new rejections. 175 passed, 0 related failures
on this PR; 322 passed at the top of the stack (#913). One distributed
checkpoint test (`test_load_checkpoint_with_missing_keys`) fails in this
sandbox identically on unmodified `main`.

GPU: the train module runs end to end in the stage-1 smoke (30 steps, 8
GPUs, FSDP2) on #913: CE 3.23 -> 2.57, linked from #913. It has no GPU
test of its own yet.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
jason718 added a commit that referenced this pull request Oct 23, 2026
…lator, mixture loader (#912)

## Summary

PR 3 of 4 for moving the Molmo2 stage-1 reproduction from the long-lived
`vision` branch onto `main` in reviewable pieces. #910 (model) and #911
(train module) are merged; this PR is the **data contract**: how a
multi-annotation example becomes tokens, positions, sub-segment ids and
float loss weights, and how examples are packed and mixed. No dataset
recipes yet (those are #913).

- `sequence_builder` (`build_packed_sequence`,
`build_branched_sequence`): multi-annotation / branch-packing sequence
assembly with float loss weights and sub-segment ids.
- `packing.pack_examples`, `MultimodalCollator`, `MultimodalDataLoader`.
- `MixtureDataLoader` + `mixture_weights`, `prefetch`: weighted,
resumable multi-dataset mixing.
- `SftFormatter` (+ `grounding`, `multiple_choice_templates`),
`message_sequence`, `message_weight`, `qwen3_layout`, `sft_common`,
`dataset_compat`, `paths`.
- `nn/vision/molmo2_image_processor.py` (`preprocess_image_molmo2`): the
Molmo2 image preprocessor (crops, pooling indices). Moved here from the
model PR because only the data pipeline uses it.
- `PixMoCapDataset`: kept here because the core tests exercise it end to
end and most #913 datasets build on its helpers.

`data/multimodal/__init__.py` exports only what is in this PR; #913
extends it. Nothing in existing code changes except one added line in
`CHANGELOG.md` and two additive exports in `nn/vision/__init__.py`.

## Series: all PRs

| # | PR | Contents | Status |
|---|---|---|---|
| 1/4 | #910 Model | Molmo2 HF loader, flex attention, split-vocab
embedding, `MultimodalLM` | merged |
| 2/4 | #911 Train module | `MultimodalTransformerTrainModule`,
`PerGroupScheduler`, weighted CE | merged |
| 3/4 | #912 Data core **← this PR** | image preprocessor, sequence
builder / branch packing, collator, mixture loader, SFT formatter,
PixMo-Cap | review |
| 4/4 | #913 Stage-1 recipe | stage-1 datasets, mixtures,
`Molmo2-Stage1.py`, unsharded-export callback | stacked on this PR |

**Follow-ups, not yet opened:** activation-checkpoint RNG replay for
`ResidualStream.masked_dropout` (sits on top of #906); stage 2
(`Molmo2-Stage2.py`, `image_only_v9`, multi-image datasets, `PixMoCap`
`sft_demo` mode), which stays on `vision` until this series lands; the
alignment / OLMoDDP layers, rebased once `vision` is synced to `main`.

## Why this is a separate PR

- This is the data contract: sequence layout, loss weighting and
packing. It is correctness-critical and reviewed by data owners, not
train-loop or model-numerics reviewers.
- No GPU or trainer dependency, only the special-token constants from
#910, so it is reviewable and testable on its own.
- Deliberately dataset-agnostic: with this API fixed, every dataset in
#913 is a mechanical adapter, so #913 need not re-litigate the core
design.
- It keeps ~4k lines of core logic from being buried under ~11k lines of
dataset adapters.

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

No. Everything is new files under `data/multimodal/` plus
`nn/vision/molmo2_image_processor.py` and its export; the text data
pipeline (`olmo_core.data` outside `multimodal/`) is untouched. `mypy
src/` (CI config), ruff, black and isort are clean.

## Review notes

Codex's findings on `PixMoCapDataset` are fixed here:
- **Epoch-aware sampling:** the dataset now uses `EpochSeededExamples`
(the loaders already call `set_epoch`), so a row with several
transcripts no longer picks the same one every epoch. Test added.
- **`sft_demo` mode removed:** it bypassed the truncation path and is
stage-2-only (wired from `image_only_v9`, which is not in this series).
It returns with stage 2.
- **Truncation (Akshita):** `pixmo_cap._truncate` and
`sft_common.truncate_example` were two near-copies. They are now one
weighting-aware `truncate_example`, which rescales surviving branches
only for `root_subsegments*` weighting (it used to rescale with
weighting `none` too), and the collator now refuses to cut `<im_patch>`
tokens instead of only asserting it in a comment. Tests added.
- **Remote URLs:** nothing in this series uses them, so `image` is
documented as a local path and `http(s)://` values now raise a clear
`ValueError` instead of a confusing `FileNotFoundError`.

## Testing

CPU: `src/test/data` and `src/test/nn/vision/multimodal_test.py`
(data-core tests, packed-example isolation for the dense and flex
backends, epoch rotation, URL rejection). Results are in the checks
below. The data path is exercised end to end, on GPU, by the stage-1
smoke linked from #913.
jason718 added a commit that referenced this pull request Oct 30, 2026
jason718 added a commit that referenced this pull request Oct 31, 2026
No code yet. The branch starts at #916's head (4fb33e9), which includes the
main sync (#885, #910-#912, #920). #916's earlier ac87d76 trained the 64K mixed
mid-training checkpoint this SFT starts from.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KshPetwmP4KzQGok1mmMXs
jason718 added a commit that referenced this pull request Nov 10, 2026
…1.py (#913)

## Summary

PR 4 of 7 for moving the Molmo2 stage-1 reproduction from the long-lived
`vision` branch onto `main`. #910 (model), #911 (train module) and #912
(data core) are merged; this PR adds the **stage-1 recipe** that makes
them runnable end to end: the datasets, the mixtures, and
`Molmo2-Stage1.py`.

About 6.7k source lines and 4.8k test lines. It also restores one fix
needed for the recipe to train correctly: activation-checkpoint RNG
replay (see "Why the RNG fix is here"). Almost all of it is new files;
the only existing files touched are listed under "Read closely" below.

## Review map

Reading every file closely is not necessary. Here is where attention
pays off.

### Read closely (about 1.9k lines)
| File | Lines | What to check |
|---|---|---|
| `scripts/train/Molmo2-Stage1.py` | 1537 | The recipe itself: the `v1`
/ `v2` / `v3` mixture rates, step counts, optimizer groups and learning
rates, the `--init_from` paths, and the launch settings. This is where a
wrong constant changes the training run silently. |
| `train/callbacks/unsharded_export.py` | 128 | Writes
`model.safetensors` and a config copy into each permanent checkpoint
from a background op on rank 0; skips ephemeral checkpoints. Moved here
from #911 because the stage-1 script is its only user. |
| `distributed/checkpoint/__init__.py` | +30 |
`load_unsharded_model_state()`: the only change to a shared distributed
module. Additive. |
| `nn/transformer/model.py` (+`ac_rng_test.py`) | +24 / -4 | Activation
checkpointing now preserves the RNG state when dropout is active
(`masked_dropout`, `ResidualStream` dropout, `nn.Dropout`), so the
recomputed forward replays the original dropout masks. Required by this
recipe; see below. |
| `data/multimodal/__init__.py`, `sequence_builder.py` | +92 / +4 |
Exports, and a type annotation on `build_branched_sequence` that already
accepted multi-turn branches. No behaviour change. |

### Skim for the shared pattern (about 4.9k lines of dataset code)
These are adapters. Each one defines a config dataclass and a map-style
dataset, formats its rows into the stage-1 prompt family, builds the
sequence with the #912 builders, and truncates with `truncate_example`.
Seven of them (`academic_dataset`, `gui_syn`, `ocr_caption_tars`,
`olmocr`, `pixmo_points_v2`, `synthetic_ocr`, `text_rich_caption`) use
the `EpochSeededExamples` mixin from #912 for epoch-aware sampling; the
others do not sample per epoch. If one is right, the rest are
variations.

| Group | Files |
|---|---|
| Pointing and counting | `pixmo_points.py` (433), `pixmo_points_v2.py`
(579), `gui_syn.py` (243), `detect_counting_question.py` (82) |
| OCR | `olmocr.py` (328), `ocr_caption_tars.py` (366),
`synthetic_ocr.py` (384), `text_rich_caption.py` (200),
`mixtures/ocr.py` (245) |
| Academic QA | `academic/registry.py` (611), `academic_dataset.py`
(179), `academic/formatters.py` (102), `mixtures/stage1_academic.py`
(149) |
| Other sources | `pixmo_clocks.py` (145), `pixmo_cap_qa.py` (104),
`pixmo_ama.py` (96), `tulu.py` (173), `finevision.py` (249),
`mmfinereason.py` (218) |

### Tests (about 4.8k lines)
They mirror the modules above (one test file per dataset group), plus
`molmo2_training_logits_parity_test.py` (GPU, needs the HF checkpoint)
and the callback and distributed-checkpoint tests. A test that needs
Weka data skips when the data is absent.

### Invariants the design relies on (worth a spot check)
These are stated in the script's docstring and should hold across every
file:
- Every default source is a **train split only**; the training set of a
benchmark the stage-2 checkpoints are evaluated on is never a stage-1
source.
- OCR and academic sources use a **style tag as the whole user turn**,
with no question text.
- Data lives on Weka, so datasets read paths from `paths.py` (#912) and
nothing here needs S3 or GCS secrets.
- Mixture rates per recipe are as in the script's docstring: `v1`
caption 0.6 / pointing and counting 0.3 / text 0.1; `v2` caption 0.5 /
pointing 0.25 / OCR 0.25; `v3` caption 0.33 / pointing 0.16 / OCR 0.34 /
academic 0.14 / clocks 0.03.

## Series

| # | PR | Status |
|---|---|---|
| 1/7 | #910 Model: HF Molmo2 loader, flex attention, split-vocab
embedding | merged |
| 2/7 | #911 Train module, `PerGroupScheduler`, weighted CE | merged |
| 3/7 | #912 Data core | merged |
| 4/7 | #913 Stage-1 recipe **(this PR)** | review |
| 5/7 | #934 Data infrastructure, stage-2 recipe, Qwen3-0.6B / 1.7B
sizes | draft, stacked on this PR |
| 6/7 | #936 OLMo 3.5 alignment training: OLMoDDP hooks and train
module, optimizer, callbacks, alignment pipeline | draft |
| 7/7 | #937 In-repo evaluation suites and remaining tools | draft |
| 8 | #938 Stable mixed mid-training (from #916) | draft |
| 9 | #939 Still-changing mixed mid-training (from #916) | draft |

PRs 5 to 7 bring the rest of `vision` onto `main`, so that `main` can do
everything `vision` can. Separate: activation-checkpoint RNG replay for
`ResidualStream.masked_dropout` is already in this PR; #906 (open) will
need a rebase on it.

## Why this is a separate PR

- It is the bulk of the series, but the review is mostly
pattern-checking, and it is the only part that depends on external data
locations and recipe choices.
- It can be iterated (new datasets, recipe tweaks) without touching any
core API from #910 to #912.
- It is what makes stage 1 runnable, so it is where the end-to-end
evidence belongs.

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

No intended text-side change. The shared files it touches are the
additive checkpoint helper, the callbacks `__init__` export, a type
annotation, and the activation-checkpointing change in
`nn/transformer/model.py`. That last one changes behaviour only for
models that use dropout together with activation checkpointing (their
recompute now replays the dropout masks, which it previously did not);
with `dropout=0`, the default, text models are unaffected. For the
series as a whole, text-side outputs (weights, logits, loss and
gradients) were compared bit for bit against `main` on CPU and match,
and the existing test suites show no regressions. Text GPU and
distributed paths (FSDP2, TP, CP) cannot run on the CPU box I used, so
CI's GPU jobs are the check there.

## Why the RNG fix is here

Stage 1 trains with full activation checkpointing and 10% response-token
residual dropout. Without replaying the RNG, the recompute draws
different dropout masks than the original forward, so gradients are
taken against a different sample than the loss. This was held out of
#910 because #906 (open) rewrites the same lines; the end-to-end parity
run below showed it cannot be left out of the recipe: without it the run
trains much worse than `vision` (final loss 1.83 vs 1.19). The change
here is `vision`'s own fix (#828) unchanged, with its test. #906 fixes
the general case differently and will need a rebase on top of this.

## Not included (stays on `vision`)

Stage 2 (`Molmo2-Stage2.py`, `image_only_v9`, multi-image datasets,
`compare_sft_example.py`), the stage-1 data infrastructure upgrades, and
the OLMo 3.5 alignment work; see the plan above.

## Testing

**CPU:** `src/test/data`, the callback and distributed-checkpoint tests:
462 passed, 0 failed (before the last test-only fix below). ruff, black,
isort and `mypy src/` (the CI config) are clean. `Molmo2-Stage1.py
dry_run` resolves for the default, `--recipe=v2` and `--recipe=v3` (32k
and 50k steps). One test (`test_st_qa_train_validation_split`) read a
Weka path with no skip, which failed on the CI runner; it now skips when
the data is absent.

**GPU smoke (Beaker, 8x GPU, FSDP2):** an earlier 30-step run of the
stack: CE loss 3.23 → 2.57, checkpoint and unsharded export written.

**End-to-end parity on Beaker** (`ai2/molmofication`, Holmes, allocated,
`--recipe=v3`, 1 node x 8 GPUs, 2000 steps, same seed and arguments; W&B
disabled because `BeakerCallback.pre_train` calls `wandb.Run.get_url()`,
which the image's `wandb` lacks, existing code unrelated to this
series). V is the control: `vision` at the commit this series was cut
from.

| Run | Code | Result |
|---|---|---|
| [V](https://beaker.org/ex/01M5N24PSKG4EYXQNXQ7KK45XC) | `vision` @
`f639a28` (control) | CE 3.16 -> 1.20 |
| [P](https://beaker.org/ex/01M5N222MQ1JSY1TBDWY3YZBEY) | this PR
**without** the RNG fix | trains worse than V, gap grows: +0.05 (steps
1-50), +0.41 (201-500), +0.60 (1501-2000); final-100-step CE 1.83 vs
1.20 |
| [P2](https://beaker.org/ex/01M5NWNH21XHNA9WFKPJRARQHS) | this PR
**with** the RNG fix | tracks V |

Windowed mean CE, with the fix (P2) against the control (V):

| steps | P2 | V | P2 - V |
|---|---|---|---|
| 1-50 | 2.619 | 2.619 | +0.000 |
| 51-200 | 2.114 | 2.096 | +0.018 |
| 201-500 | 1.638 | 1.640 | -0.002 |
| 501-1000 | 1.326 | 1.315 | +0.011 |
| 1001-1500 | 1.248 | 1.238 | +0.011 |
| 1501-2000 | 1.199 | 1.201 | -0.002 |

Last 100 steps: P2 1.192, V 1.197. The offset has no trend (-0.002 per
1000 steps; without the fix, +0.195 per 1000 steps). Two identical-code
runs (P and R1) differ by about 0.015 per logged point, so window means
agree within about that. Per-point differences between P2 and V are
larger (stdev 0.057) because the data draws differ on purpose: the
review fixes made PixMo-Cap sampling epoch-aware.

Caveats: one run per arm. The gradient norm is spiky; P2 had two
transient spikes (step 300: 30, step 455: 37.6) that V did not, with
normal loss at those steps and clipping at 1.0 (the unfixed run spiked
as high as 165). I cannot tell noise from a small residual difference
from single runs.

**Checkpoint and resume:** run
[R1](https://beaker.org/ex/01M5N222PV51TWTJ7YR9KXWWNP) (1000 steps)
wrote a checkpoint;
[R2](https://beaker.org/ex/01M5NS0S9NSNFQGJBQVDGF2ENE) resumed it from
step 1000 to 2000 (first logged step 1005). Over steps 1001-2000 its
loss differs from the uninterrupted run P by +0.003 on average (stdev
0.013), inside the same-code noise. The unsharded `model.safetensors`
export was written. This pair ran on the code before the RNG fix; resume
does not depend on it, but I have not rerun it on the final code.

**Second parity check: Qwen3-0.6B on 2 nodes (16 GPUs), against a
finished `vision` run.** This covers paths the 4B runs above did not:
`response_logits_only=true`, no activation checkpointing, and 16-GPU
FSDP. Reference: `molmo2-stage1-0p6b-v3-50k-20261023` (`vision` HEAD),
whose per-step training loss is readable from its W&B files. Test:
[`mm-e2e-0p6b-main-2k`](https://beaker.org/ex/01M5QC1TVNGX0R8CXF8VZ725C5),
this branch plus `vision`'s #933 (the 0.6B size) cherry-picked, with the
reference's launch arguments, image and environment, stopped at step
2000 by `hard_stop` while keeping its 50k-step LR schedule. Windowed
mean CE:

| steps | run | reference | diff |
|---|---|---|---|
| 1-50 | 4.580 | 4.595 | -0.015 |
| 51-200 | 2.722 | 2.729 | -0.007 |
| 201-500 | 2.383 | 2.380 | +0.002 |
| 501-1000 | 1.738 | 1.737 | +0.002 |
| 1001-2000 | 1.519 | 1.520 | -0.002 |

Last 100 steps: 1.443 vs 1.458; trend of the difference -0.006 per 1000
steps; loss finite throughout. Per-point differences between the two
runs have stdev 0.093, which matches what two independent runs of the
same curve should give (the reference's own per-step noise is about
0.064, so about 0.09 for a difference). Caveat: the reference ran
`vision` HEAD, which includes data-code changes made after this series'
cut point (#902, #903, #918), so this is a sanity check of overall
health, not an apples-to-apples control; the rigorous rerun comes once
those changes land on `main`.

**Offline check, no GPU:** one training step of a tiny multimodal model
on `vision`@cut and on this branch (dropout off) produces bit-identical
loss, gradients and updated weights, so the model and train-module path
is unchanged apart from the RNG fix.

**GPU logit parity vs HF Molmo2 (4B and 8B pass; O-7B skipped):** see
#910.

**Not covered:** long-horizon loss parity against the released
Molmo2-4B-Pretrain recipe (these are 2000-step checks); GPU text-side
paths beyond CI; a resume rerun on the final code.
jason718 added a commit that referenced this pull request Nov 11, 2026
No code yet. The branch starts at #916's head (4fb33e9), which includes the
main sync (#885, #910-#912, #920). #916's earlier ac87d76 trained the 64K mixed
mid-training checkpoint this SFT starts from.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KshPetwmP4KzQGok1mmMXs
jason718 added a commit that referenced this pull request Nov 30, 2026
…1.7B sizes (#934)

## Summary

PR 5 of 7 for moving the Molmo2 reproduction from the long-lived
`vision` branch onto `main`. **#913 (stage-1 recipe) is merged, so this
targets `main` directly**; the diff here is only this PR's change. This
PR brings the multimodal **data pipeline up to `vision`'s current
state** and adds the **stage-2 recipe**, plus the Qwen3-0.6B / 1.7B
model sizes:

- **Epoch-aware, resumable mixture loading** (`mixture_data_loader`,
`alignment.py`, `mixture_weights`, `packing`, `rng`): per-source epochs
(`get(index, epoch)`), configurable `MultimodalMixtureConfig` /
`MultimodalSourceConfig` mixtures, loader state that resumes mid-epoch.
- **Message layouts** (`document_layout`, `qwen3_layout`,
`molmo2_tokens`: `Molmo2TokenIds`, `prepare_molmo2_tokenizer`): the
released `qwen3` layout and a `document` layout, selected per source.
- **Truncation and sampling** (`sft_common`, `pixmo_cap`,
`message_sequence`, `collator`): `truncate_example(...,
recompute_root_subsegments=...)` and `truncate_for_format`;
`sft_example_rng`.
- **Stage-1 data updates** from `vision`: `pixmo_points`,
`pixmo_points_v2`, `finevision`, `fs_cache`, and small updates to the
OCR, academic and text-rich sources.
- **Stage 2:** `Molmo2-Stage2.py`, the `image_only_v9` mixture,
multi-image datasets, `mm_olmo_loader`, and the `sft_demo` mode of
`PixMoCapDataset`.
- **Model sizes:** `MultimodalLMConfig.molmo2_0_6B()` / `molmo2_1_7B()`
and `--model_size=0.6b|1.7b` in `Molmo2-Stage1.py`.

About 5.4k source lines and 3.7k test lines in 56 files. Everything is
opt-in; existing behaviour on `main` does not change.

## Review map

Reading every file closely is not necessary.

### Read closely
| File | Lines | What to check |
|---|---|---|
| `data/multimodal/mixture_data_loader.py` | +925 / -79 | The loader's
state, epoch and resume semantics, and how per-source epochs reach
`get(index, epoch)`. The most behaviour-sensitive file in the PR. |
| `data/multimodal/sft_common.py` | +174 / -32 | `truncate_example`
(rejects cutting any image-structural token; rescales branch weights
only when `recompute_root_subsegments=True`) and `truncate_for_format`.
Replaces the weighting-aware version added in #912's review; same
behaviour, `vision`'s API. |
| `data/multimodal/pixmo_cap.py` | +293 / -37 | Routes through the
shared `truncate_example` (the local copy that always rescaled is gone);
`sft_demo` now truncates; `__getitem__` uses the dataset's current
epoch. |
| `data/multimodal/packing.py`, `collator.py` | +150 / +41 | Packing
contract; the collator still refuses to cut `<im_patch>` tokens (from
#912's review). |
| `scripts/train/Molmo2-Stage2.py` | 564 (new) | The stage-2 recipe:
mixture, optimizer groups, learning rates, launch settings. |
| `nn/vision/multimodal.py`, `molmo2_tokens.py` | +80 / +118 | The
model-side pieces the new data pipeline needs (0.6B / 1.7B factories,
token ids). Only the data-pipeline and size parts of `vision`'s file are
here. |

### Skim for the shared pattern
`pixmo_points.py` (+1005), `finevision.py` (+334), `pixmo_points_v2.py`
(+135), `multi_image_datasets.py` (289 new), `mixtures/image_only_v9.py`
(360 new), `alignment.py` (314 new), `message_sequence.py`,
`document_layout.py`, `fs_cache.py`, and small updates to
`text_rich_caption`, `ocr_caption_tars`, `olmocr`, `synthetic_ocr`,
`academic_dataset`. These are dataset adapters and mixture definitions
that follow one shape; if one is right, the rest are variations.

### Tests (about 3.7k lines)
One test file per module group, plus `molmo2_tokens_test`,
`molmo2_native_config_test` (now covers 0.6B / 1.7B) and the model-size
test for the stage-1 script.

## Series

| # | PR | Status |
|---|---|---|
| 1/7 | #910 Model: HF Molmo2 loader, flex attention, split-vocab
embedding | merged |
| 2/7 | #911 Train module, `PerGroupScheduler`, weighted CE | merged |
| 3/7 | #912 Data core | merged |
| 4/7 | #913 Stage-1 recipe | merged |
| 5/7 | this PR: data infrastructure, stage-2 recipe, 0.6B / 1.7B sizes
| approved |
| 6/7 | #936 OLMo 3.5 alignment training: OLMoDDP hooks and train
module, optimizer, callbacks, alignment pipeline | draft |
| 7/7 | #937 evals, mixed mid-training (from #916), catch-up with #916 |
draft |

With PRs 6 and 7, `main` reproduces everything on `vision`, apart from
the intentional divergences below.

## Why this is a separate PR

- It is the data and recipe layer that every later PR builds on, and it
can be checked without any OLMo 3.5 or OLMoDDP code.
- The loader and truncation changes are behaviour-sensitive and deserve
a focused review, separate from #913's recipe.
- Stage 2 only needs this data layer, so it lands here and not behind
the alignment work.

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

No. This PR adds files under `data/multimodal/`, `nn/vision/` and
`scripts/`; `nn/transformer`, `optim`, `train` and the text data
pipeline are untouched. Only multimodal entry points change behaviour.

## Behaviour added or fixed during review

These are in the final diff; each has a test that fails without it.
- **Epochs reach every source.** `sft_example_rng` varies Qwen-layout
streams with the epoch (epoch 0 is the unchanged stream, so first passes
are identical). Points, Count, CoSyn and FineVision honor `set_epoch`,
which the default (non-continuous) loader calls; GUISyn builds per
explicit epoch; selected sources forward the epoch. A scan test fails
for any source with an epoch-taking `get` but no `set_epoch` (the
alignment and mid-training sources run with `continuous_stream=True` and
are excluded).
- **Truncation is independent of strict validation**
(`pixmo_points._finalize_example`), and multi-image examples longer than
the recipe's length are truncated or rejected so the loader skips them
instead of the collator stopping the run. The collator's image-patch id
follows the mixture's `token_ids`.
- **Resume identities.** FineVision fingerprints every source with a
stable Arrow fingerprint and binds it to the token ids;
`strict_annotations=True` requires `skip_bad_rows=False`; a row
selection over an unpinned source advertises no fingerprint.
- **Mixture and stage-2 plumbing.** Subset mixtures open only the groups
they need; Stage 2 derives source names from the registry order
(matching the datasets returned) without opening sources twice; the
stage-2 registry test skips without Weka data.

## Intentional divergences from `vision`

Where `vision` and `main` differ on purpose:
- **No HF export direction** (`multimodal_lm_state_dict_to_hf`) and no
`output_vocab_size` logit masking: both were removed in #910's review.
Nothing on `vision` calls either.
- **Reviewed fixes kept:** the collator's image-token guard, and
PixMo-Cap's truncation through the shared function (the weighting-off
fix).
- **Type-only fixes** so `mypy src/` passes (annotations in tests and
the stage-2 script, an undefined `Molmo2TokenIds` annotation in
`sft_common`, which was a latent lint error on `vision`).
- **Not in this PR:** the B-side parts of `vision`'s `multimodal.py` and
the data package exports (OLMoDDP model, document-mode attention, replay
datasets), which arrive with PR 6.

## Testing

CPU on the final tip: `src/test/{data/multimodal,scripts,nn/vision}` 665
passed, 26 skipped, 1 failed. The failure, `test_clip_parity`, is
environment-only and fails the same way on `main` on the dev box. ruff,
black, isort and `mypy src/` (CI config) are clean.
`package_import_test` runs subprocess imports with a 45 s timeout that
the slow dev box exceeds, so it was checked separately with a longer
timeout; CI runs it as is.

**GPU parity (Beaker
[`mm-e2e-0p6b-A-2k`](https://beaker.org/ex/01M5RK532QEWWEVZG8S6HG2S0W),
0.6B, 2 nodes, 2000 steps, this PR's code) vs the `vision` reference run
`molmo2-stage1-0p6b-v3-50k-20261023`:** windowed mean train CE,
2026-10-25.

| steps | this PR | reference | diff |
|---|---|---|---|
| 1-50 | 4.623 | 4.595 | +0.027 |
| 51-200 | 2.720 | 2.729 | -0.008 |
| 201-500 | 2.371 | 2.380 | -0.010 |
| 501-1000 | 1.739 | 1.737 | +0.002 |
| 1001-2000 | 1.530 | 1.520 | +0.010 |

Per-point diff over 401 logged steps: mean +0.004, stdev 0.099
(independent runs of this size differ by about this much per point). All
windows after warm-up are within ±0.015, the noise floor for identical
code. Caveats: one run per arm, loss only (no downstream eval), and the
run is of an earlier tip. The later review fixes change only Qwen-layout
draws from epoch 1 on (epoch 0 is bit-identical, tested against
`example_rng`), and I did not rerun parity after them.
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.

2 participants