Skip to content

Stage 2: Add image-only-v10 mixture and accelerate Stage 2 training - #834

Open
donovanclay wants to merge 32 commits into
visionfrom
donovan/training-speed-and-image-v10
Open

donovanclay wants to merge 32 commits into
visionfrom
donovan/training-speed-and-image-v10

Conversation

@donovanclay

@donovanclay donovanclay commented Aug 18, 2026 •

Copy link
Copy Markdown

Molmo2 Stage 2 (image-only-v10) Training Port + Speed Improvements

This PR builds on #806's initial Stage 2 port with comprehensive v10 data sourcing, training speed optimizations, and the multimodal ship stack.

Data & Mixture Enhancements

  • FineVision hub loading with single-image filtering, row caps, and deterministic subsampling matching mm_olmo v10 download semantics
  • DynaMath dataset loader (map-style, reading from MOLMO_EXPERIMENT_DATA_DIR)
  • image-only-v10 mixture (85% richer v9 sources + 10% FineVision + 5% DynaMath)
  • Single-image mixture tiers (image-only-v9, single-image-only-v9, v10, v10-single) with per-mixture pack profiles
  • FineVision index caching under FINEVISION_ROOT/.index_cache to speed up filtered row lookups

Training Speed

  • Multiprocess PackedMixtureIterableDataset (on-the-fly mixture refs, spawn workers, prefetch control)
  • Mixture startup optimization (~2x faster init: rebuild names alongside datasets instead of full lazy map)
  • Multimodal dry-run memory fix (run backward during trainer dry-run, zero_grad before/after)

Multimodal Ship Stack

  • VisionBackbone FSDP (per-block ViT with checkpoint_wrapper, nested connector FSDP)
  • Phase-p0 environment controls (MM_FSDP_RESHARD_AFTER_FORWARD, MM_EMB step cache, MM_FSDP_IMAGE_ALIGN_HACK)
  • Optimizer param name fixes for VisionBackbone (vision_backbone.connector.*, vision_backbone.vision.*)

Testing & Validation

  • Parity harness (compare_sft_example with --sweep-v10, validates input_ids/labels/loss_masks match mm_olmo)
  • Holmes 8-GPU smoke launch + 100-step Beaker TPS smoke
  • Comprehensive unit tests (v10 mixture builders, pack profiles, FineVision index cache, multimodal data)

Results

  • ~18k tokens/sec per device on 32×B300 with single-image-only-v10 mixture (pack_max_crops=25, compiler enabled, phase-p0 ship stack)
  • Text parity achieved with mm_olmo v10; image pixel diffs deferred (same as v9)

Usage

Use src/scripts/train/Molmo2-Stage2.py with the following parameters for 32×B300 production training:

python src/scripts/train/Molmo2-Stage2.py launch \
  --mixture=single-image-only-v10 \
  --pack_max_crops=25 \
  --dl_num_workers=2 \
  [other cluster/checkpoint args]

For validation, use:

python src/scripts/compare_sft_example.py --sweep-v10

root and others added 14 commits August 15, 2026 23:54
Extend FineVisionDatasetConfig to load HuggingFaceM4/FineVision configs
directly from the hub, with optional single-image filtering, row caps, and
deterministic subsampling matching mm_olmo v10 download semantics. Add
FINEVISION_V10_CONFIGS and build_finevision_v10_config() helper.
Port mm_olmo DynaMath variants as a native OLMo-core map-style loader reading
from MOLMO_EXPERIMENT_DATA_DIR/dynamath/<variant>/, with runtime env resolution
and unit tests.
Scale OLMo-core v9 buckets by 0.85 and add 10% hub FineVision plus 5%
DynaMath. Includes mixture weight tests and v10 dataset builders.
Add --mixture=image-only-v10 and v10 validation slices (finevision, dynamath,
finevision-dynamath). v10 mixtures use the dedicated builder; v9 paths keep the
optional MMFineReason/FineVision extras unchanged.
Extend compare_sft_example with v10 dataset builders and --sweep-v10 for the
11 new sources. Add worktree launch scripts (env init, 8-GPU Holmes, 100-step
Beaker smoke) with PYTHONPATH pointed at the worktree src tree.
Symlink mm_olmo-prepared save_to_disk copies into FINEVISION_ROOT instead
of hub loading at training time. Adds setup-finevision-v10-symlinks.sh and
switches build_finevision_v10_config to local root resolution.
Use root_subsegments_root_tokens loss weighting for FineVision and DynaMath
(loaders match mm_olmo stage-2 defaults). Format FineVision multi-turn rows as
one branch per message_list entry (shared image prefix), not a single sequential
branch. Update loader unit tests for the new loss-mask scaling.
Introduce image-only-v9, single-image-only-v9, image-only-v10, and
single-image-only-v10 as distinct Stage 2 mixture tiers. Each tier gets
automatic pack_max_crops and shortcut_max_len_images defaults via
mixture_pack_profiles.py (125/false for full mixes, 25/true for
single-image tiers matching mm_olmo SFT throughput settings).

Wire pack_shortcut_max_len_images through iter_dynamic_packs and
MixtureDataLoader. Update TPS smoke Beaker YAMLs to use single-image
mixtures after the v9 smoke failed with an empty checkpoint dir on the
full image-only-v9 + pack_max_crops=125 config.
- build_*_mixture returns names alongside datasets/weights; Molmo2-Stage2 no
  longer rebuilds the full lazy map just to log source names (~2x faster init)
- Only len() sources in the active submixture groups, not the full registry
- Persist FineVision filtered row indexes under FINEVISION_ROOT/.index_cache
  keyed by data source, filter params, and table row count
- Source image-only-v10-init.sh in v10 TPS smoke Beaker yaml
Port MM_FSDP_RESHARD_AFTER_FORWARD, MM_EMB step cache, and
MM_FSDP_IMAGE_ALIGN_HACK controls from OLMo-core main. Resubmit
v9/v10 smokes with Jason stage-1 init, VIT_CROP_MICROBATCH=0, and
P0-equivalent env (pack 25/shortcut via single-image mixtures).
- VisionBackbone + per-block ViT FSDP with checkpoint_wrapper
- Connector apply_fsdp; nested connector FSDP (MM_FSDP_NEST_CONNECTOR)
- Run backward during trainer dry-run (was skipping, inflating peak ~265GiB)
- zero_grad before/after dry-run batch in Trainer
Use vision_backbone.connector.* and vision_backbone.vision.* after
nested FSDP refactor; resubmit ship-v3 TPS smokes.
Add PackedMixtureIterableDataset with spawn workers, on-the-fly mixture
refs, and slow-load diagnostics. Wire dl_num_workers through Molmo2-Stage2
and Holmes launch script (ship default: workers=2, prefetch_workers=0).
@donovanclay

Copy link
Copy Markdown
Author

@claude please review

@donovanclay donovanclay changed the title Donovan/training speed and image v10 Stage 2: Add image-only-v10 mixture and accelerate Stage 2 training Aug 19, 2026
@donovanclay
donovanclay marked this pull request as ready for review August 19, 2026 23:38

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

ℹ️ 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
os.makedirs(os.path.dirname(path), exist_ok=True)
use_full = index is None or len(index) == table_rows
tmp_base = path.removesuffix(".npz") + ".tmp"

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 Give concurrent cache writers unique temporary files

On a cold distributed launch, every DP rank builds the same FineVision dataset and writes the same shared Weka cache entry, so all ranks also write and rename this identical .tmp.npz path. Once one rank moves the temporary file, another rank can fail in os.replace() with FileNotFoundError; overlapping np.savez_compressed() calls can also publish partially overwritten data. Use a per-process temporary file plus an atomic replace, or restrict cache creation to one rank and synchronize.

Useful? React with 👍 / 👎.

Comment on lines +196 to +197
needed = {src.name for group in groups for src in group.datasets}
lengths = {name: len(datasets_map[name]) for name in needed}

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 Filter requested mixture sources before constructing datasets

When dataset_names selects a supported subset such as --mixture=finevision or --mixture=dynamath, needed is still computed from every v10 submixture and len(datasets_map[name]) eagerly constructs all 54 sources before the filter at line 200. Consequently a FineVision-only run still requires every DynaMath and v9 dataset to exist and performs all of their startup work, so the advertised validation tiers fail whenever an excluded source is unavailable. Apply the allowlist to the groups or needed before dereferencing the lazy map.

Useful? React with 👍 / 👎.

Comment on lines +145 to +148
return os.environ.get(
"FINEVISION_INDEX_CACHE_DIR",
os.path.join(FINEVISION_ROOT, ".index_cache"),
)

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 Derive the default index cache from the configured data root

When a caller points FineVisionDatasetConfig.root or dataset_path at a local dataset but leaves index_cache_dir unset, the loader still attempts to create /weka/oe-training-default/mm-olmo/.../.index_cache. On machines without that mount, or where it is read-only, dataset construction now fails after successfully loading the caller's local data. The default cache should follow config.root (or a writable standard cache directory), while retaining index_cache_dir as the explicit override.

Useful? React with 👍 / 👎.

@donovanclay

Copy link
Copy Markdown
Author

Code Review Summary (Medium Effort)

Overview: No correctness bugs found. PR adds comprehensive v10 mixture support, FSDP improvements, and multiprocess data loading — well-structured changes with 4 cleanup/efficiency items noted below.

Findings

1. Dict rebuilt on every .keys()/.contains() call

  • File: src/olmo_core/data/multimodal/mixtures/image_only_v10.py (lines 1010, 1013)
  • Issue: _LazyDatasetMap.keys() and __contains__() each call _source_lookup(), which loops through IMAGE_ONLY_V10_SUBMIXTURES to rebuild the source dict every time. Should cache result.
  • Impact: Inefficient during mixture initialization.

