# Molmo3 for vLLM A [vLLM](https://github.com/vllm-project/vllm) plugin that serves Molmo3 through [vllm-omni](https://github.com/vllm-project/vllm-omni). It integrates Molmo3's pointing and segmentation heads and can directly return points as image coordinates and masks as RLE encoded JSON. It serves the model using the huggingface checkpoint and uses the same pre-processing and document format. ## Install ```bash git clone git@github.com:allenai/molmo3-vllm.git && cd molmo3-vllm pip install -e . # vllm==0.26.0, vllm-omni==0.26.0 pip install torchcodec # for video ``` Installing the package registers the model with vLLM through its plugin entry points. This repo is built to be used with the Molmo3 huggingface checkpoints and includes its own copy of the huggingface code so `--trust-remote-code` is not required. ## Usage ### Serve ```bash vllm-omni serve allenai/Molmo3-4B --omni --served-model-name molmo3 \ --dtype bfloat16 --max-model-len 12800 --max-num-batched-tokens 12800 \ --limit-mm-per-prompt '{"image": 5, "video": 1}' ``` The server is `vllm-omni serve`, and `--omni` is required: without it the command falls back to plain vLLM, which cannot carry the grounding outputs. Add `--allowed-local-media-path ` to send videos or images as `file://` URLs. ### Grounding output Molmo3's points and masks come from its grounding heads, alongside the text tokens. The `grounding` entry of `vllm_xargs` chooses how a response carries them: | `grounding` | `message.content` | Points and masks | |---|---|---| | `json_objects` | A JSON document with the text and the grounding elements | In the document | | `grounding_tokens` | The model's text, with groundings as location tokens | `message.grounding`, a list of elements | | not set | The model's text, with groundings as location tokens | Not returned | `json_objects` is the easiest to use: ```python import json from openai import OpenAI client = OpenAI(base_url="http://localhost:8000/v1", api_key="none") image_url = "https://raw.githubusercontent.com/scikit-image/scikit-image/v0.19.3/skimage/data/coffee.png" messages = [{"role": "user", "content": [ {"type": "image_url", "image_url": {"url": image_url}}, {"type": "text", "text": "Point to the spoon."}]}] response = client.chat.completions.create( model="molmo3", messages=messages, max_tokens=256, temperature=0, extra_body={"vllm_xargs": {"grounding": "json_objects"}}, ) document = json.loads(response.choices[0].message.content) print(document["text"]) # spoon. print(document["multi_modal"][0]["coordinates"][0]) # {'mm_ix': 0, 'x': 366.8, 'y': 281.5, ...} ``` The document follows the HF format documented [here](https://huggingface.co/allenai/Molmo3-8B#grounding-output): `text` marks each grounding with a tag like ``, and `multi_modal` holds the elements, with points in pixels and normalized coordinates and masks as COCO RLE. The other two modes return the model's "raw" text, in which each point is written as location tokens that name the image patch, the sub-patch and the location within it: ``` spoon. ``` `grounding_tokens` also returns the decoded elements as `response.choices[0].message.grounding`. ### Streaming Streaming works in every mode, but the points and masks are only ready once a grounding's tag closes: - **Not set** and **`grounding_tokens`**: the text streams as usual, and with `grounding_tokens` the elements arrive in the final chunk as `delta.grounding`. - **`json_objects`**: the deltas concatenate into the document. The text streams first, holding each grounding until its tag closes, and the elements arrive at the end. ### Input points The server accepts grounding elements in a prompt as a JSON object with a `multi_modal` list, sent as its own text part. Coordinates may be pixels (`x`, `y`) or normalized (`x_norm`, `y_norm`), and `mm_ix` is the image index: ```python points = {"type": "points", "coordinates": [{"mm_ix": 0, "x_norm": 0.5, "y_norm": 0.5}, {"mm_ix": 0, "x_norm": 0.15, "y_norm": 0.85}]} content = [{"type": "image_url", "image_url": {"url": image_url}}, {"type": "text", "text": "What is the depth of these points? "}, {"type": "text", "text": json.dumps({"multi_modal": [points]})}] ``` The server converts the object into the model's grounding tokens with the HF processor, as described [here](https://huggingface.co/allenai/Molmo3-8B#grounding-input). ### Multi-turn Send an answer back as the assistant turn exactly as it came, in any mode: ```python messages.append({"role": "assistant", "content": response.choices[0].message.content}) messages.append({"role": "user", "content": "Now point to the cup."}) ``` ### Video One video per prompt, as a `video_url` part (an `http(s)://`, `data:` or allowed `file://` URL). A request can include images or a video, but not both. Frames are sampled following Molmo3's default (up to 128 frames, at most 2 fps), with each frame's time added to the prompt. ```python content = [{"type": "video_url", "video_url": {"url": "file:///data/videos/clip.mp4"}}, {"type": "text", "text": "Track the dog."}] ``` ## Tests ```bash pip install -e ".[test]" pytest tests ``` The tests need no GPU. ## Implementation The plugin registers Molmo3 as a single-stage vllm-omni pipeline. vllm-omni is used rather than plain vLLM because it lets a model keep state per request across decode steps and return tensors alongside the tokens, which the grounding head needs. Supporting the pointing/segmentation heads in vLLM required a significant amount of hacking so brace yourself if you look under the hood. Here is a high-level overview of the approach: 1. **Preprocessing** Images and videos are preprocessed with the HF preprocessor's code, and vLLM inserts their image tokens into the prompt as normal. Grounding elements sent as JSON in the prompt are converted by the HF processor (`render_document`) into text and location ids. The location ids are then encoded as special tokens (e.g., `<|PATCH_578|>` encodes patch location 578) so they can be retrieved later. 2. **Image Embedding** `embed_multimodal` runs the vision encoder and connector, in Molmo3 this builds the image embeddings, image metadata (like the image size), and some additional image features that are needed for pointing/segmentation. The API only supports returning the image embedding tensor; we work around this by packing the extra data with the image embeddings into a single large tensor and returning that as an "extended" image embedding tensor. Packing this way makes `embed_multimodal` continue to work with vLLM's caching mechanisms for embedding images. 3. **Embedding** `embed_input_ids` uses the outputs of `embed_multimodal` and the text token ids to build the full input embedding sequence. The embedding happens as usual, but the extra data packed into the image tensor needs to be unpacked and preserved as well. The stage also detects the location ids tokens, retrieve the original location ids, and pass them to the next stage as well. vLLM has no convenient channel to return this extra data (the same packing trick no longer works since the output of this function must match the model's embeddings size). We side-channel the data through a field in the model, the current usage of model in vLLM allows this since `embed_input_ids` and `forward` are called in sequence. 4. **Prefilling** `forward` does forward steps for both pre-filling and decoding. For pre-filling, we collect the side-channel data and compute some additional pieces (like the top-level image location keys that use the LLM's hidden state), all this auxiliary data is then stored per-request using vllm-omni's state tracking mechanism. By default the data is all offloaded to the CPU, which is cheap since it will only be read sparsely, however we also support storing the large tensors in the KV cache (`MOLMO3_GROUNDING_STORE=kv`). Before running the transformer, this stage will also use the location ids from the previous step to update the input embeddings of the grounding tokens (this cannot be done in `embed_input_ids` since `embed_input_ids` does have access to position ids or request state information). 5. **Decoding** `forward` decoding steps mostly proceeds as normal, with the pointing/segmentation running when the input token is a pointing/mask special token using the cached image data. Decoding returns both the hidden state and the outputs of those heads through vllm-omni's `OmniOutput.multimodal_outputs` field. 6. **Sampling** `compute_logits` builds the logits. We add some additional masking so the grounding tokens are correctly constrained and cannot be generated out-of-order. This requires side-channeling a little bit of the per-request state from `forward` to this function, we resort to doing this through another model field holding one entry per batch row. 7. **Post-processing** We wrap vllm-omni's OpenAI chat handler to generate output. Location ids returned by the pointing head are converted into special tokens so they can be returned as text or token ids, which is convenient for handling multi-turn inputs. In the `json_objects` setting the handler decodes the locations into point coordinates, computes RLE encodings of the masks, and returns them as a document. When streaming, a grounded span is held back until its tag closes. ### Workarounds in vllm and vllm-omni When the plugin registers it will patch running vLLM processes with: - **Image split across prefill chunks.** vLLM can split an image across two prefill chunks, which changes the image's hidden states under its bidirectional attention and breaks our state-tracking mechanism ([vllm#52306](https://github.com/vllm-project/vllm/issues/52306); closed upstream, but 0.26.0 still has the bug). - **vllm-omni single-stage fix.** Patches vllm-omni to allow keeping the payload of any single-stage model ([vllm-omni#6218](https://github.com/vllm-project/vllm-omni/issues/6218)). - **KV cache size fix.** Fixes KV cache sizing when vllm-omni misreads the model's memory use ([vllm-omni#6243](https://github.com/vllm-project/vllm-omni/issues/6243); closed upstream, but 0.26.0 still has the bug). - **Model runner mismatch.** vllm-omni builds the V1 model runner while vLLM's scheduler assumes V2, which crashes the engine when a preempted request resumes. We align the config with the runner actually built. - **Tokenizer.** We add extended tokens to the tokenizer, which encode the chosen location ids in text. - **Chat requests.** `max_completion_tokens` (what the OpenAI client sends) is used as `max_tokens`, since vllm-omni otherwise ignores it and stops at 16 tokens. - **Hardcoded vLLM settings.** We force some vLLM settings that are required: `PIECEWISE` cuda graph captures and prefix caching off. We also register a custom video loader that matches what the model expects. ## Limitations - vLLM's default `FULL_AND_PIECEWISE` and `FULL` compilation modes are not supported due to the difficulty of making them work with the grounding head. `PIECEWISE` is forced instead. - Prefix caching, pipeline parallelism, and speculative decoding are also not supported for the same reason. - Requests that ask for `logprobs` fail (vllm-omni's chat path does not return them for this model). - The plugin patches vLLM and vllm-omni internals, so versions other than 0.26.0 might not work. - Beam search is not supported.