Add Molmo2#43451
Conversation
Adds AllenAI Molmo2 multimodal VLM to transformers, supporting: - Molmo2ForConditionalGeneration (image+video+text → text) - Molmo2TextModel / Molmo2TextForCausalLM (text-only) - Molmo2ImageProcessor and Molmo2VideoProcessor - Molmo2Processor Key implementation details: - Uses is_first_iteration (v5 API) for prepare_inputs_for_generation - Custom Molmo2Embedding with embedding + new_embedding parameters - Vision backbone with pooling adapter and multi-layer ViT features - Dynamic full cache support for generation Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…odel_prefix - Replace einops.rearrange with native numpy reshape+transpose+reshape - Add @strict decorator to all 4 config classes (Molmo2VitConfig, Molmo2AdapterConfig, Molmo2TextConfig, Molmo2Config) to satisfy TRF010 - Set Molmo2Model.base_model_prefix = "model" (was empty, violating TRF002) - Fix image_mean/image_std mutable shared list (copy constants on init) - Fix test_image_processing: use image_processing_class instead of image_processor_list; skip CHW torch and 4-channel unsupported tests Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Re-sort _toctree.yml to place Molmo2 after mllama alphabetically - Add None guard in test_video_processor_from_dict_with_kwargs to skip when fast_video_processing_class is not defined Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Molmo2TextModel is an internal sub-component used by Molmo2Model and Molmo2ForConditionalGeneration and is tested implicitly through those. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
requests is not part of the standard library and caused ImportError in minimal environments (e.g. HuggingFace Jobs). Use urllib.request instead. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Molmo2's processor has several behaviors that are incompatible with the default ProcessorTesterMixin assumptions: - Chat template enforces strict user/assistant alternation (no system role) - Processor inserts BOS token, shifting sequence length by 1 - Image processor patchifies output, so rescale_factor passthrough fails - Video processor requires FPS metadata not provided by base tests - Hub processor_config.json contains auto_map not preserved in save/load Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Add @auto_docstring(checkpoint="allenai/Molmo2-8B") decorator to Molmo2TextConfig and Molmo2Config with custom_args for documenting non-standard parameters. This fixes check_config_docstrings CI check. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
… date Add parameter docstrings to Molmo2TextConfig and Molmo2Config __init__ methods so @strict-wrapped classes pass config docstring CI checks. Update model doc date to 2026-03-28. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Move top-level `import torch` and `import torchvision.transforms` behind `is_torch_available()` / `is_torchvision_available()` guards in both image and video processors to prevent ModuleNotFoundError when torchvision is not installed. Also skip test_kwargs_overrides_default_image_processor_kwargs since Molmo2's patchifying image processor doesn't support rescale_factor passthrough. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Convert all absolute imports (from transformers.xxx) to relative imports (from ...xxx) in image_processing, video_processing, and processing modules to match the convention used by all other in-library models. Remove register_for_auto_class() calls which are only needed for custom hub models and were causing dynamic_module_utils to incorrectly scan local files for relative imports during save_pretrained. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…n_available The processor's top-level imports from image_processing_molmo2 and video_processing_molmo2 pull in PILImageResampling which requires PIL. Guard these imports with is_vision_available() so `from transformers import *` works when only torch is installed (no PIL/torchvision). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…L imports Move Molmo2ImagesKwargs and Molmo2VideosKwargs definitions directly into processing_molmo2.py instead of importing them from image/video processor modules which require PIL. Also remove Molmo2ImageProcessor/VideoProcessor type hints from __init__ to avoid NameError when vision is unavailable. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
|
@molbap Hi I am still working on it since I have to make some example visualizer for this and (most of the code is generated by Claude code). However, you can start review this with brief level of code review! cc. @merveenoyan |
Add integration tests for Molmo2-8B covering: - Image generation with exact expected text verification - Video QA (penguin identification) - Video pointing (coordinate output) - Multi-image comparison All expected values derived from actual model inference on A10G. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
zucchini-nlp
left a comment
There was a problem hiding this comment.
Hey @SangbumChoi
Great model to add to Transformers. After reviewing I see that using modular would be much better since a lot of part are copy-paste from different models. I left comments on each class about where it can be copied from. Apart from that, there are a few places where we need to clean up and align API with the rest of VLMs for consistency
If you have q, ping me on slack. I will unsubscribe myself from this PR to not get notif about each commit, so when you want another review ping me again by @
zucchini-nlp
left a comment
There was a problem hiding this comment.
Hey @SangbumChoi
Great model to add to Transformers. After reviewing I see that using modular would be much better since a lot of part are copy-paste from different models. I left comments on each class about where it can be copied from. Apart from that, there are a few places where we need to clean up and align API with the rest of VLMs for consistency
If you have q, ping me on slack. I will unsubscribe myself from this PR to not get notif about each commit, so when you want another review ping me again by @
`token_type_ids_mask_function` only clamped `kv_idx` against the length of `mm_token_type_ids` (which covers just the original prompt), but indexed `token_type_ids[batch_idx, q_idx]` directly. When generation verifies several new tokens in one forward (e.g. assisted/speculative decoding), the query length exceeds the prompt length and `q_idx` runs out of bounds: `IndexError: index N is out of bounds for dimension 1 with size N`. Newly generated positions are always text, never image patches, so clamp the `q_idx` lookup the same way as `kv_idx` and treat out-of-range positions as token-type 0. Fixes test_assisted_decoding_sample and test_assisted_decoding_matches_greedy_search. Fast Molmo2ModelTest is now fully green (129 passed, 119 skipped).
|
@molbap @merveenoyan @guarin gentle ping |
molbap
left a comment
There was a problem hiding this comment.
Hey @SangbumChoi , thanks a lot for iterating on this.
The modular implementation is muuuch cleaner. processor is also looking good. There's no more numpy, einsum, tests are leaner, there's not much missing.
The PR has been open for a long time, and we need to merge it before main drifts away, we get new API changes, and so on. What's left is a small, well-understood set of items that have been through two review rounds already, so rather than start a third one I'll finish them myself directly on this branch.
One ask: please don't push to this branch, so we don't overwrite each other. Your commits and authorship stay exactly as they are and if you spot something you'd like changed, review the PR and I'll include it. I'll ping you when it's ready to merge. Thanks again for carrying the model this far!
| from transformers import Molmo2ForConditionalGeneration, Molmo2Processor | ||
| import torch | ||
|
|
||
| processor = Molmo2Processor.from_pretrained("allenai/Molmo2-8B") | ||
| model = Molmo2ForConditionalGeneration.from_pretrained( | ||
| "allenai/Molmo2-8B", |
There was a problem hiding this comment.
these should work with AutoModel/AutoProcessor
| from transformers import Molmo2ForConditionalGeneration, Molmo2Processor | ||
| from transformers.video_utils import load_video |
| ("mistral3", "PixtralProcessor"), | ||
| ("mm-grounding-dino", "GroundingDinoProcessor"), | ||
| ("modernvbert", "Idefics3Processor"), | ||
| ("molmo2", "Molmo2Processor"), |
There was a problem hiding this comment.
not needed here AFAIK
| ("molmo2", "Molmo2Processor"), |
| add_generation_prompt=True, | ||
| return_tensors="pt", | ||
| return_dict=True, | ||
| processor_kwargs={"video_metadata": [metadata]}, |
There was a problem hiding this comment.
i don't think we should need to pass explicitly processor_kwargs here... we should be able to send video_metadata directly imo
There was a problem hiding this comment.
we dont need to load video manually tbh, video processor does it internally for us
| image_num_pos: int = 577 | ||
| attention_dropout: float = 0.0 | ||
| residual_dropout: float = 0.0 | ||
| float32_attention: bool = True |
There was a problem hiding this comment.
if you upcast inputs just before the dispatched call then sdpa is computed in whatever dtype the inputs are in, that should be enough
| def __post_init__(self, **kwargs): | ||
| if self.attn_implementation is not None: | ||
| kwargs["attn_implementation"] = self.attn_implementation | ||
| super().__post_init__(**kwargs) |
| def __post_init__(self, **kwargs): | ||
| if self.attn_implementation is not None: | ||
| kwargs["attn_implementation"] = self.attn_implementation | ||
| super().__post_init__(**kwargs) |
| def tearDown(self): | ||
| cleanup(torch_device, gc_collect=True) |
There was a problem hiding this comment.
these should call super.teardown
| if self.config._attn_implementation == "eager": | ||
| key_states = repeat_kv(key_states, self.num_key_value_groups) | ||
| value_states = repeat_kv(value_states, self.num_key_value_groups) | ||
| attn_weights = torch.matmul(query_states / math.sqrt(query_states.size(-1)), key_states.transpose(2, 3)) | ||
| if attention_mask is not None: | ||
| # The image pooling adapter passes a boolean keep-mask (valid patches); exclude the | ||
| # invalid ones with -inf to match the SDPA path. A float mask is already additive. | ||
| if attention_mask.dtype == torch.bool: | ||
| attn_weights = attn_weights.masked_fill(~attention_mask, torch.finfo(attn_weights.dtype).min) | ||
| else: | ||
| attn_weights = attn_weights + attention_mask | ||
|
|
||
| attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) | ||
| attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=self.training) | ||
| attn_output = torch.matmul(attn_weights.to(value_states.dtype), value_states) | ||
| attn_output = attn_output.transpose(1, 2).contiguous() | ||
| elif self.config._attn_implementation == "sdpa": |
There was a problem hiding this comment.
this conditional branching, as said, only reason is the upcast, which can done before the call, and casted back after output.
|
@molbap Got it. From now on I will just leave it as a comment only |
|
Thanks @SangbumChoi ! I also am trying to help narrow down AI-assisted PRs scope to boost contribution. I am trying out a "Self-review" skill to run on your end on your PRs, which should cover the recent API changes/alignment and boost a bit. If you have feedback on it it'd be very helpful! |
|
run-slow: molmo2 |
|
This comment contains models: ["models/molmo2"] |
CI ResultsCommit Info
The test failure analysis could not be completed. Please check the workflow run for details. |
zucchini-nlp
left a comment
There was a problem hiding this comment.
Adding my two cents as the model is closer to merge
| add_generation_prompt=True, | ||
| return_tensors="pt", | ||
| return_dict=True, | ||
| processor_kwargs={"video_metadata": [metadata]}, |
There was a problem hiding this comment.
we dont need to load video manually tbh, video processor does it internally for us
| def select_tiling(height: int, width: int, patch_size: int, max_num_crops: int) -> tuple[int, int]: | ||
| """Select the image tiling in the same height/width order as the original Molmo2 processor.""" | ||
| tilings = [] | ||
| for tile_height in range(1, max_num_crops + 1): | ||
| for tile_width in range(1, max_num_crops + 1): | ||
| if tile_height * tile_width <= max_num_crops: | ||
| tilings.append((tile_height, tile_width)) | ||
| tilings.sort(key=lambda x: (x[0] * x[1], x[0])) | ||
|
|
||
| candidate_resolutions = torch.tensor(tilings, dtype=torch.int32) * patch_size | ||
| original_size = torch.tensor([height, width], dtype=torch.float32) | ||
|
|
||
| required_scales = candidate_resolutions.to(torch.float32) / original_size | ||
| required_scale = required_scales.amin(dim=-1, keepdim=True) | ||
|
|
||
| if torch.all(required_scale < 1): | ||
| return tilings[int(required_scale.argmax())] | ||
|
|
||
| required_scale = torch.where(required_scale < 1.0, 10e9, required_scale) | ||
| return tilings[int(required_scale.argmin())] |
There was a problem hiding this comment.
looks same as get_optimal_tiled_canvas in cohere vision
There was a problem hiding this comment.
same core min-scale selection, but molmo sorts candidates by (area + height) while cohere enumerates aspect ratios sorted by area only, and returns (w, h) not (h, w). so using it changes the grid (except for near-square imags)
| def test_training_gradient_checkpointing_use_reentrant_true(self): | ||
| pass | ||
|
|
||
| @unittest.skip(reason="VLMs have dynamic control flow in preparing inputs for generation") |
There was a problem hiding this comment.
+1, preparing inputs for generation shouldn't be the issue since other VLMs dont skip the test
| input_len = device_inputs["input_ids"].shape[1] | ||
| generated_text = self.processor.batch_decode(generated_ids[:, input_len:], skip_special_tokens=True)[0] | ||
| EXPECTED_TEXT = "Penguins appear in the video." | ||
| self.assertEqual(generated_text.strip(), EXPECTED_TEXT) |
There was a problem hiding this comment.
quite a lot of slow tests, do we need all of them? 👁️
There was a problem hiding this comment.
yeah well the 3 models are quite different... maybe we can skip the 4B ones
|
[For maintainers] Suggested jobs to run (before merge) run-slow: auto, molmo2 |
CI recapDashboard: View test results in Grafana |
What does this PR do?
Fixes # (issue)
Before submitting
Pull Request section?
to it if that's the case.
documentation guidelines, and
here are tips on formatting docstrings.
Who can review?
Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.