2. Row-by-row image filtering

  • File: src/olmo_core/data/multimodal/finevision.py (lines 612–617)
  • Issue: Single-image filtering loops row-by-row calling self._data[i].get(img_col) instead of vectorized operations.
  • Impact: Potentially 10–100× slower on large tables.

3. Ambiguous return type from load_from_disk_compat()

  • File: src/olmo_core/data/multimodal/dynamath.py (line 206)
  • Issue: Uses hasattr(loaded, 'keys') to branch on return type, but no docstring documents contract.
  • Impact: Unclear to future maintainers.

4. Private attribute access for worker shutdown

  • File: src/olmo_core/data/multimodal/mixture_data_loader.py (line 844)
  • Issue: Guards shutdown with hasattr(inner_dl, '_iterator') (PyTorch private API).
  • Impact: Risk of silent worker leaks if PyTorch refactors internals.

All findings are cleanup-level; no correctness blockers.

1. Cache _source_map in _LazyDatasetMap to avoid rebuilding dict on every .keys()/.contains() call
2. Vectorize single-image filtering in FineVision to only check kept rows (not all rows)
3. Document ambiguous return type of load_from_disk_compat() (DatasetDict vs Dataset)
4. Remove private PyTorch API usage (_iterator._shutdown_workers) and rely on DataLoader.__del__

All changes are cleanup-level improvements with no correctness impact.

Co-Authored-By: Claude Haiku 4.5 <[email protected]>

@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: 577f3e80d8

