Repository navigation
[1/n] Add vision transformer, connector, and MultimodalLM - #692
Conversation
CI failure analysisAll 3 failing CI jobs are due to the PR coming from an external fork ( Test (CPU)5 tests fail — all with credential errors, not logic errors:
These tests all pass on PRs from within the main repo (e.g. #681) where secrets are available. Test checkpointFails with S3 Test olmo3 ladderFails with empty Beaker token — same root cause. These failures are pre-existing on all external fork PRs and do not reflect on the correctness of the vision architecture code being introduced here. |
VLM/multimodal vision-language architecture stack: - VisionBackbone (OpenAI CLIP / SigLIP / SigLIP2): OpenAI-style ViT encoder with configurable image size, patch size, embedding dim, and attention heads. Supports CLIP (openai), SigLIP (siglip), and SigLIP2 (siglip2) initialisation. - VisionConnector: attention-pooling (2×2) + SwiGLU MLP projector that maps vision embeddings to the language-model hidden dimension. - MultimodalTransformer: composite model that fuses image patch tokens into the LM token stream at image-patch positions, then runs the full LM forward pass. - Removed DINOv2 backbone variants (not used in Molmo2). - HF parity tests for CLIP, SigLIP, and SigLIP2 vision encoders.
There was a problem hiding this comment.
Pull request overview
Adds the first slice of multimodal/VLM support to olmo_core.nn by introducing a vision backbone (ViT variants), a vision→LM connector, and a composite multimodal model that splices projected image features into the LM embedding stream. This lays the groundwork for subsequent PRs to build full multimodal training/inference workflows.
Changes:
- Added new vision modules:
VisionTransformer/SiglipVisionTransformer,VisionConnector, andMultimodalTransformerwith corresponding config objects. - Extended the LM
Transformer.forward()API to optionally accept precomputedinput_embeddings(for multimodal fusion). - Added unit tests and HF parity tests for CLIP/SigLIP/SigLIP2 equivalence (skipping when checkpoints/deps aren’t available).
Reviewed changes
Copilot reviewed 13 out of 14 changed files in this pull request and generated 5 comments.
Show a summary per file
| File | Description |
|---|---|
src/olmo_core/nn/vision/__init__.py |
Exposes vision and multimodal public API from the new vision package. |
src/olmo_core/nn/vision/config.py |
Adds VisionBackboneConfig / VisionBackboneType and factory methods for CLIP/SigLIP/SigLIP2 variants. |
src/olmo_core/nn/vision/image_vit.py |
Implements CLIP-style and SigLIP-style ViT encoders returning per-layer hidden states. |
src/olmo_core/nn/vision/connector.py |
Implements pooling + projection connector from vision features to LM d_model. |
src/olmo_core/nn/vision/multimodal.py |
Implements composite multimodal model that injects pooled image features into LM embeddings. |
src/olmo_core/nn/transformer/model.py |
Adds input_embeddings support to Transformer.forward() for multimodal embedding splice. |
src/olmo_core/nn/__init__.py |
Re-exports vision/multimodal modules at the olmo_core.nn package level. |
src/test/nn/vision/__init__.py |
Adds test package initializer for vision tests. |
src/test/nn/vision/config_test.py |
Tests vision config factories, build dispatch, and basic invariants. |
src/test/nn/vision/image_vit_test.py |
Tests ViT forward shapes, determinism, CLS presence, and pos-emb interpolation behavior. |
src/test/nn/vision/connector_test.py |
Tests connector pooling/projector variants, padding mask behavior, and multi-layer inputs. |
src/test/nn/vision/multimodal_test.py |
Tests multimodal forward in text-only and image-splice modes, plus multi-crop and meta device. |
src/test/nn/vision/parity_test.py |
HF numerical parity tests for CLIP/SigLIP/SigLIP2 vision encoders (skip when unavailable). |
CHANGELOG.md |
Documents the addition of the new multimodal/vision modules. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
- image_vit.py: drop the `transformers` dependency. The needed activations (`quick_gelu`, `gelu_pytorch_tanh`, `gelu`) are implemented with plain PyTorch ops (verified bit-exact vs transformers); unknown names raise. - transformer/model.py: raise early when `input_embeddings` is used with context parallelism, which would misalign the (unsharded) embeddings against sharded input_ids/labels/RoPE. - multimodal.py: make the image-feature splice robust to a non-contiguous `h` by calling `.contiguous()` before the masked view-assignment. - config.py: use `Self` for factory return types; clarify the `image_num_layers`=23 docstring (full CLIP tower is 24; final block unused when reading from layer -2). - Convert relative imports to absolute across the vision modules and drop external-project references from docstrings. - parity_test.py: try `local_files_only=True` first so cached checkpoints don't trigger a network download.
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
AkshitaB
left a comment
There was a problem hiding this comment.
Class structure and organization looks good to me overall. Added a couple of questions / comments mostly to understand the conventions in multimodal work.
Address PR review: mirror the LM TransformerBlockConfig pattern on the vision side. Promote ViTAttention/ViTMLP/ViTBlock to public classes and add a VisionBlockType enum + VisionBlockConfig with a build() dispatch, selected via the new VisionBackboneConfig.block field. State dict keys are unchanged, so existing checkpoints and the HF loader are unaffected.
- Collapse VisionTransformer/SiglipVisionTransformer into a single configurable VisionTransformer; the CLS-token, patch-embedding-bias, and pre-LN switches are now explicit fields on the encoder config. - Rename VisionBackboneConfig/VisionBackboneType -> VisionEncoderConfig/ VisionEncoderType (and VisionConnectorConfig.from_vision_backbone -> from_vision_encoder). - Rename MultimodalTransformer/Config -> MultimodalLM/Config. State dict keys are unchanged for both CLIP and SigLIP variants, so the HF loader and parity tests are unaffected.
> Supersedes #693. **Targets the `vision` branch** — the integration branch for the multimodal stack now that [1/n] (#692) is merged to main (`vision` currently equals that merge commit). Diff is the Molmo2 loader only, rebased to a single commit. ## Summary 2nd PR in the VLM stack building Molmo2-style multimodal support. - [1/n] Vision architecture (#692) - **[2/n] This PR — HF Molmo2 loader** 1. **`molmo2_loader.py`** — HF Molmo2 → `MultimodalLM` weight converter handling three architecture deltas: - **Embedding split**: concatenates HF's `wte.embedding` + `wte.new_embedding` into one flat `embeddings.weight` - **Fused QKV + gated MLP**: splits `att_proj` → `w_q`/`w_k`/`w_v` and `ff_proj` → `w1`/`w3` - **Patch-embedding flatten order**: permutes spatial-first `(kh,kw,c)` HF weights to channel-first `(c,kh,kw)` Also exports two public helpers for transformers 5.x compatibility: - `ensure_default_rope_registered()` — re-registers `ROPE_INIT_FUNCTIONS["default"]` before `from_pretrained` - `reinit_rope_buffers(model)` — re-runs `rope_init_fn` after loading to fix uninitialised `inv_freq` buffers 2. **Parity tests** (`molmo2_parity_test.py`, `molmo2_logits_parity_test.py`): - Vision encoder: max abs diff < 5e-3 in fp32 at every ViT layer the connector reads - Embedding: < 1e-3 in bf16 - LM-only forward and full pipeline (4B and 8B) 3. **Generation test** (`molmo2_generation_test.py`): - PIL-based single-crop preprocessor (no torchvision) — resize → SigLIP2 normalize → patchify → 2×2 pool - Synthetic RGB gradient image + prompt `"What colors do you see?"` → greedy-decode 8 tokens - Asserts our model's token IDs match HF exactly step-by-step ## Parity results (bfloat16, GPU) | Variant | Embedding diff | LM argmax | LM max diff | Full pipeline argmax | Generation (8 tok) | |---------|---------------|-----------|-------------|---------------------|-------------------| | Molmo2-4B | < 1e-3 | ✅ match | **0.125** (thr 1.0) | ✅ match | ✅ exact match | | Molmo2-8B | < 1e-3 | ✅ match | **0.313** (thr 1.0) | ✅ match | (4B only tested) | | Molmo2-O-7B | < 1e-3 | — |⚠️ skipped |⚠️ skipped | — | Vision-encoder layer parity (fp32, all 3 variants): max abs diff < 5e-3 ✅ O-7B logit tests skipped: uses per-layer YaRN attention scaling (`attention_factor ≈ 1.208`) on 24/32 LM layers; `MultimodalLM` uses a single global RoPE config. Vision-encoder and embedding parity still pass for O-7B. ## Generation QA (Molmo2-4B, bf16) Prompt: image of a synthetic RGB gradient (red↗ green↗ blue=flat) + `"What colors do you see?"` ``` Question : What colors do you see? HF output: The colors I see in this image are: - Blue - Purple - Pink - Green Our output: The colors I see in this image are: - Blue - Purple - Pink - Green Token IDs (HF = ours): [785, 7987, 358, 1490, 304, 419, 2168, 525] ``` Both models produce **identical token IDs** for all 8 greedy-decode steps, and the answer is semantically coherent for the image content. ## transformers 5.x RoPE compat transformers 5.8.1 removed `ROPE_INIT_FUNCTIONS["default"]` and its fast-init (meta-device) leaves non-persistent `inv_freq` buffers uninitialised. The two-step fix lives in `molmo2_loader.py`: ```python ensure_default_rope_registered() # before from_pretrained hf = AutoModelForImageTextToText.from_pretrained(model_id, trust_remote_code=True) reinit_rope_buffers(hf) # after from_pretrained ``` ## Test command ```bash # Requires Molmo2 checkpoints in HF cache; auto-skips otherwise pytest -v src/test/nn/vision/molmo2_parity_test.py \ src/test/nn/vision/molmo2_logits_parity_test.py \ src/test/nn/vision/molmo2_generation_test.py ``` --- ## Verification on the rebased tip (`035f86fa`) - **Full vision suite: 88 passed, 2 skipped** (4m40s) — includes real-checkpoint Molmo2 **4B/8B vision, logit, and generation parity**. The 2 skips are the intentional Molmo2-O-7B per-layer-YaRN cases. - `ruff` / `mypy` / `isort` / `black` all clean. - The rebase onto `vision` is content-identical to the previously tested commit (same git tree), and the suite was re-run fresh on the rebased tip to confirm. ## Review feedback from #693 — status | Comment | Status | |---|---| | `molmo2_loader_test.py` imports `olmo_core.data.multimodal` (doesn't exist yet) | ✅ Fixed — test now owns a self-contained base/extra vocab split (120+8), no forward dependency; the embedding-split path is actually exercised now | | `torch.zeros(...)` padding fails when the HF state dict is on CUDA | ✅ Fixed — uses `hf_lm_head.new_zeros(...)`, preserving device and dtype | | HF-config → factory dispatch is a growing, hard-to-maintain list that ignores many HF fields | ✅ TODO added on `_build_lm_config` to replace the preset-matching table with a generic builder constructing `TransformerConfig` directly from HF fields | | Zero-padded extra-vocab `lm_head` rows give finite logits and shift the loss vs HF | ✅ Documented (not masked here) — the misleading "matches HF exactly" comment is corrected; exact **loss** parity requires masking those output IDs to `-inf` at the loss/forward layer, which is out of scope for a weight converter and deferred to the training/eval PRs. Argmax/generation parity is unaffected, and the logit-parity tests compare base-vocab columns only |
> Supersedes #693. **Targets the `vision` branch** — the integration branch for the multimodal stack now that [1/n] (#692) is merged to main (`vision` currently equals that merge commit). Diff is the Molmo2 loader only, rebased to a single commit. ## Summary 2nd PR in the VLM stack building Molmo2-style multimodal support. - [1/n] Vision architecture (#692) - **[2/n] This PR — HF Molmo2 loader** 1. **`molmo2_loader.py`** — HF Molmo2 → `MultimodalLM` weight converter handling three architecture deltas: - **Embedding split**: concatenates HF's `wte.embedding` + `wte.new_embedding` into one flat `embeddings.weight` - **Fused QKV + gated MLP**: splits `att_proj` → `w_q`/`w_k`/`w_v` and `ff_proj` → `w1`/`w3` - **Patch-embedding flatten order**: permutes spatial-first `(kh,kw,c)` HF weights to channel-first `(c,kh,kw)` Also exports two public helpers for transformers 5.x compatibility: - `ensure_default_rope_registered()` — re-registers `ROPE_INIT_FUNCTIONS["default"]` before `from_pretrained` - `reinit_rope_buffers(model)` — re-runs `rope_init_fn` after loading to fix uninitialised `inv_freq` buffers 2. **Parity tests** (`molmo2_parity_test.py`, `molmo2_logits_parity_test.py`): - Vision encoder: max abs diff < 5e-3 in fp32 at every ViT layer the connector reads - Embedding: < 1e-3 in bf16 - LM-only forward and full pipeline (4B and 8B) 3. **Generation test** (`molmo2_generation_test.py`): - PIL-based single-crop preprocessor (no torchvision) — resize → SigLIP2 normalize → patchify → 2×2 pool - Synthetic RGB gradient image + prompt `"What colors do you see?"` → greedy-decode 8 tokens - Asserts our model's token IDs match HF exactly step-by-step ## Parity results (bfloat16, GPU) | Variant | Embedding diff | LM argmax | LM max diff | Full pipeline argmax | Generation (8 tok) | |---------|---------------|-----------|-------------|---------------------|-------------------| | Molmo2-4B | < 1e-3 | ✅ match | **0.125** (thr 1.0) | ✅ match | ✅ exact match | | Molmo2-8B | < 1e-3 | ✅ match | **0.313** (thr 1.0) | ✅ match | (4B only tested) | | Molmo2-O-7B | < 1e-3 | — |⚠️ skipped |⚠️ skipped | — | Vision-encoder layer parity (fp32, all 3 variants): max abs diff < 5e-3 ✅ O-7B logit tests skipped: uses per-layer YaRN attention scaling (`attention_factor ≈ 1.208`) on 24/32 LM layers; `MultimodalLM` uses a single global RoPE config. Vision-encoder and embedding parity still pass for O-7B. ## Generation QA (Molmo2-4B, bf16) Prompt: image of a synthetic RGB gradient (red↗ green↗ blue=flat) + `"What colors do you see?"` ``` Question : What colors do you see? HF output: The colors I see in this image are: - Blue - Purple - Pink - Green Our output: The colors I see in this image are: - Blue - Purple - Pink - Green Token IDs (HF = ours): [785, 7987, 358, 1490, 304, 419, 2168, 525] ``` Both models produce **identical token IDs** for all 8 greedy-decode steps, and the answer is semantically coherent for the image content. ## transformers 5.x RoPE compat transformers 5.8.1 removed `ROPE_INIT_FUNCTIONS["default"]` and its fast-init (meta-device) leaves non-persistent `inv_freq` buffers uninitialised. The two-step fix lives in `molmo2_loader.py`: ```python ensure_default_rope_registered() # before from_pretrained hf = AutoModelForImageTextToText.from_pretrained(model_id, trust_remote_code=True) reinit_rope_buffers(hf) # after from_pretrained ``` ## Test command ```bash # Requires Molmo2 checkpoints in HF cache; auto-skips otherwise pytest -v src/test/nn/vision/molmo2_parity_test.py \ src/test/nn/vision/molmo2_logits_parity_test.py \ src/test/nn/vision/molmo2_generation_test.py ``` --- ## Verification on the rebased tip (`035f86fa`) - **Full vision suite: 88 passed, 2 skipped** (4m40s) — includes real-checkpoint Molmo2 **4B/8B vision, logit, and generation parity**. The 2 skips are the intentional Molmo2-O-7B per-layer-YaRN cases. - `ruff` / `mypy` / `isort` / `black` all clean. - The rebase onto `vision` is content-identical to the previously tested commit (same git tree), and the suite was re-run fresh on the rebased tip to confirm. ## Review feedback from #693 — status | Comment | Status | |---|---| | `molmo2_loader_test.py` imports `olmo_core.data.multimodal` (doesn't exist yet) | ✅ Fixed — test now owns a self-contained base/extra vocab split (120+8), no forward dependency; the embedding-split path is actually exercised now | | `torch.zeros(...)` padding fails when the HF state dict is on CUDA | ✅ Fixed — uses `hf_lm_head.new_zeros(...)`, preserving device and dtype | | HF-config → factory dispatch is a growing, hard-to-maintain list that ignores many HF fields | ✅ TODO added on `_build_lm_config` to replace the preset-matching table with a generic builder constructing `TransformerConfig` directly from HF fields | | Zero-padded extra-vocab `lm_head` rows give finite logits and shift the loss vs HF | ✅ Documented (not masked here) — the misleading "matches HF exactly" comment is corrected; exact **loss** parity requires masking those output IDs to `-inf` at the loss/forward layer, which is out of scope for a weight converter and deferred to the training/eval PRs. Argmax/generation parity is unaffected, and the logit-parity tests compare base-vocab columns only |
|
This PR has been released in v2.6.0. |
…ing (#910) ## Summary PR 1 of 4 for moving the Molmo2 stage-1 reproduction from the long-lived `vision` branch onto `main` in reviewable pieces (follows `[1/n]` #692). This one is the **model side only**: no data pipeline, no train module, no scripts. Everything is opt-in; existing `Transformer` / `OLMo` configs behave exactly as before. ## What is in this PR, how each piece is used, and why it has to be here ### 1. HF Molmo2 loader (`nn/vision/molmo2_loader.py`) - **What:** converts a released HuggingFace Molmo2 checkpoint (4B / 8B) into a `MultimodalLM` state dict (fused QKV and gated-MLP splitting, the base/extra embedding split, the patch-embedding flatten order), and derives a `MultimodalLMConfig` from an HF config (`molmo2_config_from_hf_config`). - **How it is used:** (a) **correctness oracle**: every parity and generation test loads the released weights through it and compares against the HF reference model, which is the only way to *prove* our architecture is Molmo2 and not merely Molmo2-shaped; (b) `MultimodalLMConfig.molmo2_4B()/molmo2_8B()`, the factories stage 1 trains from, are asserted equal to the HF-derived config (`molmo2_native_config_test`), so a launch needs no HF access; (c) `Molmo2-Stage1.py --init_from=molmo2` (continue from the released checkpoint) goes through the converter. - **Why here:** the model is only trustworthy once it matches HF numerically; landing the model without the thing that verifies it would leave #911-#913 building on unverified code. ### 2. FlexAttention backend (`nn/attention/backend.py`, plus the dense `or_mask` / `and_mask` path) - **What:** an attention backend that expresses Molmo2's mask (causal, image tokens attending bidirectionally to each other, and isolation between the branches/examples packed into one sequence) as a fused kernel built from per-token vectors, instead of materialising a `(B, 1, S, S)` boolean mask. - **How it is used:** stage 1 packs several annotations per image into one sequence, so every training step needs this mask. `Molmo2-Stage1.py` sets `USE_FLEX_ATTN = True` (about +8% MFU over the dense `torch` backend, per the script). The dense masks stay as the CPU / inference path and as the oracle: `flex_backend_test` checks flex against dense for causal / or / and / both, MHA and GQA, and `test_packed_examples_are_isolated` checks packed examples don't leak into each other (dense and flex). - **Why here:** the mask semantics are part of the model definition (HF Molmo2 attends bidirectionally over image tokens; getting this wrong silently changes logits, see the bidirectional-vs-causal parity numbers below), and `MultimodalLM.forward` is where the mask gets built. ### 3. Split-vocab embedding (`nn/embedding.py`, `TransformerConfig.n_extra_vocab`) - **What:** an embedding table split into a base block and a small "extra" block (Molmo2's 128 image-special tokens) held as two parameters, with an LM head that spans only the base vocab and can be tied to the base block. - **How it is used:** HF Molmo2 stores `wte.embedding` and `wte.new_embedding` separately, so the loader maps them one-to-one onto `embeddings.weight` / `embeddings.extra_weight`. Stage 1 sets `freeze_base_embeddings=True`: it keeps the pretrained vocabulary fixed while learning the new image tokens. With one fused table that is a partial-row freeze, which `requires_grad` cannot express; with the split it is `embeddings.weight.requires_grad_(False)`. It also gives the head the base width structurally (extra tokens are inputs, never targets), which replaced an earlier logit-masking mechanism that I deleted as dead code in this PR. - **Why here:** it changes the model's parameter layout, and the loader (above) and every checkpoint conversion depend on that layout, so it cannot come later without re-doing the loader. ### Smaller opt-in pieces the model needs `response_logits_only` (compute logits only at response positions, used by the train module to save memory), `masked_dropout` (Molmo2's `response_residual_dropout`: 10% residual dropout on response tokens only), `RoPE position_ids` (packed branches share an overlapping position range), and ViT / connector activation checkpointing and compile hooks. ## Why this PR is fundamental Everything else in the series imports from it, so it must land first: | PR | What it takes from this one | |---|---| | #911 train module | wraps `MultimodalLM`; calls `response_logits_only`, `masked_dropout`, the flex backend, the ViT / connector AC and compile hooks | | #912 data core | special-token ids (`molmo2_tokens`) and the sequence layout (`position_ids`, sub-segments, image-token spans) that `MultimodalLM.forward` consumes | | #913 stage-1 recipe | `MultimodalLMConfig.molmo2_4B/8B`, `n_extra_vocab` + `freeze_base_embeddings`, the loader for `--init_from=molmo2` | It also defines the numerical contract (parity with released Molmo2) that the later PRs are checked against, and it is the only PR whose correctness can be validated without data or a trainer. It is safe to merge first: all defaults are unchanged and text-side behaviour is bit-identical to `main` (see below). ## Series: all PRs Linear stack. Each PR is cut fresh from `main` (not cherry-picked from `vision`), so every diff shows only its own change; the base is retargeted to `main` as parents land. | # | PR | Contents | Touches | |---|---|---|---| | 1/4 | #910 Model **← this PR** | Molmo2 HF loader, image processor, flex attention, split-vocab embedding, `MultimodalLM` extensions | `nn/` | | 2/4 | #911 Train infrastructure | `MultimodalTransformerTrainModule`, `PerGroupScheduler`, weighted CE, unsharded-export callback | `train/`, `optim/`, `nn/functional`, `distributed/` | | 3/4 | #912 Data core | sequence builder / branch packing, collator, mixture loader, SFT formatter, PixMo-Cap | `data/multimodal` (core) | | 4/4 | #913 Stage-1 recipe | stage-1 datasets, mixtures, `Molmo2-Stage1.py` | `data/multimodal` (datasets), `scripts/` | **Not yet opened (planned follow-ups):** - *AC-RNG follow-up*: make activation-checkpoint RNG replay cover `ResidualStream.masked_dropout`. It has to sit on top of #906, which rewrites the same lines, so it waits for #906. - *Stage 2* (`Molmo2-Stage2.py`, the `image_only_v9` mixture, multi-image datasets, `compare_sft_example.py`): stays on `vision` until this series lands, then follows as its own PR(s). - *Alignment / OLMoDDP multimodal layers* (#886, #889, #902, #903, currently targeting `vision`): rebased on top once `vision` is synced to `main`. ## Does this change anything on `main` / the text side? No intended text-side change. What was checked: - **Diff audit of every pre-existing file the series modifies** (`nn/transformer/{model,block,config}`, `nn/attention`, `nn/lm_head`, `nn/residual_stream`, `nn/rope`, `nn/ddp/block`, `train/callbacks/speed_monitor`, `optim`, `distributed`). All remaining edits add optional arguments that default to the old behaviour (`masked_dropout=0`, `n_extra_vocab=0`, `response_logits_only=False`, `position_ids=None`, `or_mask/and_mask=None`, ...). The audit also found two edits that *did* alter text behaviour; both were removed from the series: a reroute of FSDP2 gradient clipping in `TransformerTrainModule` (text FSDP2 models would have left the torchtitan path), and new "examples per second" metrics in `SpeedMonitorCallback` on text runs (now emitted only for batches carrying `example_ids`). - **Bit-for-bit comparison, `main` vs the series tip**, same seeds, CPU: `state_dict` keys and values, eval logits, loss, and every parameter gradient are identical (SHA-256 over the bytes) for `olmo2_1M` in eval, train, and train with `dropout=0.1`, and for a qwen3-style `llama_like` model with `qk_norm`. - **Existing (non-multimodal) test suites, run on `main` and on the tip of this series** (`src/test/{nn,train,optim,data,distributed}`, CPU): `main` 1175 passed / 8 failed; series tip 1204 passed / 8 failed. The 8 failures are identical on both and are environment issues (S3/network: `mixes_test` x3, S3 checkpoint tests x4; and `test_logprobs_match_after_roundtrip[gemma3]`). Nothing that passed on `main` fails on the series. - `mypy src/` (CI config, `<1.4`), ruff, black, isort all clean. - **Not covered:** text GPU/distributed paths (FSDP2, TP, CP, flash kernels) can't run on a CPU box. The GPU smoke below exercises FSDP2 on the multimodal path only, so text-side GPU CI remains the gap. ## Left out on purpose - Activation-checkpoint RNG replay for `masked_dropout` (`ac_rng_test`, `_dropout_is_active`). It touches the same lines as #906, which fixes the general case. I'll send a small follow-up on top of #906 so `ResidualStream.masked_dropout` also counts. Until then `masked_dropout` is inert by default but not AC-safe. - Two tests that need the data package (`test_packed_examples_are_isolated`, `molmo2_training_logits_parity_test`) move to PR 3. ## Testing **CPU:** `src/test/nn/vision`, `flex_backend_test`, `embedding_test`, `lm_head_test`, `residual_stream_test`: pass (the one failure, `parity_test::test_clip_parity`, is this dev box's `transformers` version; it passes on the Beaker image). `mypy src/` (CI config), ruff, black, isort clean. **GPU logit parity vs HF Molmo2 (Beaker, 1 GPU, bf16, 146 passed / 5 skipped / 0 failed):** max |diff| vs the HF reference. Two runs on different hardware: [A100](https://beaker.org/ex/01M47FK4ES7M0QY3BA2HDSS9TG) (on `987a5dbeb`, before the last trims) and [B300](https://beaker.org/ex/01M48RE6ZHWSD6CKGK216EVPA4) (on `3dd8281e4`, the current tip of #913). bf16 kernels differ across hardware, so the diffs move a little; the two A100-era runs agree to every printed digit with each other, i.e. the trims did not change numerics. | check | 4B (A100 / B300) | 8B (A100 / B300) | |---|---|---| | token embedding | 0.0 / 0.0 | 0.0 / 0.0 | | LM-only last-token logits | 0.203 / 0.188 | 0.250 / 0.250 | | full pipeline (ViT + connector + splice + LM) logits | 0.156 / 0.156 | 0.188 / 0.375 | | vision tower layers 18 and 24 | 1.5e-3 / 2.3e-3 | 4.9e-4 / 8.5e-4 | Argmax matches HF in every case; the weighted training loss and all-response logits match for both models; bidirectional image attention matches HF (0.25 vs 1.3 if left causal, i.e. the mask matters and is correct). Also passing on GPU: generation parity, FlexAttention vs dense masks, packed-example isolation, the multimodal train module. **Skipped: Molmo2-O-7B** (all 5 variants): per-layer YaRN attention scaling is not implemented in `MultimodalLM` (known, deferred), so O-7B is *not* verified by this series. **GPU training smoke (8x GPU, FSDP2)** on the tip of #913: [`mm-trim2-gpu-smoke`](https://beaker.org/ex/01M48RF37WG2Y6HWK05T7XKY5C) (B300): 30 steps of `Molmo2-Stage1.py`, CE 3.23 -> 2.57, grad norm 24.2 -> 7.7, checkpoint and unsharded export written. Earlier runs of previous commits (A100-class nodes) went 3.24 -> 2.61.
Summary
This is the first in a series of a few PRs adding VLM/multimodal support to OLMo-core.
What's in this PR
Three new modules under
src/olmo_core/nn/vision/:Vision encoder (
image_vit.py,config.py)A single, configurable
VisionTransformer(built fromVisionEncoderConfig) covering both supported encoder families. There is one module class; the architectural variant is selected entirely through config switches rather than separate subclasses:openai)use_cls_tokenTrue(prepends a learnable CLS)Falsepatch_embedding_biasFalseTrueuse_pre_lnTrue(LayerNorm before blocks)Falseopenai(CLIP)openai/clip-vit-large-patch14-336siglipgoogle/siglip-so400m-patch14-384siglip2google/siglip2-so400m-patch14-384Key config knobs:
image_default_input_size,image_patch_size,image_emb_dim,image_num_heads,image_num_layers,image_num_pos. Factory class-methods cover all standard Molmo2 variants.The transformer block follows the same pattern as the LM side:
ViTAttention/ViTMLP/ViTBlockare public, and the block is selected viaVisionBlockConfig/VisionBlockType(VisionEncoderConfig.block), so additional block implementations can be registered as they're added.VisionConnector(connector.py)Maps variable-length vision embeddings to the LM hidden dimension:
output_dim = lm.d_modelConstructed via
VisionConnectorConfig.from_vision_encoder(vis_cfg, output_dim, mlp_hidden_size).MultimodalLM(multimodal.py)Composite model holding
lm: Transformer,vision: VisionTransformer, andconnector: VisionConnector. It composes an LM rather than subclassingTransformer— the LM exposes a genericinput_embeddingsentry point (the standard precomputed-embeddings hook), and the multimodal logic lives here. Forward pass:VisionConnector.image_patch_token_idpositions.HF Parity Tests
src/test/nn/vision/parity_test.pyloads real checkpoints and asserts numerical equivalence between our implementation and HuggingFace's reference models. Tests skip automatically when checkpoints are not cached.Measured max absolute errors on CPU in float32 (24–27 transformer layers):
openai/clip-vit-large-patch14-336atol=3e-3, rtol=1e-3google/siglip-so400m-patch14-384atol=3e-3, rtol=1e-3google/siglip2-so400m-patch14-384atol=3e-3, rtol=1e-3These errors reflect genuine float32 accumulation across 24–27 attention/MLP layers from independent kernel implementations — not any precision loss. They are ~10–100× tighter than fp16 parity would require. State-dict key layouts are unchanged across the CLIP and SigLIP variants, so all three parity tests pass against the single configurable encoder.
Files changed