Skip to content

Multimodal data/loader infrastructure from #869: packed resumable mixture loading, document layout, vision loaders - #902

Merged
jason718 merged 3 commits into
visionfrom
jasonr/multimodal-data-infra
Oct 5, 2026
Merged

jason718 merged 3 commits into
visionfrom
jasonr/multimodal-data-infra

Conversation

@jason718

@jason718 jason718 commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

What this PR is

Molmo2-style multimodal training needs three things the data code on vision did not have yet:

  1. A data loader that packs several image+text examples into one training sequence, can resume mid-epoch, and notices when a dataset changed under it. MixtureDataLoader gains a buffered packer, a per-rank cursor saved in state_dict, dataset fingerprints checked on resume, and a data-error policy (total_data_errors).
  2. A "document" text layout: plain long_caption:-style text instead of chat turns (document_layout.py, PixMo-Cap document format with transcript validation, message-format helpers), plus sampling weights derived from a target loss mass (mixture_weights.py).
  3. Helpers for a language model that is not Qwen: Molmo2 image-token ids and tokenizer preparation (Molmo2TokenIds), and a factory that builds the Molmo2-4B vision stack around an already-built LM config.

All of it comes from RustinS's #869 and is split out so it can be reviewed and merged on its own. Existing behaviour is unchanged by default: the new loading mode (a continuous, resumable Molmo2-style stream with dataset fingerprints) and the extra batch metadata are opt-in (continuous_stream=True, batch_metadata=True); with them off, the loader, packer and collator produce exactly what vision produces today, and the defaults (pack_buffer_size=48, pack_image_weight=30.0) are vision's. It changes only files under data/multimodal/ and nn/vision/; text-only training code is untouched (the shared-code allow-list check against vision passes with an empty list). It does not depend on the OLMoDDP hooks (#886); the vision-alignment PR (#889) is its first user.

Size

30 files, +3,352 / −294. vision's own data_loader.py, dataset_compat.py, molmo2_loader.py, connector.py, image_vit.py and sequence_builder.py are untouched.

How it was checked

  • Re-checked on the newest vision (f639a28, after Add MolmoPoint-GUISyn to the stage-1 pointing group (v2 and v3 recipes) #898 added MolmoPoint-GUISyn to the stage-1 pointing group), with this branch merged on top: first batches of Molmo2-Stage1.py on the default recipe and on --recipe=v3 (4 batches each) and Molmo2-Stage2.py (2 batches), ranks 0 and 3, are bitwise identical to vision (6 of 6 comparisons); src/test/data/multimodal and src/test/nn/vision: 502 passed, 25 skipped (test_clip_parity, which also fails on vision, deselected).

  • Existing and new multimodal tests on this branch: src/test/data/multimodal, src/test/nn/vision, src/test/train/train_module: 512 passed, 32 skipped, 1 failed (the one failure, parity_test::test_clip_parity, also fails on vision).

  • The OLMo 3.5 bridge smoke (150 steps on 8 B300, Beaker 01M3TRTWNZ8SZ3EW77P72Z6MD4) and the 20-step launch checks ran with this code as part of the full stack.

  • Molmo2 loaders unchanged: the first batches from Molmo2-Stage1.py (4 batches) and Molmo2-Stage2.py (2 batches), built on real data for data-parallel ranks 0 and 3, are bitwise identical on vision and this branch (every tensor). An earlier version of this PR failed that check (it changed the packing mode, two loader defaults that Stage 2 relies on, and the order of examples inside each pack) and was fixed. The same check across all 8 data-parallel ranks × 30 batches (the whole 30-step run) is also bitwise identical, both on the dev box and inside the Beaker training image (Beaker 01M400HMJDF0748YKH1ZHDVMQ4).

  • Molmo2 Stage-1 on GPU (30 steps, 8 GPUs, three runs per side): no difference beyond run-to-run noise. Step-1 loss is 3.232 in all six runs. vision itself is not deterministic run to run: on the identical first batch its step-1 grad norm was 22.0, 36.3 and 36.7, and this branch's was 22.2, 23.7 and 39.2.

    step vision CE (3 runs) this PR CE (3 runs)
    1 3.232 / 3.232 / 3.232 3.232 / 3.232 / 3.232
    5 3.106 / 3.104 / 3.100 3.104 / 3.104 / 3.099
    10 3.032 / 3.035 / 3.011 3.027 / 3.023 / 3.008
    15 2.872 / 2.881 / 2.833 2.850 / 2.839 / 2.823
    20 2.752 / 2.753 / 2.732 2.738 / 2.734 / 2.729
    25 2.637 / 2.636 / 2.622 2.621 / 2.620 / 2.617
    30 2.486 / 2.480 / 2.474 2.469 / 2.470 / 2.471

    Through step 15 this PR's runs fall among vision's. From step 20 on, some or all of them sit 0.001 to 0.005 below vision's lowest run, while vision's own three runs are 0.012 to 0.048 apart at steps 10 to 30. Since the data, model code and resolved config are the same, this is consistent with noise. The only config differences are the new fields, whose defaults are vision's values.

Review follow-ups

🤖 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: 4dcf8c7ae6

ℹ️ 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 +97 to +102
"router_token_mask": self._pad_1d(
[np.ones(min(len(ex["input_ids"]), max_len), dtype=np.bool_) for ex in examples],
False,
max_len,
np.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 Route the padding mask into MoE execution

When this collator is used with an MoE language model and any example is shorter than the fixed sequence length, router_token_mask has no effect: MultimodalTransformerTrainModule._prepare_batch() leaves it in model kwargs, but Transformer._prepare_inputs() never extracts or forwards that name to the MoE layers. The padded slots therefore still participate in routing and router auxiliary losses, despite this mask being added specifically to exclude them; this can skew expert loads and training losses on padded multimodal batches.

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 changed in this PR. router_token_mask is only emitted with the opt-in batch_metadata=True; vision's Molmo2 scripts don't set it, so their batches are unchanged (loader parity bitwise identical). Its consumer is the alignment train module in #889, which uses the mask for the router-loss token count; it is not meant to reach the MoE forward pass.

Comment thread src/olmo_core/nn/vision/__init__.py Outdated
Comment on lines +25 to +29
from .molmo2_loader import (
load_molmo2_hf_vision_config,
molmo2_hf_state_dict_to_multimodal_lm,
multimodal_lm_state_dict_to_hf,
molmo2_hf_state_dict_to_vision,
multimodal_config_from_molmo2_vision,

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 Restore the package-level state-dict exporter

This replacement drops the existing package-level import of multimodal_lm_state_dict_to_hf, although the converter still exists in molmo2_loader.py. Existing callers using from olmo_core.nn.vision import multimodal_lm_state_dict_to_hf now fail with an ImportError, so the public vision API regresses even though the underlying functionality remains available.

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: multimodal_lm_state_dict_to_hf is exported from olmo_core.nn.vision again (same as on vision).

@jason718
jason718 force-pushed the jasonr/multimodal-data-infra branch from 4dcf8c7 to ccce7bb Compare October 2, 2026 17:55

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

ℹ️ 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 +727 to +728
get = getattr(dataset, "get", None)
ex = get(example_idx, source_epoch) if get is not None else dataset[example_idx]

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 source epochs for legacy epoch-aware datasets

When buffered packing is enabled, this fallback calls dataset[example_idx] for every source that has not implemented the new get(index, epoch) API. Several mixture sources (for example TextRichCaptionDataset, NvidiaSynthOcrDataset, and OlmOcrMixDataset) instead inherit EpochSeededExamples and derive their augmentation RNG from the mutable epoch set only by reshuffle(). Because buffered loaders report total_batches=None, normal step-bounded training stays in one trainer epoch while the reference stream's source_epoch advances, so repeated visits to those rows reuse identical crops/augmentations rather than rotating with their source epoch.

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.

Valid for the opt-in continuous stream (continuous_stream=True, used by the alignment recipe); vision's default Molmo2 path is unchanged by this PR. Not fixed here by decision; tracked with possible fixes in #909.

@jason718 jason718 self-assigned this Oct 2, 2026
@jason718
jason718 force-pushed the jasonr/multimodal-data-infra branch from ccce7bb to 0075fa4 Compare October 2, 2026 22:12
From RustinS's #869, behind opt-in switches so the Molmo2 training scripts load exactly the
same batches as before (verified bitwise on the first Stage-1 and Stage-2 batches):

- MixtureDataLoader(continuous_stream=True): Molmo2's continuous multinomial source stream
  with per-source epochs and a buffered packer whose cursor, buffer and dataset fingerprints
  are saved in state_dict for an exact resume, plus explicit per-group sequence quotas. The
  default keeps the epoch-shuffled order, dataset[index] loading and iter_dynamic_packs,
  with vision's pack_buffer_size=48 / pack_image_weight=30 defaults.
- MixtureDataLoaderConfig, a registered config for the loader.
- MultimodalCollator(batch_metadata=True): router_token_mask, image_crop_counts and
  pooled_token_counts for the OLMoDDP multimodal train module; off by default.
- The document message layout and PixMo-Cap document format with transcript validation
  (the qwen3 layout is unchanged), sampling weights from target loss mass, per-example
  deterministic RNG streams for the document format, and packed-image direct copy.

Nothing here depends on the OLMoDDP hooks or the alignment recipe.
Molmo2TokenIds / prepare_molmo2_tokenizer (from #869) so the Molmo2 image tokens can live in
another LM's spare vocabulary rows, and MultimodalLMConfig.molmo2_vision_stack, which pairs
Molmo2-4B's vision tower and connector with an already-built language-model config.
@jason718
jason718 force-pushed the jasonr/multimodal-data-infra branch from 0075fa4 to 956d17b Compare October 3, 2026 03:28

@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: 956d17b68f

ℹ️ 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 +395 to +396
def __getitem__(self, index: int) -> Dict[str, Any]:
return self.get(index, 0)

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 Forward epoch changes through the max-length wrapper

When MaxSequenceLengthDataset wraps an EpochSeededExamples source such as Stage1AcademicDataset, the standard epoch-shuffled loader finds no set_epoch method on the wrapper, so the wrapped dataset remains at epoch 0. Its __getitem__ path then always loads the underlying source with that stale epoch, causing crops, negative choices, and other epoch-seeded augmentation to repeat in every trainer epoch even though MixtureDataLoader.reshuffle() is designed to rotate them.

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.

Resolved by removing MaxSequenceLengthDataset (5a328b9): nothing in the stack used it outside its own tests.

Nothing in the stack wraps a source with it (only its own tests did), and it did not forward
set_epoch to the wrapped dataset (Codex review on #902). truncate_example, which it called,
stays and keeps its tests.

@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: 5a328b9a1c

ℹ️ 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 +1105 to +1109
"pack": self.pack,
"pack_buffer_size": self.pack_buffer_size,
"pack_max_crops": self.pack_max_crops,
"pack_image_weight": self.pack_image_weight,
"est_tokens_per_example": self.est_tokens_per_example,

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 Validate stream mode when restoring grouped checkpoints

When a grouped checkpoint made with continuous_stream=True is restored using the same packing parameters but continuous_stream=False (or vice versa), this identity map still matches because it records pack but not the stream mode. load_state_dict() then accepts the checkpoint: default-mode children ignore the saved packing cursor, while continuous-mode children replay from a different source stream when no cursor is present, silently changing the resumed examples instead of rejecting the incompatible configuration.

Useful? React with 👍 / 👎.

@jason718
jason718 merged commit c69ee81 into vision Oct 5, 2026
1 check passed
@jason718
jason718 deleted the jasonr/multimodal-data-infra branch October 5, 2026 18:17
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.
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.
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