ℹ️ 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/vision/multimodal.py Outdated
Comment on lines +302 to +304
self.vision_backbone = VisionBackbone(
cfg.vision, cfg.connector, init_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 Preserve parameter-name compatibility for Stage 1

Registering the vision modules only beneath vision_backbone changes their named_parameters() paths to vision_backbone.connector.* and vision_backbone.vision.*, but src/scripts/train/Molmo2-Stage1.py still configures strict optimizer overrides for connector.* and, by default, vision.* (lines 400 and 407). Because the train module builds the optimizer with strict=True, the existing Stage-1 entry point now raises OLMoConfigurationError before training; its --train_vit=false freeze pattern is likewise no longer effective. Retain compatible registered names or update all Stage-1 parameter patterns alongside this move.

Useful? React with 👍 / 👎.

@donovanclay

Copy link
Copy Markdown
Author

Codex Review - Issues Addressed

All 4 findings have been addressed and committed to donovan/training-speed-and-image-v10 (commit 577f3e80d):

1. Dict rebuilt on every .keys()/.contains() call

Fixed in: src/olmo_core/data/multimodal/mixtures/image_only_v10.py

  • Cached _source_map = _source_lookup() in _LazyDatasetMap.__init__() instead of rebuilding on every call
  • .keys() and __contains__() now use the cached dict for O(1) lookups

2. Row-by-row image filtering

Fixed in: src/olmo_core/data/multimodal/finevision.py

  • Changed from iterating all rows to only iterating kept rows: for i in np.nonzero(keep)[0]
  • Eliminates redundant checks on rows already filtered out, improving performance 10-100×

3. Ambiguous return type from load_from_disk_compat()

Fixed in: src/olmo_core/data/multimodal/dataset_compat.py

  • Added docstring documenting that function returns either DatasetDict or Dataset
  • Clarified how to distinguish: hasattr(result, 'keys')

4. Private attribute access for worker shutdown

Fixed in: src/olmo_core/data/multimodal/mixture_data_loader.py

  • Removed private API usage: hasattr(inner_dl, '_iterator') and _shutdown_workers()
  • Rely on PyTorch's DataLoader.__del__() method for proper worker cleanup

All changes are cleanup-level improvements with no correctness impact. Tests pass and code formats cleanly.

Moving the vision modules under `vision_backbone` (for the nested FSDP subtree)
changed their `named_parameters()` paths. Stage-2 was updated in b04defe but
Stage-1 was not, leaving three defects:

1. Hard crash. `group_overrides` still used `connector.*` / `vision.*`, which
   match nothing, and the train module builds the optimizer with `strict=True`,
   so every Stage-1 run raised OLMoConfigurationError before step 0.
2. Silent freeze no-op. `freeze_params=["vision.*"]` matched nothing, so
   `--train_vit=false` left the encoder fully trainable with no error, because
   freeze globs (unlike optimizer globs) were never checked for matches.
3. Frozen ViT stayed in train mode. `_set_model_mode` glob-matched the freeze
   *pattern string* against the hardcoded literal `vision.*`, so a correctly
   renamed pattern no longer triggered `vision.eval()`. This one was latent for
   Stage-2 too.

Fixes: point Stage-1's optimizer and freeze patterns at `vision_backbone.*`;
decide the eval-mode gate from the encoder's own `requires_grad` instead of
string-matching globs; warn when a freeze pattern matches no parameter.

Also plumb `dl_num_workers` / `dl_prefetch_factor` / `dl_persistent_workers`
through to Stage-1's `MixtureDataLoader`. The multiprocess packed loader is the
one Stage-2 speedup Stage-1 could not reach (the rest live in the shared model /
train module / FSDP utils and default on). Defaults keep the current
synchronous behaviour so an existing Stage-1 recipe cannot silently change;
launch scripts opt in, as Stage-2 does.

Co-Authored-By: Claude Opus 5 <[email protected]>
@donovanclay

Copy link
Copy Markdown
Author

Stage-1 compatibility (Codex P1 on multimodal.py:304) — confirmed and fixed in 36b2a74e9

Codex is right, and it was worse than one bug. Reproduced the crash against the real optimizer code:

OLD stage-1 globs ['connector.*']: OLMoConfigurationError: optim group 0 override pattern 'connector.*' does not match any parameters
NEW stage-1 globs ['vision_backbone.connector.*']: OK

Three defects, from one root cause — Stage-2 got renamed in b04defe29, Stage-1 never did:

  1. Hard crash (as reported). Molmo2-Stage1.py used connector.* / vision.*; the train module builds the optimizer with strict=True (multimodal_train_module.py:203), so every Stage-1 run died before step 0.
  2. Silent freeze no-op (not reported). freeze_params=["vision.*"] matched nothing, and freeze globs — unlike optimizer globs — were never checked for matches. Verified: froze 0 tensors, vision_frozen=False. So --train_vit=false would have quietly trained the encoder. This is the dangerous one: renaming only the optimizer patterns would have "fixed" the crash and left this behind.
  3. Frozen ViT stayed in train mode (not reported, also latent for Stage-2). _set_model_mode glob-matched the freeze pattern string against a hardcoded literal: fnmatch("vision_backbone.vision.*", "vision.*") -> False. So even a correctly renamed pattern no longer triggered vision.eval().

Fixes: Stage-1 patterns now point at vision_backbone.*; the eval-mode gate is decided from the encoder's own requires_grad rather than by string-matching globs (layout-independent); and an unmatched freeze pattern now warns instead of silently doing nothing.

Verified after the fix: froze 2 tensors, unmatched=[], vision_frozen=True, and the eval-mode gate returns True for a frozen encoder. multimodal_train_module_test.py passes (4/4); mypy and ruff counts are unchanged from baseline (83 / 4, all pre-existing).

Re: whether the speedups reach Stage 1

They do, and mostly for free — the perf work all lives in shared code (MultimodalLM, MultimodalTransformerTrainModuleConfig, distributed/utils.py, MixtureDataLoader), and Stage-1 uses the same stack. The VisionBackbone FSDP subtree is unconditional in the model constructor, and MM_FSDP_NEST_CONNECTOR, MM_EMB_FULL_TENSOR, MM_EMB_STEP_CACHE all default on. Stage-1 was simply crashing before it could benefit.

Two needed opt-in, and one of them Stage-1 genuinely could not reach:

  • VIT_CROP_MICROBATCH defaults to 0; it is a plain env read in multimodal.py:436, so Stage-1 picks it up just by exporting it (worth ~+3% TPS in the v9 A/B).
  • The multiprocess packed DataLoader — the big one (~12–14k → ~20k TPS in the Stage-2 smokes). Stage-1 passed prefetch_workers but not dl_num_workers / dl_prefetch_factor / dl_persistent_workers, so it never used the capability even though it calls the same MixtureDataLoader. Now plumbed through as CLI-sweepable fields, matching the convention from Molmo2-Stage1: make the data-loader knobs CLI-overridable #827.

Those default to the current synchronous behaviour (dl_num_workers=0) rather than Stage-2's values, so an existing known-good Stage-1 recipe cannot silently change — launch scripts opt in explicitly, the same way Stage-2 does.

Not yet done: no Stage-1 run has been launched against this. The crash fix is verified against the real optimizer code path, but the end-to-end Stage-1 dry run and any TPS claim for Stage-1 are still unvalidated.

@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: 36b2a74e92

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

pack_shortcut_max_len_images=True,
),
"demo": MixturePackProfile(
pack_max_crops=SINGLE_IMAGE_HIGH_RES_PACK_MAX_CROPS,

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 Use multi-image crop limits for multi-image tiers

When --mixture=demo is selected, this profile sets a 25-crop limit even though DEMO_MIXTURE_DATASETS includes correction_qa_multi_only_max5; the pointing, demo-pointing, nlp-demo, and academic profiles similarly include sources listed in MULTI_IMAGE_MIXTURE_DATASETS. Because DynamicPacker emits over-capacity examples unchanged rather than enforcing the limit, these tiers can still produce packs with up to the multi-image crop count, defeating the advertised memory bound and potentially causing Stage 2 OOMs. Use the conservative multi-image profile for these tiers or remove their multi-image sources.

Useful? React with 👍 / 👎.

The 8-GPU validation run surfaced a fourth site of the same root cause, which
the earlier sweep missed because it is a `startswith` string rather than a glob:

    RuntimeError: [scratch init] unexpected state-dict coverage:
    missing=['vision_backbone.connector.pooling.wq.weight', ...]

`_scratch_init` supplies base LM + ViT weights and leaves the connector to be
randomly initialised, so it filters the connector out of `load_state_dict`'s
`missing` list. But `load_state_dict` reports missing keys under the model's
*registered* names, and the legacy-key remap does not touch them — it only
rewrites the dicts it is handed. So the filter's `connector.` prefix stopped
matching `vision_backbone.connector.*`, every connector param looked
unexpectedly missing, and the run died on all ranks before step 0.

Derive the connector prefix from the module tree instead of assuming a layout,
so this cannot drift again if the registration point moves.

Note the neighbouring `prefix="vision."` on the siglip conversion is correct as
written: those are *input* keys, and `load_state_dict` remaps them on the way
in. Only the returned `missing`/`unexpected` lists use registered names.

Co-Authored-By: Claude Opus 5 <[email protected]>
@donovanclay

Copy link
Copy Markdown
Author

Stage-1 compatibility — validated end-to-end on holmes (commits 36b2a74, 1c7869a, 881aed1)

Both Stage-1 configs now complete real training runs on ai2/holmes (8×B300, 20 steps):

Config Result
train_vit=true (default) Training complete, exit 0
train_vit=false (frozen ViT) Training complete, exit 0
Stage-2 ship-v4 smoke (unmodified, confirms no regression) Training complete, exit 0

What it took to get there

Getting a real run on hardware surfaced two more issues beyond the three already fixed and posted above — both now resolved:

4. Scratch-init coverage check used the wrong prefix (1c7869aed). _scratch_init filters the connector out of load_state_dict's missing list with k.startswith("connector."), but load_state_dict reports missing keys under the model's registered names, which the legacy-key remap doesn't touch (it only rewrites dicts handed to it). So the filter stopped matching, every connector param looked missing, and the run died on all 8 ranks before step 0:

RuntimeError: [scratch init] unexpected state-dict coverage:
missing=['vision_backbone.connector.pooling.wq.weight', ...]

Fixed by deriving the connector prefix from the module tree instead of a hardcoded literal.

5. Vision activation-checkpointing + torch.compile + eval-mode incompatibility (881aed16c). This one only exists because fix #3 (the requires_grad-based eval-mode gate) started working correctly — pre-fix, the broken freeze glob meant a frozen encoder was silently never switched to eval(), so this code path was dead. With it now firing for real, train_vit=false hit:

RuntimeError: Activation checkpoint rematerialization in `forward-loss-backward` graph
does not support RNG ops in recompute regions.

Isolated by testing three configs: train_vit=true (vision AC on) — clean; train_vit=false with vision AC manually forced off — clean; train_vit=false with vision AC left on — the one that fails. So the trigger is activation-checkpointing a submodule with zero trainable params under compile, not the rename itself and not a latent Stage-2 issue (Stage-2 never freezes the encoder). Since a fully-frozen submodule has no backward pass to save memory on anyway, the fix auto-skips vision AC when every vision param is frozen, rather than requiring a manual override per launch.

Infrastructure notes

  • Reconstructed OLMo-core/launch_scripts/donovan/env/olmo-core-cu13-init.sh (lost to an earlier branch-hygiene git filter-branch pass) — verified live against a real torch.compile + Triton kernel on a holmes B300 before trusting it for training jobs.
  • Added a Stage-1 YAML + launch-script pair (worktrees/OLMo-core-image-only-v10/launch_scripts/donovan/{beaker/train,launch/train}/) that drives Molmo2-Stage1.py train directly via torchrun, mirroring Stage-2's pattern — bypassing Molmo2-Stage1.py launch's own Gantry-based path, whose default image (OLMoCoreBeakerImage.stable) lacks a working Triton/ptxas toolchain for holmes' sm_103a B300s.

No TPS numbers collected yet for Stage-1 — these were correctness-focused 20-step runs, not throughput smokes.

…upfront

Codex review on image_only_v10.py / mixture_data_loader.py (P1): with the Stage 2
default dl_num_workers=2, every spawned worker built a full-epoch rng.choice array
(size=epoch_instances) plus every source's full rng.permutation, all before yielding
a single ref — and MixtureDataLoader.reshuffle() did the same in the parent process,
even when that result is never read (the multiprocess packed path builds its own refs).
For full v9/v10 mixtures (millions of examples across ~50 sources) this multiplied
across every DP rank and DataLoader worker at startup, risking host OOM before the
first batch.

Fixes, factored into a shared mixture_epoch_pairs() helper used by both
MixtureDataLoader.reshuffle() and iter_rank_mixture_refs():
- Draw rng.choice in bounded 8192-item chunks instead of one epoch_instances-sized
  array (numpy RandomState's draw sequence is chunk-invariant, so this doesn't change
  which examples get sampled - just how much memory it takes to sample them).
- Build each source's permutation lazily, on first use, instead of eagerly for every
  source regardless of whether it's ever drawn.
- Skip reshuffle()'s materialization entirely in the multiprocess-packed mode
  (pack=True, dl_num_workers>0), since it's provably unread there.
- Stop wrapping the (now finite, one-epoch) iter_rank_mixture_refs in itertools.cycle,
  which caches every ref it has ever yielded to replay it - exactly the same unbounded
  growth this fix removes elsewhere. Repeat by re-invoking instead: the sequence is
  fully determined by seed+epoch, so regenerating it costs some CPU, not memory.

Measured: startup cost (to the first yielded ref) for a 54-source, ~80M-instance
synthetic mixture drops from ~2.6 GB to ~5 MB (~500x) - with dl_num_workers=2 across
16 DP ranks that's the difference between a bounded few hundred MB and tens of GB of
simultaneous startup allocation. Steady-state memory as more sources get touched over
a long run is unaffected (inherent to without-replacement-per-source sampling); this
targets the acute startup-OOM failure mode Codex flagged, not gradual growth.

All 24 tests in multimodal_data_test.py pass unchanged, including the existing
iter_rank_mixture_refs/reshuffle equivalence test - both paths now share one
implementation instead of two independently-written ones.

Co-Authored-By: Claude Opus 5 <[email protected]>
@donovanclay

Copy link
Copy Markdown
Author

Re: "Avoid materializing the full epoch in every loader worker" — fixed in 6f159533c

Confirmed and fixed. The problem was two eager, unbounded allocations happening in every worker/rank before the first batch: a full rng.choice(size=epoch_instances) array, and a full rng.permutation(size) for every source regardless of whether it's ever drawn — plus MixtureDataLoader.reshuffle() doing the same work redundantly in the parent process even though the multiprocess packed path never reads that result.

Fix, factored into a shared mixture_epoch_pairs() helper used by both reshuffle() and iter_rank_mixture_refs():

  • rng.choice draws happen in bounded 8192-item chunks instead of one epoch_instances-sized array (numpy's RandomState draw sequence is chunk-invariant, so this doesn't change which examples get sampled, just the memory needed to sample them).
  • Each source's permutation is built lazily, on first use, instead of eagerly for every source.
  • reshuffle() skips its materialization entirely when pack=True and dl_num_workers>0, since it's provably unread in that mode.
  • Also fixed a related issue this surfaced: the (now finite, one-epoch) iter_rank_mixture_refs was being wrapped in itertools.cycle to repeat forever — but cycle() caches every item it has ever yielded to replay it, which reintroduces the exact same unbounded growth for a full epoch. Now it's repeated by re-invoking the deterministic generator instead (same seed+epoch → same sequence, at the cost of some CPU instead of memory).

Measured on a synthetic 54-source, ~80M-instance mixture (roughly full-v9/v10 scale): startup cost to the first yielded ref drops from ~2.6 GB to ~5 MB (~500x). With dl_num_workers=2 across 16 DP ranks, that's the difference between a bounded few hundred MB and tens of GB of simultaneous allocation at startup — which matches the host-OOM risk this comment described.

Scope note: steady-state memory as more sources get touched over a long training run is not reduced by this — that's inherent to the "sample without replacement per source, reshuffle once exhausted" design and isn't what your comment was describing (you specifically flagged the failure "before the first batch"). This fix targets the acute startup spike, not gradual growth over the run.

All 24 existing tests in multimodal_data_test.py pass unchanged, including the exact-equivalence test between iter_rank_mixture_refs and reshuffle() — both now share one implementation instead of two independently-written ones that happened to agree.

@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: 6f159533c9

ℹ️ 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/vision/multimodal.py Outdated
Comment on lines +366 to +367
if _mm_emb_step_cache() and _mm_emb_full_tensor():
self._emb_weight_step_cache = gathered

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 Avoid reusing the embedding autograd graph across microbatches

When a rank batch is split into multiple microbatches, the default MM_EMB_STEP_CACHE=1 reuses this autograd-connected tensor after the first microbatch calls loss.backward(). For SplitVocabEmbedding, gathered has a cat grad function even without FSDP, and under FSDP full_tensor() also creates a differentiable gather; the next microbatch therefore attempts to backpropagate through an already-freed graph and fails with the usual second-backward error. Stage 2's default global batch produces multiple microbatches on supported 8/16/32-GPU runs, so cache only data that can safely participate in each microbatch's fresh graph or disable this cache during training.

Useful? React with 👍 / 👎.

Resuming a training run (WANDB_RUN_ID + WANDB_RESUME=allow, e.g. after preemption or
manual restart) always runs under a *new* Beaker experiment id, since the whole point
of a resume is that the job identity changes while the training state doesn't. But
BeakerCallback stamped `beaker_experiment_url`/`beaker_experiment_id` into the W&B
run's config with plain `.update()`, and wandb refuses to overwrite an existing config
key without `allow_val_change=True` - so every resumed run crashed on all ranks as
soon as this callback fired:

    ConfigError: Attempted to change value of key "beaker_experiment_url" from
    <old-experiment-url> to <new-experiment-url>

Pass `allow_val_change=True`, since a resume legitimately changing this value is
expected, not a config mistake to guard against.

Co-Authored-By: Claude Opus 5 <[email protected]>
@donovanclay

Copy link
Copy Markdown
Author

Re: "Avoid reusing the embedding autograd graph across microbatches"

I looked into this in depth, since it's a specific, checkable claim about PyTorch's "trying to backward through the graph a second time" mechanism — and I don't think it reproduces for this codebase, for a precise, verifiable reason.

Why the claimed mechanism doesn't apply here. That error fires only when a backward pass needs a tensor a previous backward call already freed via ctx.save_for_backward(...). DTensor.full_tensor() is implemented as two chained torch.autograd.Functions — Redistribute and _ToTorchTensor. I read both directly: neither calls save_for_backward on anything. They only stash lightweight metadata on ctx (dtensor_spec, grad_placements, dtype configs). Redistribute.backward re-derives its result from whatever grad_output it's handed at call time — it doesn't depend on state from the original forward still being alive. Same story for torch.cat (the SplitVocabEmbedding case): its backward only needs the split boundaries, which are plain ints, not saved tensors. So there's no "already-freed graph" for a second backward() call to trip over — each call is self-contained.

I verified this three ways rather than trusting the source read alone:

  1. Synthetic single-process repro: reused a cat-based differentiable tensor (mirroring SplitVocabEmbedding) across three independent backward() calls — no error.
  2. Real FSDP2 repro on 2 GPUs on ai2/holmes (same image/toolchain as production): built an nn.Embedding-like param, fully_shard()'d it, cached .full_tensor()'s output, and called it across three microbatches each with their own backward(). All three succeeded, with gradients correctly accumulating each time (norms 4.90 → 5.66 → 9.38).
  3. Live production evidence: a 32-GPU Stage-2 run with MM_EMB_STEP_CACHE=1 and mb2 (multiple microbatches/step, exactly the condition this comment describes) just completed 500 steps and saved a checkpoint cleanly.

This also matches project history: an explicit 2026-08-14 A/B test (MM_EMB_STEP_CACHE=1 vs. off) found it TPS-neutral and correctness-neutral, and it shipped as the default; multiple prior 100-step ship-v4 smokes ran the same mb2 + cache-on configuration to completion.

I did initially write a defensive fix (clearing the cache after every microbatch instead of once per step) before finishing this investigation, but reverted it — the caching pattern is safe as designed, and clearing more aggressively would just add a redundant AllGather per microbatch instead of one per step, undoing the point of the cache, to guard against a failure mode I could not reproduce.

If you're aware of a specific PyTorch/DTensor version or a different embedding-parallel configuration where full_tensor()'s autograd functions do save tensors, that would change this — happy to dig further with more specifics.

@donovanclay
donovanclay requested a review from jason718 August 20, 2026 19:50
The throughput settings validated in the 8/16-GPU A/B sweeps only existed in
the hand-written Beaker YAMLs under launch_scripts/donovan/beaker/sft/, which
is gitignored on this branch. `Molmo2-Stage2.py launch` (the Gantry path)
therefore silently ran a measurably slower configuration than the YAML path,
with nothing in version control recording the difference.

Adds VIT_CROP_MICROBATCH=32, MM_FSDP_RESHARD_AFTER_FORWARD=0, and
MM_FSDP_IMAGE_ALIGN_HACK=0 to launch_config.env_vars only - not the in-code
defaults in distributed/utils.py or nn/vision/multimodal.py, which are shared
with Stage 1 and have a much wider blast radius. A local `train` run under
torchrun still gets the in-code defaults; only Gantry-launched jobs pick up
the ship-stack values.

Left MM_EMB_FULL_TENSOR, MM_EMB_STEP_CACHE, DL_NUM_WORKERS, and
PREFETCH_WORKERS out: checked each against its in-code/ExperimentConfig
default and all four are already no-ops at their ship-stack values.

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

ℹ️ 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 +65 to +68
:func:`iter_rank_mixture_refs` so both compute the exact same sequence. Draws source
choices in bounded chunks and builds each source's permutation lazily, on first use,
rather than allocating a full ``n``-length choice array and every source's permutation
up front regardless of whether that source is ever drawn.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve the seeded shuffle when resuming existing runs

The previous reshuffle() generated every source permutation before drawing src_choices, whereas this helper draws a choice chunk before lazily generating permutations, so the same seed and epoch now produce a different reference order. Because loader checkpoints persist only seed, epoch, and batches_processed, resuming an existing Stage 1 or Stage 2 run with this commit regenerates a different epoch and skips into it at the old batch offset, repeating some examples and omitting others. Preserve the legacy RNG ordering or version and persist enough shuffle state to resume safely.

Useful? React with 👍 / 👎.

… resumes

Codex review on 6f15953 (bounding mixture-shuffle memory): MixtureDataLoader's
checkpoint only persists (seed, epoch, batches_processed) and reconstructs the
reference order on resume by replaying reshuffle() and skipping ahead by
batches_processed - it never persists the order itself. That's only correct if
reshuffle()'s RNG call sequence for a given (seed, epoch) is stable across the
checkpoint boundary.

6f15953 changed that sequence: the original reshuffle() built every source's
full permutation up front (in source order) before drawing any choices;
mixture_epoch_pairs draws choices in bounded chunks and builds each source's
permutation lazily, interleaved with the draws. Same (seed, epoch) now produces
a different sequence. Resuming a pre-6f159533c checkpoint with this code
silently regenerates a different epoch and skips into it at the old batch
offset - repeating some examples and omitting others, with nothing to indicate
it happened.

Making reshuffle() bit-compatible with the old algorithm isn't possible without
reintroducing the eager everything-up-front pattern that fix specifically
removed to bound startup memory (P1: OOM risk on full v9/v10 mixtures) - the
two goals are in direct tension. Instead: version the algorithm and refuse an
unsafe resume by default, following the same pattern this file already uses
for dataset_fingerprint mismatches. A checkpoint predating this field is
treated as version 1; loading it now raises RuntimeError unless the caller
sets ignore_shuffle_algo_version_mismatch=True (logs a warning instead).

Existing checkpoints written before this commit (e.g. the 16-GPU Stage-2 v9
run's step8000-step12000 checkpoints) will need the explicit override to
resume, since they predate the shuffle_algo_version field.
@donovanclay

Copy link
Copy Markdown
Author

Re: "Preserve the seeded shuffle when resuming existing runs" — fixed in f21edf144

Confirmed, and it's a real gap I missed: MixtureDataLoader's checkpoint only persists (seed, epoch, batches_processed) and reconstructs the reference order on resume by replaying reshuffle() and skipping ahead — it never persists the order itself. 6f159533c changed reshuffle()'s RNG call sequence (chunked rng.choice() + lazily-built per-source permutations, instead of building every source's full permutation up front before any choice draw), so the same (seed, epoch) now produces a different sequence than it did before that commit. Resuming a pre-6f159533c checkpoint would silently regenerate a different epoch and skip into it at the old offset — exactly as described.

I couldn't reconcile bit-compatibility with the memory fix's actual goal: matching the old RNG sequence requires knowing every source up front to build all permutations before any choice is drawn, which is the exact eager pattern that fix removed to bound startup memory on full v9/v10 mixtures. So I went with your other suggested remedy — versioning — following the pattern this file already uses for dataset_fingerprint mismatches:

  • Added MixtureDataLoader.SHUFFLE_ALGO_VERSION (currently 2), persisted in state_dict().
  • load_state_dict() treats a missing key as version 1 (pre-6f159533c) and raises RuntimeError on any mismatch, describing exactly what would go wrong, unless the caller explicitly sets ignore_shuffle_algo_version_mismatch=True (then it proceeds with a log.warning instead).

Verified: a synthetic old-format checkpoint (no shuffle_algo_version key) is rejected by default, proceeds correctly under the override with a warning, and a version-matched checkpoint loads with no friction. All 24 tests in multimodal_data_test.py still pass; no new mypy/ruff issues.

One practical consequence worth flagging: the existing 16-GPU Stage-2 v9 run's step8000–step12000 checkpoints (made earlier this session, before 6f159533c) now need the explicit override to resume, since they predate this field — that's the intended tradeoff (a loud, actionable error instead of silent data corruption).

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

ℹ️ 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 +430 to +432
for i in np.nonzero(keep)[0]:
images = self._data[i].get(img_col) or []
keep[i] = len(images) == 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.

P1 Badge Count image entries without decoding every row

On the first image-only-v10 launch, every FineVision config enables require_single_image, and indexing a Hugging Face row here formats the retained Image column, decoding its images merely to call len(). This scans the complete uncapped source before max_rows is applied (including million-row sources), independently on every distributed rank, causing enormous redundant image I/O and potentially preventing the job from reaching training. Read the Arrow list offsets or temporarily use a non-decoding image feature when building this index.

Useful? React with 👍 / 👎.

Beaker stores job preemption policy as minRuntime + autoResume; `preemptible`
is legacy sugar that the server expands into those two (preemptible=False
becomes minRuntime: 8h + autoResume: false). BeakerLaunchConfig only exposed
`preemptible`, so a Gantry-launched job could never get autoResume: true and
had to fall back to the raw-YAML launch path to survive preemption.

That gap is not theoretical: both the 32-GPU v9 stage-2 run and the 16-GPU
stage-1 run were killed outright when a higher-priority job preempted them
after their 8h minRuntime guarantee elapsed, losing hours of allocated-pool
time each despite having recent checkpoints to resume from.

Expose `min_runtime` and `auto_resume`, and omit `preemptible` from the spec
when either is set, since passing both is ambiguous (gantry's own CLI rejects
the combination). Defaults are None, so existing launch configs are unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>

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

Read through the whole PR. The bulk of this is solid — DynaMath reuses the shared SFT helpers correctly, VisionBackbone is a clean abstraction, PackedMixtureIterableDataset builds on iter_dynamic_packs rather than reimplementing the packer, and there are five new test files. My comments are concentrated in a few places.

Heads up on process: both CI workflows are branches: [main] only, so nothing here ran tests, lint, or type-check — the single green check is GitGuardian secret scanning. That's a branch-config gap rather than anything you did, but it means none of the below was caught mechanically.

Blocking

1. mixture_data_loader.py — the shuffle-version guard makes every existing checkpoint un-resumable, with no reachable escape hatch.
checkpoint_version = state_dict.get("shuffle_algo_version", 1) returns 1 for any checkpoint written before this PR, so load_state_dict raises and the job dies at startup. The error text says "Set ignore_shuffle_algo_version_mismatch=True to resume anyway" — but that's a MixtureDataLoader.__init__ kwarg, and neither Molmo2-Stage1.py nor Molmo2-Stage2.py exposes it as an ExperimentConfig field or passes it. There's no --override that reaches it, so the only recovery is editing code. The guard itself is the right call (it came out of the Codex resume thread) — it just needs a config field wired through both scripts.

2. nn/vision/multimodal.py — model state-dict keys are remapped to legacy names but optimizer keys are not.
self.vision_backbone = VisionBackbone(...) moves real param FQNs to vision_backbone.*. state_dict() remaps them back to vision.* / connector.*, but optimizer FQNs come from named_parameters() and are untouched — and this PR's own optim group overrides use vision_backbone.connector.* / vision_backbone.vision.*. So get_model_state_dict yields vision.weight while get_optimizer_state_dict(flatten_optimizer_state_dict=True) yields param_groups.vision_backbone.connector.bias.lr. Pre-PR checkpoints fail to match under StateDictOptions(strict=True), and post-PR checkpoints are internally inconsistent. load_key_mapping exists for exactly this and is currently unused.

Related, same area: the state_dict() override returns a new dict, but nn.Module.state_dict writes into destination in place and parents discard the child's return value. If MultimodalLM is ever nested, or anyone calls model.state_dict(destination=d), d keeps vision_backbone.* keys while the return value has vision.* — the remap is silently bypassed.

3. Three changes reach outside Stage 2.

  • multimodal.py — the in-code VIT_CROP_MICROBATCH default went 16 → 0. Molmo2-Stage2.py:157 explicitly says env overrides are "Applied only to launch_config.env_vars below, not the in-code defaults in nn/vision/multimodal.py: those are shared with Stage 1 and have a much wider blast radius" — but the in-code default changed anyway. Stage 1 never sets the env var, so _encode_images now runs all B*T crops through the ViT in one forward instead of 16-crop chunks, which can OOM a Stage-1 config that fits today.
  • nn/transformer/model.py — apply_fsdp now reads MM_FSDP_RESHARD_AFTER_FORWARD. That's the shared LM path for every text-only OLMo2/OLMo3 run; with the var set (SHIP_STACK_ENV sets it unconditionally, and it's easy to leave in a shell or launch template) a text-only 32B run loses per-block resharding, roughly doubling FSDP parameter memory with nothing in its config to explain it.
  • finevision.py — loss_token_weighting default flips root_subsegments → root_subsegments_root_tokens, and _build now passes turns instead of [turns], so encode_sft_example splits multi-turn rows into per-turn branches and shuffles them. Both apply to existing image-only-v9 FineVision sources and to VisualWebInstructDatasetConfig. The updated assertions in sft_datasets_test.py (4.0 → 6.265986, 3.0 → 2*sqrt(3)) confirm the weights change. A v9 run before and after this PR trains on different supervision for identical rows, with nothing in the config to signal it.

