> Agents: page URLs you remember may be outdated. Fetch https://huggingface.co/docs/transformers/main/llms.txt to find the right page first, and add `.md` to a page's path (before any `#`) to get Markdown instead of HTML. To search these docs, use the Hugging Face MCP server: https://huggingface.co/mcp

# Molmo3

[Molmo3](https://allenai.org/papers/molmo3) is a family of open vision-language models from the Allen Institute for AI
(Ai2), focused on spatial and 3D understanding and grounding. It takes single images, multiple images and videos. The
architecture is the one of [Molmo2](./molmo2): a vision transformer initialized from SigLIP 2, an adapter that pools
patch features into image tokens, and a text decoder initialized from Qwen3.

Molmo3 adds a grounding head. The model does not write coordinates as text. It generates grounding tokens, as
introduced by [MolmoPoint](https://allenai.org/papers/molmopoint). After `<|POINT_PATCH|>`, the head selects an image
token or ends the list of points. After `<|POINT_SUBPATCH|>`, it selects a ViT patch inside that image token. After
`<|POINT_LOC|>`, it selects a location inside that patch. The features of each selection are added to the embedding of
the next token. After `<|SEG_MASK|>`, the head predicts a segmentation mask around the selected image token.

With this head, Molmo3 can point to objects in images and videos, track objects in videos, segment objects in images,
estimate the depth or the surface normal at a point, and predict 3D boxes.

You can find all the original Molmo3 checkpoints under the [Molmo3](https://huggingface.co/collections/allenai/molmo3)
collection.

## Usage example

### Image-text-to-text generation

The example below demonstrates how to generate text based on an image with [Pipeline](/docs/transformers/main/en/main_classes/pipelines#transformers.Pipeline) or the [AutoModel](/docs/transformers/main/en/model_doc/auto#transformers.AutoModel) class.
The other examples on this page reuse the `processor` and `model` of the [AutoModel](/docs/transformers/main/en/model_doc/auto#transformers.AutoModel) tab.

> [!WARNING]
> With images or videos, [generate()](/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationMixin.generate) supports greedy decoding and sampling, with one sequence per
> prompt and `use_cache=True`. Beam search, `num_return_sequences > 1`, assisted decoding and `use_cache=False` raise
> an error because the grounding head keeps a state for each sequence.

**Option: Pipeline**

```python
import torch

from transformers import pipeline

pipeline = pipeline(task="image-text-to-text", model="allenai/Molmo3-4B", dtype=torch.bfloat16, device_map="auto")

messages = [
    {
        "role": "user",
        "content": [
            {"type": "image", "url": "https://huggingface.co/datasets/hf-internal-testing/test-images/resolve/main/skimage/astronaut.png"},
            {"type": "text", "text": "Describe this image."},
        ],
    }
]
pipeline(text=messages, max_new_tokens=128, return_full_text=False)
```

**Option: AutoModel**

```python
import torch

from transformers import AutoModelForImageTextToText, AutoProcessor

processor = AutoProcessor.from_pretrained("allenai/Molmo3-4B")
model = AutoModelForImageTextToText.from_pretrained("allenai/Molmo3-4B", dtype=torch.bfloat16, device_map="auto")

messages = [
    {
        "role": "user",
        "content": [
            {"type": "image", "url": "https://huggingface.co/datasets/hf-internal-testing/test-images/resolve/main/skimage/astronaut.png"},
            {"type": "text", "text": "Describe this image."},
        ],
    }
]
inputs = processor.apply_chat_template(
    messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt"
).to(model.device)

generated_ids = model.generate(**inputs, max_new_tokens=128, do_sample=False)
print(processor.decode(generated_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True))
```

### Pointing and segmentation

Pass `return_dict_in_generate=True` to [generate()](/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationMixin.generate) to also get `grounding`, one
`Molmo3GroundingOutput` per sequence with the indices selected by the grounding head.
[post_process_grounding()](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3Processor.post_process_grounding) converts them to pixel coordinates and masks.

```python
from transformers.image_utils import load_image

image = load_image("https://huggingface.co/datasets/hf-internal-testing/test-images/resolve/main/skimage/coffee.png")
messages = [
    {
        "role": "user",
        "content": [{"type": "image", "image": image}, {"type": "text", "text": "Point to the spoon."}],
    }
]
inputs = processor.apply_chat_template(
    messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt"
).to(model.device)

output = model.generate(**inputs, max_new_tokens=64, do_sample=False, return_dict_in_generate=True)
generated_ids = output.sequences[:, inputs["input_ids"].shape[1] :]
print(processor.decode(generated_ids[0], skip_special_tokens=True))
# <points coords="1">spoon</points>

results = processor.post_process_grounding(
    generated_ids, output.grounding, inputs, target_sizes=[[(image.height, image.width)]]
)
element = results[0][0]
print(element["type"], element["label"], element["points"])
# points spoon tensor([[366.8, 281.5]])
```

The prompt decides the type of the output. The prompts below are from the
[model card](https://huggingface.co/allenai/Molmo3-4B).

| Prompt | Output `type` |
|---|---|
| "Point to the cat's eyes." | `points` |
| "Segment the cat." | `segmentation` |
| "Point to the spoon and tell me how far each is from the camera." | `points_3d` |
| "Point to the table and give the surface normal at each." | `points_normal` |
| "Find the 3D boxes for cup." | `camera` and `boxes_3d` |
| "Give the horizontal and vertical field of view of this image, in degrees." | `camera` |
| "Track the penguin on the left." on a video | `video_tracks` |

[post_process_grounding()](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3Processor.post_process_grounding) returns a list of dicts for each sequence, in the order of the tags in the
generated text. Each dict has a `type`, a `label` (the text inside the tag, or `None`) and the fields below.

| `type` | Tag | Fields |
|---|---|---|
| `points` | `<points>` on images | `points` `(num_points, 2)`, the `(x, y)` of each point, and `image_index` `(num_points,)`, the image of each point |
| `trace` | `<trace>` on images | `points` and `image_index` |
| `video_points` | `<points>` or `<trace>` on a video | `points` and `timestamps` `(num_points,)`, in seconds |
| `video_tracks` | `<tracks>` on a video | `points`, `timestamps` and `object_ids` `(num_points,)` |
| `points_3d` | `<points3d>` | `points`, `image_index` and `depth` `(num_points,)` in meters, NaN where the answer gives no depth |
| `points_normal` | `<pointsn>` | `points`, `image_index`, `normals` `(num_points, 3)` and `flags` `(num_points,)`, 1 where the normal is missing or could not be estimated |
| `segmentation` | `<seg>` on images | `masks`, a list with one boolean tensor per mask, and `image_index` `(num_masks,)` |
| `boxes_3d`, `video_boxes_3d` | `<box3d>`, or `<tracks>` of boxes on a video | see [3D boxes](#3d-boxes) |
| `camera` | `<camera>` | `fovs` `(num_cameras, 2)`, the horizontal and vertical field of view in degrees, and `image_index` |

`target_sizes` gives the `(height, width)` of each image and video of each prompt, in the order they appear in the
prompt. Coordinates are then in pixels, and masks have that size. Without `target_sizes`, coordinates are fractions of
the image size, in `[0, 1]`.

> [!WARNING]
> `post_process_grounding` does not decode 2D boxes (`<bboxes>` tags), and decodes segmentation masks for images only.
> If `max_new_tokens` cuts an answer inside a grounding tag, `post_process_grounding` and `parse_response` drop that
> tag.

> [!TIP]
> For batched generation, pass a list of conversations and `processor_kwargs={"padding": True}` to
> [apply_chat_template()](/docs/transformers/main/en/main_classes/processors#transformers.ProcessorMixin.apply_chat_template), and give `target_sizes` one list per conversation.

### Multi-turn conversations

To continue a conversation, convert each answer to a message with [parse_response()](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3Processor.parse_response) and pass the
`grounding` of that answer. The message keeps the selected indices of its points and masks, and
[apply_chat_template()](/docs/transformers/main/en/main_classes/processors#transformers.ProcessorMixin.apply_chat_template) passes them back to the model. The example below continues the pointing
example.

```python
answer = processor.parse_response(generated_ids[0], prefix=inputs["input_ids"][0], grounding=output.grounding[0])
print(answer["grounding"])
# {'point_indices': [[578, 0, 1]], 'mask_indices': []}

messages += [answer, {"role": "user", "content": "Now point to the cup."}]
inputs = processor.apply_chat_template(
    messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt"
).to(model.device)
output = model.generate(**inputs, max_new_tokens=64, do_sample=False, return_dict_in_generate=True)
```

The `grounding` of a message is made of plain lists, so a conversation can be saved as JSON and continued later. The
indices refer to the image tokens of the prompt, so keep the same images, in the same order, with the same processor
settings.

If you format the chat with `tokenize=False` and call the processor separately, pass the `grounding` of each answer to
the processor, one list per text: `processor(text=[prompt], images=[image], grounding=[[answer["grounding"]]])`.

### Points in the prompt

A user message can contain points in a `points` block. Give each point in pixels (`x`, `y`) or as fractions of the
image size (`x_norm`, `y_norm`), with `mm_ix`, the index of its image. On a video, give `time` in seconds instead of
`mm_ix`. The chat template writes the points as grounding tokens, and the processor computes the image token, ViT patch
and location of each point.

```python
image = load_image("https://huggingface.co/datasets/hf-internal-testing/test-images/resolve/main/skimage/astronaut.png")
points = {
    "type": "points",
    "coordinates": [
        {"mm_ix": 0, "x_norm": 0.4, "y_norm": 0.25},
        {"mm_ix": 0, "x_norm": 0.9, "y_norm": 0.2},
        {"mm_ix": 0, "x_norm": 0.4, "y_norm": 0.9},
    ],
}
messages = [
    {
        "role": "user",
        "content": [
            {"type": "image", "image": image},
            {"type": "text", "text": "How far are these points from the camera? "},
            points,
        ],
    }
]
inputs = processor.apply_chat_template(
    messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt"
).to(model.device)

output = model.generate(**inputs, max_new_tokens=64, do_sample=False, return_dict_in_generate=True)
generated_ids = output.sequences[:, inputs["input_ids"].shape[1] :]
element = processor.post_process_grounding(
    generated_ids, output.grounding, inputs, target_sizes=[[(image.height, image.width)]]
)[0][0]
print(element["type"], element["points"])
# points_3d tensor([[460.5, 101.6], [204.5, 129.4], [204.5, 460.5]])
```

`element["depth"]` is the depth of each point in meters. The processor sorts the points in image token order, row by
row, so the prompt lists the point at `(0.9, 0.2)` first and the answer uses the same order.

### Video pointing

Add a `video` block to the chat and pass `return_metadata=True` to the processor. The processor then returns the
`video_metadata` that [post_process_grounding()](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3Processor.post_process_grounding) needs to find the timestamp of each frame. Pop
`video_metadata` from the inputs before calling [generate()](/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationMixin.generate).

```python
messages = [
    {
        "role": "user",
        "content": [
            {"type": "video", "url": "https://storage.googleapis.com/oe-training-public/demo_videos/many_penguins.mp4"},
            {"type": "text", "text": "Point to the penguins."},
        ],
    }
]
inputs = processor.apply_chat_template(
    messages,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    processor_kwargs={"return_metadata": True},
)
video_metadata = inputs.pop("video_metadata")
inputs = inputs.to(model.device)

output = model.generate(**inputs, max_new_tokens=512, do_sample=False, return_dict_in_generate=True)
generated_ids = output.sequences[:, inputs["input_ids"].shape[1] :]
results = processor.post_process_grounding(generated_ids, output.grounding, inputs, video_metadata=video_metadata)
for element in results[0]:
    print(element["type"], element["timestamps"], element["points"])
```

Without `target_sizes`, the points are fractions of the frame width and height.

### 3D boxes

Ask for 3D boxes with "Find the 3D boxes for {label}." on an image. A `boxes_3d` element has one row per box:

- `points` `(num_boxes, 2)`: the pixel that the box center projects to.
- `depth` `(num_boxes,)`: the depth of the box center, in meters.
- `sizes` `(num_boxes, 3)`: the width, height and length of the box, in meters.
- `rotations` `(num_boxes, 3, 3)`: the rotation from the object frame to the camera frame.
- `reference_points` `(num_boxes, 2)`: the point on the object that the model gives before the box, NaN when there is
  none.
- `image_index` `(num_boxes,)`: the image of each box.

When the answer also has a `<camera hfov=... vfov=...>` tag, the results include a `camera` element, and `boxes_3d`
has `centers` `(num_boxes, 3)`: the box centers in meters, in the camera frame (X right, Y down, Z forward).

Molmo3 is not trained to track 3D boxes in a video. The prompt "Build 3D boxes for {label} and track them." returns a
`video_boxes_3d` element, with `timestamps` and `object_ids` instead of `image_index`, and without `centers`. Its
`points` change from frame to frame, but `depth`, `sizes` and `rotations` are the same in every frame of an object. For
a 3D box in every frame, pass each frame as an image.

## Molmo3Config[[transformers.Molmo3Config]]

#### transformers.Molmo3Config[[transformers.Molmo3Config]]

```python
transformers.Molmo3Config(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, adapter_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, image_start_token_id: int = 151936, low_res_image_start_token_id: int = 151940, image_end_token_id: int = 151937, image_patch_id: int = 151938, frame_start_token_id: int = 151943, frame_end_token_id: int = 151944, initializer_range: float = 0.02, tie_word_embeddings: bool = False, image_low_res_id: int = 151942, point_patch_id: int = 151950, point_subpatch_id: int = 151951, point_loc_id: int = 151952, seg_mask_id: int = 151953, center_patch_id: int = 151954, point_query_dims: list[int] | None = None, subpatch_location_size: int = 4, subpatch_hidden_size: int = 512, subpatch_conv_kernel: int = 3, mask_diffusion_steps: int = 2, presence_threshold: float = 0.5, rope_parameters: dict[str, dict] | None = None, patch_position_embedding_size: int = 512)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/configuration_molmo3.py#L146)

**Parameters:**

vision_config (`Molmo3VisionConfig`, *optional*) : Configuration for the vision transformer backbone.

adapter_config (`Molmo3AdapterConfig`, *optional*) : Configuration for the vision-to-language adapter.

text_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *optional*) : The config object or dictionary of the text backbone.

image_start_token_id (`int`, *optional*, defaults to 151936) : Token ID marking the start of the high-resolution crops of an image.

low_res_image_start_token_id (`int`, *optional*, defaults to 151940) : Token ID marking the start of the low-resolution view of an image.

image_end_token_id (`int`, *optional*, defaults to 151937) : Token ID marking the end of an image region.

image_patch_id (`int`, *optional*, defaults to 151938) : Token ID of the high-resolution image and video tokens.

frame_start_token_id (`int`, *optional*, defaults to 151943) : Token ID marking the start of a video.

frame_end_token_id (`int`, *optional*, defaults to 151944) : Token ID marking the end of a video.

initializer_range (`float`, *optional*, defaults to `0.02`) : The standard deviation of the truncated_normal_initializer for initializing all weight matrices.

tie_word_embeddings (`bool`, *optional*, defaults to `False`) : Whether the model's input and output word embeddings should be tied.

image_low_res_id (`int`, *optional*, defaults to 151942) : Token ID of the low-resolution image tokens.

point_patch_id (`int`, *optional*, defaults to 151950) : Token ID after which the grounding head selects a pooled patch to point at (or ends the list of points).

point_subpatch_id (`int`, *optional*, defaults to 151951) : Token ID after which the grounding head selects a subpatch of the selected pooled patch.

point_loc_id (`int`, *optional*, defaults to 151952) : Token ID after which the grounding head selects a location within the selected ViT patch.

seg_mask_id (`int`, *optional*, defaults to 151953) : Token ID after which the grounding head predicts a segmentation mask around the selected pooled patch.

center_patch_id (`int`, *optional*, defaults to 151954) : Token ID like `point_patch_id`, for a point that can never end a list of points.

point_query_dims (`list[int]`, *optional*, defaults to `[512, 512, 32]`) : Dimensions of the grounding head's queries and keys for the pooled patches, the subpatches and the locations.

subpatch_location_size (`int`, *optional*, defaults to 4) : Side length of the square grid of grounding locations within each subpatch (one ViT patch).

subpatch_hidden_size (`int`, *optional*, defaults to 512) : Hidden size of the ViT patch features of the grounding head.

subpatch_conv_kernel (`int`, *optional*, defaults to 3) : Kernel size of the convolution mixing each ViT patch with its neighbours.

mask_diffusion_steps (`int`, *optional*, defaults to 2) : Number of diffusion steps that smooth the segmentation mask logits.

presence_threshold (`float`, *optional*, defaults to 0.5) : Probability mass that the grounding head must assign to the pooled patches, rather than to ending the list, for a new list of points or masks to select a patch. Below it, the list ends right away. A list that has already selected a patch ends by plain argmax.

rope_parameters (`dict`, *optional*) : RoPE parameters keyed by `"grounding"` for the pooled patch positions of the grounding head and `"patch_position"` for the (time, row, column) coordinates of ViT patches. Defaults to `{"rope_type": "default", "rope_theta": 50000.0}` and `{"rope_type": "default", "rope_theta": 10000.0}`, respectively. Text attention uses `text_config.rope_parameters`.

patch_position_embedding_size (`int`, *optional*, defaults to 512) : Size of the sinusoidal embedding of each of the (time, row, column) coordinates of a ViT patch.

This is the configuration class to store the configuration of a Molmo3Model. It is used to instantiate a Molmo3
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuration to that of the [allenai/Molmo3-4B](https://huggingface.co/allenai/Molmo3-4B)

Configuration objects inherit from [PreTrainedConfig](/docs/transformers/main/en/main_classes/configuration#transformers.PreTrainedConfig) and can be used to control the model outputs. Read the
documentation from [PreTrainedConfig](/docs/transformers/main/en/main_classes/configuration#transformers.PreTrainedConfig) for more information.

## Molmo3VisionConfig[[transformers.Molmo3VisionConfig]]

#### transformers.Molmo3VisionConfig[[transformers.Molmo3VisionConfig]]

```python
transformers.Molmo3VisionConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, hidden_size: int = 1152, intermediate_size: int = 4304, num_hidden_layers: int = 25, num_attention_heads: int = 16, num_key_value_heads: int = 16, head_dim: int = 72, hidden_act: str = 'gelu_pytorch_tanh', layer_norm_eps: float = 1e-06, image_size: list[int] | None = None, patch_size: int = 14, num_position_embeddings: int | None = None, num_channels: int = 3, attention_dropout: float = 0.0, attention_bias: bool = True, initializer_range: float = 0.02)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/configuration_molmo3.py#L30)

**Parameters:**

hidden_size (`int`, *optional*, defaults to `1152`) : Dimension of the hidden representations.

intermediate_size (`int`, *optional*, defaults to `4304`) : Dimension of the MLP representations.

num_hidden_layers (`int`, *optional*, defaults to `25`) : Number of hidden layers in the Transformer decoder.

num_attention_heads (`int`, *optional*, defaults to `16`) : Number of attention heads for each attention layer in the Transformer decoder.

num_key_value_heads (`int`, *optional*, defaults to `16`) : This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out [this paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `num_attention_heads`.

head_dim (`int`, *optional*, defaults to `72`) : The attention head dimension. If None, it will default to hidden_size // num_attention_heads

hidden_act (`str`, *optional*, defaults to `gelu_pytorch_tanh`) : The non-linear activation function (function or string) in the decoder. For example, `"gelu"`, `"relu"`, `"silu"`, etc.

layer_norm_eps (`float`, *optional*, defaults to `1e-06`) : The epsilon used by the layer normalization layers.

image_size (`list[int]`, *optional*) : Input image size as (height, width), `[378, 378]` when not provided.

patch_size (`int`, *optional*, defaults to `14`) : The size (resolution) of each patch.

num_position_embeddings (`int`, *optional*) : Number of positional embeddings, one per image patch. Derived from `image_size` and `patch_size` when not provided.

num_channels (`int`, *optional*, defaults to `3`) : The number of input channels.

attention_dropout (`float`, *optional*, defaults to `0.0`) : The dropout ratio for the attention probabilities.

attention_bias (`bool`, *optional*, defaults to `True`) : Whether to use a bias in the query, key, value and output projection layers during self-attention.

initializer_range (`float`, *optional*, defaults to `0.02`) : The standard deviation of the truncated_normal_initializer for initializing all weight matrices.

This is the configuration class to store the configuration of a Molmo3Model. It is used to instantiate a Molmo3
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuration to that of the [allenai/Molmo3-4B](https://huggingface.co/allenai/Molmo3-4B)

Configuration objects inherit from [PreTrainedConfig](/docs/transformers/main/en/main_classes/configuration#transformers.PreTrainedConfig) and can be used to control the model outputs. Read the
documentation from [PreTrainedConfig](/docs/transformers/main/en/main_classes/configuration#transformers.PreTrainedConfig) for more information.

## Molmo3AdapterConfig[[transformers.Molmo3AdapterConfig]]

#### transformers.Molmo3AdapterConfig[[transformers.Molmo3AdapterConfig]]

```python
transformers.Molmo3AdapterConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, vision_feature_layer: list[int] | None = None, hidden_size: int = 1152, num_attention_heads: int = 16, num_key_value_heads: int = 16, head_dim: int = 72, attention_dropout: float = 0.0, attention_bias: bool = True, hidden_act: str = 'silu', intermediate_size: int = 9728, text_hidden_size: int = 2560, mlp_bias: bool = False, initializer_range: float = 0.02, num_pooling_positions: int = 9)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/configuration_molmo3.py#L70)

**Parameters:**

vision_feature_layer (`list[int]`, *optional*) : Indices of the ViT layers whose outputs are concatenated and pooled, `[24, 18]` when not provided. Negative indices count from the last layer.

hidden_size (`int`, *optional*, defaults to `1152`) : Dimension of the hidden representations.

num_attention_heads (`int`, *optional*, defaults to `16`) : Number of attention heads for each attention layer in the Transformer decoder.

num_key_value_heads (`int`, *optional*, defaults to `16`) : This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out [this paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `num_attention_heads`.

head_dim (`int`, *optional*, defaults to `72`) : The attention head dimension. If None, it will default to hidden_size // num_attention_heads

attention_dropout (`float`, *optional*, defaults to `0.0`) : The dropout ratio for the attention probabilities.

attention_bias (`bool`, *optional*, defaults to `True`) : Whether to use a bias in the query, key, value and output projection layers during self-attention.

hidden_act (`str`, *optional*, defaults to `silu`) : The non-linear activation function (function or string) in the decoder. For example, `"gelu"`, `"relu"`, `"silu"`, etc.

intermediate_size (`int`, *optional*, defaults to `9728`) : Dimension of the MLP representations.

text_hidden_size (`int`, *optional*, defaults to 2560) : Hidden size of the text model (used for projection).

mlp_bias (`bool`, *optional*, defaults to `False`) : Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.

initializer_range (`float`, *optional*, defaults to `0.02`) : The standard deviation of the truncated_normal_initializer for initializing all weight matrices.

num_pooling_positions (`int`, *optional*, defaults to 9) : Number of learned position embeddings over the slots of a pooling window (3x3 for videos).

This is the configuration class to store the configuration of a Molmo3Model. It is used to instantiate a Molmo3
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuration to that of the [allenai/Molmo3-4B](https://huggingface.co/allenai/Molmo3-4B)

Configuration objects inherit from [PreTrainedConfig](/docs/transformers/main/en/main_classes/configuration#transformers.PreTrainedConfig) and can be used to control the model outputs. Read the
documentation from [PreTrainedConfig](/docs/transformers/main/en/main_classes/configuration#transformers.PreTrainedConfig) for more information.

## Molmo3TextConfig[[transformers.Molmo3TextConfig]]

#### transformers.Molmo3TextConfig[[transformers.Molmo3TextConfig]]

```python
transformers.Molmo3TextConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, hidden_size: int = 2560, num_attention_heads: int = 32, num_key_value_heads: int = 8, head_dim: int = 128, vocab_size: int = 152064, attention_bias: bool = False, qk_norm_type: str = 'qwen3', num_hidden_layers: int = 36, intermediate_size: int = 9728, hidden_act: str = 'silu', attention_dropout: float = 0.0, max_position_embeddings: int = 16384, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None, rms_norm_eps: float = 1e-06, initializer_range: float = 0.02, use_cache: bool = True, tie_word_embeddings: bool = False)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/configuration_molmo3.py#L108)

**Parameters:**

hidden_size (`int`, *optional*, defaults to `2560`) : Dimension of the hidden representations.

num_attention_heads (`int`, *optional*, defaults to `32`) : Number of attention heads for each attention layer in the Transformer decoder.

num_key_value_heads (`int`, *optional*, defaults to `8`) : This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out [this paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `num_attention_heads`.

head_dim (`int`, *optional*, defaults to `128`) : The attention head dimension. If None, it will default to hidden_size // num_attention_heads

vocab_size (`int`, *optional*, defaults to `152064`) : Vocabulary size of the model. Defines the number of different tokens that can be represented by the `input_ids`.

attention_bias (`bool`, *optional*, defaults to `False`) : Whether to use a bias in the query, key, value and output projection layers during self-attention.

qk_norm_type (`str`, *optional*, defaults to `"qwen3"`) : Query/key normalization layout used by the checkpoint. `"qwen3"` normalizes per head; `"olmo"` normalizes the full projected query/key tensors.

num_hidden_layers (`int`, *optional*, defaults to `36`) : Number of hidden layers in the Transformer decoder.

intermediate_size (`int`, *optional*, defaults to `9728`) : Dimension of the MLP representations.

hidden_act (`str`, *optional*, defaults to `silu`) : The non-linear activation function (function or string) in the decoder. For example, `"gelu"`, `"relu"`, `"silu"`, etc.

attention_dropout (`float`, *optional*, defaults to `0.0`) : The dropout ratio for the attention probabilities.

max_position_embeddings (`int`, *optional*, defaults to `16384`) : The maximum sequence length that this model might ever be used with.

rope_parameters (`Union[~modeling_rope_utils.RopeParameters, dict]`, *optional*) : Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE with longer `max_position_embeddings`.

rms_norm_eps (`float`, *optional*, defaults to `1e-06`) : The epsilon used by the rms normalization layers.

initializer_range (`float`, *optional*, defaults to `0.02`) : The standard deviation of the truncated_normal_initializer for initializing all weight matrices.

use_cache (`bool`, *optional*, defaults to `True`) : Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True` or when the model is a decoder-only generative model.

tie_word_embeddings (`bool`, *optional*, defaults to `False`) : Whether to tie weight embeddings according to model's `tied_weights_keys` mapping.

This is the configuration class to store the configuration of a Molmo3Model. It is used to instantiate a Molmo3
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuration to that of the [allenai/Molmo3-4B](https://huggingface.co/allenai/Molmo3-4B)

Configuration objects inherit from [PreTrainedConfig](/docs/transformers/main/en/main_classes/configuration#transformers.PreTrainedConfig) and can be used to control the model outputs. Read the
documentation from [PreTrainedConfig](/docs/transformers/main/en/main_classes/configuration#transformers.PreTrainedConfig) for more information.

## Molmo3Processor[[transformers.Molmo3Processor]]

#### transformers.Molmo3Processor[[transformers.Molmo3Processor]]

```python
transformers.Molmo3Processor(image_processor = None, video_processor = None, tokenizer = None, chat_template: str | None = None, subpatch_location_size: int = 4, **kwargs)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/processing_molmo3.py#L80)

**Parameters:**

image_processor (`Molmo2ImageProcessor`) : The image processor is a required input.

video_processor (`Molmo3VideoProcessor`) : The video processor is a required input.

tokenizer (`tokenizer_class`) : The tokenizer is a required input.

chat_template (`str`, *optional*) : A Jinja template to convert lists of messages in a chat into a tokenizable string.

subpatch_location_size (`int`, *optional*, defaults to 4) : Side length of the square grid of grounding locations within each subpatch (one ViT patch), as in [Molmo3Config](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3Config).

Constructs a Molmo3Processor which wraps a image processor, a video processor, and a tokenizer into a single processor.

[Molmo3Processor](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3Processor) offers all the functionalities of [Molmo2ImageProcessor](/docs/transformers/main/en/model_doc/molmo2#transformers.Molmo2ImageProcessor), [Molmo3VideoProcessor](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3VideoProcessor), and `tokenizer_class`. See the
[~Molmo2ImageProcessor](/docs/transformers/main/en/model_doc/molmo2#transformers.Molmo2ImageProcessor), [~Molmo3VideoProcessor](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3VideoProcessor), and `~tokenizer_class` for more information.

#### __call__[[transformers.Molmo3Processor.__call__]]

```python
__call__(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, text: str | list[str] | list[list[str]] | None = None, videos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = None, grounding: list[list[dict]] | None = None, **kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'>)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/processing_molmo3.py#L162)

**Parameters:**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`, *optional*) : Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`.

text (`Union[str, list[str], list[list[str]]]`, *optional*) : The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings (pretokenized string). If you pass a pretokenized input, set `is_split_into_words=True` to avoid ambiguity with batched inputs.

videos (`Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]]`, *optional*) : Video to preprocess. Expects a single or batch of videos with pixel values ranging from 0 to 255. If passing in videos with pixel values between 0 and 1, set `do_rescale=False`.

grounding (`list[list[dict]]`, *optional*) : For each text, what its points and masks point at, in order. Each entry is the `grounding` of an earlier answer, as [parse_response()](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3Processor.parse_response) stores it in the message (`{"point_indices", "mask_indices"}`), or the content of a `points` block (`{"coordinates": [{"mm_ix", "x", "y"}, ...]}`, in pixels of the original image; `x_norm` and `y_norm` for fractions of its size, and `time` instead of `mm_ix` for a video). [apply_chat_template()](/docs/transformers/main/en/main_classes/processors#transformers.ProcessorMixin.apply_chat_template) collects them from the chat. They become `grounding_indices`: each selection at the position after its grounding token, -1 elsewhere.

return_mm_token_type_ids (`bool`, *kwargs*) : Whether to return multimodal token type ids indicating multimodal placeholder token positions.

return_text_replacement_offsets (`bool`, *kwargs*) : Whether to return character offsets for each multimodal placeholder and its replacement.

return_tensors (`str` or [TensorType](/docs/transformers/main/en/internal/file_utils#transformers.TensorType), *optional*) : If set, will return tensors of a particular framework. Acceptable values are:  - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return NumPy `np.ndarray` objects.

- ****kwargs** ([ProcessingKwargs](/docs/transformers/main/en/main_classes/processors#transformers.ProcessingKwargs), *optional*) : Additional processing options for each modality (text, images, videos, audio). Model-specific parameters are listed above; see the TypedDict class for the complete list of supported arguments.

**Returns:** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- Dictionary of lists/arrays/tensors returned by the __call__ method ('pixel_values', etc.).
- **tensor_type** (`Union[None, str, TensorType]`, *optional*) -- You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at
  initialization.

#### post_process_grounding[[transformers.Molmo3Processor.post_process_grounding]]

```python
post_process_grounding(generated_ids, grounding, inputs: BatchFeature, target_sizes: list[list[tuple[int, int]]] | None = None, video_metadata: list[transformers.video_utils.VideoMetadata] | None = None, mask_threshold: float = 0.5)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/processing_molmo3.py#L718)

**Parameters:**

generated_ids (`torch.Tensor` or `list[list[int]]`) : The generated token ids of each sequence, without the prompt.

grounding (`list[Molmo3GroundingOutput]`) : The grounding of each sequence, from `generate(..., return_dict_in_generate=True).grounding`.

inputs ([BatchFeature](/docs/transformers/main/en/main_classes/feature_extractor#transformers.BatchFeature)) : The processor outputs the sequences were generated from.

target_sizes (`list[list[tuple[int, int]]]`, *optional*) : The `(height, width)` of each image or video of each prompt, in placeholder order. Coordinates are in pixels of that size and masks have that size. Without it, coordinates are fractions of the size, in `[0, 1]`, and masks have the resolution of the grounding head.

video_metadata (`list[VideoMetadata]`, *optional*) : The metadata of each video, as the processor returns it with `return_metadata=True`. Required for prompts with a video.

mask_threshold (`float`, *optional*, defaults to 0.5) : Probability above which a pixel belongs to a mask.

**Returns:** `list[list[dict]]`

For each sequence, one dict per grounding tag of its answer, in text order, with its
`type`, its `label` (the text the tag encloses, if any) and the tensors of that type. The model
documentation lists the types and their fields.

Decodes the points, masks and 3D boxes of generated sequences into coordinates.

#### parse_response[[transformers.Molmo3Processor.parse_response]]

```python
parse_response(response, schema: dict | None = None, prefix = None, tools: list[dict | collections.abc.Callable] | None = None, grounding = None)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/processing_molmo3.py#L662)

Same as `parse_response()`, and drops a grounding tag the answer was cut off in. With the
`grounding` of the answer (`Molmo3GroundingOutput`, or a list of them for a batch), the message also holds
the indices of its points and masks as plain lists (`{"point_indices", "mask_indices"}`), which
[apply_chat_template()](/docs/transformers/main/en/main_classes/processors#transformers.ProcessorMixin.apply_chat_template) passes back to the model.

## Molmo3VideoProcessor[[transformers.Molmo3VideoProcessor]]

#### transformers.Molmo3VideoProcessor[[transformers.Molmo3VideoProcessor]]

```python
transformers.Molmo3VideoProcessor(**kwargs: *<class 'transformers.models.molmo3.video_processing_molmo3.Molmo3VideoProcessorKwargs'>)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/video_processing_molmo3.py#L148)

**Parameters:**

do_convert_rgb (`bool`, *kwargs*, *optional*, defaults to `True`) : Whether to convert the image to RGB.

do_resize (`bool`, *kwargs*, *optional*, defaults to `True`) : Whether to resize the image.

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*, defaults to `{'height' : 378, 'width': 378}`): Describes the maximum input dimensions to the model.

default_to_square (`bool`, *kwargs*, *optional*, defaults to `True`) : Whether to default to a square image when resizing, if size is an int.

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*, defaults to `2`) : Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only has an effect if `do_resize` is set to `True`.

do_rescale (`bool`, *kwargs*, *optional*, defaults to `True`) : Whether to rescale the image.

rescale_factor (`float`, *kwargs*, *optional*, defaults to `0.00392156862745098`) : Rescale factor to rescale the image by if `do_rescale` is set to `True`.

do_normalize (`bool`, *kwargs*, *optional*, defaults to `True`) : Whether to normalize the image.

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, defaults to `[0.5, 0.5, 0.5]`) : Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, defaults to `[0.5, 0.5, 0.5]`) : Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to `True`.

do_center_crop (`bool`, *kwargs*, *optional*) : Whether to center crop the image.

do_pad (`bool`, *kwargs*, *optional*) : Whether to pad the image. Padding is done either to the largest size in the batch or to a fixed square size per image. The exact padding strategy depends on the model.

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : Size of the output image after applying `center_crop`.

data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *optional*) : Only `ChannelDimension.FIRST` is supported. Added for compatibility with slow processors.

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *optional*) : The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : The device to process the videos on. If unset, the device is inferred from the input videos.

do_sample_frames (`bool`, *kwargs*, *optional*, defaults to `True`) : Whether to sample frames from the video before processing or to process the whole video.

video_metadata (`Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None]`, *kwargs*) : Metadata of the video containing information about total duration, fps and total number of frames. It will be used to sample frames from video or compute timestamps. Don't pass any metadata unless you are trying to decode the video manually before processing

fps (`Annotated[int | float | None, None]`, *kwargs*) : Target frames to sample per second when `do_sample_frames=True`.

num_frames (`Annotated[int | None, None]`, *kwargs*, defaults to `128`) : Maximum number of frames to sample when `do_sample_frames=True`.

return_metadata (`bool`, *kwargs*, *optional*, defaults to `False`) : Whether to return video metadata or not. Video metadats is an object containing info about video duration, fps, decoding backend, etc.

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : If set, will return tensors of a particular framework. Acceptable values are:  - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return NumPy `np.ndarray` objects.

patch_size (`int`, *kwargs*, *optional*) : Side length in pixels of each ViT patch for video frames.

pooling_size (`list[int]`, *kwargs*, *optional*) : `[pool_h, pool_w]` pooling window applied to video patch features.

max_fps (`int`, *kwargs*, *optional*) : Maximum sampling rate in frames per second for short videos.

- ****kwargs** ([ProcessingKwargs](/docs/transformers/main/en/main_classes/processors#transformers.ProcessingKwargs), *optional*) : Additional processing options for each modality (text, images, videos, audio). Model-specific parameters are listed above; see the TypedDict class for the complete list of supported arguments.

Constructs a Molmo3VideoProcessor video processor.

#### __call__[[transformers.Molmo3VideoProcessor.__call__]]

```python
__call__(videos, **kwargs)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/video_processing_utils.py#L86)

## Molmo3Model[[transformers.Molmo3Model]]

#### transformers.Molmo3Model[[transformers.Molmo3Model]]

```python
transformers.Molmo3Model(config: Molmo3Config)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/modeling_molmo3.py#L1427)

**Parameters:**

config ([Molmo3Config](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3Config)) : Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from_pretrained()](/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

The Molmo3 model which consists of a vision backbone, a pooling adapter, a language model and a grounding head,
without a language modeling head.

This model inherits from [PreTrainedModel](/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel). Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.)

This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
and behavior.

#### forward[[transformers.Molmo3Model.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, pixel_values: typing.Optional[torch.Tensor] = None, image_token_pooling: typing.Optional[torch.Tensor] = None, image_grids: typing.Optional[torch.Tensor] = None, image_num_crops: typing.Optional[torch.Tensor] = None, image_position_ids: typing.Optional[torch.Tensor] = None, grounding_indices: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.Tensor] = None, cache: transformers.cache_utils.Cache | None = None, mm_token_type_ids: typing.Optional[torch.LongTensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, use_cache: bool | None = None, mm_encoder_outputs: dict[str, transformers.models.molmo3.modeling_molmo3.Molmo3ImageFeaturesOutput] | None = None, grounding_state: transformers.models.molmo3.generation_molmo3.Molmo3GroundingState | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/modeling_molmo3.py#L1528)

**Parameters:**

input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) : Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.  Indices can be obtained using [AutoTokenizer](/docs/transformers/main/en/model_doc/auto#transformers.AutoTokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/main/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and [PreTrainedTokenizer.__call__()](/docs/transformers/main/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.  [What are input IDs?](../glossary#input-ids)

pixel_values (`torch.Tensor` of shape `(batch_size, num_channels, image_size, image_size)`, *optional*) : The tensors corresponding to the input images. Pixel values can be obtained using `image_processor_class`. See `image_processor_class.__call__` for details (`processor_class` uses `image_processor_class` for processing images).

image_token_pooling (`torch.Tensor` of shape `(num_image_tokens, pool_h * pool_w)`, *optional*) : Indices into each image's own flattened patch sequence gathered by each pooled image token, with `-1` marking padding slots. Can be obtained using [AutoProcessor](/docs/transformers/main/en/model_doc/auto#transformers.AutoProcessor). See [ProcessorMixin.__call__()](/docs/transformers/main/en/main_classes/processors#transformers.ProcessorMixin.__call__) for details.

image_grids (`torch.Tensor` of shape `(num_images, 4)`, *optional*) : Per-image `[low_res_h, low_res_w, high_res_h, high_res_w]` pooled token grid. Can be obtained using [AutoProcessor](/docs/transformers/main/en/model_doc/auto#transformers.AutoProcessor). See [ProcessorMixin.__call__()](/docs/transformers/main/en/main_classes/processors#transformers.ProcessorMixin.__call__) for details.

image_num_crops (`torch.Tensor` of shape `(num_images,)`, *optional*) : Number of crops per image, low-resolution view included. Required for more than one image. Can be obtained using [AutoProcessor](/docs/transformers/main/en/model_doc/auto#transformers.AutoProcessor). See [ProcessorMixin.__call__()](/docs/transformers/main/en/main_classes/processors#transformers.ProcessorMixin.__call__) for details.

image_position_ids (`torch.Tensor` of shape `(num_crops, num_patches, 3)`, *optional*) : The (time, row, column) position of each ViT patch of the image crops or video frames.

grounding_indices (`torch.LongTensor` of shape `(batch_size, sequence_length, 3)`, *optional*) : The `(pooled_patch_index, subpatch_index, location)` selected by the grounding token before each position, -1 elsewhere (see `Molmo3GroundingEmbedding.forward`). Each selection is added to the embedding at its position. The processor computes them for the points and masks of the prompt.

attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*) : Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:  - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**.  [What are attention masks?](../glossary#attention-mask)

position_ids (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*) : Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`.  [What are position IDs?](../glossary#position-ids)

cache (`~cache_utils.Cache`, *optional*) : Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the `cache` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.  Only [Cache](/docs/transformers/main/en/internal/generation_utils#transformers.Cache) instance is allowed as input, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). If no `cache` are passed, [DynamicCache](/docs/transformers/main/en/internal/generation_utils#transformers.DynamicCache) will be initialized by default.  The model will output the same cache format that is fed as input.  If `cache` are used, the user is expected to input only unprocessed `input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, unprocessed_length)` instead of all `input_ids` of shape `(batch_size, sequence_length)`.

mm_token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) : Indices of input sequence tokens matching each modality. For example text (0), image (1), video (2). Multimodal token type ids can be obtained using [AutoProcessor](/docs/transformers/main/en/model_doc/auto#transformers.AutoProcessor). See [ProcessorMixin.__call__()](/docs/transformers/main/en/main_classes/processors#transformers.ProcessorMixin.__call__) for details. 

inputs_embeds (`torch.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) : Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix.

use_cache (`bool`, *optional*) : If set to `True`, `cache` key value states are returned and can be used to speed up decoding (see `cache`).

mm_encoder_outputs (`dict[str, ~models.molmo3.modeling_molmo3.Molmo3ImageFeaturesOutput]`, *optional*) : Dict where keys are supported modalities and values are encoded outputs for that modality. Each encoded output is a tuple that consists of (`pooler_output`, *optional*: `last_hidden_states`, *optional*: `hidden_states`, *optional*: `attentions`) `pooler_output` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of multimmodal features of the encoder merged into text embeddings.

grounding_state (`Molmo3GroundingState`, *optional*) : The pointing and segmentation state of a generation, created by [generate()](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3ForConditionalGeneration.generate). The forward pass returns the grounding image features at prefill and the queries for the last token.

**Returns:** `Molmo3ModelOutputWithPast` or `tuple(torch.Tensor)`

A `Molmo3ModelOutputWithPast` or a tuple of
`torch.Tensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various
elements depending on the configuration (`None`) and inputs.

The [Molmo3Model](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3Model) forward method, overrides the `__call__` special method.

> [!TIP]
> Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
> instance afterwards instead of this since the former takes care of running the pre and post processing steps while
> the latter silently ignores them.

- **last_hidden_state** (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) -- Sequence of hidden-states at the output of the last layer of the language model backbone.
  If `cache` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
  hidden_size)` is output.
- **cache** (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) -- It is a [Cache](/docs/transformers/main/en/internal/generation_utils#transformers.Cache) instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
  Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
  `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `cache`
  input) to speed up sequential decoding.
- **hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
  one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
  Hidden-states of the language model backbone at the output of each layer plus the optional initial
  embedding outputs.
- **attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  sequence_length)`. Attention weights of the language model backbone, after the attention softmax.
- **image_outputs** (`BaseModelOutputWithPooling`, *optional*) -- Output of the image encoder: `last_hidden_state`, `pooler_output`, `hidden_states` and `attentions`.
  `None` if no images were processed.
- **video_outputs** (`BaseModelOutputWithPooling`, *optional*) -- Output of the video encoder: `last_hidden_state`, `pooler_output`, `hidden_states` and `attentions`.
  `None` if no videos were processed.
- **audio_outputs** (`BaseModelOutputWithPooling`, *optional*) -- Output of the audio encoder: `last_hidden_state`, `pooler_output`, `hidden_states` and `attentions`.
  `None` if no audio was processed.
- **grounding_outputs** (`Molmo3GroundingModelOutput`, *optional*) -- Outputs of the grounding module when a `grounding_state` is passed.

## Molmo3TextModel[[transformers.Molmo3TextModel]]

#### transformers.Molmo3TextModel[[transformers.Molmo3TextModel]]

```python
transformers.Molmo3TextModel(config: Molmo3TextConfig)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/modeling_molmo3.py#L801)

**Parameters:**

config ([Molmo3TextConfig](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3TextConfig)) : Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from_pretrained()](/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

The bare Molmo3 Text Model outputting raw hidden-states without any specific head on top.

This model inherits from [PreTrainedModel](/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel). Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.)

This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
and behavior.

#### forward[[transformers.Molmo3TextModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, cache: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.FloatTensor] = None, use_cache: bool | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/modeling_molmo3.py#L819)

**Parameters:**

input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) : Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.  Indices can be obtained using [AutoTokenizer](/docs/transformers/main/en/model_doc/auto#transformers.AutoTokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/main/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and [PreTrainedTokenizer.__call__()](/docs/transformers/main/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.  [What are input IDs?](../glossary#input-ids)

attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*) : Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:  - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**.  [What are attention masks?](../glossary#attention-mask)

position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) : Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`.  [What are position IDs?](../glossary#position-ids)

cache (`~cache_utils.Cache`, *optional*) : Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the `cache` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.  Only [Cache](/docs/transformers/main/en/internal/generation_utils#transformers.Cache) instance is allowed as input, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). If no `cache` are passed, [DynamicCache](/docs/transformers/main/en/internal/generation_utils#transformers.DynamicCache) will be initialized by default.  The model will output the same cache format that is fed as input.  If `cache` are used, the user is expected to input only unprocessed `input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, unprocessed_length)` instead of all `input_ids` of shape `(batch_size, sequence_length)`.

inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) : Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix.

use_cache (`bool`, *optional*) : If set to `True`, `cache` key value states are returned and can be used to speed up decoding (see `cache`).

**Returns:** `Molmo3TextModelOutputWithPast` or `tuple(torch.Tensor)`

A `Molmo3TextModelOutputWithPast` or a tuple of
`torch.Tensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various
elements depending on the configuration (`None`) and inputs.

The [Molmo3TextModel](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3TextModel) forward method, overrides the `__call__` special method.

> [!TIP]
> Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
> instance afterwards instead of this since the former takes care of running the pre and post processing steps while
> the latter silently ignores them.

- **last_hidden_state** (`torch.Tensor` of shape `(batch_size, sequence_length, hidden_size)`) -- Sequence of hidden-states at the output of the last layer of the model.

  If `cache` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
  hidden_size)` is output.
- **cache** (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) -- It is a [Cache](/docs/transformers/main/en/internal/generation_utils#transformers.Cache) instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).

  Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
  `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `cache`
  input) to speed up sequential decoding.
- **hidden_states** (`tuple(torch.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.Tensor` (one for the output of the embeddings, if the model has an embedding layer, +
  one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

  Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
- **attentions** (`tuple(torch.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  sequence_length)`.

  Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
  heads.
- **pre_norm_last_hidden_state** (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) -- Output of the last decoder layer, before the final normalization.

## Molmo3Adapter[[transformers.Molmo3Adapter]]

#### transformers.Molmo3Adapter[[transformers.Molmo3Adapter]]

```python
transformers.Molmo3Adapter(config: Molmo3AdapterConfig)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/modeling_molmo3.py#L721)

**Parameters:**

config ([Molmo3AdapterConfig](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3AdapterConfig)) : Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from_pretrained()](/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

Pools ViT patch features with a single-query attention layer and projects them into the language model's embedding space.

This model inherits from [PreTrainedModel](/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel). Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.)

This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
and behavior.

#### forward[[transformers.Molmo3Adapter.forward]]

```python
forward(image_features: Tensor, pooled_patches_idx: Tensor, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/modeling_molmo3.py#L738)

**Parameters:**

image_features (`torch.Tensor` of shape `(num_crops, num_patches, hidden_size * len(vision_feature_layer))`) : Concatenated intermediate ViT features of every crop, with their patch position embeddings.

pooled_patches_idx (`torch.Tensor` of shape `(num_tokens, pool_h * pool_w)`) : Indices into the flattened patch sequence pooled by each output token; `-1` marks padding slots.

**Returns:** [BaseModelOutput](/docs/transformers/main/en/main_classes/output#transformers.modeling_outputs.BaseModelOutput) or `tuple(torch.Tensor)`

A [BaseModelOutput](/docs/transformers/main/en/main_classes/output#transformers.modeling_outputs.BaseModelOutput) or a tuple of
`torch.Tensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various
elements depending on the configuration ([Molmo3Config](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3Config)) and inputs.

The [Molmo3Adapter](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3Adapter) forward method, overrides the `__call__` special method.

> [!TIP]
> Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
> instance afterwards instead of this since the former takes care of running the pre and post processing steps while
> the latter silently ignores them.

- **last_hidden_state** (`torch.Tensor` of shape `(batch_size, sequence_length, hidden_size)`) -- Sequence of hidden-states at the output of the last layer of the model.
- **hidden_states** (`tuple(torch.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.Tensor` (one for the output of the embeddings, if the model has an embedding layer, +
  one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

  Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
- **attentions** (`tuple(torch.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  sequence_length)`.

  Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
  heads.

## Molmo3VisionModel[[transformers.Molmo3VisionModel]]

#### transformers.Molmo3VisionModel[[transformers.Molmo3VisionModel]]

```python
transformers.Molmo3VisionModel(config: Molmo3VisionConfig)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/modeling_molmo3.py#L650)

**Parameters:**

config ([Molmo3VisionConfig](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3VisionConfig)) : Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from_pretrained()](/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

The bare Molmo3 Model outputting raw hidden-states without any specific head on top.

This model inherits from [PreTrainedModel](/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel). Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.)

This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
and behavior.

#### forward[[transformers.Molmo3VisionModel.forward]]

```python
forward(pixel_values: Tensor, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/modeling_molmo3.py#L670)

**Parameters:**

pixel_values (`torch.Tensor` of shape `(batch_size, num_channels, image_size, image_size)`) : The tensors corresponding to the input images. Pixel values can be obtained using [Molmo2ImageProcessor](/docs/transformers/main/en/model_doc/molmo2#transformers.Molmo2ImageProcessor). See [Molmo2ImageProcessor.__call__()](/docs/transformers/main/en/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) for details ([Molmo3Processor](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3Processor) uses [Molmo2ImageProcessor](/docs/transformers/main/en/model_doc/molmo2#transformers.Molmo2ImageProcessor) for processing images).

**Returns:** [BaseModelOutputWithPooling](/docs/transformers/main/en/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) or `tuple(torch.Tensor)`

A [BaseModelOutputWithPooling](/docs/transformers/main/en/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) or a tuple of
`torch.Tensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various
elements depending on the configuration ([Molmo3Config](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3Config)) and inputs.

The [Molmo3VisionModel](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3VisionModel) forward method, overrides the `__call__` special method.

> [!TIP]
> Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
> instance afterwards instead of this since the former takes care of running the pre and post processing steps while
> the latter silently ignores them.

- **last_hidden_state** (`torch.Tensor` of shape `(batch_size, sequence_length, hidden_size)`) -- Sequence of hidden-states at the output of the last layer of the model.
- **pooler_output** (`torch.Tensor` of shape `(batch_size, hidden_size)`) -- Last layer hidden-state of the first token of the sequence (classification token) after further processing
  through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns
  the classification token after processing through a linear layer and a tanh activation function. The linear
  layer weights are trained from the next sentence prediction (classification) objective during pretraining.
- **hidden_states** (`tuple(torch.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.Tensor` (one for the output of the embeddings, if the model has an embedding layer, +
  one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

  Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
- **attentions** (`tuple(torch.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  sequence_length)`.

  Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
  heads.

## Molmo3ForConditionalGeneration[[transformers.Molmo3ForConditionalGeneration]]

#### transformers.Molmo3ForConditionalGeneration[[transformers.Molmo3ForConditionalGeneration]]

```python
transformers.Molmo3ForConditionalGeneration(config: Molmo3Config)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/modeling_molmo3.py#L1681)

**Parameters:**

config ([Molmo3Config](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3Config)) : Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from_pretrained()](/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

The Molmo3 model which consists of a vision backbone, a pooling adapter, a language model with a language modeling
head, and a grounding head for pointing and segmentation.

This model inherits from [PreTrainedModel](/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel). Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.)

This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
and behavior.

#### forward[[transformers.Molmo3ForConditionalGeneration.forward]]

```python
forward(input_ids: LongTensor = None, pixel_values: typing.Optional[torch.Tensor] = None, image_token_pooling: typing.Optional[torch.Tensor] = None, image_grids: typing.Optional[torch.Tensor] = None, image_num_crops: typing.Optional[torch.Tensor] = None, image_position_ids: typing.Optional[torch.Tensor] = None, grounding_indices: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, cache: transformers.cache_utils.Cache | None = None, mm_token_type_ids: typing.Optional[torch.LongTensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.LongTensor] = None, use_cache: bool | None = None, logits_to_keep: typing.Union[int, torch.Tensor] = 0, mm_encoder_outputs: dict[str, transformers.models.molmo3.modeling_molmo3.Molmo3ImageFeaturesOutput] | None = None, grounding_state: transformers.models.molmo3.generation_molmo3.Molmo3GroundingState | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/modeling_molmo3.py#L1733)

**Parameters:**

input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) : Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.  Indices can be obtained using [AutoTokenizer](/docs/transformers/main/en/model_doc/auto#transformers.AutoTokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/main/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and [PreTrainedTokenizer.__call__()](/docs/transformers/main/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.  [What are input IDs?](../glossary#input-ids)

pixel_values (`torch.Tensor` of shape `(batch_size, num_channels, image_size, image_size)`, *optional*) : The tensors corresponding to the input images. Pixel values can be obtained using `image_processor_class`. See `image_processor_class.__call__` for details (`processor_class` uses `image_processor_class` for processing images).

image_token_pooling (`torch.Tensor` of shape `(num_image_tokens, pool_h * pool_w)`, *optional*) : Indices into each image's own flattened patch sequence gathered by each pooled image token, with `-1` marking padding slots. Can be obtained using [AutoProcessor](/docs/transformers/main/en/model_doc/auto#transformers.AutoProcessor). See [ProcessorMixin.__call__()](/docs/transformers/main/en/main_classes/processors#transformers.ProcessorMixin.__call__) for details.

image_grids (`torch.Tensor` of shape `(num_images, 4)`, *optional*) : Per-image `[low_res_h, low_res_w, high_res_h, high_res_w]` pooled token grid. Can be obtained using [AutoProcessor](/docs/transformers/main/en/model_doc/auto#transformers.AutoProcessor). See [ProcessorMixin.__call__()](/docs/transformers/main/en/main_classes/processors#transformers.ProcessorMixin.__call__) for details.

image_num_crops (`torch.Tensor` of shape `(num_images,)`, *optional*) : Number of crops per image, low-resolution view included. Required for more than one image. Can be obtained using [AutoProcessor](/docs/transformers/main/en/model_doc/auto#transformers.AutoProcessor). See [ProcessorMixin.__call__()](/docs/transformers/main/en/main_classes/processors#transformers.ProcessorMixin.__call__) for details.

image_position_ids (`torch.Tensor` of shape `(num_crops, num_patches, 3)`, *optional*) : The (time, row, column) position of each ViT patch of the image crops or video frames.

grounding_indices (`torch.LongTensor` of shape `(batch_size, sequence_length, 3)`, *optional*) : The `(pooled_patch_index, subpatch_index, location)` selected by the grounding token before each position, -1 elsewhere (see `Molmo3GroundingEmbedding.forward`). Each selection is added to the embedding at its position. The processor computes them for the points and masks of the prompt.

attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*) : Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:  - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**.  [What are attention masks?](../glossary#attention-mask)

position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) : Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`.  [What are position IDs?](../glossary#position-ids)

cache (`~cache_utils.Cache`, *optional*) : Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the `cache` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.  Only [Cache](/docs/transformers/main/en/internal/generation_utils#transformers.Cache) instance is allowed as input, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). If no `cache` are passed, [DynamicCache](/docs/transformers/main/en/internal/generation_utils#transformers.DynamicCache) will be initialized by default.  The model will output the same cache format that is fed as input.  If `cache` are used, the user is expected to input only unprocessed `input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, unprocessed_length)` instead of all `input_ids` of shape `(batch_size, sequence_length)`.

mm_token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) : Indices of input sequence tokens matching each modality. For example text (0), image (1), video (2). Multimodal token type ids can be obtained using [AutoProcessor](/docs/transformers/main/en/model_doc/auto#transformers.AutoProcessor). See [ProcessorMixin.__call__()](/docs/transformers/main/en/main_classes/processors#transformers.ProcessorMixin.__call__) for details. 

inputs_embeds (`torch.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) : Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix.

labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) : Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

use_cache (`bool`, *optional*) : If set to `True`, `cache` key value states are returned and can be used to speed up decoding (see `cache`).

logits_to_keep (`Union[int, torch.Tensor]`, *optional*, defaults to `0`) : If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that token can save memory, which becomes pretty significant for long sequences or large vocabulary size. If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension. This is useful when using packed tensor format (single dimension for batch and sequence length).

mm_encoder_outputs (`dict[str, ~models.molmo3.modeling_molmo3.Molmo3ImageFeaturesOutput]`, *optional*) : Dict where keys are supported modalities and values are encoded outputs for that modality. Each encoded output is a tuple that consists of (`pooler_output`, *optional*: `last_hidden_states`, *optional*: `hidden_states`, *optional*: `attentions`) `pooler_output` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of multimmodal features of the encoder merged into text embeddings.

grounding_state (`Molmo3GroundingState`, *optional*) : The pointing and segmentation state of a generation, created by [generate()](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3ForConditionalGeneration.generate). The forward pass returns the grounding image features at prefill and the queries for the last token. In a manual decoding loop, call `model.update_grounding_state(outputs, grounding_state)` before applying logits processors or feeding the next token. `generate` does this automatically.

**Returns:** `Molmo3CausalLMOutputWithPast` or `tuple(torch.Tensor)`

A `Molmo3CausalLMOutputWithPast` or a tuple of
`torch.Tensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various
elements depending on the configuration (`None`) and inputs.

The [Molmo3ForConditionalGeneration](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3ForConditionalGeneration) forward method, overrides the `__call__` special method.

> [!TIP]
> Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
> instance afterwards instead of this since the former takes care of running the pre and post processing steps while
> the latter silently ignores them.

- **loss** (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) -- Language modeling loss (for next-token prediction).
- **logits** (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`) -- Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
- **cache** (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) -- It is a [Cache](/docs/transformers/main/en/internal/generation_utils#transformers.Cache) instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
  Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
  `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `cache`
  input) to speed up sequential decoding.
- **hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
  one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
  Hidden-states of the language model backbone at the output of each layer plus the optional initial
  embedding outputs.
- **attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  sequence_length)`. Attention weights of the language model backbone, after the attention softmax.
- **image_outputs** (`BaseModelOutputWithPooling`, *optional*) -- Output of the image encoder: `last_hidden_state`, `pooler_output`, `hidden_states` and `attentions`.
  `None` if no images were processed.
- **video_outputs** (`BaseModelOutputWithPooling`, *optional*) -- Output of the video encoder: `last_hidden_state`, `pooler_output`, `hidden_states` and `attentions`.
  `None` if no videos were processed.
- **audio_outputs** (`BaseModelOutputWithPooling`, *optional*) -- Output of the audio encoder: `last_hidden_state`, `pooler_output`, `hidden_states` and `attentions`.
  `None` if no audio was processed.
- **grounding_outputs** (`Molmo3GroundingModelOutput`, *optional*) -- Outputs of the grounding module when a `grounding_state` is passed.

Example:

```python
>>> from transformers import AutoProcessor, Molmo3ForConditionalGeneration
>>> from transformers.image_utils import load_image

>>> model = Molmo3ForConditionalGeneration.from_pretrained("allenai/Molmo3-4B", device_map="auto")
>>> processor = AutoProcessor.from_pretrained("allenai/Molmo3-4B")

>>> url = "https://raw.githubusercontent.com/scikit-image/scikit-image/v0.19.3/skimage/data/coffee.png"
>>> image = load_image(url)
>>> messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "Point to the spoon."}]}]
>>> prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
>>> inputs = processor(images=[image], text=prompt, return_tensors="pt").to(model.device)

>>> output = model.generate(**inputs, max_new_tokens=64, return_dict_in_generate=True)
>>> generated_ids = output.sequences[:, inputs["input_ids"].shape[1] :]
>>> target_sizes = [[(image.height, image.width)]]
>>> processor.post_process_grounding(generated_ids, output.grounding, inputs, target_sizes=target_sizes)
```

#### generate[[transformers.Molmo3ForConditionalGeneration.generate]]

```python
generate(*args, **kwargs)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/generation_molmo3.py#L289)

[generate()](/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationMixin.generate). With `return_dict_in_generate=True`, the output also has `grounding`,
one `Molmo3GroundingOutput` per sequence, which [Molmo3Processor.post_process_grounding()](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3Processor.post_process_grounding) turns into
coordinates and masks.

With images or videos, the grounding head keeps a state per sequence across the decoding steps, so beam
search, `num_return_sequences > 1`, assisted decoding and decoding without cache are not supported, and
`inputs_embeds` must come with their `input_ids`.

## Molmo3GroundingOutput[[transformers.models.molmo3.generation_molmo3.Molmo3GroundingOutput]]

#### transformers.models.molmo3.generation_molmo3.Molmo3GroundingOutput[[transformers.models.molmo3.generation_molmo3.Molmo3GroundingOutput]]

```python
transformers.models.molmo3.generation_molmo3.Molmo3GroundingOutput(point_indices: list[torch.LongTensor], mask_indices: list[torch.LongTensor] | None = None, mask_scores: list[torch.Tensor] | None = None, grounding_end_prob: typing.Optional[torch.Tensor] = None)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/generation_molmo3.py#L32)

**Parameters:**

point_indices (`list[torch.LongTensor]`) : One `(pooled_patch_index, subpatch_index, location)` tensor of shape `(3,)` per generated point, with the same indexing as `grounding_indices`.

mask_indices (`list[torch.LongTensor]`) : The pooled_patch_index of the pooled patch each generated segmentation mask is anchored on, as a 0-dim tensor.

mask_scores (`list[torch.Tensor]`) : One `(num_image_tokens, num_subpatches, subpatch_location_size**2)` tensor of mask probabilities per generated segmentation mask (`-1` where nothing can be selected). Each image token has `num_subpatches` slots for ViT patches. Each subpatch contains a square grid of locations with side length `subpatch_location_size`.

grounding_end_prob (`torch.Tensor`, *optional*) : Softmax probability, as a 0-dim tensor, that the grounding head assigns to ending the current sequence of points or masks before selecting another image patch. Recorded once per generated sequence, at the first `<|POINT_PATCH|>`, before the patch selection rules are applied. `None` until it is processed.

The grounding of one generated sequence.

## Molmo3GroundingLogitsProcessor[[transformers.models.molmo3.generation_molmo3.Molmo3GroundingLogitsProcessor]]

#### transformers.models.molmo3.generation_molmo3.Molmo3GroundingLogitsProcessor[[transformers.models.molmo3.generation_molmo3.Molmo3GroundingLogitsProcessor]]

```python
transformers.models.molmo3.generation_molmo3.Molmo3GroundingLogitsProcessor(config, grounding_state: Molmo3GroundingState, device: typing.Union[torch.device, str, NoneType] = None)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/generation_molmo3.py#L223)

**Parameters:**

config (`Molmo3Config`) : The model config, for the ids of the grounding tokens.

grounding_state (`Molmo3GroundingState`) : The state updated in place by the same generation. Scores are returned unchanged until the prefill has filled it.

device (`str` or `torch.device`, *optional*) : Device on which to prepare the grounding token IDs.

[LogitsProcessor](/docs/transformers/main/en/internal/generation_utils#transformers.LogitsProcessor) that constrains the token after each grounding token of [Molmo3ForConditionalGeneration](/docs/transformers/main/en/model_doc/molmo3#transformers.Molmo3ForConditionalGeneration),
from the selections the grounding head recorded in `grounding_state` at the latest generation step:

- after a patch token that selected a pooled patch, only grounding tokens are allowed
- after a patch token that ended the list, no grounding token is allowed
- `<|POINT_SUBPATCH|>` is always followed by `<|POINT_LOC|>`
- a center point (`<|CENTER_PATCH|>`...`<|POINT_LOC|>`) is not followed by another `<|CENTER_PATCH|>`
- `<|SEG_MASK|>`, `<|POINT_SUBPATCH|>` and `<|POINT_LOC|>` only follow grounding tokens.

#### __call__[[transformers.models.molmo3.generation_molmo3.Molmo3GroundingLogitsProcessor.__call__]]

```python
__call__(input_ids: LongTensor, scores: FloatTensor)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/molmo3/generation_molmo3.py#L256)
