Repository navigation
Vision donovan stage 2 training - #806
Conversation
Keep frozen vision in evaluation mode and make full caption, pointing, and Tulu mixture runs safe by bounding Tulu sequences and preventing mixed-modality packs. Co-authored-by: Cursor <[email protected]>
Port mm_olmo mixture sources, academic registry, SFT formatter, Qwen3 layout, and parity tests for Molmo2 stage-2 dataset coverage. Co-authored-by: Cursor <[email protected]>
Multimodal train module (response_logits_only, flex attention, FSDP fixes), Molmo2-Stage2.py, mixture loader hardening, and model/trainer updates for image-only-v9 SFT. Co-authored-by: Cursor <[email protected]>
HF Molmo2 predicts only the base vocab: the 128 image-special tokens are inputs-only, and the 4B ties its head to the base embedding table. Previously the loader zero-padded the head to base+128 (which, on a tied model, clobbered the 128 new-embedding input rows on load — both state-dict keys copy into one shared tensor) and the extra columns entered every softmax with finite logits and live gradients. - MultimodalLMConfig.output_vocab_size: forward masks logit columns >= base vocab to finfo.min — exactly 0 softmax mass and exactly 0 gradient, matching mm_olmo's base-vocab-only head for loss, sampling, and tied training dynamics (works for both full and response-only logits). - molmo2_loader: tied configs get one consistent concatenated table for both embedding and head keys (verified against the HF checkpoint, which exports the tied weight byte-identically); untied configs keep inert zero-pad rows. - retie_word_embeddings(): Module.to_empty silently breaks weight tying; call it after every meta -> to_empty -> load flow (wired into Stage1/Stage2). - ensure_hf_masking_compat(): transformers>=5 renamed create_causal_mask(input_embeds=...) and dropped cache_position; the bundled Molmo2 remote code uses the old signature. Lets the HF reference run for parity tests. - Tests: tied-table conversion regression tests, retie-after-to_empty, labels guard, masked-column assertions; GPU parity for Molmo2-4B (embedding / LM / full pipeline / training loss) passes. Co-Authored-By: Claude Fable 5 <[email protected]>
Faithful port of mm_olmo olmo/data/dynamic_packer.py (DynamicSolver + select_subset_2d_knapsack): a 48-example candidate buffer, two capacity constraints (text tokens <= seq_len at granularity seq_len//512; image crops <= per-sequence crop capacity at granularity 1), objective value n_tokens + 30 * n_crops, and shortcut-emission for token-full examples — PackingConfig(buffer_size=48, image_weight=30, shortcut_max_len_images=False) in mm_olmo's SFT recipe. Unlike the next-fit packer this freely packs text-only NLP (Tulu) together with image examples, exactly like mm_olmo's pack() (text-only rows contribute an empty crop array; cross-example attention isolation is unchanged via example_ids). One documented deviation: an example that alone exceeds a non-shortcut capacity is emitted as its own pack instead of poisoning the buffer (mm_olmo's knapsack can never select it, which would eventually starve the buffer). MixtureDataLoader routes pack=True through the knapsack whenever pack_max_crops is set (the legacy token-only next-fit remains for stage-1). Molmo2-Stage2.py now uses PACK_MAX_CROPS = 25 = 1 global + 24 high-res local crops — matching mm_olmo's probed per-example capacity; the previous cap of 8 was below a single max-tiling example (9 crops), which forced every image example into its own mostly-padding 16k pack. Tests: knapsack vs brute force on random instances, capacity respect, mixed text+image packs, oversize fallback, shortcut, flush, determinism. Co-Authored-By: Claude Fable 5 <[email protected]>
Multi-image examples (up to 5 images, 8 crops each) now flow through the same
shared formatter + encoder as single-image data, following mm_olmo's
MultiImagePreprocessor + Molmo2 build_sequence:
- encode_sft_example accepts a list of images: each image is multicropped
independently, 'Image {i+1}' text prefixes are inserted when there is more
than one image (nothing for a single image), crops are concatenated along
the crop axis, and each image's pooled patch indices are offset by the
running crop-patch count (token_pooling_offset parity). Single-image
behaviour is bit-identical (list-of-one == bare image, tested).
- Cross-image bidirectional attention needs no model change: HF Molmo2's
token_type_ids mask lets all image tokens in an example attend each other
(mm_olmo bi_directional_attn='image_tokens'), which is exactly our existing
or-mask semantics.
- Multi-image pointing: SftFormatter port of mm_olmo format_multi_points
(p_multi_point_all_image=0.5, 'all images' vs image_k subsets, verbatim
multi_image_pointing / multi_image_point_then_count prompt pools) and
grounding-side serialization with 1-based image indices, per-image (x,y)
sort, point ids continuing across images, ';'-joined groups (html-v2).
- New datasets (mm_olmo all-v9 image slice parity):
mantis_instruct_{llava_665k_multi,nlvr2,spot-the-diff}_multi_only (MC with
option shuffling), correction_qa_multi_only_max5 (grouped human QA with
NO_POINT_PREFIX on counting questions), cosyn_multidoc_{chart,chemical,
diagram,doc,music,table}_exp, and pixmo_multi_points (root size 200k,
weight 0.2, p_high_res 0.30).
- image-only-v9 mixture grows from 32 to 43 sources, matching mm_olmo
IMAGE_ACADEMIC_V2 + the all-v9 demo/pointing groups (video entries
excluded); adds a 'multi-image' validation tier. mantis_instruct_mc /
correction_qa / multi_image_* style-prefix membership matches mm_olmo.
- PACK_MAX_CROPS raised to 125 (= 5 images x (1 global + 24 high-res crops)),
mm_olmo's probed per-example capacity with multi-image enabled.
Co-Authored-By: Claude Fable 5 <[email protected]>
Formatter / dataset parity (reference: mm_olmo data_formatter.py +
text_preprocessor.py + example_preprocessor.py):
- Pointing prompts: restore the 50% label-lowercase draw and stop lowercasing
label_cased (data_formatter.py:1851-1857) — previously ~85% of pointing/
counting examples drew a different template than mm_olmo and labels were
always lowercase; also handle point_then_count.
- Multi-turn conversations ({'messages': [...]}) stay ONE sequential branch
(turn 2 attends turn 1; style prefix on the first turn only; no loss at
intermediate turn ends; single EOS target at the conversation end) via
SftFormatter.format_branches + multi-segment branches in
build_branched_sequence. PixMoCapQa uses it and gains mm_olmo's
NO_POINT_PREFIX treatment of counting questions.
- Tulu4: turn layout now matches the qwen3 chat template exactly (missing
'\n' after intermediate <|im_end|>), no double-im_end loss target, root
weight 2/sqrt(total_assistant_tokens+1) without separator tokens, mm_olmo
truncation semantics (trim to last loss token, raise when truncation
removes all loss), and malformed rows raise instead of a junk fallback.
- style sets: synthetic_qa / transcript removed from DEMO_STYLES (mm_olmo
prefixes them); short_caption gets its own 11-prompt pool; empty style no
longer yields a bare ':' prefix.
- select_vqa_answer: blank answers vote like mm_olmo (no filtering, no extra
rng draw); 'first' == min(); unknown modes raise. chart_qa answers is a
bare string again (no spurious tie-break draw).
- template_options: never passes unlabelled=True (mm_olmo keeps the default
even for unlabelled_options — fixes prompt AND gold-label divergence on
ai2_diagram_no_letter); isinstance(int) guard on answer_idx.
- format_points: count is always len(points); label/label_cased casing per
mm_olmo; 'prompt' takes precedence over templating.
- RNG derivation: every dataset now threads ONE per-example stream derived as
seed*195172+index (mm_olmo dataset.py:68) through row formatting, prompt
templating, and branch shuffling — pixmo_clocks augmentation now varies per
example (was frozen at a constant seed), and compare_sft_example.py aligns
the mm_olmo export to the same stream so parity can be checked at ANY
index, not just 0.
- mixture_weights: add mm_olmo's root_size_factor < 1 branch
(sqrt(len*factor)); MessageWeight overrides pass through intact (flags no
longer silently reduced to the scalar weight).
- pixmo_cap truncation: raise when all loss tokens are cut; recompute
1/sqrt(n_subsegments) over surviving branches (example_preprocessor post-
pass parity).
Pipeline correctness:
- MixtureDataLoader prefetch: refs are consumed on the submitting thread and
results yield in ref order for any worker count (the previous stateful
worker-side iterator made example order — and therefore packing and resume
replay — nondeterministic with prefetch_workers > 1); error counters are
lock-guarded and skip-broken keeps 1:1 ref->result order.
- Non-finite-loss guard: reduce_distributed_failure_flag is now an
unconditional per-microbatch collective — calling it only on failing ranks
mismatched healthy ranks' backward collectives (NCCL hang).
- Trainer: remove per-step debug log lines left in the core fit loop.
- Molmo2-Stage2: residual dropout 0.1 (mm_olmo SFT fine-tuning setting).
- Remove dead encode_text_only_sft (unshifted labels; would prepend
<|im_end|> as BOS) and the dead pointing message-weight helper; correct the
mislabeled EOS_TOKEN_ID comment (151643 is the pad token).
Co-Authored-By: Claude Fable 5 <[email protected]>
…extras).
Ports the six user-added SFT sources that do not exist in mm_olmo:
MMFineReason-SFT-586K (long-form multimodal reasoning; only the <answer>
content of the original_answer column is supervised, the <think> trace is
dropped — see extract_answer_text) and five verified FineVision configs
(visualwebinstruct(filtered) 263,581 / mavis_math_rule_geo 99,986 /
mavis_math_metagen 87,348 / geo170k(align) 35,297 / geo170k(qa) 12,101),
one loader for any FineVision config with the four per-row quality-minimum
filters (min_visual_dependency is the useful one; image_correspondence_min
is 1 for most synthetic-geometry rows).
Compared to the original working-tree version, sequence assembly now goes
through the shared stage-2 encode path (encode_sft_example), so these sources
use exactly the same qwen3 layout as the rest of the mixture: NO leading BOS
(the old [BOS] was <|im_end|> on Molmo2's tokenizer), the image token
block(s) inside the first user turn with 'Image {i+1}' prefixes for
multi-image rows, multi-turn rows as ONE sequential branch with mm_olmo turn
semantics (no loss at intermediate turn ends), and mm_olmo's per-example rng
derivation. encode_sft_example also gains text-only (zero-image) support.
sft_common keeps the shared plumbing: parquet/arrow map-style loading (via
the datasets-compat loader), <image>-placeholder stripping, PIL decoding,
image-token-safe truncation (now also refusing to drop every loss token),
and deterministic bad-row skipping.
Molmo2-Stage2.py exposes the sources as optional extras (MMFINEREASON_RATE +
FINEVISION_RATES, all 0.0 by default): enabling them scales the 43 official
image-only-v9 sources by (1 - sum(extra rates)) and appends the extras, so
the official recipe is diluted proportionally and never silently reweighted.
Also fixes a latent dataset_compat bug the new tests exposed: the List->
Sequence feature alias is now a no-op on datasets >= 5 (which has a native
List) — the process-global alias made Sequence re-order any later-loaded
list-of-structs column into a struct-of-lists, breaking unrelated loads.
Verified: 32 CPU tests (answer parsing, filters, layout, packing-compat,
end-to-end from synthetic parquet) + real-weka smoke tests for geo170k(qa)
(12,101 rows) and MMFineReason (585,744 rows) with the real tokenizer —
im_patch/pooled invariant holds and sequences start '<|im_start|>user\n
<low_res_im_start>...' like every other stage-2 source.
Co-Authored-By: Claude Fable 5 <[email protected]>
|
Pushed 5 stacked commits (
All 145 data-layer CPU tests + 10 Molmo2-4B GPU parity tests pass. Full commit messages carry the details and mm_olmo line references. 🤖 Generated with Claude Code |
…idable. The mm_olmo parity-bridge root honors the MM_OLMO_ROOT env var (used only by the offline parity harness, never by training); the harness's conda / activate-script defaults are flagged with their CLI overrides; the stage-2 default load path is flagged with the --trainer.load_path override. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 17b441a079
ℹ️ 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".
| **flex_mask_kwargs | ||
| ) | ||
|
|
||
| if not use_flex_attn: |
There was a problem hiding this comment.
Build dense masks unless the backend is actually flex
When OLMO2_FLEX_ATTN=1 is present but the Transformer was built or overridden with the torch attention backend, this branch skips constructing the dense or_mask/and_mask. The only mask passed is flex_attn_block_mask, and Attention.sdpa ignores that unless the backend is FlexAttentionBackend, so torch attention runs without bidirectional image-token attention or packed-example/subsegment isolation. That silently corrupts packed multimodal batches in this configuration; gate this on the actual backend or still build dense masks for non-flex backends.
Useful? React with 👍 / 👎.
| else: | ||
| from datasets import load_from_disk | ||
|
|
||
| return load_from_disk(str(path), **kwargs) |
There was a problem hiding this comment.
Check every DatasetDict split before falling back
For a DatasetDict, this returns load_from_disk() as soon as the first split without a legacy List schema is seen. If a later split contains the deprecated List feature, the compat path is never used for that split, and load_from_disk() still parses the whole dict and can hit the same schema failure this helper is meant to avoid. Multi-split datasets with mixed schemas should scan all splits first and only fall back to load_from_disk() when none need the Arrow loader.
Useful? React with 👍 / 👎.
…Stage2. --mmfinereason_rate / --finevision_rate (total, split evenly across the five FineVision configs) let comparison runs toggle the extra SFT sources without editing module constants; official sources rescale by 1 - sum(extras). Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6364d4b61a
ℹ️ 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 response_mask is not None: | ||
| response_mask = move_to_device(response_mask, self.device) | ||
|
|
There was a problem hiding this comment.
Shard response masks under context parallelism
When response_logits_only is used with context parallelism, this keeps the full (B, S) response_mask in lm_head_kwargs, but the CP path below only sequence-shards input_ids, labels, and RoPE buffers. The LM head then applies an unsharded mask to a sequence-sharded hidden tensor, so response-only logits either fail shape checks or select the wrong positions; add response_mask to the CP sharding inputs or reject this combination.
Useful? React with 👍 / 👎.
| # mm_olmo's count is always len(points) (data_formatter.py:1141) — never a | ||
| # dataset-provided "count" field, which its formatter cannot even see. | ||
| if style in ("point_count", "point_then_count"): | ||
| return pointing_answer(norm, label, "point_count") |
There was a problem hiding this comment.
Preserve explicit counts in counting answers
When PixMoCountDataset builds a point_count row it passes row['count'] into the formatter, but this path ignores that field and lets pointing_answer() fall back to len(points). For count rows whose point coordinates are missing, capped, or otherwise not exactly the count label, the supervised answer says the wrong number (or There are none.); pass example.get('count') through for counting styles.
Useful? React with 👍 / 👎.
| assert self._sft_formatter is not None | ||
| rng = example_rng(self.config.seed, index) | ||
| turns = self._sft_formatter.format_turns(formatted, index=index, rng=rng) | ||
| return encode_sft_example( |
There was a problem hiding this comment.
Apply max-sequence truncation in sft demo mode
In mode='sft_demo', this returns the encoded PixMoCap example directly and bypasses the max_sequence_length truncation used by the other PixMoCap modes, even though the stage-2 registry passes that limit into this config. Any overlength caption example is then left for the packer/collator to tail-cut without the _truncate() checks that preserve <im_patch>/pooled-feature alignment and ensure some loss tokens survive.
Useful? React with 👍 / 👎.
…iant (#818) Stage 1 is pretraining, but the script started from the released `allenai/Molmo2-4B` — an already post-trained model — and continued it on the stage-1 objective. The last 32k-step run opened at CE ~1.15 where mm_olmo's true stage-1 start is ~3.1. `init_from` now defaults to `"scratch"`, reproducing mm_olmo's `reset_with_pretrained_weights`: LM from the base Qwen3 backbone (128 extra embedding rows N(0, 0.02)), ViT from base google/siglip2-so400m-patch14-384 (blocks 0..24 of 27, matching vit_layers (24, 18)), connector randomly initialised. `--init_from=molmo2` keeps the old behaviour for parity tests and continuation experiments. A scratch run now reads *nothing* from the released Molmo2 repo — not weights, not the config, not the tokenizer. `MultimodalLMConfig.molmo2_4B()` / `molmo2_8B()` build the architecture natively from `TransformerConfig.qwen3_4B`/`qwen3_8B` plus a shared `_molmo2_like` vision stack; a cache-gated test pins each field-for-field to `molmo2_config_from_hf_config` on the corresponding released config. The tokenizer is the base Qwen3 backbone's, verified a drop-in for training (identical BPE, identical eos_token_id 151645, byte-identical output for the only chat-template calls the data pipeline makes — Qwen3's template diverges only for assistant messages, which qwen3_layout.py never passes). `--model_size=4b|8b` selects the architecture factory, the base backbone, the released checkpoint and the tokenizer, via a typed frozen `ModelSizeSpec`. An 8B stage-1 run is planned, so the variant lands with the plumbing that uses it. Three real bugs fixed: * The tied head was not actually tied. `to_empty` unties tied word embeddings, so the head and the embedding table were two independent tensors that would drift apart during training. The molmo2 path already called `retie_word_embeddings`; the scratch path did not. * Wrong RoPE base for scratch runs. Deriving the architecture from a released config while loading base weights put base Qwen3-4B weights on the released model's 5e6 base instead of the 1e6 they were trained with. `rope_theta` now follows the weight source. The 8B confirms why this matters: base Qwen3-8B and released Molmo2-8B are both 1e6, so the released 4B is the only variant disagreeing with its own backbone. * The 8B path discarded Qwen3-8B's trained `lm_head`. The init unconditionally overwrote it with the embedding table, which is right only for a tied backbone; Qwen3-8B and Molmo2-8B are untied and the converter emits a distinct trained head for them. The head is now built per tying, with the 128 extra rows zero-padded (masked by `output_vocab_size`, so no softmax contribution and no gradient — matching mm_olmo's untied `ff_out`). Also: one SigLIP converter instead of two. The mapping only existed in `parity_test.py` and had been copied into the training script; it is now `olmo_core.nn.vision.siglip_state_dict_to_vision_encoder` with `n_blocks` / `prefix` arguments, accepts `SiglipVisionModel` state dicts directly, and raises if more blocks are requested than the checkpoint has. And `make checks` was already failing on Molmo2-Stage1.py on `vision` (ruff E402 from #806's mid-file import, plus isort/black), now fixed. Verified: 97 passed / 17 skipped in src/test/nn/vision, with the CLIP/SigLIP/SigLIP2 parity tests exercising the shared converter. Both native configs identical to their HF-derived counterparts. Scratch init run end-to-end on CPU for both sizes against the real architectures — exact state-dict coverage, 4.462B / 8.662B params, new rows at std 0.0200, 4B tied and sharing storage, 8B correctly untied with head[:151936] equal to the base trained lm_head, 25 vision blocks with loaded SigLIP2 weights, 0 non-finite. Invalid `--model_size` / `--init_from` rejected at config-build time rather than after a Beaker job has queued and downloaded weights. isort/black/ruff clean; mypy at the `vision` baseline.
…the 2D-knapsack packer (#824) The two remaining settings from the released `Molmo2-4B-Pretrain/config.yaml` that were reachable without new code. Both are already-implemented capabilities this script never turned on. ## Activation checkpointing + microbatch 4 Released config: `activation_checkpointing: true`, `llm.activation_checkpoint: whole_layer`, `device_train_microbatch_size: 4`. `ac_config` already exists on `MultimodalTransformerTrainModuleConfig` and wires to `Transformer.apply_activation_checkpointing` — it was simply left `None`, which is why microbatch >1 OOM'd in earlier probes. Setting `mode=full` (checkpoint every block, i.e. mm_olmo's `whole_layer`) and microbatch 4 together, since the first is what pays for the second. Vision and connector AC were already on by default, matching the released config's vit `activation_checkpointing: true` and `connector_activation_checkpointing: true`. **Divisibility:** `128 % (4 x dp_world_size)` must be 0, so microbatch 4 supports world sizes up to 32 — the released 4B ran 16 GPUs, the 8B ran 32. At 64 GPUs use microbatch 2. ## 2D-knapsack packing Released config: `packing: {mode: dynamic_solver, buffer_size: 48, text_weight: 1.0, image_weight: 1.0}`. `iter_dynamic_packs` (a verbatim port of mm_olmo's solver) has been in the repo since #806, but stage 1 never passed `pack_max_crops`, so it silently fell through to token-only next-fit. Now wired — **with `image_weight=1.0`**, since `MixtureDataLoader` defaults to 30.0 and wiring it up without overriding that would still have diverged. `PACK_MAX_CROPS = 3 * (1 + 8)` — the crop budget is the knapsack's second dimension. Measured with `build_image_token_ids`, an 8-crop example costs at most 9 crops (1 global + 8 high-res) and ~1348 image tokens, so at seq 2560 the **token** budget binds first and the crop cap mainly bounds worst-case ViT/collator memory. Set below a single example's 9 crops, it would force that example into its own mostly-padding pack. ### Measured effect, and where it actually comes from Synthetic stream shaped like the real mixture (image examples ~1400 tok / 9 crops, text-only ~600 tok), 81 packs each: | stream | knapsack | next-fit | |---|---|---| | image-only | 1.00 ex/pack, 54.7% fill | **identical** | | with text-only (Tulu) | **1.70 ex/pack, 69.3% fill** | 1.00 ex/pack, 44.3% fill | So the gain is almost entirely **cross-modal packing**. `iter_packs` deliberately refuses to mix text-only and image-bearing examples in one pack ("head-truncating a cross-modal pack can orphan `<im_patch>` tokens from their pooled rows"); the knapsack has no such guard, and mm_olmo likewise packs across modalities whenever `nlp > 0` (`shortcut_max_len_images: args.nlp == 0`). **That removed guard deserves review attention.** The invariant it protects — one `<im_patch>` token per pooled row — held in **0/81 packs** for both packers on both streams, because the knapsack respects the token budget by construction so nothing gets truncated. Note also that the equal-length synthetic *understates* the knapsack on image-only data: real caption lengths vary, which a knapsack can exploit and sequential next-fit cannot. ## Verification * 242 passed / 17 skipped across `src/test/nn/vision` and `src/test/data/multimodal`. * Packer exercised directly (numbers above), including the `<im_patch>`/pooled-row invariant. * `isort` / `black` / `ruff` / `mypy` clean. ## Not yet validated **Whether microbatch 4 with AC actually fits at seq 2560 has not been confirmed on GPU.** That is the entire point of the change and it matches what mm_olmo ran on comparable hardware, but it warrants a short GPU run before a full launch — earlier microbatch probes OOM'd precisely because AC was off. Co-authored-by: Jason Ren <[email protected]>
No description provided.