4. Molmo2-Stage2.py — MM_FSDP_IMAGE_ALIGN_HACK=0 on every launch may deadlock multi-node.
The justification is that DP max-crop padding makes the lockstep guard redundant, but that padding equalizes the forward, not the backward graph. tulu4 is ~14% of image-only-v9/v10 and text-only, so a rank can draw an all-text pack: the collator supplies a dummy zero crop with pooled_patches_idx all -1, valid_rows is all-False, image_features is (0, d), and the splice connects nothing. With the align hack off there's no other edge from connector/ViT output into the loss, so that rank runs no connector/ViT backward while its peers do — asymmetric reduce-scatter. The A/B that justified this ran at 8 GPUs; the env var is applied unconditionally, including multi-node.

Also worth fixing

  • Molmo2-Stage2.py — _append_extra_sft_sources is only called on the v9 else branch, so mmfinereason_rate and finevision_rate are silently no-ops for single-image-only-v10, VALIDATION_MIXTURES_V10, and single-image-only-v9. --mixture=single-image-only-v10 --mmfinereason_rate=0.05 starts, logs a mixture with no MMFineReason, and trains the wrong distribution with no warning. Both fields are still documented as live knobs.
  • Molmo2-Stage2.py — DL_NUM_WORKERS = 2 as the default makes --pack_sequences=false an unconditional startup error, since dl_num_workers > 0 requires pack=True. Users now have to know to pass --dl_num_workers=0 alongside it.
  • finevision.py — image-only-v10 can't run from a clean checkout. build_finevision_v10_config never sets hub_repo, so uses_hub() is False and all five sources take the local-parquet branch, pointing at paths created by launch_scripts/donovan/env/setup-finevision-v10-symlinks.sh — which this PR adds to .gitignore. Same shape for DynaMath: paths.py:9 defaults to /weka/oe-training-default/donovanc/molmo-experimental-data, a personal directory baked into a library default. The docstring and PR body both call this "hub-backed FineVision", which no path outside test_finevision_hub_load exercises.
  • mixture_pack_profiles.py — four tiers labeled single-image get pack_max_crops=25 + shortcut_max_len_images=True but contain multi-image sources: demo/demo-pointing include correction_qa_multi_only_max5, pointing/demo-pointing include pixmo_multi_points, and academic includes mantis_instruct_*_multi_only plus six cosyn_multidoc_* (image_only_v9.py:95-114). DynamicPacker emits those solo and the collator sizes the batch to ~125 crops — 5x the ViT memory the profile was chosen to cap.
  • finevision.py — save_finevision_index_cache uses one fixed <key>.tmp.npz shared by all ranks, so 8 DP ranks building the same source race: the second os.replace raises an uncaught FileNotFoundError, and a half-written file that gets renamed raises zipfile.BadZipFile, which the loader's except (OSError, KeyError, ValueError) doesn't catch. The default dir is inside the shared read-mostly FineVision corpus root, and the new unit tests pass no index_cache_dir, so in CI they'd try to create /weka/oe-training-default/....
  • finevision.py — require_single_image decodes every image to count them. The comment says "Vectorized check" but it's a per-row loop, and load_hf_dataset never casts to Image(decode=False), so building finevision_densefusion_1m runs 1M PNG/JPEG decodes on every rank just to evaluate len(images) == 1. self._data.data.column(img_col) (Arrow list lengths) or with_format('arrow') gives the count without decoding.
  • multimodal.py — the embedding step cache is invalidated only by clear_embedding_step_cache(), which exactly one train module calls, and MM_EMB_STEP_CACHE defaults on. Any other loop that calls MultimodalLM.forward and steps the optimizer reads the first forward's gather for the rest of the process. Also _mm_emb_full_tensor is misnamed — _gathered_embedding_weight always calls full_tensor(), so MM_EMB_FULL_TENSOR=0 only disables the cache, never the gather.

