Repository navigation
[2/n] HF Molmo2 loader and logit parity tests - #715
Merged
Merged
Conversation
- molmo2_loader.py: HF Molmo2 → MultimodalLM weight converter (embedding split, fused QKV/MLP split, patch-embedding permute) - molmo2_parity_test.py: vision-encoder parity vs HF reference - molmo2_logits_parity_test.py: embedding + LM + full-pipeline logit parity (4B/8B pass; O-7B skipped pending per-layer YaRN support) - Fix transformers 5.x RoPE compat: re-register ROPE_INIT_FUNCTIONS['default'] and reinit non-persistent inv_freq buffers after from_pretrained fast-init Adapted to the unified VisionEncoderConfig / MultimodalLM API from [1/n], and addressed PR #693 review feedback: - lm_head padding now uses new_zeros to preserve the HF tensor's device/dtype, so conversion works when the state dict is on CUDA. - Decoupled molmo2_loader_test from the not-yet-added data.multimodal tokenizer (it now owns a self-contained base/extra vocab split). - Added a TODO to replace the hard-coded HF text_config → factory dispatch with a generic builder. - Documented that the zero-padded extra-vocab lm_head rows shift the loss vs HF; exact loss parity needs masking those output IDs to -inf at the loss layer (out of scope for the weight converter).
jason718
force-pushed
the
jasonr/vlm-2-molmo2-loader
branch
from
June 10, 2026 06:23
c3880f9 to
035f86f
Compare
jason718
added a commit
that referenced
this pull request
Jun 13, 2026
## Summary Adds **bidirectional image-token attention** to `MultimodalLM`, matching HF Molmo2. HF Molmo2 attends **bidirectionally among image tokens** (driven by `token_type_ids`) while text stays causal — image tokens see *all* image tokens in the prefix, not just earlier ones. Our `MultimodalLM` previously ran the LM **fully causal** over the spliced image tokens, so this was a real parity gap. Targets the `vision` integration branch; stacked on the Molmo2 loader (#715). ## Why this wasn't caught before The existing full-pipeline logit-parity test used **exactly one** `<im_patch>` token, where causal and bidirectional attention are identical — a structural blind spot. The generation test used 196 image tokens but never passed `token_type_ids` to HF, so HF ran causal too (causal-vs-causal). So the gap was entirely untested. ## What's in this PR ### Fix - `MultimodalLM.forward` gains an HF-aligned `token_type_ids` argument and builds a `(B, 1, S, S)` boolean **`or_mask`** (`True` where `image[q] & image[k]`). - `or_mask` is threaded through `Transformer.forward` → block kwargs → `Attention.forward`/`sdpa` → `TorchAttentionBackend`, which **OR's it onto the causal/sliding base** — exactly mirroring HF's `or_mask_function`, and correct even for sliding-window layers. - Capability-gated by `AttentionBackend.SUPPORTS_OR_MASK` (only the dense `torch` SDPA backend supports it). Flash/TE/Fused backends and context parallelism **raise** rather than silently fall back to causal. - `token_type_ids=None` → unchanged causal behavior (fully backward compatible). ### Test (pins the gap) `test_molmo2_image_bidirectional_attention_parity` (196 image tokens, real Molmo2-4B): - **(1)** with `token_type_ids`, our last-token logits match HF (bidirectional); - **(2)** pure-causal is **measurably worse** — guards against the test silently regressing to causal-vs-causal. ## Verification - **Full vision suite: 89 passed, 2 skipped** (the 2 skips are the intentional Molmo2-O-7B per-layer-YaRN cases). The new GPU parity test passes against real Molmo2-4B weights. - End-to-end smoke confirms the mask flows through the whole stack (`token_type_ids` changes the output) and the causal path (`or_mask=None`) is unchanged. - `ruff` / `mypy` / `isort` / `black` clean. ## Scope / follow-ups (intentionally out of scope here) - The parity check compares **last-token** logits (< 5.0 bf16 threshold) and asserts causal-is-worse to prove the gap; it does not yet assert a per-image-token logit bound. - The `(B, 1, S, S)` mask is O(S²) memory — fine for these models, but a `flex_attention` path would be the scalable follow-up for long sequences and for enabling this on flash backends.
jason718
added a commit
that referenced
this pull request
Jun 13, 2026
> 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 |
jason718
added a commit
that referenced
this pull request
Jun 13, 2026
## Summary Adds **bidirectional image-token attention** to `MultimodalLM`, matching HF Molmo2. HF Molmo2 attends **bidirectionally among image tokens** (driven by `token_type_ids`) while text stays causal — image tokens see *all* image tokens in the prefix, not just earlier ones. Our `MultimodalLM` previously ran the LM **fully causal** over the spliced image tokens, so this was a real parity gap. Targets the `vision` integration branch; stacked on the Molmo2 loader (#715). ## Why this wasn't caught before The existing full-pipeline logit-parity test used **exactly one** `<im_patch>` token, where causal and bidirectional attention are identical — a structural blind spot. The generation test used 196 image tokens but never passed `token_type_ids` to HF, so HF ran causal too (causal-vs-causal). So the gap was entirely untested. ## What's in this PR ### Fix - `MultimodalLM.forward` gains an HF-aligned `token_type_ids` argument and builds a `(B, 1, S, S)` boolean **`or_mask`** (`True` where `image[q] & image[k]`). - `or_mask` is threaded through `Transformer.forward` → block kwargs → `Attention.forward`/`sdpa` → `TorchAttentionBackend`, which **OR's it onto the causal/sliding base** — exactly mirroring HF's `or_mask_function`, and correct even for sliding-window layers. - Capability-gated by `AttentionBackend.SUPPORTS_OR_MASK` (only the dense `torch` SDPA backend supports it). Flash/TE/Fused backends and context parallelism **raise** rather than silently fall back to causal. - `token_type_ids=None` → unchanged causal behavior (fully backward compatible). ### Test (pins the gap) `test_molmo2_image_bidirectional_attention_parity` (196 image tokens, real Molmo2-4B): - **(1)** with `token_type_ids`, our last-token logits match HF (bidirectional); - **(2)** pure-causal is **measurably worse** — guards against the test silently regressing to causal-vs-causal. ## Verification - **Full vision suite: 89 passed, 2 skipped** (the 2 skips are the intentional Molmo2-O-7B per-layer-YaRN cases). The new GPU parity test passes against real Molmo2-4B weights. - End-to-end smoke confirms the mask flows through the whole stack (`token_type_ids` changes the output) and the causal path (`or_mask=None`) is unchanged. - `ruff` / `mypy` / `isort` / `black` clean. ## Scope / follow-ups (intentionally out of scope here) - The parity check compares **last-token** logits (< 5.0 bf16 threshold) and asserts causal-is-worse to prove the gap; it does not yet assert a per-image-token logit bound. - The `(B, 1, S, S)` mask is O(S²) memory — fine for these models, but a `flex_attention` path would be the scalable follow-up for long sequences and for enabling this on flash backends.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
2nd PR in the VLM stack building Molmo2-style multimodal support.
molmo2_loader.py— HF Molmo2 →MultimodalLMweight converter handling three architecture deltas:wte.embedding+wte.new_embeddinginto one flatembeddings.weightatt_proj→w_q/w_k/w_vandff_proj→w1/w3(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-registersROPE_INIT_FUNCTIONS["default"]beforefrom_pretrainedreinit_rope_buffers(model)— re-runsrope_init_fnafter loading to fix uninitialisedinv_freqbuffersParity tests (
molmo2_parity_test.py,molmo2_logits_parity_test.py):Generation test (
molmo2_generation_test.py):"What colors do you see?"→ greedy-decode 8 tokensParity results (bfloat16, GPU)
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;MultimodalLMuses 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?"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-persistentinv_freqbuffers uninitialised. The two-step fix lives inmolmo2_loader.py:Test command
# 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.pyVerification on the rebased tip (
035f86fa)ruff/mypy/isort/blackall clean.visionis 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
molmo2_loader_test.pyimportsolmo_core.data.multimodal(doesn't exist yet)torch.zeros(...)padding fails when the HF state dict is on CUDAhf_lm_head.new_zeros(...), preserving device and dtype_build_lm_configto replace the preset-matching table with a generic builder constructingTransformerConfigdirectly from HF fieldslm_headrows give finite logits and shift the loss vs HF-infat 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