Run this model with HF Jobs

Run VisualInference/Molmo3-8B-MLX-4bit on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs to fine-tune https://huggingface.co/VisualInference/Molmo3-8B-MLX-4bit. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/VisualInference/Molmo3-8B-MLX-4bit on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.

Evaluate on a benchmark

Use HF Jobs to evaluate https://huggingface.co/VisualInference/Molmo3-8B-MLX-4bit. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Molmo3-8B-MLX-4bit / modeling_molmo3.py
VisualInference's picture
Upload MLX build
fe6fb4e verified
Raw History Blame Contribute Delete
43.1 kB
"""Molmo3 for HuggingFace transformers.
Module and parameter names mirror the native model (olmo/models/molmo3/molmo3.py), so a native
state dict loads under the `model.` prefix with only the lm_head added.
Pointing and segmentation are resolved during generation: each grounding token is followed by a
dot-product head that picks a patch, sub-patch, or location, and the pick is fed back into the next
token's embedding. With `return_dict_in_generate=True`, `generate` returns those picks per row as
`output.grounding`, which `Molmo3Processor.decode` turns into coordinates and masks.
"""
import inspect
import math
from dataclasses import dataclass
from typing import Optional
import torch
from torch import nn
from torch.nn import functional as F
from transformers import initialization as hf_init
from transformers.activations import ACT2FN
from transformers.cache_utils import Cache, DynamicCache
from transformers.generation import GenerateDecoderOnlyOutput, GenerationMixin
from transformers.masking_utils import create_causal_mask
from transformers.modeling_outputs import CausalLMOutputWithPast
from transformers.utils import ModelOutput
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
from .configuration_molmo3 import Molmo3Config, Molmo3TextConfig, Molmo3VisionConfig
SMALL_VALUE = -1000000
# ───────────────────────────── shared ─────────────────────────────
class Molmo3RMSNorm(nn.Module):
def __init__(self, size: int, eps: float = 1e-6):
super().__init__()
self.weight = nn.Parameter(torch.ones(size))
self.eps = eps
def forward(self, x: torch.Tensor) -> torch.Tensor:
dtype = x.dtype
x = x.float()
x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
return self.weight * x.to(dtype)
def rotate_half(x: torch.Tensor) -> torch.Tensor:
x1, x2 = x.chunk(2, dim=-1)
return torch.cat((-x2, x1), dim=-1)
def rope_sin_cos(positions: torch.Tensor, dim: int, theta: float):
"""fp32 sin/cos tables for `positions` (any shape) -> `positions.shape + (dim,)`."""
inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, device=positions.device, dtype=torch.float) / dim))
freqs = positions.float()[..., None] * inv_freq
emb = torch.cat((freqs, freqs), dim=-1)
return emb.sin(), emb.cos()
def apply_rope(x: torch.Tensor, sin: torch.Tensor, cos: torch.Tensor) -> torch.Tensor:
x_ = x.float()
return (x_ * cos + rotate_half(x_) * sin).to(x.dtype)
# ───────────────────────────── vision encoder ─────────────────────────────
class Molmo3VitAttention(nn.Module):
def __init__(self, config: Molmo3VisionConfig):
super().__init__()
self.num_heads = config.num_attention_heads
self.head_dim = config.head_dim
inner = self.num_heads * self.head_dim
self.wq = nn.Linear(config.hidden_size, inner)
self.wk = nn.Linear(config.hidden_size, inner)
self.wv = nn.Linear(config.hidden_size, inner)
self.wo = nn.Linear(inner, config.hidden_size)
def forward(self, x: torch.Tensor) -> torch.Tensor:
B, N, _ = x.shape
q, k, v = (proj(x).view(B, N, self.num_heads, self.head_dim).transpose(1, 2).float()
for proj in (self.wq, self.wk, self.wv))
out = F.scaled_dot_product_attention(q, k, v).transpose(1, 2).reshape(B, N, -1)
return self.wo(out.to(x.dtype))
class Molmo3VitMLP(nn.Module):
def __init__(self, config: Molmo3VisionConfig):
super().__init__()
self.w1 = nn.Linear(config.hidden_size, config.intermediate_size)
self.act = ACT2FN[config.hidden_act]
self.w2 = nn.Linear(config.intermediate_size, config.hidden_size)
def forward(self, x):
return self.w2(self.act(self.w1(x)))
class Molmo3VitBlock(nn.Module):
def __init__(self, config: Molmo3VisionConfig):
super().__init__()
self.attention = Molmo3VitAttention(config)
self.feed_forward = Molmo3VitMLP(config)
self.attention_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.ffn_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
def forward(self, x):
x = x + self.attention(self.attention_norm(x))
return x + self.feed_forward(self.ffn_norm(x))
class Molmo3VitBlocks(nn.Module):
def __init__(self, config: Molmo3VisionConfig, n_layers: int):
super().__init__()
self.resblocks = nn.ModuleList([Molmo3VitBlock(config) for _ in range(n_layers)])
class Molmo3VisionTransformer(nn.Module):
"""SigLIP2 encoder, truncated after the deepest layer the connector reads."""
def __init__(self, config: Molmo3VisionConfig, n_layers: int):
super().__init__()
self.positional_embedding = nn.Parameter(torch.zeros(config.grid_size ** 2, config.hidden_size))
self.patch_embedding = nn.Linear(config.patch_size ** 2 * 3, config.hidden_size)
self.transformer = Molmo3VitBlocks(config, n_layers)
def forward(self, x: torch.Tensor) -> list:
x = self.patch_embedding(x) + self.positional_embedding[None].to(x.dtype)
hidden_states = []
for block in self.transformer.resblocks:
x = block(x)
hidden_states.append(x)
return hidden_states
# ───────────────────────────── connector ─────────────────────────────
class Molmo3PoolingAttention(nn.Module):
"""Single-query attention pooling over each pooling window (no output projection)."""
def __init__(self, input_dim: int, num_heads: int, head_dim: int):
super().__init__()
self.num_heads, self.head_dim = num_heads, head_dim
self.wq = nn.Linear(input_dim, num_heads * head_dim)
self.wk = nn.Linear(input_dim, num_heads * head_dim)
self.wv = nn.Linear(input_dim, num_heads * head_dim)
def forward(self, query, to_pool, mask):
def split(t):
return t.reshape(t.shape[:2] + (self.num_heads, self.head_dim)).float()
q, k, v = split(self.wq(query)), split(self.wk(to_pool)), split(self.wv(to_pool))
weights = torch.einsum("...qhd,...khd->...hqk", q / math.sqrt(self.head_dim), k)
weights = weights.masked_fill(~mask[:, None, None, :], torch.finfo(weights.dtype).min)
out = torch.einsum("...hqk,...khd->...qhd", F.softmax(weights, dim=-1), v)
return out.to(query.dtype).reshape(out.shape[:2] + (-1,))
class Molmo3ImageProjector(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, hidden_act):
super().__init__()
self.w1 = nn.Linear(input_dim, hidden_dim, bias=False)
self.w2 = nn.Linear(hidden_dim, output_dim, bias=False)
self.w3 = nn.Linear(input_dim, hidden_dim, bias=False)
self.act = ACT2FN[hidden_act]
def forward(self, x):
return self.w2(self.act(self.w1(x)) * self.w3(x))
class Molmo3AddPosEmbed(nn.Module):
def __init__(self, dim: int, n_pos: int):
super().__init__()
self.bias = nn.Parameter(torch.zeros(n_pos, dim))
def forward(self, x):
return x + self.bias[None, :x.shape[-2]].to(x.dtype)
class Molmo3Connector(nn.Module):
def __init__(self, config: Molmo3Config):
super().__init__()
vit, adapter = config.vision_config, config.adapter_config
pool_dim = vit.hidden_size * len(adapter.vision_feature_layer)
self.image_pooling_2d = Molmo3PoolingAttention(
pool_dim, adapter.num_attention_heads, adapter.head_dim)
self.image_projector = Molmo3ImageProjector(
adapter.num_attention_heads * adapter.head_dim, adapter.intermediate_size,
config.text_config.hidden_size, adapter.hidden_act)
self.positional_embeddings = Molmo3AddPosEmbed(pool_dim, adapter.num_pooling_positions)
def forward(self, to_pool: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
"""`[n, pool, dim]` features with `[n, pool]` validity -> `[n, llm_dim]`."""
# The bias is added after masking, so it also enters the mean of padded slots (as native)
to_pool = self.positional_embeddings(to_pool)
denom = mask.float().sum(-1).clamp(min=1)
query = to_pool.sum(-2, keepdim=True) / denom[:, None, None].to(to_pool.dtype)
pooled = self.image_pooling_2d(query, to_pool, mask)
return self.image_projector(pooled)[:, 0]
class Molmo3SinusoidalPosEmbed(nn.Module):
"""(t, h, w) sinusoids projected to the ViT feature width, added before pooling."""
SINUSOID_DIM = 512
def __init__(self, dim: int):
super().__init__()
self.proj = nn.Linear(self.SINUSOID_DIM * 3, dim)
def forward(self, pos: torch.Tensor) -> torch.Tensor:
half = torch.arange(0, self.SINUSOID_DIM, 2, device=pos.device, dtype=torch.float)
div = torch.exp(half * (-math.log(10000.0) / self.SINUSOID_DIM))
angles = pos.float()[..., None] * div # [..., 3, 256]
emb = torch.stack([angles.sin(), angles.cos()], -1).flatten(-2) # interleaved sin/cos
return self.proj(emb.flatten(-2).to(self.proj.weight.dtype))
# ───────────────────────────── language model ─────────────────────────────
class Molmo3DecoderLayer(nn.Module):
def __init__(self, config: Molmo3TextConfig, layer_idx: int):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.num_heads = config.num_attention_heads
self.num_kv_heads = config.num_key_value_heads
self.num_key_value_groups = self.num_heads // self.num_kv_heads
self.head_dim = config.head_dim
self.scaling = self.head_dim ** -0.5
self.is_causal = True
self.fused_dims = (self.num_heads * self.head_dim, self.num_kv_heads * self.head_dim,
self.num_kv_heads * self.head_dim)
self.att_proj = nn.Linear(config.hidden_size, sum(self.fused_dims), bias=False)
self.attn_out = nn.Linear(self.num_heads * self.head_dim, config.hidden_size, bias=False)
self.q_norm = Molmo3RMSNorm(self.head_dim, config.rms_norm_eps)
self.k_norm = Molmo3RMSNorm(self.head_dim, config.rms_norm_eps)
self.ff_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
self.ff_out = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
self.act = ACT2FN[config.hidden_act]
self.attn_norm = Molmo3RMSNorm(config.hidden_size, config.rms_norm_eps)
self.ff_norm = Molmo3RMSNorm(config.hidden_size, config.rms_norm_eps)
def forward(self, x, rope, attention_mask, past_key_values):
B, L, _ = x.shape
q, k, v = self.att_proj(self.attn_norm(x)).split(self.fused_dims, dim=-1)
q = self.q_norm(q.view(B, L, -1, self.head_dim)).transpose(1, 2)
k = self.k_norm(k.view(B, L, -1, self.head_dim)).transpose(1, 2)
v = v.view(B, L, -1, self.head_dim).transpose(1, 2)
sin, cos = rope
q, k = apply_rope(q, sin, cos), apply_rope(k, sin, cos)
if past_key_values is not None:
k, v = past_key_values.update(k, v, self.layer_idx)
impl = self.config._attn_implementation or "sdpa"
attention = eager_attention_forward if impl == "eager" else ALL_ATTENTION_FUNCTIONS[impl]
out, _ = attention(self, q, k, v, attention_mask, dropout=0.0, scaling=self.scaling)
x = x + self.attn_out(out.reshape(B, L, -1))
h, gate = self.ff_proj(self.ff_norm(x)).chunk(2, dim=-1)
return x + self.ff_out(self.act(gate) * h)
def eager_attention_forward(module, q, k, v, attention_mask, scaling, dropout=0.0, **kwargs):
k = k.repeat_interleave(module.num_key_value_groups, dim=1)
v = v.repeat_interleave(module.num_key_value_groups, dim=1)
weights = torch.matmul(q, k.transpose(2, 3)) * scaling
if attention_mask is not None:
weights = weights + attention_mask[:, :, :, :k.shape[-2]]
weights = F.softmax(weights, dim=-1, dtype=torch.float32).to(q.dtype)
return torch.matmul(weights, v).transpose(1, 2).contiguous(), weights
class Molmo3Embedding(nn.Module):
def __init__(self, num_embeddings: int, num_new_embeddings: int, features: int):
super().__init__()
self.embedding = nn.Parameter(torch.zeros(num_embeddings, features))
self.new_embedding = nn.Parameter(torch.zeros(num_new_embeddings, features))
def forward(self, x):
return F.embedding(x, torch.cat([self.embedding, self.new_embedding], dim=0))
class Molmo3TextModel(nn.Module):
def __init__(self, config: Molmo3TextConfig):
super().__init__()
self.config = config
self.wte = Molmo3Embedding(config.base_vocab_size, config.additional_vocab_size, config.hidden_size)
self.blocks = nn.ModuleList(
[Molmo3DecoderLayer(config, i) for i in range(config.num_hidden_layers)])
self.ln_f = Molmo3RMSNorm(config.hidden_size, config.rms_norm_eps)
def forward(self, x, position_ids, attention_mask, past_key_values):
"""Returns the final block output *before* `ln_f`; the grounding head reads that."""
sin, cos = rope_sin_cos(position_ids, self.config.head_dim, self.config.rope_theta)
rope = (sin[:, None], cos[:, None])
for block in self.blocks:
x = block(x, rope, attention_mask, past_key_values)
return x
# ───────────────────────────── grounding head ─────────────────────────────
class Molmo3MlpMerge(nn.Module):
def __init__(self, in_dim1, in_dim2, hidden_size, out_dim):
super().__init__()
self.w_in1 = nn.Linear(in_dim1, hidden_size * 2, bias=False)
self.w_in2 = nn.Linear(in_dim2, hidden_size * 2, bias=False)
self.w_out = nn.Linear(hidden_size, out_dim)
def forward(self, x1, x2):
x, gate = (self.w_in1(x1) + self.w_in2(x2)).chunk(2, dim=-1)
return self.w_out(x * F.silu(gate))
class Molmo3SubpatchConv(nn.Module):
"""Mixes each ViT patch with its neighbours before the sub-patch keys are read off it."""
def __init__(self, in_dim, out_dim, kernel):
super().__init__()
self.proj = nn.Conv2d(in_dim, out_dim, 1)
self.conv = nn.Conv2d(out_dim, out_dim, kernel, padding=kernel // 2)
def forward(self, features, grid):
batch, n, dim = features.shape
x = features.reshape(-1, grid, grid, dim).permute(0, 3, 1, 2)
x = self.conv(F.gelu(self.proj(x)))
return x.permute(0, 2, 3, 1).reshape(batch, n, -1)
MASK_EDGES = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1))
class Molmo3MaskAffinity(nn.Module):
"""Per-location edge weights used to diffuse the mask logits, from the image alone."""
def __init__(self, in_dim, n_locations):
super().__init__()
self.upscale = int(round(math.sqrt(n_locations)))
self.conv = nn.Conv2d(in_dim, len(MASK_EDGES) * n_locations, 3, padding=1)
def forward(self, features, grid):
"""`[batch, n_crops*grid*grid, dim]` -> `[batch*n_crops, 8, grid*r, grid*r]`."""
x = features.reshape(-1, grid, grid, features.shape[-1]).permute(0, 3, 1, 2)
return F.pixel_shuffle(self.conv(x), self.upscale)
def diffuse_mask(mask, weights, steps):
"""`m <- m + sum_j w_j (m_j - m)` over the 8 neighbours, `steps` times."""
h, w = mask.shape[-2:]
bounded = torch.tanh(weights) / len(MASK_EDGES)
for _ in range(steps):
padded = F.pad(mask, (1, 1, 1, 1), mode="replicate")
delta = torch.zeros_like(mask)
for i, (dy, dx) in enumerate(MASK_EDGES):
delta = delta + bounded[:, i:i + 1] * (padded[..., 1 + dy:1 + dy + h, 1 + dx:1 + dx + w] - mask)
mask = mask + delta
return mask
@dataclass
class Molmo3ImageCache:
"""Image-side tensors built at prefill, used by every later grounding step."""
patch_k: torch.Tensor # [B, P, q]
patch_k_mask: torch.Tensor # [B, P, S], which (token, ViT patch) pairs can be pointed at
subpatch_k: torch.Tensor # [B, P, S, s]
loc_k: torch.Tensor # [B, P, S, n_locs, l]
vit_features: torch.Tensor # [B, P, S, subpatch_hidden]
image_features: torch.Tensor # [n_image_tokens, d_model], connector output
token_offset: torch.Tensor # [B], offset of each row into `image_features`
image_pos_ids: torch.Tensor # [B, P], rotary position of each image token
token_pooling: torch.Tensor # [B, P, S]
diffusion_weights: torch.Tensor
@dataclass
class Molmo3Grounding:
"""One generated sequence's grounding picks, in output order: a (patch, subpatch, loc) per
`<|POINT_LOC|>`, an anchor patch and `[P, S, 16]` scores per `<|SEG_MASK|>`, and the
end-of-points probability at the first patch choice that could stop the list."""
point_ids: list
mask_anchors: list
mask_scores: list
no_point: Optional[float] = None
@dataclass
class Molmo3GenerateOutput(GenerateDecoderOnlyOutput):
"""`generate` output with `grounding`, one `Molmo3Grounding` per row."""
grounding: Optional[list] = None
class Molmo3GroundingState:
"""Per-generation pointing/segmentation state, internal to `generate`."""
def __init__(self):
self.cache: Optional[Molmo3ImageCache] = None
self.point_triples = self.mask_scores = self.mask_anchors = None
def reset(self, batch_size: int, device):
def zeros():
return torch.zeros(batch_size, dtype=torch.long, device=device)
self.patch, self.subpatch, self.loc, self.rotate_by = zeros(), zeros(), zeros(), zeros()
self.patch_resolved = torch.zeros(batch_size, dtype=torch.bool, device=device)
self.list_started = [False] * batch_size
self.last_patch_token = [None] * batch_size
self.prev_token: Optional[torch.Tensor] = None
self.point_triples = [[] for _ in range(batch_size)]
self.mask_scores = [[] for _ in range(batch_size)]
self.mask_anchors = [[] for _ in range(batch_size)]
self.first_no_point = [None] * batch_size
# ───────────────────────────── model ─────────────────────────────
class Molmo3PreTrainedModel(PreTrainedModel):
config_class = Molmo3Config
base_model_prefix = "model"
supports_gradient_checkpointing = False
_no_split_modules = ["Molmo3DecoderLayer", "Molmo3VitBlock"]
_skip_keys_device_placement = "past_key_values"
_supports_sdpa = True
_supports_flex_attn = True
_supports_attention_backend = True
@torch.no_grad()
def _init_weights(self, module):
# These helpers skip tensors that were loaded from the checkpoint
std = 0.02
if isinstance(module, (nn.Linear, nn.Conv2d)):
hf_init.normal_(module.weight, 0.0, std)
if module.bias is not None:
hf_init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
hf_init.normal_(module.weight, 0.0, std)
elif isinstance(module, Molmo3Embedding):
hf_init.normal_(module.embedding, 0.0, std)
hf_init.normal_(module.new_embedding, 0.0, std)
elif isinstance(module, (Molmo3RMSNorm, nn.LayerNorm)):
hf_init.ones_(module.weight)
if getattr(module, "bias", None) is not None:
hf_init.zeros_(module.bias)
elif isinstance(module, Molmo3AddPosEmbed):
hf_init.zeros_(module.bias)
elif isinstance(module, Molmo3VisionTransformer):
hf_init.normal_(module.positional_embedding, 0.0, std)
class Molmo3Model(Molmo3PreTrainedModel):
def __init__(self, config: Molmo3Config):
super().__init__(config)
vit, adapter, text = config.vision_config, config.adapter_config, config.text_config
self.vit_layers = list(adapter.vision_feature_layer)
d_vit = vit.hidden_size * len(self.vit_layers)
d_model = text.hidden_size
q, s, l = config.point_query_dims
n_locs = config.subpatch_location_size ** 2
sub = config.subpatch_hidden_size
# The mask builder and the attention layers both read this off the text config
text._attn_implementation = config._attn_implementation or "sdpa"
self.transformer = Molmo3TextModel(text)
self.vit = Molmo3VisionTransformer(vit, max(self.vit_layers) + 1)
self.connector = Molmo3Connector(config)
self.subpatch_pos_embed = Molmo3SinusoidalPosEmbed(d_vit)
self.x_norm = Molmo3RMSNorm(d_model, text.rms_norm_eps)
self.subpatch_hidden = nn.Linear(d_vit, sub)
self.subpatch_conv = Molmo3SubpatchConv(d_vit, sub, config.subpatch_conv_kernel)
self.mask_affinity = Molmo3MaskAffinity(d_vit, n_locs)
self.patch_k = nn.Linear(d_model, q)
self.subpatch_loc_k = Molmo3MlpMerge(sub, d_model, sub * 2, s + l * n_locs)
self.patch_q = nn.Linear(d_model, q)
self.subpatch_q = nn.Linear(d_model, s)
self.loc_q = nn.Linear(d_model, n_locs)
self.mask_q = nn.Linear(d_model, q + s + l)
self.build_subpatch_embeddings = nn.Linear(sub, d_model)
self.build_location_embeddings = nn.Embedding(n_locs, d_model)
self.post_init()
if (config._attn_implementation or "").startswith("flash"):
raise ValueError("Molmo3 needs a bidirectional mask over image tokens, which flash "
"attention cannot express; use 'sdpa' or 'flex_attention'")
def get_input_embeddings(self):
return self.transformer.wte
# ── vision ──
def encode_images(self, pixel_values, token_pooling, patch_pos_ids):
"""Returns `(image_features [n_tokens, d], vit_features [B, P, S, d_vit], conv, weights)`."""
B, T, N, D = pixel_values.shape
grid = self.config.vision_config.grid_size
dtype = self.vit.patch_embedding.weight.dtype
pixels = pixel_values.reshape(B * T, N, D)
if pixels.dtype == torch.uint8:
pixels = pixels.float() / 255.0 * 2 - 1 # SigLIP normalization
hidden = self.vit(pixels.to(dtype))
features = torch.cat([hidden[i] for i in self.vit_layers], -1).reshape(B, T * N, -1)
features = features + self.subpatch_pos_embed(
patch_pos_ids.reshape(B, T * N, 3).clamp(min=0)).to(features.dtype)
# Both run on the ViT raster, before the gather by pooled token reorders it
diffusion_weights = self.mask_affinity(features, grid)
valid = token_pooling >= 0
batch_ix = torch.arange(B, device=features.device)[:, None, None]
conv = self.subpatch_conv(features, grid)[batch_ix, token_pooling.clamp(min=0)]
conv = conv * valid[..., None].to(conv.dtype)
vit_features = features[batch_ix, token_pooling.clamp(min=0)] * valid[..., None].to(features.dtype)
is_token = valid.any(-1)
image_features = self.connector(vit_features[is_token], valid[is_token])
return image_features, vit_features, conv, diffusion_weights
def image_pos_ids(self, input_ids):
"""Rotary position of each image token for the pointer: a running count of high-res tokens,
continued across images; low-res tokens share the position of the first high-res token."""
cfg = self.config
is_high = input_ids == cfg.image_patch_id
is_image = is_high | (input_ids == cfg.image_low_res_id)
starts = (input_ids == cfg.low_res_image_start_token_id) | (input_ids == cfg.frame_start_token_id)
out = torch.zeros(input_ids.shape[0], int(is_image.sum(-1).max()), dtype=torch.long,
device=input_ids.device)
for b in range(input_ids.shape[0]):
owner = (torch.cumsum(starts[b].long(), 0) - 1)[is_image[b]]
high = is_high[b][is_image[b]].long()
pos, offset = torch.zeros_like(owner), 0
for i in torch.unique(owner).tolist():
rows = owner == i
local = (torch.cumsum(high[rows], 0) - 1).clamp(min=0)
pos[rows] = local + offset
offset += int(local.max()) + 1
out[b, :len(pos)] = pos
return out
def build_image_cache(self, input_ids, x_norm, token_pooling, image_features, vit_features,
conv, diffusion_weights) -> Molmo3ImageCache:
cfg = self.config
B, P, S = token_pooling.shape
q, s, l = cfg.point_query_dims
n_locs = cfg.subpatch_location_size ** 2
is_high = input_ids == cfg.image_patch_id
is_image = is_high | (input_ids == cfg.image_low_res_id)
is_token = (token_pooling >= 0).any(-1)
image_pos_ids = self.image_pos_ids(input_ids)
image_pos_ids = F.pad(image_pos_ids, [0, max(0, P - image_pos_ids.shape[1])])[:, :P]
x_image = x_norm.new_zeros(B, P, x_norm.shape[-1])
x_image[is_token] = x_norm[is_image]
patch_k = self.patch_k(x_image)
sin, cos = rope_sin_cos(image_pos_ids, q, cfg.pointer_rope_theta)
patch_k = apply_rope(patch_k, sin, cos) * is_token[..., None].to(patch_k.dtype)
patch_k_mask = (token_pooling >= 0).clone()
is_high_token = torch.zeros_like(is_token)
is_high_token[is_token] = is_high[is_image]
patch_k_mask &= is_high_token[..., None] # only high-res tokens can be pointed at
vit_features = self.subpatch_hidden(vit_features)
keys = self.subpatch_loc_k(vit_features + conv.to(vit_features.dtype), x_image[:, :, None])
subpatch_k, loc_k = keys.split([s, l * n_locs], dim=-1)
counts = is_token.sum(-1)
return Molmo3ImageCache(
patch_k=patch_k, patch_k_mask=patch_k_mask, subpatch_k=subpatch_k,
loc_k=loc_k.reshape(B, P, S, n_locs, l), vit_features=vit_features,
image_features=image_features, token_offset=F.pad(counts.cumsum(0)[:-1], [1, 0]),
image_pos_ids=image_pos_ids, token_pooling=token_pooling,
diffusion_weights=diffusion_weights)
# ── grounding ──
def add_grounding_feedback(self, x, state: Molmo3GroundingState):
"""Add the previous step's selection to the embedding of the token that follows it."""
cfg, cache, prev = self.config, state.cache, state.prev_token
x = x.clone()
is_patch = (prev == cfg.point_patch_id) | (prev == cfg.center_patch_id)
rows = is_patch & state.patch_resolved
if rows.any():
ix = (cache.token_offset + state.patch)[rows]
x[rows, -1] += cache.image_features[ix].to(x.dtype)
rows = prev == cfg.point_subpatch_id
if rows.any():
feats = cache.vit_features[rows, state.patch[rows], state.subpatch[rows]]
x[rows, -1] += self.build_subpatch_embeddings(feats).to(x.dtype)
rows = prev == cfg.point_loc_id
if rows.any():
x[rows, -1] += self.build_location_embeddings(state.loc[rows]).to(x.dtype)
return x
def add_input_point_feedback(self, x, input_ids, input_point_ids, token_pooling,
image_features, vit_features):
"""Prefill version of `add_grounding_feedback` for grounding tokens in the prompt.
`input_point_ids` has one (patch, subpatch, loc) row per patch token that is followed by a
sub-patch token, or (anchor, -1, -1) for one followed by a mask token, in prompt order.
"""
cfg = self.config
is_patch = torch.isin(input_ids, torch.tensor(
[cfg.point_patch_id, cfg.center_patch_id], device=input_ids.device))
nxt = F.pad(input_ids[:, 1:], [0, 1], value=-1)
# Not the end-of-points marker
real_patch = is_patch & ((nxt == cfg.point_subpatch_id) | (nxt == cfg.seg_mask_id))
counts = (token_pooling >= 0).any(-1).sum(-1)
offsets = F.pad(counts.cumsum(0)[:-1], [1, 0])
x = x.clone()
for b in range(input_ids.shape[0]):
ids = input_point_ids[b] if input_point_ids is not None else input_ids.new_zeros(0, 3)
ids = ids[ids[:, 0] >= 0]
patch_pos = real_patch[b].nonzero()[:, 0]
sub_pos = (input_ids[b] == cfg.point_subpatch_id).nonzero()[:, 0]
loc_pos = (input_ids[b] == cfg.point_loc_id).nonzero()[:, 0]
is_point = ids[:, 1] >= 0
if not (len(ids) == len(patch_pos) and int(is_point.sum()) == len(sub_pos) == len(loc_pos)):
raise ValueError(
f"the prompt has {len(patch_pos)} grounding blocks but {len(ids)} input point ids; "
"pass groundings through the processor so it can build `input_point_ids`")
if not len(ids):
continue
x[b, patch_pos + 1] += image_features[offsets[b] + ids[:, 0]].to(x.dtype)
if not len(sub_pos):
continue
patch, subpatch, loc = ids[is_point].unbind(-1)
feats = self.subpatch_hidden(vit_features[b, patch, subpatch])
x[b, sub_pos + 1] += self.build_subpatch_embeddings(feats).to(x.dtype)
x[b, loc_pos + 1] += self.build_location_embeddings(loc).to(x.dtype)
return x
def patch_logits(self, h, b, state):
"""`[n_patches + 1]` logits for row `b`, the last entry being end-of-points."""
cache = state.cache
q = self.patch_q(h)
sin, cos = rope_sin_cos(cache.image_pos_ids[b, state.rotate_by[b]], q.shape[-1],
self.config.pointer_rope_theta)
q = apply_rope(q, sin, cos)
logits = (cache.patch_k[b].float() @ q.float()) / math.sqrt(q.shape[-1])
logits = torch.where(cache.patch_k_mask[b].any(-1), logits, SMALL_VALUE)
return F.pad(logits, [0, 1])
def subpatch_logits(self, h, b, state):
k = state.cache.subpatch_k[b, state.patch[b]]
return (k.float() @ self.subpatch_q(h).float()) / math.sqrt(k.shape[-1])
def mask_scores(self, h, b, state):
"""`[P, S, n_locs]` mask probabilities for row `b`, -1 where nothing can be selected."""
cfg, cache = self.config, state.cache
tok_q, vit_q, loc_q = self.mask_q(h).float().split(cfg.point_query_dims, dim=-1)
sin, cos = rope_sin_cos(cache.image_pos_ids[b, state.patch[b]], tok_q.shape[-1],
cfg.pointer_rope_theta)
tok_q = apply_rope(tok_q, sin, cos)
scores = (
(cache.patch_k[b].float() @ tok_q)[:, None, None] / math.sqrt(tok_q.shape[-1])
+ (cache.subpatch_k[b].float() @ vit_q)[..., None] / math.sqrt(vit_q.shape[-1])
+ (cache.loc_k[b].float() @ loc_q) / math.sqrt(loc_q.shape[-1]))
scores = self.diffuse(scores, b, cache)
return torch.where(cache.patch_k_mask[b][..., None], torch.sigmoid(scores), -1.0)
def diffuse(self, scores, b, cache):
"""Scatter the scores onto each crop's ViT raster, diffuse them, and read them back."""
P, S, n_locs = scores.shape
grid = self.config.vision_config.grid_size
r = int(round(math.sqrt(n_locs)))
weights = cache.diffusion_weights
n_crops = weights.shape[0] // cache.token_pooling.shape[0]
weights = weights[b * n_crops:(b + 1) * n_crops]
pooling = cache.token_pooling[b]
keep = pooling >= 0
raster = scores.new_zeros(n_crops * grid * grid, n_locs)
raster[pooling[keep]] = scores[keep]
m = raster.reshape(n_crops, grid, grid, r, r).permute(0, 1, 3, 2, 4)
m = diffuse_mask(m.reshape(n_crops, 1, grid * r, grid * r), weights.to(m.dtype),
self.config.mask_diffusion_steps)
m = m.reshape(n_crops, grid, r, grid, r).permute(0, 1, 3, 2, 4).reshape(-1, n_locs)
out = scores.clone()
out[keep] = m[pooling[keep]]
return out
# ── forward ──
def bidirectional_mask_fn(self, input_ids):
"""Contiguous runs of vision tokens attend to each other; a <frame_start> starts a new run."""
is_vision = torch.isin(input_ids, torch.tensor(self.config.vision_token_ids, device=input_ids.device))
span = torch.cumsum((~is_vision) | (input_ids == self.config.frame_start_token_id), -1)
n = input_ids.shape[1]
def inner(batch_idx, head_idx, q_idx, kv_idx):
kv = torch.where(kv_idx < n, kv_idx, 0)
return (is_vision[batch_idx, q_idx] & is_vision[batch_idx, kv] & (kv_idx < n)
& (span[batch_idx, q_idx] == span[batch_idx, kv]))
return inner
def forward(self, input_ids, attention_mask=None, position_ids=None, past_key_values=None,
pixel_values=None, token_pooling=None, patch_pos_ids=None, input_point_ids=None,
grounding_state=None, use_cache=True):
cfg = self.config
B, L = input_ids.shape
past_len = 0 if past_key_values is None else past_key_values.get_seq_length()
is_prefill = past_len == 0
has_images = is_prefill and pixel_values is not None
if use_cache and past_key_values is None:
past_key_values = DynamicCache(config=cfg.text_config)
if position_ids is None:
if attention_mask is not None and attention_mask.ndim == 2:
position_ids = (attention_mask.long().cumsum(-1) - 1).clamp(min=0)[:, -L:]
else:
position_ids = torch.arange(past_len, past_len + L, device=input_ids.device)[None].expand(B, -1)
has_points = is_prefill and torch.isin(input_ids, torch.tensor(
cfg.grounding_token_ids, device=input_ids.device)).any()
if has_points and not has_images:
raise ValueError("points in the prompt need an image or video")
# <im_low> shares the <im_patch> embedding
to_embed = torch.where(input_ids == cfg.image_low_res_id, cfg.image_patch_id, input_ids)
x = self.transformer.wte(to_embed)
if has_images:
image_features, vit_features, conv, weights = self.encode_images(
pixel_values, token_pooling, patch_pos_ids)
is_image = (input_ids == cfg.image_patch_id) | (input_ids == cfg.image_low_res_id)
if int(is_image.sum()) != len(image_features):
raise ValueError(f"{int(is_image.sum())} image tokens but {len(image_features)} image features")
x = x.clone()
x[is_image] = image_features.to(x.dtype)
if has_points:
x = self.add_input_point_feedback(x, input_ids, input_point_ids, token_pooling,
image_features, vit_features)
elif grounding_state is not None and grounding_state.cache is not None and not is_prefill:
x = self.add_grounding_feedback(x, grounding_state)
mask_kwargs = dict(config=cfg.text_config, inputs_embeds=x, attention_mask=attention_mask,
past_key_values=past_key_values, position_ids=position_ids)
if "cache_position" in inspect.signature(create_causal_mask).parameters:
mask_kwargs["cache_position"] = torch.arange(past_len, past_len + L, device=x.device)
if is_prefill:
mask_kwargs["or_mask_function"] = self.bidirectional_mask_fn(input_ids)
mask = create_causal_mask(**mask_kwargs)
hidden = self.transformer(x, position_ids, mask, past_key_values)
if grounding_state is not None and is_prefill and has_images:
grounding_state.reset(B, input_ids.device)
grounding_state.cache = self.build_image_cache(
input_ids, self.x_norm(hidden), token_pooling, image_features, vit_features,
conv, weights)
return hidden, past_key_values
class Molmo3ForConditionalGeneration(Molmo3PreTrainedModel, GenerationMixin):
_tied_weights_keys = []
def __init__(self, config: Molmo3Config):
super().__init__(config)
self.model = Molmo3Model(config)
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self.post_init()
def get_input_embeddings(self):
return self.model.transformer.wte
def get_output_embeddings(self):
return self.lm_head
def forward(self, input_ids, attention_mask=None, position_ids=None, past_key_values=None,
pixel_values=None, token_pooling=None, patch_pos_ids=None, input_point_ids=None,
use_cache=True, logits_to_keep=0,
grounding_state: Optional[Molmo3GroundingState] = None, **kwargs):
hidden, past_key_values = self.model(
input_ids, attention_mask=attention_mask, position_ids=position_ids,
past_key_values=past_key_values, pixel_values=pixel_values,
token_pooling=token_pooling, patch_pos_ids=patch_pos_ids,
input_point_ids=input_point_ids,
grounding_state=grounding_state, use_cache=use_cache)
keep = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
logits = self.lm_head(self.model.transformer.ln_f(hidden[:, keep]))
state = grounding_state
if state is not None and state.cache is not None:
logits = self.resolve_grounding(input_ids[:, -1], self.model.x_norm(hidden[:, -1]), logits, state)
state.prev_token = input_ids[:, -1]
return CausalLMOutputWithPast(logits=logits, past_key_values=past_key_values)
@torch.no_grad()
def resolve_grounding(self, tokens, h, logits, state: Molmo3GroundingState):
"""Resolve the grounding token each row was fed, and constrain each row's next token."""
cfg, model = self.config, self.model
grounding_ids = cfg.grounding_token_ids
patch_tokens = (cfg.point_patch_id, cfg.center_patch_id)
for b, token in enumerate(tokens.tolist()):
row = logits[b, -1]
if cfg.corresponding_patch_id is not None:
row[cfg.corresponding_patch_id] = SMALL_VALUE # deprecated
if token in patch_tokens:
state.last_patch_token[b] = token
patch_logits = model.patch_logits(h[b], b, state)
eop = len(patch_logits) - 1
if token == cfg.center_patch_id:
ix = int(patch_logits[:-1].argmax()) # a center point can never end a list
else:
no_point = float(torch.softmax(patch_logits.float(), -1)[-1])
if state.first_no_point[b] is None:
state.first_no_point[b] = no_point
# Point iff the real patches hold more than `presence_threshold` of the mass,
# except that a list already under way stops by plain argmax
continuing = token == cfg.point_patch_id and state.list_started[b]
if not continuing:
if 1.0 - no_point > cfg.presence_threshold:
patch_logits[-1] = SMALL_VALUE
else:
patch_logits[:-1] = SMALL_VALUE
ix = int(patch_logits.argmax())
if token == cfg.point_patch_id:
state.list_started[b] = ix != eop
if ix == eop:
state.patch[b] = 0
state.rotate_by[b] = 0
state.patch_resolved[b] = False
row[grounding_ids] = SMALL_VALUE
else:
state.patch[b] = ix
state.patch_resolved[b] = True
if token != cfg.center_patch_id:
state.rotate_by[b] = ix # the next patch query rotates to this one
allowed = row[grounding_ids].clone()
row.fill_(SMALL_VALUE)
row[grounding_ids] = allowed
elif token == cfg.seg_mask_id:
state.mask_scores[b].append(model.mask_scores(h[b], b, state).cpu())
state.mask_anchors[b].append(int(state.patch[b]))
elif token == cfg.point_subpatch_id:
state.subpatch[b] = int(model.subpatch_logits(h[b], b, state).argmax())
row[cfg.point_loc_id] = 100000
elif token == cfg.point_loc_id:
state.loc[b] = int(model.loc_q(h[b]).float().argmax())
state.point_triples[b].append(
(int(state.patch[b]), int(state.subpatch[b]), int(state.loc[b])))
if state.last_patch_token[b] == cfg.center_patch_id:
row[cfg.center_patch_id] = SMALL_VALUE
else:
# These can only follow a patch token
row[[cfg.seg_mask_id, cfg.point_subpatch_id, cfg.point_loc_id]] = SMALL_VALUE
return logits
def generate(self, *args, **kwargs):
"""`GenerationMixin.generate`. With `return_dict_in_generate=True` the output also has
`grounding`, one `Molmo3Grounding` per row, for `Molmo3Processor.decode`."""
config = kwargs.get("generation_config") or self.generation_config
setting = lambda name: kwargs.get(name, getattr(config, name, None)) or 1 # unset is None
if kwargs.get("pixel_values") is not None and (
setting("num_beams") > 1 or setting("num_return_sequences") > 1):
raise NotImplementedError("grounding picks are kept per batch row, so beam search and "
"num_return_sequences > 1 are not supported with images")
# Grounding tokens are only decoded correctly with a state, so always keep one
state = Molmo3GroundingState() if kwargs.get("pixel_values") is not None else None
out = super().generate(*args, grounding_state=state, **kwargs)
if not isinstance(out, ModelOutput):
return out
n = out.sequences.shape[0]
if state is None or state.point_triples is None:
grounding = [Molmo3Grounding([], [], []) for _ in range(n)]
else:
grounding = [Molmo3Grounding(state.point_triples[b], state.mask_anchors[b],
state.mask_scores[b], state.first_no_point[b])
for b in range(n)]
return Molmo3GenerateOutput(**out, grounding=grounding)
__all__ = ["Molmo3ForConditionalGeneration", "Molmo3Model", "Molmo3Grounding", "Molmo3GenerateOutput"]