Consolidation

Four things I'd like to see restructured before this lands, roughly in order of how much they'll cost later:

Move the env knobs into the Config system. This PR adds nine MM_* flags plus VIT_CROP_MICROBATCH, read through os.environ at call sites, and promotes three of them into olmo_core/distributed/utils.py (fsdp_reshard_after_forward, fsdp_nest_connector, log_fsdp_topology) — a module every training path imports. AGENTS.md makes @dataclass Config with dot-notation overrides the central pattern; these knobs sit outside it, so they aren't serialized into the saved config, aren't --override-able, and aren't type-checked. Two of the blockers above are direct consequences. Fields on MultimodalTransformerTrainModuleConfig / the dp config would fix the category rather than the instances.

Collapse the two prefetch mechanisms. MixtureDataLoader now carries both prefetch_workers (threads, prefetch.py) and dl_num_workers (processes, PackedMixtureIterableDataset). Of the four combinations, two raise and one silently zeroes prefetch_workers with a warning — and that surface is what turns the new DL_NUM_WORKERS=2 default into the --pack_sequences=false trap above. A single loader strategy field validated in __post_init__ would replace three scattered runtime raises.

Parameterize v9/v10 rather than forking the module. Measuring the two files: _source_lookup is 100% identical, _LazyDatasetMap 88%, build_image_only_*_mixture 82% — and the entire delta is threading one finevision_cache_dir kwarg. Drift has already started: v10's _LazyDatasetMap caches _source_map while v9 recomputes it on every call. Collapsing the fork removes roughly 160 of image_only_v10.py's 231 lines and means the next fix lands once instead of twice.

