Repository navigation
[Multimodal 5/7] Data infrastructure, stage-2 recipe, and Qwen3-0.6B/1.7B sizes - #934
Conversation
c58653d to
1e2de64
Compare
1e2de64 to
7d5f498
Compare
c6f1473 to
6b22cef
Compare
…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.
7d5f498 to
8e0ebfe
Compare
Codex Review Summary: ❌ FailedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8e0ebfe05e
ℹ️ 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".
| return PixMoMultiPointsDatasetConfig( | ||
| loss_token_weighting="none", | ||
| message_weight=src.message_weight, | ||
| p_high_res=src.override_p_high_res or 0.0, | ||
| seed=seed, |
There was a problem hiding this comment.
Truncate high-resolution multi-image examples before collation
When the full or pointing Stage-2 mixture samples pixmo_multi_points, this enables high-resolution preprocessing with probability 0.3 while allowing up to five images; encode_sft_example can therefore emit several 24-crop image blocks whose structural prefix alone exceeds the recipe's 16,384-token sequence length. _MultiImageSftDataset returns that sequence without applying any length-aware truncation, so MultimodalCollator detects <im_patch> tokens beyond the cutoff and raises, terminating training as soon as such a row is sampled. Pass the recipe's maximum sequence length into this dataset and safely truncate or reject the example before it reaches the collator.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in fa6cf79. The multi-image datasets now take max_sequence_length (the stage-2 builder passes the recipe's 16,384) and run truncate_example on each encoded example, the way PixMoCapDataset does. A longer example is tail-truncated; if the cut would drop part of an image block it raises a ValueError instead, which the loader's bad-example path skips, so it no longer reaches the collator and stops the run. Tests cover truncation, rejection and the unchanged no-limit case. I haven't measured how often the 30% high-resolution sampling produces such rows.
| MultimodalCollator( | ||
| pad_token_id=pad_token_id, | ||
| pad_sequence_length=self.sequence_length, | ||
| batch_metadata=self.batch_metadata, | ||
| ), |
There was a problem hiding this comment.
Propagate the mixture's image patch token into the collator
For a MultimodalMixtureConfig using the new document/non-Qwen token layout, dataset.token_ids.im_patch_id differs from the released Molmo2 constant, but this builder constructs a collator without that ID. The collator's truncation guard consequently still searches only for the hard-coded IM_PATCH_ID; if the configured sequence length cuts a custom-token image block, it misses the cut and produces fewer image-token positions than pooled features, causing the multimodal forward pass to fail. Make the collator's protected patch ID configurable and initialize it from dataset.token_ids.im_patch_id here.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in fa6cf79: MultimodalCollator and its config take image_patch_token_id (default: the released id), and MixtureDataLoaderConfig.build passes dataset.token_ids.im_patch_id. Tests check both the guard with a custom id and that the loader forwards the mixture's id.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fa6cf79e06
ℹ️ 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".
| datasets_map = build_image_only_v9_datasets( | ||
| tokenizer, seed, max_sequence_length=max_sequence_length | ||
| ) | ||
| lengths = {name: len(datasets_map[name]) for name in datasets_map.keys()} |
There was a problem hiding this comment.
Filter unselected sources before constructing datasets
When dataset_names selects a validation tier such as the default debug mixture, this comprehension indexes every entry in the lazy map before applying the filter below. It therefore constructs all 43 datasets and fails if any unrelated production asset is unavailable, so the documented three-source local smoke configuration still requires the complete image-only-v9 corpus. Determine the selected sources before dereferencing the lazy map, while preserving any length metadata needed for the intended weights.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This is the same issue as Akshita's thread on this line (subset mixtures opened every registered source before filtering); fixed in c332a9d. build_image_only_v9_mixture now opens only the groups that contain a requested source, and the weights are unchanged because the other groups' lengths cancel when renormalizing over the subset. See #934 (comment) for the test.
| names = ( | ||
| _full_image_only_v9_names(tokenizer, config.data_seed) | ||
| if names_filter is None | ||
| else list(names_filter) | ||
| ) |
There was a problem hiding this comment.
Keep source names aligned with filtered datasets
For filtered mixtures, the returned datasets remain in the registry's flattened order, but names is taken in the caller-provided filter order. The default debug tier consequently pairs datasets ordered as text_vqa, chart_qa_weighted, tulu4 with names ordered as tulu4, text_vqa, chart_qa_weighted; MixtureDataLoader then records misleading _source_name values and attributes data-loading errors to the wrong source. Return the selected names alongside the datasets or derive them using the same flattened ordering.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed, and I should have answered this earlier (it was in the 11-11 review). Fixed in c332a9d: _build_mixture now takes the names from the registry order (_full_image_only_v9_names(), filtered by the requested set), the order build_image_only_v9_mixture returns its datasets in, so the debug tier now pairs text_vqa, chart_qa_weighted, tulu4 with their own names. Test added that builds the debug mixture with fake sources and checks names == [d.name for d in datasets]; it fails on the old code.
AkshitaB
left a comment
There was a problem hiding this comment.
Found three correctness issues in the new data-loading paths; inline comments describe the triggers and suggested fixes. Confirmed these with isolated executions of the relevant source definitions. Full tests were not run because the local Python environment lacks NumPy and PyTorch.
| :param index: Row index. | ||
| :param epoch: Source epoch; it seeds the row's RNG stream in place of the shared epoch. | ||
| """ | ||
| return get_example_with_skip(self, index, len(self), epoch) # type: ignore[arg-type] |
There was a problem hiding this comment.
[P2] Implement the epoch-aware path for GUISyn before adding the inherited get()
GuiSynDataset inherits EpochSeededExamples but only implements getitem, not _build. With continuous_stream=True, MixtureDataLoader now discovers this inherited get() and calls it for every GUISyn reference. Each call fails after 32 retries with AttributeError: GuiSynDataset has no attribute _build; the loader skips every example from this source and eventually exhausts its data-error allowance. Please implement _build(index, epoch) or an equivalent epoch-aware get() for GUISyn as part of this change.
There was a problem hiding this comment.
Confirmed and fixed in 5573654. GuiSynDataset now defines _build(index, epoch) (with __getitem__ delegating to it), so the inherited get() works in continuous-stream mode. I scanned the other nine EpochSeededExamples subclasses: GUISyn was the only one with neither _build nor get. Added a test that scans every subclass and fails if one inherits get() without a _build, and a GUISyn test that builds per explicit epoch, checks the element sample rotates, and checks the shared epoch is left alone. Both new tests fail on the old code with the AttributeError you described.
| return int(self.indices[index]) | ||
|
|
||
| def __getitem__(self, index: int) -> Any: | ||
| return self.get(index, 0) |
There was a problem hiding this comment.
[P2] Preserve the current epoch when indexing selected datasets
_SelectedDataset always passes epoch zero here and exposes no set_epoch(). The default non-continuous MixtureDataLoader advances sources through set_epoch() and then reads dataset[index], so wrapping an epoch-aware source in a row selection silently disables its epoch-dependent augmentation and annotation sampling. An isolated reproduction returns epoch zero after both epoch-1 and epoch-2 reshuffles. Please preserve/forward the current epoch in the wrapper and use it for getitem.
There was a problem hiding this comment.
Fixed in 5573654. _SelectedDataset now keeps an epoch: set_epoch() stores it and forwards it to the wrapped dataset when that has one, and __getitem__ uses it. An explicit epoch passed to get() still wins. Tests cover a base with get() and one that only tracks its own epoch via set_epoch (the case your reproduction hit).
| datasets_map = build_image_only_v9_datasets( | ||
| tokenizer, seed, max_sequence_length=max_sequence_length | ||
| ) | ||
| lengths = {name: len(datasets_map[name]) for name in datasets_map.keys()} |
There was a problem hiding this comment.
[P2] Avoid opening unrequested datasets when building a subset mixture
This comprehension instantiates every registered source before dataset_names is applied below. Consequently, the debug and single-source validation modes still require every image-only-v9 dataset to be installed: requesting only tulu4 fails immediately if an unrelated source is missing. This defeats the incremental validation workflow and incurs full-mixture initialization even for a small smoke test. Please obtain the lengths needed for weighting from separate metadata, or otherwise avoid opening unrequested sources while preserving the intended sampling rates.
There was a problem hiding this comment.
Fixed in 5573654. build_image_only_v9_mixture now opens only the groups that contain a requested source. A source's rate is its group's rate times its share of the group's size factors, so other groups' lengths cancel when the weights are renormalized over the subset; the weights are unchanged. A test checks that for three subsets the weights equal the old all-sources computation renormalized, and that only the needed groups are opened; requesting tulu4 alone now needs only its own group. The full mixture and the unknown-name error are unchanged.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5573654ea5
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if config.strict_annotations: | ||
| self.content_fingerprint = self._build_content_fingerprint() |
There was a problem hiding this comment.
Record FineVision fingerprints in non-strict mode
When a FineVision source with the default strict_annotations=False and no expected materialization pin is consumed by MixtureDataLoader(continuous_stream=True), this condition leaves content_fingerprint undefined. The loader consequently stores None for the source and accepts a checkpoint restore after the Arrow corpus or filtering configuration changes, even though the config documents the live Arrow fingerprint as the fallback resume identity. Build _build_content_fingerprint() independently of annotation strictness.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in fc91cba: every FineVision source that has a stable Arrow fingerprint (the pinned materialization one, else the live one) now gets a content_fingerprint, not only strict ones. A source with no stable fingerprint stays permissive and has none; a strict one still raises. Test added (it fails on the old code).
5573654 to
4982b4a
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4982b4af84
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if config.strict_annotations: | ||
| self.content_fingerprint = self._build_content_fingerprint() |
There was a problem hiding this comment.
Enforce strict annotations when constructing the dataset
When strict_annotations=True, this branch only creates a fingerprint and never calls validate_required_annotations(); a repo-wide search finds no production caller for that validator. Consequently malformed selected rows are not rejected up front as the config promises, and with the default skip_bad_rows=True they are silently replaced by later rows during training, defeating the fail-closed alignment subset contract. Invoke the validator while constructing a strict dataset, before exposing its fingerprint.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Partly addressed in fc91cba, differently from the suggestion. The strict scan (validate_required_annotations) is already called by the alignment pipeline (vision_alignment_perception.py), in the layer that stacks on this PR, so it is not unused. The real gap you point at is that a strict source with the default skip_bad_rows=True would silently replace a malformed row, so strict_annotations=True now raises a configuration error unless skip_bad_rows=False (which the pipeline already passes). I did not make the constructor run the scan itself: it reads every selected row's list lengths and text structs, so it would add that full pass to every build, including the tests and dry runs. Test added for the rejection and for a bad row now raising on access.
| "max_sequence_length": cfg.max_sequence_length, | ||
| "loss_token_weighting": cfg.loss_token_weighting, | ||
| "message_format": cfg.message_format, | ||
| "seed": cfg.seed, |
There was a problem hiding this comment.
Bind FineVision fingerprints to configured token IDs
For a strict FineVision source built through MultimodalMixtureConfig with non-default Molmo2TokenIds, changing the tokenizer revision or image-token assignment changes every serialized example but not this fingerprint because the payload records message_format while omitting cfg.token_ids. A continuous-stream loader can therefore accept a version-5 checkpoint and restore buffered references against a different token stream. Include the resolved token IDs in the fingerprint payload so exact-resume validation detects this change.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in fc91cba: the fingerprint payload now includes the resolved token_ids, so a changed tokenizer revision or image-token assignment changes the identity and a checkpoint's buffered references are not restored against a different token stream. Test added.
4982b4a to
fc91cba
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fc91cbaaa6
ℹ️ 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".
| datasets_map = build_image_only_v9_datasets( | ||
| tokenizer, seed, max_sequence_length=SEQUENCE_LENGTH | ||
| ) | ||
| lengths = {name: len(datasets_map[name]) for name in datasets_map.keys()} |
There was a problem hiding this comment.
Reuse the datasets already built for full-mixture names
When --mixture=image-only-v9 is selected, build_image_only_v9_mixture() has already constructed every source to compute its weights, but this helper creates a second lazy registry and line 224 dereferences every entry again. The production recipe therefore loads all source metadata and rebuilds expensive indexes twice before training, increasing startup time and peak memory for the full corpus; derive the names from the already-built mixture or directly from the submixture ordering instead.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 94496cf: _full_image_only_v9_names no longer takes a tokenizer or builds anything. It lists the submixture sources in order, skipping groups with no weight, which is the order build_image_only_v9_mixture returns its datasets in. A test checks the two orders match and that deriving the names opens no source.
AkshitaB
left a comment
There was a problem hiding this comment.
Found two issues. Both were validated with isolated reproductions. The targeted pytest run was blocked by a missing cached_path dependency; GPU training was not tested.
|
|
||
| cfg = self.config | ||
| rng = self.epoch_rng(index) | ||
| rng = sft_example_rng(cfg.seed, index, epoch, cfg.message_format) |
There was a problem hiding this comment.
[P2] Preserve epoch-dependent transcript sampling for the Qwen path
This replaces epoch_rng() with sft_example_rng(), whose default qwen3 path ignores epoch. For transcript or transcript_and_caption mode, an image with multiple transcripts now selects the same transcript every epoch, leaving the others unused. A focused reproduction selected all eight transcripts across 32 epochs with the previous RNG derivation, versus one with this path. Please preserve epoch-dependent sampling for the existing Qwen path. The existing transcript-rotation test calls epoch_rng() directly, so it does not exercise this regression in get().
There was a problem hiding this comment.
Confirmed and fixed in 94496cf, and it was wider than this one call. sft_example_rng returned the same stream in every epoch for the Qwen layout, which affected PixMo-Cap transcripts, the v1 points / count / CoSyn pointing-style choice, and FineVision. It now takes dataset_len and uses mm_olmo's per-epoch stride for Qwen, passed at all six call sites. At epoch 0 the stream is identical to before (tested against example_rng), so a run's first pass over the data is unchanged. New test through get() (the layer the loader calls, unlike the old one that used epoch_rng directly): a given epoch repeats its draw, and all eight transcripts are used across 32 epochs for both layouts. It fails on the old code for Qwen. I also found my earlier points test passed vacuously on this branch (the dataset hands _build_example a closure, so two calls always compared unequal); it now evaluates the closure and checks same-epoch determinism first, and fails on the old stream.
| if not strict_validation: | ||
| return example |
There was a problem hiding this comment.
[P2] Apply the sequence limit independently of split validation
This early return skips truncation whenever strict_validation=False, which the dataset callers derive from require_split (False by default). Setting max_sequence_length alone therefore has no effect: a focused call with 100 tokens and a limit of 10 returns all 100. Oversized examples can reach the collator without the branch-weight adjustment performed below; if the cut drops image tokens, collation raises outside the loader's data-error handling. Please apply configured truncation independently of the strict split/validation option.
There was a problem hiding this comment.
Fixed in 94496cf: _finalize_example now truncates whenever max_sequence_length is set; only the geometry validation and the metadata stay behind strict_validation. One existing test, test_serialized_examples_preserve_legacy_non_strict_behavior, asserted exactly the old behaviour (a limit of 4 leaving 6 tokens), so I changed it to pin what stays legacy (no validation, no metadata) and added test_truncation_applies_without_strict_validation, which fails on the old code and also checks that a cut through an image block raises.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 94496cf763
ℹ️ 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".
| get = getattr(dataset, "get", None) if self.continuous_stream else None | ||
| ex = get(example_idx, source_epoch) if get is not None else dataset[example_idx] |
There was a problem hiding this comment.
Pass the training epoch to ordinary mixture sources
In the non-continuous path used by Molmo2-Stage2.py, this disables the epoch-aware get(index, epoch) interface and instead calls dataset[index], while the generated references always carry source epoch 0. Several selected sources—including PixMoPointsDataset, PixMoCountDataset, and CoSynPointDataset—vary prompts, styles, branch selection, and high-resolution preprocessing only through get and do not implement set_epoch, so every trainer epoch repeats the same augmentation for each row despite reshuffle() advancing the epoch. Pass the current loader epoch through these references and call get, or make every affected source's __getitem__ honor set_epoch.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in c332a9d. The default (non-continuous) loader advances sources with set_epoch() and then calls dataset[index], but PixMoPointsDataset, PixMoCountDataset, CoSynPointDataset and FineVisionDataset implemented __getitem__ as get(i, 0) with no set_epoch, so each trainer epoch repeated the same per-row augmentation. They now inherit EpochSeededExamples and __getitem__ is get(i, self._epoch). Tests: a points test that goes through set_epoch then ds[0] and compares with get(0, 1) and with epoch 0, and a scan that fails for any source with an epoch-taking get but no set_epoch (scoped to sources the default loader can use: the alignment and mid-training sources in the layers above only run with continuous_stream=True, which calls get(index, epoch) itself). Both fail on the old code.
AkshitaB
left a comment
There was a problem hiding this comment.
Re-reviewed commit 94496cf. The two findings from my original review (PixMo-Cap transcript rotation and truncation independent of strict split validation) are fixed. These two previously reported issues remain reproducible:
-
[P2] Pass the training epoch to ordinary mixture sources. In the non-continuous mode used by the stage-2 recipe, the loader bypasses
get(index, epoch)and usesdataset[index]. Points, Count, and CoSyn implement that asget(index, 0)and have noset_epoch, so each training epoch repeats the same per-row augmentation choices. An isolated reproduction confirms that a loader at epoch 3 still passes epoch 0 to these sources. Propagate the loader epoch or make these sources honorset_epoch. Existing inline finding. -
[P2] Keep filtered source names aligned with returned datasets.
_build_mixturetakes names from filter order, while the mixture builder returns datasets in registry order. Fordebug, the datasets are[text_vqa, chart_qa_weighted, tulu4]but the assigned names are[tulu4, text_vqa, chart_qa_weighted], misattributing source diagnostics and loading errors. Derive names using the same ordering as the returned datasets. Existing inline finding.
Both remaining issues were confirmed with focused reproductions. Full pytest execution was unavailable because the local environment lacks pytest. Linking the existing inline threads here to avoid duplicating them.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c332a9d2af
ℹ️ 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".
| ).encode() | ||
| ) | ||
| digest.update(indices.astype("<i8", copy=False).tobytes()) | ||
| self.content_fingerprint = digest.hexdigest() |
There was a problem hiding this comment.
Do not advertise an unpinned selection fingerprint
When the wrapped dataset exposes neither content_fingerprint nor fingerprint, this still publishes a stable-looking digest based only on its config and selected indices. A continuous-stream MixtureDataLoader will therefore accept a version-5 checkpoint after the underlying corpus changes in place, then restore buffered references against different content despite promising content-validated resume. Only expose the wrapper fingerprint when the base dataset supplies a stable fingerprint; otherwise leave the selection unpinned as the base source was.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c3aef42. _SelectedDataset now publishes a content_fingerprint only when its base source provides one; over an unpinned base it advertises none, so the loader sees the selection as unpinned like the base. With a pinned base the digest is unchanged (base fingerprint, config and the selected indices). Tests: the wrapper's fingerprint changes with the base's identity and with the selection, and over an unpinned base there is no fingerprint (the loader's helper returns None). The unpinned test fails on the old code.
|
Thanks for the re-review of 94496cf. Both remaining findings are fixed in c332a9d (branch tip is c332a9d); sorry the answers were only on the linked threads, not here.
Your two earlier findings (PixMo-Cap transcript rotation, truncation independent of strict validation) were fixed in 94496cf, as you confirmed. I have re-requested your review. |
…izes (from vision) Brings the stage-1 data pipeline up to vision's current state and adds the stage-2 recipe: epoch-aware resumable mixture loading, document layout, configurable mixtures, the image_only_v9 stage-2 mixture, multi-image datasets, Molmo2-Stage2.py, and the 0.6B/1.7B model sizes. OLMoDDP / alignment training and the eval suites follow in later PRs.
…r truncate over-long multi-image examples, configurable collator patch id
…loader's epoch, subset mixtures open only the needed groups
…s; strict sources must not skip bad rows
…is independent of strict validation, Stage 2 derives its names from the registry
…e 2 names follow the returned datasets' order
…e a content fingerprint
c332a9d to
c3aef42
Compare
…minutes of CI time
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Heads-up on the last two commits, both CI-only:
Why: the CPU |
Summary
PR 5 of 7 for moving the Molmo2 reproduction from the long-lived
visionbranch ontomain. #913 (stage-1 recipe) is merged, so this targetsmaindirectly; the diff here is only this PR's change. This PR brings the multimodal data pipeline up tovision's current state and adds the stage-2 recipe, plus the Qwen3-0.6B / 1.7B model sizes:mixture_data_loader,alignment.py,mixture_weights,packing,rng): per-source epochs (get(index, epoch)), configurableMultimodalMixtureConfig/MultimodalSourceConfigmixtures, loader state that resumes mid-epoch.document_layout,qwen3_layout,molmo2_tokens:Molmo2TokenIds,prepare_molmo2_tokenizer): the releasedqwen3layout and adocumentlayout, selected per source.sft_common,pixmo_cap,message_sequence,collator):truncate_example(..., recompute_root_subsegments=...)andtruncate_for_format;sft_example_rng.vision:pixmo_points,pixmo_points_v2,finevision,fs_cache, and small updates to the OCR, academic and text-rich sources.Molmo2-Stage2.py, theimage_only_v9mixture, multi-image datasets,mm_olmo_loader, and thesft_demomode ofPixMoCapDataset.MultimodalLMConfig.molmo2_0_6B()/molmo2_1_7B()and--model_size=0.6b|1.7binMolmo2-Stage1.py.About 5.4k source lines and 3.7k test lines in 56 files. Everything is opt-in; existing behaviour on
maindoes not change.Review map
Reading every file closely is not necessary.
Read closely
data/multimodal/mixture_data_loader.pyget(index, epoch). The most behaviour-sensitive file in the PR.data/multimodal/sft_common.pytruncate_example(rejects cutting any image-structural token; rescales branch weights only whenrecompute_root_subsegments=True) andtruncate_for_format. Replaces the weighting-aware version added in #912's review; same behaviour,vision's API.data/multimodal/pixmo_cap.pytruncate_example(the local copy that always rescaled is gone);sft_demonow truncates;__getitem__uses the dataset's current epoch.data/multimodal/packing.py,collator.py<im_patch>tokens (from #912's review).scripts/train/Molmo2-Stage2.pynn/vision/multimodal.py,molmo2_tokens.pyvision'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 totext_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
PerGroupScheduler, weighted CEWith PRs 6 and 7,
mainreproduces everything onvision, apart from the intentional divergences below.Why this is a separate PR
Does this change anything on
main/ the text side?No. This PR adds files under
data/multimodal/,nn/vision/andscripts/;nn/transformer,optim,trainand 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.
sft_example_rngvaries Qwen-layout streams with the epoch (epoch 0 is the unchanged stream, so first passes are identical). Points, Count, CoSyn and FineVision honorset_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-takinggetbut noset_epoch(the alignment and mid-training sources run withcontinuous_stream=Trueand are excluded).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'stoken_ids.strict_annotations=Truerequiresskip_bad_rows=False; a row selection over an unpinned source advertises no fingerprint.Intentional divergences from
visionWhere
visionandmaindiffer on purpose:multimodal_lm_state_dict_to_hf) and nooutput_vocab_sizelogit masking: both were removed in [Multimodal 1/4] HF Molmo2 loader, flex attention, split-vocab embedding #910's review. Nothing onvisioncalls either.mypy src/passes (annotations in tests and the stage-2 script, an undefinedMolmo2TokenIdsannotation insft_common, which was a latent lint error onvision).vision'smultimodal.pyand 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 onmainon the dev box. ruff, black, isort andmypy src/(CI config) are clean.package_import_testruns 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, 0.6B, 2 nodes, 2000 steps, this PR's code) vs thevisionreference runmolmo2-stage1-0p6b-v3-50k-20261023: windowed mean train CE, 2026-10-25.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.