Transformers documentation
Molmo3
该模型于 2026-12-02 贡献至 Hugging Face Transformers。
Molmo3
Molmo3 是由 Allen Institute for AI (Ai2) 推出的一系列开源视觉语言模型,专注于空间与 3D 理解及定位。它支持单张图像、多张图像和视频输入。其架构与 Molmo2 相同:一个从 SigLIP 2 初始化的视觉 Transformer,一个将 patch 特征池化为图像 token 的适配器,以及一个从 Qwen3 初始化的文本解码器。
Molmo3 增加了一个定位头(grounding head)。该模型不会以文本形式输出坐标,而是生成定位 token,如 MolmoPoint 所引入的那样。在 <|POINT_PATCH|> 之后,该头会选择一个图像 token 或结束点列表。在 <|POINT_SUBPATCH|> 之后,它会选择该图像 token 内部的一个 ViT patch。在 <|POINT_LOC|> 之后,它会选择该 patch 内部的一个位置。每次选择的特征都会加到下一个 token 的嵌入上。在 <|SEG_MASK|> 之后,该头会预测围绕所选图像 token 的分割掩码。
借助该头部,Molmo3 可以指向图像和视频中的对象,在视频中跟踪对象,对图像中的对象进行分割,估计某一点的深度或表面法线,并预测 3D 边界框。
您可以在 Molmo3 集合中找到所有原始的 Molmo3 检查点。
使用示例
图像文本到文本生成
以下示例演示了如何使用 Pipeline 或 AutoModel 类基于图像生成文本。
本页面上的其他示例将复用 AutoModel 选项卡中的 processor 和 model。
对于图像或视频,generate() 支持贪心解码和采样,每个提示词生成一个序列,且
use_cache=True。束搜索、num_return_sequences > 1、辅助解码以及use_cache=False会引发错误,因为 grounding head 会为每个序列维护一个状态。
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)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))指向与分割
将 return_dict_in_generate=True 传递给 generate(),即可同时获取 grounding,每个序列对应一个 Molmo3GroundingOutput,其中包含由 grounding 头选中的索引。post_process_grounding() 会将它们转换为像素坐标和掩码。
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]])提示词决定了输出的类型。以下提示词来自模型卡片。
| 提示 | 输出 type |
|---|---|
| “指向猫的眼睛。” | points |
| “对猫进行分割。” | segmentation |
| “指向勺子,并告诉我每个勺子距离相机有多远。” | points_3d |
| “指向该表格,并给出每个位置的法向量。” | points_normal |
| “找到杯子的 3D 框。” | camera 和 boxes_3d |
| “请给出此图像的水平视场角和垂直视场角,单位为度。” | camera |
| 在视频上“跟踪左侧的企鹅。” | video_tracks |
post_process_grounding() 按生成文本中标签的顺序,为每个序列返回一个字典列表。每个字典包含 type、label(标签内的文本,或 None)以及以下字段。
type | 标签 | 字段 |
|---|---|---|
points | 图像上的 <points> | points (num_points, 2),每个点的 (x, y) 坐标,以及 image_index (num_points,),每个点对应的图像 |
trace | 在图像上使用 <trace> | points 和 image_index |
video_points | 视频上的 <points> 或 <trace> | points 和 timestamps (num_points,),单位为秒 |
video_tracks | 视频上的 <tracks> | points、timestamps 和 object_ids (num_points,) |
points_3d | <points3d> | points、image_index 和 depth (num_points,),单位为米,当答案未提供深度时值为 NaN |
points_normal | <pointsn> | points、image_index、normals (num_points, 3) 以及 flags (num_points,),当法线缺失或无法估计时为 1 |
segmentation | 图像上的 <seg> | masks,一个列表,每个掩码对应一个布尔张量,以及 image_index (num_masks,) |
boxes_3d, video_boxes_3d | <box3d>,或视频上的 <tracks> 框 | 参见 3D 框 |
camera | <camera> | fovs (num_cameras, 2),以度为单位的水平和垂直视场角,以及 image_index |
target_sizes 按提示中出现的顺序,给出每个提示中每张图片及视频的 (height, width)。此时坐标以像素为单位,掩码也具有相应尺寸。若未指定 target_sizes,则坐标为图像尺寸的分数,取值范围为 [0, 1]。
post_process_grounding不会解码 2D 框(<bboxes>标签),并且仅针对图像解码分割掩码。 如果max_new_tokens在某个 grounding 标签内部截断了回答,post_process_grounding和parse_response会丢弃该标签。
对于批量生成,请将对话列表和
processor_kwargs={"padding": True}传递给 apply_chat_template(),并为target_sizes提供每个对话对应的一个列表。
多轮对话
要继续对话,请使用 parse_response() 将每个回答转换为消息,并传入该回答的 grounding。消息会保留其点和掩码的选中索引,apply_chat_template() 会将它们传回给模型。下面的示例继续了指向示例。
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)消息的 grounding 由普通列表组成,因此对话可以保存为 JSON 并在之后继续。索引指向提示中的图像 token,因此请保持相同的图像、相同的顺序以及相同的处理器设置。
如果将聊天格式化为 tokenize=False 并单独调用处理器,请将每个答案的 grounding 传递给处理器,每个文本对应一个列表:processor(text=[prompt], images=[image], grounding=[[answer["grounding"]]])。
提示词中的要点
用户消息可以在 points 块中包含点。每个点可以以像素(x、y)或图像尺寸的比例(x_norm、y_norm)给出,并附带 mm_ix,即该点所属图像的索引。对于视频,请提供以秒为单位的 time,而不是 mm_ix。聊天模板会将这些点写入为 grounding token,处理器会计算每个点的图像 token、ViT patch 及其位置。
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"] 是每个点的深度,单位为米。处理器按图像 token 的顺序逐行对点进行排序,因此提示中首先列出 (0.9, 0.2) 处的点,答案也采用相同的顺序。
视频指向
在聊天中添加一个 video 块,并向处理器传入 return_metadata=True。随后,处理器会返回 video_metadata,post_process_grounding() 需要用它来查找每一帧的时间戳。在调用 generate() 之前,从输入中弹出 video_metadata。
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"])如果不使用 target_sizes,则这些点表示为帧宽度和高度的分数。
3D 框
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):框中心投影到的像素。depth(num_boxes,):框中心的深度,单位为米。sizes(num_boxes, 3):框的宽度、高度和长度,单位为米。rotations(num_boxes, 3, 3):从物体坐标系到相机坐标系的旋转。reference_points(num_boxes, 2):模型在输出框之前给出的对象上的点,若不存在则为 NaN。image_index(num_boxes,):每个框对应的图像。
当答案中也包含 <camera hfov=... vfov=...> 标签时,结果中将包含一个 camera 元素,并且 boxes_3d 具有 centers (num_boxes, 3):以米为单位的框中心,位于相机坐标系中(X 向右,Y 向下,Z 向前)。
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
class transformers.Molmo3Config
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneadapter_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneimage_start_token_id: int = 151936low_res_image_start_token_id: int = 151940image_end_token_id: int = 151937image_patch_id: int = 151938frame_start_token_id: int = 151943frame_end_token_id: int = 151944initializer_range: float = 0.02tie_word_embeddings: bool = Falseimage_low_res_id: int = 151942point_patch_id: int = 151950point_subpatch_id: int = 151951point_loc_id: int = 151952seg_mask_id: int = 151953center_patch_id: int = 151954point_query_dims: list[int] | None = Nonesubpatch_location_size: int = 4subpatch_hidden_size: int = 512subpatch_conv_kernel: int = 3mask_diffusion_steps: int = 2presence_threshold: float = 0.5rope_parameters: dict[str, dict] | None = Nonepatch_position_embedding_size: int = 512 )
参数
- vision_config (
Molmo3VisionConfig,可选) — 视觉 Transformer 骨干网络的配置。 - adapter_config (
Molmo3AdapterConfig,可选) — 视觉到语言适配器的配置。 - text_config (
Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 文本骨干网络的配置对象或字典。 - image_start_token_id (
int,可选,默认为 151936) — 标记图像高分辨率裁剪起始位置的 Token ID。 - low_res_image_start_token_id (
int,可选,默认值为 151940) — 标记图像低分辨率视图起始位置的 Token ID。 - image_end_token_id (
int,可选,默认为 151937) — 标记图像区域结束的 Token ID。 - image_patch_id (
int,可选,默认为 151938) — 高分辨率图像和视频令牌的 Token ID。 - frame_start_token_id (
int,可选,默认为 151943) — 标记视频起始位置的 Token ID。 - frame_end_token_id (
int,可选,默认为 151944) — 标记视频结束的 Token ID。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - tie_word_embeddings (
bool,可选,默认为False) — 是否应绑定模型的输入和输出词嵌入。 - image_low_res_id (
int,可选,默认为 151942) — 低分辨率图像标记的 Token ID。 - point_patch_id (
int,可选,默认为 151950) — 定位头在此 Token ID 之后选择一个池化 patch 进行指向(或结束点列表)。 - point_subpatch_id (
int,可选,默认为 151951) — 定位头在选定的池化 patch 之后,用于选择该 patch 内子 patch 的 Token ID。 - point_loc_id (
int,可选,默认为 151952) — 该 Token ID 之后,grounding head 会在选定的 ViT patch 内选择一个位置。 - seg_mask_id (
int,可选,默认为 151953) — 在此 Token ID 之后,grounding head 会预测围绕所选 pooled patch 的分割掩码。 - center_patch_id (
int,可选,默认为 151954) — 类似于point_patch_id的 Token ID,用于一个永远不会结束点列表的点。 - point_query_dims (
list[int],可选,默认为[512, 512, 32]) — 用于池化补丁、子补丁和位置的 grounding head 查询和键的维度。 - subpatch_location_size (
int,可选,默认为 4) — 每个子补丁(一个 ViT 补丁)内定位点方形网格的边长。 - subpatch_hidden_size (
int, 可选, 默认为 512) — 定位头中 ViT 补丁特征的隐藏层大小。 - subpatch_conv_kernel (
int,可选,默认为 3) — 用于将每个 ViT patch 与其相邻 patch 进行卷积混合的卷积核大小。 - mask_diffusion_steps (
int,可选,默认为 2) — 用于平滑分割掩码 logits 的扩散步数。 - presence_threshold (
float, 可选,默认值为 0.5) — 定位头必须分配给池化 patch 的概率质量(而非结束列表),以便新的点或掩码列表选择该 patch。低于此阈值时,列表会立即结束。已经选择了 patch 的列表通过普通的 argmax 结束。 - rope_parameters (
dict, 可选) — RoPE 参数,以"grounding"为键,对应 grounding 头中池化 patch 位置的参数;以"patch_position"为键,对应 ViT patch 的 (time, row, column) 坐标参数。默认值分别为{"rope_type": "default", "rope_theta": 50000.0}和{"rope_type": "default", "rope_theta": 10000.0}。文本注意力使用text_config.rope_parameters。 - patch_position_embedding_size (
int, 可选,默认为 512) — ViT 补丁的 (time, row, column) 坐标各自的正弦嵌入的大小。
这是用于存储 Molmo3Model 配置的类。它根据指定的参数实例化 Molmo3 模型,并定义模型架构。使用默认值实例化配置将生成与 allenai/Molmo3-4B 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
Molmo3VisionConfig
class transformers.Molmo3VisionConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 1152intermediate_size: int = 4304num_hidden_layers: int = 25num_attention_heads: int = 16num_key_value_heads: int = 16head_dim: int = 72hidden_act: str = 'gelu_pytorch_tanh'layer_norm_eps: float = 1e-06image_size: list[int] | None = Nonepatch_size: int = 14num_position_embeddings: int | None = Nonenum_channels: int = 3attention_dropout: float = 0.0attention_bias: bool = Trueinitializer_range: float = 0.02 )
参数
- hidden_size (
int,可选,默认为1152) — 隐藏表示的维度。 - intermediate_size (
int,可选,默认为4304) — MLP 表示的维度。 - num_hidden_layers (
int,可选,默认为25) — Transformer 解码器中的隐藏层数量。 - num_attention_heads (
int,可选,默认为16) — Transformer 解码器中每个注意力层的注意力头数量。 - num_key_value_heads (
int, 可选,默认为16) — 这是用于实现 Grouped Query Attention 的 key_value 头数。如果num_key_value_heads=num_attention_heads,模型将使用 Multi Head Attention (MHA);如果num_key_value_heads=1,模型将使用 Multi Query Attention (MQA);否则将使用 GQA。在将多头检查点转换为 GQA 检查点时,每个组的 key 和 value 头应通过对该组内所有原始头进行平均池化来构建。更多详情请参阅 这篇论文。如果未指定,则默认为num_attention_heads。 - head_dim (
int,可选,默认为72) — 注意力头维度。如果为 None,则默认为 hidden_size // num_attention_heads - hidden_act (
str,可选,默认为gelu_pytorch_tanh) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - layer_norm_eps (
float,可选,默认为1e-06) — 层归一化层所使用的 epsilon 值。 - image_size (
list[int],可选) — 输入图像尺寸,格式为 (height, width),未提供时默认为[378, 378]。 - patch_size (
int,可选,默认为14) — 每个 patch 的大小(分辨率)。 - num_position_embeddings (
int, 可选) — 位置嵌入的数量,每个图像块对应一个。如果未提供,则根据image_size和patch_size推导得出。 - num_channels (
int,可选,默认为3) — 输入通道的数量。 - attention_dropout (
float,可选,默认为0.0) — 注意力概率的 dropout 比率。 - attention_bias (
bool,可选,默认为True) — 在自注意力机制中,是否在查询、键、值以及输出投影层中使用偏置。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
这是用于存储 Molmo3Model 配置的类。它根据指定的参数实例化 Molmo3 模型,并定义模型架构。使用默认值实例化配置将生成与 allenai/Molmo3-4B 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
Molmo3AdapterConfig
class transformers.Molmo3AdapterConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevision_feature_layer: list[int] | None = Nonehidden_size: int = 1152num_attention_heads: int = 16num_key_value_heads: int = 16head_dim: int = 72attention_dropout: float = 0.0attention_bias: bool = Truehidden_act: str = 'silu'intermediate_size: int = 9728text_hidden_size: int = 2560mlp_bias: bool = Falseinitializer_range: float = 0.02num_pooling_positions: int = 9 )
参数
- vision_feature_layer (
list[int], 可选) — 用于拼接和池化的 ViT 层输出的索引,未提供时默认为[24, 18]。负索引从最后一层开始计数。 - hidden_size (
int,可选,默认为1152) — 隐藏表示的维度。 - num_attention_heads (
int,可选,默认为16) — Transformer 解码器中每个注意力层的注意力头数量。 - num_key_value_heads (
int, 可选,默认为16) — 这是用于实现 Grouped Query Attention 的 key_value 头数。如果num_key_value_heads=num_attention_heads,模型将使用 Multi Head Attention (MHA);如果num_key_value_heads=1,模型将使用 Multi Query Attention (MQA);否则将使用 GQA。在将多头检查点转换为 GQA 检查点时,每个组的 key 和 value 头应通过对该组内所有原始头进行平均池化来构建。更多详情请参阅 这篇论文。如果未指定,则默认为num_attention_heads。 - head_dim (
int,可选,默认为72) — 注意力头维度。如果为 None,则默认为 hidden_size // num_attention_heads - attention_dropout (
float,可选,默认为0.0) — 注意力概率的 dropout 比率。 - attention_bias (
bool,可选,默认为True) — 在自注意力机制中,是否在查询、键、值以及输出投影层中使用偏置。 - hidden_act (
str,可选,默认为silu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - intermediate_size (
int,可选,默认为9728) — MLP 表示的维度。 - text_hidden_size (
int,可选,默认为 2560) — 文本模型的隐藏层大小(用于投影)。 - mlp_bias (
bool,可选,默认为False) — 是否在 MLP 层的 up_proj、down_proj 和 gate_proj 层中使用偏置。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - num_pooling_positions (
int, 可选,默认为 9) — 池化窗口(对于视频为 3x3)中槽位的可学习位置嵌入数量。
这是用于存储 Molmo3Model 配置的类。它根据指定的参数实例化 Molmo3 模型,并定义模型架构。使用默认值实例化配置将生成与 allenai/Molmo3-4B 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
Molmo3TextConfig
class transformers.Molmo3TextConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 2560num_attention_heads: int = 32num_key_value_heads: int = 8head_dim: int = 128vocab_size: int = 152064attention_bias: bool = Falseqk_norm_type: str = 'qwen3'num_hidden_layers: int = 36intermediate_size: int = 9728hidden_act: str = 'silu'attention_dropout: float = 0.0max_position_embeddings: int = 16384rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Nonerms_norm_eps: float = 1e-06initializer_range: float = 0.02use_cache: bool = Truetie_word_embeddings: bool = False )
参数
- hidden_size (
int,可选,默认为2560) — 隐藏表示的维度。 - num_attention_heads (
int,可选,默认为32) — Transformer 解码器中每个注意力层的注意力头数量。 - num_key_value_heads (
int, 可选,默认为8) — 这是用于实现 Grouped Query Attention 的 key_value 头数。如果num_key_value_heads=num_attention_heads,模型将使用 Multi Head Attention (MHA);如果num_key_value_heads=1,模型将使用 Multi Query Attention (MQA);否则使用 GQA。在将多头检查点转换为 GQA 检查点时,每个组的 key 和 value 头应通过对该组内所有原始头进行 meanpooling 来构建。更多详情请参阅 这篇论文。如果未指定,则默认为num_attention_heads。 - head_dim (
int,可选,默认为128) — 注意力头维度。如果为 None,则默认为 hidden_size // num_attention_heads - vocab_size (
int,可选,默认为152064) — 模型的词汇表大小。定义了input_ids可以表示的不同 token 数量。 - attention_bias (
bool,可选,默认为False) — 在自注意力机制中,是否在 query、key、value 和 output 投影层中使用偏置。 - qk_norm_type (
str, 可选,默认为"qwen3") — 检查点所使用的查询/键归一化布局。"qwen3"按头进行归一化;"olmo"对完整的投影后的查询/键张量进行归一化。 - num_hidden_layers (
int,可选,默认为36) — Transformer 解码器中的隐藏层数量。 - intermediate_size (
int,可选,默认为9728) — MLP 表示的维度。 - hidden_act (
str,可选,默认为silu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - attention_dropout (
float,可选,默认为0.0) — 注意力概率的 dropout 比率。 - max_position_embeddings (
int,可选,默认为16384) — 该模型可能使用的最大序列长度。 - rope_parameters (
Union[~modeling_rope_utils.RopeParameters, dict], 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含rope_theta的值,并且如果希望使用 RoPE 处理更长的max_position_embeddings,则可选地包含用于缩放的参数。 - rms_norm_eps (
float,可选,默认为1e-06) — RMS 归一化层使用的 epsilon 值。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - use_cache (
bool,可选,默认为True) — 模型是否应返回最后一次键/值注意力(并非所有模型都使用)。仅当config.is_decoder=True或模型为仅解码器生成式模型时相关。 - tie_word_embeddings (
bool,可选,默认为False) — 是否根据模型的tied_weights_keys映射来绑定权重嵌入。
这是用于存储 Molmo3Model 配置的类。它根据指定的参数实例化 Molmo3 模型,并定义模型架构。使用默认值实例化配置将生成与 allenai/Molmo3-4B 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
Molmo3Processor
class transformers.Molmo3Processor
< source >( image_processor = Nonevideo_processor = Nonetokenizer = Nonechat_template: str | None = Nonesubpatch_location_size: int = 4**kwargs )
参数
- image_processor (
Molmo2ImageProcessor) — 图像处理器是必需的输入。 - video_processor (
Molmo3VideoProcessor) — 视频处理器是必需的输入。 - tokenizer (
tokenizer_class) — 分词器是必需的输入。 - chat_template (
str, 可选) — 一个 Jinja 模板,用于将聊天中的消息列表转换为可分词的字符串。 - subpatch_location_size (
int, 可选,默认为 4) — 每个子补丁(一个 ViT 补丁)内定位点方形网格的边长,与 Molmo3Config 中的定义一致。
构造一个 Molmo3Processor,它将图像处理器、视频处理器和分词器封装为单一处理器。
Molmo3Processor 提供了 Molmo2ImageProcessor、Molmo3VideoProcessor 和 tokenizer_class 的所有功能。有关更多信息,请参阅 ~Molmo2ImageProcessor、~Molmo3VideoProcessor 和 ~tokenizer_class。
__call__
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonetext: str | list[str] | list[list[str]] | None = Nonevideos: 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] = Nonegrounding: list[list[dict]] | None = None**kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'> ) → ~image_processing_base.BatchFeature
参数
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], 可选) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False。 - text (
Union[str, list[str], list[list[str]]],可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果传入预分词输入,请设置is_split_into_words=True,以避免与批量输入产生歧义。 - 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]]], 可选) — 要预处理的视频。期望输入单个视频或一批视频,其像素值范围为 0 到 255。如果传入的像素值在 0 到 1 之间,请设置do_rescale=False。 - grounding (
list[list[dict]],可选) — 对于每段文本,其点和掩码按顺序指向的内容。每个条目都是先前某个答案的grounding,即 parse_response() 在消息中存储的形式({"point_indices", "mask_indices"}),或者是points块的内容({"coordinates": [{"mm_ix", "x", "y"}, ...]},以原始图像的像素为单位;x_norm和y_norm表示其尺寸的分数,对于视频则使用time代替mm_ix)。apply_chat_template() 会从聊天中收集它们。它们会变成grounding_indices:每个选择位于其 grounding token 之后的位置,其他位置为 -1。 - return_mm_token_type_ids (
bool, kwargs) — 是否返回多模态 token 类型 id,用于指示多模态占位符 token 的位置。 - return_text_replacement_offsets (
bool, kwargs) — 是否返回每个多模态占位符及其替换内容的字符偏移量。 - return_tensors (
str或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:'pt':返回 PyTorchtorch.Tensor对象。'np':返回 NumPynp.ndarray对象。
- **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。
返回值
~image_processing_base.BatchFeature
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。 - tensor_type (
Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
post_process_grounding
< source >( generated_idsgroundinginputs: BatchFeaturetarget_sizes: list[list[tuple[int, int]]] | None = Nonevideo_metadata: list[transformers.video_utils.VideoMetadata] | None = Nonemask_threshold: float = 0.5 ) → list[list[dict]]
参数
- generated_ids(
torch.Tensor或list[list[int]])— 每个序列生成的 token id,不包含提示词。 - grounding (
list[Molmo3GroundingOutput]) — 每个序列的 grounding,来自generate(..., return_dict_in_generate=True).grounding。 - inputs (BatchFeature) — 处理器输出的序列生成来源。
- target_sizes (
list[list[tuple[int, int]]], 可选) — 每个提示词中每张图片或视频的(height, width),按占位符顺序排列。坐标以该尺寸的像素为单位,掩码也具有该尺寸。如果未提供,坐标则为该尺寸的分数,取值范围为[0, 1],且掩码具有 grounding head 的分辨率。 - video_metadata (
list[VideoMetadata], 可选) — 每个视频的元数据,即处理器在return_metadata=True时返回的内容。对于包含视频的提示,此项为必填。 - mask_threshold (
float,可选,默认值为 0.5) — 像素属于掩码的概率阈值。
返回值
list[list[dict]]
对于每个序列,其答案中的每个 grounding 标签对应一个字典,按文本顺序排列,包含其 type、其 label(标签所包围的文本,如果有的话)以及该类型的张量。模型文档中列出了这些类型及其字段。
将生成序列中的点、掩码和 3D 框解码为坐标。
parse_response
< source >( responseschema: dict | None = Noneprefix = Nonetools: list[dict | collections.abc.Callable] | None = Nonegrounding = None )
与 parse_response() 相同,并移除答案被截断时所在的 grounding 标签。对于答案的 grounding(Molmo3GroundingOutput,或批处理时为其列表),该消息还以普通列表的形式保存其点和掩码的索引({"point_indices", "mask_indices"}),apply_chat_template() 会将这些索引传回给模型。
Molmo3VideoProcessor
class transformers.Molmo3VideoProcessor
< source >( **kwargs: *<class 'transformers.models.molmo3.video_processing_molmo3.Molmo3VideoProcessorKwargs'> )
参数
- do_convert_rgb (
bool,kwargs,可选,默认为True) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选,默认为True) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为{'height' -- 378, 'width': 378}): 描述输入到模型的最大尺寸。 - default_to_square (
bool,kwargs,可选,默认为True) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为2) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时才会生效。 - do_rescale (
bool,kwargs,可选,默认为True) — 是否对图像进行重新缩放。 - rescale_factor (
float,kwargs,可选,默认为0.00392156862745098) — 当do_rescale设置为True时,用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选,默认为True) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.5, 0.5, 0.5]) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.5, 0.5, 0.5]) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - do_sample_frames (
bool,kwargs,可选,默认为True) — 是否在处理前从视频中采样帧,还是处理整个视频。 - video_metadata (
Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None], kwargs) — 视频的元数据,包含总时长、帧率(fps)和总帧数等信息。该元数据将用于从视频中采样帧或计算时间戳。除非您打算在预处理之前手动解码视频,否则请勿传入任何元数据。 - fps (
Annotated[int | float | None, None], kwargs) — 当do_sample_frames=True时,每秒要采样的目标帧数。 - num_frames (
Annotated[int | None, None], kwargs,默认为128) — 当do_sample_frames=True时,采样的最大帧数。 - return_metadata (
bool,kwargs,可选,默认为False) — 是否返回视频元数据。视频元数据是一个包含视频时长、帧率、解码后端等信息的对象。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置,将返回特定框架的张量。可接受的值为:'pt':返回 PyTorchtorch.Tensor对象。'np':返回 NumPynp.ndarray对象。
- patch_size (
int, kwargs, 可选) — 视频帧中每个 ViT patch 的边长(以像素为单位)。 - pooling_size (
list[int],kwargs,可选) —[pool_h, pool_w]应用于视频 patch 特征的池化窗口。 - max_fps (
int, kwargs, 可选) — 短视频的最大采样率,单位为每秒帧数。 - **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。
构建一个 Molmo3VideoProcessor 视频处理器。
Molmo3Model
class transformers.Molmo3Model
< source >( config: Molmo3Config )
参数
- config (Molmo3Config) — 包含模型所有参数的模型配置类。使用配置文件进行初始化不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
Molmo3 模型由视觉骨干网络、池化适配器、语言模型和定位头组成,不包含语言建模头。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Noneimage_token_pooling: typing.Optional[torch.Tensor] = Noneimage_grids: typing.Optional[torch.Tensor] = Noneimage_num_crops: typing.Optional[torch.Tensor] = Noneimage_position_ids: typing.Optional[torch.Tensor] = Nonegrounding_indices: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = Nonecache: transformers.cache_utils.Cache | None = Nonemm_token_type_ids: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = Nonemm_encoder_outputs: dict[str, transformers.models.molmo3.modeling_molmo3.Molmo3ImageFeaturesOutput] | None = Nonegrounding_state: transformers.models.molmo3.generation_molmo3.Molmo3GroundingState | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Molmo3ModelOutputWithPast or tuple(torch.Tensor)
参数
- input_ids (
torch.LongTensor形状为(batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- pixel_values(形状为
(batch_size, num_channels, image_size, image_size)的torch.Tensor,可选) — 与输入图像对应的张量。可以使用image_processor_class获取像素值。有关详细信息,请参阅image_processor_class.__call__(processor_class使用image_processor_class来处理图像)。 - image_token_pooling(形状为
(num_image_tokens, pool_h * pool_w)的torch.Tensor,可选)— 每个池化图像令牌从各自图像的展平补丁序列中收集的索引,其中-1表示填充槽位。可通过 AutoProcessor 获取。详情请参见 ProcessorMixin.call()。 - image_grids(形状为
(num_images, 4)的torch.Tensor,可选) — 每张图像的[low_res_h, low_res_w, high_res_h, high_res_w]池化 token 网格。可通过 AutoProcessor 获取。有关详细信息,请参阅 ProcessorMixin.call()。 - image_num_crops (
torch.Tensor,形状为(num_images,),可选) — 每张图片的裁剪数量,包含低分辨率视图。当处理多张图片时必填。可通过 AutoProcessor 获取。详情请参见 ProcessorMixin.call()。 - image_position_ids (
torch.Tensor,形状为(num_crops, num_patches, 3),可选) — 图像裁剪或视频帧中每个 ViT patch 的(时间,行,列)位置。 - grounding_indices (
torch.LongTensor,形状为(batch_size, sequence_length, 3),可选) — 每个位置之前由 grounding token 选中的(pooled_patch_index, subpatch_index, location), 其余位置为 -1(参见Molmo3GroundingEmbedding.forward)。每个选中的值会加到其对应位置的嵌入上。处理器会为提示中的点和掩码计算这些值。 - attention_mask (
torch.Tensor形状为(batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自[0, 1]:- 1 表示未被屏蔽的 token,
- 对于被掩码的 token,值为 0。
- position_ids (
torch.Tensor形状为(batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为[0, config.n_positions - 1]. - cache (
~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由cache在解码的先前阶段返回,当use_cache=True或config.use_cache=True.仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入
cache,则默认会初始化 DynamicCache。模型将输出与输入相同的缓存格式。
如果使用
cache,用户应仅输入未处理的input_ids(即未向该模型提供其过去键值状态的那些),其形状为(batch_size, unprocessed_length),而不是形状为(batch_size, sequence_length)的所有input_ids。 - mm_token_type_ids (
torch.LongTensor,形状为(batch_size, sequence_length),可选) — 输入序列中匹配每种模态的 token 索引。例如文本 (0)、图像 (1)、视频 (2)。 可通过 AutoProcessor 获取多模态 token 类型 id。详情请参见 ProcessorMixin.call()。 - inputs_embeds(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入input_ids。如果您希望对input_ids索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。 - use_cache (
bool, 可选) — 如果设置为True,则会返回cache键值状态,可用于加速解码(参见cache)。 - mm_encoder_outputs (
dict[str, ~models.molmo3.modeling_molmo3.Molmo3ImageFeaturesOutput], 可选) — 一个字典,其中键为支持的模态,值为该模态的编码输出。每个编码输出是一个元组,由 (pooler_output, 可选:last_hidden_states, 可选:hidden_states, 可选:attentions)pooler_output形状为(batch_size, sequence_length, hidden_size), 可选) 组成,它是编码器生成的多模态特征序列,已合并到文本嵌入中。 - grounding_state (
Molmo3GroundingState,可选) — 生成过程中的指向和分割状态,由 generate() 创建。 前向传播返回预填充阶段的 grounding 图像特征以及最后一个 token 的查询。
返回值
Molmo3ModelOutputWithPast 或 tuple(torch.Tensor)
Molmo3ModelOutputWithPast 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(None)和输入。
Molmo3Model 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
- last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.FloatTensor)— 语言模型主干最后一层输出的隐藏状态序列。 如果使用cache,则仅输出形状为(batch_size, 1, hidden_size)的序列最后一个隐藏状态。 - cache (
Cache,可选,在传入use_cache=True或config.use_cache=True时返回) — 它是一个 Cache 实例。有关更多详细信息,请参阅我们的 kv cache 指南。 包含预计算的隐藏状态(自注意力块中的键和值,以及如果config.is_encoder_decoder=True则还包括交叉注意力块中的键和值),可用于(参见cache输入)加速顺序解码。 - hidden_states (
tuple(torch.FloatTensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.FloatTensor元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为(batch_size, sequence_length, hidden_size)。 语言模型主干在每一层输出处的隐藏状态,以及可选的初始嵌入输出。 - attentions (
tuple(torch.FloatTensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.FloatTensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。语言模型主干的注意力权重,位于注意力 softmax 之后。 - image_outputs(
BaseModelOutputWithPooling,可选)— 图像编码器的输出:last_hidden_state、pooler_output、hidden_states和attentions。如果未处理任何图像,则为None。 - video_outputs(
BaseModelOutputWithPooling,可选)— 视频编码器的输出:last_hidden_state、pooler_output、hidden_states和attentions。如果未处理任何视频,则为None。 - audio_outputs(
BaseModelOutputWithPooling,可选)— 音频编码器的输出:last_hidden_state、pooler_output、hidden_states和attentions。如果未处理任何音频,则为None。 - grounding_outputs (
Molmo3GroundingModelOutput,可选) — 当传入grounding_state时,grounding 模块的输出。
Molmo3TextModel
class transformers.Molmo3TextModel
< source >( config: Molmo3TextConfig )
参数
- config (Molmo3TextConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
未附加任何特定头部的裸 Molmo3 文本模型,直接输出原始隐藏状态。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Molmo3TextModelOutputWithPast or tuple(torch.Tensor)
参数
- input_ids (
torch.LongTensor形状为(batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor形状为(batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自[0, 1]:- 1 表示未被屏蔽的 token,
- 对于被掩码的 token,值为 0。
- position_ids (
torch.LongTensor形状为(batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为[0, config.n_positions - 1]. - cache (
~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由cache在解码的先前阶段返回,当use_cache=True或config.use_cache=True.仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入
cache,则默认会初始化 DynamicCache。模型将输出与输入相同的缓存格式。
如果使用
cache,用户应仅输入未处理的input_ids(即未向该模型提供其过去键值状态的那些),其形状为(batch_size, unprocessed_length),而不是形状为(batch_size, sequence_length)的所有input_ids。 - inputs_embeds (
torch.FloatTensor,形状为(batch_size, sequence_length, hidden_size),可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入input_ids。如果您希望对input_ids索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。 - use_cache (
bool, 可选) — 如果设置为True,则会返回cache键值状态,可用于加速解码(参见cache)。
返回值
Molmo3TextModelOutputWithPast 或 tuple(torch.Tensor)
Molmo3TextModelOutputWithPast 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(None)和输入。
Molmo3TextModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor)— 模型最后一层输出的隐藏状态序列。如果使用了
cache,则仅输出形状为(batch_size, 1, hidden_size)的序列的最后一个隐藏状态。cache(
Cache,可选,在传入use_cache=True或config.use_cache=True时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。包含预计算的隐藏状态(自注意力块中的键和值,以及如果
config.is_encoder_decoder=True则还包括交叉注意力块中的键和值),可用于(参见cache输入)加速顺序解码。hidden_states (
tuple(torch.Tensor),可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
pre_norm_last_hidden_state (
torch.FloatTensor,形状为(batch_size, sequence_length, hidden_size),可选) — 最后一个解码器层的输出,位于最终归一化之前。
Molmo3Adapter
class transformers.Molmo3Adapter
< source >( config: Molmo3AdapterConfig )
参数
- config (Molmo3AdapterConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
使用单查询注意力层对 ViT 的 patch 特征进行池化,并将其投影到语言模型的嵌入空间中。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( image_features: Tensorpooled_patches_idx: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutput or tuple(torch.Tensor)
参数
- image_features(形状为
(num_crops, num_patches, hidden_size * len(vision_feature_layer))的torch.Tensor)— 所有裁剪区域的中间 ViT 特征的拼接结果,包含其 patch 位置嵌入。 - pooled_patches_idx(形状为
(num_tokens, pool_h * pool_w)的torch.Tensor)— 每个输出 token 所池化的展平 patch 序列中的索引;-1表示填充槽位。
返回值
BaseModelOutput 或 tuple(torch.Tensor)
一个 BaseModelOutput 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Molmo3Config)和输入。
Molmo3Adapter 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor)— 模型最后一层输出的隐藏状态序列。hidden_states (
tuple(torch.Tensor),可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
Molmo3VisionModel
class transformers.Molmo3VisionModel
< source >( config: Molmo3VisionConfig )
参数
- config (Molmo3VisionConfig) — 包含模型所有参数的模型配置类。使用配置文件进行初始化不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
未附加任何特定头部的裸 Molmo3 模型,直接输出原始隐藏状态。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用 Molmo2ImageProcessor 获取像素值。有关详细信息,请参阅 Molmo2ImageProcessor.call()(Molmo3Processor 使用 Molmo2ImageProcessor 处理图像)。
返回值
BaseModelOutputWithPooling 或 tuple(torch.Tensor)
一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Molmo3Config)和输入。
Molmo3VisionModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor)— 模型最后一层输出的隐藏状态序列。pooler_output (
torch.Tensor,形状为(batch_size, hidden_size)) — 序列中第一个 token(分类 token)的最后一层隐藏状态,经过用于辅助预训练任务的层进一步处理后得到。例如,对于 BERT 系列模型,这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重在预训练期间通过下一句预测(分类)目标进行训练。hidden_states (
tuple(torch.Tensor),可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
Molmo3ForConditionalGeneration
class transformers.Molmo3ForConditionalGeneration
< source >( config: Molmo3Config )
参数
- config (Molmo3Config) — 包含模型所有参数的模型配置类。使用配置文件进行初始化不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
Molmo3 模型由视觉骨干网络、池化适配器、带有语言建模头的语言模型,以及用于指向和分割的定位头组成。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( input_ids: LongTensor = Nonepixel_values: typing.Optional[torch.Tensor] = Noneimage_token_pooling: typing.Optional[torch.Tensor] = Noneimage_grids: typing.Optional[torch.Tensor] = Noneimage_num_crops: typing.Optional[torch.Tensor] = Noneimage_position_ids: typing.Optional[torch.Tensor] = Nonegrounding_indices: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Nonemm_token_type_ids: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0mm_encoder_outputs: dict[str, transformers.models.molmo3.modeling_molmo3.Molmo3ImageFeaturesOutput] | None = Nonegrounding_state: transformers.models.molmo3.generation_molmo3.Molmo3GroundingState | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Molmo3CausalLMOutputWithPast or tuple(torch.Tensor)
参数
- input_ids (
torch.LongTensor形状为(batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- pixel_values(形状为
(batch_size, num_channels, image_size, image_size)的torch.Tensor,可选) — 与输入图像对应的张量。可以使用image_processor_class获取像素值。有关详细信息,请参阅image_processor_class.__call__(processor_class使用image_processor_class来处理图像)。 - image_token_pooling(形状为
(num_image_tokens, pool_h * pool_w)的torch.Tensor,可选)— 每个池化图像令牌从各自图像的展平补丁序列中收集的索引,其中-1表示填充槽位。可通过 AutoProcessor 获取。详情请参见 ProcessorMixin.call()。 - image_grids(形状为
(num_images, 4)的torch.Tensor,可选) — 每张图像的[low_res_h, low_res_w, high_res_h, high_res_w]池化 token 网格。可通过 AutoProcessor 获取。有关详细信息,请参阅 ProcessorMixin.call()。 - image_num_crops (
torch.Tensor,形状为(num_images,),可选) — 每张图片的裁剪数量,包含低分辨率视图。当处理多张图片时必填。可通过 AutoProcessor 获取。详情请参见 ProcessorMixin.call()。 - image_position_ids (
torch.Tensor,形状为(num_crops, num_patches, 3),可选) — 图像裁剪或视频帧中每个 ViT patch 的(时间,行,列)位置。 - grounding_indices (
torch.LongTensor,形状为(batch_size, sequence_length, 3),可选) — 每个位置之前由 grounding token 选中的(pooled_patch_index, subpatch_index, location), 其余位置为 -1(参见Molmo3GroundingEmbedding.forward)。每个选中的值会加到其对应位置的嵌入上。处理器会为提示中的点和掩码计算这些值。 - attention_mask (
torch.Tensor形状为(batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自[0, 1]:- 1 表示未被屏蔽的 token,
- 对于被掩码的 token,值为 0。
- position_ids (
torch.LongTensor形状为(batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为[0, config.n_positions - 1]. - cache (
~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由cache在解码的先前阶段返回,当use_cache=True或config.use_cache=True.仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入
cache,则默认会初始化 DynamicCache。模型将输出与输入相同的缓存格式。
如果使用
cache,用户应仅输入未处理的input_ids(即未向该模型提供其过去键值状态的那些),其形状为(batch_size, unprocessed_length),而不是形状为(batch_size, sequence_length)的所有input_ids。 - mm_token_type_ids (
torch.LongTensor,形状为(batch_size, sequence_length),可选) — 输入序列中匹配每种模态的 token 索引。例如文本 (0)、图像 (1)、视频 (2)。 可通过 AutoProcessor 获取多模态 token 类型 id。详情请参见 ProcessorMixin.call()。 - inputs_embeds(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入input_ids。如果您希望对input_ids索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。 - labels (
torch.LongTensor,形状为(batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引值应在[0, ..., config.vocab_size]范围内,或为 -100(参见input_ids的文档字符串)。索引值设为-100的 token 将被忽略(即被掩码),损失仅针对标签位于[0, ..., config.vocab_size]范围内的 token 进行计算。 - use_cache (
bool, 可选) — 如果设置为True,则会返回cache键值状态,可用于加速解码(参见cache)。 - logits_to_keep (
Union[int, torch.Tensor], 可选,默认为0) — 如果为int,则计算最后logits_to_keep个 token 的 logits。如果为0,则计算所有input_ids的 logits(特殊情况)。生成过程只需要最后一个 token 的 logits,仅针对该 token 进行计算可以节省内存,对于长序列或大词汇量而言,这种节省相当显著。 如果为torch.Tensor,则必须是一维张量,对应于序列长度维度中需要保留的索引。 这在使用打包张量格式(将批次和序列长度合并为单一维度)时非常有用。 - mm_encoder_outputs (
dict[str, ~models.molmo3.modeling_molmo3.Molmo3ImageFeaturesOutput], 可选) — 一个字典,其中键为支持的模态,值为该模态的编码输出。每个编码输出是一个元组,由 (pooler_output, 可选:last_hidden_states, 可选:hidden_states, 可选:attentions)pooler_output形状为(batch_size, sequence_length, hidden_size), 可选) 组成,它是编码器生成的多模态特征序列,已合并到文本嵌入中。 - grounding_state (
Molmo3GroundingState,可选) — 生成过程中的指向和分割状态,由 generate() 创建。 前向传播在预填充阶段返回 grounding 图像特征,并返回最后一个 token 的查询。 在手动解码循环中,请在应用 logits 处理器或输入下一个 token 之前调用model.update_grounding_state(outputs, grounding_state)。generate会自动执行此操作。
返回值
Molmo3CausalLMOutputWithPast 或 tuple(torch.Tensor)
Molmo3CausalLMOutputWithPast 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(None)和输入。
Molmo3ForConditionalGeneration 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
- loss (
torch.FloatTensor,形状为(1,),可选,在提供labels时返回) — 语言建模损失(用于下一个 token 预测)。 - logits(形状为
(batch_size, sequence_length, config.vocab_size)的torch.FloatTensor)— 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。 - cache (
Cache,可选,在传入use_cache=True或config.use_cache=True时返回) — 它是一个 Cache 实例。有关更多详细信息,请参阅我们的 kv cache 指南。 包含预计算的隐藏状态(自注意力块中的键和值,以及如果config.is_encoder_decoder=True则还包括交叉注意力块中的键和值),可用于(参见cache输入)加速顺序解码。 - hidden_states (
tuple(torch.FloatTensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.FloatTensor元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为(batch_size, sequence_length, hidden_size)。 语言模型主干在每一层输出处的隐藏状态,以及可选的初始嵌入输出。 - attentions (
tuple(torch.FloatTensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.FloatTensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。语言模型主干的注意力权重,位于注意力 softmax 之后。 - image_outputs(
BaseModelOutputWithPooling,可选)— 图像编码器的输出:last_hidden_state、pooler_output、hidden_states和attentions。如果未处理任何图像,则为None。 - video_outputs(
BaseModelOutputWithPooling,可选)— 视频编码器的输出:last_hidden_state、pooler_output、hidden_states和attentions。如果未处理任何视频,则为None。 - audio_outputs(
BaseModelOutputWithPooling,可选)— 音频编码器的输出:last_hidden_state、pooler_output、hidden_states和attentions。如果未处理任何音频,则为None。 - grounding_outputs (
Molmo3GroundingModelOutput,可选) — 当传入grounding_state时,grounding 模块的输出。
示例:
>>> 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()。当 return_dict_in_generate=True 时,输出还包含 grounding,
每个序列对应一个 Molmo3GroundingOutput,Molmo3Processor.post_process_grounding() 会将其转换为
坐标和掩码。
对于图像或视频,grounding head 会在解码步骤之间为每个序列维护状态,因此不支持 beam search、num_return_sequences > 1、辅助解码以及无缓存解码,并且 inputs_embeds 必须与其对应的 input_ids 一起提供。
Molmo3GroundingOutput
class transformers.models.molmo3.generation_molmo3.Molmo3GroundingOutput
< source >( point_indices: list[torch.LongTensor]mask_indices: list[torch.LongTensor] | None = Nonemask_scores: list[torch.Tensor] | None = Nonegrounding_end_prob: typing.Optional[torch.Tensor] = None )
参数
- point_indices (
list[torch.LongTensor]) — 每个生成的点对应一个形状为(3,)的(pooled_patch_index, subpatch_index, location)张量,其索引方式与grounding_indices相同。 - mask_indices (
list[torch.LongTensor]) — 每个生成的分割掩码所锚定的池化块的 pooled_patch_index,表示为 0 维张量。 - mask_scores (
list[torch.Tensor]) — 每个生成的分割掩码对应一个形状为(num_image_tokens, num_subpatches, subpatch_location_size**2)的掩码概率张量(-1表示该位置不可选)。每个图像 token 拥有num_subpatches个用于存放 ViT patch 的槽位。每个 subpatch 包含一个边长为subpatch_location_size的方形位置网格。 - grounding_end_prob (
torch.Tensor, 可选) — Softmax 概率,以 0 维张量的形式表示,即 grounding 头在从当前点或掩码序列中结束并选择另一个图像块之前所分配的概率。在生成的每个序列中记录一次,位于第一个<|POINT_PATCH|>处,且在应用块选择规则之前。在处理之前为None。
一条生成序列的接地。
Molmo3GroundingLogitsProcessor
class transformers.models.molmo3.generation_molmo3.Molmo3GroundingLogitsProcessor
< source >( configgrounding_state: Molmo3GroundingStatedevice: typing.Union[torch.device, str, NoneType] = None )
LogitsProcessor 用于约束 Molmo3ForConditionalGeneration 中每个 grounding token 之后的 token,
其约束范围来自 grounding head 在最新生成步骤中记录在 grounding_state 中的候选项:
- 在选择了池化 patch 的 patch token 之后,仅允许使用 grounding token
- 在结束列表的补丁标记之后,不允许出现任何定位标记
<|POINT_SUBPATCH|>之后总是跟随<|POINT_LOC|>- 中心点(
<|CENTER_PATCH|>…<|POINT_LOC|>)后面没有跟随另一个<|CENTER_PATCH|> <|SEG_MASK|>、<|POINT_SUBPATCH|>和<|POINT_LOC|>仅跟随 grounding token。