Derive the pack profiles. mixture_pack_profiles.py is a hand-maintained name → profile table, and MULTI_IMAGE_MIXTURE_DATASETS already exists in image_only_v9.py to compute it from. The table has already drifted, which is the multi-image bug above; deriving it makes that class of mistake impossible.

Happy to pair on any of these, particularly the config migration — that one touches the most files and is the easiest to get half-done.

donovanclay and others added 7 commits September 14, 2026 22:42
Review flagged that Stage 2's SHIP_STACK_ENV setting
MM_FSDP_IMAGE_ALIGN_HACK=0 could deadlock a multi-node run: FSDP2 skips a
param group's reduce-scatter when none of its parameters has a gradient,
so a rank whose microbatch draws an all-text pack (tulu4 is ~14% of
image-only-v9/v10) could issue fewer collectives than a peer with image
rows and hang the DP group. Reproduced that general mechanism on 2 CPU
gloo processes -- it needs neither multiple nodes nor GPUs, only two DP
ranks with asymmetric batches.

This model doesn't hit it. MultimodalLM's splice
(`flat[is_image_patch] = flat[is_image_patch] + image_features.reshape(-1, d)`)
runs whenever `images is not None`, which the collator guarantees via a
dummy zero crop, and a masked index_put with an all-False mask still
builds an autograd node -- so an all-text microbatch leaves the vision
and connector parameters with present-but-zero gradients rather than
None, and FSDP issues the reduce-scatter on every rank regardless.
`apply_compile` also only targets the lm/vision/connector submodules,
never `MultimodalLM.forward`, so the splice is never inside a compiled
region either.

Verified on 2 holmes GPUs under real FSDP2 + torch.compile (experiment
01M2622FH6WTMHZAD6A9WT5D7F): tie off, rank 0 with image rows and rank 1
all-text, gave [10, 10] symmetric collectives and zero None gradients on
either rank.

Net effect: disabling the tie is safe, but not worth doing. The 8-GPU
A/Bs already on record show the win doesn't stack with the no-reshard
win that's already shipped (no-reshard alone 13,281 TPS vs 12,973
baseline; align-hack-off alone 13,299; both together only 13,106) --
so there's no throughput case for it either way. Left on as the
conservative default; corrected the SHIP_STACK_ENV comment, which
previously asserted a costed-throughput tradeoff with no number behind
it, to record the actual A/B results and the hardware verification.

New: src/test/nn/vision/align_tie_test.py pins the invariant that makes
the tie redundant (vision/connector params get real, not None,
gradients on an all-text batch) so it fails loudly if that assumption
ever breaks and the tie becomes load-bearing again.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ive pack profiles (C-2, J-14, J-15)

C-2: restrict_submixtures() now applies the dataset_names allowlist to a
mixture's submixture groups before any dataset is built and before
weights are computed. Filtering afterwards (the previous order) gave
each surviving group a share of rate * (surviving size-mass / total
size-mass), so a tier keeping only part of one group was silently
crushed relative to groups it kept whole -- the debug tier came out
~87% tulu4 despite a nominal 16.6% nlp rate. Filtering first gives every
surviving group its nominal rate; the two orderings are bit-identical
whenever a tier's groups are each kept whole or dropped entirely, which
covers every validation tier except debug and multi-image. Also means
--mixture=finevision now builds 5 sources instead of the full v10
registry's 54 (dynamath 6, finevision-dynamath 11).

J-14: image_only_v9.py and image_only_v10.py shared duplicated lazy
dataset-registry / weighting plumbing that had already drifted --
v10's map cached its source lookup, v9 recomputed it on every keys()
call. Extracted to a new mixtures/registry.py (LazyDatasetMap,
build_mixture, source_lookup, mixture_dataset_names); v9 and v10 keep
their existing public functions, now backed by one implementation.

J-15: mixture_pack_profiles.py was a hand-maintained tier -> profile
table that had drifted: demo, demo-pointing, pointing, nlp-demo and
academic all got the 25-crop single-image budget despite each
containing a source from MULTI_IMAGE_MIXTURE_DATASETS, and
DynamicPacker emits an over-budget example as its own pack rather than
enforcing the cap, so those tiers silently exceeded the memory bound
the profile was chosen to provide. New mixtures/tiers.py resolves a
tier to its actual sources from metadata alone (mirroring the same
v9-vs-v10, full-vs-single-image dispatch Molmo2-Stage2.py performs, so
the two can't diverge again); mixture_pack_profiles.py derives the
crop budget from whether any of those sources is multi-image. An
unrecognized tier fails safe to the conservative (multi-image) profile.

Co-Authored-By: Claude Opus 5 <[email protected]>
…nal path default; mm_olmo supervision semantics (J-10, C-3, J-11, J-7a, J-3c)

J-10/C-3: save_finevision_index_cache() used one fixed <key>.tmp.npz
shared by every writer, so concurrent DP ranks building the same
source on a cold launch raced -- the second os.replace() could raise
FileNotFoundError, and overlapping savez_compressed() calls could
publish a truncated archive. Each writer now stages to its own
.tmp.<pid>.<uuid> file. load_finevision_index_cache()'s except clause
didn't catch zipfile.BadZipFile/EOFError, so a truncated .npz (an
archive format) escaped it; both are now caught. Both the makedirs and
the write are best-effort: a read-only or absent cache directory now
warns and continues rather than failing dataset construction after the
data itself loaded fine. The default cache directory also now follows
the configured data root instead of always defaulting to the shared
FINEVISION_ROOT, so a local-data run doesn't need write access to that
corpus.

J-11: require_single_image counted images by indexing every row, which
decodes the retained Image column just to call len() -- a full decode
of the uncapped source on every rank, before max_rows is applied.
Counts now come from Arrow list offsets (pc.list_value_length) when the
column is a list type, with a logged decode fallback otherwise.

J-7a: paths.py's MOLMO_EXPERIMENT_DATA_DIR silently defaulted to
/weka/.../donovanc/molmo-experimental-data, a personal directory baked
into a library default. It now has no default; the new
require_experiment_data_dir() raises an actionable
OLMoConfigurationError naming what needed it, and dynamath.py uses it.

J-3c: FineVision (v9 extras and v10 alike) moves to mm_olmo's
supervision semantics -- loss_token_weighting defaults to
root_subsegments_root_tokens, and _build passes flat turns so a
multi-turn row splits into one branch per message_list entry instead
of being assembled as a single sequential conversation. This is a
deliberate, not incidental, change in what a FineVision row trains on;
documented on the field and in the module docstring (which previously
described the old single-branch assembly), and pinned by
test_finevision_matches_mm_olmo_supervision_defaults plus the existing
loss-mask-sum assertions (confirmed to fail if _build is reverted to
passing [turns]).

Co-Authored-By: Claude Opus 5 <[email protected]>
… (J-13)

prefetch_workers (threads) and dl_num_workers (processes) are mutually
exclusive prefetch mechanisms; the legality rules for their
combinations lived as three separate checks inside MixtureDataLoader's
constructor -- two raises and one silent zeroing. New
MixtureLoaderStrategy + resolve_loader_strategy() validate the
combination and reduce it to exactly one active mechanism in a single
place; the constructor now delegates to it instead of duplicating the
logic. The shuffle-version mismatch error message now names the actual
CLI override (--ignore_shuffle_algo_version_mismatch=true) instead of
the constructor kwarg, which an operator hitting the error from a
training script has no way to pass directly.

packed_mixture_iterable.py: the MM_DL_SLOW_LOAD_S diagnostic threshold
is now read once per dataset instance instead of once per example (it
stays an env var deliberately -- it only gates a log line, never
training behaviour, so the reasons for migrating the other MM_* knobs
to Config fields don't apply to it).

Co-Authored-By: Claude Opus 5 <[email protected]>
… override (J-2)

MultimodalLM used to override state_dict()/load_state_dict() to rewrite
the vision_backbone.* parameter names (from the VisionBackbone
submodule move) back to the pre-move vision.*/connector.* names, for
checkpoint back-compat. That override only covered the model: optimizer
FQNs come from named_parameters(), which it never touched, so a saved
checkpoint carried model key vision.class_embedding beside optimizer
key param_groups.vision_backbone.vision.class_embedding.lr -- two key
spaces in one checkpoint. Measured on a tiny model: 48 legacy-named
model keys vs 528 vision_backbone-named optimizer keys. The override
also had a second bug: nn.Module.state_dict() writes into `destination`
in place and callers use that, not the return value, so
state_dict(destination=d) left d with the internal names while the
return value had the legacy ones -- the remap was silently bypassed for
any nested use.

Both overrides are removed. Back-compat now lives at the checkpoint
layer: MultimodalLM.legacy_vision_key_mapping() (derived from the
module tree, not a hardcoded prefix list) returns the
{current: legacy} mapping swap_param_keys() expects, and
molmo2_loader.canonicalize_vision_keys() / strip_vision_backbone_prefix()
normalize converter input/output so the three sites that build
legacy-keyed dicts and load them with strict=False keep covering the
ViT and connector instead of reporting them as unexpected and leaving
them randomly initialized.

VISION_BACKBONE_PREFIX, canonicalize_vision_keys and
strip_vision_backbone_prefix are added to molmo2_loader.__all__ and
re-exported from olmo_core.nn.vision -- they are now a cross-repo
compat contract (olmo-eval's checkpoint loader imports
canonicalize_vision_keys directly) and should be declared rather than
reached into. multimodal_lm_state_dict_to_hf, already imported there
but never declared, is added to the same __all__.

New: src/test/nn/vision/vision_key_space_test.py, including a
regression test for the silent failure this would have caused: without
canonicalize_vision_keys, a converter's legacy-keyed output loaded with
strict=False leaves the vision tower randomly initialized with no
error.

Co-Authored-By: Claude Opus 5 <[email protected]>
…12, J-3a, J-3b, J-8)

