Skip to content

[2/n] HF Molmo2 loader and logit parity tests - #693

Closed
jason718 wants to merge 1 commit into
pr/vlm-1-vision-architecturefrom
pr/vlm-2-molmo2-loader
Closed

jason718 wants to merge 1 commit into
pr/vlm-1-vision-architecturefrom
pr/vlm-2-molmo2-loader

Conversation

@jason718

@jason718 jason718 commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

2nd PR in the VLM stack building Molmo2-style multimodal support.

  1. molmo2_loader.py — HF Molmo2 → MultimodalTransformer 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; MultimodalTransformer 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:

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

# 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

@jason718 jason718 changed the title [2/7] HF Molmo2 loader, logit parity tests, and MultimodalGenerator [2/n] HF Molmo2 loader, logit parity tests, and MultimodalGenerator May 27, 2026
@jason718
jason718 changed the base branch from pr/vlm-1-vision-architecture to main May 27, 2026 08:01
@jason718
jason718 changed the base branch from main to pr/vlm-1-vision-architecture May 27, 2026 08:03
@jason718
jason718 force-pushed the pr/vlm-2-molmo2-loader branch from 7c5cc80 to 2196746 Compare May 27, 2026 08:07
@jason718 jason718 changed the title [2/n] HF Molmo2 loader, logit parity tests, and MultimodalGenerator [2/7] HF Molmo2 loader and logit parity tests May 27, 2026
@jason718
jason718 force-pushed the pr/vlm-2-molmo2-loader branch from 2196746 to 084c133 Compare May 27, 2026 08:14
@jason718 jason718 self-assigned this May 27, 2026
@jason718 jason718 added the enhancement New feature or request label May 27, 2026
@jason718 jason718 changed the title [2/7] HF Molmo2 loader and logit parity tests [2/n] HF Molmo2 loader and logit parity tests May 27, 2026
@jason718
jason718 force-pushed the pr/vlm-2-molmo2-loader branch from 084c133 to e8ec9ad Compare May 27, 2026 09:15
- molmo2_loader.py: HF Molmo2 → MultimodalTransformer 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
import pytest
import torch

from olmo_core.data.multimodal import MultimodalTokenizerConfig

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.

I'm not able to run this:

src/test/nn/vision/molmo2_loader_test.py:20: in <module>
    from olmo_core.data.multimodal import MultimodalTokenizerConfig
E   ModuleNotFoundError: No module named 'olmo_core.data.multimodal'

# ---------------------------------------------------------------------------


def _build_lm_config(text_cfg, total_vocab_size: int) -> TransformerConfig:

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.

Let's take a TODO to make this a bit more robust / generic. The growing list of models it will dispatch to make it something that will be difficult to maintain over time. Also, this ignores many HF fields right?

f"vocab_size is only {lm_cfg.vocab_size}"
)
if extra_rows > 0:
pad = torch.zeros(extra_rows, hf_lm_head.shape[1], dtype=hf_lm_head.dtype)

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.

This torch.zeros(...) defaults to CPU, so torch.cat([hf_lm_head, pad], ...) can fail when the HF state dict is already on CUDA. Elsewhere we tend to allocate from the existing tensor for this case, so hf_lm_head.new_zeros((extra_rows, hf_lm_head.shape[1])) would preserve both device and dtype.

# HF Molmo2 keeps the extra image-token embeddings in a separate
# parameter (``new_embedding``); after concatenation our model needs the
# combined vocab.
total_vocab = text_cfg.vocab_size + text_cfg.additional_vocab_size

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.

Do we need to mask Molmo2’s input-only extra vocab rows at output?

HF Molmo2’s lm_head predicts only the base vocab. This pads our lm_head with zero rows for the extra image-token IDs. Even if the base logits and argmax match, those finite zero rows change the loss right?

Minimal example:

import torch
import torch.nn.functional as F

hf_logits = torch.tensor([[4.0, 1.5, -0.5, 0.0, 2.0]])
olmo_logits = torch.cat([hf_logits, torch.zeros(1, 3)], dim=-1)
target = torch.tensor([0])

print("HF logits:        ", hf_logits.tolist())
print("OLMo full logits: ", olmo_logits.tolist())
print("HF prediction:    ", int(hf_logits.argmax(-1)))
print("OLMo prediction:  ", int(olmo_logits.argmax(-1)))
print("HF loss:          ", round(F.cross_entropy(hf_logits, target).item(), 4))
print("OLMo padded loss: ", round(F.cross_entropy(olmo_logits, target).item(), 4))
print("loss drift:       ", round((F.cross_entropy(olmo_logits, target) - F.cross_entropy(hf_logits, target)).item(), 4))

"""
Output:

text


HF logits:         [[4.0, 1.5, -0.5, 0.0, 2.0]]
OLMo full logits:  [[4.0, 1.5, -0.5, 0.0, 2.0, 0.0, 0.0, 0.0]]
HF prediction:     0
OLMo prediction:   0
HF loss:           0.2206
OLMo padded loss:  0.2637
delta:        0.0431

Do we need to explicitly mask the extra output IDs to -inf for Molmo2 parity?
"""

@jason718
jason718 marked this pull request as draft June 9, 2026 06:13
@jason718

jason718 commented Jun 9, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #715, which contains the same Molmo2 loader rebased on top of the vision branch (the unified VisionEncoderConfig/MultimodalLM API) and addresses the review feedback here (device-safe lm_head padding, decoupled loader test, dispatch TODO, extra-vocab loss note). Closing in favor of #715.

@jason718 jason718 closed this Jun 9, 2026
@jason718
jason718 deleted the pr/vlm-2-molmo2-loader branch June 10, 2026 06:05
jason718 added a commit that referenced this pull request Jun 10, 2026
- 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 added a commit that referenced this pull request Jun 10, 2026
- 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

Copy link
Copy Markdown
Contributor Author

@undfined All four of your review comments are addressed in the successor PR #715 (rebased onto the vision branch) — see the "Review feedback from #693 — status" table in its description. Three are code fixes (decoupled test import, new_zeros device-safe padding, dispatch TODO); the extra-vocab logit question is documented in the loader with the -inf masking deferred to the loss/forward layer in the training/eval PRs, since a weight converter can't mask logits. If you'd rather see the masking land in #715 itself, happy to discuss there.

jason718 added a commit that referenced this pull request Jun 10, 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
> 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 |
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dont review enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants