Add molmo3 model to MLX (#20126)

This commit is contained in:
Patrick Devine authored and GitHub committed 2026-12-03 08:46:00 -08:00
1 parent 83931ae4ee
commit b5f0eb268c
30 files changed
+2913

No files matched your search

+1
View File
@@ -449,6 +449,7 @@ var tensorImportTransformRegistry = map[string]tensorImportTransformFactory{
"gemma4_unified_text": newGemma4ImportTransform,
"LagunaForCausalLM": newLagunaImportTransform,
"MuseGlimmerForConditionalGeneration": newGlimmerImportTransform,
"Molmo3ForConditionalGeneration": newMolmo3ImportTransform,
"Cohere2MoeForCausalLM": newCohere2MoeImportTransform,
"Gemma4AssistantForCausalLM": newGemma4ImportTransform,
"Gemma4UnifiedAssistantForCausalLM": newGemma4ImportTransform,
+2
View File
@@ -336,6 +336,8 @@ func rendererNameForIdentifier(modelDir, s, chatTemplate string) (string, error)
return lagunaRendererParserNameFromTemplate(modelDir, chatTemplate)
case strings.Contains(s, "cohere2moe") || strings.Contains(s, "cohere2_moe"):
return "cohere", nil
case strings.Contains(s, "molmo3"):
return "molmo3", nil
case strings.Contains(s, "gemma4"):
return "gemma4", nil
case strings.Contains(s, "glm4") || strings.Contains(s, "glm-4"):
+14
View File
@@ -42,6 +42,20 @@ func TestDetectSafetensorsCapabilities(t *testing.T) {
}
}
func TestMolmo3Metadata(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(`{"architectures":["Molmo3ForConditionalGeneration"],"model_type":"molmo3","vision_config":{}}`), 0o644); err != nil {
t.Fatal(err)
}
got := inferConfigForTest(t, dir, "", "")
if got.Parser != "" || got.Renderer != "molmo3" {
t.Fatalf("parser/renderer = %q/%q, want empty/molmo3", got.Parser, got.Renderer)
}
if want := []string{"completion", "vision"}; !slices.Equal(got.Capabilities, want) {
t.Fatalf("capabilities = %v, want %v", got.Capabilities, want)
}
}
func TestInferSafetensorsConfigAppliesOverrides(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(`{"architectures":["Qwen3ForCausalLM"]}`), 0o644); err != nil {
+19
View File
@@ -0,0 +1,19 @@
package create
import (
"encoding/json"
"strings"
)
type molmo3ImportTransform struct{}
func newMolmo3ImportTransform(json.RawMessage) (quantizePolicy, error) {
return molmo3ImportTransform{}, nil
}
func (molmo3ImportTransform) quantizationType(name string, shape []int32, requested string) string {
if strings.HasPrefix(name, "model.vit.") || strings.HasPrefix(name, "model.connector.") {
return ""
}
return GetTensorQuantization(name, shape, requested)
}
+43
View File
@@ -0,0 +1,43 @@
package create
import "testing"
func TestMolmo3PlanKeepsVisionDense(t *testing.T) {
const (
vit = "model.vit.transformer.resblocks.0.attention.wq.weight"
connector = "model.connector.image_pooling_2d.wq.weight"
text = "model.transformer.blocks.0.att_proj.weight"
)
inv := Inventory{
Config: sourceModelConfig{Architectures: []string{"Molmo3ForConditionalGeneration"}},
Tensors: map[string]SourceTensor{
vit: {Name: vit, Dtype: "BF16", Shape: []int32{1152, 1152}},
connector: {Name: connector, Dtype: "BF16", Shape: []int32{1152, 2304}},
text: {Name: text, Dtype: "BF16", Shape: []int32{6144, 2560}},
},
}
policy, err := newTensorImportTransform(inv)
if err != nil {
t.Fatal(err)
}
for _, requested := range []string{"nvfp4", "mxfp8", "int4"} {
t.Run(requested, func(t *testing.T) {
specs, err := Plan(inv, Classification{Kind: SourceFloat, Quantize: requested}, policy)
if err != nil {
t.Fatal(err)
}
got := make(map[string]string)
for _, spec := range specs {
got[spec.Name] = spec.Tensors[0].Quantize
}
for _, name := range []string{vit, connector} {
if got[name] != "" {
t.Errorf("%s quantize = %q, want source precision", name, got[name])
}
}
if want := GetTensorQuantization(text, inv.Tensors[text].Shape, requested); got[text] != want || want == "" {
t.Errorf("text quantize = %q, want generic policy %q", got[text], want)
}
})
}
}
+73
View File
@@ -0,0 +1,73 @@
package create
import (
"bytes"
"context"
"path/filepath"
"slices"
"testing"
st "github.com/ollama/ollama/fs/safetensors"
"github.com/ollama/ollama/mlx/mlxtest"
)
func TestWriteBlobsMolmo3KeepsVisionDense(t *testing.T) {
mlxtest.SkipIfUnavailable(t)
const (
vit = "model.vit.transformer.resblocks.0.attention.wq.weight"
connector = "model.connector.image_pooling_2d.wq.weight"
text = "model.transformer.blocks.0.att_proj.weight"
)
dir := t.TempDir()
writeConfigJSON(t, dir, `{"architectures":["Molmo3ForConditionalGeneration"]}`)
vitBytes := bytes.Repeat([]byte{0x42, 0x3f}, 32*32)
connectorBytes := bytes.Repeat([]byte{0x77, 0x3f}, 32*64)
createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{
st.NewTensorDataFromBytes(vit, "BF16", []int32{32, 32}, vitBytes),
st.NewTensorDataFromBytes(connector, "BF16", []int32{32, 64}, connectorBytes),
st.NewTensorDataFromBytes(text, "BF16", []int32{128, 128}, make([]byte, 128*128*2)),
})
inv, err := ReadInventory(dir)
if err != nil {
t.Fatal(err)
}
policy, err := newTensorImportTransform(inv)
if err != nil {
t.Fatal(err)
}
specs, err := Plan(inv, Classification{Kind: SourceFloat, Quantize: "nvfp4"}, policy)
if err != nil {
t.Fatal(err)
}
store := newCaptureStore()
if _, err := WriteBlobs(context.Background(), specs, dir, store); err != nil {
t.Fatal(err)
}
for name, want := range map[string][]byte{vit: vitBytes, connector: connectorBytes} {
blob, ok := store.blobs[name]
if !ok {
t.Fatalf("missing dense blob %s", name)
}
header := blobHeader(t, blob)
if got := header[name]; got.Dtype != "BF16" || !slices.Equal(got.Shape, inv.Tensors[name].Shape) {
t.Errorf("%s header = %+v, want source BF16 shape", name, got)
}
if _, ok := header[name+".scale"]; ok {
t.Errorf("%s has a quantization scale", name)
}
if got := readPackedTensorRaw(t, blob, name); !bytes.Equal(got, want) {
t.Errorf("%s payload differs from source", name)
}
}
blob, ok := store.blobs[text]
if !ok {
t.Fatal("missing text projection blob")
}
header := blobHeader(t, blob)
if header[text].Dtype != "U32" {
t.Errorf("text projection dtype = %q, want U32", header[text].Dtype)
}
if _, ok := header[text+".scale"]; !ok {
t.Error("text projection missing scale")
}
}
@@ -18,6 +18,7 @@ import (
_ "github.com/ollama/ollama/mlxrunner/model/laya"
_ "github.com/ollama/ollama/mlxrunner/model/lfm3"
_ "github.com/ollama/ollama/mlxrunner/model/llama"
_ "github.com/ollama/ollama/mlxrunner/model/molmo3"
_ "github.com/ollama/ollama/mlxrunner/model/nemotron_h"
_ "github.com/ollama/ollama/mlxrunner/model/phonon"
_ "github.com/ollama/ollama/mlxrunner/model/qwen3"
@@ -0,0 +1,13 @@
package architectures
import (
"testing"
"github.com/ollama/ollama/mlxrunner/model"
)
func TestMolmo3Registered(t *testing.T) {
if !model.SupportsArchitecture("Molmo3ForConditionalGeneration") {
t.Fatal("Molmo3ForConditionalGeneration is not registered")
}
}
+5
View File
@@ -32,6 +32,11 @@ type Model interface {
MaxContextLength() int
}
// PromptTokenValidator rejects prompt tokens a model cannot consume safely.
type PromptTokenValidator interface {
ValidatePromptToken(int32) error
}
// SkippedTensorsModel identifies checkpoint tensors to exclude from MLX loading.
// Names use the original safetensors namespace, including any quantization
// companions. The model is responsible for accessing any required skipped tensors.
+190
View File
@@ -0,0 +1,190 @@
package molmo3
import "fmt"
// Config holds the checkpoint's multimodal and text configuration.
type Config struct {
TextConfig TextConfig `json:"text_config"`
VisionConfig VisionConfig `json:"vision_config"`
AdapterConfig AdapterConfig `json:"adapter_config"`
ImagePatchID int32 `json:"image_patch_id"`
ImageLowResID int32 `json:"image_low_res_id"`
ImageColID int32 `json:"image_col_id"`
ImageStartTokenID int32 `json:"image_start_token_id"`
LowResImageStartTokenID int32 `json:"low_res_image_start_token_id"`
ImageEndTokenID int32 `json:"image_end_token_id"`
FrameStartTokenID int32 `json:"frame_start_token_id"`
FrameEndTokenID int32 `json:"frame_end_token_id"`
PointPatchID int32 `json:"point_patch_id"`
PointSubpatchID int32 `json:"point_subpatch_id"`
PointLocID int32 `json:"point_loc_id"`
SegMaskID int32 `json:"seg_mask_id"`
CenterPatchID int32 `json:"center_patch_id"`
CorrespondingPatchID int32 `json:"corresponding_patch_id"`
}
// VisionConfig holds the image encoder configuration.
type VisionConfig struct {
HiddenSize int32 `json:"hidden_size"`
IntermediateSize int32 `json:"intermediate_size"`
NumHiddenLayers int32 `json:"num_hidden_layers"`
NumAttentionHeads int32 `json:"num_attention_heads"`
NumKeyValueHeads int32 `json:"num_key_value_heads"`
HeadDim int32 `json:"head_dim"`
NumPositionEmbeddings int32 `json:"num_position_embeddings"`
PatchSize int32 `json:"patch_size"`
ImageSize []int32 `json:"image_size"`
NumChannels int32 `json:"num_channels"`
LayerNormEps float32 `json:"layer_norm_eps"`
HiddenAct string `json:"hidden_act"`
AttentionBias bool `json:"attention_bias"`
}
// AdapterConfig holds the image pooling and projection configuration.
type AdapterConfig struct {
VisionFeatureLayer []int `json:"vision_feature_layer"`
NumAttentionHeads int32 `json:"num_attention_heads"`
NumKeyValueHeads int32 `json:"num_key_value_heads"`
HeadDim int32 `json:"head_dim"`
HiddenSize int32 `json:"hidden_size"`
IntermediateSize int32 `json:"intermediate_size"`
TextHiddenSize int32 `json:"text_hidden_size"`
NumPoolingPositions int32 `json:"num_pooling_positions"`
HiddenAct string `json:"hidden_act"`
AttentionBias bool `json:"attention_bias"`
MLPBias bool `json:"mlp_bias"`
}
// TextConfig holds the Qwen3-style decoder configuration.
type TextConfig struct {
HiddenSize int32 `json:"hidden_size"`
NumHiddenLayers int32 `json:"num_hidden_layers"`
IntermediateSize int32 `json:"intermediate_size"`
NumAttentionHeads int32 `json:"num_attention_heads"`
NumKeyValueHeads int32 `json:"num_key_value_heads"`
HeadDim int32 `json:"head_dim"`
VocabSize int32 `json:"vocab_size"`
RMSNormEps float32 `json:"rms_norm_eps"`
MaxPositionEmbeddings int32 `json:"max_position_embeddings"`
HiddenAct string `json:"hidden_act"`
QKNormType string `json:"qk_norm_type"`
AttentionBias bool `json:"attention_bias"`
TieWordEmbeddings bool `json:"tie_word_embeddings"`
RopeParameters struct {
RopeTheta float32 `json:"rope_theta"`
RopeType string `json:"rope_type"`
} `json:"rope_parameters"`
}
const additionalVocabSize = 128
func (c *Config) validate() error {
if err := c.TextConfig.validate(); err != nil {
return err
}
v, a := &c.VisionConfig, &c.AdapterConfig
if v.HiddenSize == 0 {
return nil
}
if v.IntermediateSize <= 0 || v.NumHiddenLayers <= 0 {
return fmt.Errorf("invalid vision intermediate_size or num_hidden_layers")
}
if v.NumAttentionHeads <= 0 {
return fmt.Errorf("invalid vision num_attention_heads %d", v.NumAttentionHeads)
}
if v.HeadDim <= 0 || v.HiddenSize != v.NumAttentionHeads*v.HeadDim {
return fmt.Errorf("invalid vision head_dim %d for hidden_size %d", v.HeadDim, v.HiddenSize)
}
if v.NumKeyValueHeads != v.NumAttentionHeads {
return fmt.Errorf("unsupported vision num_key_value_heads %d", v.NumKeyValueHeads)
}
if v.HiddenAct != "gelu_pytorch_tanh" {
return fmt.Errorf("unsupported vision hidden_act %q", v.HiddenAct)
}
if !v.AttentionBias {
return fmt.Errorf("unsupported vision attention_bias false")
}
if v.NumChannels != 3 || v.PatchSize <= 0 || len(v.ImageSize) != 2 || v.ImageSize[0] <= 0 || v.ImageSize[1] <= 0 || v.ImageSize[0] != v.ImageSize[1] {
return fmt.Errorf("invalid vision image_size, patch_size, or num_channels")
}
gridSize := v.ImageSize[0] / v.PatchSize
expectedPositions := gridSize * gridSize
if v.NumPositionEmbeddings != expectedPositions {
return fmt.Errorf("invalid vision num_position_embeddings %d, want %d", v.NumPositionEmbeddings, expectedPositions)
}
if v.LayerNormEps <= 0 {
return fmt.Errorf("invalid vision layer_norm_eps %g", v.LayerNormEps)
}
if a.NumAttentionHeads <= 0 || a.HeadDim <= 0 || a.HiddenSize != a.NumAttentionHeads*a.HeadDim {
return fmt.Errorf("invalid adapter num_attention_heads or head_dim")
}
if a.NumKeyValueHeads != a.NumAttentionHeads {
return fmt.Errorf("unsupported adapter num_key_value_heads %d", a.NumKeyValueHeads)
}
if a.HiddenAct != "silu" {
return fmt.Errorf("unsupported adapter hidden_act %q", a.HiddenAct)
}
if !a.AttentionBias {
return fmt.Errorf("unsupported adapter attention_bias false")
}
if a.MLPBias {
return fmt.Errorf("unsupported adapter mlp_bias true")
}
if a.IntermediateSize <= 0 || a.TextHiddenSize != c.TextConfig.HiddenSize {
return fmt.Errorf("invalid adapter intermediate_size or text_hidden_size")
}
if a.NumPoolingPositions != 9 {
return fmt.Errorf("unsupported num_pooling_positions %d", a.NumPoolingPositions)
}
if len(a.VisionFeatureLayer) != 2 || a.VisionFeatureLayer[0] != int(v.NumHiddenLayers-1) ||
a.VisionFeatureLayer[0] <= a.VisionFeatureLayer[1] || a.VisionFeatureLayer[1] < 0 {
return fmt.Errorf("unsupported vision_feature_layer %v", a.VisionFeatureLayer)
}
return nil
}
func (c *TextConfig) baseVocabSize() int32 {
return c.VocabSize - additionalVocabSize
}
func (c *TextConfig) validate() error {
if c.NumHiddenLayers <= 0 {
return fmt.Errorf("invalid num_hidden_layers: %d", c.NumHiddenLayers)
}
if c.HiddenSize <= 0 || c.IntermediateSize <= 0 {
return fmt.Errorf("invalid hidden_size or intermediate_size: %d, %d", c.HiddenSize, c.IntermediateSize)
}
if c.NumAttentionHeads <= 0 || c.HeadDim <= 0 {
return fmt.Errorf("invalid num_attention_heads or head_dim: %d, %d", c.NumAttentionHeads, c.HeadDim)
}
if c.NumKeyValueHeads <= 0 || c.NumAttentionHeads%c.NumKeyValueHeads != 0 {
return fmt.Errorf("invalid num_key_value_heads: %d", c.NumKeyValueHeads)
}
if c.VocabSize <= additionalVocabSize {
return fmt.Errorf("invalid vocab_size: %d", c.VocabSize)
}
if c.MaxPositionEmbeddings <= 0 {
return fmt.Errorf("invalid max_position_embeddings: %d", c.MaxPositionEmbeddings)
}
if c.HiddenAct != "silu" {
return fmt.Errorf("unsupported hidden_act %q", c.HiddenAct)
}
if c.QKNormType != "qwen3" {
return fmt.Errorf("unsupported qk_norm_type %q", c.QKNormType)
}
if c.AttentionBias {
return fmt.Errorf("unsupported attention_bias true")
}
if c.TieWordEmbeddings {
return fmt.Errorf("unsupported tie_word_embeddings true")
}
if c.RopeParameters.RopeType != "default" {
return fmt.Errorf("unsupported rope_type %q", c.RopeParameters.RopeType)
}
if c.RopeParameters.RopeTheta <= 0 {
return fmt.Errorf("invalid rope_theta: %g", c.RopeParameters.RopeTheta)
}
return nil
}
@@ -0,0 +1,98 @@
package molmo3
import (
"encoding/json"
"strings"
"testing"
)
func TestMultimodalConfigValidation(t *testing.T) {
cfg := validMediaConfig(t)
if err := cfg.validate(); err != nil {
t.Fatalf("valid config rejected: %v", err)
}
for _, tc := range []struct {
name string
mutate func(*Config)
want string
}{
{name: "vision activation", mutate: func(c *Config) { c.VisionConfig.HiddenAct = "gelu" }, want: "vision hidden_act"},
{name: "vision attention bias", mutate: func(c *Config) { c.VisionConfig.AttentionBias = false }, want: "vision attention_bias"},
{name: "vision kv heads", mutate: func(c *Config) { c.VisionConfig.NumKeyValueHeads = 1 }, want: "vision num_key_value_heads"},
{name: "vision head width", mutate: func(c *Config) { c.VisionConfig.HeadDim = 5 }, want: "vision head_dim"},
{name: "vision positions", mutate: func(c *Config) { c.VisionConfig.NumPositionEmbeddings = 5 }, want: "num_position_embeddings"},
{name: "rectangular vision grid", mutate: func(c *Config) {
c.VisionConfig.ImageSize = []int32{28, 56}
c.VisionConfig.NumPositionEmbeddings = 8
}, want: "vision image_size"},
{name: "feature order", mutate: func(c *Config) { c.AdapterConfig.VisionFeatureLayer = []int{0, 1} }, want: "vision_feature_layer"},
{name: "missing deepest tap", mutate: func(c *Config) { c.AdapterConfig.VisionFeatureLayer = []int{0, 0} }, want: "vision_feature_layer"},
{name: "adapter activation", mutate: func(c *Config) { c.AdapterConfig.HiddenAct = "gelu" }, want: "adapter hidden_act"},
{name: "adapter attention bias", mutate: func(c *Config) { c.AdapterConfig.AttentionBias = false }, want: "adapter attention_bias"},
{name: "adapter mlp bias", mutate: func(c *Config) { c.AdapterConfig.MLPBias = true }, want: "mlp_bias"},
{name: "adapter pooling", mutate: func(c *Config) { c.AdapterConfig.NumPoolingPositions = 4 }, want: "num_pooling_positions"},
{name: "text width mismatch", mutate: func(c *Config) { c.AdapterConfig.TextHiddenSize = 4 }, want: "text_hidden_size"},
} {
t.Run(tc.name, func(t *testing.T) {
cfg := validMediaConfig(t)
tc.mutate(&cfg)
if err := cfg.validate(); err == nil || !strings.Contains(err.Error(), tc.want) {
t.Fatalf("error = %v, want field %q", err, tc.want)
}
})
}
}
func TestProcessorConfigValidation(t *testing.T) {
valid := []byte(`{"image_processor":{"do_convert_rgb":true,"do_normalize":true,"do_rescale":true,"do_resize":true,"image_mean":[0.5,0.5,0.5],"image_std":[0.5,0.5,0.5],"max_crops":8,"overlap_margins":[4,4],"patch_size":14,"pooling_size":[2,2],"resample":2,"rescale_factor":0.00392156862745098,"size":{"height":378,"width":378}}}`)
if err := validateProcessorConfig(valid); err != nil {
t.Fatalf("valid processor config rejected: %v", err)
}
for _, tc := range []struct{ name, path, want string }{
{name: "max crops", path: `"max_crops":8`, want: "max_crops"},
{name: "pooling", path: `"pooling_size":[2,2]`, want: "pooling_size"},
{name: "patch", path: `"patch_size":14`, want: "patch_size"},
{name: "overlap", path: `"overlap_margins":[4,4]`, want: "overlap_margins"},
{name: "resample", path: `"resample":2`, want: "resample"},
} {
t.Run(tc.name, func(t *testing.T) {
var replacement string
switch tc.name {
case "max crops":
replacement = `"max_crops":9`
case "pooling":
replacement = `"pooling_size":[3,3]`
case "patch":
replacement = `"patch_size":16`
case "overlap":
replacement = `"overlap_margins":[2,2]`
case "resample":
replacement = `"resample":3`
}
data := []byte(strings.Replace(string(valid), tc.path, replacement, 1))
if err := validateProcessorConfig(data); err == nil || !strings.Contains(err.Error(), tc.want) {
t.Fatalf("error = %v, want %q", err, tc.want)
}
})
}
}
func validMediaConfig(t *testing.T) Config {
t.Helper()
var cfg Config
if err := json.Unmarshal([]byte(tinyConfig(t)), &cfg); err != nil {
t.Fatal(err)
}
cfg.VisionConfig = VisionConfig{
HiddenSize: 8, IntermediateSize: 12, NumHiddenLayers: 2,
NumAttentionHeads: 2, NumKeyValueHeads: 2, HeadDim: 4,
NumPositionEmbeddings: 4, PatchSize: 14, ImageSize: []int32{28, 28}, NumChannels: 3,
LayerNormEps: 1e-6, HiddenAct: "gelu_pytorch_tanh", AttentionBias: true,
}
cfg.AdapterConfig = AdapterConfig{
VisionFeatureLayer: []int{1, 0}, NumAttentionHeads: 2, NumKeyValueHeads: 2,
HeadDim: 4, HiddenSize: 8, IntermediateSize: 12, TextHiddenSize: 8,
NumPoolingPositions: 9, HiddenAct: "silu", AttentionBias: true,
}
return cfg
}
+22
View File
@@ -0,0 +1,22 @@
package molmo3
import (
"image"
modelmolmo3 "github.com/ollama/ollama/model/molmo3"
)
const (
molmo3CropSize = 378
molmo3PatchSize = 14
molmo3Patches = (molmo3CropSize / molmo3PatchSize) * (molmo3CropSize / molmo3PatchSize)
DefaultMaxCrops = modelmolmo3.DefaultMaxCrops
)
// ImageProcessorResult is the pure-CPU output for one still image.
type ImageProcessorResult = modelmolmo3.ImageProcessorResult
// ProcessImage converts and tiles one image using the Molmo 3 publisher layout.
func ProcessImage(src image.Image, maxCrops int) (*ImageProcessorResult, error) {
return modelmolmo3.ProcessImage(src, maxCrops)
}
+220
View File
@@ -0,0 +1,220 @@
package molmo3
import (
"bytes"
"fmt"
"image"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/model"
"github.com/ollama/ollama/mlxrunner/nn"
modelmolmo3 "github.com/ollama/ollama/model/molmo3"
)
type imageFeatureSpan struct {
start int
count int
featureStart int
}
type imageForwardState struct {
length int
spans []imageFeatureSpan
tokenPooling []int32
tokenPoolingShape [2]int
patchPosIDs []int32
patchPosShape [3]int
}
var _ model.MediaModel = (*Model)(nil)
const maxSourceImagePixels = 64 << 20
func validateImageDimensions(width, height int) error {
if width <= 0 || height <= 0 || width > maxSourceImagePixels/height {
return fmt.Errorf("molmo3: image dimensions %dx%d exceed the 64-megapixel limit", width, height)
}
return nil
}
func (m *Model) PrepareMedia(segments []model.Segment) (*model.PreparedRequest, error) {
totalTokens := 0
limit := m.MaxContextLength()
for _, segment := range segments {
switch segment.Kind {
case "":
totalTokens += len(segment.Tokens)
case "image":
if m.Vision == nil {
return nil, fmt.Errorf("molmo3: image input requires a vision configuration")
}
metadata, _, err := image.DecodeConfig(bytes.NewReader(segment.Data))
if err != nil {
return nil, fmt.Errorf("molmo3: decode image: %w", err)
}
if err := validateImageDimensions(metadata.Width, metadata.Height); err != nil {
return nil, err
}
count, err := modelmolmo3.ImageTokenCount(segment.Data, DefaultMaxCrops)
if err != nil {
return nil, err
}
totalTokens += count
default:
return nil, fmt.Errorf("molmo3: unsupported %s input", segment.Kind)
}
if totalTokens >= limit {
return nil, fmt.Errorf("molmo3: input length (%d tokens) exceeds the model's maximum context length (%d tokens)", totalTokens, limit)
}
}
prepared := &model.PreparedRequest{}
var timeOffset int32
for s, segment := range segments {
switch segment.Kind {
case "":
prepared.Tokens = append(prepared.Tokens, segment.Tokens...)
case "image":
processed, err := modelmolmo3.ProcessImageBytes(segment.Data, DefaultMaxCrops)
if err != nil {
return nil, err
}
positions := append([]int32(nil), processed.PatchPosIDs...)
for i := 0; i < len(positions); i += 3 {
positions[i] += timeOffset
}
timeOffset += 2
tokens, state := m.expandImage(processed)
state.tokenPooling = processed.TokenPooling
state.tokenPoolingShape = processed.TokenPoolingShape
state.patchPosIDs = positions
state.patchPosShape = processed.PatchPosShape
start := len(prepared.Tokens)
prepared.Tokens = append(prepared.Tokens, tokens...)
prepared.Items = append(prepared.Items, model.PreparedItem{
Range: [2]int{start, len(prepared.Tokens)}, Source: s,
MediaData: processed.Pixels, Dims: []int{processed.PixelShape[0], processed.PixelShape[1], processed.PixelShape[2]},
Opaque: state,
})
default:
return nil, fmt.Errorf("molmo3: unsupported %s input", segment.Kind)
}
}
if len(prepared.Items) > 0 && prepared.Items[len(prepared.Items)-1].Range[1] == len(prepared.Tokens) {
return nil, fmt.Errorf("molmo3: trailing image input requires following text")
}
return prepared, nil
}
func (m *Model) expandImage(processed *ImageProcessorResult) ([]int32, imageForwardState) {
var tokens []int32
state := imageForwardState{}
lowTokens := processed.NumGlobalTokens
tokens = append(tokens, m.Config.LowResImageStartTokenID)
state.spans = append(state.spans, imageFeatureSpan{start: len(tokens), count: lowTokens})
for range lowTokens {
tokens = append(tokens, m.Config.ImageLowResID)
}
tokens = append(tokens, m.Config.ImageEndTokenID, m.Config.ImageStartTokenID)
for row := range processed.Grid[2] {
state.spans = append(state.spans, imageFeatureSpan{
start: len(tokens), count: processed.Grid[3], featureStart: lowTokens + row*processed.Grid[3],
})
for range processed.Grid[3] {
tokens = append(tokens, m.Config.ImagePatchID)
}
tokens = append(tokens, m.Config.ImageColID)
}
tokens = append(tokens, m.Config.ImageEndTokenID)
state.length = len(tokens)
return tokens, state
}
func (m *Model) EncodeMedia(item *model.PreparedItem, data *mlx.Array) *mlx.Array {
state, ok := mediaImageState(item.Opaque)
if !ok {
panic("molmo3: unknown media item")
}
pooling := mlx.FromValues(state.tokenPooling, 1, state.tokenPoolingShape[0], state.tokenPoolingShape[1])
positions := mlx.FromValues(state.patchPosIDs, 1, state.patchPosShape[0], state.patchPosShape[1], state.patchPosShape[2])
return m.Vision.Encode(data.ExpandDims(0), pooling, positions)
}
func (m *Model) embedInput(b *batch.Batch) *mlx.Array {
ids := b.InputIDs
if m.Config.ImageLowResID != m.Config.ImagePatchID {
low := mlx.FromValue(int(m.Config.ImageLowResID)).AsType(ids.DType())
patch := mlx.FromValue(int(m.Config.ImagePatchID)).AsType(ids.DType())
ids = mlx.Where(ids.Equal(low), patch, ids)
}
return m.scatterMedia(m.EmbedTokens.Forward(ids), b)
}
func (m *Model) scatterMedia(hidden *mlx.Array, b *batch.Batch) *mlx.Array {
for _, item := range b.Media {
state, ok := mediaImageState(item.Opaque)
if !ok || item.Features == nil {
continue
}
offset := int(b.SeqOffsets[item.Seq])
queryEnd := offset + int(b.SeqQueryLens[item.Seq])
for _, span := range state.spans {
start := item.Pos + span.start
end := start + span.count
lo, hi := max(start, offset), min(end, queryEnd)
if hi <= lo {
continue
}
featureStart := span.featureStart + lo - start
features := item.Features.Slice(mlx.Slice(featureStart, featureStart+hi-lo), mlx.Slice())
features = mlx.Reshape(features.AsType(hidden.DType()), 1, int32(hi-lo), int32(hidden.Dim(2)))
hidden = hidden.SliceUpdate(features,
mlx.Slice(item.Seq, item.Seq+1), mlx.Slice(lo-offset, hi-offset), mlx.Slice())
}
}
return hidden
}
func mediaImageState(opaque any) (imageForwardState, bool) {
switch state := opaque.(type) {
case imageForwardState:
return state, true
case *imageForwardState:
return *state, true
default:
return imageForwardState{}, false
}
}
func (m *Model) mediaMask(b *batch.Batch) nn.AttentionMask {
mask := nn.CausalMask()
type run struct{ seq, start, end int }
var current run
flush := func() {
if current.end <= current.start {
return
}
offset := int(b.SeqOffsets[current.seq])
queryEnd := offset + int(b.SeqQueryLens[current.seq])
if current.end > offset && current.start < queryEnd {
mask = mask.Relax(current.seq, current.start, current.end, current.start, current.end)
}
}
for _, item := range b.Media {
state, ok := mediaImageState(item.Opaque)
if !ok {
continue
}
start, end := item.Pos, item.Pos+state.length
if current.end > current.start && current.seq == item.Seq && start == current.end {
current.end = end
continue
}
flush()
current = run{seq: item.Seq, start: start, end: end}
}
flush()
return mask
}
+130
View File
@@ -0,0 +1,130 @@
package molmo3
import (
"bytes"
"encoding/binary"
"encoding/hex"
"hash/crc32"
"image"
"image/png"
"strings"
"testing"
"github.com/ollama/ollama/mlxrunner/model"
)
const transparentPaletteGIF = "47494638396101000100810000d2214d00000000000000000021f90401000000002c000000000100010000080400010404003b"
func TestPrepareMediaRejectsVideo(t *testing.T) {
loaded, err := newModel(testModelRoot(t, testConfig))
if err != nil {
t.Fatal(err)
}
_, err = loaded.(*Model).PrepareMedia([]model.Segment{{Kind: "video"}})
if err == nil || !strings.Contains(err.Error(), "video") {
t.Fatalf("error = %v, want video rejection", err)
}
}
func TestImageDimensionBounds(t *testing.T) {
if err := validateImageDimensions(8192, 8192); err != nil {
t.Fatalf("64-megapixel image rejected: %v", err)
}
if err := validateImageDimensions(8193, 8192); err == nil {
t.Fatal("oversized image accepted")
}
width := int(^uint32(0))
if err := validateImageDimensions(width, width); err == nil {
t.Fatal("image dimensions whose pixel count overflows accepted")
}
}
func TestPrepareMediaRejectsOverContextBeforeDecode(t *testing.T) {
m := &Model{Config: &Config{TextConfig: TextConfig{MaxPositionEmbeddings: 16384}}, Vision: &Vision{}}
data := encodePNG(t, image.NewNRGBA(image.Rect(0, 0, 64, 64)))
segments := make([]model.Segment, 0, 41)
for range 39 {
segments = append(segments, model.Segment{Kind: "image", Data: data})
}
segments = append(segments, model.Segment{Kind: "image", Data: data[:33]}, model.Segment{Tokens: []int32{1}})
if _, _, err := image.DecodeConfig(bytes.NewReader(data[:33])); err != nil {
t.Fatalf("truncated image header is invalid: %v", err)
}
if _, err := m.PrepareMedia(segments); err == nil || !strings.Contains(err.Error(), "context") {
t.Fatalf("PrepareMedia error = %v, want a context error before pixel decode", err)
}
}
func TestPrepareMediaAllowsTotalImagePixels(t *testing.T) {
m := &Model{Config: &Config{TextConfig: TextConfig{MaxPositionEmbeddings: 16384}}, Vision: &Vision{}}
header := pngHeader(t, 8192, 8192)
if config, _, err := image.DecodeConfig(bytes.NewReader(header)); err != nil || config.Width != 8192 || config.Height != 8192 {
t.Fatalf("large image header = %+v, %v", config, err)
}
segments := []model.Segment{{Kind: "image", Data: header}, {Kind: "image", Data: header}, {Tokens: []int32{1}}}
// Headers only: reaching pixel decoding proves the aggregate area was admitted.
if _, err := m.PrepareMedia(segments); err == nil || !strings.Contains(err.Error(), "decode image: unexpected EOF") {
t.Fatalf("PrepareMedia error = %v, want pixel decoding after admitting both headers", err)
}
}
func TestPrepareMediaPreservesTransparentGIFRGB(t *testing.T) {
data, err := hex.DecodeString(transparentPaletteGIF)
if err != nil {
t.Fatal(err)
}
m := &Model{Config: &Config{TextConfig: TextConfig{MaxPositionEmbeddings: 16384}}, Vision: &Vision{}}
prepared, err := m.PrepareMedia([]model.Segment{{Kind: "image", Data: data}, {Tokens: []int32{1}}})
if err != nil {
t.Fatal(err)
}
if got := prepared.Items[0].MediaData[:3]; got[0] != 210 || got[1] != 33 || got[2] != 77 {
t.Fatalf("transparent pixel RGB = %v, want [210 33 77]", got)
}
}
func TestPrepareMediaCountsGIFFrameDimensions(t *testing.T) {
data, err := hex.DecodeString(transparentPaletteGIF)
if err != nil {
t.Fatal(err)
}
binary.LittleEndian.PutUint16(data[6:8], 1024)
binary.LittleEndian.PutUint16(data[8:10], 600)
metadata, _, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil || metadata.Width != 1024 || metadata.Height != 600 {
t.Fatalf("GIF logical screen = %+v, %v", metadata, err)
}
text := make([]int32, 15500)
for i := range text {
text[i] = 1
}
m := &Model{Config: &Config{TextConfig: TextConfig{MaxPositionEmbeddings: 16384}}, Vision: &Vision{}}
prepared, err := m.PrepareMedia([]model.Segment{
{Tokens: text}, {Kind: "image", Data: data}, {Tokens: []int32{1}},
})
if err != nil {
t.Fatal(err)
}
if got, want := len(prepared.Tokens), len(text)+410+1; got != want {
t.Fatalf("expanded tokens = %d, want %d", got, want)
}
}
func pngHeader(t *testing.T, width, height int) []byte {
t.Helper()
data := encodePNG(t, image.NewNRGBA(image.Rect(0, 0, 1, 1)))
header := append([]byte(nil), data[:33]...)
binary.BigEndian.PutUint32(header[16:20], uint32(width))
binary.BigEndian.PutUint32(header[20:24], uint32(height))
binary.BigEndian.PutUint32(header[29:33], crc32.ChecksumIEEE(header[12:29]))
return header
}
func encodePNG(t *testing.T, img image.Image) []byte {
t.Helper()
var out bytes.Buffer
if err := png.Encode(&out, img); err != nil {
t.Fatal(err)
}
return out.Bytes()
}
+130
View File
@@ -0,0 +1,130 @@
// Package molmo3 provides the Molmo 3 model implementation for MLX.
package molmo3
import (
"encoding/json"
"fmt"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
"github.com/ollama/ollama/mlxrunner/nn"
"github.com/ollama/ollama/mlxrunner/tokenizer"
)
func init() {
model.Register("Molmo3ForConditionalGeneration", newModel)
}
// Model is a Molmo 3 conditional-generation model.
type Model struct {
Config *Config
tok *tokenizer.Tokenizer
EmbedTokens nn.EmbeddingLayer
Layers []*Layer
Norm *nn.RMSNorm
LMHead nn.LinearLayer
Vision *Vision
SuppressLogitBias *mlx.Array
quantGroupSize int
quantBits int
quantMode string
tensorQuant map[string]*model.TensorQuantInfo
}
func newModel(root *model.Root) (model.Model, error) {
configData, err := root.Manifest.ReadConfig("config.json")
if err != nil {
return nil, fmt.Errorf("load config: %w", err)
}
var cfg Config
if err := json.Unmarshal(configData, &cfg); err != nil {
return nil, fmt.Errorf("parse config: %w", err)
}
if err := cfg.validate(); err != nil {
return nil, err
}
if _, ok := root.Manifest.ConfigLayer("processor_config.json"); ok {
processorData, err := root.Manifest.ReadConfig("processor_config.json")
if err != nil {
return nil, fmt.Errorf("load processor config: %w", err)
}
if err := validateProcessorConfig(processorData); err != nil {
return nil, err
}
}
tok, err := root.LoadTokenizer(configData)
if err != nil {
return nil, err
}
m := &Model{Config: &cfg, tok: tok}
m.quantGroupSize, m.quantBits, m.quantMode, m.tensorQuant = root.Quantization()
m.Layers = make([]*Layer, cfg.TextConfig.NumHiddenLayers)
for i := range m.Layers {
m.Layers[i] = &Layer{}
}
if cfg.VisionConfig.HiddenSize > 0 {
m.Vision = &Vision{Config: &m.Config.VisionConfig, Adapter: &m.Config.AdapterConfig}
}
return m, nil
}
func (m *Model) NewCaches() []cache.Cache {
caches := make([]cache.Cache, len(m.Layers))
for i := range caches {
caches[i] = cache.NewKVCache()
}
return caches
}
func (m *Model) Forward(b *batch.Batch, caches []cache.Layer) (*mlx.Array, *mlx.Array) {
hidden := m.embedInput(b)
positions := mlx.FromValues(b.SeqOffsets, len(b.SeqOffsets))
mask := m.mediaMask(b)
for i, layer := range m.Layers {
var c cache.Layer
if caches != nil {
c = caches[i]
}
hidden = layer.Forward(hidden, b, c, positions, &m.Config.TextConfig, mask)
}
return hidden, hidden
}
func (m *Model) ValidatePromptToken(token int32) error {
if m.isGroundingToken(token) {
return fmt.Errorf("molmo3: grounding input is not supported")
}
return nil
}
func (m *Model) isGroundingToken(token int32) bool {
if token <= 0 {
return false
}
switch token {
case m.Config.PointPatchID, m.Config.PointSubpatchID, m.Config.PointLocID,
m.Config.SegMaskID, m.Config.CenterPatchID, m.Config.CorrespondingPatchID:
return true
}
return false
}
func (m *Model) Unembed(x *mlx.Array) *mlx.Array {
logits := m.LMHead.Forward(m.Norm.Forward(x, m.Config.TextConfig.RMSNormEps))
if m.SuppressLogitBias != nil {
logits = logits.Add(m.SuppressLogitBias.AsType(logits.DType()))
}
return logits
}
func (m *Model) Tokenizer() *tokenizer.Tokenizer {
return m.tok
}
func (m *Model) MaxContextLength() int {
return int(m.Config.TextConfig.MaxPositionEmbeddings)
}
+229
View File
@@ -0,0 +1,229 @@
package molmo3
import (
"encoding/json"
"fmt"
"math"
"slices"
"strings"
"testing"
"github.com/ollama/ollama/manifest"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
)
func TestConfig(t *testing.T) {
loaded, err := newModel(testModelRoot(t, testConfig))
if err != nil {
t.Fatal(err)
}
if got := loaded.MaxContextLength(); got != 16384 {
t.Fatalf("context length = %d, want 16384", got)
}
if loaded.Tokenizer() == nil {
t.Fatal("missing tokenizer")
}
}
func TestUnembedSuppressesGroundingTokens(t *testing.T) {
var cfg map[string]any
if err := json.Unmarshal([]byte(tinyConfig(t)), &cfg); err != nil {
t.Fatal(err)
}
for i, name := range []string{"point_patch_id", "point_subpatch_id", "point_loc_id", "seg_mask_id", "center_patch_id", "corresponding_patch_id"} {
cfg[name] = 130 + i
}
data, err := json.Marshal(cfg)
if err != nil {
t.Fatal(err)
}
loaded, err := newModel(testModelRoot(t, string(data)))
if err != nil {
t.Fatal(err)
}
m := loaded.(*Model)
mlxtest.Run(t, func(t *mlxtest.T) {
if err := m.LoadWeights(testTensors(&m.Config.TextConfig)); err != nil {
t.Fatal(err)
}
if !slices.Contains(mlx.Collect(m), m.SuppressLogitBias) {
t.Fatal("output suppression bias is not retained with the model")
}
hidden := mlx.FromValues(slices.Repeat([]float32{1, 2, 3, 4, 5, 6, 7, 8}, 4), 2, 2, 8)
raw := m.LMHead.Forward(m.Norm.Forward(hidden, m.Config.TextConfig.RMSNormEps)).Floats()
got := m.Unembed(hidden).Floats()
vocab := int(m.Config.TextConfig.VocabSize)
for row := range 4 {
for id := range vocab {
at := row*vocab + id
if id >= 130 && id < 136 {
if !math.IsInf(float64(got[at]), -1) || math.IsInf(float64(raw[at]), 0) {
t.Errorf("row %d grounding token %d logit = %g, raw = %g", row, id, got[at], raw[at])
}
} else if got[at] != raw[at] {
t.Errorf("row %d ordinary token %d logit = %g, want %g", row, id, got[at], raw[at])
}
}
}
})
}
func TestLoadWeights(t *testing.T) {
loaded, err := newModel(testModelRoot(t, tinyConfig(t)))
if err != nil {
t.Fatal(err)
}
m := loaded.(*Model)
mlxtest.Run(t, func(t *mlxtest.T) {
if err := m.LoadWeights(testTensors(&m.Config.TextConfig)); err != nil {
t.Fatal(err)
}
caches := m.NewCaches()
if len(caches) != 2 {
t.Fatalf("cache count = %d, want 2", len(caches))
}
defer func() {
for _, c := range caches {
c.Free()
}
}()
for i, c := range caches {
if _, ok := c.(*cache.KVCache); !ok {
t.Fatalf("cache %d has type %T, want full KV cache", i, c)
}
}
})
}
func tinyConfig(t *testing.T) string {
t.Helper()
var raw map[string]any
if err := json.Unmarshal([]byte(testConfig), &raw); err != nil {
t.Fatal(err)
}
text := raw["text_config"].(map[string]any)
for key, value := range map[string]any{
"hidden_size": 8, "num_hidden_layers": 2, "intermediate_size": 12,
"num_attention_heads": 2, "num_key_value_heads": 1, "head_dim": 4,
"vocab_size": 140, "max_position_embeddings": 128,
} {
text[key] = value
}
data, err := json.Marshal(raw)
if err != nil {
t.Fatal(err)
}
return string(data)
}
func testTensors(cfg *TextConfig) map[string]*mlx.Array {
tensors := make(map[string]*mlx.Array)
tensor := func(shape ...int) *mlx.Array {
n := 1
for _, d := range shape {
n *= d
}
values := make([]float32, n)
for i := range values {
values[i] = float32(i%17-8) / 32
}
return mlx.FromValues(values, shape...)
}
h := int(cfg.HiddenSize)
tensors["model.transformer.wte.embedding"] = tensor(int(cfg.baseVocabSize()), h)
tensors["model.transformer.wte.new_embedding"] = tensor(additionalVocabSize, h)
tensors["model.transformer.ln_f.weight"] = tensor(h)
tensors["lm_head.weight"] = tensor(int(cfg.VocabSize), h)
for i := range int(cfg.NumHiddenLayers) {
prefix := fmt.Sprintf("model.transformer.blocks.%d.", i)
tensors[prefix+"att_proj.weight"] = tensor(int((cfg.NumAttentionHeads+2*cfg.NumKeyValueHeads)*cfg.HeadDim), h)
tensors[prefix+"attn_out.weight"] = tensor(h, int(cfg.NumAttentionHeads*cfg.HeadDim))
tensors[prefix+"attn_norm.weight"] = tensor(h)
tensors[prefix+"ff_norm.weight"] = tensor(h)
tensors[prefix+"ff_proj.weight"] = tensor(2*int(cfg.IntermediateSize), h)
tensors[prefix+"ff_out.weight"] = tensor(h, int(cfg.IntermediateSize))
tensors[prefix+"q_norm.weight"] = tensor(int(cfg.HeadDim))
tensors[prefix+"k_norm.weight"] = tensor(int(cfg.HeadDim))
}
return tensors
}
func TestConfigRejectsUnsupportedSettings(t *testing.T) {
for _, tc := range []struct {
name string
mutate func(map[string]any)
want string
}{
{name: "rope type", mutate: textConfigMutation("rope_parameters", map[string]any{"rope_theta": 5000000, "rope_type": "yarn"}), want: "rope_type"},
{name: "qk norm", mutate: textConfigMutation("qk_norm_type", "other"), want: "qk_norm_type"},
{name: "activation", mutate: textConfigMutation("hidden_act", "gelu"), want: "hidden_act"},
{name: "attention bias", mutate: textConfigMutation("attention_bias", true), want: "attention_bias"},
{name: "tied embeddings", mutate: textConfigMutation("tie_word_embeddings", true), want: "tie_word_embeddings"},
{name: "layers", mutate: textConfigMutation("num_hidden_layers", 0), want: "num_hidden_layers"},
{name: "head divisibility", mutate: textConfigMutation("num_key_value_heads", 3), want: "num_key_value_heads"},
} {
t.Run(tc.name, func(t *testing.T) {
var raw map[string]any
if err := json.Unmarshal([]byte(testConfig), &raw); err != nil {
t.Fatal(err)
}
tc.mutate(raw)
data, err := json.Marshal(raw)
if err != nil {
t.Fatal(err)
}
if _, err := newModel(testModelRoot(t, string(data))); err == nil || !strings.Contains(err.Error(), tc.want) {
t.Fatalf("newModel error = %v, want field %q", err, tc.want)
}
})
}
}
func textConfigMutation(key string, value any) func(map[string]any) {
return func(raw map[string]any) {
raw["text_config"].(map[string]any)[key] = value
}
}
const testConfig = `{
"architectures": ["Molmo3ForConditionalGeneration"],
"model_type": "molmo3",
"text_config": {
"attention_bias": false,
"head_dim": 128,
"hidden_act": "silu",
"hidden_size": 2560,
"intermediate_size": 9728,
"max_position_embeddings": 16384,
"num_attention_heads": 32,
"num_hidden_layers": 36,
"num_key_value_heads": 8,
"qk_norm_type": "qwen3",
"rms_norm_eps": 0.000001,
"rope_parameters": {"rope_theta": 5000000, "rope_type": "default"},
"tie_word_embeddings": false,
"use_cache": true,
"vocab_size": 152064
}
}`
func testModelRoot(t *testing.T, config string) *model.Root {
t.Helper()
t.Setenv("OLLAMA_MODELS", t.TempDir())
root := &model.Root{Manifest: &manifest.Manifest{}}
for _, file := range []struct{ name, data string }{
{"config.json", config},
{"tokenizer.json", `{"model":{"type":"BPE","vocab":{"a":0},"merges":[]}}`},
} {
layer, err := manifest.NewLayer(strings.NewReader(file.data), manifest.MediaTypeImageJSON)
if err != nil {
t.Fatal(err)
}
layer.Name = file.name
root.Manifest.Layers = append(root.Manifest.Layers, layer)
}
return root
}
@@ -0,0 +1,65 @@
package molmo3
import (
"encoding/json"
"fmt"
"math"
"slices"
)
type processorConfig struct {
ImageProcessor struct {
DoConvertRGB bool `json:"do_convert_rgb"`
DoNormalize bool `json:"do_normalize"`
DoRescale bool `json:"do_rescale"`
DoResize bool `json:"do_resize"`
ImageMean []float32 `json:"image_mean"`
ImageStd []float32 `json:"image_std"`
MaxCrops int `json:"max_crops"`
OverlapMargins []int `json:"overlap_margins"`
PatchSize int `json:"patch_size"`
PoolingSize []int `json:"pooling_size"`
Resample int `json:"resample"`
RescaleFactor float64 `json:"rescale_factor"`
Size struct {
Height int `json:"height"`
Width int `json:"width"`
} `json:"size"`
} `json:"image_processor"`
}
func validateProcessorConfig(data []byte) error {
var cfg processorConfig
if err := json.Unmarshal(data, &cfg); err != nil {
return fmt.Errorf("parse processor config: %w", err)
}
image := cfg.ImageProcessor
if !image.DoConvertRGB || !image.DoNormalize || !image.DoRescale || !image.DoResize {
return fmt.Errorf("unsupported processor conversion, normalization, rescale, or resize setting")
}
if !slices.Equal(image.ImageMean, []float32{0.5, 0.5, 0.5}) || !slices.Equal(image.ImageStd, []float32{0.5, 0.5, 0.5}) {
return fmt.Errorf("unsupported image_mean or image_std")
}
if image.MaxCrops != 8 {
return fmt.Errorf("unsupported max_crops %d", image.MaxCrops)
}
if !slices.Equal(image.OverlapMargins, []int{4, 4}) {
return fmt.Errorf("unsupported overlap_margins %v", image.OverlapMargins)
}
if image.PatchSize != molmo3PatchSize {
return fmt.Errorf("unsupported patch_size %d", image.PatchSize)
}
if !slices.Equal(image.PoolingSize, []int{2, 2}) {
return fmt.Errorf("unsupported pooling_size %v", image.PoolingSize)
}
if image.Resample != 2 {
return fmt.Errorf("unsupported resample %d", image.Resample)
}
if math.Abs(image.RescaleFactor-1.0/255) > 1e-12 {
return fmt.Errorf("unsupported rescale_factor %g", image.RescaleFactor)
}
if image.Size.Height != molmo3CropSize || image.Size.Width != molmo3CropSize {
return fmt.Errorf("unsupported crop size %dx%d", image.Size.Height, image.Size.Width)
}
return nil
}
+164
View File
@@ -0,0 +1,164 @@
package molmo3
import (
"fmt"
"math"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
"github.com/ollama/ollama/mlxrunner/nn"
)
// Layer is a Molmo 3 decoder block.
type Layer struct {
Attention *Attention
MLP *MLP
AttentionNorm *nn.RMSNorm
MLPNorm *nn.RMSNorm
}
// Attention holds the fused QKV projection and output projection.
type Attention struct {
AttProj nn.LinearLayer
OProj nn.LinearLayer
QNorm *nn.RMSNorm
KNorm *nn.RMSNorm
}
// MLP holds the fused gate/up projection and output projection.
type MLP struct {
FFProj nn.LinearLayer
FFOut nn.LinearLayer
}
func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
cfg := &m.Config.TextConfig
required := func(name string) (*mlx.Array, error) {
weight := tensors[name]
if weight == nil {
return nil, fmt.Errorf("missing weight: %s", name)
}
return weight, nil
}
base, err := required("model.transformer.wte.embedding")
if err != nil {
return err
}
special, err := required("model.transformer.wte.new_embedding")
if err != nil {
return err
}
m.EmbedTokens = nn.NewEmbedding(mlx.Concatenate([]*mlx.Array{base, special}, 0))
norm, err := required("model.transformer.ln_f.weight")
if err != nil {
return err
}
m.Norm = nn.NewRMSNorm(norm, cfg.RMSNormEps)
linears := model.NewLinearFactory(tensors, m.quantGroupSize, m.quantBits, m.quantMode, m.tensorQuant)
m.LMHead = linears.Make("lm_head")
if m.LMHead == nil {
return fmt.Errorf("missing weight: lm_head.weight")
}
for i, layer := range m.Layers {
prefix := fmt.Sprintf("model.transformer.blocks.%d", i)
attentionNorm, err := required(prefix + ".attn_norm.weight")
if err != nil {
return err
}
mlpNorm, err := required(prefix + ".ff_norm.weight")
if err != nil {
return err
}
qNorm, err := required(prefix + ".q_norm.weight")
if err != nil {
return err
}
kNorm, err := required(prefix + ".k_norm.weight")
if err != nil {
return err
}
layer.AttentionNorm = nn.NewRMSNorm(attentionNorm, cfg.RMSNormEps)
layer.MLPNorm = nn.NewRMSNorm(mlpNorm, cfg.RMSNormEps)
layer.Attention = &Attention{
AttProj: linears.Make(prefix + ".att_proj"),
OProj: linears.Make(prefix + ".attn_out"),
QNorm: nn.NewRMSNorm(qNorm, cfg.RMSNormEps),
KNorm: nn.NewRMSNorm(kNorm, cfg.RMSNormEps),
}
layer.MLP = &MLP{
FFProj: linears.Make(prefix + ".ff_proj"),
FFOut: linears.Make(prefix + ".ff_out"),
}
if layer.Attention.AttProj == nil || layer.Attention.OProj == nil {
return fmt.Errorf("layer %d: missing attention projection", i)
}
if layer.MLP.FFProj == nil || layer.MLP.FFOut == nil {
return fmt.Errorf("layer %d: missing feed-forward projection", i)
}
}
if m.Vision != nil {
if err := m.Vision.LoadWeights(tensors); err != nil {
return err
}
}
bias := make([]float32, cfg.VocabSize)
suppress := false
for _, id := range []int32{
m.Config.PointPatchID, m.Config.PointSubpatchID, m.Config.PointLocID,
m.Config.SegMaskID, m.Config.CenterPatchID, m.Config.CorrespondingPatchID,
} {
if id > 0 && id < cfg.VocabSize {
bias[id] = float32(math.Inf(-1))
suppress = true
}
}
if suppress {
m.SuppressLogitBias = mlx.FromValues(bias, 1, 1, int(cfg.VocabSize))
}
return nil
}
func (l *Layer) Forward(x *mlx.Array, b *batch.Batch, c cache.Layer, positions *mlx.Array, cfg *TextConfig, mask nn.AttentionMask) *mlx.Array {
h := mlx.Add(x, l.Attention.Forward(l.AttentionNorm.Forward(x, cfg.RMSNormEps), b, c, positions, cfg, mask))
return mlx.Add(h, l.MLP.Forward(l.MLPNorm.Forward(h, cfg.RMSNormEps), cfg))
}
func (a *Attention) Forward(x *mlx.Array, b *batch.Batch, c cache.Layer, positions *mlx.Array, cfg *TextConfig, mask nn.AttentionMask) *mlx.Array {
B, L := int32(x.Dim(0)), int32(x.Dim(1))
qSize := cfg.NumAttentionHeads * cfg.HeadDim
kvSize := cfg.NumKeyValueHeads * cfg.HeadDim
projected := a.AttProj.Forward(x)
q := mlx.Contiguous(projected.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(0, int(qSize))), false)
k := mlx.Contiguous(projected.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(int(qSize), int(qSize+kvSize))), false)
v := mlx.Contiguous(projected.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(int(qSize+kvSize), mlx.End)), false)
q = a.QNorm.Forward(mlx.Reshape(q, B, L, cfg.NumAttentionHeads, cfg.HeadDim), cfg.RMSNormEps)
k = a.KNorm.Forward(mlx.Reshape(k, B, L, cfg.NumKeyValueHeads, cfg.HeadDim), cfg.RMSNormEps)
q = mlx.Transpose(q, 0, 2, 1, 3)
k = mlx.Transpose(k, 0, 2, 1, 3)
v = mlx.Transpose(mlx.Reshape(v, B, L, cfg.NumKeyValueHeads, cfg.HeadDim), 0, 2, 1, 3)
theta := cfg.RopeParameters.RopeTheta
q = mlx.RoPEWithFreqs(q, int(cfg.HeadDim), false, theta, 1, positions, nil)
k = mlx.RoPEWithFreqs(k, int(cfg.HeadDim), false, theta, 1, positions, nil)
var kv nn.SDPAOption
if c != nil {
kv = nn.WithKVHistory(c.(cache.Attention).Update(b, k, v))
} else {
kv = nn.WithKV(k, v, b.SeqQueryLens)
}
scale := float32(1 / math.Sqrt(float64(cfg.HeadDim)))
out := nn.ScaledDotProductAttention(b, q, scale, kv, nn.WithMask(mask))
out = mlx.Reshape(mlx.Transpose(out, 0, 2, 1, 3), B, L, qSize)
return a.OProj.Forward(out)
}
func (m *MLP) Forward(x *mlx.Array, cfg *TextConfig) *mlx.Array {
projected := m.FFProj.Forward(x)
width := int(cfg.IntermediateSize)
h := projected.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(0, width))
gate := projected.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(width, mlx.End))
return m.FFOut.Forward(mlx.SwiGLU(gate, h))
}
+238
View File
@@ -0,0 +1,238 @@
package molmo3
import (
"fmt"
"math"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/nn"
)
// Vision contains the image encoder and its text-space connector.
type Vision struct {
Config *VisionConfig
Adapter *AdapterConfig
PatchEmbedding *nn.Linear
PositionalEmbedding *mlx.Array
Layers []*VisionLayer
PositionProjection *nn.Linear
PoolingQuery *nn.Linear
PoolingKey *nn.Linear
PoolingValue *nn.Linear
PoolingPositionBias *mlx.Array
ProjectorGate *nn.Linear
ProjectorOutput *nn.Linear
ProjectorUp *nn.Linear
}
type VisionLayer struct {
Attention *VisionAttention
FeedForward *VisionFeedForward
AttentionNorm *nn.LayerNorm
FeedForwardNorm *nn.LayerNorm
}
type VisionAttention struct {
Query *nn.Linear
Key *nn.Linear
Value *nn.Linear
Output *nn.Linear
}
type VisionFeedForward struct {
Input *nn.Linear
Output *nn.Linear
}
func (v *Vision) LoadWeights(tensors map[string]*mlx.Array) error {
var err error
if v.PatchEmbedding, err = visionLinear(tensors, "model.vit.patch_embedding", true); err != nil {
return err
}
if v.PositionalEmbedding, err = requireTensor(tensors, "model.vit.positional_embedding"); err != nil {
return err
}
v.Layers = make([]*VisionLayer, v.Config.NumHiddenLayers)
for i := range v.Layers {
prefix := fmt.Sprintf("model.vit.transformer.resblocks.%d", i)
layer := &VisionLayer{}
if layer.AttentionNorm, err = visionLayerNorm(tensors, prefix+".attention_norm", v.Config.LayerNormEps); err != nil {
return err
}
if layer.FeedForwardNorm, err = visionLayerNorm(tensors, prefix+".ffn_norm", v.Config.LayerNormEps); err != nil {
return err
}
attention := &VisionAttention{}
if attention.Query, err = visionLinear(tensors, prefix+".attention.wq", true); err != nil {
return err
}
if attention.Key, err = visionLinear(tensors, prefix+".attention.wk", true); err != nil {
return err
}
if attention.Value, err = visionLinear(tensors, prefix+".attention.wv", true); err != nil {
return err
}
if attention.Output, err = visionLinear(tensors, prefix+".attention.wo", true); err != nil {
return err
}
feedForward := &VisionFeedForward{}
if feedForward.Input, err = visionLinear(tensors, prefix+".feed_forward.w1", true); err != nil {
return err
}
if feedForward.Output, err = visionLinear(tensors, prefix+".feed_forward.w2", true); err != nil {
return err
}
layer.Attention, layer.FeedForward = attention, feedForward
v.Layers[i] = layer
}
if v.PositionProjection, err = visionLinear(tensors, "model.subpatch_pos_embed.proj", true); err != nil {
return err
}
if v.PoolingQuery, err = visionLinear(tensors, "model.connector.image_pooling_2d.wq", true); err != nil {
return err
}
if v.PoolingKey, err = visionLinear(tensors, "model.connector.image_pooling_2d.wk", true); err != nil {
return err
}
if v.PoolingValue, err = visionLinear(tensors, "model.connector.image_pooling_2d.wv", true); err != nil {
return err
}
if v.PoolingPositionBias, err = requireTensor(tensors, "model.connector.positional_embeddings.bias"); err != nil {
return err
}
if v.ProjectorGate, err = visionLinear(tensors, "model.connector.image_projector.w1", false); err != nil {
return err
}
if v.ProjectorOutput, err = visionLinear(tensors, "model.connector.image_projector.w2", false); err != nil {
return err
}
if v.ProjectorUp, err = visionLinear(tensors, "model.connector.image_projector.w3", false); err != nil {
return err
}
return nil
}
func requireTensor(tensors map[string]*mlx.Array, name string) (*mlx.Array, error) {
tensor := tensors[name]
if tensor == nil {
return nil, fmt.Errorf("missing weight: %s", name)
}
return tensor, nil
}
func visionLinear(tensors map[string]*mlx.Array, name string, bias bool) (*nn.Linear, error) {
weight, err := requireTensor(tensors, name+".weight")
if err != nil {
return nil, err
}
var biasArray *mlx.Array
if bias {
if biasArray, err = requireTensor(tensors, name+".bias"); err != nil {
return nil, err
}
}
return nn.NewLinear(weight, biasArray), nil
}
func visionLayerNorm(tensors map[string]*mlx.Array, name string, eps float32) (*nn.LayerNorm, error) {
weight, err := requireTensor(tensors, name+".weight")
if err != nil {
return nil, err
}
bias, err := requireTensor(tensors, name+".bias")
if err != nil {
return nil, err
}
return &nn.LayerNorm{Weight: weight, Bias: bias, Eps: eps}, nil
}
func (v *Vision) Encode(pixels, pooling, positions *mlx.Array) *mlx.Array {
B, T, N := int32(pixels.Dim(0)), int32(pixels.Dim(1)), int32(pixels.Dim(2))
x := pixels.AsType(mlx.DTypeFloat32)
x = x.Divide(mlx.FromValue(float32(255))).Multiply(mlx.FromValue(float32(2))).Subtract(mlx.FromValue(float32(1)))
x = x.Reshape(int(B*T), int(N), int(v.Config.PatchSize*v.Config.PatchSize*3)).AsType(v.PatchEmbedding.Weight.DType())
x = v.PatchEmbedding.Forward(x)
x = x.Add(v.PositionalEmbedding)
hidden := make([]*mlx.Array, 0, len(v.Layers))
for _, layer := range v.Layers {
x = layer.Forward(x, v.Config)
hidden = append(hidden, x)
}
taps := make([]*mlx.Array, len(v.Adapter.VisionFeatureLayer))
for i, index := range v.Adapter.VisionFeatureLayer {
taps[i] = hidden[index]
}
features := mlx.Concatenate(taps, -1).Reshape(int(B), int(T*N), -1)
features = features.Add(v.positionFeatures(positions, B, T*N).AsType(features.DType()))
P, S, D := int32(pooling.Dim(1)), int32(pooling.Dim(2)), int32(features.Dim(2))
zero := mlx.FromValue(0).AsType(pooling.DType())
valid := pooling.Greater(mlx.FromValue(-1).AsType(pooling.DType()))
indices := mlx.BroadcastTo(mlx.Maximum(pooling, zero).ExpandDims(-1), B, P, S, D)
gatherInput := mlx.BroadcastTo(features.ExpandDims(2), B, T*N, S, D)
gathered := gatherInput.TakeAlongAxis(indices, 1)
validFeatures := valid.ExpandDims(-1).AsType(gathered.DType())
gathered = gathered.Multiply(validFeatures)
gathered = gathered.Reshape(int(B*P), int(S), int(D))
valid = valid.Reshape(int(B*P), int(S))
return v.connect(gathered, valid)
}
func (v *Vision) positionFeatures(positions *mlx.Array, B, rows int32) *mlx.Array {
half := mlx.Arange(0, 512, 2, mlx.DTypeFloat32)
div := mlx.Exp(half.Multiply(mlx.FromValue(float32(-math.Log(10000) / 512))))
angles := positions.AsType(mlx.DTypeFloat32).Reshape(int(B), int(rows), 3, 1).Multiply(div)
embedded := mlx.Stack([]*mlx.Array{mlx.Sin(angles), mlx.Cos(angles)}, -1)
embedded = embedded.Reshape(int(B), int(rows), 1536).AsType(v.PositionProjection.Weight.DType())
return v.PositionProjection.Forward(embedded)
}
func (v *Vision) connect(toPool, mask *mlx.Array) *mlx.Array {
S := int32(toPool.Dim(1))
bias := v.PoolingPositionBias.Slice(mlx.Slice(0, int(S)), mlx.Slice())
toPool = toPool.Add(bias)
denom := mlx.Maximum(mask.AsType(mlx.DTypeFloat32).SumAxis(-1, false), mlx.FromValue(float32(1)))
query := toPool.SumAxis(1, true).Divide(denom.Reshape(denom.Dim(0), 1, 1).AsType(toPool.DType()))
pooled := v.poolingAttention(query, toPool, mask)
return v.ProjectorOutput.Forward(mlx.SwiGLU(v.ProjectorGate.Forward(pooled), v.ProjectorUp.Forward(pooled))).Reshape(pooled.Dim(0), -1)
}
func (v *Vision) poolingAttention(query, toPool, mask *mlx.Array) *mlx.Array {
n, slots := int32(query.Dim(0)), int32(toPool.Dim(1))
heads, headDim := v.Adapter.NumAttentionHeads, v.Adapter.HeadDim
q := v.PoolingQuery.Forward(query).Reshape(int(n), 1, int(heads), int(headDim)).Transpose(0, 2, 1, 3).AsType(mlx.DTypeFloat32)
k := v.PoolingKey.Forward(toPool).Reshape(int(n), int(slots), int(heads), int(headDim)).Transpose(0, 2, 1, 3).AsType(mlx.DTypeFloat32)
value := v.PoolingValue.Forward(toPool).Reshape(int(n), int(slots), int(heads), int(headDim)).Transpose(0, 2, 1, 3).AsType(mlx.DTypeFloat32)
scale := float32(1 / math.Sqrt(float64(headDim)))
weights := q.Matmul(k.Transpose(0, 1, 3, 2)).Multiply(mlx.FromValue(scale))
finiteMin := mlx.FromValue(float32(-math.MaxFloat32))
weights = mlx.Where(mask.Reshape(int(n), 1, 1, int(slots)), weights, finiteMin)
weights = mlx.SoftmaxAxis(weights, -1, true)
out := weights.Matmul(value).Transpose(0, 2, 1, 3)
out = mlx.Contiguous(out, false).Reshape(int(n), 1, int(heads*headDim)).AsType(query.DType())
return out
}
func (l *VisionLayer) Forward(x *mlx.Array, cfg *VisionConfig) *mlx.Array {
attention := l.Attention.Forward(l.AttentionNorm.Forward(x), cfg)
x = x.Add(attention)
return x.Add(l.FeedForward.Forward(l.FeedForwardNorm.Forward(x)))
}
func (a *VisionAttention) Forward(x *mlx.Array, cfg *VisionConfig) *mlx.Array {
B, N := int32(x.Dim(0)), int32(x.Dim(1))
split := func(input *mlx.Array) *mlx.Array {
return input.Reshape(int(B), int(N), int(cfg.NumAttentionHeads), int(cfg.HeadDim)).Transpose(0, 2, 1, 3).AsType(mlx.DTypeFloat32)
}
q, k, v := split(a.Query.Forward(x)), split(a.Key.Forward(x)), split(a.Value.Forward(x))
scale := float32(1 / math.Sqrt(float64(cfg.HeadDim)))
out := mlx.FastScaledDotProductAttention(q, k, v, scale, mlx.FastSDPANoWindow, "", nil)
out = mlx.Contiguous(out.Transpose(0, 2, 1, 3), false).Reshape(int(B), int(N), int(cfg.NumAttentionHeads*cfg.HeadDim))
return a.Output.Forward(out.AsType(x.DType()))
}
func (f *VisionFeedForward) Forward(x *mlx.Array) *mlx.Array {
return f.Output.Forward(mlx.GELUApprox(f.Input.Forward(x)))
}
+8
View File
@@ -139,6 +139,14 @@ func (r *Runner) Prepare(request *request) (err error) {
request.Layout = prepared.Layout
}
if validator, ok := r.Model.(model.PromptTokenValidator); ok {
for _, token := range tokens {
if err := validator.ValidatePromptToken(token); err != nil {
return err
}
}
}
if len(tokens) == 0 {
return errors.New("empty prompt")
}
+21
View File
@@ -29,6 +29,27 @@ func (textOnlyModel) Unembed(x *mlx.Array) *mlx.Array { return x }
func (textOnlyModel) Tokenizer() *tokenizer.Tokenizer { return nil }
func (textOnlyModel) MaxContextLength() int { return 0 }
type guardedTextOnlyModel struct{ textOnlyModel }
func (guardedTextOnlyModel) ValidatePromptToken(token int32) error {
if token == 1 {
return fmt.Errorf("unsupported prompt token")
}
return nil
}
func TestPrepareRejectsUnsupportedPromptToken(t *testing.T) {
tok, err := tokenizer.LoadFromBytes([]byte(`{"model":{"type":"BPE","vocab":{"a":0,"b":1},"merges":[]}}`))
if err != nil {
t.Fatal(err)
}
r := &Runner{Model: guardedTextOnlyModel{}, Tokenizer: tok, contextLength: 4096}
req := &request{CompletionRequest: CompletionRequest{Prompt: "b"}}
if err := r.Prepare(req); err == nil || !strings.Contains(err.Error(), "unsupported prompt token") {
t.Fatalf("Prepare error = %v, want unsupported prompt token", err)
}
}
func TestPrepareRejectsMediaWithoutSupport(t *testing.T) {
r := &Runner{Model: textOnlyModel{}}
req := &request{
+452
View File
@@ -0,0 +1,452 @@
package molmo3
import (
"bytes"
"encoding/binary"
"fmt"
"image"
"image/color"
"image/gif"
_ "image/jpeg"
_ "image/png"
"math"
"slices"
)
// DefaultMaxCrops is the reference-validated still-image crop budget.
const DefaultMaxCrops = 8
// ImageProcessorResult is the pure-CPU output for one still image. Pixels,
// TokenPooling, and PatchPosIDs are flattened in row-major order using their
// corresponding shape fields. Pixel values are unnormalized RGB in [0, 255].
type ImageProcessorResult struct {
Pixels []float32
PixelShape [3]int // [crops, 729, 588]
TokenPooling []int32
TokenPoolingShape [2]int // [tokens, 4]
PatchPosIDs []int32
PatchPosShape [3]int // [crops, 729, 3]
NumGlobalTokens int
Grid [4]int
}
type rgbImage struct {
width, height int
pix []uint8
}
type resizeAxis struct {
lo, hi int
w0, w1 float32
}
func resizeBilinear(src rgbImage, targetH, targetW int) rgbImage {
if src.height == targetH && src.width == targetW {
return rgbImage{width: targetW, height: targetH, pix: slices.Clone(src.pix)}
}
xs := bilinearAxis(src.width, targetW)
ys := bilinearAxis(src.height, targetH)
dst := rgbImage{width: targetW, height: targetH, pix: make([]uint8, targetH*targetW*3)}
for y, ya := range ys {
for x, xa := range xs {
for c := range 3 {
p00 := float32(src.pix[(ya.lo*src.width+xa.lo)*3+c])
p01 := float32(src.pix[(ya.lo*src.width+xa.hi)*3+c])
p10 := float32(src.pix[(ya.hi*src.width+xa.lo)*3+c])
p11 := float32(src.pix[(ya.hi*src.width+xa.hi)*3+c])
top := fma32(xa.w0, p00, xa.w1*p01)
bottom := fma32(xa.w0, p10, xa.w1*p11)
value := fma32(ya.w0, top, ya.w1*bottom)
dst.pix[(y*targetW+x)*3+c] = uint8(math.RoundToEven(float64(value)))
}
}
}
return dst
}
func fma32(a, b, addend float32) float32 {
// The publisher's ARM64 vector kernel fuses the first product into the
// already-rounded second product. Evaluate in float64 to avoid an
// intermediate float32 rounding of the fused product.
return float32(math.FMA(float64(a), float64(b), float64(addend)))
}
func bilinearAxis(sourceSize, targetSize int) []resizeAxis {
scale := float32(sourceSize) / float32(targetSize)
out := make([]resizeAxis, targetSize)
for i := range out {
center := (float32(i) + 0.5) * scale
coordinate := center - 0.5
if coordinate < 0 {
coordinate = 0
}
lo := int(coordinate)
hi := min(lo+1, sourceSize-1)
w1 := coordinate - float32(lo)
out[i] = resizeAxis{lo: lo, hi: hi, w0: 1 - w1, w1: w1}
}
return out
}
func patchifyCrops(crops []rgbImage) []float32 {
const patch = 14
total := 0
for _, crop := range crops {
total += (crop.height / patch) * (crop.width / patch) * patch * patch * 3
}
out := make([]float32, total)
offset := 0
for _, crop := range crops {
gridW := crop.width / patch
nPatches := (crop.height / patch) * gridW
for patchY := range crop.height / patch {
for patchX := range gridW {
dst := out[offset+(patchY*gridW+patchX)*patch*patch*3:]
for y := range patch {
for x := range patch {
src := ((patchY*patch+y)*crop.width + patchX*patch + x) * 3
dstAt := (y*patch + x) * 3
for c := range 3 {
dst[dstAt+c] = float32(crop.pix[src+c])
}
}
}
}
}
offset += nPatches * patch * patch * 3
}
return out
}
func poolWindows(idx []int32, height, width, pool int) ([]int32, [2]int) {
hPad := (pool - height%pool) % pool
wPad := (pool - width%pool) % pool
hBefore, wBefore := hPad/2, wPad/2
outH, outW := (height+hPad)/pool, (width+wPad)/pool
out := make([]int32, outH*outW*pool*pool)
for oh := range outH {
for ow := range outW {
window := out[(oh*outW+ow)*pool*pool:]
for py := range pool {
for px := range pool {
y := oh*pool + py - hBefore
x := ow*pool + px - wBefore
value := int32(-1)
if y >= 0 && y < height && x >= 0 && x < width {
value = idx[y*width+x]
}
window[py*pool+px] = value
}
}
}
}
return out, [2]int{outH * outW, pool * pool}
}
func selectTiling(height, width, tile, maxCrops int) [2]int {
// Python sorts by (crop count, rows), then takes the first extremum.
// Enumerating area and then rows produces precisely that order.
var down, up [2]int
var downScale, upScale float32
allBelow := true
for area := 1; area <= maxCrops; area++ {
for rows := 1; rows <= maxCrops; rows++ {
if area%rows != 0 {
continue
}
cols := area / rows
if cols > maxCrops {
continue
}
scale := min(float32(rows*tile)/float32(height), float32(cols*tile)/float32(width))
if scale < 1 {
if down == [2]int{} || scale > downScale {
down, downScale = [2]int{rows, cols}, scale
}
continue
}
allBelow = false
if up == [2]int{} || scale < upScale {
up, upScale = [2]int{rows, cols}, scale
}
}
}
if allBelow {
return down
}
return up
}
const (
molmo3CropSize = 378
molmo3PatchSize = 14
molmo3Grid = molmo3CropSize / molmo3PatchSize
molmo3Patches = molmo3Grid * molmo3Grid
molmo3Overlap = 4
molmo3ImagePool = 2
molmo3PatchValues = molmo3PatchSize * molmo3PatchSize * 3
)
type molmo3ImageLayout struct {
tiling [2]int
resizedHW [2]int
window int
tokenPooling []int32
patchPosIDs []int32
numGlobalTokens int
grid [4]int
}
func makeMolmo3ImageLayout(height, width, maxCrops int) molmo3ImageLayout {
margin := 2 * molmo3Overlap * molmo3PatchSize
window := (molmo3Grid - 2*molmo3Overlap) * molmo3PatchSize
tiling := selectTiling(height-margin, width-margin, window, maxCrops)
rows, cols := tiling[0], tiling[1]
crops := make([][]int32, rows*cols)
for i := range rows {
for j := range cols {
crop := make([]int32, molmo3Patches)
for p := range crop {
crop[p] = int32((i*cols+j)*molmo3Patches + p)
}
for y := range molmo3Grid {
for x := range molmo3Grid {
if (i != 0 && y < molmo3Overlap) ||
(j != 0 && x < molmo3Overlap) ||
(i != rows-1 && y >= molmo3Grid-molmo3Overlap) ||
(j != cols-1 && x >= molmo3Grid-molmo3Overlap) {
crop[y*molmo3Grid+x] = -1
}
}
}
crops[i*cols+j] = crop
}
}
resizedH, resizedW := rows*window+margin, cols*window+margin
mappingH, mappingW := resizedH/molmo3PatchSize, resizedW/molmo3PatchSize
mapping := make([]int32, 0, mappingH*mappingW)
for i := range rows {
for y := range molmo3Grid {
for j := range cols {
crop := crops[i*cols+j]
for x := range molmo3Grid {
if value := crop[y*molmo3Grid+x]; value >= 0 {
mapping = append(mapping, value+molmo3Patches)
}
}
}
}
}
globalIdx := make([]int32, molmo3Patches)
for i := range globalIdx {
globalIdx[i] = int32(i)
}
globalPooling, _ := poolWindows(globalIdx, molmo3Grid, molmo3Grid, molmo3ImagePool)
highPooling, _ := poolWindows(mapping, mappingH, mappingW, molmo3ImagePool)
tokenPooling := append(globalPooling, highPooling...)
positions := make([]int32, (1+len(crops))*molmo3Patches*3)
for p := range molmo3Patches {
positions[p*3+1] = int32(p / molmo3Grid)
positions[p*3+2] = int32(p % molmo3Grid)
}
for i, value := range mapping {
crop, patch := int(value)/molmo3Patches, int(value)%molmo3Patches
at := (crop*molmo3Patches + patch) * 3
positions[at] = 1
positions[at+1] = int32(i / mappingW)
positions[at+2] = int32(i % mappingW)
}
nGlobal := (molmo3Grid + molmo3ImagePool - 1) / molmo3ImagePool
gridH := (mappingH + molmo3ImagePool - 1) / molmo3ImagePool
gridW := (mappingW + molmo3ImagePool - 1) / molmo3ImagePool
return molmo3ImageLayout{
tiling: tiling, resizedHW: [2]int{resizedH, resizedW}, window: window,
tokenPooling: tokenPooling, patchPosIDs: positions,
numGlobalTokens: nGlobal * nGlobal, grid: [4]int{nGlobal, nGlobal, gridH, gridW},
}
}
// ImageTokenCount returns the still-image expansion length without decoding pixels.
func ImageTokenCount(data []byte, maxCrops int) (int, error) {
metadata, format, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil {
return 0, fmt.Errorf("molmo3: decode image: %w", err)
}
width, height := metadata.Width, metadata.Height
if err := validateImageDimensions(width, height); err != nil {
return 0, err
}
if format == "gif" {
var ok bool
_, width, height, ok = gifFirstFrame(data)
if !ok {
return 0, fmt.Errorf("molmo3: decode image: invalid GIF frame descriptor")
}
if err := validateImageDimensions(width, height); err != nil {
return 0, err
}
}
if maxCrops <= 0 {
return 0, fmt.Errorf("molmo3: max crops must be positive, got %d", maxCrops)
}
layout := makeMolmo3ImageLayout(height, width, maxCrops)
return 1 + layout.numGlobalTokens + 2 + layout.grid[2]*(layout.grid[3]+1) + 1, nil
}
func convertMolmo3RGB(src image.Image) (rgbImage, error) {
if src == nil {
return rgbImage{}, fmt.Errorf("molmo3: nil image")
}
bounds := src.Bounds()
width, height := bounds.Dx(), bounds.Dy()
if width <= 0 || height <= 0 {
return rgbImage{}, fmt.Errorf("molmo3: invalid image size %dx%d", width, height)
}
maxInt := int(^uint(0) >> 1)
if width > maxInt/3 || height > maxInt/(width*3) {
return rgbImage{}, fmt.Errorf("molmo3: image size %dx%d overflows address space", width, height)
}
out := rgbImage{width: width, height: height, pix: make([]uint8, width*height*3)}
if img, ok := src.(*image.NRGBA); ok {
for y := range height {
row := img.PixOffset(bounds.Min.X, bounds.Min.Y+y)
for x := range width {
copy(out.pix[(y*width+x)*3:], img.Pix[row+x*4:row+x*4+3])
}
}
return out, nil
}
for y := range height {
for x := range width {
pixel := color.NRGBAModel.Convert(src.At(bounds.Min.X+x, bounds.Min.Y+y)).(color.NRGBA)
copy(out.pix[(y*width+x)*3:], []uint8{pixel.R, pixel.G, pixel.B})
}
}
return out, nil
}
// decodeImage preserves the palette RGB of transparent GIF pixels.
func decodeImage(data []byte, format string) (image.Image, error) {
if format == "gif" {
return gif.Decode(bytes.NewReader(gifWithOpaquePalette(data)))
}
decoded, _, err := image.Decode(bytes.NewReader(data))
return decoded, err
}
func gifFirstFrame(data []byte) (control, width, height int, ok bool) {
control = -1
if len(data) < 13 {
return
}
i := 13
if data[10]&0x80 != 0 {
i += 3 * (1 << (uint(data[10]&7) + 1))
}
for i < len(data) {
switch data[i] {
case 0x21:
if len(data)-i < 2 {
return
}
label := data[i+1]
i += 2
if label == 0xf9 && len(data)-i >= 6 && data[i] == 4 {
control = i + 1
}
for {
if i >= len(data) {
return
}
size := int(data[i])
i++
if size == 0 {
break
}
if size > len(data)-i {
return
}
i += size
}
case 0x2c:
if len(data)-i < 10 {
return
}
return control, int(binary.LittleEndian.Uint16(data[i+5 : i+7])), int(binary.LittleEndian.Uint16(data[i+7 : i+9])), true
default:
return
}
}
return
}
func gifWithOpaquePalette(data []byte) []byte {
control, _, _, ok := gifFirstFrame(data)
if ok && control >= 0 && data[control]&1 != 0 {
cloned := bytes.Clone(data)
cloned[control] &^= 1
return cloned
}
return data
}
const maxSourceImagePixels = 64 << 20
func validateImageDimensions(width, height int) error {
if width <= 0 || height <= 0 || width > maxSourceImagePixels/height {
return fmt.Errorf("molmo3: image dimensions %dx%d exceed the 64-megapixel limit", width, height)
}
return nil
}
// ProcessImageBytes checks dimensions before decoding and processing pixels.
func ProcessImageBytes(data []byte, maxCrops int) (*ImageProcessorResult, error) {
metadata, format, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil {
return nil, fmt.Errorf("molmo3: decode image: %w", err)
}
if err := validateImageDimensions(metadata.Width, metadata.Height); err != nil {
return nil, err
}
decoded, err := decodeImage(data, format)
if err != nil {
return nil, fmt.Errorf("molmo3: decode image: %w", err)
}
return ProcessImage(decoded, maxCrops)
}
// ProcessImage converts and tiles one image using the Molmo 3 publisher layout.
func ProcessImage(src image.Image, maxCrops int) (*ImageProcessorResult, error) {
if maxCrops <= 0 {
return nil, fmt.Errorf("molmo3: max crops must be positive, got %d", maxCrops)
}
rgb, err := convertMolmo3RGB(src)
if err != nil {
return nil, err
}
layout := makeMolmo3ImageLayout(rgb.height, rgb.width, maxCrops)
resized := resizeBilinear(rgb, layout.resizedHW[0], layout.resizedHW[1])
crops := make([]rgbImage, 1, 1+layout.tiling[0]*layout.tiling[1])
crops[0] = resizeBilinear(rgb, molmo3CropSize, molmo3CropSize)
for i := range layout.tiling[0] {
for j := range layout.tiling[1] {
crop := rgbImage{width: molmo3CropSize, height: molmo3CropSize, pix: make([]uint8, molmo3CropSize*molmo3CropSize*3)}
for y := range molmo3CropSize {
srcAt := ((i*layout.window+y)*resized.width + j*layout.window) * 3
copy(crop.pix[y*molmo3CropSize*3:(y+1)*molmo3CropSize*3], resized.pix[srcAt:srcAt+molmo3CropSize*3])
}
crops = append(crops, crop)
}
}
cropCount := len(crops)
return &ImageProcessorResult{
Pixels: patchifyCrops(crops), PixelShape: [3]int{cropCount, molmo3Patches, molmo3PatchValues},
TokenPooling: layout.tokenPooling, TokenPoolingShape: [2]int{len(layout.tokenPooling) / 4, 4},
PatchPosIDs: layout.patchPosIDs, PatchPosShape: [3]int{cropCount, molmo3Patches, 3},
NumGlobalTokens: layout.numGlobalTokens, Grid: layout.grid,
}, nil
}
+138
View File
@@ -0,0 +1,138 @@
package molmo3
import (
"bytes"
"encoding/hex"
"image"
"image/color"
"image/draw"
"image/png"
"slices"
"testing"
)
const transparentGIFHex = "47494638396101000100810000d2214d00000000000000000021f90401000000002c000000000100010000080400010404003b"
func transparentGIF(t *testing.T, localPalette bool) []byte {
t.Helper()
data, err := hex.DecodeString(transparentGIFHex)
if err != nil {
t.Fatal(err)
}
if !localPalette {
return data
}
local := append([]byte(nil), data[:13]...)
local[10] &^= 0x80
local = append(local, data[25:43]...)
local[len(local)-1] = 0x81
local = append(local, data[13:25]...)
return append(local, data[43:]...)
}
func TestProcessImageBytesTransparentGIFRGB(t *testing.T) {
for _, local := range []bool{false, true} {
name := "global palette"
if local {
name = "local palette"
}
t.Run(name, func(t *testing.T) {
processed, err := ProcessImageBytes(transparentGIF(t, local), DefaultMaxCrops)
if err != nil {
t.Fatal(err)
}
if !slices.Equal(processed.Pixels[:3], []float32{210, 33, 77}) {
t.Fatalf("transparent pixel RGB = %v, want [210 33 77]", processed.Pixels[:3])
}
})
}
}
func TestProcessImageBytesOpaqueGIFRGB(t *testing.T) {
data := transparentGIF(t, false)
data[28] &^= 1
original := slices.Clone(data)
processed, err := ProcessImageBytes(data, DefaultMaxCrops)
if err != nil {
t.Fatal(err)
}
if !slices.Equal(processed.Pixels[:3], []float32{210, 33, 77}) || !slices.Equal(data, original) {
t.Fatalf("opaque GIF RGB = %v, original bytes preserved = %t", processed.Pixels[:3], slices.Equal(data, original))
}
}
func TestImageDimensionOverflow(t *testing.T) {
width := int(^uint32(0))
if err := validateImageDimensions(width, width); err == nil {
t.Fatal("image dimensions whose pixel count overflows accepted")
}
}
func TestProcessImageMatchesReferenceLayout(t *testing.T) {
tiny := image.NewNRGBA(image.Rect(0, 0, 2, 3))
colors := [3][2]color.NRGBA{
{{R: 10, G: 20, B: 30, A: 255}, {R: 210, G: 50, B: 80, A: 255}},
{{R: 30, G: 200, B: 40, A: 255}, {R: 40, G: 50, B: 220, A: 255}},
{{R: 255, G: 255, B: 255, A: 255}, {A: 255}},
}
for y, row := range colors {
for x, c := range row {
tiny.SetNRGBA(x, y, c)
}
}
wide := image.NewNRGBA(image.Rect(0, 0, 1024, 600))
draw.Draw(wide, wide.Bounds(), image.NewUniform(color.NRGBA{R: 210, G: 33, B: 77, A: 255}), image.Point{}, draw.Src)
for _, tc := range []struct {
name string
image image.Image
shape [3]int
poolCount int
lastPool []int32
lastPos []int32
pixels []float32
tokens int
}{
{"tiny", tiny, [3]int{2, 729, 588}, 392, []int32{1457, -1, -1, -1}, []int32{1, 26, 26}, []float32{10, 10, 10, 30, 0}, 410},
{"wide", wide, [3]int{9, 729, 588}, 1162, []int32{6532, 6533, 6559, 6560}, []int32{1, 45, 83}, []float32{210, 210, 210, 77, 210}, 1189},
} {
t.Run(tc.name, func(t *testing.T) {
got, err := ProcessImage(tc.image, DefaultMaxCrops)
if err != nil {
t.Fatal(err)
}
if got.PixelShape != tc.shape || got.TokenPoolingShape != [2]int{tc.poolCount, 4} {
t.Fatalf("shapes = %v, %v, want %v, [%d 4]", got.PixelShape, got.TokenPoolingShape, tc.shape, tc.poolCount)
}
for at, want := range map[int][]int32{
0: {0, 1, 27, 28}, 195: {728, -1, -1, -1}, 196: {729, 730, 756, 757},
} {
if actual := got.TokenPooling[at*4 : at*4+4]; !slices.Equal(actual, want) {
t.Errorf("pool %d = %v, want %v", at, actual, want)
}
}
if actual := got.TokenPooling[len(got.TokenPooling)-4:]; !slices.Equal(actual, tc.lastPool) {
t.Errorf("last pool = %v, want %v", actual, tc.lastPool)
}
if actual := got.PatchPosIDs[len(got.PatchPosIDs)-3:]; !slices.Equal(actual, tc.lastPos) {
t.Errorf("last position = %v, want %v", actual, tc.lastPos)
}
var sampled []float32
for _, at := range []int{0, 3, 42, 587} {
sampled = append(sampled, got.Pixels[at])
}
sampled = append(sampled, got.Pixels[len(got.Pixels)-588])
if !slices.Equal(sampled, tc.pixels) {
t.Errorf("pixel samples = %v, want %v", sampled, tc.pixels)
}
var encoded bytes.Buffer
if err := png.Encode(&encoded, tc.image); err != nil {
t.Fatal(err)
}
count, err := ImageTokenCount(encoded.Bytes(), DefaultMaxCrops)
if err != nil || count != tc.tokens {
t.Errorf("token count = %d, %v, want %d", count, err, tc.tokens)
}
})
}
}
+81
View File
@@ -0,0 +1,81 @@
package renderers
import (
"errors"
"slices"
"strconv"
"strings"
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/types/model"
)
type Molmo3Renderer struct {
useImgTags bool
}
func (r *Molmo3Renderer) Render(messages []api.Message, tools []api.Tool, think *api.ThinkValue) (string, error) {
if len(tools) > 0 {
return "", errors.New("molmo3: tools are not supported")
}
messages = slices.DeleteFunc(slices.Clone(messages), func(message api.Message) bool {
return message.Role == "system"
})
totalImages := 0
for _, message := range messages {
totalImages += len(message.Images)
}
var out strings.Builder
imageIndex := 0
for i, message := range messages {
if len(message.ToolCalls) > 0 {
return "", errors.New("molmo3: tools are not supported")
}
if strings.Contains(message.Content, "<|video|>") {
return "", errors.New("molmo3: video is not supported")
}
var content strings.Builder
for range message.Images {
imageIndex++
if totalImages > 1 {
content.WriteString("Image ")
content.WriteString(strconv.Itoa(imageIndex))
}
if r.useImgTags {
content.WriteString("[img-")
content.WriteString(strconv.Itoa(imageIndex - 1))
content.WriteString("]")
} else {
content.WriteString("<|image|>")
}
}
content.WriteString(message.Content)
switch {
case message.Role == "user" && i%2 == 0:
if i > 0 {
out.WriteString("<|im_end|>\n")
}
out.WriteString("<|im_start|>user\n")
out.WriteString(content.String())
out.WriteString("<|im_end|>\n")
case message.Role == "assistant" && i%2 == 1:
out.WriteString("<|im_start|>assistant\n")
out.WriteString(content.String())
default:
return "", errors.New("molmo3: conversation roles must alternate user/assistant/user/assistant/...")
}
}
if len(messages) == 0 || messages[len(messages)-1].Role != "assistant" {
out.WriteString("<|im_start|>assistant\n")
}
return out.String(), nil
}
func (r *Molmo3Renderer) LeadingBOS() string { return "" }
func (r *Molmo3Renderer) Thinking() *model.Thinking { return nil }
+187
View File
@@ -0,0 +1,187 @@
package renderers
import (
"bytes"
"crypto/sha256"
"encoding/json"
"fmt"
"os"
"os/exec"
"slices"
"strings"
"testing"
)
const (
molmo3SourceRevision = "bf3b580d0f694d3851553f3974f54bbe349ce2f8"
molmo3TemplateSHA256 = "ca8881757179c6d72ee512b5fc445279320cdde6189e53b4952a52344e4430a2"
molmo3TemplatePath = "testdata/molmo3_chat_template.jinja"
)
type molmo3ReferenceResult struct {
Prompt string `json:"prompt"`
TokenIDs []int `json:"token_ids"`
ProcessorError string `json:"processor_error"`
JinjaError string `json:"jinja_error"`
}
func TestMolmo3RendererMatchesPublisher(t *testing.T) {
if os.Getenv("VERIFY_JINJA2") == "" {
t.Skip("set VERIFY_JINJA2=1 with MOLMO3_REFERENCE_PYTHON, MOLMO3_REFERENCE_SOURCE, and MOLMO3_TEST_TOKENIZER for live publisher parity")
}
python := os.Getenv("MOLMO3_REFERENCE_PYTHON")
source := os.Getenv("MOLMO3_REFERENCE_SOURCE")
tokenizer := os.Getenv("MOLMO3_TEST_TOKENIZER")
if python == "" || source == "" || tokenizer == "" {
t.Fatal("live Molmo 3 parity requires MOLMO3_REFERENCE_PYTHON, MOLMO3_REFERENCE_SOURCE, and MOLMO3_TEST_TOKENIZER")
}
revision, err := exec.Command("git", "-C", source, "rev-parse", "HEAD").Output()
if err != nil {
t.Fatalf("resolve publisher source revision: %v", err)
}
if got := strings.TrimSpace(string(revision)); got != molmo3SourceRevision {
t.Fatalf("publisher source revision = %s, want %s", got, molmo3SourceRevision)
}
template, err := os.ReadFile(molmo3TemplatePath)
if err != nil {
t.Fatal(err)
}
if got := fmt.Sprintf("%x", sha256.Sum256(template)); got != molmo3TemplateSHA256 {
t.Fatalf("publisher template SHA256 = %s, want %s", got, molmo3TemplateSHA256)
}
for _, tc := range molmo3TestCases() {
t.Run(tc.name, func(t *testing.T) {
reference := renderMolmo3Reference(t, python, source, tokenizer, tc)
if tc.referenceError != "" {
if !strings.Contains(reference.ProcessorError, tc.referenceError) {
t.Fatalf("publisher processor error = %q, want error containing %q", reference.ProcessorError, tc.referenceError)
}
if reference.JinjaError == "" {
t.Fatal("publisher Jinja template unexpectedly accepted invalid roles")
}
} else {
if reference.ProcessorError != "" || reference.JinjaError != "" {
t.Fatalf("publisher rendering failed: processor=%q jinja=%q", reference.ProcessorError, reference.JinjaError)
}
if reference.Prompt != tc.want {
t.Fatalf("publisher prompt mismatch\n got: %q\nwant: %q", reference.Prompt, tc.want)
}
if !slices.Equal(reference.TokenIDs, tc.wantTokenIDs) {
t.Fatalf("publisher token IDs mismatch\n got: %v\nwant: %v", reference.TokenIDs, tc.wantTokenIDs)
}
}
got, err := (&Molmo3Renderer{}).Render(tc.messages, tc.tools, nil)
if tc.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
t.Fatalf("Render error = %v, want error containing %q", err, tc.wantErr)
}
if got != "" {
t.Fatalf("Render prompt = %q on error, want empty", got)
}
return
}
if err != nil {
t.Fatal(err)
}
if got != reference.Prompt {
t.Fatalf("renderer differs from publisher\n got: %q\nwant: %q", got, reference.Prompt)
}
})
}
}
func renderMolmo3Reference(t *testing.T, python, source, tokenizer string, tc molmo3TestCase) molmo3ReferenceResult {
t.Helper()
// The renderer ignores system messages; the reference template does not.
messages := make([]map[string]any, 0, len(tc.messages))
for _, message := range tc.messages {
if message.Role == "system" {
continue
}
item := map[string]any{"role": message.Role, "content": message.Content}
content := message.Content
var parts []map[string]any
if strings.Contains(content, "<|video|>") {
parts = append(parts, map[string]any{"type": "video"})
content = strings.ReplaceAll(content, "<|video|>", "")
}
for range message.Images {
parts = append(parts, map[string]any{"type": "image"})
}
if len(parts) > 0 {
if content != "" {
parts = append(parts, map[string]any{"type": "text", "text": content})
}
item["content"] = parts
}
if len(message.ToolCalls) > 0 {
item["tool_calls"] = message.ToolCalls
}
messages = append(messages, item)
}
input, err := json.Marshal(map[string]any{
"messages": messages,
"tools": tc.tools,
"add_generation_prompt": len(messages) == 0 || messages[len(messages)-1]["role"] != "assistant",
})
if err != nil {
t.Fatal(err)
}
const script = `
import hashlib
import json
import sys
from pathlib import Path
source, template_path, tokenizer_path = sys.argv[1:4]
sys.path.insert(0, source)
from transformers import AutoTokenizer
from transformers.utils.chat_template_utils import render_jinja_template
from molmo3_hf import Molmo3Processor
case = json.load(sys.stdin)
tokenizer = AutoTokenizer.from_pretrained(tokenizer_path, local_files_only=True)
processor = Molmo3Processor.from_pretrained(tokenizer_path, local_files_only=True)
template = Path(template_path).read_text()
result = {}
try:
processor_prompt = processor._format_chat(case["messages"], case["add_generation_prompt"])
except Exception as exc:
result["processor_error"] = str(exc)
try:
rendered, _ = render_jinja_template(
[case["messages"]], tools=case.get("tools"), chat_template=template,
add_generation_prompt=case["add_generation_prompt"])
jinja_prompt = rendered[0]
except Exception as exc:
result["jinja_error"] = str(exc)
if "processor_error" not in result and "jinja_error" not in result:
if processor_prompt != jinja_prompt:
raise AssertionError((processor_prompt, jinja_prompt))
result["prompt"] = processor_prompt
result["token_ids"] = tokenizer.encode(processor_prompt, add_special_tokens=False)
elif "processor_error" not in result or "jinja_error" not in result:
raise AssertionError("processor and Jinja disagreement: " + repr(result))
json.dump(result, sys.stdout, ensure_ascii=False)
`
cmd := exec.Command(python, "-c", script, source, molmo3TemplatePath, tokenizer)
cmd.Stdin = bytes.NewReader(input)
cmd.Env = slices.DeleteFunc(os.Environ(), func(entry string) bool {
return strings.HasPrefix(entry, "PYTHONPATH=") || strings.HasPrefix(entry, "PYTHONHOME=")
})
cmd.Env = append(cmd.Env, "HF_HUB_OFFLINE=1", "TRANSFORMERS_OFFLINE=1")
var stderr bytes.Buffer
cmd.Stderr = &stderr
output, err := cmd.Output()
if err != nil {
t.Fatalf("execute live publisher reference: %v\n%s", err, stderr.String())
}
var result molmo3ReferenceResult
if err := json.Unmarshal(output, &result); err != nil {
t.Fatalf("decode publisher reference output %q: %v", output, err)
}
return result
}
+252
View File
@@ -0,0 +1,252 @@
package renderers
import (
"reflect"
"slices"
"strings"
"testing"
"github.com/ollama/ollama/api"
)
type molmo3TestCase struct {
name string
messages []api.Message
tools []api.Tool
want string
wantTokenIDs []int
wantErr string
referenceError string
}
func molmo3TestCases() []molmo3TestCase {
tool := api.Tool{Type: "function", Function: api.ToolFunction{Name: "noop"}}
toolCall := api.ToolCall{Function: api.ToolCallFunction{Name: "noop", Arguments: api.NewToolCallFunctionArguments()}}
return []molmo3TestCase{
{
name: "first user and generation prompt",
messages: []api.Message{{Role: "user", Content: "Hello, Molmo 3!"}},
want: "<|im_start|>user\nHello, Molmo 3!<|im_end|>\n<|im_start|>assistant\n",
wantTokenIDs: []int{151644, 872, 198, 9707, 11, 32418, 6355, 220, 18, 0, 151645, 198, 151644, 77091, 198},
},
{
name: "assistant history and later user",
messages: []api.Message{
{Role: "user", Content: "Name a color."},
{Role: "assistant", Content: "Blue."},
{Role: "user", Content: "Now name a fruit."},
},
want: "<|im_start|>user\nName a color.<|im_end|>\n<|im_start|>assistant\nBlue.<|im_end|>\n<|im_start|>user\nNow name a fruit.<|im_end|>\n<|im_start|>assistant\n",
wantTokenIDs: []int{151644, 872, 198, 675, 264, 1894, 13, 151645, 198, 151644, 77091, 198, 10331, 13, 151645, 198, 151644, 872, 198, 7039, 829, 264, 13779, 13, 151645, 198, 151644, 77091, 198},
},
{
name: "one image",
messages: []api.Message{
{Role: "user", Content: "Describe this image.", Images: []api.ImageData{api.ImageData("image-a")}},
},
want: "<|im_start|>user\n<|image|>Describe this image.<|im_end|>\n<|im_start|>assistant\n",
wantTokenIDs: []int{151644, 872, 198, 151941, 74785, 419, 2168, 13, 151645, 198, 151644, 77091, 198},
},
{
name: "multiple images",
messages: []api.Message{
{Role: "user", Content: "Compare these images.", Images: []api.ImageData{api.ImageData("image-a"), api.ImageData("image-b")}},
},
want: "<|im_start|>user\nImage 1<|image|>Image 2<|image|>Compare these images.<|im_end|>\n<|im_start|>assistant\n",
wantTokenIDs: []int{151644, 872, 198, 1906, 220, 16, 151941, 1906, 220, 17, 151941, 27374, 1493, 5335, 13, 151645, 198, 151644, 77091, 198},
},
{
name: "image numbering across turns",
messages: []api.Message{
{Role: "user", Content: "What is here?", Images: []api.ImageData{api.ImageData("image-a")}},
{Role: "assistant", Content: "A cat."},
{Role: "user", Content: "And here?", Images: []api.ImageData{api.ImageData("image-b")}},
},
want: "<|im_start|>user\nImage 1<|image|>What is here?<|im_end|>\n<|im_start|>assistant\nA cat.<|im_end|>\n<|im_start|>user\nImage 2<|image|>And here?<|im_end|>\n<|im_start|>assistant\n",
wantTokenIDs: []int{151644, 872, 198, 1906, 220, 16, 151941, 3838, 374, 1588, 30, 151645, 198, 151644, 77091, 198, 32, 8251, 13, 151645, 198, 151644, 872, 198, 1906, 220, 17, 151941, 3036, 1588, 30, 151645, 198, 151644, 77091, 198},
},
{
name: "assistant prefill",
messages: []api.Message{
{Role: "user", Content: "Name a color."},
{Role: "assistant", Content: "Blue."},
},
want: "<|im_start|>user\nName a color.<|im_end|>\n<|im_start|>assistant\nBlue.",
wantTokenIDs: []int{151644, 872, 198, 675, 264, 1894, 13, 151645, 198, 151644, 77091, 198, 10331, 13},
},
{
name: "empty assistant prefill",
messages: []api.Message{
{Role: "user", Content: "Name a color."},
{Role: "assistant"},
},
want: "<|im_start|>user\nName a color.<|im_end|>\n<|im_start|>assistant\n",
wantTokenIDs: []int{151644, 872, 198, 675, 264, 1894, 13, 151645, 198, 151644, 77091, 198},
},
{
name: "whitespace assistant prefill",
messages: []api.Message{
{Role: "user", Content: "Name a color."},
{Role: "assistant", Content: " \n"},
},
want: "<|im_start|>user\nName a color.<|im_end|>\n<|im_start|>assistant\n \n",
wantTokenIDs: []int{151644, 872, 198, 675, 264, 1894, 13, 151645, 198, 151644, 77091, 26809},
},
{
name: "image assistant prefill",
messages: []api.Message{
{Role: "user", Content: "Describe this image.", Images: []api.ImageData{api.ImageData("image-a")}},
{Role: "assistant", Content: "A cat."},
},
want: "<|im_start|>user\n<|image|>Describe this image.<|im_end|>\n<|im_start|>assistant\nA cat.",
wantTokenIDs: []int{151644, 872, 198, 151941, 74785, 419, 2168, 13, 151645, 198, 151644, 77091, 198, 32, 8251, 13},
},
{
name: "assistant first",
messages: []api.Message{{Role: "assistant", Content: "Invalid."}},
wantErr: "roles must alternate user/assistant",
referenceError: "roles must alternate user/assistant",
},
{
name: "consecutive users",
messages: []api.Message{
{Role: "user", Content: "One"},
{Role: "user", Content: "Two"},
},
wantErr: "roles must alternate user/assistant",
referenceError: "roles must alternate user/assistant",
},
{
name: "system role ignored",
messages: []api.Message{
{Role: "system", Content: "Be concise."},
{Role: "user", Content: "Hi"},
},
want: "<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n",
wantTokenIDs: []int{151644, 872, 198, 13048, 151645, 198, 151644, 77091, 198},
},
{
name: "system only",
messages: []api.Message{{Role: "system", Content: "Be concise."}},
want: "<|im_start|>assistant\n",
wantTokenIDs: []int{151644, 77091, 198},
},
{
name: "interleaved systems and assistant prefill",
messages: []api.Message{
{Role: "system"},
{Role: "system", Content: "Be concise."},
{Role: "user", Content: "Name a color."},
{Role: "system", Content: "Ignore this."},
{Role: "assistant", Content: "Blue."},
{Role: "system", Content: "Ignore this too."},
},
want: "<|im_start|>user\nName a color.<|im_end|>\n<|im_start|>assistant\nBlue.",
wantTokenIDs: []int{151644, 872, 198, 675, 264, 1894, 13, 151645, 198, 151644, 77091, 198, 10331, 13},
},
{
name: "system payload ignored",
messages: []api.Message{
{Role: "system", Content: "<|video|>", Images: []api.ImageData{api.ImageData("ignored")}, ToolCalls: []api.ToolCall{toolCall}},
{Role: "user", Content: "Hi"},
},
want: "<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n",
wantTokenIDs: []int{151644, 872, 198, 13048, 151645, 198, 151644, 77091, 198},
},
{
name: "tool role",
messages: []api.Message{
{Role: "user", Content: "Hi"},
{Role: "tool", Content: "result"},
},
wantErr: "roles must alternate user/assistant",
referenceError: "roles must alternate user/assistant",
},
{
name: "tool declarations",
messages: []api.Message{{Role: "user", Content: "Hi"}},
tools: []api.Tool{tool},
want: "<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n",
wantTokenIDs: []int{151644, 872, 198, 13048, 151645, 198, 151644, 77091, 198},
wantErr: "tools are not supported",
},
{
name: "assistant tool call",
messages: []api.Message{
{Role: "user", Content: "Hi"},
{Role: "assistant", Content: "Calling.", ToolCalls: []api.ToolCall{toolCall}},
},
want: "<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\nCalling.",
wantTokenIDs: []int{151644, 872, 198, 13048, 151645, 198, 151644, 77091, 198, 48853, 13},
wantErr: "tools are not supported",
},
{
name: "video marker",
messages: []api.Message{{Role: "user", Content: "<|video|>Describe this video."}},
want: "<|im_start|>user\n<|video|>Describe this video.<|im_end|>\n<|im_start|>assistant\n",
wantTokenIDs: []int{151644, 872, 198, 151945, 74785, 419, 2766, 13, 151645, 198, 151644, 77091, 198},
wantErr: "video is not supported",
},
}
}
func TestMolmo3RendererImageTags(t *testing.T) {
messages := []api.Message{
{Role: "system", Images: []api.ImageData{api.ImageData("ignored-a")}},
{Role: "user", Content: "What is here?", Images: []api.ImageData{api.ImageData("image-a")}},
{Role: "assistant", Content: "A cat."},
{Role: "system", Images: []api.ImageData{api.ImageData("ignored-b")}},
{Role: "user", Content: "And here?", Images: []api.ImageData{api.ImageData("image-b")}},
}
got, err := (&Molmo3Renderer{useImgTags: true}).Render(messages, nil, nil)
if err != nil {
t.Fatal(err)
}
want := "<|im_start|>user\nImage 1[img-0]What is here?<|im_end|>\n<|im_start|>assistant\nA cat.<|im_end|>\n<|im_start|>user\nImage 2[img-1]And here?<|im_end|>\n<|im_start|>assistant\n"
if got != want {
t.Fatalf("Render prompt mismatch\n got: %q\nwant: %q", got, want)
}
}
func TestMolmo3RendererRegistered(t *testing.T) {
oldRenderImgTags := RenderImgTags
RenderImgTags = true
t.Cleanup(func() { RenderImgTags = oldRenderImgTags })
messages := []api.Message{{Role: "user", Content: "Describe.", Images: []api.ImageData{api.ImageData("image-a")}}}
got, err := RenderWithRenderer("molmo3", messages, nil, nil)
if err != nil {
t.Fatal(err)
}
want := "<|im_start|>user\n[img-0]Describe.<|im_end|>\n<|im_start|>assistant\n"
if got != want {
t.Fatalf("registered renderer prompt mismatch\n got: %q\nwant: %q", got, want)
}
}
func TestMolmo3Renderer(t *testing.T) {
for _, tc := range molmo3TestCases() {
t.Run(tc.name, func(t *testing.T) {
original := slices.Clone(tc.messages)
got, err := (&Molmo3Renderer{}).Render(tc.messages, tc.tools, nil)
if !reflect.DeepEqual(tc.messages, original) {
t.Fatal("Render mutated the input messages")
}
if tc.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
t.Fatalf("Render error = %v, want error containing %q", err, tc.wantErr)
}
if got != "" {
t.Fatalf("Render prompt = %q on error, want empty", got)
}
return
}
if err != nil {
t.Fatal(err)
}
if got != tc.want {
t.Fatalf("Render prompt mismatch\n got: %q\nwant: %q", got, tc.want)
}
})
}
}
+2
View File
@@ -87,6 +87,8 @@ func rendererForName(name string) Renderer {
case "deepseek3.1":
renderer := &DeepSeek3Renderer{IsThinking: true, Variant: Deepseek31}
return renderer
case "molmo3":
return &Molmo3Renderer{useImgTags: RenderImgTags}
case "olmo3":
renderer := &Olmo3Renderer{UseExtendedSystemMessage: false}
return renderer
+64
View File
@@ -0,0 +1,64 @@
{#- Count the images of the conversation. If there are more than one, each is prefixed with "Image <n>" -#}
{%- set counts = namespace(images=0, image=0) -%}
{%- for message in messages -%}
{%- if message['content'] is not string -%}
{%- for item in message['content'] -%}
{%- if item['type'] == 'image' -%}
{%- set counts.images = counts.images + 1 -%}
{%- endif -%}
{%- endfor -%}
{%- endif -%}
{%- endfor -%}
{%- for message in messages -%}
{%- if (message['role'] == 'user') != (loop.index0 % 2 == 0) or message['role'] not in ['user', 'assistant'] -%}
{{- raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') -}}
{%- endif -%}
{%- set text = namespace(value='') -%}
{%- if message['content'] is string -%}
{%- set text.value = message['content'] -%}
{%- else -%}
{%- for item in message['content'] -%}
{%- if item['type'] == 'image' -%}
{%- set counts.image = counts.image + 1 -%}
{%- if counts.images > 1 -%}
{%- set text.value = text.value + 'Image ' + counts.image|string -%}
{%- endif -%}
{%- set text.value = text.value + '<|image|>' -%}
{%- elif item['type'] == 'video' -%}
{%- set text.value = text.value + '<|video|>' -%}
{%- elif item['type'] == 'text' -%}
{%- if item['style'] is defined and item['style'] -%}
{%- set text.value = text.value + item['style'] + ': ' + item['text'] -%}
{%- else -%}
{%- set text.value = text.value + item['text'] -%}
{%- endif -%}
{%- elif item['type'] == 'points' -%}
{%- set coords = namespace(value='') -%}
{%- for coordinate in item['coordinates'] -%}
{%- set coords.value = coords.value + '<|POINT_PATCH|><|POINT_SUBPATCH|><|POINT_LOC|>' + loop.index|string -%}
{%- endfor -%}
{%- set tag = '<points coords="' + coords.value + '<|POINT_PATCH|>"' -%}
{%- if item['label'] is defined and item['label'] -%}
{%- set text.value = text.value + tag + '>' + item['label'] + '</points>' -%}
{%- else -%}
{%- set text.value = text.value + tag + '/>' -%}
{%- endif -%}
{%- endif -%}
{%- endfor -%}
{%- endif -%}
{%- if message['role'] == 'user' -%}
{%- if not loop.first -%}
{{- '<|im_end|>\n' -}}
{%- endif -%}
{{- '<|im_start|>user\n' + text.value + '<|im_end|>\n' -}}
{%- else -%}
{{- '<|im_start|>assistant\n' + text.value -}}
{%- endif -%}
{%- endfor -%}
{%- if add_generation_prompt -%}
{{- '<|im_start|>assistant\n' -}}
{%- endif -%}
+3
View File
@@ -107,6 +107,9 @@ func imageTaggedMessages(m *Model, msgs []api.Message, start int, clearImages bo
var media []llm.MediaData
for cnt, msg := range renderMsgs[start:] {
if m.Config.Renderer == "molmo3" && msg.Role == "system" {
continue
}
if slices.Contains(m.Config.ModelFamilies, "mllama") && len(msg.Images) > 1 {
return nil, nil, errors.New("this model only supports one image while more than one image requested")
}
+48
View File
@@ -631,6 +631,54 @@ func TestChatPromptLFM3PreservesIndexedImagePlaceholders(t *testing.T) {
}
}
func TestChatPromptMolmo3IgnoresSystemMessages(t *testing.T) {
m := Model{Config: model.ConfigV2{ModelFormat: "safetensors", Renderer: "molmo3"}, System: "Be concise."}
messages := []api.Message{
{Role: "user", Content: "What is here?", Images: []api.ImageData{api.ImageData("image-a")}},
{Role: "assistant", Content: "A cat."},
{Role: "system", Content: "<|video|>", Images: []api.ImageData{api.ImageData("ignored-a")}},
{Role: "user", Content: "And here?", Images: []api.ImageData{api.ImageData("image-b")}},
{Role: "assistant", Content: "A dog."},
{Role: "system", Images: []api.ImageData{api.ImageData("ignored-b")}},
}
original := slices.Clone(messages)
opts := api.DefaultOptions()
prompt, media, err := chatPrompt(t.Context(), &m, nil, &opts, chatMessagesForRequest(&m, messages), nil, nil, false)
if err != nil {
t.Fatal(err)
}
want := "<|im_start|>user\nImage 1[img-0]What is here?<|im_end|>\n<|im_start|>assistant\nA cat.<|im_end|>\n<|im_start|>user\nImage 2[img-1]And here?<|im_end|>\n<|im_start|>assistant\nA dog."
if prompt != want {
t.Fatalf("prompt = %q, want %q", prompt, want)
}
if len(media) != 2 {
t.Fatalf("media count = %d, want 2", len(media))
}
for i, want := range []string{"image-a", "image-b"} {
if media[i].ID != i || string(media[i].Data) != want {
t.Errorf("media %d = %+v, want image %q", i, media[i], want)
}
}
if diff := cmp.Diff(original, messages); diff != "" {
t.Fatalf("input messages changed (-want +got):\n%s", diff)
}
}
func TestImageTaggedMessagesPreservesOtherSystemImages(t *testing.T) {
m := Model{Config: testConfigWithRenderer("qwen3-vl-instruct")}
messages := []api.Message{
{Role: "system", Images: []api.ImageData{api.ImageData("system-image")}},
{Role: "user", Images: []api.ImageData{api.ImageData("user-image")}},
}
_, media, err := imageTaggedMessages(&m, messages, 0, false)
if err != nil {
t.Fatal(err)
}
if len(media) != 2 || string(media[0].Data) != "system-image" || string(media[1].Data) != "user-image" {
t.Fatalf("media = %+v, want both system and user images", media)
}
}
func TestRenderPromptResolvesDynamicGemma4Renderer(t *testing.T) {
msgs := []api.Message{{Role: "user", Content: "Hello"}}