Nine MM_* flags plus VIT_CROP_MICROBATCH were read via os.environ at
their call sites, including from olmo_core/distributed/utils.py -- a
module every training path imports, not just the multimodal one. That
meant they weren't serialized into a saved config, weren't
--override-able, and weren't type-checked; two review blockers were
direct consequences of that (see below). New env_bool()/env_int()
helpers in olmo_core/utils.py resolve a legacy env var into a typed
default -- raising on an unparseable value rather than silently
defaulting -- for use in a Config's __post_init__, so the *resolved*
value is what gets recorded and overridden, not the env var itself.

MultimodalLMConfig gains vit_crop_microbatch, emb_step_cache,
image_align_tie and pre_lm_barrier.
MultimodalTransformerTrainModuleConfig gains fsdp_reshard_after_forward,
fsdp_nest_connector, log_fsdp_topology and verbose_step_logs. Both
resolve their env var in __post_init__, so the resolved value survives
build()'s as_dict(exclude_none=True) instead of being dropped as None.

J-3b: Transformer.apply_fsdp gains an explicit reshard_after_forward
parameter (default None = current behaviour, False under pipeline
parallelism) instead of calling the now-removed
distributed.utils.fsdp_reshard_after_forward(), which read
MM_FSDP_RESHARD_AFTER_FORWARD. That function was promoted into a module
every text-only OLMo2/OLMo3 training path imports, so a value left in a
shell or inherited from a multimodal launch template could silently
roughly double an unrelated run's FSDP parameter memory with nothing in
its config to explain it. multimodal_train_module.py now passes its
resolved value explicitly to model.lm.apply_fsdp(...); the shared
text-only path (train_module/transformer/common.py) passes nothing and
gets the standard default. Guarded by
test_apply_fsdp_reshard_after_forward_is_a_parameter_not_an_env_read,
which parses the module's AST so an explanatory comment mentioning the
old env var doesn't false-positive the check. The now-fully-dead
fsdp_reshard_after_forward()/fsdp_nest_connector() helpers are deleted
from distributed/utils.py.

J-3a: VIT_CROP_MICROBATCH's in-code default is restored to 16 (it had
regressed to 0). Stage 1 never sets the env var and shares this config
with Stage 2, so 0 ran every crop through the ViT in one forward and
could OOM a Stage-1 configuration that fits today.

J-8: MM_EMB_FULL_TENSOR is removed -- it never disabled the gather it
was named after (F.embedding needs a full tensor, so
_gathered_embedding_weight always calls full_tensor()) and its only
real effect duplicated MM_EMB_STEP_CACHE. Setting it now warns once
rather than being silently ignored. The embedding step cache is also
now "armed" only by clear_embedding_step_cache(), so a caller that
never invalidates it gets a fresh gather every forward instead of
silently reusing the first step's weights for the rest of the process;
train_batch calls it at both entry and exit, so this doesn't change the
measured caching behaviour.

Co-Authored-By: Claude Opus 5 <[email protected]>
…alidation into Stage 1 & Stage 2 (J-1, J-5, J-6)

J-1: ignore_shuffle_algo_version_mismatch is now an ExperimentConfig
field on both Molmo2-Stage1.py and Molmo2-Stage2.py, passed through to
MixtureDataLoader. Previously it was only a MixtureDataLoader.__init__
kwarg with no ExperimentConfig field and no script wiring it through,
so the shuffle-version guard's own escape hatch was unreachable from
the CLI -- every checkpoint written before that guard existed was
unresumable with no override.

J-5: _append_extra_sft_sources (MMFineReason-SFT / FineVision rate
knobs) now runs on every mixture branch instead of only the v9 else
branch, so --mixture=single-image-only-v10 --mmfinereason_rate=0.05 no
longer starts up, logs a mixture with no MMFineReason in it, and trains
the wrong distribution with no warning. The FineVision configs it
appends now also pass require_single_image=True: they're documented as
one-image-per-row already, but J-5 made this path reachable from
single-image tiers, and get_mixture_pack_profile derives its crop
budget from the tier's registry sources -- which don't include these
runtime-appended extras -- so a multi-image row sneaking in here would
silently exceed a single-image tier's crop budget the same way the old
hand-maintained profile table did.

J-6/J-13: ExperimentConfig.__post_init__ now validates the loader
configuration via resolve_loader_strategy() (rather than only checking
the pack_sequences/dl_num_workers pair ad hoc), and does so without
mutating pack_sequences/dl_num_workers/prefetch_workers -- Config.merge
is as_dict() -> apply overrides -> from_dict(), so a __post_init__ that
writes back into its own fields would feed already-normalized values
into the *next* merge (verified: --dl_num_workers=0 on a
prefetch_workers=4 config would silently resolve to synchronous
instead of threads on a second merge). The effective value is exposed
via an effective_dl_num_workers property instead, so
--pack_sequences=false alone still works without also requiring
--dl_num_workers=0, and the underlying DL_NUM_WORKERS default survives
a later merge back to pack_sequences=true.

_build_mixture's four-way v9-vs-v10 / full-vs-single-image dispatch
now goes through mixtures.tiers.is_v10_mixture() instead of checking
membership in VALIDATION_MIXTURES_V10 inline, so it can't drift from
the same dispatch mixture_pack_profiles.py relies on (see the J-14/J-15
commit).

New: src/test/data/multimodal/test_stage2_config.py, loading the
script by path to test __post_init__ and the derived properties
directly; confirmed test_pack_sequences_false_does_not_require_also_setting_dl_num_workers
fails if the pack_sequences=false fallback is reverted.

Co-Authored-By: Claude Opus 5 <[email protected]>
@donovanclay

Copy link
Copy Markdown
Author

Thanks for the thorough review — went through everything below, pushed as 7 commits (c5f1bdc..208d0be). Summary follows your structure; commit refs are short SHAs on this branch.

Blocking

1. mixture_data_loader.py shuffle-version guard unreachable. Fixed in 208d0be. ignore_shuffle_algo_version_mismatch is now an ExperimentConfig field on both Molmo2-Stage1.py and Molmo2-Stage2.py, passed through to MixtureDataLoader. Also fixed the error message itself — it named the constructor kwarg, not the CLI flag an operator actually has (--ignore_shuffle_algo_version_mismatch=true).

2. nn/vision/multimodal.py model/optimizer key mismatch. Fixed in c897977. Removed the state_dict()/load_state_dict() override pair entirely; back-compat moved to the checkpoint layer via MultimodalLM.legacy_vision_key_mapping() (derived from the module tree) + swap_param_keys. Measured the actual mismatch before fixing: 48 legacy model keys vs 528 vision_backbone-named optimizer keys on a tiny model. Also caught the destination= bypass you flagged — confirmed it was real, now moot since there's no override to bypass. Three call sites build legacy-keyed dicts and load with strict=False; without normalizing those too, this fix alone would have made the ViT/connector silently random-init on every HF/scratch init. molmo2_loader.canonicalize_vision_keys()/strip_vision_backbone_prefix() handle that, and are now public (__all__ + re-exported from olmo_core.nn.vision) since olmo-eval's checkpoint loader needs them directly — see the "olmo-eval coordination" note below.

3. Three changes reaching outside Stage 2. All three fixed in b2131a4:

  • VIT_CROP_MICROBATCH in-code default restored 0 → 16.
  • Transformer.apply_fsdp no longer reads MM_FSDP_RESHARD_AFTER_FORWARD; it's now an explicit reshard_after_forward parameter (default None = today's behavior). The multimodal train module passes its resolved value explicitly; the shared text-only path passes nothing. Guarded by an AST-based test so a future contributor can't quietly reintroduce the env read.
  • FineVision's loss_token_weighting/per-turn-branching change: keeping it, deliberately, for both v9 and v10 (see 6c22310) — decided this should move everything to mm_olmo's supervision semantics rather than preserve the old OLMo-core behavior for v9 alone. Documented on the field, in the module docstring, and pinned by a new test plus the existing loss-mask-sum assertions (confirmed they fail if _build is reverted to [turns]). Flagging explicitly per your ask: a v9 run before/after this PR trains on different supervision for identical rows.

4. MM_FSDP_IMAGE_ALIGN_HACK=0 deadlock risk. Investigated properly rather than just reverting — c5f1bdc. The mechanism you flagged is real (confirmed on 2 CPU gloo processes: an asymmetric FSDP param-group gradient state does hang backward(), and it needs neither multiple nodes nor GPUs, just 2 DP ranks). But this model doesn't hit it: the splice always runs when images is not None (the collator's dummy zero crop guarantees that), and a masked index_put with an all-False mask still builds an autograd node, so an all-text microbatch leaves vision/connector params with present-but-zero gradients, not None — FSDP issues the reduce-scatter regardless. Verified on 2 holmes GPUs under real FSDP2 + torch.compile (exp 01M2622FH6WTMHZAD6A9WT5D7F): tie off, asymmetric batches, [10, 10] symmetric collectives, zero None grads. New align_tie_test.py pins the invariant that makes it safe. Net call: left the tie on — turning it off is safe but the 8-GPU A/Bs on record show the win doesn't stack with the no-reshard win already shipped (no-reshard alone 13,281 TPS, align-off alone 13,299, both together only 13,106), so there's no throughput case for it either way.

