Run this model with HF Jobs

Run allenai/Molmo3-4B 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 and TRL to fine-tune https://huggingface.co/allenai/Molmo3-4B. 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/allenai/Molmo3-4B 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/allenai/Molmo3-4B. 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.

Quantize for lower memory use

Use HF Jobs to create a 4-bit version of https://huggingface.co/allenai/Molmo3-4B. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Molmo3-4B / processing_molmo3.py
chrisc36's picture
Add Molmo3-4B
f33d924
Raw History Blame Contribute Delete
66.2 kB
"""Stand-alone Molmo3 processor: chat formatting, image/video preprocessing and grounding decoding. processor = Molmo3Processor.from_pretrained(path) messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "Point to the cats."}]}] inputs = processor.apply_chat_template(messages, images=[image], tokenize=True) out = model.generate(**inputs, max_new_tokens=512, return_dict_in_generate=True) answer = processor.decode(out.sequences[0, inputs["input_ids"].shape[1]:], out.grounding[0], images=[image]) `answer` is the same document vLLM's `json_objects` grounding mode returns. For multi-turn chat, append `processor.answer_message(ids, out.grounding[0])`, the raw answer with its grounding; `encode_document` turns a document back into text and grounding. Images are tiled into up to `max_crops` overlapping 378px crops plus a low-res global crop; videos are sampled at up to `max_fps` (at most `max_frames` frames) and each frame resized to 378px. """ import json import math import os import re from typing import List, Optional, Union import numpy as np import torch import torchvision.transforms from PIL import Image from transformers import AutoTokenizer, BatchFeature from transformers.utils import cached_file from .configuration_molmo3 import Molmo3Config # noqa: F401, remote code copies direct imports only from .modeling_molmo3 import Molmo3Grounding IMAGE_PATCH_TOKEN = "<im_patch>" IMAGE_LOW_RES_TOKEN = "<im_low>" IM_START_TOKEN = "<im_start>" LOW_RES_IMAGE_START_TOKEN = "<low_res_im_start>" IM_END_TOKEN = "<im_end>" IM_COL_TOKEN = "<im_col>" FRAME_START_TOKEN = "<frame_start>" FRAME_END_TOKEN = "<frame_end>" IMAGE_PROMPT = "<|image|>" VIDEO_PROMPT = "<|video|>" POINT_PATCH, POINT_SUBPATCH, POINT_LOC = "<|POINT_PATCH|>", "<|POINT_SUBPATCH|>", "<|POINT_LOC|>" SEG_MASK, CENTER_PATCH = "<|SEG_MASK|>", "<|CENTER_PATCH|>" PATCH_LOCATION = 4 # each ViT patch is split into a 4x4 grid of locations N_PATCH_EXT = 32768 # `<|PATCH_32768|>` is the extended format's end-of-points marker N_SUBPATCH_EXT = 9 # sub-patches per pooled token, up to video's 3x3 # The tags `extract_grounding` decodes, each with its own label / closing-tag rules TAG_RES = [re.compile(x, re.DOTALL) for x in ( r'<(tracks|bboxes|box3d) coords="([^"]+)">(.*?)</(?:tracks|bboxes|seg|point|box3d)>', r'<(points|trace) coords="([^"]+)"(?:/>|>(?:([^<]*)</(?:points?|trace)>)?)', r'<(seg) coords="([^"]+)"(?:/>|>(?:([^<]*)</seg>)?)', r'<(points3d) coords="([^"]+)"(?:/>|>(?:([^<]*)</points3d>)?)', r'<(pointsn) coords="([^"]+)"(?:/>|>(?:([^<]*)</pointsn>)?)', )] ID_LAST_RE = re.compile(re.escape(POINT_LOC) + r" ?([0-9]+)") DIST_RE = re.compile(r"^\s*(?:1\s+(\d+(?:\.\d+)?)|0(?![\d.]))") NORMAL_RE = re.compile(r"^\s*(?:(0)(?!\S)|([12])\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?))") STANDARD_TOKEN_RE = re.compile(r"(<\|(?:POINT_PATCH|POINT_SUBPATCH|POINT_LOC|SEG_MASK|CENTER_PATCH)\|>)") EXTENDED_TOKEN_RE = re.compile(r"<\|(CENTER_PATCH|PATCH|SUBPATCH|LOC|MASK)(?:_(\d+))?\|>") # Only the extended forms; the standard `<|CENTER_PATCH|>` also matches the pattern above EXTENDED_ONLY_RE = re.compile(r"<\|(?:(?:CENTER_PATCH|PATCH|SUBPATCH|LOC)_\d+|MASK)\|>") # A 3D box track's id sits at the box boundary, before the next `<|POINT_PATCH|>` BOX3D_ID_RE = re.compile(r"(?<![\d.])([0-9]+) ?(?=<\|POINT_PATCH\|>)") NUMBER_RE = re.compile(r"-?\d+(?:\.\d+)?") # A predicted camera, `<camera hfov=.. vfov=../>` per image, or the older `<intr vals="1 h v">` CAMERA_TAG_RE = re.compile(r"<camera\s+hfov=(-?[\d.]+)\s+vfov=(-?[\d.]+)\s*/?>") INTR_TAG_RE = re.compile(r'<intr .*?vals="([^"]*)"/?>') INTR_RECORD_SEP_RE = re.compile(r"[;\t:,]") MARKER_RE = re.compile(r'<(points|points3d|pointsn|tracks|seg|box3d|dopoints) id="(\d+)">(.*?)</\1>', re.DOTALL) # Fields and defaults of each element type, in order; training-only fields of the native # `olmo.message` dataclasses are left out ELEMENT_FIELDS = { "points": dict(coordinates=None, label=None, confidence=None, ordered=False), "video_points": dict(coordinates=None, label=None, confidence=None), "points_3d": dict(coordinates=None, label=None, confidence=None), "points_normal": dict(coordinates=None, label=None, confidence=None, flags=None), "video_tracks": dict(coordinates=None, label=None, confidence=None), "segmentation": dict(masks=None, label=None, mm_ids=None, confidence=None), "bounding_boxes_3d": dict(coordinates=None, label=None, K=None, confidence=None), } # One `Box3D` (a `bounding_boxes_3d` coordinate), then the `_norm` companions vLLM adds BOX3D_FIELDS = dict(mm_ix=0, center=None, size=None, rotation=None, time=None, object_id=None, bbox_2d=None, reference_point_2d=None, center_2d=None, depth=None, mask_2d=None) COORDINATE_FIELDS = { "points": ("mm_ix", "x", "y"), "video_points": ("mm_ix", "time", "x", "y"), "points_3d": ("mm_ix", "x", "y", "depth"), "points_normal": ("mm_ix", "x", "y", "nx", "ny", "nz"), "video_tracks": ("mm_ix", "object_id", "time", "x", "y"), } TAG_NAMES = {"points": "points", "points_3d": "points3d", "points_normal": "pointsn", "video_points": "points", "video_tracks": "tracks", "segmentation": "seg", "bounding_boxes_3d": "box3d"} # Styles the checkpoint was trained to see without their `style: ` prefix (native's # `demo_or_style_v3` with `surface_normal_demo_style`) NO_PREFIX_STYLES = frozenset([ "3d_pointing", "camera_intrinsics", "camera_pose", "correction_qa", "cosyn_point", "long_caption", "multi_image_count_then_point", "multi_image_counting", "multi_image_point_then_count", "multi_image_pointing", "pixmo_seg", "point_count", "point_distance", "point_to_depth", "pointing", "segmentation", "short_caption", "spatial_codes_da", "spatial_da", "spatial_depth_da", "text_sft", "user_qa", "video_clip_caption_start_end", "video_clip_caption_start_end_in_seconds", "video_clip_transcript_start_end", "video_clip_transcript_start_end_in_seconds", "video_count", "video_count_point", "video_frame_caption_timestamp", "video_frame_caption_timestamp_in_seconds", "video_long_caption", "video_point", "video_point_count", "video_point_track_all_frames", "video_point_track_per_frame", "video_point_track_start_end", "video_short_caption", "video_single_point_track_start_end", "video_transcript", "video_multiple_choice", "video_multiple_choice_count_without_pointing", "video_multiple_choice_multiple_correct", "video_multiple_choice_w_subtitle", "a_okvqa_mc", "ai2_diagram", "ai2_diagram_no_letter", "eval_multi_image_mc", "eval_multiple_choice", "mantis_instruct_mc", "multi_image_mc", "multi_image_mc_exp", "science_qa", "spatial_codes_mc", "spatial_depth_mc", "spatial_mc", "points_as_3d_det", "video_points_as_3d_det", "3d_detection_from_jitter", "3d_detection_from_jitter_supervised", "video_box3d_track_per_frame", "video_box3d_ground_start_end", "video_single_box3d_track_per_frame", "surface_normal", ]) # The same prompt `Molmo3Processor.apply_chat_template` builds, for servers that format chats with # the tokenizer's template (vLLM). Content items may also be OpenAI-style `image_url` / `video_url`. CHAT_TEMPLATE = ( "{%- set NO_PREFIX = [" + ", ".join(f"'{s}'" for s in sorted(NO_PREFIX_STYLES)) + "] -%}" "{%- set ns = namespace(images=0, n_images=0) -%}" "{%- for message in messages -%}{%- if message['content'] is not string -%}" "{%- for c in message['content'] -%}" "{%- if c['type'] == 'image' or c['type'] == 'image_url' -%}" "{%- set ns.n_images = ns.n_images + 1 -%}{%- endif -%}" "{%- endfor -%}{%- endif -%}{%- endfor -%}" "{%- for message in messages -%}" "{%- if (loop.index0 % 2 == 0 and message['role'] != 'user') or " "(loop.index0 % 2 == 1 and message['role'] != 'assistant') -%}" "{{ raise_exception('roles must alternate user/assistant, starting with user') }}{%- endif -%}" "{%- set m = namespace(text='') -%}" "{%- if message['content'] is string -%}{%- set m.text = message['content'] -%}" "{%- else -%}{%- for c in message['content'] -%}" "{%- if c['type'] == 'text' -%}" "{%- if c['style'] is defined and c['style'] and c['style'] not in NO_PREFIX -%}" "{%- set m.text = m.text ~ c['style'] ~ ': ' ~ c['text'] -%}" "{%- else -%}{%- set m.text = m.text ~ c['text'] -%}{%- endif -%}" "{%- elif c['type'] == 'image' or c['type'] == 'image_url' -%}" "{%- set ns.images = ns.images + 1 -%}" "{%- set m.text = m.text ~ ('Image ' ~ ns.images if ns.n_images > 1 else '') ~ '<|image|>' -%}" "{%- elif c['type'] == 'video' or c['type'] == 'video_url' -%}" "{%- set m.text = m.text ~ '<|video|>' -%}{%- endif -%}" "{%- endfor -%}{%- endif -%}" "{%- if message['role'] == 'user' -%}" "{{ ('<|im_end|>\n' if not loop.first else '') ~ '<|im_start|>user\n' ~ m.text ~ '<|im_end|>\n' }}" "{%- else -%}{{ '<|im_start|>assistant\n' ~ m.text }}{%- endif -%}" "{%- endfor -%}" "{%- if add_generation_prompt -%}{{ '<|im_start|>assistant\n' }}{%- endif -%}" ) CROP_SIZE = 378 PATCH_SIZE = 14 GRID = CROP_SIZE // PATCH_SIZE # ViT patches per crop side N_PATCHES = GRID * GRID OVERLAP_MARGINS = (4, 4) IMAGE_POOLING = 2 VIDEO_POOLING = 3 # ───────────────────────────── images ───────────────────────────── def resize(image: np.ndarray, size) -> np.ndarray: """uint8 `[..., H, W, 3]` -> uint8 `[..., h, w, 3]`, bilinear without antialiasing.""" x = torch.from_numpy(np.array(image, dtype=np.uint8)) x = x.permute(2, 0, 1) if x.ndim == 3 else x.permute(0, 3, 1, 2) x = torchvision.transforms.Resize(list(size), torchvision.transforms.InterpolationMode.BILINEAR, antialias=False)(x) x = torch.clip(x, 0, 255).to(torch.uint8) return (x.permute(1, 2, 0) if x.ndim == 3 else x.permute(0, 2, 3, 1)).numpy() def patchify(crops: np.ndarray) -> np.ndarray: """`[n, H, W, 3]` -> `[n, n_patches, PATCH_SIZE**2 * 3]`.""" n, h, w, c = crops.shape x = crops.reshape(n, h // PATCH_SIZE, PATCH_SIZE, w // PATCH_SIZE, PATCH_SIZE, c) return x.transpose(0, 1, 3, 2, 4, 5).reshape(n, -1, PATCH_SIZE * PATCH_SIZE * c) def pool_windows(idx: np.ndarray, pool: int) -> np.ndarray: """Group a `[h, w]` patch index grid into `[ceil(h/pool) * ceil(w/pool), pool*pool]` windows.""" h_pad = -idx.shape[0] % pool w_pad = -idx.shape[1] % pool idx = np.pad(idx, [[h_pad // 2, (h_pad + 1) // 2], [w_pad // 2, (w_pad + 1) // 2]], constant_values=-1) h, w = idx.shape[0] // pool, idx.shape[1] // pool return idx.reshape(h, pool, w, pool).transpose(0, 2, 1, 3).reshape(h * w, pool * pool) def select_tiling(h: float, w: float, tile: int, max_crops: int) -> np.ndarray: tilings = sorted(((i, j) for i in range(1, max_crops + 1) for j in range(1, max_crops + 1) if i * j <= max_crops), key=lambda x: (x[0] * x[1], x[0])) tilings = np.array(tilings, dtype=np.int32) with np.errstate(divide="ignore"): scale = np.min((tilings * tile).astype(np.float32) / np.array([h, w], np.float32), -1) if np.all(scale < 1): return tilings[np.argmax(scale)] # forced to downscale, so downscale as little as possible return tilings[np.argmin(np.where(scale < 1.0, 10e9, scale))] def image_layout(height: int, width: int, max_crops: int) -> dict: """Everything about how an image is tiled that does not depend on its pixels.""" left, right = OVERLAP_MARGINS margin_px = PATCH_SIZE * (left + right) window = (GRID - left - right) * PATCH_SIZE tiling = select_tiling(height - margin_px, width - margin_px, window, max_crops) # For each crop, which of its patches lie outside the overlap margins crops = [] for i in range(tiling[0]): for j in range(tiling[1]): idx = np.arange(N_PATCHES).reshape(GRID, GRID) + len(crops) * N_PATCHES if i != 0: idx[:left, :] = -1 if j != 0: idx[:, :left] = -1 if i != tiling[0] - 1: idx[-right:, :] = -1 if j != tiling[1] - 1: idx[:, -right:] = -1 crops.append(idx) resized_hw = (int(tiling[0] * window + margin_px), int(tiling[1] * window + margin_px)) mapping = np.stack(crops).reshape(tiling[0], tiling[1], GRID, GRID).transpose(0, 2, 1, 3).reshape(-1) # `mapping[y, x]` is the ViT patch for each patch of the resized image; the global crop goes first mapping = mapping[mapping >= 0].reshape(resized_hw[0] // PATCH_SIZE, resized_hw[1] // PATCH_SIZE) mapping = mapping + N_PATCHES global_pooling = pool_windows(np.arange(N_PATCHES).reshape(GRID, GRID), IMAGE_POOLING) token_pooling = np.concatenate([global_pooling, pool_windows(mapping, IMAGE_POOLING)]) n_global = -(-GRID // IMAGE_POOLING) grid_h, grid_w = -(-mapping.shape[0] // IMAGE_POOLING), -(-mapping.shape[1] // IMAGE_POOLING) # (t, h, w) of each ViT patch: t=0 for the global crop, t=1 for the high-res crops n_crops = 1 + len(crops) pos = np.zeros((n_crops, N_PATCHES, 3), dtype=np.int64) pos[0, :, 1], pos[0, :, 2] = np.divmod(np.arange(N_PATCHES), GRID) hh, ww = np.indices(mapping.shape) flat = mapping.reshape(-1) pos[flat // N_PATCHES, flat % N_PATCHES] = np.stack( [np.ones_like(flat), hh.reshape(-1), ww.reshape(-1)], -1) return dict(tiling=tiling, resized_hw=resized_hw, window=window, mapping=mapping, token_pooling=token_pooling, patch_pos_ids=pos, n_global_tokens=n_global ** 2, grid=(n_global, n_global, grid_h, grid_w)) def image_tokens(grid) -> str: low_h, low_w, h, w = grid return (LOW_RES_IMAGE_START_TOKEN + IMAGE_LOW_RES_TOKEN * (low_h * low_w) + IM_END_TOKEN + IM_START_TOKEN + (IMAGE_PATCH_TOKEN * w + IM_COL_TOKEN) * h + IM_END_TOKEN) def preprocess_image(image, max_crops: int) -> dict: image = np.asarray(image.convert("RGB") if isinstance(image, Image.Image) else image) if image.dtype != np.uint8: raise ValueError("images must be PIL images or uint8 arrays") layout = image_layout(image.shape[0], image.shape[1], max_crops) src = resize(image, layout["resized_hw"]) crops = [resize(image, (CROP_SIZE, CROP_SIZE))] window = layout["window"] for i in range(layout["tiling"][0]): for j in range(layout["tiling"][1]): crops.append(src[i * window:i * window + CROP_SIZE, j * window:j * window + CROP_SIZE]) return dict(pixels=patchify(np.stack(crops)), token_pooling=layout["token_pooling"], patch_pos_ids=layout["patch_pos_ids"], tokens=image_tokens(layout["grid"])) # ───────────────────────────── video ───────────────────────────── def sample_times(duration: float, max_frames: int, max_fps: float) -> np.ndarray: """Every `1/max_fps` seconds, or `max_frames` evenly spaced times when that would not fit.""" if max_frames / max_fps >= duration: times = np.arange(0.0, duration, 1 / max_fps) else: times = np.linspace(0, duration, num=max_frames, endpoint=False, dtype=np.float64) return times if len(times) else np.zeros(1) def load_video(path: str, max_frames: int = 128, max_fps: float = 2.0) -> dict: """Decode the frames to show the model; returns `{"frames": [T, H, W, 3] uint8, "timestamps": [T]}`.""" try: from torchcodec.decoders import VideoDecoder except ImportError: return _load_video_pyav(path, max_frames, max_fps) decoder = VideoDecoder(path, seek_mode="exact", num_ffmpeg_threads=0) meta = decoder.metadata times = sample_times(meta.duration_seconds, max_frames, max_fps) offset = meta.begin_stream_seconds_from_content lo, hi = offset + 1e-6, meta.end_stream_seconds_from_content - 1e-6 played = [max(lo, min(hi, float(t) + offset)) for t in times] frames = decoder.get_frames_played_at(played).data.numpy().transpose(0, 2, 3, 1) return dict(frames=frames, timestamps=times) def _load_video_pyav(path: str, max_frames: int, max_fps: float) -> dict: try: # optional: trust_remote_code requires every import outside a try block import av except ImportError: raise ImportError("video loading needs torchcodec or PyAV (`pip install torchcodec` or `av`)") with av.open(path) as container: stream = container.streams.video[0] frames = list(container.decode(video=0)) start = float(frames[0].pts * stream.time_base) ends = np.array([float(f.pts * stream.time_base) - start for f in frames[1:]]) fps = float(stream.average_rate or stream.guessed_rate) duration = float(frames[-1].pts * stream.time_base) - start + 1 / fps times = sample_times(duration, max_frames, max_fps) ix = np.minimum(np.searchsorted(np.append(ends, duration), times, side="right"), len(frames) - 1) video = np.stack([frames[i].to_ndarray(format="rgb24") for i in ix]) return dict(frames=video, timestamps=times) def preprocess_video(video: dict) -> dict: frames, times = np.asarray(video["frames"]), np.asarray(video["timestamps"]) n = len(frames) pooling = pool_windows(np.arange(N_PATCHES).reshape(GRID, GRID), VIDEO_POOLING) token_pooling = np.concatenate([pooling + i * N_PATCHES for i in range(n)]) pos = np.stack(np.indices((n, GRID, GRID)), -1).reshape(n, N_PATCHES, 3) per_frame = IMAGE_PATCH_TOKEN * len(pooling) tokens = FRAME_START_TOKEN + "".join( f"{' ' if i else ''}{t:.1f} " + per_frame for i, t in enumerate(times)) + FRAME_END_TOKEN return dict(pixels=patchify(resize(frames, (CROP_SIZE, CROP_SIZE))), token_pooling=token_pooling, patch_pos_ids=pos, tokens=tokens) def mask_to_rle(mask: np.ndarray) -> dict: """A boolean `[H, W]` mask as COCO compressed RLE, as `pycocotools.mask.encode` writes it.""" h, w = mask.shape flat = np.asarray(mask, dtype=bool).reshape(-1, order="F") change = np.flatnonzero(flat[1:] != flat[:-1]) + 1 runs = np.diff(np.concatenate([[0], change, [flat.size]])).tolist() if flat.size and flat[0]: runs = [0] + runs chars = [] for i, x in enumerate(runs): x = int(x) - (int(runs[i - 2]) if i > 2 else 0) more = True while more: c = x & 0x1F x >>= 5 more = x != -1 if c & 0x10 else x != 0 chars.append(chr((c | 0x20 if more else c) + 48)) return {"size": [int(h), int(w)], "counts": "".join(chars)} def rle_to_mask(rle: dict) -> np.ndarray: """COCO compressed RLE (as in `decode` output) -> a boolean `[H, W]` mask.""" h, w = rle["size"] s, counts, p = rle["counts"], [], 0 while p < len(s): x = k = 0 more = True while more: c = ord(s[p]) - 48 x |= (c & 0x1F) << (5 * k) more = bool(c & 0x20) p, k = p + 1, k + 1 if not more and c & 0x10: x |= -1 << (5 * k) counts.append(x + (counts[-2] if len(counts) > 2 else 0)) flat = np.zeros(h * w, dtype=bool) pos = 0 for i, c in enumerate(counts): flat[pos:pos + c] = i % 2 == 1 pos += c return flat.reshape((h, w), order="F") def extended_grounding_tokens() -> List[str]: """The extended grounding tokens in id order: `<|PATCH_n|>` (the last one is end-of-points), `<|SUBPATCH_n|>`, `<|LOC_n|>`, `<|MASK|>` and `<|CENTER_PATCH_n|>`.""" return ([f"<|PATCH_{i}|>" for i in range(N_PATCH_EXT + 1)] + [f"<|SUBPATCH_{i}|>" for i in range(N_SUBPATCH_EXT)] + [f"<|LOC_{i}|>" for i in range(PATCH_LOCATION ** 2)] + ["<|MASK|>"] + [f"<|CENTER_PATCH_{i}|>" for i in range(N_PATCH_EXT + 1)]) def add_extended_tokens(tokenizer, vocab_size: int) -> int: """Mint the extended grounding tokens right after the model's `vocab_size` rows, where vLLM reads them; returns how many were added (0 if they already are). Non-special, so they survive `skip_special_tokens`. This processor never tokenizes them: it rejects them in text and takes groundings as `Molmo3Grounding` instead. """ tokens = extended_grounding_tokens() if tokenizer.convert_tokens_to_ids(tokens[0]) == vocab_size: return 0 if len(tokenizer) != vocab_size: raise ValueError(f"the tokenizer has {len(tokenizer)} tokens, so the extended tokens would " f"not start at {vocab_size}, after the model's vocabulary") from tokenizers import AddedToken added = tokenizer.add_tokens([AddedToken(t, special=False, normalized=False) for t in tokens], special_tokens=False) assert tokenizer.convert_tokens_to_ids(tokens[0]) == vocab_size return added def merge_groundings(groundings) -> Optional[Molmo3Grounding]: """One chat's message groundings, in order, as one; None when there are none.""" groundings = [g for g in groundings if g is not None] if not groundings: return None return Molmo3Grounding(point_ids=[p for g in groundings for p in g.point_ids], mask_anchors=[a for g in groundings for a in g.mask_anchors], mask_scores=[]) def media_metadata(images=None, video=None, max_crops: int = 8) -> list: """Per image, or for the one video, the layout grounding is decoded and encoded against. Reads no pixels: `images` are PIL images, uint8 arrays or `(width, height)` sizes, and `video` is a `load_video` dict or `{"size": (width, height), "timestamps": [...]}`. """ if video is not None: if "frames" in video: n, h, w = np.asarray(video["frames"]).shape[:3] else: (w, h), n = video["size"], len(video["timestamps"]) pooling = pool_windows(np.arange(N_PATCHES).reshape(GRID, GRID), VIDEO_POOLING) return [dict(size=(w, h), timestamps=np.asarray(video["timestamps"], dtype=np.float64), token_pooling=np.concatenate([pooling + i * N_PATCHES for i in range(n)]))] metadata = [] for image in images or []: if isinstance(image, Image.Image): w, h = image.size elif isinstance(image, (tuple, list)): w, h = (int(v) for v in image) else: h, w = np.asarray(image).shape[:2] layout = image_layout(h, w, max_crops) mapping = layout["mapping"] inverse = {int(v): divmod(i, mapping.shape[1]) for i, v in enumerate(mapping.reshape(-1))} metadata.append(dict(size=(w, h), mapping=mapping, mapping_shape=mapping.shape, inverse=inverse, token_pooling=layout["token_pooling"], n_global_tokens=layout["n_global_tokens"])) return metadata # ───────────────────────────── processor ───────────────────────────── class Molmo3Processor: config_keys = ("max_crops", "max_frames", "max_fps") def __init__(self, tokenizer, max_crops: int = 8, max_frames: int = 128, max_fps: float = 2.0): self.tokenizer = tokenizer self.max_crops = max_crops self.max_frames = max_frames self.max_fps = max_fps # so trust_remote_code users, who cannot import this module, still reach the mask helpers rle_to_mask = staticmethod(rle_to_mask) mask_to_rle = staticmethod(mask_to_rle) @classmethod def register_for_auto_class(cls, auto_class="AutoProcessor"): """Called by AutoProcessor when loading with trust_remote_code; nothing to register.""" @classmethod def from_pretrained(cls, path, **kwargs): hub_kwargs = {k: kwargs.pop(k) for k in ("revision", "token", "cache_dir") if k in kwargs} config_file = cached_file(path, "processor_config.json", **hub_kwargs) with open(config_file) as f: config = cls._read_config(json.load(f)) config.update({k: kwargs.pop(k) for k in cls.config_keys if k in kwargs}) tokenizer = AutoTokenizer.from_pretrained(path, **hub_kwargs, **kwargs) return cls(tokenizer, **config) @staticmethod def _sub_config(pooling: int, **extra) -> dict: """The fixed preprocessing settings, in the transformers-native processor config layout.""" return dict(do_convert_rgb=True, do_normalize=True, do_rescale=True, do_resize=True, image_mean=[0.5] * 3, image_std=[0.5] * 3, patch_size=PATCH_SIZE, pooling_size=[pooling, pooling], resample=2, rescale_factor=1 / 255, size={"height": CROP_SIZE, "width": CROP_SIZE}, **extra) @classmethod def _read_config(cls, config: dict) -> dict: """Our settings from a processor config, either layout; raises on fixed settings we don't match.""" if "image_processor" not in config: # this repo's older flat layout return {k: v for k, v in config.items() if k in cls.config_keys} image, video = config["image_processor"], config.get("video_processor", {}) expected = [(image, cls._sub_config(IMAGE_POOLING, overlap_margins=list(OVERLAP_MARGINS))), (video, cls._sub_config(VIDEO_POOLING))] for sub, fixed in expected: for k, v in fixed.items(): if k in sub and sub[k] != v and not (isinstance(v, float) and abs(sub[k] - v) < 1e-9): raise ValueError(f"processor setting {k}={sub[k]!r} is not supported (only {v!r})") out = {"max_crops": image.get("max_crops"), "max_frames": video.get("num_frames"), "max_fps": video.get("max_fps")} return {k: v for k, v in out.items() if v is not None} def save_pretrained(self, path): os.makedirs(path, exist_ok=True) self.tokenizer.save_pretrained(path) config = dict( image_processor=self._sub_config( IMAGE_POOLING, image_processor_type="Molmo3ImageProcessor", max_crops=self.max_crops, overlap_margins=list(OVERLAP_MARGINS)), processor_class="Molmo3Processor", subpatch_location_size=4, video_processor=self._sub_config( VIDEO_POOLING, video_processor_type="Molmo3VideoProcessor", do_sample_frames=True, max_fps=self.max_fps, num_frames=self.max_frames, return_metadata=False)) with open(os.path.join(path, "processor_config.json"), "w") as f: json.dump(config, f, indent=2, sort_keys=True) def load_video(self, path: str) -> dict: return load_video(path, self.max_frames, self.max_fps) def apply_chat_template(self, conversation: list, add_generation_prompt: bool = True, tokenize: bool = False, images=None, videos=None, return_tensors: Optional[str] = "pt"): """Format a chat, or a batch of chats, as a prompt; with `tokenize=True` also run the processor on it and return the model inputs. Messages are `{"role", "content", "grounding"?}`, alternating user / assistant. Content is a string or a list of `{"type": "image"}` / `{"type": "video"}` (consuming `images` / `videos` in order) and `{"type": "text", "text", "style"?}` items; a `style` is prefixed as "style: text". A message whose text has grounding tokens needs the matching `Molmo3Grounding` as `grounding`: for an earlier answer, the message `answer_message` builds, or text and grounding from `encode_document`. Put images and videos first, as in training. """ batched = bool(conversation) and isinstance(conversation[0], (list, tuple)) convs = conversation if batched else [conversation] prompts = [self._format_chat(conv, add_generation_prompt) for conv in convs] groundings = [merge_groundings([m.get("grounding") for m in conv]) for conv in convs] if not tokenize: if any(g is not None for g in groundings): raise ValueError("a grounding cannot be carried in a prompt string; use tokenize=True") return prompts if batched else prompts[0] return self(prompts if batched else prompts[0], images=images, videos=videos, grounding=groundings if batched else groundings[0], return_tensors=return_tensors) def _format_chat(self, messages, add_generation_prompt) -> str: n_images = sum(1 for m in messages if isinstance(m["content"], list) for c in m["content"] if c.get("type") == "image") prompt, on_image = "", 0 for ix, message in enumerate(messages): role = message["role"] if role != ("user" if ix % 2 == 0 else "assistant"): raise ValueError("roles must alternate user/assistant, starting with user") content = message["content"] if isinstance(content, str): text = content else: text = "" for item in content: kind = item.get("type") if kind == "image": on_image += 1 text += (f"Image {on_image}" if n_images > 1 else "") + IMAGE_PROMPT elif kind == "video": text += VIDEO_PROMPT elif kind == "text": style = item.get("style") text += (f"{style}: {item['text']}" if style and style not in NO_PREFIX_STYLES else item["text"]) else: raise ValueError(f"unknown content type {kind}") if role == "user": prompt += ("<|im_end|>\n" if ix else "") + f"<|im_start|>user\n{text}<|im_end|>\n" else: prompt += f"<|im_start|>assistant\n{text}" if add_generation_prompt: prompt += "<|im_start|>assistant\n" return prompt def encode_document(self, document, images=None, videos=None): """A grounding document -> `(text, Molmo3Grounding)` for a message's content and grounding. `document` is what `decode` returns (or its JSON string): each `<points id="N">` marker in its `text` becomes element N's tag, and elements no marker names are appended. An element with its `text` is used as is; a points element can instead give `coordinates` in pixels (`x`, `y`) or normalized (`x_norm`, `y_norm`), plus `time` for a video, which needs the chat's `images` / `videos`. A bare element or list of elements gives just the tags. """ text, rows = self._parse_extended(self.render_document(document, images, videos)) return text, Molmo3Grounding(point_ids=[r for r in rows if r[1] >= 0], mask_anchors=[r[0] for r in rows if r[1] < 0], mask_scores=[]) def render_document(self, document, images=None, videos=None, seen_images: Optional[int] = None) -> str: """`encode_document`'s text before it is split from its grounding: every grounding in extended tokens, the format vLLM takes in a prompt. `images` may be `(width, height)` sizes and a video `{"size", "timestamps"}`. A point may name only the first `seen_images` images (default: all of them).""" if isinstance(document, str): document = json.loads(document) if isinstance(document, list) or "multi_modal" not in document: document = {"text": None, "multi_modal": document} videos = [self.load_video(v) if isinstance(v, str) else v for v in videos or []] metadata = None def render(element): nonlocal metadata if isinstance(element.get("text"), str): return element["text"] if metadata is None: metadata = self._mm_metadata(images, videos[0] if videos else None) return self._render_points(element, metadata, len(metadata) if seen_images is None else seen_images) return self._render_document(document, render) @staticmethod def _render_document(document, render) -> str: """A `{"text", "multi_modal"}` document as prompt text: each `<points id="N">` marker replaced by element N, and elements no marker names appended after a space.""" elements = document.get("multi_modal") or [] elements = [elements] if isinstance(elements, dict) else elements # A predicted camera's tag is already in the text elements = [e for e in elements if e.get("type") != "camera_intrinsics"] by_id = {e.get("grounding_id"): e for e in elements if e.get("grounding_id") is not None} used = set() def substitute(match): number = int(match.group(2)) if number not in by_id: return match.group(0) used.add(number) return render(by_id[number]) text = document.get("text") placed = MARKER_RE.sub(substitute, text) if text else "" trailing = "".join(render(e) for e in elements if e.get("grounding_id") not in used) if not trailing: return placed if text is None: return trailing return placed + ("" if not placed or placed[-1].isspace() else " ") + trailing def _render_points(self, element, metadata, seen_images) -> str: """A points element given by coordinates as the tag an answer uses, in extended tokens.""" if element.get("type") not in (None, "points", "video_points"): raise ValueError(f"a {element.get('type')} element needs its `text`; only points can be " "given by coordinates") if not metadata: raise ValueError("a point was given but the chat has no image or video") is_video = "timestamps" in metadata[0] triples = [] for c in element.get("coordinates") or []: index = int(c.get("mm_ix", c.get("mm_id", 0))) if not 0 <= index < len(metadata): raise ValueError(f"a point refers to image {index}, but there are {len(metadata)}") if not is_video and index >= seen_images: raise ValueError("a point refers to an image that comes after it; put images first") w, h = metadata[index]["size"] if "x" in c and "y" in c: x, y = float(c["x"]), float(c["y"]) elif "x_norm" in c and "y_norm" in c: x, y = float(c["x_norm"]) * w, float(c["y_norm"]) * h else: raise ValueError(f"a point needs x and y, or x_norm and y_norm; got {sorted(c)}") where = float(c.get("time", 0.0)) if is_video else index triples.append(self._pixels_to_ids(where, x, y, metadata, is_video)) coords = "".join(f"<|PATCH_{t}|><|SUBPATCH_{s}|><|LOC_{l}|>{i + 1}" for i, (t, s, l) in enumerate(sorted(triples))) coords += f"<|PATCH_{N_PATCH_EXT}|>" label = element.get("label") return f'<points coords="{coords}">{label}</points>' if label else f'<points coords="{coords}"/>' def __call__(self, text: Union[str, List[str]], images=None, videos=None, grounding=None, return_tensors: Optional[str] = "pt") -> BatchFeature: """`text` holds one `<|image|>` / `<|video|>` per image / video, each consumed in order across the batch. A video is a path or a `load_video`-style dict. `grounding` is a `Molmo3Grounding` per text (or one for a single text) whose ids match the text's grounding tokens in order; they become `input_point_ids`. """ texts = [text] if isinstance(text, str) else list(text) groundings = grounding if isinstance(grounding, (list, tuple)) else [grounding] * len(texts) if len(groundings) != len(texts): raise ValueError(f"{len(groundings)} groundings for {len(texts)} texts") images, videos = list(images or []), list(videos or []) split_re = "(" + "|".join(re.escape(t) for t in (IMAGE_PROMPT, VIDEO_PROMPT)) + ")" examples, point_ids = [], [] for t, g in zip(texts, groundings): if EXTENDED_ONLY_RE.search(t): raise ValueError("extended grounding tokens in text; convert the document with " "`encode_document` and pass its grounding") rows = self._grounding_rows(t, g) parts, pieces = [], re.split(split_re, t) for i, piece in enumerate(pieces): if piece == IMAGE_PROMPT: part = preprocess_image(images.pop(0), self.max_crops) elif piece == VIDEO_PROMPT: video = videos.pop(0) part = preprocess_video(self.load_video(video) if isinstance(video, str) else video) else: continue pieces[i] = part["tokens"] parts.append(part) n_tokens = sum(len(p["token_pooling"]) for p in parts) if rows and (not parts or max(r[0] for r in rows) >= n_tokens): raise ValueError("a grounding refers to an image token this prompt does not have") point_ids.append(rows) examples.append(("".join(pieces), parts)) if images or videos: raise ValueError("more images/videos than placeholders in the text") ids = [self.tokenizer.encode(t, add_special_tokens=False) for t, _ in examples] seq_len = max(len(x) for x in ids) pad = self.tokenizer.pad_token_id out = dict( input_ids=np.array([[pad] * (seq_len - len(x)) + x for x in ids], dtype=np.int64), attention_mask=np.array([[0] * (seq_len - len(x)) + [1] * len(x) for x in ids], dtype=np.int64), ) if any(parts for _, parts in examples): out.update(self._batch_visual([parts for _, parts in examples])) if any(point_ids): arr = np.full((len(point_ids), max(len(x) for x in point_ids), 3), -1, dtype=np.int64) for b, x in enumerate(point_ids): if x: arr[b, :len(x)] = x out["input_point_ids"] = arr return BatchFeature(out, tensor_type=return_tensors) @staticmethod def _grounding_rows(text, grounding) -> list: """The `input_point_ids` rows for `text`'s grounding blocks: the next of `grounding.point_ids` for each point and (anchor, -1, -1) for each mask, in order.""" adjacent = list(re.finditer( "(" + "|".join(re.escape(t) for t in (POINT_PATCH, CENTER_PATCH)) + ")" "(" + re.escape(POINT_SUBPATCH) + "|" + re.escape(SEG_MASK) + ")", text)) if grounding is None: if adjacent: raise ValueError("this text has grounding tokens but no `grounding`; pass the " "Molmo3Grounding they came with") return [] points, anchors = list(grounding.point_ids), list(grounding.mask_anchors) n_points = sum(m.group(2) == POINT_SUBPATCH for m in adjacent) if n_points != len(points) or len(adjacent) - n_points != len(anchors): raise ValueError(f"the text has {n_points} points and {len(adjacent) - n_points} masks, " f"but the grounding has {len(points)} and {len(anchors)}") rows = [] for m in adjacent: rows.append(tuple(int(v) for v in points.pop(0)[:3]) if m.group(2) == POINT_SUBPATCH else (int(anchors.pop(0)), -1, -1)) return rows @staticmethod def _parse_extended(text): """Extended grounding tokens -> standard ones, plus a (patch, subpatch, loc) row per point and an (anchor, -1, -1) row per mask, in order.""" out, rows, at = [], [], 0 tokens = list(EXTENDED_TOKEN_RE.finditer(text)) i = 0 while i < len(tokens): m = tokens[i] kind, index = m.group(1), m.group(2) if kind not in ("PATCH", "CENTER_PATCH") or index is None: raise ValueError(f"grounding: {m.group(0)} does not follow a patch token") patch_token = POINT_PATCH if kind == "PATCH" else CENTER_PATCH out.append(text[at:m.start()]) nxt = [t for t in tokens[i + 1:i + 3]] follows = lambda k, j: (j < len(nxt) and nxt[j].group(1) == k and nxt[j].start() == (nxt[j - 1].end() if j else m.end())) if int(index) == N_PATCH_EXT: out.append(patch_token) at, i = m.end(), i + 1 elif follows("MASK", 0): out.append(patch_token + SEG_MASK) rows.append((int(index), -1, -1)) at, i = nxt[0].end(), i + 2 elif follows("SUBPATCH", 0) and follows("LOC", 1): out.append(patch_token + POINT_SUBPATCH + POINT_LOC) rows.append((int(index), int(nxt[0].group(2)), int(nxt[1].group(2)))) at, i = nxt[1].end(), i + 3 else: raise ValueError(f"grounding: {m.group(0)} is not followed by a sub-patch and " "location, or a mask") out.append(text[at:]) return "".join(out), rows @staticmethod def _pixels_to_ids(where, x, y, metadata, is_video): """Pixel coordinates -> (token, subpatch, location) ids, the inverse of `_point_to_pixels`.""" if is_video: meta = metadata[0] frame = int(np.argmin(np.abs(meta["timestamps"] - where))) mapping = np.arange(N_PATCHES).reshape(GRID, GRID) + frame * N_PATCHES offset = 0 else: meta = metadata[int(where)] mapping = meta["mapping"] offset = sum(len(m["token_pooling"]) for m in metadata[:int(where)]) w, h = meta["size"] ph, pw = mapping.shape px, py = pw * (x / w), ph * (y / h) ix, iy = min(math.floor(px), pw - 1), min(math.floor(py), ph - 1) vit_patch = mapping[iy, ix] token, subpatch = np.argwhere(meta["token_pooling"] == vit_patch)[0] n = PATCH_LOCATION loc = min(math.floor((py - iy) * n), n - 1) + min(math.floor((px - ix) * n), n - 1) * n return int(token) + offset, int(subpatch), int(loc) @staticmethod def _batch_visual(batch_parts) -> dict: """Concatenate each example's crops/frames, offsetting the pooling indices and the patch `t` positions part by part, then pad across the batch.""" examples = [] for parts in batch_parts: pixels, pooling, pos, n_crops, t_offset = [], [], [], 0, 0 for part in parts: p = part["patch_pos_ids"].copy() p[..., 0] += t_offset used = part["token_pooling"][part["token_pooling"] >= 0] t_offset = int(p.reshape(-1, 3)[used, 0].max()) + 1 pooling.append(np.where(part["token_pooling"] >= 0, part["token_pooling"] + n_crops * N_PATCHES, -1)) pixels.append(part["pixels"]) pos.append(p) n_crops += len(part["pixels"]) examples.append((pixels, pooling, pos)) n_crops = max((sum(len(x) for x in e[0]) for e in examples), default=0) n_tokens = max((sum(len(x) for x in e[1]) for e in examples), default=0) pool = max((x.shape[1] for e in examples for x in e[1]), default=1) pixel_values = np.zeros((len(examples), n_crops, N_PATCHES, PATCH_SIZE ** 2 * 3), np.uint8) token_pooling = np.full((len(examples), n_tokens, pool), -1, np.int64) patch_pos_ids = np.zeros((len(examples), n_crops, N_PATCHES, 3), np.int64) for b, (pixels, pooling, pos) in enumerate(examples): if not pixels: continue pixels, pos = np.concatenate(pixels), np.concatenate(pos) pooling = np.concatenate([np.pad(x, [[0, 0], [0, pool - x.shape[1]]], constant_values=-1) for x in pooling]) pixel_values[b, :len(pixels)] = pixels patch_pos_ids[b, :len(pos)] = pos token_pooling[b, :len(pooling)] = pooling return dict(pixel_values=pixel_values, token_pooling=token_pooling, patch_pos_ids=patch_pos_ids) # ── decoding ── def decode(self, token_ids, grounding=None, images=None, video: Optional[dict] = None, mask_threshold: float = 0.5, mode: str = "structured", intrinsics=None): """Decode one generated sequence (without its prompt) into the document vLLM's `json_objects` grounding mode returns. `{"text", "multi_modal", "type": "text"}`: `text` names each grounding as `<points id="N">label</points>`, and `multi_modal` holds the elements, each with pixel and normalized coordinates (masks as COCO RLE) and its `text`, the tag exactly as generated. `grounding` is the row's `Molmo3Grounding` from `generate(..., return_dict_in_generate=True)`; pass the same `images` (or loaded `video` dict) the prompt used. `encode_document` inverts it. `mode="json"` returns the document as a JSON string, and `mode="string"` the raw generated text, which carries the groundings only together with `grounding`. A 3D box's center is lifted into camera coordinates with `intrinsics`: a 3x3 `K` or an `(hfov, vfov)` pair in degrees, for all images or one per image. Without them, an image the model predicted a `<camera>` for uses that, and otherwise a box has only its `center_2d` pixel, `depth`, size and rotation. Predicted cameras are also returned, like vLLM, as a `camera_intrinsics` element (the tag stays in `text`). """ if mode not in ("structured", "json", "string"): raise ValueError(f"mode must be 'structured', 'json' or 'string', not {mode!r}") text = self._answer_text(token_ids) if mode == "string": return text doc = self.decode_text(text, grounding, images=images, video=video, mask_threshold=mask_threshold, intrinsics=intrinsics) return json.dumps(doc) if mode == "json" else doc def decode_text(self, text: str, grounding=None, images=None, video: Optional[dict] = None, mask_threshold: float = 0.5, intrinsics=None) -> dict: """`decode` from the generated text rather than its ids. `images` may be `(width, height)` sizes and `video` `{"size", "timestamps"}`, since only the layout is needed.""" fovs = self._camera_fovs(text) camera = [] if not any(fovs) else [dict(type="camera_intrinsics", label=None, coordinates=[ dict(mm_ix=i, hfov=fov[0], vfov=fov[1]) for i, fov in enumerate(fovs) if fov is not None])] if grounding is None or not (images or video is not None): return dict(text=text, multi_modal=camera, type="text") triples = [tuple(int(v) for v in t[:3]) for t in grounding.point_ids] masks = list(grounding.mask_scores) anchors = [int(a) for a in grounding.mask_anchors] metadata = self._mm_metadata(images, video) if intrinsics is None and any(fovs): intrinsics = [fovs[i] if i < len(fovs) else None for i in range(len(metadata))] for meta, K in zip(metadata, self._camera_matrices(intrinsics, metadata)): meta["K"] = K matches = sorted((m for r in TAG_RES for m in r.finditer(text)), key=lambda m: m.start()) parts, elements, on = [], [], 0 for tag in matches: if tag.start() < on: continue before, coords = text[:tag.start()], tag.group(2) t0, m0 = before.count(POINT_LOC), before.count(SEG_MASK) span_triples = triples[t0:t0 + coords.count(POINT_LOC)] n_masks = coords.count(SEG_MASK) element = self._element(tag.group(1), coords, tag.group(3) or None, span_triples, masks[m0:m0 + n_masks], anchors[m0:m0 + n_masks], metadata, mask_threshold) if element is None: continue # left in the text as generated, like vLLM element["text"] = self._extended_tag(tag.group(0), span_triples, anchors[m0:m0 + n_masks]) parts.append(text[on:tag.start()]) on = tag.end() elements.append(element) parts.append(text[on:]) out = [parts[0]] for number, (element, tail) in enumerate(zip(elements, parts[1:]), start=1): element_text = element.pop("text") element["grounding_id"] = number element["text"] = element_text name = TAG_NAMES[element["type"]] out.append(f'<{name} id="{number}">{element.get("label") or ""}</{name}>') out.append(tail) # The first patch choice decides whether the answer grounds anything, so like native its # complement is the first element's confidence if elements and grounding.no_point is not None: elements[0]["confidence"] = 1.0 - grounding.no_point return dict(text="".join(out), multi_modal=elements + camera, type="text") def answer_message(self, token_ids, grounding=None) -> dict: """The assistant message for a generated answer, to continue the chat: its raw text plus the `Molmo3Grounding` it came with, both trimmed if the answer was cut off mid-tag.""" text = self._answer_text(token_ids) if grounding is None: return {"role": "assistant", "content": text} n_points, n_masks = text.count(POINT_LOC), text.count(SEG_MASK) grounding = Molmo3Grounding(point_ids=list(grounding.point_ids)[:n_points], mask_anchors=list(grounding.mask_anchors)[:n_masks], mask_scores=list(grounding.mask_scores)[:n_masks], no_point=grounding.no_point) return {"role": "assistant", "content": text, "grounding": grounding} def _answer_text(self, token_ids) -> str: """Generated ids as text, without the stop tokens. An answer that does not end in one was cut off, and like vLLM a trailing tag that never closed is dropped.""" ids = [int(t) for t in token_ids] stop = {self.tokenizer.eos_token_id, self.tokenizer.pad_token_id, self.tokenizer.convert_tokens_to_ids("<|im_end|>")} truncated = not ids or ids[-1] not in stop while ids and ids[-1] in stop: ids.pop() text = self.tokenizer.decode(ids, skip_special_tokens=False) if not truncated: return text cut = len(text) for kind in ("points3d", "pointsn", "points", "trace", "tracks", "bboxes", "seg", "box3d", "dopoints"): at = text.rfind(f'<{kind} coords="') if at >= 0 and f"</{kind}>" not in text[at:] and '"/>' not in text[at:]: cut = min(cut, at) return text[:cut] def _element(self, kind, coords, label, triples, masks, anchors, metadata, mask_threshold): """One tag as a vLLM `json_objects` element, or None when it decodes to nothing.""" is_video = "timestamps" in metadata[0] if kind == "bboxes": return None # not supported by this port if kind == "box3d" or (kind == "tracks" and CENTER_PATCH in coords): return self._box_element(kind, coords, label, triples, metadata) if kind == "seg": if is_video or not masks: return None decoded, mm_ids = [], [] for i, scores in enumerate(masks): anchor = anchors[i] if i < len(anchors) else 0 decoded.append(self._decode_mask(scores, anchor, metadata, mask_threshold)) mm_ids.append(self._image_of_token(anchor, metadata)) return self._make_element("segmentation", metadata, label=label, masks=[mask_to_rle(m) for m in decoded], mm_ids=None if len(metadata) == 1 else mm_ids) if kind in ("points3d", "pointsn"): targets = triples else: targets = triples[:len(ID_LAST_RE.findall(coords))] points, kept = [], [] for i, triple in enumerate(targets): point = self._point_to_pixels(triple, metadata) if point is not None: points.append(point) kept.append(i) if not points: return None if kind in ("points3d", "pointsn"): block = f"{POINT_PATCH}{POINT_SUBPATCH}{POINT_LOC}" groups = [re.sub(r"^\s*\d+", "", g) for g in coords.split(block)[1:]] if kind == "points3d": dists = [] for g in groups: m = DIST_RE.match(g) dists.append(float(m.group(1)) if m and m.group(1) is not None else -1.0) return self._make_element("points_3d", metadata, label=label, coordinates=[ (p.get("image", 0), p["x"], p["y"], dists[i] if i < len(dists) else -1.0) for p, i in zip(points, kept)]) if kind == "pointsn": normals, flags = [], [] for g in groups: m = NORMAL_RE.match(g) unattainable = m is not None and m.group(1) == "0" flags.append(int(m.group(2)) if m is not None and not unattainable else 1) normals.append(None if m is None or unattainable else tuple(float(m.group(j)) for j in (3, 4, 5))) return self._make_element("points_normal", metadata, label=label, coordinates=[ (p.get("image", 0), p["x"], p["y"], *(normals[i] if i < len(normals) and normals[i] else (None,) * 3)) for p, i in zip(points, kept)], flags=[flags[i] if i < len(flags) else 1 for i in kept]) if kind == "tracks": ex_ids = [int(x) for x in ID_LAST_RE.findall(coords)] return self._make_element("video_tracks", metadata, label=label, coordinates=[ (0, ex_ids[i], p["time"], p["x"], p["y"]) for p, i in zip(points, kept)]) if is_video: return self._make_element("video_points", metadata, label=label, coordinates=[ (0, p["time"], p["x"], p["y"]) for p in points]) trace = kind == "trace" return self._make_element("points", metadata, label=label, coordinates=[ (p["image"], p["x"], p["y"]) for p in points], ordered=trace) @staticmethod def _make_element(kind, metadata, **values) -> dict: element = dict(ELEMENT_FIELDS[kind], **values) if kind in COORDINATE_FIELDS: keys = COORDINATE_FIELDS[kind] named = [] for coord in element["coordinates"]: c = dict(zip(keys, coord)) w, h = metadata[c["mm_ix"]]["size"] if c["mm_ix"] < len(metadata) else (None, None) for key in keys: size = {"x": w, "y": h}.get(key[0]) if key[0] in "xy": c[f"{key}_norm"] = None if size is None or c[key] is None else c[key] / size named.append(c) element["coordinates"] = named element["type"] = kind return element def _box_element(self, kind, coords, label, triples, metadata) -> Optional[dict]: """A `<box3d>` tag, or a `<tracks>` of boxes, as a `bounding_boxes_3d` element. Each box is an optional anchor point, its center point, then `log(depth) W H L` and a 6D rotation; the center is lifted into the camera frame when its image has a `K`.""" is_video = "timestamps" in metadata[0] anchor_block = f"{POINT_PATCH}{POINT_SUBPATCH}{POINT_LOC}" center_block = f"{CENTER_PATCH}{POINT_SUBPATCH}{POINT_LOC}" stride, delim = (2, anchor_block + center_block) if anchor_block in coords else (1, center_block) track_ids = [int(m.group(1)) for m in BOX3D_ID_RE.finditer(coords)] if kind == "tracks" else [] # Group points by emitted index, so a point that cannot be placed does not shift the roles by_box = {} for i, triple in enumerate(triples): point = self._point_to_pixels(triple, metadata) if point is not None: box_ix, role = divmod(i, stride) by_box.setdefault(box_ix, {})["center" if role == stride - 1 else "anchor"] = point boxes, box_K = [], None for box_ix, group in enumerate(coords.split(delim)[1:]): entry = by_box.get(box_ix, {}) nums = [float(v) for v in NUMBER_RE.findall(group)[:10]] if "center" not in entry or len(nums) < 10: continue c, anchor = entry["center"], entry.get("anchor") mm_ix = 0 if is_video else c["image"] meta = metadata[mm_ix] depth = math.exp(nums[0]) center, K = None, meta.get("K") if K is not None: center = [depth * (c["x"] - K[0][2]) / K[0][0], depth * (c["y"] - K[1][2]) / K[1][1], depth] box_K = K a1, a2 = np.array(nums[4:7]), np.array(nums[7:10]) b1 = a1 / np.linalg.norm(a1) b2 = a2 - b1.dot(a2) * b1 b2 = b2 / np.linalg.norm(b2) rotation = np.stack([b1, b2, np.cross(b1, b2)], axis=1).tolist() box = dict(BOX3D_FIELDS, mm_ix=mm_ix, center=center, size=nums[1:4], rotation=rotation, time=c["time"] if is_video else None, object_id=track_ids[box_ix] if box_ix < len(track_ids) else None, reference_point_2d=[anchor["x"], anchor["y"]] if anchor else None, center_2d=[c["x"], c["y"]], depth=depth) w, h = meta["size"] for key in ("center_2d", "reference_point_2d", "bbox_2d"): box[f"{key}_norm"] = None if box[key] is None else [ v / (w if i % 2 == 0 else h) for i, v in enumerate(box[key])] boxes.append(box) if not boxes: return None return self._make_element("bounding_boxes_3d", metadata, coordinates=boxes, label=label, K=box_K) @staticmethod def _camera_fovs(text) -> list: """`(hfov, vfov)` per predicted camera in `text`, in order; None for an invalid one.""" def pair(h, v): try: h, v = float(h), float(v) except ValueError: # a malformed number, e.g. `1.2.3` return None return (h, v) if 0 < h < 180 and 0 < v < 180 else None found = [pair(h, v) for h, v in CAMERA_TAG_RE.findall(text)] if not found and (m := INTR_TAG_RE.search(text)): for record in INTR_RECORD_SEP_RE.split(m.group(1)): toks = record.split() if len(toks) == 3 and toks[0].isdigit(): found.append(pair(toks[1], toks[2])) return found @staticmethod def _camera_matrices(intrinsics, metadata) -> list: """A 3x3 `K` (as lists) or None per image, from a K or (hfov, vfov) for all or per image.""" def shape(value): try: return np.shape(value) except ValueError: # a per-image list mixing None and values return None if intrinsics is None: return [None] * len(metadata) if shape(intrinsics) in ((3, 3), (2,)): intrinsics = [intrinsics] * len(metadata) if len(intrinsics) != len(metadata): raise ValueError(f"got intrinsics for {len(intrinsics)} images, but there are {len(metadata)}") out = [] for value, meta in zip(intrinsics, metadata): if value is None or shape(value) == (3, 3): out.append(None if value is None else np.asarray(value, dtype=np.float64).tolist()) continue if shape(value) != (2,): raise ValueError(f"intrinsics must be a 3x3 K or (hfov, vfov), got {value!r}") (w, h), (hfov, vfov) = meta["size"], value fx = w / 2 / math.tan(math.radians(hfov) / 2) fy = h / 2 / math.tan(math.radians(vfov) / 2) out.append([[fx, 0.0, w / 2], [0.0, fy, h / 2], [0.0, 0.0, 1.0]]) return out @staticmethod def _image_of_token(token, metadata) -> int: offset = 0 for image_ix, meta in enumerate(metadata): offset += len(meta["token_pooling"]) if token < offset: return image_ix return len(metadata) - 1 @staticmethod def _extended_tag(span, triples, anchors) -> str: """A generated tag in the extended format: each point as `<|PATCH_n|><|SUBPATCH_s|><|LOC_l|>`, each mask as `<|PATCH_anchor|><|MASK|>`, and end-of-points as `<|PATCH_32768|>`.""" pieces = [p for p in STANDARD_TOKEN_RE.split(span) if p] grounding = {POINT_PATCH, POINT_SUBPATCH, POINT_LOC, SEG_MASK, CENTER_PATCH} out = list(pieces) name = lambda patch, n: f"<|PATCH_{n}|>" if patch == POINT_PATCH else f"<|CENTER_PATCH_{n}|>" patch_at = sub_at = patch = None on_triple = on_mask = 0 for pos, piece in enumerate(pieces): following = pieces[pos + 1] if pos + 1 < len(pieces) else None if piece in (POINT_PATCH, CENTER_PATCH): if following not in grounding: out[pos] = name(piece, N_PATCH_EXT) patch_at = sub_at = None continue patch_at, patch, sub_at = pos, piece, None elif piece == POINT_SUBPATCH: sub_at = pos elif piece == SEG_MASK: if on_mask < len(anchors): if patch_at is not None: out[patch_at] = name(patch, anchors[on_mask]) out[pos] = "<|MASK|>" on_mask += 1 patch_at = sub_at = None elif piece == POINT_LOC: if on_triple >= len(triples): raise ValueError("more location tokens than recorded points") t, sp, loc = triples[on_triple] on_triple += 1 if patch_at is not None and sub_at is not None: out[patch_at] = name(patch, t) out[sub_at] = f"<|SUBPATCH_{sp}|>" out[pos] = f"<|LOC_{loc}|>" patch_at = sub_at = None return "".join(out) def _mm_metadata(self, images, video) -> list: return media_metadata(images, video, self.max_crops) def _point_to_pixels(self, triple, metadata) -> Optional[dict]: token, subpatch, loc = triple n = PATCH_LOCATION dx, dy = (loc // n + 0.5) / n, (loc % n + 0.5) / n if "timestamps" in metadata[0]: meta = metadata[0] if not (0 <= token < len(meta["token_pooling"])): return None vit_patch = int(meta["token_pooling"][token, subpatch]) frame, (y, x) = divmod(vit_patch, N_PATCHES)[0], divmod(vit_patch % N_PATCHES, GRID) w, h = meta["size"] return dict(time=float(meta["timestamps"][frame]), x=(x + dx) / GRID * w, y=(y + dy) / GRID * h) offset = 0 for image_ix, meta in enumerate(metadata): n_tokens = len(meta["token_pooling"]) if token < offset + n_tokens: break offset += n_tokens else: return None pooling = meta["token_pooling"] if subpatch >= pooling.shape[1]: return None rc = meta["inverse"].get(int(pooling[token - offset, subpatch])) if rc is None: # a low-res token or a padded slot, which cannot be pointed at return None (y, x), (ph, pw), (w, h) = rc, meta["mapping_shape"], meta["size"] return dict(image=image_ix, x=(x + dx) / pw * w, y=(y + dy) / ph * h) def _decode_mask(self, scores, anchor, metadata, threshold) -> Optional[np.ndarray]: """`[P, S, n_locs]` mask probabilities -> a boolean mask the size of its image.""" if "timestamps" in metadata[0]: return None # masks are only decoded for images offset = 0 for image_ix, meta in enumerate(metadata): if anchor < offset + len(meta["token_pooling"]) or image_ix == len(metadata) - 1: break offset += len(meta["token_pooling"]) ph, pw = meta["mapping_shape"] pool, r = IMAGE_POOLING, 4 gh, gw = -(-ph // pool), -(-pw // pool) lo = offset + meta["n_global_tokens"] score = torch.as_tensor(scores[lo:lo + gh * gw, :pool * pool]).float() score = score.reshape(gh, gw, pool, pool, r, r).permute(0, 2, 4, 1, 3, 5) score = score.reshape(gh * pool * r, gw * pool * r)[:ph * r, :pw * r] w, h = meta["size"] score = torch.nn.functional.interpolate(score[None, None], size=(h, w), mode="bilinear", align_corners=False, antialias=False)[0, 0] return (score > threshold).numpy() __all__ = ["Molmo3Processor", "load_video", "mask_to_rle", "rle_to_mask"]
"""Stand-alone Molmo3 processor: chat formatting, image/video preprocessing and grounding decoding.
processor = Molmo3Processor.from_pretrained(path)
messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "Point to the cats."}]}]
inputs = processor.apply_chat_template(messages, images=[image], tokenize=True)
out = model.generate(**inputs, max_new_tokens=512, return_dict_in_generate=True)
answer = processor.decode(out.sequences[0, inputs["input_ids"].shape[1]:], out.grounding[0], images=[image])
`answer` is the same document vLLM's `json_objects` grounding mode returns. For multi-turn chat,
append `processor.answer_message(ids, out.grounding[0])`, the raw answer with its grounding;
`encode_document` turns a document back into text and grounding.
Images are tiled into up to `max_crops` overlapping 378px crops plus a low-res global crop; videos
are sampled at up to `max_fps` (at most `max_frames` frames) and each frame resized to 378px.
"""
import json
import math
import os
import re
from typing import List, Optional, Union
import numpy as np
import torch
import torchvision.transforms
from PIL import Image
from transformers import AutoTokenizer, BatchFeature
from transformers.utils import cached_file
from .configuration_molmo3 import Molmo3Config # noqa: F401, remote code copies direct imports only
from .modeling_molmo3 import Molmo3Grounding
IMAGE_PATCH_TOKEN = "<im_patch>"
IMAGE_LOW_RES_TOKEN = "<im_low>"
IM_START_TOKEN = "<im_start>"
LOW_RES_IMAGE_START_TOKEN = "<low_res_im_start>"
IM_END_TOKEN = "<im_end>"
IM_COL_TOKEN = "<im_col>"
FRAME_START_TOKEN = "<frame_start>"
FRAME_END_TOKEN = "<frame_end>"
IMAGE_PROMPT = "<|image|>"
VIDEO_PROMPT = "<|video|>"
POINT_PATCH, POINT_SUBPATCH, POINT_LOC = "<|POINT_PATCH|>", "<|POINT_SUBPATCH|>", "<|POINT_LOC|>"
SEG_MASK, CENTER_PATCH = "<|SEG_MASK|>", "<|CENTER_PATCH|>"
PATCH_LOCATION = 4 # each ViT patch is split into a 4x4 grid of locations
N_PATCH_EXT = 32768 # `<|PATCH_32768|>` is the extended format's end-of-points marker
N_SUBPATCH_EXT = 9 # sub-patches per pooled token, up to video's 3x3
# The tags `extract_grounding` decodes, each with its own label / closing-tag rules
TAG_RES = [re.compile(x, re.DOTALL) for x in (
r'<(tracks|bboxes|box3d) coords="([^"]+)">(.*?)</(?:tracks|bboxes|seg|point|box3d)>',
r'<(points|trace) coords="([^"]+)"(?:/>|>(?:([^<]*)</(?:points?|trace)>)?)',
r'<(seg) coords="([^"]+)"(?:/>|>(?:([^<]*)</seg>)?)',
r'<(points3d) coords="([^"]+)"(?:/>|>(?:([^<]*)</points3d>)?)',
r'<(pointsn) coords="([^"]+)"(?:/>|>(?:([^<]*)</pointsn>)?)',
)]
ID_LAST_RE = re.compile(re.escape(POINT_LOC) + r" ?([0-9]+)")
DIST_RE = re.compile(r"^\s*(?:1\s+(\d+(?:\.\d+)?)|0(?![\d.]))")
NORMAL_RE = re.compile(r"^\s*(?:(0)(?!\S)|([12])\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?))")
STANDARD_TOKEN_RE = re.compile(r"(<\|(?:POINT_PATCH|POINT_SUBPATCH|POINT_LOC|SEG_MASK|CENTER_PATCH)\|>)")
EXTENDED_TOKEN_RE = re.compile(r"<\|(CENTER_PATCH|PATCH|SUBPATCH|LOC|MASK)(?:_(\d+))?\|>")
# Only the extended forms; the standard `<|CENTER_PATCH|>` also matches the pattern above
EXTENDED_ONLY_RE = re.compile(r"<\|(?:(?:CENTER_PATCH|PATCH|SUBPATCH|LOC)_\d+|MASK)\|>")
# A 3D box track's id sits at the box boundary, before the next `<|POINT_PATCH|>`
BOX3D_ID_RE = re.compile(r"(?<![\d.])([0-9]+) ?(?=<\|POINT_PATCH\|>)")
NUMBER_RE = re.compile(r"-?\d+(?:\.\d+)?")
# A predicted camera, `<camera hfov=.. vfov=../>` per image, or the older `<intr vals="1 h v">`
CAMERA_TAG_RE = re.compile(r"<camera\s+hfov=(-?[\d.]+)\s+vfov=(-?[\d.]+)\s*/?>")
INTR_TAG_RE = re.compile(r'<intr .*?vals="([^"]*)"/?>')
INTR_RECORD_SEP_RE = re.compile(r"[;\t:,]")
MARKER_RE = re.compile(r'<(points|points3d|pointsn|tracks|seg|box3d|dopoints) id="(\d+)">(.*?)</\1>', re.DOTALL)
# Fields and defaults of each element type, in order; training-only fields of the native
# `olmo.message` dataclasses are left out
ELEMENT_FIELDS = {
"points": dict(coordinates=None, label=None, confidence=None, ordered=False),
"video_points": dict(coordinates=None, label=None, confidence=None),
"points_3d": dict(coordinates=None, label=None, confidence=None),
"points_normal": dict(coordinates=None, label=None, confidence=None, flags=None),
"video_tracks": dict(coordinates=None, label=None, confidence=None),
"segmentation": dict(masks=None, label=None, mm_ids=None, confidence=None),
"bounding_boxes_3d": dict(coordinates=None, label=None, K=None, confidence=None),
}
# One `Box3D` (a `bounding_boxes_3d` coordinate), then the `_norm` companions vLLM adds
BOX3D_FIELDS = dict(mm_ix=0, center=None, size=None, rotation=None, time=None, object_id=None, bbox_2d=None,
reference_point_2d=None, center_2d=None, depth=None, mask_2d=None)
COORDINATE_FIELDS = {
"points": ("mm_ix", "x", "y"),
"video_points": ("mm_ix", "time", "x", "y"),
"points_3d": ("mm_ix", "x", "y", "depth"),
"points_normal": ("mm_ix", "x", "y", "nx", "ny", "nz"),
"video_tracks": ("mm_ix", "object_id", "time", "x", "y"),
}
TAG_NAMES = {"points": "points", "points_3d": "points3d", "points_normal": "pointsn",
"video_points": "points", "video_tracks": "tracks", "segmentation": "seg",
"bounding_boxes_3d": "box3d"}
# Styles the checkpoint was trained to see without their `style: ` prefix (native's
# `demo_or_style_v3` with `surface_normal_demo_style`)
NO_PREFIX_STYLES = frozenset([
"3d_pointing", "camera_intrinsics", "camera_pose", "correction_qa", "cosyn_point", "long_caption",