Repository navigation
Conversation
7c5cc80 to
2196746
Compare
2196746 to
084c133
Compare
084c133 to
e8ec9ad
Compare
- 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
e8ec9ad to
9f5c0b8
Compare
| import pytest | ||
| import torch | ||
|
|
||
| from olmo_core.data.multimodal import MultimodalTokenizerConfig |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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?
"""|
Superseded by #715, which contains the same Molmo2 loader rebased on top of the |
- 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).
- 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).
|
@undfined All four of your review comments are addressed in the successor PR #715 (rebased onto the |
> 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 |
Summary
2nd PR in the VLM stack building Molmo2-style multimodal support.
molmo2_loader.py— HF Molmo2 →MultimodalTransformerweight 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;MultimodalTransformeruses 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.py