Also worth fixing

  • _append_extra_sft_sources only on the v9 branch → fixed, 208d0be. Also pinned require_single_image=True on the FineVision extras it builds — J-5 made this path reachable from single-image tiers, and the pack-profile derivation (below) doesn't see these runtime-appended sources, so a multi-image row here would've silently blown a single-image tier's crop budget.
  • DL_NUM_WORKERS=2 making --pack_sequences=false an unconditional error → fixed, 208d0be, via the same resolve_loader_strategy() used for the consolidation item below.
  • image-only-v10 can't run from a clean checkout — partially addressed, flagging the gap rather than claiming it's closed: paths.py's MOLMO_EXPERIMENT_DATA_DIR (the DynaMath side of this) no longer defaults to a personal directory (6c22310), but build_finevision_v10_config still doesn't set hub_repo, so the FineVision side of this is not fixed — it still takes the local-parquet branch pointing at the gitignored symlink script's output. Left open; didn't want to guess at hub config wiring without knowing which HF repo/revision you want pinned.
  • mixture_pack_profiles.py multi-image bug → fixed and generalized, c82f65d. Derived the profile from the tier's actual sources (mixtures/tiers.py) instead of a hand-maintained table, so this class of bug can't recur. Also caught one you didn't list: nlp-demo had the same problem (Codex flagged it, independently).
  • FineVision index-cache race → fixed, 6c22310. Per-writer staging file instead of one shared .tmp.npz; BadZipFile/EOFError added to the corrupt-cache guard (an .npz is a zip, so a truncated one wasn't being caught); both the mkdir and the write are now best-effort so a read-only cache dir warns instead of aborting a run whose data loaded fine.
  • require_single_image decoding every image → fixed, 6c22310. Counts come from Arrow list offsets now, no decode, with a logged fallback if the column isn't a list type.
  • Embedding step-cache invalidation / MM_EMB_FULL_TENSOR misnaming → fixed, b2131a4. Removed MM_EMB_FULL_TENSOR (it never gated the gather it was named for); the cache is now "armed" only by clear_embedding_step_cache(), so a caller that never invalidates gets a fresh gather instead of silently reusing step 0's weights forever.

Consolidation

Did all four, in dependency order (registry before deriving profiles from it, one loader strategy before wiring the scripts to it):

  • Env knobs → Config: b2131a4. All MM_* + VIT_CROP_MICROBATCH are now typed fields on MultimodalLMConfig / MultimodalTransformerTrainModuleConfig, resolved from the legacy env var once in __post_init__ so the resolved value is what's serialized/overridable, not None.
  • Collapse the two prefetch mechanisms: 937c9b4. MixtureLoaderStrategy + resolve_loader_strategy() replace the three scattered constructor checks with one validated dispatch.
  • Parameterize v9/v10 instead of forking: c82f65d. Shared lazy-registry/weighting plumbing extracted to mixtures/registry.py; this also fixed a live bug your "drift has already started" comment predicted — v10's registry cached its source lookup, v9 rebuilt it every call.
  • Derive the pack profiles: c82f65d, described above.

What's still open

  • The FineVision hub_repo clean-checkout gap noted above.
  • No full-scale training run on any of this yet — verification is CPU tests plus the one targeted 2-GPU hardware check for item 4. Recommend at least a Stage-2 smoke before merge.
  • Sequencing with olmo-eval: canonicalize_vision_keys()/legacy_vision_key_mapping() are now a real cross-repo contract — olmo-eval's checkpoint loader needs to accept both key layouts or it breaks against any checkpoint written with this PR. That olmo-eval-side fix exists but isn't merged yet; flagging so it doesn't get missed as a merge-order dependency.
  • Stage 1 doesn't go through the same loader-strategy validation as Stage 2 (harmless today since its DL_NUM_WORKERS defaults to 0, but noting the asymmetry).

Full test run against the pushed state: 399 passed, 1 pre-existing failure unrelated to this branch (parity_test.py::test_clip_parity, a transformers version issue reproduced identically on a clean vision checkout). mypy flat, no new ruff findings beyond the repo's existing baseline.

@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: 208d0bee13

ℹ️ 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 +113 to +116
kw = dict(variant=variant, seed=seed)
if max_sequence_length is not None:
kw["max_sequence_length"] = max_sequence_length
return DynaMathDatasetConfig(**kw).build(tokenizer)

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 Propagate the DynaMath root into launched jobs

When the advertised --mixture=image-only-v10, dynamath, or finevision-dynamath tier is run through Molmo2-Stage2.py launch, this constructs every DynaMath config without data_root or dataset_path, so DynaMathDatasetConfig._resolved_data_root() requires MOLMO_EXPERIMENT_DATA_DIR. The Stage 2 recipe only adds SHIP_STACK_ENV, and a repo-wide search shows no launch code that exports this required variable, causing the standard Beaker launch to fail while building the first DynaMath source. Add a configured DynaMath root to the mixture/experiment config and propagate it into the recipe or these constructors.

Useful? React with 👍 / 👎.

donovanclay added a commit that referenced this pull request Sep 14, 2026
Snapshot of the uncommitted PR #834 review-response work from the main
OLMo-core checkout (23 modified files, 7 new files), applied here as the
base commit so compute-efficiency work builds on top of it rather than
diverging from it.

This is not new work -- it is the same diff that is still uncommitted in
the main checkout. Keeping it as a separate first commit means the perf
changes that follow stay reviewable independently, and this commit can be
dropped or rebased away once #834 lands on the branch proper.

Tests: 329 passed, 18 skipped in src/test/data/multimodal + src/test/nn/vision.
The single failure (nn/vision/parity_test.py::test_clip_parity, KeyError on
an embedding key) is pre-existing -- verified failing on the clean base
commit 3c922f2 with this diff stashed.

Co-Authored-By: Claude Opus 5 <[email protected]>
donovanclay added a commit that referenced this pull request Sep 14, 2026
Molmo2-Stage2.py registered no profiler callback, so a profiling run meant
hand-editing the script. It now registers ProfilerCallback disabled, enabled
with --trainer.callbacks.profiler.enabled=true. Defaults suit a 100-step
throughput smoke: skip the compile-warmup steps, then trace a short window,
with_stack=False to keep the trace small.

ProfilerCallback also gains export_chrome_trace (default True, so existing
behaviour is unchanged). The export serializes and gzips the entire trace,
which on a multimodal step is large enough to look like a hang -- it stalled
a previous profiling run, and a second profiling run OOMed mid-profile. With
it off, the logged self-CUDA and self-CPU op tables still come through, and
those are usually enough to rank bottlenecks.

Exposed as a config field rather than an env var, matching the direction PR
#834 is taking the other perf knobs.

Tests: 50 passed in src/test/train + test_stage2_config.py. The two failures
(checkpoint_test.py remote S3) are environmental -- no S3 credentials on this
box, AccessDenied on ListObjectsV2 -- and unrelated to this change.

Co-Authored-By: Claude Opus 5 <[email protected]>
donovanclay added a commit to allenai/olmo-eval that referenced this pull request Sep 14, 2026
All three let a misconfiguration through as a plausible-looking result rather
than an error, which is the failure mode this branch is otherwise built to close.

`load_checkpoint_weights` guarded the vision-key remap with `hasattr`, so on an
OLMo-core predating the `vision_backbone` rename the remap was silently inert:
a legacy `vision.*` checkpoint loaded with an empty vision tower and scored at
chance with nothing logged. The same function hard-failed on the unsharded path
with a bare ImportError naming only a symbol. Both now raise and name the
OLMo-core that supplies the helpers (allenai/Olmo-core#834), since the helper and
the rename it compensates for ship in the same change -- its absence means the
install is too old, not that back-compat is unnecessary.

`TaskConfig.__post_init__` merged dotted `sampling_params` overrides onto
`type(self).__dict__["sampling_params"]`, which resolves to TaskConfig's `None`
default rather than the task's own value. The merge therefore always rebuilt from
a bare SamplingParams and dropped every field the override omitted -- gsm8k's and
humaneval's `stop_sequences` among them. There is nothing to merge against by the
time `__post_init__` runs, so it is now validation only; the runner remains the
single place that merges.

`looks_multimodal_hf` swallowed every config-read failure, including transformers
refusing to run a repo's custom code. A Molmo2 checkpoint without
`trust_remote_code` then took the text path and died with `Unrecognized
configuration class Molmo2Config ... AutoModelForCausalLM` -- the error this
function exists to prevent. That case is now re-raised naming the flag, and
`trust_remote_code` is pinned False when unset so the `[y/N]` stdin prompt cannot
hang a Beaker worker with no stdin.

Tests for the OLMo-core-dependent paths now skip rather than fail when the
installed OLMo-core lacks the helpers, with the required branch named in the skip
reason: `pyproject.toml` pins an ai2-olmo-core release with no olmo_core.nn.vision
at all, so those cases were red on a clean checkout for reasons unrelated to the
code under test.

Co-Authored-By: Claude Opus 5 <[email protected]>
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