server: add molmo3 grounding support (#20131)

This commit is contained in:
Patrick Devine authored and GitHub committed 2026-12-03 11:31:14 -08:00
1 parent ce94980ea8
commit 641fe1b18f
30 files changed
+4300 -67

No files matched your search

+2
View File
@@ -209,6 +209,8 @@ type CompletionRequest struct {
Format json.RawMessage
Media []MediaData
Options *api.Options
// JSONDocument selects model-decoded content instead of a JSON sampling grammar.
JSONDocument bool
Shift bool
Truncate bool
+16 -11
View File
@@ -119,12 +119,13 @@ func (c *Client) WaitUntilRunning(ctx context.Context) error {
}
type CompletionRequest struct {
Prompt string
Media []llm.MediaData
Format json.RawMessage
Options api.Options
Logprobs bool
TopLogprobs int
Prompt string
Media []llm.MediaData
Format json.RawMessage
Options api.Options
Logprobs bool
TopLogprobs int
JSONDocument bool
}
type CompletionResponse struct {
@@ -162,6 +163,9 @@ func (c *Client) Close() error {
// API's format as a json_schema tag, behind the free thinking the response
// begins with when there is any.
func requestGrammar(req llm.CompletionRequest) json.RawMessage {
if req.JSONDocument {
return nil
}
schema := req.Format
switch string(schema) {
case ``, `null`, `""`:
@@ -226,11 +230,12 @@ func jsonString(s string) string {
// Completion implements llm.LlamaServer.
func (c *Client) Completion(ctx context.Context, req llm.CompletionRequest, fn func(llm.CompletionResponse)) error {
creq := CompletionRequest{
Prompt: req.Prompt,
Media: req.Media,
Format: requestGrammar(req),
Logprobs: req.Logprobs,
TopLogprobs: req.TopLogprobs,
Prompt: req.Prompt,
Media: req.Media,
Format: requestGrammar(req),
Logprobs: req.Logprobs,
TopLogprobs: req.TopLogprobs,
JSONDocument: req.JSONDocument,
}
if req.Options != nil {
creq.Options = *req.Options
+155
View File
@@ -0,0 +1,155 @@
package mlxrunner
import (
"bufio"
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/llm"
)
func TestCompletionJSONDocumentRequest(t *testing.T) {
for _, document := range []bool{false, true} {
name := "grammar"
if document {
name = "document"
}
t.Run(name, func(t *testing.T) {
requests := make(chan CompletionRequest, 1)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req CompletionRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
t.Error(err)
w.WriteHeader(http.StatusBadRequest)
return
}
requests <- req
if err := json.NewEncoder(w).Encode(CompletionResponse{Content: "result", Done: true}); err != nil {
t.Error(err)
}
}))
defer server.Close()
client := &Client{port: server.Listener.Addr().(*net.TCPAddr).Port, client: server.Client()}
var output llm.CompletionResponse
err := client.Completion(t.Context(), llm.CompletionRequest{
Prompt: "prompt", Format: json.RawMessage(`"json"`), JSONDocument: document,
}, func(response llm.CompletionResponse) { output = response })
if err != nil {
t.Fatal(err)
}
got := <-requests
wantGrammar := `{"type":"structural_tag","format":{"type":"json_schema","json_schema":{"type":"object"}}}`
if document {
wantGrammar = "null"
if grammar := requestGrammar(llm.CompletionRequest{Format: json.RawMessage(`"json"`), JSONDocument: true}); grammar != nil {
t.Fatalf("document sampling grammar = %s", grammar)
}
}
if got.JSONDocument != document || string(got.Format) != wantGrammar || got.Prompt != "prompt" {
t.Fatalf("request = %+v, want document=%t, grammar=%s", got, document, wantGrammar)
}
if output.Content != "result" || !output.Done {
t.Fatalf("response = %+v", output)
}
})
}
}
func TestDocumentRLEClientReaders(t *testing.T) {
// A synthetic one-column alternating mask has an initial zero run,
// followed by one-pixel runs; the fourth and later counts encode deltas.
const pixels = 128 << 10
data, err := json.Marshal(map[string]any{
"text": `<seg id="1">猫</seg>`, "type": "text",
"multi_modal": []any{map[string]any{
"type": "segmentation", "label": "猫", "grounding_id": 1,
"annotation_image_size": nil, "mm_ids": nil, "confidence": nil,
"text": `<seg coords="<|PATCH_1|><|MASK|><|PATCH_32768|>">猫</seg>`,
"masks": []any{map[string]any{"size": []int{pixels, 1}, "counts": "011" + strings.Repeat("0", pixels-2)}},
}},
})
if err != nil {
t.Fatal(err)
}
if len(data) <= bufio.MaxScanTokenSize {
t.Fatal("fixture does not exceed the internal frame limit")
}
frames, err := documentResponses(string(data), CompletionResponse{Done: true, EvalCount: 19})
if err != nil {
t.Fatal(err)
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
enc := json.NewEncoder(w)
if r.URL.Path == "/completion" {
for _, frame := range frames {
if err := enc.Encode(frame); err != nil {
t.Error(err)
return
}
}
return
}
var req api.ChatRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
t.Error(err)
w.WriteHeader(http.StatusBadRequest)
return
}
if req.Stream != nil && !*req.Stream {
if err := enc.Encode(api.ChatResponse{Message: api.Message{Role: "assistant", Content: string(data)}, Done: true}); err != nil {
t.Error(err)
}
return
}
for _, frame := range frames {
if err := enc.Encode(api.ChatResponse{Message: api.Message{Role: "assistant", Content: frame.Content}, Done: frame.Done}); err != nil {
t.Error(err)
return
}
}
}))
defer server.Close()
client := &Client{port: server.Listener.Addr().(*net.TCPAddr).Port, client: server.Client()}
var content strings.Builder
done := false
if err := client.Completion(t.Context(), llm.CompletionRequest{JSONDocument: true}, func(response llm.CompletionResponse) {
if done {
t.Error("internal response after Done")
}
content.WriteString(response.Content)
done = response.Done
}); err != nil {
t.Fatal(err)
}
if !done || content.String() != string(data) {
t.Fatal("internal client changed the document")
}
base, err := url.Parse(server.URL)
if err != nil {
t.Fatal(err)
}
apiClient := api.NewClient(base, server.Client())
for _, stream := range []bool{false, true} {
content.Reset()
done = false
if err := apiClient.Chat(t.Context(), &api.ChatRequest{Stream: &stream}, func(response api.ChatResponse) error {
if done {
t.Error("public response after Done")
}
content.WriteString(response.Message.Content)
done = response.Done
return nil
}); err != nil {
t.Fatalf("stream=%t: %v", stream, err)
}
if !done || content.String() != string(data) {
t.Fatalf("public client changed the document with stream=%t", stream)
}
}
}
+105
View File
@@ -0,0 +1,105 @@
package mlxrunner
import (
"errors"
"unicode/utf8"
"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/sample"
)
// groundingDecoder keeps the ordinary one-token-ahead emission boundary. Its
// pending successor has not been forwarded or resolved when drain returns it.
type groundingDecoder struct {
*pipelinedDecoder
grounding model.GroundingState
seed, forwarded, drained bool
}
func newGroundingDecoder(r *Runner, slotID int, spec *speculationSession, caches []cache.Cache, seed *mlx.Array, position int, layout []any, grounding model.GroundingState) *groundingDecoder {
d := &groundingDecoder{
pipelinedDecoder: &pipelinedDecoder{
r: r, slotID: slotID, spec: spec, caches: caches, position: position, layout: layout,
pending: sample.Result{Token: seed}, scope: mlx.NewScope(),
},
grounding: grounding, seed: true,
}
d.scope.Attach(seed)
_, d.err = d.advance()
return d
}
func (d *groundingDecoder) advance() (sample.Result, error) {
previous := d.pending
var resolveErr error
logits := mlx.ScopedArrays(func() []*mlx.Array {
token := previous.Token.ExpandDims(-1)
b := &batch.Batch{InputIDs: token, SeqOffsets: []int32{int32(d.position)}, SeqQueryLens: []int32{1}, Layout: d.layout}
hidden, aux := d.grounding.Forward(b, cache.Layers(d.caches))
position := d.position
d.position++
d.forwarded = true
d.spec.committed(token, aux, position, nil)
logits, err := d.grounding.Logits(previous.Token.Int(), hidden)
resolveErr = err
return []*mlx.Array{logits}
})[0]
if resolveErr != nil {
return sample.Result{}, resolveErr
}
d.pending = d.sample(logits)
d.scope.Detach(previous.Arrays()...)
d.seed, d.forwarded = false, false
return previous, nil
}
func (d *groundingDecoder) next(int) ([]sample.Result, error) {
if d.err != nil {
return nil, d.err
}
previous, err := d.advance()
if err != nil {
d.err = err
return nil, err
}
return []sample.Result{previous}, nil
}
func (d *groundingDecoder) drain() ([]sample.Result, int, error) {
if d.drained || d.seed {
return nil, d.position, d.err
}
d.drained = true
d.scope.Detach(d.pending.Arrays()...)
return []sample.Result{d.pending}, d.position, d.err
}
func (d *groundingDecoder) close() {
if !d.forwarded {
d.spec.settle(d.pending.Token)
}
d.scope.Close()
}
// documentResponses leaves room for sixfold JSON escaping and the envelope
// in the runner client's default scanner buffer.
func documentResponses(content string, final CompletionResponse) ([]CompletionResponse, error) {
if !utf8.ValidString(content) {
return nil, errors.New("molmo3: document contains invalid UTF-8")
}
const chunkSize = 8 << 10
var responses []CompletionResponse
for len(content) > chunkSize {
n := chunkSize
for !utf8.RuneStart(content[n]) {
n--
}
responses = append(responses, CompletionResponse{Content: content[:n]})
content = content[n:]
}
final.Content = content
return append(responses, final), nil
}
+150
View File
@@ -0,0 +1,150 @@
package mlxrunner
import (
"context"
"fmt"
"slices"
"strings"
"testing"
"github.com/ollama/ollama/llm"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/sample"
)
func TestBatchSchedulerGroundingDispatch(t *testing.T) {
for _, tc := range []struct {
name string
groundingSlot int
cacheError bool
}{
{name: "grounding first", groundingSlot: 0},
{name: "grounding middle", groundingSlot: 1},
{name: "grounding last", groundingSlot: 2},
{name: "mixed cache error", groundingSlot: 0, cacheError: true},
} {
t.Run(tc.name, func(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
tok := newTestTokenizer(t, []int32{7})
m := &groundingTestModel{schedulingModel: schedulingModel{fakeMTPModel: fakeMTPModel{tok: tok}}}
r := &Runner{Model: m, Tokenizer: tok, Sampler: sample.New(4096), contextLength: 4096}
s := &batchScheduler{r: r, slots: make([]*batchSlot, 3)}
defer closeGroundingScheduler(s)
for i := range s.slots {
req := documentRequest(t, []int32{int32(i + 1)}, 20)
req.JSONDocument = i == tc.groundingSlot
if req.JSONDocument {
req.Prompt = "0[img-0]1"
req.Media = []llm.MediaData{{ID: 0, Kind: llm.MediaKindImage, Data: []byte{1}}}
if err := r.Prepare(&req); err != nil {
t.Fatal(err)
}
}
if tc.cacheError && i == 2 {
cs := []cache.Cache{cache.NewRotatingKVCache(8)}
s.slots[i] = &batchSlot{id: i, targets: cs, cache: newPrefixCache(cs)}
}
mlx.Scoped(func() { s.admitGeneration(req, i) })
}
// Finish one prefill per step, so every row can join the next decode.
for range len(s.slots) {
mlx.Scoped(func() { s.step() })
}
if tc.cacheError {
for i, slot := range s.slots {
if slot.request == nil || !slot.request.finished {
t.Fatalf("row %d was not finished by the cohort error", i)
}
responses := slot.request.responses
if len(responses) == 0 || responses[len(responses)-1].Error == nil || !strings.Contains(responses[len(responses)-1].Error.Error(), "incompatible") {
t.Fatalf("row %d lost the cache error: %+v", i, responses)
}
}
if m.state.closed != 1 || m.state.documentCalled {
t.Fatalf("failed grounding: closed=%d document=%t", m.state.closed, m.state.documentCalled)
}
return
}
m.batches = nil
before := make([]int, len(s.slots))
for i, slot := range s.slots {
before[i] = slot.request.output.generated
}
mlx.Scoped(func() { s.step() })
if !slices.Equal(m.batches, []int{1, 2}) {
t.Fatalf("forward batch order = %v, want grounding then ordinary batch", m.batches)
}
for i, slot := range s.slots {
if slot.request.output.generated != before[i]+1 {
t.Fatalf("row %d did not advance exactly once", i)
}
}
})
})
}
}
func TestBatchSchedulerGroundingKeepsSharedDrafting(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
tok := newTestTokenizer(t, []int32{7})
m := &groundingTestModel{schedulingModel: schedulingModel{fakeMTPModel: fakeMTPModel{tok: tok}}}
r := &Runner{Model: m, Tokenizer: tok, Sampler: sample.New(4096), contextLength: 4096}
r.cache = newPrefixCache(m.NewCaches())
r.spec = newSpeculation(r, pipelineSlot, &fakeMTPDraft{}, r.cache.caches, nil)
defer r.cache.close()
s := &batchScheduler{r: r, slots: make([]*batchSlot, 2)}
defer closeGroundingScheduler(s)
grounded := documentRequest(t, nil, 20)
grounded.Prompt = "0[img-0]1"
grounded.Media = []llm.MediaData{{ID: 0, Kind: llm.MediaKindImage, Data: []byte{1}}}
if err := r.Prepare(&grounded); err != nil {
t.Fatal(err)
}
ordinary := documentRequest(t, []int32{1}, 20)
ordinary.JSONDocument = false
mlx.Scoped(func() {
s.admitGeneration(grounded, 0)
s.admitGeneration(ordinary, 1)
})
for range 2 {
mlx.Scoped(func() { s.step() })
}
// The ordinary row is not running alone just because it is the only
// row left after grounding dispatch. Keep its shared depth controller.
if s.drafting.depths[draftBatchSize{rows: 1, drafting: 1}] == nil {
t.Fatal("grounding peer was excluded from the active-request count")
}
})
}
// dispatchBenchmarkDecoder excludes model work from the dispatch measurement.
type dispatchBenchmarkDecoder struct{}
func (dispatchBenchmarkDecoder) next(int) ([]sample.Result, error) { return nil, nil }
func (dispatchBenchmarkDecoder) drain() ([]sample.Result, int, error) {
return nil, 0, nil
}
func (dispatchBenchmarkDecoder) close() {}
func BenchmarkBatchSchedulerOrdinaryDispatch(b *testing.B) {
for _, wholeStep := range []bool{false, true} {
b.Run(fmt.Sprintf("whole_step=%t", wholeStep), func(b *testing.B) {
s := &batchScheduler{r: &Runner{}, slots: []*batchSlot{{request: &batchRequest{
request: request{Ctx: context.Background()},
decoder: dispatchBenchmarkDecoder{},
output: &generationOutput{limit: 100},
}}}}
b.ReportAllocs()
b.ResetTimer()
for range b.N {
if wholeStep {
s.step()
} else if err := s.decode(s.slots, 1); err != nil {
b.Fatal(err)
}
}
})
}
}
+524
View File
@@ -0,0 +1,524 @@
package mlxrunner
import (
"bytes"
"context"
"encoding/json"
"fmt"
"image"
"image/png"
"strings"
"testing"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
"github.com/ollama/ollama/mlxrunner/model"
"github.com/ollama/ollama/mlxrunner/model/molmo3"
"github.com/ollama/ollama/mlxrunner/sample"
)
// Synthetic weights run the real vision, grounding, decoder and KV paths.
func loadSchedulerMolmoImages(t *mlxtest.T, m *molmo3.Model) {
t.Helper()
shapes := map[string][]int{
"model.transformer.wte.embedding": {8, 8}, "model.transformer.wte.new_embedding": {128, 8},
"model.transformer.ln_f.weight": {8}, "lm_head.weight": {136, 8},
"model.transformer.blocks.0.att_proj.weight": {24, 8}, "model.transformer.blocks.0.attn_out.weight": {8, 8},
"model.transformer.blocks.0.ff_proj.weight": {16, 8}, "model.transformer.blocks.0.ff_out.weight": {8, 8},
"model.transformer.blocks.0.attn_norm.weight": {8}, "model.transformer.blocks.0.ff_norm.weight": {8},
"model.transformer.blocks.0.q_norm.weight": {8}, "model.transformer.blocks.0.k_norm.weight": {8},
"model.vit.patch_embedding.weight": {8, 588}, "model.vit.patch_embedding.bias": {8}, "model.vit.positional_embedding": {729, 8},
"model.subpatch_pos_embed.proj.weight": {16, 1536}, "model.subpatch_pos_embed.proj.bias": {16},
"model.connector.positional_embeddings.bias": {9, 16},
"model.connector.image_projector.w1.weight": {8, 8}, "model.connector.image_projector.w2.weight": {8, 8}, "model.connector.image_projector.w3.weight": {8, 8},
"model.x_norm.weight": {8},
"model.patch_k.weight": {4, 8}, "model.patch_k.bias": {4}, "model.patch_q.weight": {4, 8}, "model.patch_q.bias": {4},
"model.subpatch_q.weight": {2, 8}, "model.subpatch_q.bias": {2}, "model.loc_q.weight": {16, 8}, "model.loc_q.bias": {16},
"model.subpatch_hidden.weight": {4, 16}, "model.subpatch_hidden.bias": {4},
"model.subpatch_loc_k.w_in1.weight": {16, 4}, "model.subpatch_loc_k.w_in2.weight": {16, 8},
"model.subpatch_loc_k.w_out.weight": {18, 8}, "model.subpatch_loc_k.w_out.bias": {18},
"model.build_subpatch_embeddings.weight": {8, 4}, "model.build_subpatch_embeddings.bias": {8},
"model.build_location_embeddings.weight": {16, 8},
"model.subpatch_conv.proj.weight": {4, 16, 1, 1}, "model.subpatch_conv.proj.bias": {4},
"model.subpatch_conv.conv.weight": {4, 4, 3, 3}, "model.subpatch_conv.conv.bias": {4},
"model.mask_q.weight": {7, 8}, "model.mask_q.bias": {7},
"model.mask_affinity.conv.weight": {128, 16, 3, 3}, "model.mask_affinity.conv.bias": {128},
}
for _, name := range []string{"wq", "wk", "wv"} {
shapes["model.connector.image_pooling_2d."+name+".weight"] = []int{8, 16}
shapes["model.connector.image_pooling_2d."+name+".bias"] = []int{8}
}
for i := range 2 {
prefix := fmt.Sprintf("model.vit.transformer.resblocks.%d.", i)
for _, name := range []string{"attention.wq", "attention.wk", "attention.wv", "attention.wo", "feed_forward.w1", "feed_forward.w2"} {
shapes[prefix+name+".weight"] = []int{8, 8}
shapes[prefix+name+".bias"] = []int{8}
}
for _, name := range []string{"attention_norm", "ffn_norm"} {
shapes[prefix+name+".weight"] = []int{8}
shapes[prefix+name+".bias"] = []int{8}
}
}
weights := make(map[string]*mlx.Array, len(shapes))
for name, shape := range shapes {
n := 1
for _, d := range shape {
n *= d
}
values := make([]float32, n)
if strings.HasSuffix(name, "weight") && (strings.Contains(name, "norm") || strings.Contains(name, "ln_f")) {
for i := range values {
values[i] = 1
}
}
weights[name] = mlx.FromValues(values, shape...)
}
if err := m.LoadWeights(weights); err != nil {
t.Fatal(err)
}
loadSchedulerMolmo(m)
}
func schedulerImageRequest(t *mlxtest.T, m *molmo3.Model, limit, images int) request {
t.Helper()
var pngBytes bytes.Buffer
if err := png.Encode(&pngBytes, image.NewRGBA(image.Rect(0, 0, 16, 16))); err != nil {
t.Fatal(err)
}
segments := []model.Segment{{Tokens: []int32{0}}}
for range images {
segments = append(segments, model.Segment{Kind: "image", Data: pngBytes.Bytes()})
}
segments = append(segments, model.Segment{Tokens: []int32{1}})
prepared, err := m.PrepareMedia(segments)
if err != nil {
t.Fatal(err)
}
items, err := bindItems(prepared, segments)
if err != nil {
t.Fatal(err)
}
req := documentRequest(t, prepared.Tokens, limit)
req.MediaItems, req.Layout = items, prepared.Layout
return req
}
func closeGroundingScheduler(s *batchScheduler) {
for _, slot := range s.slots {
if slot == nil {
continue
}
if slot.request != nil && !slot.request.finished {
s.finish(slot, context.Canceled)
}
if slot.cache != nil {
slot.cache.close()
}
}
s.r.Sampler.Free()
}
func TestMolmoGroundedFreshPrefill(t *testing.T) {
m := schedulerMolmo(t, true)
mlxtest.Run(t, func(t *mlxtest.T) {
loadSchedulerMolmoImages(t, m)
r := &Runner{Model: m, Tokenizer: m.Tokenizer(), Sampler: sample.New(8192)}
s := &batchScheduler{r: r, slots: make([]*batchSlot, 1)}
defer closeGroundingScheduler(s)
ordinary := schedulerImageRequest(t, m, 1, 1)
ordinary.JSONDocument = false
mlx.Scoped(func() { s.admitGeneration(ordinary, 0) })
for range 8 {
mlx.Scoped(func() { s.step() })
}
if s.slots[0].request != nil {
t.Fatal("ordinary warmup did not finish")
}
document := schedulerImageRequest(t, m, 2, 1)
mlx.Scoped(func() { s.admitGeneration(document, 0) })
owned := s.slots[0].request
if owned == nil {
t.Fatal("document request was rejected")
}
if len(owned.session.remaining) != len(document.Tokens) {
t.Fatalf("grounded request reused %d prompt tokens", len(document.Tokens)-len(owned.session.remaining))
}
})
}
func TestMolmoGroundedDraftMaintenance(t *testing.T) {
m := schedulerMolmo(t, true)
mlxtest.Run(t, func(t *mlxtest.T) {
loadSchedulerMolmoImages(t, m)
draftCaches, _ := newMTPTestCaches(1)
draft := &fakeKVDraft{draftCaches: draftCaches}
r := &Runner{Model: m, Tokenizer: m.Tokenizer(), Sampler: sample.New(8192)}
r.cache = newPrefixCache(m.NewCaches())
r.spec = newSpeculation(r, pipelineSlot, draft, r.cache.caches, draftCaches)
defer r.cache.close()
s := &batchScheduler{r: r, slots: make([]*batchSlot, 1)}
defer closeGroundingScheduler(s)
req := schedulerImageRequest(t, m, 2, 2)
mlx.Scoped(func() { s.admitGeneration(req, 0) })
owner := s.slots[0].request
if owner == nil {
t.Fatal("document request was rejected")
}
for range 10 {
mlx.Scoped(func() { s.step() })
}
var final CompletionResponse
for len(req.Responses) > 0 {
res := <-req.Responses
if res.Error != nil {
t.Fatal(res.Error)
}
if res.Done {
final = res
}
}
if !final.Done || owner.spec.enabled || owner.spec.stats.drafted != 0 {
t.Fatalf("document drafted or failed: final=%+v spec=%+v", final, owner.spec)
}
for i, kv := range s.slots[0].cache.caches {
if got, want := kv.Offset(), len(req.Tokens)-1; got != want {
t.Fatalf("cache %d offset %d, want prompt lookahead boundary %d", i, got, want)
}
}
if len(draft.extends) == 0 {
t.Fatal("parked draft cache was not maintained")
}
})
}
func TestMolmoGroundedCancellationIsolation(t *testing.T) {
m := schedulerMolmo(t, true)
mlxtest.Run(t, func(t *mlxtest.T) {
loadSchedulerMolmoImages(t, m)
r := &Runner{Model: m, Tokenizer: m.Tokenizer(), Sampler: sample.New(8192), parallel: 2}
s := &batchScheduler{r: r, slots: make([]*batchSlot, 2)}
defer closeGroundingScheduler(s)
a, b := schedulerImageRequest(t, m, 5, 1), schedulerImageRequest(t, m, 2, 1)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
a.Ctx = ctx
b.Tokens[len(b.Tokens)-1] = 3
mlx.Scoped(func() { s.admitGeneration(a, 0); s.admitGeneration(b, 1) })
first, second := s.slots[0].request, s.slots[1].request
ga, gb := first.grounding, second.grounding
if ga == gb {
t.Fatal("requests share a grounding owner")
}
mlx.Scoped(func() { s.step() })
if len(a.Responses) != 0 {
t.Fatal("provisional document content escaped")
}
cancel()
for range 10 {
mlx.Scoped(func() { s.step() })
}
if _, ok := <-a.Responses; ok {
t.Fatal("canceled request emitted a response")
}
if !first.finished || first.grounding != nil {
t.Fatal("canceled request retained state")
}
if _, err := ga.Document(nil, false); err == nil {
t.Fatal("canceled grounding remains usable")
}
var content strings.Builder
var final CompletionResponse
for len(b.Responses) > 0 {
res := <-b.Responses
if res.Error != nil {
t.Fatal(res.Error)
}
content.WriteString(res.Content)
if res.Done {
final = res
}
}
var document struct {
Text string `json:"text"`
}
if err := json.Unmarshal([]byte(content.String()), &document); err != nil {
t.Fatal(err)
}
if document.Text != "45" || !final.Done {
t.Fatalf("peer was changed by cancellation: %q %+v", content.String(), final)
}
if _, err := gb.Document(nil, false); err == nil {
t.Fatal("completed peer retained grounding")
}
})
}
func TestMolmoGroundedPrefillErrorAccounting(t *testing.T) {
m := schedulerMolmo(t, true)
mlxtest.Run(t, func(t *mlxtest.T) {
loadSchedulerMolmoImages(t, m)
r := &Runner{Model: m, Tokenizer: m.Tokenizer(), Sampler: sample.New(8192)}
s := &batchScheduler{r: r, slots: make([]*batchSlot, 1)}
defer closeGroundingScheduler(s)
req := schedulerImageRequest(t, m, 2, 1)
mlx.Scoped(func() { s.admitGeneration(req, 0) })
owner := s.slots[0].request
g, p := owner.grounding, owner.prefill
closed, err := m.NewGrounding(req.Tokens, nil)
if err != nil {
t.Fatal(err)
}
closed.Close()
// Inject a concrete closed capture target; encoding and Forward still run.
p.grounding = closed
mlx.Scoped(func() { s.step() })
if p.position != len(req.Tokens)-1 || p.processed != p.position {
t.Fatalf("forwarded prefill lost its position: %d/%d", p.position, p.processed)
}
if !owner.finished || owner.grounding != nil || len(owner.responses) != 1 || owner.responses[0].Error == nil || owner.responses[0].Done {
t.Fatalf("capture error produced success or retained state: %+v", owner.responses)
}
if _, err := g.Document(nil, false); err == nil {
t.Fatal("capture error leaked request owner")
}
})
}
func TestMolmoGroundedResolverErrorAccounting(t *testing.T) {
m := schedulerMolmo(t, true)
mlxtest.Run(t, func(t *mlxtest.T) {
loadSchedulerMolmoImages(t, m)
r := &Runner{Model: m, Tokenizer: m.Tokenizer(), Sampler: sample.New(8192)}
s := &batchScheduler{r: r, slots: make([]*batchSlot, 1)}
defer closeGroundingScheduler(s)
req := schedulerImageRequest(t, m, 4, 1)
mlx.Scoped(func() { s.admitGeneration(req, 0); s.step() })
owner := s.slots[0].request
g := owner.grounding
d := owner.decoder.(*groundingDecoder)
position := d.position
// Force a real model validation error after Forward, not a fake decoder.
d.scope.Discard(d.pending.Arrays()...)
d.pending = sample.Result{Token: mlx.FromValues([]int32{m.Config.PointSubpatchID}, 1)}
d.scope.Attach(d.pending.Arrays()...)
mlx.Scoped(func() { s.step() })
if d.position != position+1 {
t.Fatalf("resolver error lost forwarded position: %d, want %d", d.position, position+1)
}
if got := fmt.Sprint(owner.session.outputs); got != "[2 131]" {
t.Fatalf("resolver error output accounting %s", got)
}
if !owner.finished || len(owner.responses) != 1 || owner.responses[0].Error == nil || owner.responses[0].Done {
t.Fatalf("resolver error responses = %+v", owner.responses)
}
if _, err := g.Document(nil, false); err == nil {
t.Fatal("resolver error leaked grounding")
}
if results, _, _ := d.drain(); len(results) != 0 {
t.Fatal("failed pending token drained twice")
}
})
}
func TestMolmoGroundedDrainDoesNotResolve(t *testing.T) {
m := schedulerMolmo(t, true)
mlxtest.Run(t, func(t *mlxtest.T) {
loadSchedulerMolmoImages(t, m)
r := &Runner{Model: m, Tokenizer: m.Tokenizer(), Sampler: sample.New(8192)}
s := &batchScheduler{r: r, slots: make([]*batchSlot, 1)}
defer closeGroundingScheduler(s)
req := schedulerImageRequest(t, m, 4, 1)
mlx.Scoped(func() { s.admitGeneration(req, 0); s.step() })
owner := s.slots[0].request
d := owner.decoder.(*groundingDecoder)
position := d.position
d.scope.Discard(d.pending.Arrays()...)
d.pending = sample.Result{Token: mlx.FromValues([]int32{m.Config.PointSubpatchID}, 1)}
d.scope.Attach(d.pending.Arrays()...)
mlx.Scoped(func() { s.finish(s.slots[0], nil) })
if d.position != position || owner.output.generated != 1 {
t.Fatal("drain forwarded or counted the overshoot")
}
if len(owner.responses) != 1 || !owner.responses[0].Done || owner.responses[0].Error != nil {
t.Fatalf("drain resolved orphan subpatch: %+v", owner.responses)
}
var doc struct {
Text string `json:"text"`
}
if err := json.Unmarshal([]byte(owner.responses[0].Content), &doc); err != nil || doc.Text != "2" {
t.Fatalf("overshoot entered document: %+v, %v", doc, err)
}
if got := fmt.Sprint(owner.session.outputs); got != "[2 131]" {
t.Fatalf("drained outputs = %s", got)
}
if results, _, _ := d.drain(); len(results) != 0 {
t.Fatal("pending token drained twice")
}
})
}
func TestMolmoGroundedSeedErrorIsNotOutput(t *testing.T) {
m := schedulerMolmo(t, true)
mlxtest.Run(t, func(t *mlxtest.T) {
loadSchedulerMolmoImages(t, m)
r := &Runner{Model: m, Tokenizer: m.Tokenizer(), Sampler: sample.New(8192)}
s := &batchScheduler{r: r, slots: make([]*batchSlot, 1)}
defer closeGroundingScheduler(s)
req := schedulerImageRequest(t, m, 4, 1)
mlx.Scoped(func() { s.admitGeneration(req, 0) })
owner := s.slots[0].request
if owner == nil {
t.Fatal("document request was rejected")
}
// Inject a malformed seed after admission's prompt validation.
req.Tokens[len(req.Tokens)-1] = m.Config.PointSubpatchID
mlx.Scoped(func() { s.step() })
d := owner.decoder.(*groundingDecoder)
if d.position != len(req.Tokens) || len(owner.session.outputs) != 0 || owner.output.generated != 0 {
t.Fatalf("seed entered generated accounting: position=%d outputs=%v generated=%d", d.position, owner.session.outputs, owner.output.generated)
}
if !owner.finished || len(owner.responses) != 1 || owner.responses[0].Error == nil || owner.responses[0].Done {
t.Fatalf("seed failure returned success: %+v", owner.responses)
}
})
}
func TestMolmoGroundedChunkedPrefill(t *testing.T) {
m := schedulerMolmo(t, true)
mlxtest.Run(t, func(t *mlxtest.T) {
loadSchedulerMolmoImages(t, m)
r := &Runner{Model: m, Tokenizer: m.Tokenizer(), Sampler: sample.New(8192)}
s := &batchScheduler{r: r, slots: make([]*batchSlot, 1)}
defer closeGroundingScheduler(s)
var data bytes.Buffer
if err := png.Encode(&data, image.NewRGBA(image.Rect(0, 0, 16, 16))); err != nil {
t.Fatal(err)
}
segments := []model.Segment{{Tokens: []int32{0}}, {Kind: "image", Data: data.Bytes()}, {Tokens: make([]int32, prefillChunkSize()+1)}, {Kind: "image", Data: data.Bytes()}, {Tokens: []int32{1}}}
prepared, err := m.PrepareMedia(segments)
if err != nil {
t.Fatal(err)
}
items, err := bindItems(prepared, segments)
if err != nil {
t.Fatal(err)
}
req := documentRequest(t, prepared.Tokens, 2)
req.MediaItems, req.Layout = items, prepared.Layout
mlx.Scoped(func() { s.admitGeneration(req, 0) })
owner := s.slots[0].request
mlx.Scoped(func() { s.step() })
if owner.prefill == nil || owner.prefill.processed == 0 {
t.Fatal("fixture did not cross multiple prefill chunks")
}
for range 12 {
mlx.Scoped(func() { s.step() })
}
var final CompletionResponse
for len(req.Responses) > 0 {
res := <-req.Responses
if res.Error != nil {
t.Fatal(res.Error)
}
if res.Done {
final = res
}
}
if !final.Done || final.EvalCount != 2 || owner.grounding != nil {
t.Fatalf("chunked document did not finish: %+v", final)
}
for _, item := range items {
if item.item.MediaData != nil {
t.Fatal("prefilled pixels retained")
}
}
})
}
func TestMolmoGroundedFinishHonorsCancellation(t *testing.T) {
m := schedulerMolmo(t, true)
mlxtest.Run(t, func(t *mlxtest.T) {
loadSchedulerMolmoImages(t, m)
r := &Runner{Model: m, Tokenizer: m.Tokenizer(), Sampler: sample.New(8192)}
s := &batchScheduler{r: r, slots: make([]*batchSlot, 1)}
defer closeGroundingScheduler(s)
req := schedulerImageRequest(t, m, 4, 1)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
req.Ctx = ctx
mlx.Scoped(func() { s.admitGeneration(req, 0); s.step() })
owner := s.slots[0].request
cancel()
// A cancellation can arrive after the scheduler's initial context check.
mlx.Scoped(func() { s.finish(s.slots[0], nil) })
if len(owner.responses) != 1 || owner.responses[0].Error == nil || owner.responses[0].Done || owner.responses[0].Content != "" {
t.Fatalf("canceled finish serialized success: %+v", owner.responses)
}
if owner.grounding != nil {
t.Fatal("canceled finish retained grounding")
}
})
}
func TestMolmoGroundedMixedLifecycle(t *testing.T) {
m := schedulerMolmo(t, true)
mlxtest.Run(t, func(t *mlxtest.T) {
loadSchedulerMolmoImages(t, m)
r := &Runner{Model: m, Tokenizer: m.Tokenizer(), Sampler: sample.New(8192), parallel: 2}
s := &batchScheduler{r: r, slots: make([]*batchSlot, 2)}
defer closeGroundingScheduler(s)
document := schedulerImageRequest(t, m, 2, 2)
ordinary := documentRequest(t, []int32{3}, 2)
ordinary.JSONDocument = false
mlx.Scoped(func() { s.admitGeneration(document, 0); s.admitGeneration(ordinary, 1) })
owner := s.slots[0].request
if owner == nil {
t.Fatal("document request was rejected")
}
grounding := owner.grounding
mlx.Scoped(func() { s.step() })
if _, ok := owner.decoder.(*groundingDecoder); !ok {
t.Fatalf("image document decoder = %T, want grounding decoder", owner.decoder)
}
for range 10 {
mlx.Scoped(func() { s.step() })
}
var content strings.Builder
var final CompletionResponse
for len(document.Responses) > 0 {
res := <-document.Responses
if res.Error != nil {
t.Fatal(res.Error)
}
content.WriteString(res.Content)
if res.Done {
final = res
}
}
var decoded struct {
Text string `json:"text"`
}
if err := json.Unmarshal([]byte(content.String()), &decoded); err != nil {
t.Fatal(err)
}
if decoded.Text != "23" || !final.Done || final.EvalCount != 2 {
t.Fatalf("document = %q, final = %+v", content.String(), final)
}
text, ordinaryFinal := collectResponses(ordinary.Responses)
if text != "45" || !ordinaryFinal.Done {
t.Fatalf("ordinary peer stalled or changed: %q %+v", text, ordinaryFinal)
}
if _, err := grounding.Document(nil, false); err == nil {
t.Fatal("finished grounding owner remains open")
}
if offset := s.slots[0].cache.minCacheOffset(); offset > len(document.Tokens) {
t.Fatalf("published generated grounding KV through offset %d beyond prompt %d", offset, len(document.Tokens))
}
if _, matched := findBestMatch(s.slots[0].cache.root, owner.session.storedKeys()); matched > len(document.Tokens) {
t.Fatalf("generated grounding prefix became reusable through %d tokens", matched)
}
if got := fmt.Sprint(owner.session.outputs); got != "[2 3 4]" {
t.Fatalf("output accounting = %s", got)
}
})
}
+167
View File
@@ -0,0 +1,167 @@
package mlxrunner
import (
"encoding/json"
"fmt"
"slices"
"strings"
"testing"
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/llm"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
"github.com/ollama/ollama/mlxrunner/sample"
)
// groundingTestModel exercises the runner contract without a concrete model implementation.
type groundingTestModel struct {
schedulingModel
state *groundingTestState
}
func (m *groundingTestModel) PrepareMedia(segments []model.Segment) (*model.PreparedRequest, error) {
return (stubMediaModel{expansion: []int32{2, 2}}).PrepareMedia(segments)
}
func (*groundingTestModel) EncodeMedia(*model.PreparedItem, *mlx.Array) *mlx.Array {
panic("grounded media must use the request state")
}
func (m *groundingTestModel) NewGrounding(tokens []int32, items []*model.PreparedItem) (model.GroundingState, error) {
m.state = &groundingTestState{model: m, tokens: slices.Clone(tokens), items: items, scope: mlx.NewScope()}
return m.state, nil
}
type groundingTestState struct {
model *groundingTestModel
tokens []int32
items []*model.PreparedItem
scope *mlx.Scope
features *mlx.Array
prefilled []int32
forwarded []int32
resolved []int32
documented []int32
truncated bool
documentCalled bool
featureAtDocument float32
closed int
}
func (g *groundingTestState) EncodeMedia(item *model.PreparedItem, data *mlx.Array) *mlx.Array {
g.features = mlx.Zeros(mlx.DTypeFloat32, item.Range[1]-item.Range[0], 1).Add(data.Reshape(1, 1))
g.scope.Attach(g.features)
return g.features
}
func (g *groundingTestState) CapturePrefill(b *batch.Batch, _ *mlx.Array) error {
if g.features == nil {
return fmt.Errorf("grounding prefill did not encode media")
}
g.prefilled = append(g.prefilled, b.InputIDs.Ints()...)
return nil
}
func (g *groundingTestState) Forward(b *batch.Batch, caches []cache.Layer) (*mlx.Array, *mlx.Array) {
g.forwarded = append(g.forwarded, b.InputIDs.Ints()...)
return g.model.Forward(b, caches)
}
func (g *groundingTestState) Logits(token int32, _ *mlx.Array) (*mlx.Array, error) {
g.resolved = append(g.resolved, token)
return oneHotLogits([]int32{3}), nil
}
func (g *groundingTestState) Document(ids []int32, truncated bool) (string, error) {
g.documentCalled = true
g.documented = slices.Clone(ids)
g.truncated = truncated
if g.features != nil {
g.featureAtDocument = g.features.Floats()[0]
}
data, err := json.Marshal(map[string]string{"text": g.model.Tokenizer().Decode(ids)})
return string(data), err
}
func (g *groundingTestState) Close() {
g.closed++
g.scope.Close()
}
func TestGroundingInterfaceLifecycle(t *testing.T) {
for _, image := range []bool{false, true} {
t.Run(fmt.Sprintf("image=%t", image), func(t *testing.T) {
ctx := t.Context()
mlxtest.Run(t, func(t *mlxtest.T) {
tok := newTestTokenizer(t, []int32{7})
m := &groundingTestModel{schedulingModel: schedulingModel{fakeMTPModel: fakeMTPModel{tok: tok}}}
r := &Runner{Model: m, Tokenizer: tok, Sampler: sample.New(4096), contextLength: 4096}
s := &batchScheduler{r: r, slots: make([]*batchSlot, 1)}
defer closeGroundingScheduler(s)
req := request{
Ctx: ctx, Responses: make(chan CompletionResponse, 16),
CompletionRequest: CompletionRequest{Prompt: "01", JSONDocument: true, Options: api.Options{NumPredict: 2}},
SamplerOpts: sample.Options{Temperature: 0},
}
if image {
req.Prompt = "0[img-0]1"
req.Media = []llm.MediaData{{ID: 0, Kind: llm.MediaKindImage, Data: []byte{1}}}
}
if err := r.Prepare(&req); err != nil {
t.Fatalf("Prepare rejected a grounding-capable model: %v", err)
}
mlx.Scoped(func() { s.admitGeneration(req, 0) })
if s.slots[0].request == nil || m.state == nil {
t.Fatal("grounding-capable model was not admitted")
}
state := m.state
if !slices.Equal(state.tokens, req.Tokens) || len(state.items) != len(req.MediaItems) {
t.Fatal("grounding factory received different prompt data")
}
if image && state.items[0] != req.MediaItems[0].item {
t.Fatal("grounding factory received a different media item")
}
var content strings.Builder
var final CompletionResponse
for range 12 {
mlx.Scoped(func() { s.step() })
for len(req.Responses) > 0 {
response := <-req.Responses
if response.Error != nil {
t.Fatal(response.Error)
}
if response.Content != "" && !state.documentCalled {
t.Fatal("grounding response leaked provisional content")
}
content.WriteString(response.Content)
if response.Done {
final = response
}
}
if final.Done {
break
}
}
want := []int32{1, 1}
if image {
want = []int32{3, 3}
if !slices.Equal(state.prefilled, []int32{0, 2, 2}) ||
!slices.Equal(state.forwarded, []int32{1, 3, 3}) ||
!slices.Equal(state.resolved, state.forwarded) || state.featureAtDocument != 1 {
t.Fatalf("grounding hooks: prefill=%v forward=%v resolve=%v feature=%v", state.prefilled, state.forwarded, state.resolved, state.featureAtDocument)
}
}
if !final.Done || final.EvalCount != 2 || !state.truncated || state.closed != 1 || !slices.Equal(state.documented, want) {
t.Fatalf("grounding completion: final=%+v ids=%v truncated=%t closed=%d", final, state.documented, state.truncated, state.closed)
}
if want := fmt.Sprintf(`{"text":%q}`, tok.Decode(want)); content.String() != want {
t.Fatalf("content = %q, want %q", content.String(), want)
}
})
})
}
}
+284
View File
@@ -0,0 +1,284 @@
package mlxrunner
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"strings"
"testing"
"time"
"unicode/utf8"
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/manifest"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
"github.com/ollama/ollama/mlxrunner/model"
"github.com/ollama/ollama/mlxrunner/model/molmo3"
"github.com/ollama/ollama/mlxrunner/nn"
"github.com/ollama/ollama/mlxrunner/sample"
)
func TestDocumentResponsesBoundedFrames(t *testing.T) {
data, err := json.Marshal(map[string]any{
"text": strings.Repeat("\"\\<>&\x00世界🙂", 12000),
"multi_modal": []any{}, "type": "text",
})
if err != nil {
t.Fatal(err)
}
cached := 0
final := CompletionResponse{
Done: true, DoneReason: 1, PromptEvalCount: 23,
PromptEvalCachedCount: &cached, PromptEvalDuration: time.Second,
EvalCount: 19, EvalDuration: 2 * time.Second,
}
responses, err := documentResponses(string(data), final)
if err != nil {
t.Fatal(err)
}
if len(responses) < 2 {
t.Fatalf("large document returned %d frames", len(responses))
}
var wire bytes.Buffer
for i, response := range responses {
if !utf8.ValidString(response.Content) || len(response.Content) > 8<<10 {
t.Fatalf("frame %d is not bounded UTF-8: %d bytes", i, len(response.Content))
}
if response.Done != (i == len(responses)-1) {
t.Fatalf("frame %d Done = %v", i, response.Done)
}
encoded, err := json.Marshal(response)
if err != nil {
t.Fatal(err)
}
if len(encoded)+1 >= bufio.MaxScanTokenSize {
t.Fatalf("encoded frame %d exceeds the runner reader: %d bytes", i, len(encoded)+1)
}
wire.Write(encoded)
wire.WriteByte('\n')
}
var joined strings.Builder
scanner := bufio.NewScanner(&wire)
for scanner.Scan() {
var response CompletionResponse
if err := json.Unmarshal(scanner.Bytes(), &response); err != nil {
t.Fatal(err)
}
joined.WriteString(response.Content)
}
if err := scanner.Err(); err != nil {
t.Fatal(err)
}
if joined.String() != string(data) {
t.Fatal("content changed across bounded runner frames")
}
last := responses[len(responses)-1]
last.Content = ""
got, _ := json.Marshal(last)
want, _ := json.Marshal(final)
if !bytes.Equal(got, want) {
t.Fatalf("final metrics = %s, want %s", got, want)
}
}
// schedulerMolmo constructs real Molmo layers with zero residuals and an
// identity embedding, so the LM head selects a known successor for each digit.
func schedulerMolmo(t *testing.T, images bool) *molmo3.Model {
t.Helper()
t.Setenv("OLLAMA_MODELS", t.TempDir())
root := &model.Root{Manifest: &manifest.Manifest{}}
for name, data := range map[string]string{
"config.json": `{"architectures":["Molmo3ForConditionalGeneration"],"text_config":{"hidden_size":8,"num_hidden_layers":1,"intermediate_size":8,"num_attention_heads":1,"num_key_value_heads":1,"head_dim":8,"vocab_size":136,"rms_norm_eps":0.000001,"max_position_embeddings":8192,"hidden_act":"silu","qk_norm_type":"qwen3","rope_parameters":{"rope_theta":10000,"rope_type":"default"}}}`,
"tokenizer.json": `{"model":{"type":"BPE","vocab":{"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7},"merges":[]}}`,
"generation_config.json": `{"eos_token_id":7}`,
} {
if images && name == "config.json" {
data = strings.TrimSuffix(data, "}") + `,"image_patch_id":120,"image_low_res_id":121,"image_col_id":122,"image_start_token_id":123,"low_res_image_start_token_id":124,"image_end_token_id":125,"point_patch_id":130,"point_subpatch_id":131,"point_loc_id":132,"seg_mask_id":133,"center_patch_id":134,"corresponding_patch_id":135,"point_query_dims":[4,2,1],"subpatch_location_size":4,"subpatch_hidden_size":4,"subpatch_conv_kernel":3,"patch_position_embedding_size":512,"mask_diffusion_steps":2,"pointer_rope_theta":50000,"vision_config":{"hidden_size":8,"intermediate_size":8,"num_hidden_layers":2,"num_attention_heads":1,"num_key_value_heads":1,"head_dim":8,"num_position_embeddings":729,"patch_size":14,"image_size":[378,378],"num_channels":3,"layer_norm_eps":0.000001,"hidden_act":"gelu_pytorch_tanh","attention_bias":true},"adapter_config":{"vision_feature_layer":[1,0],"num_attention_heads":1,"num_key_value_heads":1,"head_dim":8,"hidden_size":8,"intermediate_size":8,"text_hidden_size":8,"num_pooling_positions":9,"hidden_act":"silu","attention_bias":true}}`
}
layer, err := manifest.NewLayer(strings.NewReader(data), manifest.MediaTypeImageJSON)
if err != nil {
t.Fatal(err)
}
layer.Name = name
root.Manifest.Layers = append(root.Manifest.Layers, layer)
}
loaded, err := model.New(root)
if err != nil {
t.Fatal(err)
}
return loaded.(*molmo3.Model)
}
func loadSchedulerMolmo(m *molmo3.Model) {
zero := func(o, i int) *nn.Linear { return nn.NewLinear(mlx.Zeros(mlx.DTypeFloat32, o, i), nil) }
norm := func() *nn.RMSNorm { return nn.NewRMSNorm(mlx.FromValues([]float32{1, 1, 1, 1, 1, 1, 1, 1}, 8), 1e-6) }
embeddings, head := make([]float32, 136*8), make([]float32, 136*8)
for i := range 8 {
embeddings[i*8+i] = 1
head[((i+1)%8)*8+i] = 1
}
m.EmbedTokens = nn.NewEmbedding(mlx.FromValues(embeddings, 136, 8))
m.LMHead = nn.NewLinear(mlx.FromValues(head, 136, 8), nil)
m.Norm = norm()
m.Layers = []*molmo3.Layer{{
AttentionNorm: norm(), MLPNorm: norm(),
Attention: &molmo3.Attention{AttProj: zero(24, 8), OProj: zero(8, 8), QNorm: norm(), KNorm: norm()},
MLP: &molmo3.MLP{FFProj: zero(16, 8), FFOut: zero(8, 8)},
}}
}
func documentRequest(t *mlxtest.T, tokens []int32, limit int) request {
t.Helper()
req := request{
Ctx: context.Background(), Tokens: tokens, Responses: make(chan CompletionResponse, 16),
CompletionRequest: CompletionRequest{JSONDocument: true, Options: api.Options{NumPredict: limit}}, SamplerOpts: sample.Options{Temperature: 0},
}
return req
}
func TestMolmoDocumentSchedulerText(t *testing.T) {
m := schedulerMolmo(t, false)
mlxtest.Run(t, func(t *mlxtest.T) {
loadSchedulerMolmo(m)
r := &Runner{Model: m, Tokenizer: m.Tokenizer(), Sampler: sample.New(8192)}
defer r.Sampler.Free()
s := &batchScheduler{r: r, slots: make([]*batchSlot, 1)}
req := documentRequest(t, []int32{0, 1}, 2)
mlx.Scoped(func() { s.admitGeneration(req, 0) })
defer s.slots[0].cache.close()
owned := s.slots[0].request
var content strings.Builder
var final CompletionResponse
for range 12 {
mlx.Scoped(func() { s.step() })
for len(req.Responses) > 0 {
res := <-req.Responses
if res.Error != nil {
t.Fatal(res.Error)
}
if !owned.finished && res.Content != "" {
t.Fatal("document leaked provisional content")
}
content.WriteString(res.Content)
if res.Done {
final = res
}
}
if final.Done {
break
}
}
var document struct {
Text string `json:"text"`
Type string `json:"type"`
MultiModal []any `json:"multi_modal"`
}
if err := json.Unmarshal([]byte(content.String()), &document); err != nil {
t.Fatalf("document content %q: %v", content.String(), err)
}
if document.Text != "23" || document.Type != "text" || document.MultiModal == nil {
t.Fatalf("document = %+v", document)
}
if !final.Done || final.EvalCount != 2 || final.PromptEvalCount != 2 {
t.Fatalf("final = %+v", final)
}
if got := fmt.Sprint(owned.session.outputs); got != "[2 3 4]" {
t.Fatalf("recorded output %s, want emitted tokens plus drained overshoot", got)
}
})
}
func TestMolmoDocumentEOSAccounting(t *testing.T) {
m := schedulerMolmo(t, false)
mlxtest.Run(t, func(t *mlxtest.T) {
loadSchedulerMolmo(m)
r := &Runner{Model: m, Tokenizer: m.Tokenizer(), Sampler: sample.New(8192)}
s := &batchScheduler{r: r, slots: make([]*batchSlot, 1)}
defer closeGroundingScheduler(s)
req := documentRequest(t, []int32{5}, 10)
mlx.Scoped(func() { s.admitGeneration(req, 0) })
owner := s.slots[0].request
for range 8 {
mlx.Scoped(func() { s.step() })
}
var content strings.Builder
var final CompletionResponse
for len(req.Responses) > 0 {
res := <-req.Responses
if res.Error != nil {
t.Fatal(res.Error)
}
content.WriteString(res.Content)
if res.Done {
final = res
}
}
var doc struct {
Text string `json:"text"`
}
if err := json.Unmarshal([]byte(content.String()), &doc); err != nil {
t.Fatal(err)
}
if doc.Text != "6" || !final.Done || final.DoneReason != 0 || final.EvalCount != 1 {
t.Fatalf("EOS accounting: %q %+v", content.String(), final)
}
if got := fmt.Sprint(owner.session.outputs); got != "[6 7 0]" {
t.Fatalf("session outputs = %s, want token, EOS and one drained overshoot", got)
}
})
}
func TestMolmoDocumentPrepareGuards(t *testing.T) {
m := schedulerMolmo(t, false)
for _, tc := range []struct {
name string
model model.Model
logprobs bool
}{
{"wrong model", textOnlyModel{}, false}, {"logprobs", m, true},
} {
t.Run(tc.name, func(t *testing.T) {
r := &Runner{Model: tc.model, Tokenizer: m.Tokenizer(), contextLength: 8192}
req := &request{CompletionRequest: CompletionRequest{Prompt: "1", JSONDocument: true, Logprobs: tc.logprobs}}
if err := r.Prepare(req); err == nil {
t.Fatal("unsupported document request was admitted")
}
})
}
}
func TestMolmoDocumentPrepareIgnoresInactiveTopLogprobs(t *testing.T) {
m := schedulerMolmo(t, false)
r := &Runner{Model: m, Tokenizer: m.Tokenizer(), contextLength: 8192}
req := &request{CompletionRequest: CompletionRequest{Prompt: "1", JSONDocument: true, TopLogprobs: 20, Format: json.RawMessage(`null`)}}
if err := r.Prepare(req); err != nil {
t.Fatalf("inactive top_logprobs rejected: %v", err)
}
if req.Grammar != nil {
t.Fatal("null private format compiled a grammar")
}
}
func TestDocumentSpeculationMaintainsWithoutDrafting(t *testing.T) {
s := &speculation{drafter: grammarTestDrafter{}, depth: newDepthController()}
req := request{CompletionRequest: CompletionRequest{JSONDocument: true}}
session := s.open(req, nil)
defer session.close()
if session == nil || session.enabled || session.limit != 0 {
t.Fatalf("document session must maintain draft caches without proposing: %+v", session)
}
ordinary := s.open(request{}, nil)
defer ordinary.close()
if !ordinary.enabled {
t.Fatal("document guard disabled ordinary drafting")
}
}
func TestDocumentResponsesRejectInvalidUTF8(t *testing.T) {
if _, err := documentResponses(string([]byte{0xff}), CompletionResponse{Done: true}); err == nil {
t.Fatal("invalid UTF-8 document was accepted")
}
}
+13 -5
View File
@@ -52,9 +52,10 @@ type requestMedia struct {
// manifest is the request-scoped batch view of items; Features is
// toggled in place so every batch shares the same slice.
manifest []batch.MediaItem
features []*mlx.Array // parallel to items; nil until encoded
scope *mlx.Scope
manifest []batch.MediaItem
features []*mlx.Array // parallel to items; nil until encoded
scope *mlx.Scope
grounding model.GroundingState // owns document-mode features; this view borrows them
// layout is the request's one-row Batch.Layout, shared by every batch
// like the manifest; nil when the model returned no layout.
@@ -134,9 +135,14 @@ func (m *requestMedia) batchMedia(pos, n int) []batch.MediaItem {
if m.features[i] == nil {
m.features[i] = mlx.ScopedArrays(func() []*mlx.Array {
data := mlx.FromValues(item.item.MediaData, item.item.Dims...)
if m.grounding != nil {
return []*mlx.Array{m.grounding.EncodeMedia(item.item, data)}
}
return []*mlx.Array{m.model.EncodeMedia(item.item, data)}
})[0]
m.scope.Attach(m.features[i])
if m.grounding == nil {
m.scope.Attach(m.features[i])
}
// The upload copied the pixels; free them here — release never
// passes the end of an expansion reaching the prompt's last token.
item.item.MediaData = nil
@@ -156,7 +162,9 @@ func (m *requestMedia) free(pos int) {
if item.pos+item.length <= pos {
item.item.MediaData = nil
if m.features[i] != nil {
m.scope.Discard(m.features[i])
if m.grounding == nil {
m.scope.Discard(m.features[i])
}
m.features[i] = nil
m.manifest[i].Features = nil
}
+36
View File
@@ -0,0 +1,36 @@
package model
import (
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
)
// GroundingModel creates request-owned state for grounding document output.
// NewGrounding runs on the MLX worker and returns nil on failure.
type GroundingModel interface {
NewGrounding(tokens []int32, items []*PreparedItem) (GroundingState, error)
}
// GroundingState owns one request's selections and retained media features.
// All methods run on the MLX worker. Image requests use fresh prefill and
// single-row decoding; their selection-dependent generated KV is not reused.
type GroundingState interface {
// EncodeMedia returns features borrowed by the runner and owned by this state.
EncodeMedia(item *PreparedItem, data *mlx.Array) *mlx.Array
// CapturePrefill retains the prompt features needed for later selections.
CapturePrefill(b *batch.Batch, hidden *mlx.Array) error
// Forward applies selection feedback before the model's forward pass.
Forward(b *batch.Batch, caches []cache.Layer) (hidden, auxHidden *mlx.Array)
// Logits resolves the forwarded token and returns logits for its successor.
Logits(token int32, hidden *mlx.Array) (*mlx.Array, error)
// Document serializes the emitted tokens and selections after generation.
Document(ids []int32, truncated bool) (string, error)
// Close releases retained state after completion, cancellation, or failure.
Close()
}
+604
View File
@@ -0,0 +1,604 @@
package molmo3
import (
"encoding/json"
"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"
modelmolmo3 "github.com/ollama/ollama/model/molmo3"
)
type groundingConfig struct {
PointQueryDims []int `json:"point_query_dims"`
SubpatchLocationSize int `json:"subpatch_location_size"`
SubpatchHiddenSize int `json:"subpatch_hidden_size"`
SubpatchConvKernel int `json:"subpatch_conv_kernel"`
PatchPositionEmbeddingSize int `json:"patch_position_embedding_size"`
MaskDiffusionSteps int `json:"mask_diffusion_steps"`
PointerRopeTheta float32 `json:"pointer_rope_theta"`
}
func (c groundingConfig) validate(model *Config) error {
if len(c.PointQueryDims) != 3 || c.PointQueryDims[0] <= 0 || c.PointQueryDims[0]%2 != 0 || c.PointQueryDims[1] <= 0 || c.PointQueryDims[2] <= 0 {
return fmt.Errorf("molmo3: invalid point_query_dims %v", c.PointQueryDims)
}
if c.SubpatchLocationSize != 4 || c.SubpatchHiddenSize <= 0 || c.SubpatchConvKernel != 3 || c.PointerRopeTheta <= 0 || c.MaskDiffusionSteps < 0 || c.PatchPositionEmbeddingSize != 512 {
return fmt.Errorf("molmo3: unsupported grounding configuration")
}
seen := map[int32]bool{}
for _, id := range []int32{model.PointPatchID, model.PointSubpatchID, model.PointLocID, model.SegMaskID, model.CenterPatchID, model.CorrespondingPatchID} {
if id <= 0 || id >= model.TextConfig.VocabSize || seen[id] {
return fmt.Errorf("molmo3: invalid grounding token ID %d", id)
}
seen[id] = true
}
return nil
}
// GroundingHead contains immutable model weights, never request state.
type GroundingHead struct {
Config groundingConfig
XNorm *nn.RMSNorm
PatchK, PatchQ, SubpatchQ, LocQ, MaskQ *nn.Linear
SubpatchHidden, MergeIn1, MergeIn2, MergeOut *nn.Linear
SubpatchEmbedding *nn.Linear
LocationEmbedding *nn.Embedding
}
func (h *GroundingHead) load(tensors map[string]*mlx.Array, eps float32) error {
weight, err := requireTensor(tensors, "model.x_norm.weight")
if err != nil {
return err
}
h.XNorm = nn.NewRMSNorm(weight, eps)
for _, projection := range []struct {
target **nn.Linear
name string
bias bool
}{
{&h.PatchK, "patch_k", true},
{&h.PatchQ, "patch_q", true},
{&h.SubpatchQ, "subpatch_q", true},
{&h.LocQ, "loc_q", true},
{&h.MaskQ, "mask_q", true},
{&h.SubpatchHidden, "subpatch_hidden", true},
{&h.MergeIn1, "subpatch_loc_k.w_in1", false},
{&h.MergeIn2, "subpatch_loc_k.w_in2", false},
{&h.MergeOut, "subpatch_loc_k.w_out", true},
{&h.SubpatchEmbedding, "build_subpatch_embeddings", true},
} {
*projection.target, err = visionLinear(tensors, "model."+projection.name, projection.bias)
if err != nil {
return err
}
}
weight, err = requireTensor(tensors, "model.build_location_embeddings.weight")
if err != nil {
return err
}
h.LocationEmbedding = nn.NewEmbedding(weight)
return nil
}
type groundingTensors struct {
patchK, valid, subpatchK, vit, image, locK, diffusion *mlx.Array
}
func (w *groundingTensors) arrays() []*mlx.Array {
return []*mlx.Array{w.patchK, w.valid, w.subpatchK, w.vit, w.image, w.locK, w.diffusion}
}
type groundingImage struct {
encoded bool
item *model.PreparedItem
media imageForwardState
// Positions in the prompt and in the high-resolution pointer sequence.
tokenPositions, positions []int32
high []float32
features, vit, conv, diffusion *mlx.Array
working *groundingTensors
}
// Grounding owns the working tensors and selections of one document request.
// All methods run on the MLX worker. Tokens/items are borrowed, not copied.
type Grounding struct {
model *Model
tokens []int32
images []groundingImage
scope *mlx.Scope
working *groundingTensors
positions []int32
pooling []int32
prefilled int
patch, subpatch, loc, rotateBy int
patchResolved, listStarted bool
previous int32
hasPrevious bool
noPoint *float64
points []modelmolmo3.GroundingPoint
masks []*mlx.Array
maskAnchors []int
err error
}
var (
_ model.GroundingModel = (*Model)(nil)
_ model.GroundingState = (*Grounding)(nil)
)
func (m *Model) NewGrounding(tokens []int32, items []*model.PreparedItem) (model.GroundingState, error) {
g, err := m.newGrounding(tokens, items)
if err != nil {
return nil, err
}
return g, nil
}
func (m *Model) newGrounding(tokens []int32, items []*model.PreparedItem) (*Grounding, error) {
if m == nil || m.Config == nil || len(tokens) == 0 {
return nil, fmt.Errorf("molmo3: grounding requires a model and prompt")
}
g := &Grounding{model: m, tokens: tokens}
if len(items) > 0 {
h := m.GroundingHead
if m.Vision == nil || h == nil || h.XNorm == nil {
return nil, fmt.Errorf("molmo3: missing grounding weights")
}
}
end, highOffset := 0, int32(0)
var rasterOffset int64
for _, item := range items {
if item == nil || item.Range[0] < end || item.Range[1] <= item.Range[0] || item.Range[1] > len(tokens) {
return nil, fmt.Errorf("molmo3: invalid grounding image range")
}
media, ok := mediaImageState(item.Opaque)
if !ok || len(item.Dims) != 3 || item.Dims[0] <= 0 || item.Dims[1] <= 0 || item.Dims[2] <= 0 || media.tokenPoolingShape[0] <= 0 || media.tokenPoolingShape[1] != 4 || len(media.tokenPooling)/4 != media.tokenPoolingShape[0] || len(media.tokenPooling)%4 != 0 {
return nil, fmt.Errorf("molmo3: invalid grounding image geometry")
}
if item.Dims[1] != int(m.Config.VisionConfig.NumPositionEmbeddings) || item.Dims[2] != m.Vision.PatchEmbedding.Weight.Dim(1) || item.Dims[0] > math.MaxInt32/item.Dims[1] || media.patchPosShape != [3]int{item.Dims[0], item.Dims[1], 3} {
return nil, fmt.Errorf("molmo3: image dimensions do not match grounding encoder")
}
raster := int64(item.Dims[0]) * int64(item.Dims[1])
if raster > math.MaxInt32 || len(media.patchPosIDs) != int(raster)*3 {
return nil, fmt.Errorf("molmo3: invalid grounding raster geometry")
}
if raster+rasterOffset > math.MaxInt32 {
return nil, fmt.Errorf("molmo3: combined image raster is too large")
}
for _, ix := range media.tokenPooling {
if ix < -1 || int64(ix) >= raster {
return nil, fmt.Errorf("molmo3: invalid grounding pooling index %d", ix)
}
if ix >= 0 {
g.pooling = append(g.pooling, ix+int32(rasterOffset))
} else {
g.pooling = append(g.pooling, -1)
}
}
for row := range media.tokenPoolingShape[0] {
valid := false
for _, ix := range media.tokenPooling[row*4 : (row+1)*4] {
valid = valid || ix >= 0
}
if !valid {
return nil, fmt.Errorf("molmo3: empty grounding pooling row %d", row)
}
}
rasterOffset += raster
im := groundingImage{item: item, media: media}
var high int32
for pos := item.Range[0]; pos < item.Range[1]; pos++ {
token := tokens[pos]
if token != m.Config.ImagePatchID && token != m.Config.ImageLowResID {
continue
}
im.tokenPositions = append(im.tokenPositions, int32(pos))
im.positions = append(im.positions, highOffset+max(high-1, 0))
if token == m.Config.ImagePatchID {
im.positions[len(im.positions)-1] = highOffset + high
high++
im.high = append(im.high, 1)
} else {
im.high = append(im.high, 0)
}
}
if len(im.tokenPositions) != media.tokenPoolingShape[0] || high == 0 {
return nil, fmt.Errorf("molmo3: image tokens do not match grounding pooling")
}
highOffset += high
g.positions = append(g.positions, im.positions...)
g.images = append(g.images, im)
end = item.Range[1]
}
g.scope = mlx.NewScope()
return g, nil
}
// EncodeMedia runs the existing image encoder once. The caller borrows the
// returned connector features; only this request may attach/discard them.
func (g *Grounding) EncodeMedia(item *model.PreparedItem, data *mlx.Array) *mlx.Array {
for i := range g.images {
im := &g.images[i]
if im.item != item {
continue
}
if im.encoded {
panic("molmo3: image encoded twice")
}
im.encoded = true
m := im.media
pool := mlx.FromValues(m.tokenPooling, 1, m.tokenPoolingShape[0], m.tokenPoolingShape[1])
pos := mlx.FromValues(m.patchPosIDs, 1, m.patchPosShape[0], m.patchPosShape[1], m.patchPosShape[2])
im.features, im.vit, im.conv, im.diffusion = g.model.Vision.encodeGrounding(data.ExpandDims(0), pool, pos)
g.scope.Attach(im.features, im.vit, im.conv, im.diffusion)
return im.features
}
panic("molmo3: unknown grounding image")
}
// CapturePrefill consumes raw hidden while it is live. Only image rows are
// projected; neither full prompt hidden nor pixels survive in the request.
// Completed ranges are idempotent so callers may also use Grounding.Forward.
func (g *Grounding) CapturePrefill(b *batch.Batch, hidden *mlx.Array) error {
if g.scope == nil {
return fmt.Errorf("molmo3: closed grounding request")
}
if g.err != nil {
return g.err
}
if len(b.SeqOffsets) != 1 || len(b.SeqQueryLens) != 1 || hidden.NumDims() != 3 || hidden.Dim(0) != 1 || int(b.SeqQueryLens[0]) > hidden.Dim(1) {
return fmt.Errorf("molmo3: grounding expects one request row, hidden %v", hidden.Dims())
}
offset, n := int(b.SeqOffsets[0]), int(b.SeqQueryLens[0])
if offset >= len(g.tokens) {
return nil
}
end := min(offset+n, len(g.tokens))
if end <= g.prefilled {
return nil
}
if offset != g.prefilled || n <= 0 {
return fmt.Errorf("molmo3: incomplete grounding prefill at %d, want %d", offset, g.prefilled)
}
for i := range g.images {
im := &g.images[i]
if im.item.Range[1] <= offset || im.item.Range[0] >= end {
continue
}
if im.item.Range[0] < offset || im.item.Range[1] > end {
return fmt.Errorf("molmo3: grounding image split across prefill chunks")
}
if im.vit == nil {
return fmt.Errorf("molmo3: image was not encoded before prefill")
}
mlx.Scoped(func() {
indices := make([]int32, len(im.tokenPositions))
for j, pos := range im.tokenPositions {
indices[j] = pos - int32(offset)
}
x := hidden.Reshape(hidden.Dim(1), hidden.Dim(2)).TakeAxis(mlx.FromValues(indices, len(indices)), 0)
im.working = g.buildImage(im, x)
g.scope.Attach(im.working.patchK, im.working.valid, im.working.subpatchK, im.working.vit, im.working.locK)
g.scope.Discard(im.vit, im.conv)
im.vit, im.conv = nil, nil
})
mlx.Eval(im.working.arrays()...)
}
g.prefilled = end
if g.working == nil && len(g.images) > 0 {
ready := true
for i := range g.images {
ready = ready && g.images[i].working != nil
}
if ready {
g.combineImages()
}
}
return nil
}
func (g *Grounding) buildImage(im *groundingImage, raw *mlx.Array) *groundingTensors {
h := g.model.GroundingHead
c := h.Config
p, s := im.media.tokenPoolingShape[0], im.media.tokenPoolingShape[1]
x := h.XNorm.Forward(raw, g.model.Config.TextConfig.RMSNormEps)
keys := groundingRoPE(h.PatchK.Forward(x), im.positions, c.PointerRopeTheta)
valid := make([]float32, p*s)
for i, v := range im.media.tokenPooling {
if v >= 0 {
valid[i] = im.high[i/s]
}
}
vit := h.SubpatchHidden.Forward(im.vit.Reshape(p*s, im.vit.Dim(-1))).Reshape(p, s, c.SubpatchHiddenSize)
merged := h.MergeIn1.Forward(vit.Add(im.conv).Reshape(p*s, c.SubpatchHiddenSize))
context := mlx.BroadcastTo(x.ExpandDims(1), int32(p), int32(s), int32(x.Dim(1))).Reshape(p*s, x.Dim(1))
merged = merged.Add(h.MergeIn2.Forward(context))
half := merged.Dim(1) / 2
value := merged.Slice(mlx.Slice(), mlx.Slice(0, half))
gate := merged.Slice(mlx.Slice(), mlx.Slice(half, merged.Dim(1)))
merged = h.MergeOut.Forward(value.Multiply(mlx.SiLU(gate)))
sub := merged.Slice(mlx.Slice(), mlx.Slice(0, c.PointQueryDims[1])).Reshape(p, s, c.PointQueryDims[1])
loc := merged.Slice(mlx.Slice(), mlx.Slice(c.PointQueryDims[1], merged.Dim(1))).Reshape(p, s, c.SubpatchLocationSize*c.SubpatchLocationSize, c.PointQueryDims[2])
return &groundingTensors{patchK: keys, valid: mlx.FromValues(valid, p, s), subpatchK: sub, vit: vit, image: im.features, locK: loc, diffusion: im.diffusion}
}
func (g *Grounding) combineImages() {
if len(g.images) == 1 {
g.working = g.images[0].working
return
}
var arrays []*mlx.Array
mlx.Scoped(func() {
for column := range g.images[0].working.arrays() {
parts := make([]*mlx.Array, len(g.images))
for i := range g.images {
parts[i] = g.images[i].working.arrays()[column]
}
joined := mlx.Concatenate(parts, 0)
g.scope.Attach(joined)
g.scope.Discard(parts...)
arrays = append(arrays, joined)
}
})
g.working = &groundingTensors{patchK: arrays[0], valid: arrays[1], subpatchK: arrays[2], vit: arrays[3], image: arrays[4], locK: arrays[5], diffusion: arrays[6]}
for i := range g.images {
g.images[i].working = nil
g.images[i].features = nil
}
mlx.Eval(arrays...)
}
// Forward adds the previous selection to the token following it, before the
// shared decoder layers. It also captures the final prompt-token handoff.
func (g *Grounding) Forward(b *batch.Batch, caches []cache.Layer) (*mlx.Array, *mlx.Array) {
hidden := g.model.embedInput(b)
if len(b.SeqOffsets) != 1 || len(b.SeqQueryLens) != 1 {
g.err = fmt.Errorf("molmo3: grounding forward requires one request row")
} else if int(b.SeqOffsets[0]) >= len(g.tokens) && g.working != nil && g.hasPrevious {
var feedback *mlx.Array
h := g.model.GroundingHead
c := g.model.Config
switch g.previous {
case c.PointPatchID:
if g.patchResolved {
feedback = g.working.image.TakeAxis(mlx.FromValue(g.patch).AsType(mlx.DTypeInt32), 0)
}
case c.PointSubpatchID:
features := g.working.vit.Slice(mlx.Slice(g.patch, g.patch+1), mlx.Slice(g.subpatch, g.subpatch+1), mlx.Slice())
feedback = h.SubpatchEmbedding.Forward(features)
case c.PointLocID:
feedback = h.LocationEmbedding.Forward(mlx.FromValues([]int32{int32(g.loc)}, 1, 1))
}
if feedback != nil {
hidden = hidden.Add(feedback.AsType(hidden.DType()).Reshape(1, 1, hidden.Dim(2)))
}
}
hidden, aux := g.model.forward(b, caches, hidden)
if g.err == nil {
g.err = g.CapturePrefill(b, hidden)
}
return hidden, aux
}
// Logits resolves the token just forwarded, not its sampled successor. The
// ordinary Unembed suppression is deliberately untouched.
func (g *Grounding) Logits(token int32, hidden *mlx.Array) (*mlx.Array, error) {
if g.scope == nil {
return nil, fmt.Errorf("molmo3: closed grounding request")
}
if g.err != nil {
return nil, g.err
}
if hidden.NumDims() != 3 || hidden.Dim(0) != 1 || hidden.Dim(1) != 1 {
return nil, fmt.Errorf("molmo3: grounding logits expect one hidden row, got %v", hidden.Dims())
}
if len(g.images) == 0 {
return g.model.Unembed(hidden), nil
}
if g.prefilled != len(g.tokens) || g.working == nil {
return nil, fmt.Errorf("molmo3: grounding prefill is incomplete")
}
m := g.model
c := m.Config
head := m.GroundingHead
logits := m.LMHead.Forward(m.Norm.Forward(hidden, c.TextConfig.RMSNormEps))
h := head.XNorm.Forward(hidden, c.TextConfig.RMSNormEps)
switch token {
case c.CenterPatchID, c.CorrespondingPatchID:
return nil, fmt.Errorf("molmo3: unsupported grounding token %d", token)
case c.PointPatchID:
q := groundingRoPE(head.PatchQ.Forward(h).Reshape(1, -1), g.positions[g.rotateBy:g.rotateBy+1], head.Config.PointerRopeTheta).Reshape(-1)
scores := g.working.patchK.AsType(mlx.DTypeFloat32).Matmul(q.AsType(mlx.DTypeFloat32)).Divide(mlx.FromValue(float32(math.Sqrt(float64(q.Dim(0))))))
valid := g.working.valid.SumAxis(-1, false).Greater(mlx.FromValue(float32(0)))
scores = mlx.Where(valid, scores, mlx.FromValue(float32(-1000000)))
scores = mlx.Concatenate([]*mlx.Array{scores, mlx.Zeros(mlx.DTypeFloat32, 1)}, 0)
eop := scores.Dim(0) - 1
prob := float64(mlx.SoftmaxAxis(scores, -1, true).Floats()[eop])
if g.noPoint == nil {
g.noPoint = &prob
}
if !g.listStarted && prob < 0.5 {
scores = groundingSetLogit(scores, int32(eop), -1000000)
}
g.patch = groundingArgmax(scores)
g.patchResolved = g.patch != eop
g.listStarted = g.patchResolved
if !g.patchResolved {
g.patch, g.rotateBy = 0, 0
} else {
g.rotateBy = g.patch
}
keep := make([]bool, int(c.TextConfig.VocabSize))
for i := range keep {
keep[i] = !g.patchResolved
}
for _, id := range []int32{c.PointPatchID, c.PointSubpatchID, c.PointLocID, c.SegMaskID, c.CenterPatchID, c.CorrespondingPatchID} {
keep[id] = g.patchResolved
}
logits = mlx.Where(mlx.FromValues(keep, len(keep)), logits, mlx.FromValue(float32(-1000000)))
case c.PointSubpatchID:
if !g.patchResolved || !g.hasPrevious || g.previous != c.PointPatchID {
return nil, fmt.Errorf("molmo3: orphan subpatch token")
}
keys := g.working.subpatchK.TakeAxis(mlx.FromValue(g.patch).AsType(mlx.DTypeInt32), 0)
q := head.SubpatchQ.Forward(h).Reshape(-1)
g.subpatch = groundingArgmax(keys.AsType(mlx.DTypeFloat32).Matmul(q.AsType(mlx.DTypeFloat32)).Divide(mlx.FromValue(float32(math.Sqrt(float64(q.Dim(0)))))))
logits = groundingSetLogit(logits, c.PointLocID, 100000)
case c.SegMaskID:
if !g.patchResolved || !g.hasPrevious || g.previous != c.PointPatchID {
return nil, fmt.Errorf("molmo3: orphan mask token")
}
scores := g.maskScores(h)
// Retain the resolved scores, not the decoder graph that produced them.
mlx.Eval(scores)
g.scope.Attach(scores)
g.masks = append(g.masks, scores)
g.maskAnchors = append(g.maskAnchors, g.patch)
case c.PointLocID:
if !g.patchResolved || !g.hasPrevious || g.previous != c.PointSubpatchID {
return nil, fmt.Errorf("molmo3: orphan location token")
}
g.loc = groundingArgmax(head.LocQ.Forward(h).Reshape(-1))
g.points = append(g.points, modelmolmo3.GroundingPoint{Patch: g.patch, Subpatch: g.subpatch, Location: g.loc})
default:
for _, id := range []int32{c.PointSubpatchID, c.PointLocID, c.SegMaskID} {
logits = groundingSetLogit(logits, id, -1000000)
}
}
for _, id := range []int32{c.CenterPatchID, c.CorrespondingPatchID} {
logits = groundingSetLogit(logits, id, float32(math.Inf(-1)))
}
g.previous, g.hasPrevious = token, true
return logits, nil
}
func (g *Grounding) maskScores(h *mlx.Array) *mlx.Array {
head := g.model.GroundingHead
q, s, l := head.Config.PointQueryDims[0], head.Config.PointQueryDims[1], head.Config.PointQueryDims[2]
// The reference casts BEFORE splitting and applying pointer RoPE. Casting
// afterward rounds the rotated token query back to BF16 and changes scores.
query := head.MaskQ.Forward(h).AsType(mlx.DTypeFloat32).Reshape(1, q+s+l)
token := groundingRoPE(query.Slice(mlx.Slice(), mlx.Slice(0, q)), g.positions[g.patch:g.patch+1], head.Config.PointerRopeTheta).Reshape(q)
vit := query.Slice(mlx.Slice(), mlx.Slice(q, q+s)).Reshape(s)
loc := query.Slice(mlx.Slice(), mlx.Slice(q+s, q+s+l)).Reshape(l)
w := g.working
a := w.patchK.AsType(mlx.DTypeFloat32).Matmul(token).Divide(mlx.FromValue(float32(math.Sqrt(float64(q))))).Reshape(-1, 1, 1)
b := w.subpatchK.AsType(mlx.DTypeFloat32).Matmul(vit).Divide(mlx.FromValue(float32(math.Sqrt(float64(s))))).ExpandDims(-1)
c := w.locK.AsType(mlx.DTypeFloat32).Matmul(loc).Divide(mlx.FromValue(float32(math.Sqrt(float64(l)))))
scores := g.diffuse(a.Add(b).Add(c))
return mlx.Where(w.valid.ExpandDims(-1).Greater(mlx.FromValue(float32(0))), scores.Sigmoid(), mlx.FromValue(float32(-1)))
}
func (g *Grounding) diffuse(scores *mlx.Array) *mlx.Array {
p, s, n := scores.Dim(0), scores.Dim(1), scores.Dim(2)
r := g.model.GroundingHead.Config.SubpatchLocationSize
grid := int(g.model.Config.VisionConfig.ImageSize[0] / g.model.Config.VisionConfig.PatchSize)
weights := g.working.diffusion.AsType(mlx.DTypeFloat32)
crops := weights.Dim(0)
var validRows, rasterRows []int32
last := make(map[int32]int32)
for i, row := range g.pooling {
if row >= 0 {
validRows = append(validRows, int32(i))
rasterRows = append(rasterRows, row)
last[row] = int32(i)
}
}
if len(validRows) == 0 {
return scores
}
// CPU reference assignment keeps the last score for a repeated raster
// index. Parallel scatter to duplicate destinations otherwise races.
var sourceRows, scatterRows []int32
for i, row := range rasterRows {
if last[row] == validRows[i] {
sourceRows = append(sourceRows, validRows[i])
scatterRows = append(scatterRows, row)
}
}
flat := scores.Reshape(p*s, n)
indices := mlx.BroadcastTo(mlx.FromValues(scatterRows, len(scatterRows), 1), int32(len(scatterRows)), int32(n))
raster := mlx.Zeros(mlx.DTypeFloat32, crops*grid*grid, n).PutAlongAxis(indices, flat.TakeAxis(mlx.FromValues(sourceRows, len(sourceRows)), 0), 0)
mask := raster.Reshape(crops, grid, grid, r, r).Transpose(0, 1, 3, 2, 4).Reshape(crops, 1, grid*r, grid*r)
bounded := weights.Tanh().Divide(mlx.FromValue(float32(8)))
edges := [][2]int{{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}
for range g.model.GroundingHead.Config.MaskDiffusionSteps {
padded := mlx.Pad(mask, []int{2, 3}, []int{1, 1}, []int{1, 1}, mlx.FromValue(float32(0)), "edge")
delta := mlx.Zeros(mlx.DTypeFloat32, mask.Dims()...)
for i, edge := range edges {
neighbor := padded.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(1+edge[0], 1+edge[0]+grid*r), mlx.Slice(1+edge[1], 1+edge[1]+grid*r))
weight := bounded.Slice(mlx.Slice(), mlx.Slice(i, i+1), mlx.Slice(), mlx.Slice())
delta = delta.Add(weight.Multiply(neighbor.Subtract(mask)))
}
mask = mask.Add(delta)
}
out := mask.Reshape(crops, grid, r, grid, r).Transpose(0, 1, 3, 2, 4).Reshape(crops*grid*grid, n)
// Gather in ViT raster order, but scatter back into score-row destinations.
values := out.TakeAxis(mlx.FromValues(rasterRows, len(rasterRows)), 0)
dest := mlx.BroadcastTo(mlx.FromValues(validRows, len(validRows), 1), int32(len(validRows)), int32(n))
return flat.PutAlongAxis(dest, values, 0).Reshape(p, s, n)
}
func groundingRoPE(x *mlx.Array, positions []int32, theta float32) *mlx.Array {
dim := x.Dim(-1)
half := dim / 2
powers := mlx.Arange(0, float64(dim), 2, mlx.DTypeFloat32).Divide(mlx.FromValue(float32(dim)))
freq := mlx.FromValue(float32(1)).Divide(mlx.FromValue(theta).Power(powers))
angles := mlx.FromValues(positions, len(positions)).AsType(mlx.DTypeFloat32).ExpandDims(1).Multiply(freq)
angles = mlx.Concatenate([]*mlx.Array{angles, angles}, -1)
x32 := x.AsType(mlx.DTypeFloat32)
rotated := mlx.Concatenate([]*mlx.Array{x32.Slice(mlx.Slice(), mlx.Slice(half, dim)).Negative(), x32.Slice(mlx.Slice(), mlx.Slice(0, half))}, -1)
return x32.Multiply(mlx.Cos(angles)).Add(rotated.Multiply(mlx.Sin(angles))).AsType(x.DType())
}
func groundingSetLogit(logits *mlx.Array, id int32, value float32) *mlx.Array {
return logits.Reshape(-1).SliceUpdate(mlx.FromValues([]float32{value}, 1).AsType(logits.DType()), mlx.Slice(int(id), int(id)+1)).Reshape(logits.Dims()...)
}
func groundingArgmax(x *mlx.Array) int {
return int(x.AsType(mlx.DTypeFloat32).Argmax(-1, false).AsType(mlx.DTypeInt32).Int())
}
func (g *Grounding) Document(ids []int32, truncated bool) (string, error) {
if g == nil || g.scope == nil || g.model.tok == nil {
return "", fmt.Errorf("molmo3: closed grounding request or missing tokenizer")
}
if g.err != nil {
return "", g.err
}
images := make([]modelmolmo3.DocumentImage, len(g.images))
for i, im := range g.images {
m := im.media
images[i] = modelmolmo3.DocumentImage{Width: m.originalWidth, Height: m.originalHeight, TokenPooling: m.tokenPooling, TokenPoolingShape: m.tokenPoolingShape, Mapping: m.mapping, MappingShape: m.mappingShape, NumGlobalTokens: m.numGlobalTokens}
}
grounding := &modelmolmo3.DocumentGrounding{Points: g.points, NoPoint: g.noPoint, MaskAnchors: g.maskAnchors}
for _, mask := range g.masks {
grounding.MaskScores = append(grounding.MaskScores, modelmolmo3.DocumentMaskScores{Values: mask.Floats(), Shape: [3]int{mask.Dim(0), mask.Dim(1), mask.Dim(2)}})
}
document, err := modelmolmo3.DecodeDocument(g.model.tok.Decode(ids), grounding, images, modelmolmo3.DocumentDecodeOptions{Truncated: truncated})
if err != nil {
return "", err
}
data, err := json.Marshal(document)
return string(data), err
}
func (g *Grounding) Close() {
if g != nil && g.scope != nil {
g.scope.Close()
g.scope = nil
g.tokens = nil
g.images = nil
g.working = nil
g.positions = nil
g.points = nil
g.masks = nil
g.maskAnchors = nil
g.pooling = nil
}
}
+707
View File
@@ -0,0 +1,707 @@
package molmo3
import (
"encoding/json"
"math"
"os"
"slices"
"strings"
"testing"
"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/tokenizer"
modelmolmo3 "github.com/ollama/ollama/model/molmo3"
"github.com/ollama/ollama/mlx/mlxtest"
)
// FP32 reference comparisons must not silently use Metal TF32 matmuls.
// MLX caches this option at first use, so set it before any test constructs graphs.
func TestMain(m *testing.M) {
if err := os.Setenv("MLX_ENABLE_TF32", "0"); err != nil {
panic(err)
}
os.Exit(m.Run())
}
// This oracle was captured from molmo3-hf bf3b580d0f694d3851553f3974f54bbe349ce2f8
// with PyTorch 2.15.0 eager attention and deterministic FP32 weights. No files,
// private checkpoint or Python runtime are needed to execute these tests.
const groundingFixtureConfig = `{"adapter_config":{"attention_bias":true,"attention_dropout":0.0,"head_dim":4,"hidden_act":"silu","hidden_size":8,"initializer_range":0.02,"intermediate_size":12,"mlp_bias":false,"model_type":"molmo3_adapter","num_attention_heads":2,"num_key_value_heads":2,"num_pooling_positions":9,"text_hidden_size":8,"vision_feature_layer":[1,0]},"architectures":["Molmo3ForConditionalGeneration"],"center_patch_id":24,"corresponding_patch_id":25,"dtype":"float32","frame_end_token_id":19,"frame_start_token_id":18,"image_col_id":14,"image_end_token_id":17,"image_low_res_id":13,"image_patch_id":12,"image_start_token_id":15,"initializer_range":0.02,"low_res_image_start_token_id":16,"mask_diffusion_steps":2,"model_type":"molmo3","patch_position_embedding_size":512,"point_loc_id":22,"point_patch_id":20,"point_query_dims":[4,2,1],"point_subpatch_id":21,"pointer_rope_theta":50000.0,"seg_mask_id":23,"subpatch_conv_kernel":3,"subpatch_hidden_size":4,"subpatch_location_size":4,"text_config":{"attention_bias":false,"attention_dropout":0.0,"head_dim":4,"hidden_act":"silu","hidden_size":8,"initializer_range":0.02,"intermediate_size":12,"max_position_embeddings":128,"model_type":"molmo3_text","num_attention_heads":2,"num_hidden_layers":2,"num_key_value_heads":1,"qk_norm_type":"qwen3","rms_norm_eps":1e-06,"rope_parameters":{"rope_theta":5000000.0,"rope_type":"default"},"tie_word_embeddings":false,"use_cache":true,"vocab_size":140},"tie_word_embeddings":false,"transformers_version":"5.2.0","use_cache":true,"vision_config":{"attention_bias":true,"attention_dropout":0.0,"head_dim":4,"hidden_act":"gelu_pytorch_tanh","hidden_size":8,"image_size":[28,28],"initializer_range":0.02,"intermediate_size":12,"layer_norm_eps":1e-06,"model_type":"molmo3_vision","num_attention_heads":2,"num_channels":3,"num_hidden_layers":2,"num_key_value_heads":2,"num_position_embeddings":4,"patch_size":14}}`
var groundingFixtureShapes = map[string][]int{
"lm_head.weight": {140, 8},
"model.build_location_embeddings.weight": {16, 8},
"model.build_subpatch_embeddings.bias": {8},
"model.build_subpatch_embeddings.weight": {8, 4},
"model.connector.image_pooling_2d.wk.bias": {8},
"model.connector.image_pooling_2d.wk.weight": {8, 16},
"model.connector.image_pooling_2d.wq.bias": {8},
"model.connector.image_pooling_2d.wq.weight": {8, 16},
"model.connector.image_pooling_2d.wv.bias": {8},
"model.connector.image_pooling_2d.wv.weight": {8, 16},
"model.connector.image_projector.w1.weight": {12, 8},
"model.connector.image_projector.w2.weight": {8, 12},
"model.connector.image_projector.w3.weight": {12, 8},
"model.connector.positional_embeddings.bias": {9, 16},
"model.loc_q.bias": {16},
"model.loc_q.weight": {16, 8},
"model.mask_affinity.conv.bias": {128},
"model.mask_affinity.conv.weight": {128, 16, 3, 3},
"model.mask_q.bias": {7},
"model.mask_q.weight": {7, 8},
"model.patch_k.bias": {4},
"model.patch_k.weight": {4, 8},
"model.patch_q.bias": {4},
"model.patch_q.weight": {4, 8},
"model.subpatch_conv.conv.bias": {4},
"model.subpatch_conv.conv.weight": {4, 4, 3, 3},
"model.subpatch_conv.proj.bias": {4},
"model.subpatch_conv.proj.weight": {4, 16, 1, 1},
"model.subpatch_hidden.bias": {4},
"model.subpatch_hidden.weight": {4, 16},
"model.subpatch_loc_k.w_in1.weight": {16, 4},
"model.subpatch_loc_k.w_in2.weight": {16, 8},
"model.subpatch_loc_k.w_out.bias": {18},
"model.subpatch_loc_k.w_out.weight": {18, 8},
"model.subpatch_pos_embed.proj.bias": {16},
"model.subpatch_pos_embed.proj.weight": {16, 1536},
"model.subpatch_q.bias": {2},
"model.subpatch_q.weight": {2, 8},
"model.transformer.blocks.0.att_proj.weight": {16, 8},
"model.transformer.blocks.0.attn_norm.weight": {8},
"model.transformer.blocks.0.attn_out.weight": {8, 8},
"model.transformer.blocks.0.ff_norm.weight": {8},
"model.transformer.blocks.0.ff_out.weight": {8, 12},
"model.transformer.blocks.0.ff_proj.weight": {24, 8},
"model.transformer.blocks.0.k_norm.weight": {4},
"model.transformer.blocks.0.q_norm.weight": {4},
"model.transformer.blocks.1.att_proj.weight": {16, 8},
"model.transformer.blocks.1.attn_norm.weight": {8},
"model.transformer.blocks.1.attn_out.weight": {8, 8},
"model.transformer.blocks.1.ff_norm.weight": {8},
"model.transformer.blocks.1.ff_out.weight": {8, 12},
"model.transformer.blocks.1.ff_proj.weight": {24, 8},
"model.transformer.blocks.1.k_norm.weight": {4},
"model.transformer.blocks.1.q_norm.weight": {4},
"model.transformer.ln_f.weight": {8},
"model.transformer.wte.embedding": {12, 8},
"model.transformer.wte.new_embedding": {128, 8},
"model.vit.patch_embedding.bias": {8},
"model.vit.patch_embedding.weight": {8, 588},
"model.vit.positional_embedding": {4, 8},
"model.vit.transformer.resblocks.0.attention.wk.bias": {8},
"model.vit.transformer.resblocks.0.attention.wk.weight": {8, 8},
"model.vit.transformer.resblocks.0.attention.wo.bias": {8},
"model.vit.transformer.resblocks.0.attention.wo.weight": {8, 8},
"model.vit.transformer.resblocks.0.attention.wq.bias": {8},
"model.vit.transformer.resblocks.0.attention.wq.weight": {8, 8},
"model.vit.transformer.resblocks.0.attention.wv.bias": {8},
"model.vit.transformer.resblocks.0.attention.wv.weight": {8, 8},
"model.vit.transformer.resblocks.0.attention_norm.bias": {8},
"model.vit.transformer.resblocks.0.attention_norm.weight": {8},
"model.vit.transformer.resblocks.0.feed_forward.w1.bias": {12},
"model.vit.transformer.resblocks.0.feed_forward.w1.weight": {12, 8},
"model.vit.transformer.resblocks.0.feed_forward.w2.bias": {8},
"model.vit.transformer.resblocks.0.feed_forward.w2.weight": {8, 12},
"model.vit.transformer.resblocks.0.ffn_norm.bias": {8},
"model.vit.transformer.resblocks.0.ffn_norm.weight": {8},
"model.vit.transformer.resblocks.1.attention.wk.bias": {8},
"model.vit.transformer.resblocks.1.attention.wk.weight": {8, 8},
"model.vit.transformer.resblocks.1.attention.wo.bias": {8},
"model.vit.transformer.resblocks.1.attention.wo.weight": {8, 8},
"model.vit.transformer.resblocks.1.attention.wq.bias": {8},
"model.vit.transformer.resblocks.1.attention.wq.weight": {8, 8},
"model.vit.transformer.resblocks.1.attention.wv.bias": {8},
"model.vit.transformer.resblocks.1.attention.wv.weight": {8, 8},
"model.vit.transformer.resblocks.1.attention_norm.bias": {8},
"model.vit.transformer.resblocks.1.attention_norm.weight": {8},
"model.vit.transformer.resblocks.1.feed_forward.w1.bias": {12},
"model.vit.transformer.resblocks.1.feed_forward.w1.weight": {12, 8},
"model.vit.transformer.resblocks.1.feed_forward.w2.bias": {8},
"model.vit.transformer.resblocks.1.feed_forward.w2.weight": {8, 12},
"model.vit.transformer.resblocks.1.ffn_norm.bias": {8},
"model.vit.transformer.resblocks.1.ffn_norm.weight": {8},
"model.x_norm.weight": {8},
}
func groundingFixtureWeights() map[string]*mlx.Array {
tensors := make(map[string]*mlx.Array)
for name, shape := range groundingFixtureShapes {
n, offset := 1, 0
for _, d := range shape {
n *= d
}
for _, b := range []byte(name) {
offset += int(b)
}
offset %= 19
values := make([]float32, n)
for i := range values {
values[i] = float32((i*7+offset)%19-9) / 32
if strings.HasSuffix(name, "weight") && (strings.Contains(name, "norm") || strings.Contains(name, "ln_f")) {
values[i] = 1 + values[i]/4
}
if name == "model.patch_q.bias" {
values[i] = 3
}
if name == "model.patch_k.bias" {
values[i] = 2
}
}
tensors[name] = mlx.FromValues(values, shape...)
}
return tensors
}
func groundingFixtureItem() *model.PreparedItem {
pixels := make([]float32, 2*4*588)
for i := range pixels {
pixels[i] = float32(i % 256)
}
return &model.PreparedItem{Range: [2]int{1, 8}, Dims: []int{2, 4, 588}, MediaData: pixels, Opaque: imageForwardState{
originalWidth: 8, originalHeight: 6, mapping: []int32{4, 5, 6, 7}, mappingShape: [2]int{2, 2}, numGlobalTokens: 1,
length: 7, spans: []imageFeatureSpan{{start: 1, count: 1}, {start: 4, count: 1, featureStart: 1}},
tokenPooling: []int32{0, 1, 2, 3, 7, 4, 6, -1}, tokenPoolingShape: [2]int{2, 4},
patchPosIDs: []int32{0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1}, patchPosShape: [3]int{2, 4, 3},
}}
}
func groundingFixtureTokenizer(t *mlxtest.T) *tokenizer.Tokenizer {
t.Helper()
tok, err := tokenizer.LoadFromBytes([]byte(`{"model":{"type":"BPE","vocab":{"a":0,"<points coords=\"":3," 0\">target</points>":4,"<seg coords=\"":5,"\">object</seg>":6},"merges":[]},"added_tokens":[{"id":20,"content":"<|POINT_PATCH|>","special":true},{"id":21,"content":"<|POINT_SUBPATCH|>","special":true},{"id":22,"content":"<|POINT_LOC|>","special":true},{"id":23,"content":"<|SEG_MASK|>","special":true}]}`))
if err != nil {
t.Fatal(err)
}
return tok
}
func groundingCloseCaches(caches []cache.Cache) {
for _, c := range caches {
c.Free()
}
}
func groundingCheckFloats(t *mlxtest.T, name string, got, want []float32, tolerance float64) {
t.Helper()
if len(got) != len(want) {
t.Fatalf("%s length=%d, want %d", name, len(got), len(want))
}
for i, v := range got {
if math.IsNaN(float64(v)) || math.Abs(float64(v-want[i])) > tolerance {
t.Fatalf("%s[%d]=%.9g, want %.9g (tol %g)", name, i, v, want[i], tolerance)
}
}
}
func TestGroundingPointReferenceTrajectory(t *testing.T) {
loaded, err := newModel(testModelRoot(t, groundingFixtureConfig))
if err != nil {
t.Fatal(err)
}
mlxtest.Run(t, func(t *mlxtest.T) {
m := loaded.(*Model)
if err := m.LoadWeights(groundingFixtureWeights()); err != nil {
t.Fatal(err)
}
tokens := []int32{1, 16, 13, 17, 15, 12, 14, 17, 2}
item := groundingFixtureItem()
g, err := m.newGrounding(tokens, []*model.PreparedItem{item})
if err != nil {
t.Fatalf("create image grounding: %v", err)
}
defer g.Close()
caches := m.NewCaches()
defer groundingCloseCaches(caches)
features := g.EncodeMedia(item, mlx.FromValues(item.MediaData, item.Dims...))
item.MediaData = nil // Encoding must not rely on a retained pixel buffer.
b := &batch.Batch{InputIDs: mlx.FromValues(tokens, 1, len(tokens)), SeqOffsets: []int32{0}, SeqQueryLens: []int32{int32(len(tokens))}, Media: []batch.MediaItem{{Pos: 1, Features: features, Opaque: item.Opaque}}}
hidden, _ := g.Forward(b, cache.Layers(caches))
if err := g.CapturePrefill(b, hidden); err != nil {
t.Fatal(err)
}
if _, err := g.Logits(2, hidden.Slice(mlx.Slice(), mlx.Slice(8, 9), mlx.Slice())); err != nil {
t.Fatal(err)
}
expected := [][]float32{
{0.312701285, -0.115422383, -0.118180782, -0.0585624203, -0.458405703, 0.266791463, -0.141133904, 0.247012407},
{0.291238308, -0.130879939, -0.135161251, -0.122934572, -0.46384418, 0.279647052, -0.167130843, 0.245547563},
{0.222168773, 0.242891327, -0.137918562, -0.0538792796, -0.214393705, -0.336621583, 0.193916187, -0.141311377},
{0.0609715655, 0.208234817, 0.0640245304, 0.154098332, -0.0133375581, 0.208217725, -0.172321036, -0.483572662},
}
defer func() {
m.tok = groundingFixtureTokenizer(t)
content, err := g.Document([]int32{3, 20, 21, 22, 4}, false)
if err != nil {
t.Fatal(err)
}
var doc modelmolmo3.Document
if err := json.Unmarshal([]byte(content), &doc); err != nil {
t.Fatal(err)
}
if doc.Text != `<points id="1">target</points>` || len(doc.MultiModal) != 1 {
t.Fatalf("point document=%s", content)
}
if !slices.Equal(g.points, []modelmolmo3.GroundingPoint{{Patch: 1, Subpatch: 1, Location: 1}}) {
t.Errorf("selected points = %v", g.points)
}
if g.noPoint == nil || math.Abs(*g.noPoint-5.377467459766194e-05) > 2e-7 {
t.Errorf("no-point probability = %v", g.noPoint)
}
}()
for i, token := range []int32{20, 21, 22, 1} {
b = &batch.Batch{InputIDs: mlx.FromValues([]int32{token}, 1, 1), SeqOffsets: []int32{int32(9 + i)}, SeqQueryLens: []int32{1}}
hidden, _ = g.Forward(b, cache.Layers(caches))
logits, err := g.Logits(token, hidden)
if err != nil {
t.Fatal(err)
}
groundingCheckFloats(t, "feedback trajectory", hidden.Floats(), expected[i], 2e-5)
values := logits.Floats()
if !math.IsInf(float64(values[24]), -1) || !math.IsInf(float64(values[25]), -1) {
t.Fatal("unsupported patch types were enabled")
}
if token == 21 && values[22] != 100000 {
t.Fatalf("location successor=%g", values[22])
}
}
})
}
func TestGroundingMaskReferenceScores(t *testing.T) {
loaded, err := newModel(testModelRoot(t, groundingFixtureConfig))
if err != nil {
t.Fatal(err)
}
mlxtest.Run(t, func(t *mlxtest.T) {
m := loaded.(*Model)
if err := m.LoadWeights(groundingFixtureWeights()); err != nil {
t.Fatal(err)
}
tokens := []int32{1, 16, 13, 17, 15, 12, 14, 17, 2}
item := groundingFixtureItem()
g, err := m.newGrounding(tokens, []*model.PreparedItem{item})
if err != nil {
t.Fatal(err)
}
defer g.Close()
caches := m.NewCaches()
defer groundingCloseCaches(caches)
features := g.EncodeMedia(item, mlx.FromValues(item.MediaData, item.Dims...))
item.MediaData = nil
b := &batch.Batch{InputIDs: mlx.FromValues(tokens, 1, 9), SeqOffsets: []int32{0}, SeqQueryLens: []int32{9}, Media: []batch.MediaItem{{Pos: 1, Features: features, Opaque: item.Opaque}}}
g.Forward(b, cache.Layers(caches))
for i, token := range []int32{20, 23, 1} {
b = &batch.Batch{InputIDs: mlx.FromValues([]int32{token}, 1, 1), SeqOffsets: []int32{int32(9 + i)}, SeqQueryLens: []int32{1}}
hidden, _ := g.Forward(b, cache.Layers(caches))
if _, err := g.Logits(token, hidden); err != nil {
t.Fatalf("mask token %d: %v", token, err)
}
}
m.tok = groundingFixtureTokenizer(t)
content, err := g.Document([]int32{5, 20, 23, 6}, false)
if err != nil {
t.Fatal(err)
}
var doc modelmolmo3.Document
if err := json.Unmarshal([]byte(content), &doc); err != nil {
t.Fatal(err)
}
if doc.Text != `<seg id="1">object</seg>` || len(doc.MultiModal) != 1 || doc.MultiModal[0]["type"] != "segmentation" {
t.Fatalf("mask document=%s", content)
}
if len(g.masks) != 1 || !slices.Equal(g.maskAnchors, []int{1}) {
t.Fatalf("masks=%d anchors=%v", len(g.masks), g.maskAnchors)
}
groundingCheckFloats(t, "mask scores", g.masks[0].Floats(), []float32{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0.232818812, 0.226573735, 0.213691577, 0.263846457, 0.258872986, 0.2474114, 0.242786229, 0.263679147, 0.252700359, 0.231400684, 0.258436054, 0.247738734, 0.266807526, 0.251666844, 0.250167698, 0.26028505, 0.243417218, 0.234367549, 0.244503155, 0.206458241, 0.270419061, 0.257060587, 0.24481827, 0.278720915, 0.245673954, 0.234973222, 0.269238412, 0.157624424, 0.267873794, 0.250189424, 0.256665796, 0.249700844, 0.249381527, 0.229130328, 0.255045205, 0.301133186, 0.265225649, 0.255016565, 0.240792558, 0.262251467, 0.24220866, 0.23849757, 0.2641325, 0.236833751, 0.268602461, 0.264288664, 0.235728979, 0.262373537, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 2e-5)
})
}
func TestGroundingMaskQueryBF16Reference(t *testing.T) {
loaded, err := newModel(testModelRoot(t, groundingFixtureConfig))
if err != nil {
t.Fatal(err)
}
mlxtest.Run(t, func(t *mlxtest.T) {
m := loaded.(*Model)
weights := groundingFixtureWeights()
for name, w := range weights {
weights[name] = w.AsType(mlx.DTypeBFloat16)
}
if err := m.LoadWeights(weights); err != nil {
t.Fatal(err)
}
g := &Grounding{model: m, patch: 1, positions: []int32{0, 137}, pooling: []int32{0, 1, 2, 3, 7, 4, 6, -1}, working: &groundingTensors{
patchK: mlx.FromValues([]float32{-.40234375, .921875, -.7109375, .2109375, .53125, -.61328125, .8046875, .349609375}, 2, 4).AsType(mlx.DTypeBFloat16),
valid: mlx.FromValues([]float32{1, 1, 1, 1, 1, 1, 1, 1}, 2, 4), subpatchK: mlx.Zeros(mlx.DTypeBFloat16, 2, 4, 2), locK: mlx.Zeros(mlx.DTypeBFloat16, 2, 4, 16, 1), diffusion: mlx.Zeros(mlx.DTypeBFloat16, 2, 8, 8, 8),
}}
h := mlx.FromValues([]float32{.3, -.7, .11, 1.3, -.2, .9, .51, -1.1}, 1, 1, 8).AsType(mlx.DTypeBFloat16)
got := g.maskScores(h).Floats()
want := make([]float32, 128)
for i := range want {
if i < 64 {
want[i] = .4171455204486847
} else {
want[i] = .5132282376289368
}
}
groundingCheckFloats(t, "BF16 query cast before RoPE", got, want, 1e-6)
})
}
func TestGroundingDiffusionRepeatedInvalidReference(t *testing.T) {
loaded, err := newModel(testModelRoot(t, groundingFixtureConfig))
if err != nil {
t.Fatal(err)
}
mlxtest.Run(t, func(t *mlxtest.T) {
weights := make([]float32, 2*8*8*8)
for i := range weights {
weights[i] = float32((i*13)%101-50) / 64
}
scores := make([]float32, 3*4*16)
for i := range scores {
scores[i] = float32(i*3-137) / 128
}
g := &Grounding{model: loaded.(*Model), pooling: []int32{7, 1, -1, 7, 2, 6, 1, -1, 3, 0, 5, 4}, working: &groundingTensors{diffusion: mlx.FromValues(weights, 2, 8, 8, 8)}}
groundingCheckFloats(t, "nonidentity repeated/invalid diffusion", g.diffuse(mlx.FromValues(scores, 3, 4, 16)).Floats(), []float32{-0.0907354355, 0.298468709, -0.291942358, 0.0388144217, 0.185313389, 0.169754416, 0.204123914, 0.190270305, 0.282694519, 0.248399258, 0.275929302, 0.296495646, 0.414102852, 0.342703104, 0.390512377, 0.437617421, 1.17647231, 1.18817031, 1.22083485, 1.23175597, 1.3093152, 1.27697885, 1.32933509, 1.32933557, 1.41089666, 1.36182714, 1.40229344, 1.42538738, 1.21115088, 1.45457745, 1.40561581, 1.48271966, -0.3203125, -0.296875, -0.2734375, -0.25, -0.2265625, -0.203125, -0.1796875, -0.15625, -0.1328125, -0.109375, -0.0859375, -0.0625, -0.0390625, -0.015625, 0.0078125, 0.03125, -0.0907354355, 0.298468709, -0.291942358, 0.0388144217, 0.185313389, 0.169754416, 0.204123914, 0.190270305, 0.282694519, 0.248399258, 0.275929302, 0.296495646, 0.414102852, 0.342703104, 0.390512377, 0.437617421, 0.0946255028, 0.432667941, 0.757686973, 0.634378076, 0.556921542, 0.57995981, 0.584988177, 0.219981432, 0.636440933, 0.666039586, 0.650858343, 0.349660337, 0.717833221, 0.728109777, 0.738247693, 0.471592784, 0.128978491, 0.505215824, 0.903791845, 1.37989068, 0.951588631, 0.963449001, 0.990100265, 0.988557756, 1.00967062, 1.03637695, 1.0284009, 1.05627823, 1.10055971, 1.11284959, 1.1244055, 1.11875033, 1.17647231, 1.18817031, 1.22083485, 1.23175597, 1.3093152, 1.27697885, 1.32933509, 1.32933557, 1.41089666, 1.36182714, 1.40229344, 1.42538738, 1.21115088, 1.45457745, 1.40561581, 1.48271966, 1.5546875, 1.578125, 1.6015625, 1.625, 1.6484375, 1.671875, 1.6953125, 1.71875, 1.7421875, 1.765625, 1.7890625, 1.8125, 1.8359375, 1.859375, 1.8828125, 1.90625, 1.84797871, 2.01223397, 1.98697186, 2.12717152, 1.79859328, 2.04126072, 2.06130409, 2.11484265, 1.83887672, 2.13083792, 2.15372157, 2.20976663, 1.89575911, 2.24503231, 2.25612211, 2.29903626, 2.3024528, 2.33610868, 2.37297201, 2.47918582, 2.42402458, 2.44372296, 2.47492576, 2.52337694, 2.50242639, 2.53468323, 2.54675698, 2.57705402, 2.57145452, 2.29414988, 2.74373269, 2.16868353, 2.62733006, 2.70991468, 2.71314478, 2.74740767, 2.72277927, 2.77607203, 2.799088, 2.82961392, 2.80865693, 2.84893155, 2.89904666, 2.9140954, 2.65885735, 3.28679609, 3.00490665, 3.62413979, 3.04087687, 3.08482409, 3.11146331, 3.07813835, 3.13935637, 3.19378138, 3.21893215, 3.1591897, 3.22309279, 3.27029991, 3.30534387, 3.37012792, 3.55943894, 3.27239633, 2.94747972, 3.57612586}, 2e-6)
})
}
func TestGroundingMultipleImagesChunkedReference(t *testing.T) {
loaded, err := newModel(testModelRoot(t, groundingFixtureConfig))
if err != nil {
t.Fatal(err)
}
mlxtest.Run(t, func(t *mlxtest.T) {
m := loaded.(*Model)
if err := m.LoadWeights(groundingFixtureWeights()); err != nil {
t.Fatal(err)
}
tokens := []int32{1, 16, 13, 17, 15, 12, 14, 17, 2, 16, 13, 17, 15, 12, 14, 17, 2}
first, second := groundingFixtureItem(), groundingFixtureItem()
second.Range = [2]int{9, 16}
for i := range second.MediaData {
second.MediaData[i] = float32((i + 97) % 256)
}
g, err := m.newGrounding(tokens, []*model.PreparedItem{first, second})
if err != nil {
t.Fatal(err)
}
defer g.Close()
caches := m.NewCaches()
defer groundingCloseCaches(caches)
for i, item := range []*model.PreparedItem{first, second} {
mlx.Scoped(func() {
features := g.EncodeMedia(item, mlx.FromValues(item.MediaData, item.Dims...))
item.MediaData = nil
b := &batch.Batch{InputIDs: mlx.FromValues(tokens[i*8:(i+1)*8], 1, 8), SeqOffsets: []int32{int32(i * 8)}, SeqQueryLens: []int32{8}, Media: []batch.MediaItem{{Pos: item.Range[0], Features: features, Opaque: item.Opaque}}}
hidden, _ := m.Forward(b, cache.Layers(caches))
if err := g.CapturePrefill(b, hidden); err != nil {
t.Fatal(err)
}
})
}
if g.prefilled != 16 {
t.Fatalf("prefill boundary=%d", g.prefilled)
}
b := &batch.Batch{InputIDs: mlx.FromValues([]int32{2}, 1, 1), SeqOffsets: []int32{16}, SeqQueryLens: []int32{1}}
hidden, _ := g.Forward(b, cache.Layers(caches))
if _, err := g.Logits(2, hidden); err != nil {
t.Fatal(err)
}
if len(g.points) != 0 || len(g.masks) != 0 || g.noPoint != nil {
t.Fatal("prompt seed became a generated selection")
}
if !slices.Equal(g.positions, []int32{0, 0, 1, 1}) || !slices.Equal(g.pooling, []int32{0, 1, 2, 3, 7, 4, 6, -1, 8, 9, 10, 11, 15, 12, 14, -1}) {
t.Fatalf("positions=%v pooling=%v", g.positions, g.pooling)
}
groundingCheckFloats(t, "multi image features", g.working.image.Floats(), []float32{-0.00968267862, -0.00415388541, 0.00946018938, -0.00256067468, 0.0117320418, -0.00189405133, 0.00653494056, 0.011964743, 0.0111031234, -0.0109877419, 0.0212836042, -0.0322187133, 0.00369966775, 0.0242047049, 0.0276398789, 0.0248828363, -0.00963002071, -0.0108472407, -0.00183256133, 0.00325146131, 0.012313135, 0.00930921733, 0.0135174431, -0.000170604093, -0.0032997271, -0.0114838667, 0.00210855855, -0.00343394792, 0.0104090925, 0.00654877163, 0.0130612757, 0.00648688059}, 2e-5)
groundingCheckFloats(t, "multi patch keys", g.working.patchK.Floats(), []float32{1.9831363, 2.05981469, 2.08770514, 2.16438365, 1.85438371, 1.86583865, 2.20564413, 2.21709919, -0.819468856, 2.08170152, 2.92869687, 2.35181975, -0.912521482, 1.81476378, 2.72729659, 2.27256894}, 2e-5)
func() {
defer func() {
if recover() == nil {
t.Error("completed image was encoded twice")
}
}()
g.EncodeMedia(second, mlx.Zeros(mlx.DTypeFloat32, second.Dims...))
}()
g.patch = 3
h := mlx.FromValues([]float32{-.1875, -.125, -.0625, 0, .0625, .125, .1875, .25}, 1, 1, 8)
groundingCheckFloats(t, "multi image mask", g.maskScores(h).Floats(), []float32{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0.35782817, 0.349104136, 0.344872326, 0.37667492, 0.374881059, 0.364892155, 0.360992879, 0.379398257, 0.370026141, 0.349091202, 0.375532448, 0.365205824, 0.383491695, 0.369017929, 0.367565632, 0.377300352, 0.361039042, 0.352103323, 0.36175409, 0.33961767, 0.386960566, 0.374269098, 0.362929016, 0.391807735, 0.363248169, 0.352705479, 0.384274781, 0.303107888, 0.384546071, 0.367616206, 0.370989919, 0.370334893, 0.366782248, 0.346798241, 0.373361051, 0.394533783, 0.381960124, 0.3722094, 0.359190077, 0.378235936, 0.359759152, 0.356104046, 0.380922705, 0.354449868, 0.38515237, 0.381070793, 0.353363335, 0.379244745, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0.430864602, 0.43324846, 0.442400724, 0.444405645, 0.451474518, 0.442728043, 0.436906308, 0.453132004, 0.448896021, 0.425638944, 0.454446048, 0.444472283, 0.466127306, 0.451598287, 0.4442375, 0.459338248, 0.439490676, 0.43055588, 0.446635038, 0.439191461, 0.466324151, 0.453983724, 0.441632509, 0.466698885, 0.440941453, 0.434611499, 0.458445996, 0.421320945, 0.466424316, 0.445638388, 0.446203023, 0.442520976, 0.450801849, 0.423847646, 0.454759985, 0.457167566, 0.465119094, 0.457946748, 0.442242831, 0.459326148, 0.432928145, 0.436666727, 0.459556788, 0.430895507, 0.473178148, 0.460021913, 0.432625026, 0.461766332, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 2e-5)
})
}
func TestGroundingConfigRejectedAtLoad(t *testing.T) {
for _, tc := range []struct {
name, field string
value any
}{
{"query width", "point_query_dims", []int{3, 2, 1}},
{"query count", "point_query_dims", []int{4, 2}},
{"locations", "subpatch_location_size", 2},
{"negative diffusion", "mask_diffusion_steps", -1},
{"pointer theta", "pointer_rope_theta", 0},
{"duplicate token", "point_patch_id", 25},
} {
t.Run(tc.name, func(t *testing.T) {
var cfg map[string]any
if err := json.Unmarshal([]byte(groundingFixtureConfig), &cfg); err != nil {
t.Fatal(err)
}
cfg[tc.field] = tc.value
data, err := json.Marshal(cfg)
if err != nil {
t.Fatal(err)
}
if _, err := newModel(testModelRoot(t, string(data))); err == nil {
t.Fatal("invalid grounding configuration accepted at model load")
}
})
}
}
func TestGroundingRejectsMalformedImageState(t *testing.T) {
loaded, err := newModel(testModelRoot(t, groundingFixtureConfig))
if err != nil {
t.Fatal(err)
}
mlxtest.Run(t, func(t *mlxtest.T) {
m := loaded.(*Model)
if err := m.LoadWeights(groundingFixtureWeights()); err != nil {
t.Fatal(err)
}
for _, name := range []string{"position shape", "empty pooling row", "pixel shape"} {
item := groundingFixtureItem()
media := item.Opaque.(imageForwardState)
switch name {
case "position shape":
media.patchPosShape = [3]int{2, 3, 4}
case "empty pooling row":
copy(media.tokenPooling[4:], []int32{-1, -1, -1, -1})
case "pixel shape":
item.Dims[2]--
}
item.Opaque = media
g, err := m.NewGrounding([]int32{1, 16, 13, 17, 15, 12, 14, 17, 2}, []*model.PreparedItem{item})
if err == nil || g != nil {
if g != nil {
g.Close()
}
t.Errorf("%s: expected nil state and an error, got %T, %v", name, g, err)
}
}
})
}
func TestGroundingFirstListAndNoPointReference(t *testing.T) {
loaded, err := newModel(testModelRoot(t, groundingFixtureConfig))
if err != nil {
t.Fatal(err)
}
mlxtest.Run(t, func(t *mlxtest.T) {
m := loaded.(*Model)
if err := m.LoadWeights(groundingFixtureWeights()); err != nil {
t.Fatal(err)
}
m.GroundingHead.PatchQ.Weight = mlx.Zeros(mlx.DTypeFloat32, 4, 8)
m.GroundingHead.PatchQ.Bias = mlx.FromValues([]float32{1, 1, 1, 1}, 4)
g, err := m.newGrounding([]int32{1, 16, 13, 17, 15, 12, 14, 17, 2}, []*model.PreparedItem{groundingFixtureItem()})
if err != nil {
t.Fatal(err)
}
defer g.Close()
g.prefilled = len(g.tokens)
g.working = &groundingTensors{patchK: mlx.FromValues([]float32{-.2, -.2, -.2, -.2, -.2, -.2, -.2, -.2}, 2, 4), valid: mlx.FromValues([]float32{1, 1, 1, 1, 1, 1, 1, 1}, 2, 4)}
hidden := mlx.Zeros(mlx.DTypeFloat32, 1, 1, 8)
for i := range 2 {
logits, err := g.Logits(20, hidden)
if err != nil {
t.Fatal(err)
}
if g.patch != 0 || g.rotateBy != 0 || g.patchResolved != (i == 0) || g.listStarted != (i == 0) {
t.Fatalf("list step %d: patch=%d resolved=%v list=%v rotate=%d", i, g.patch, g.patchResolved, g.listStarted, g.rotateBy)
}
if g.noPoint == nil || math.Abs(*g.noPoint-.42723357677459717) > 1e-7 {
t.Fatalf("no-point probability=%v", g.noPoint)
}
if i == 1 {
for _, id := range []int{20, 21, 22, 23} {
if logits.Floats()[id] != -1000000 {
t.Fatalf("end-of-list token %d not constrained", id)
}
}
}
}
content, err := g.Document([]int32{0}, false)
if err != nil {
t.Fatal(err)
}
var doc modelmolmo3.Document
if err := json.Unmarshal([]byte(content), &doc); err != nil {
t.Fatal(err)
}
if doc.Text != "a" || doc.MultiModal == nil || len(doc.MultiModal) != 0 {
t.Fatalf("no-point document=%s", content)
}
})
}
func TestGroundingRequestIsolationAndCleanup(t *testing.T) {
loaded, err := newModel(testModelRoot(t, groundingFixtureConfig))
if err != nil {
t.Fatal(err)
}
mlxtest.Run(t, func(t *mlxtest.T) {
m := loaded.(*Model)
if err := m.LoadWeights(groundingFixtureWeights()); err != nil {
t.Fatal(err)
}
mlx.Eval(mlx.Collect(m)...)
baseline := -1
for range 4 {
mlx.Scoped(func() {
item := groundingFixtureItem()
tokens := []int32{1, 16, 13, 17, 15, 12, 14, 17, 2}
g, err := m.newGrounding(tokens, []*model.PreparedItem{item})
if err != nil {
t.Fatal(err)
}
defer g.Close()
features := g.EncodeMedia(item, mlx.FromValues(item.MediaData, item.Dims...))
item.MediaData = nil
caches := m.NewCaches()
defer groundingCloseCaches(caches)
b := &batch.Batch{InputIDs: mlx.FromValues(tokens, 1, 9), SeqOffsets: []int32{0}, SeqQueryLens: []int32{9}, Media: []batch.MediaItem{{Pos: 1, Features: features, Opaque: item.Opaque}}}
hidden, _ := g.Forward(b, cache.Layers(caches))
h := hidden.Slice(mlx.Slice(), mlx.Slice(8, 9), mlx.Slice())
for _, token := range []int32{21, 22, 23, 24, 25} {
if _, err := g.Logits(token, h); err == nil {
t.Fatalf("orphan/unsupported token %d accepted", token)
}
}
for i, token := range []int32{20, 23} {
b = &batch.Batch{InputIDs: mlx.FromValues([]int32{token}, 1, 1), SeqOffsets: []int32{int32(9 + i)}, SeqQueryLens: []int32{1}}
hidden, _ = g.Forward(b, cache.Layers(caches))
logits, err := g.Logits(token, hidden)
if err != nil {
t.Fatal(err)
}
mlx.Eval(logits)
}
mlx.Eval(g.masks...)
// An overlapping request shares weights, never selections or tensors.
other, err := m.newGrounding(tokens, []*model.PreparedItem{groundingFixtureItem()})
if err != nil {
t.Fatal(err)
}
if other.working != nil || other.noPoint != nil || other.patchResolved || len(other.masks) != 0 {
t.Fatal("selection state leaked to a second request")
}
other.Close()
plain, err := m.newGrounding([]int32{1}, nil)
if err != nil {
t.Fatal(err)
}
plainLogits, err := plain.Logits(1, h)
if err != nil {
t.Fatal(err)
}
got, want := plainLogits.Floats(), m.Unembed(h).Floats()
for i := range got {
if got[i] != want[i] {
t.Fatalf("ordinary logit %d changed", i)
}
}
for _, id := range []int{20, 21, 22, 23, 24, 25} {
if !math.IsInf(float64(got[id]), -1) {
t.Fatalf("ordinary token %d enabled", id)
}
}
plain.Close()
g.Close()
g.Close()
if _, err := g.Logits(1, h); err == nil {
t.Fatal("closed grounding accepted logits")
}
if g.scope != nil || g.working != nil || len(g.masks) != 0 || len(g.images) != 0 {
t.Fatal("request retained state after close")
}
})
mlx.DefaultStream().Synchronize()
current := mlx.ActiveMemory()
if baseline >= 0 && current != baseline {
t.Fatalf("request memory after close=%d, baseline=%d", current, baseline)
}
baseline = current
}
})
}
func TestGroundingCloseDuringPrefill(t *testing.T) {
loaded, err := newModel(testModelRoot(t, groundingFixtureConfig))
if err != nil {
t.Fatal(err)
}
mlxtest.Run(t, func(t *mlxtest.T) {
m := loaded.(*Model)
if err := m.LoadWeights(groundingFixtureWeights()); err != nil {
t.Fatal(err)
}
mlx.Eval(mlx.Collect(m)...)
baseline := mlx.ActiveMemory()
for range 3 {
mlx.Scoped(func() {
item := groundingFixtureItem()
g, err := m.newGrounding([]int32{1, 16, 13, 17, 15, 12, 14, 17, 2}, []*model.PreparedItem{item})
if err != nil {
t.Fatal(err)
}
defer g.Close()
mlx.Eval(g.EncodeMedia(item, mlx.FromValues(item.MediaData, item.Dims...)))
b := &batch.Batch{SeqOffsets: []int32{1}, SeqQueryLens: []int32{1}}
if err := g.CapturePrefill(b, mlx.Zeros(mlx.DTypeFloat32, 1, 1, 8)); err == nil {
t.Fatal("prefill hole accepted")
}
// Cancellation and a prefill error use the same unconditional close.
})
mlx.DefaultStream().Synchronize()
if current := mlx.ActiveMemory(); current != baseline {
t.Fatalf("cancelled request retained %d bytes", current-baseline)
}
}
})
}
func TestGroundingDocumentWithoutImages(t *testing.T) {
loaded, err := newModel(testModelRoot(t, tinyConfig(t)))
if err != nil {
t.Fatal(err)
}
mlxtest.Run(t, func(t *mlxtest.T) {
g, err := loaded.(*Model).NewGrounding([]int32{0}, nil)
if err != nil {
t.Fatalf("create document request: %v", err)
}
defer g.Close()
content, err := g.Document([]int32{0}, false)
if err != nil {
t.Fatal(err)
}
var document struct {
Text string `json:"text"`
MultiModal []json.RawMessage `json:"multi_modal"`
Type string `json:"type"`
}
if err := json.Unmarshal([]byte(content), &document); err != nil {
t.Fatal(err)
}
if document.Text != "a" || document.Type != "text" || document.MultiModal == nil || len(document.MultiModal) != 0 {
t.Fatalf("document = %s", content)
}
g.Close()
})
}
+11 -7
View File
@@ -19,12 +19,16 @@ type imageFeatureSpan struct {
}
type imageForwardState struct {
length int
spans []imageFeatureSpan
tokenPooling []int32
tokenPoolingShape [2]int
patchPosIDs []int32
patchPosShape [3]int
length int
spans []imageFeatureSpan
tokenPooling []int32
tokenPoolingShape [2]int
patchPosIDs []int32
patchPosShape [3]int
originalWidth, originalHeight int
mapping []int32
mappingShape [2]int
numGlobalTokens int
}
var _ model.MediaModel = (*Model)(nil)
@@ -110,7 +114,7 @@ func (m *Model) PrepareMedia(segments []model.Segment) (*model.PreparedRequest,
func (m *Model) expandImage(processed *ImageProcessorResult) ([]int32, imageForwardState) {
var tokens []int32
state := imageForwardState{}
state := imageForwardState{originalWidth: processed.OriginalWidth, originalHeight: processed.OriginalHeight, mapping: processed.Mapping, mappingShape: processed.MappingShape, numGlobalTokens: processed.NumGlobalTokens}
lowTokens := processed.NumGlobalTokens
tokens = append(tokens, m.Config.LowResImageStartTokenID)
state.spans = append(state.spans, imageFeatureSpan{start: len(tokens), count: lowTokens})
+15 -1
View File
@@ -28,6 +28,7 @@ type Model struct {
LMHead nn.LinearLayer
Vision *Vision
SuppressLogitBias *mlx.Array
GroundingHead *GroundingHead
quantGroupSize int
quantBits int
@@ -68,6 +69,16 @@ func newModel(root *model.Root) (model.Model, error) {
}
if cfg.VisionConfig.HiddenSize > 0 {
m.Vision = &Vision{Config: &m.Config.VisionConfig, Adapter: &m.Config.AdapterConfig}
var grounding groundingConfig
if err := json.Unmarshal(configData, &grounding); err != nil {
return nil, fmt.Errorf("parse grounding config: %w", err)
}
if len(grounding.PointQueryDims) > 0 {
if err := grounding.validate(&cfg); err != nil {
return nil, err
}
m.GroundingHead = &GroundingHead{Config: grounding}
}
}
return m, nil
}
@@ -81,7 +92,10 @@ func (m *Model) NewCaches() []cache.Cache {
}
func (m *Model) Forward(b *batch.Batch, caches []cache.Layer) (*mlx.Array, *mlx.Array) {
hidden := m.embedInput(b)
return m.forward(b, caches, m.embedInput(b))
}
func (m *Model) forward(b *batch.Batch, caches []cache.Layer, hidden *mlx.Array) (*mlx.Array, *mlx.Array) {
positions := mlx.FromValues(b.SeqOffsets, len(b.SeqOffsets))
mask := m.mediaMask(b)
for i, layer := range m.Layers {
+8
View File
@@ -104,6 +104,14 @@ func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
return err
}
}
if m.GroundingHead != nil {
if err := m.GroundingHead.load(tensors, cfg.RMSNormEps); err != nil {
return err
}
if err := m.Vision.loadGrounding(tensors); err != nil {
return err
}
}
bias := make([]float32, cfg.VocabSize)
suppress := false
for _, id := range []int32{
+84 -14
View File
@@ -13,17 +13,20 @@ 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
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
SubpatchProjection *nn.Linear
SubpatchConvWeight, SubpatchConvBias *mlx.Array
MaskAffinityWeight, MaskAffinityBias *mlx.Array
}
type VisionLayer struct {
@@ -148,6 +151,15 @@ func visionLayerNorm(tensors map[string]*mlx.Array, name string, eps float32) (*
}
func (v *Vision) Encode(pixels, pooling, positions *mlx.Array) *mlx.Array {
features, _, _, _ := v.encode(pixels, pooling, positions, false)
return features
}
func (v *Vision) encodeGrounding(pixels, pooling, positions *mlx.Array) (*mlx.Array, *mlx.Array, *mlx.Array, *mlx.Array) {
return v.encode(pixels, pooling, positions, true)
}
func (v *Vision) encode(pixels, pooling, positions *mlx.Array, grounding bool) (*mlx.Array, *mlx.Array, *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)))
@@ -175,9 +187,67 @@ func (v *Vision) Encode(pixels, pooling, positions *mlx.Array) *mlx.Array {
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)
image := v.connect(gathered.Reshape(int(B*P), int(S), int(D)), valid.Reshape(int(B*P), int(S)))
if !grounding {
return image, nil, nil, nil
}
conv := v.subpatchConvolution(features)
convIndices := mlx.BroadcastTo(mlx.Maximum(pooling, zero).ExpandDims(-1), B, P, S, int32(conv.Dim(-1)))
conv = mlx.BroadcastTo(conv.ExpandDims(2), B, T*N, S, int32(conv.Dim(-1))).TakeAlongAxis(convIndices, 1)
conv = conv.Multiply(valid.ExpandDims(-1).AsType(conv.DType()))
return image, gathered, conv, v.maskDiffusionWeights(features)
}
func (v *Vision) loadGrounding(tensors map[string]*mlx.Array) error {
var err error
if v.SubpatchProjection, err = visionLinear(tensors, "model.subpatch_conv.proj", true); err != nil {
return err
}
w := v.SubpatchProjection.Weight
if w.NumDims() != 4 || w.Dim(2) != 1 || w.Dim(3) != 1 {
return fmt.Errorf("molmo3: invalid subpatch projection shape %v", w.Dims())
}
v.SubpatchProjection.Weight = w.Reshape(w.Dim(0), w.Dim(1))
if v.SubpatchConvWeight, err = requireTensor(tensors, "model.subpatch_conv.conv.weight"); err != nil {
return err
}
if v.SubpatchConvBias, err = requireTensor(tensors, "model.subpatch_conv.conv.bias"); err != nil {
return err
}
if v.MaskAffinityWeight, err = requireTensor(tensors, "model.mask_affinity.conv.weight"); err != nil {
return err
}
if v.MaskAffinityBias, err = requireTensor(tensors, "model.mask_affinity.conv.bias"); err != nil {
return err
}
return nil
}
func groundingConv(x, weight, bias *mlx.Array) *mlx.Array {
w := mlx.Contiguous(weight.Transpose(0, 2, 3, 1), false)
pad := int32((weight.Dim(2) - 1) / 2)
return mlx.Conv2d(x, w, 1, 1, pad, pad, 1, 1, 1).Add(bias)
}
func (v *Vision) subpatchConvolution(features *mlx.Array) *mlx.Array {
b, n, d := features.Dim(0), features.Dim(1), features.Dim(2)
grid := int(v.Config.ImageSize[0] / v.Config.PatchSize)
x := mlx.GELU(v.SubpatchProjection.Forward(features.Reshape(b*n, d)))
width := x.Dim(-1)
x = groundingConv(x.Reshape(b*n/(grid*grid), grid, grid, width), v.SubpatchConvWeight, v.SubpatchConvBias)
return x.Reshape(b, n, width).AsType(features.DType())
}
func (v *Vision) maskDiffusionWeights(features *mlx.Array) *mlx.Array {
b, n, d := features.Dim(0), features.Dim(1), features.Dim(2)
grid := int(v.Config.ImageSize[0] / v.Config.PatchSize)
crops := b * n / (grid * grid)
x := groundingConv(features.Reshape(crops, grid, grid, d), v.MaskAffinityWeight, v.MaskAffinityBias)
// The checkpoint packs channel, subpixel-y, subpixel-x, as pixel_shuffle.
r := int(math.Sqrt(float64(x.Dim(3) / 8)))
x = x.Reshape(crops, grid, grid, 8, r, r).Transpose(0, 1, 4, 2, 5, 3)
x = mlx.Contiguous(x, false).Reshape(crops, grid*r, grid*r, 8)
return x.Transpose(0, 3, 1, 2).AsType(features.DType())
}
func (v *Vision) positionFeatures(positions *mlx.Array, B, rows int32) *mlx.Array {
+39 -12
View File
@@ -103,6 +103,14 @@ func (r *Runner) Prepare(request *request) (err error) {
if r.Model == nil {
return errors.New("model not loaded")
}
if request.JSONDocument {
if _, ok := r.Model.(model.GroundingModel); !ok {
return errors.New("model does not support grounding document output")
}
if request.Logprobs {
return errors.New("document output does not support logprobs")
}
}
// Launched first so the compile overlaps tokenization and media
// preparation as well as prefill.
@@ -187,6 +195,7 @@ type prefillCursor struct {
session *cacheSession
spec *speculationSession
media *requestMedia
grounding model.GroundingState
processed, position int
started time.Time
}
@@ -228,19 +237,24 @@ func (p *prefillCursor) step(ctx context.Context) (bool, error) {
chunk := min(prefillChunkSize(), len(tokens)-p.processed-1)
n = p.media.extendChunk(p.position, chunk, len(p.session.inputs)-1)
}
var captureErr error
mlx.Scoped(func() {
chunkIDs := mlx.FromValues(tokens[p.processed:p.processed+n], 1, n)
chunkMedia := p.media.batchMedia(p.position, n)
auxHidden := mlx.ScopedArrays(func() []*mlx.Array {
_, auxHidden := p.r.Model.Forward(&batch.Batch{
InputIDs: chunkIDs,
SeqOffsets: []int32{int32(p.position)},
SeqQueryLens: []int32{int32(n)},
Media: chunkMedia,
Layout: p.media.rowLayout(),
}, cache.Layers(p.session.caches))
b := &batch.Batch{
InputIDs: chunkIDs,
SeqOffsets: []int32{int32(p.position)},
SeqQueryLens: []int32{int32(n)},
Media: chunkMedia,
Layout: p.media.rowLayout(),
}
forward := mlx.ScopedArrays(func() []*mlx.Array {
hidden, auxHidden := p.r.Model.Forward(b, cache.Layers(p.session.caches))
if p.grounding != nil {
return []*mlx.Array{auxHidden, hidden}
}
return []*mlx.Array{auxHidden}
})[0]
})
var state []*mlx.Array
for _, c := range p.session.caches {
if c != nil {
@@ -250,13 +264,21 @@ func (p *prefillCursor) step(ctx context.Context) (bool, error) {
mlx.Eval(state...)
// Report to the drafter only after the chunk's eval: a draft
// flush evaluates.
p.spec.committed(chunkIDs, auxHidden, p.position, chunkMedia)
p.spec.committed(chunkIDs, forward[0], p.position, chunkMedia)
if p.grounding != nil {
// Combining images releases their individual feature handles. The
// drafter must borrow its own handles before that ownership change.
captureErr = p.grounding.CapturePrefill(b, forward[1])
}
// Freed after committed so the drafter can capture rows its
// deferred flush still embeds.
p.media.free(p.position + n)
})
p.processed += n
p.position += n
if captureErr != nil {
return false, captureErr
}
slog.Info("Prompt processing progress", "processed", p.processed, "total", len(tokens))
logutil.TraceContext(ctx, "mlx prompt forward", "processed", p.processed, "total", len(tokens), "tokens", n, "memory", mlx.Memory{})
mlx.ClearCache()
@@ -295,14 +317,16 @@ type generationOutput struct {
limit, generated int
started time.Time
final CompletionResponse
document bool
}
func newGenerationOutput(r *Runner, request request, session *cacheSession, promptEval time.Duration) *generationOutput {
cached := len(session.inputs) - len(session.remaining)
return &generationOutput{
r: r, session: session, limit: request.Options.NumPredict, started: time.Now(),
detok: detokenizer{tokenizer: r.Tokenizer, wantLogprobs: request.SamplerOpts.Logprobs, wantTopLogprobs: request.SamplerOpts.TopLogprobs},
final: CompletionResponse{Done: true, DoneReason: 1, PromptEvalCount: len(request.Tokens), PromptEvalCachedCount: &cached, PromptEvalDuration: promptEval},
document: request.JSONDocument,
detok: detokenizer{tokenizer: r.Tokenizer, wantLogprobs: request.SamplerOpts.Logprobs, wantTopLogprobs: request.SamplerOpts.TopLogprobs},
final: CompletionResponse{Done: true, DoneReason: 1, PromptEvalCount: len(request.Tokens), PromptEvalCachedCount: &cached, PromptEvalDuration: promptEval},
}
}
@@ -327,6 +351,9 @@ func (o *generationOutput) consume(results []sampler.Result) ([]CompletionRespon
stream = i + 1
}
}
if o.document {
return nil, done
}
var responses []CompletionResponse
for _, res := range results[:stream] {
if response, ok := o.detok.detokenize(res); ok {
+100 -7
View File
@@ -2,6 +2,7 @@ package mlxrunner
import (
"context"
"fmt"
"log/slog"
"slices"
"time"
@@ -11,6 +12,7 @@ import (
"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/sample"
)
@@ -56,6 +58,7 @@ type batchRequest struct {
decoder decoder
grammar *grammar
output *generationOutput
grounding model.GroundingState
responses []CompletionResponse
finished bool
@@ -421,16 +424,44 @@ func (s *batchScheduler) admitGeneration(request request, best int) {
s.slots[best] = slot
}
req := &batchRequest{request: request}
if request.JSONDocument {
m, ok := s.r.Model.(model.GroundingModel)
if !ok {
request.reject(fmt.Errorf("model does not support grounding document output"))
return
}
items := make([]*model.PreparedItem, len(request.MediaItems))
for i, item := range request.MediaItems {
items[i] = item.item
}
var err error
req.grounding, err = m.NewGrounding(request.Tokens, items)
if err != nil {
if req.grounding != nil {
req.grounding.Close()
}
request.reject(err)
return
}
}
var peers []*prefixCache
for _, other := range s.slots {
if other != nil && other != slot && other.cache != nil {
peers = append(peers, other.cache)
}
}
req.session = slot.cache.begin(request.Tokens, request.MediaItems, peers...)
if req.grounding != nil && len(request.MediaItems) > 0 {
req.session = slot.cache.beginAt(request.Tokens, request.MediaItems, 0)
} else {
req.session = slot.cache.begin(request.Tokens, request.MediaItems, peers...)
}
req.media = s.r.openMedia(request)
req.spec = slot.speculation.open(request, req.media.rowLayout())
req.prefill = s.r.newPrefill(req.session, req.spec, req.media)
if req.grounding != nil && len(request.MediaItems) > 0 {
req.media.grounding = req.grounding
req.prefill.grounding = req.grounding
}
slot.request = req
}
@@ -440,7 +471,10 @@ func (s *batchScheduler) finish(slot *batchSlot, err error) {
return
}
if req.decoder != nil {
results, _, _ := req.decoder.drain()
results, _, drainErr := req.decoder.drain()
if req.grounding != nil && err == nil {
err = drainErr
}
for _, result := range results {
req.session.outputs = append(req.session.outputs, result.Token.Int())
}
@@ -457,6 +491,13 @@ func (s *batchScheduler) finish(slot *batchSlot, err error) {
// Discard uncommitted writes. Previously saved prefixes remain available on retry.
slot.cache.switchToPath([]*trieNode{slot.cache.root}, 0)
} else {
if req.grounding != nil && len(req.request.MediaItems) > 0 {
// Generated embeddings depend on selections absent from token keys.
// Retain only prompt KV, including the drafter's look-ahead boundary.
limit := min(slot.cache.minCacheOffset(), max(0, len(req.session.inputs)-slot.cache.draftLookahead))
slot.cache.rewind(limit)
slot.cache.alignCaches()
}
req.session.close()
}
if slog.Default().Enabled(req.request.Ctx, logutil.LevelTrace) {
@@ -464,11 +505,31 @@ func (s *batchScheduler) finish(slot *batchSlot, err error) {
}
req.media.close()
req.request.Grammar.close()
var responses []CompletionResponse
if err == nil && req.grounding != nil {
err = req.request.Ctx.Err()
}
if err == nil {
final := req.output.finish()
if req.grounding != nil {
var document string
document, err = req.grounding.Document(req.session.outputs[:req.output.generated], final.DoneReason != 0)
if err == nil {
responses, err = documentResponses(document, final)
}
} else {
responses = []CompletionResponse{final}
}
}
if req.grounding != nil {
req.grounding.Close()
req.grounding = nil
}
req.finished = true
if err != nil {
req.responses = append(req.responses, CompletionResponse{Error: completionStatusError(err)})
} else {
req.responses = append(req.responses, req.output.finish())
req.responses = append(req.responses, responses...)
}
slog.Debug("MLX batch request finished", "slot", slot.id, "memory", mlx.Memory{})
}
@@ -560,7 +621,9 @@ func (s *batchScheduler) step() bool {
seed := req.prefill.seed()
req.promptEval += time.Since(started)
s.r.Sampler.Add(slot.id, req.request.SamplerOpts, req.request.Tokens)
if req.spec != nil {
if req.grounding != nil && len(req.request.MediaItems) > 0 {
req.decoder = newGroundingDecoder(s.r, slot.id, req.spec, slot.targets, seed, req.prefill.position, req.media.rowLayout(), req.grounding)
} else if req.spec != nil {
req.decoder = req.spec.decoder(seed, req.prefill.position, req.grammar)
} else {
req.decoder = s.r.pipelinedDecoder(slot.id, nil, slot.targets, seed.ExpandDims(-1), req.prefill.position, req.media.rowLayout(), req.grammar)
@@ -576,6 +639,7 @@ func (s *batchScheduler) step() bool {
}
var ready []*batchSlot
active := 0
hasGrounding := false
for _, slot := range s.slots {
if slot == nil || slot.request == nil || slot.request.finished {
continue
@@ -583,13 +647,22 @@ func (s *batchScheduler) step() bool {
active++
if slot.request.prefill == nil && len(slot.request.responses) == 0 {
ready = append(ready, slot)
if _, ok := slot.request.decoder.(*groundingDecoder); ok {
hasGrounding = true
}
}
}
if len(ready) == 0 {
s.drafting.reset()
return progressed
}
if err := s.decode(ready, active); err != nil {
var err error
if hasGrounding {
err = s.decodeWithGrounding(ready, active)
} else {
err = s.decode(ready, active)
}
if err != nil {
// Cache compatibility is checked before a shared forward writes state.
// Fail this cohort without leaving an idle HTTP server waiting forever.
for _, slot := range ready {
@@ -615,8 +688,28 @@ func (s *batchScheduler) emit(slot *batchSlot, results []sample.Result, err erro
}
}
// decode advances the ready requests, grouping equal-length speculative rounds
// for a shared target forward when multiple requests are active.
// decodeWithGrounding advances grounding rows individually before ordinary rows.
// Keep ready intact so the caller can fail the complete cohort on an error.
func (s *batchScheduler) decodeWithGrounding(ready []*batchSlot, active int) error {
ordinary := make([]*batchSlot, 0, len(ready))
for _, slot := range ready {
if d, ok := slot.request.decoder.(*groundingDecoder); ok {
s.drafting.interrupt()
results, err := d.next(slot.request.output.limit - slot.request.output.generated)
s.emit(slot, results, err)
} else {
ordinary = append(ordinary, slot)
}
}
if len(ordinary) == 0 {
s.drafting.reset()
return nil
}
return s.decode(ordinary, active)
}
// decode advances ordinary ready requests, grouping equal-length speculative
// rounds for a shared target forward when multiple requests are active.
// Proposals, sampling and rollback still belong to each request. Plain rows keep
// their pipelined forward; no request waits for a peer to choose the same depth.
func (s *batchScheduler) decode(ready []*batchSlot, active int) error {
+3 -3
View File
@@ -130,10 +130,10 @@ func (s *speculation) open(request request, layout []any) *speculationSession {
}
d := s.drafter.open(layout)
// Logprobs are not yet supported, so a logprobs request keeps a speculationSession
// only to maintain a draft cache in lockstep (permanently parked).
// Logprobs and document requests keep a parked session so draft caches
// remain level with the target without proposing tokens.
opts := request.SamplerOpts
enabled := !opts.Logprobs && opts.TopLogprobs == 0
enabled := !request.JSONDocument && !opts.Logprobs && opts.TopLogprobs == 0
spec := &speculationSession{spec: s, drafter: d, layout: layout, enabled: enabled, depth: s.depth, prevDrafts: -1, roundDrafts: -1}
if enabled {
+347
View File
@@ -0,0 +1,347 @@
package molmo3
import (
"fmt"
"math"
"regexp"
"strconv"
"strings"
)
// GroundingPoint is one resolved (patch, subpatch, location) selection.
type GroundingPoint struct{ Patch, Subpatch, Location int }
// Document is the reference-compatible output document, without live model state.
type Document struct {
Text string `json:"text"`
MultiModal []map[string]any `json:"multi_modal"`
Type string `json:"type"`
}
// DocumentImage describes an original still image and its local patch layout.
type DocumentImage struct {
Width, Height int
TokenPooling []int32
TokenPoolingShape [2]int
Mapping []int32
MappingShape [2]int
NumGlobalTokens int
}
// DocumentMaskScores contains row-major [tokens, subpatches, locations] scores.
type DocumentMaskScores struct {
Values []float32
Shape [3]int
}
// DocumentGrounding holds request-owned selections, never serialized in Document.
type DocumentGrounding struct {
Points []GroundingPoint
MaskAnchors []int
MaskScores []DocumentMaskScores
NoPoint *float64
}
// DocumentDecodeOptions identifies answers cut off before a stop token.
type DocumentDecodeOptions struct{ Truncated bool }
// DecodeDocument resolves still-image point, trace and segmentation tags. It
// preserves generation order and reference element defaults, including extended
// element text. Selection counts and geometry are checked rather than clamped.
func DecodeDocument(answer string, grounding *DocumentGrounding, images []DocumentImage, options DocumentDecodeOptions) (*Document, error) {
droppedPoints, droppedMasks := 0, 0
if options.Truncated {
// Discard only the unfinished tag and the selections attributable to it.
cut := len(answer)
for _, kind := range []string{"points", "trace", "seg"} {
at := strings.LastIndex(answer, `<`+kind+` coords="`)
if at >= 0 && !strings.Contains(answer[at:], `</`+kind+`>`) && !strings.Contains(answer[at:], `"/>`) {
cut = min(cut, at)
}
}
droppedPoints = strings.Count(answer[cut:], "<|POINT_LOC|>")
droppedMasks = strings.Count(answer[cut:], "<|SEG_MASK|>")
answer = answer[:cut]
}
doc := &Document{Text: answer, MultiModal: []map[string]any{}, Type: "text"}
if grounding == nil {
grounding = &DocumentGrounding{}
}
if grounding.NoPoint != nil && (math.IsNaN(*grounding.NoPoint) || *grounding.NoPoint < 0 || *grounding.NoPoint > 1) {
return nil, fmt.Errorf("molmo3: invalid no-point probability")
}
totalTokens, err := validateDocumentImages(images)
if err != nil {
return nil, err
}
pointAt, maskAt, on := 0, 0, 0
checked := 0
var text strings.Builder
for _, tag := range documentTagRE.FindAllStringSubmatchIndex(answer, -1) {
if documentTokenRE.MatchString(answer[checked:tag[0]]) {
return nil, fmt.Errorf("molmo3: orphan grounding token")
}
checked = tag[1]
kind, coords := answer[tag[2]:tag[3]], answer[tag[4]:tag[5]]
pattern := documentPointCoordsRE
if kind == "seg" {
pattern = documentMaskCoordsRE
}
if !pattern.MatchString(coords) {
return nil, fmt.Errorf("molmo3: malformed %s coordinates", kind)
}
label := ""
if tag[6] >= 0 {
label = answer[tag[6]:tag[7]]
}
coordinates := []map[string]any{}
extended := coords
for _, block := range documentPointBlockRE.FindAllString(coords, -1) {
if _, err := strconv.Atoi(strings.TrimSpace(strings.TrimPrefix(block, documentPointBlock))); err != nil {
return nil, fmt.Errorf("molmo3: point label index: %w", err)
}
if pointAt >= len(grounding.Points) {
return nil, fmt.Errorf("molmo3: missing point selection")
}
point := grounding.Points[pointAt]
coordinate, err := documentPointCoordinate(point, images)
if err != nil {
return nil, err
}
coordinates = append(coordinates, coordinate)
replacement := fmt.Sprintf("<|PATCH_%d|><|SUBPATCH_%d|><|LOC_%d|>", point.Patch, point.Subpatch, point.Location)
extended = strings.Replace(extended, block, replacement+strings.TrimPrefix(block, documentPointBlock), 1)
pointAt++
}
element := map[string]any{"coordinates": coordinates, "label": nil, "scale": nil, "clip_points": false, "format_as": nil, "corresponding": "none", "confidence": nil, "fov": nil, "measurable": nil, "ordered": kind == "trace", "type": "points"}
marker := "points"
if kind == "seg" {
var masks []map[string]any
var ids []int
for range strings.Count(coords, documentMaskBlock) {
if maskAt >= len(grounding.MaskScores) || maskAt >= len(grounding.MaskAnchors) {
return nil, fmt.Errorf("molmo3: missing mask selection")
}
anchor := grounding.MaskAnchors[maskAt]
if grounding.MaskScores[maskAt].Shape[0] != totalTokens {
return nil, fmt.Errorf("molmo3: mask score token count does not match images")
}
imageIndex, offset, err := documentImageOfToken(anchor, images)
if err != nil {
return nil, err
}
mask, err := documentDecodeMask(grounding.MaskScores[maskAt], offset, images[imageIndex])
if err != nil {
return nil, err
}
masks = append(masks, documentMaskRLE(mask))
ids = append(ids, imageIndex)
extended = strings.Replace(extended, documentMaskBlock, fmt.Sprintf("<|PATCH_%d|><|MASK|>", anchor), 1)
maskAt++
}
if len(masks) == 0 {
continue
}
element = map[string]any{"masks": masks, "annotation_image_size": nil, "label": nil, "mm_ids": nil, "confidence": nil, "type": "segmentation"}
if len(images) > 1 {
element["mm_ids"] = ids
}
marker = "seg"
} else if len(coordinates) == 0 {
continue
}
extended = strings.ReplaceAll(extended, documentPointPatch, "<|PATCH_32768|>")
if label != "" {
element["label"] = label
}
if kind == "trace" {
element["format_as"] = "trace"
}
if len(doc.MultiModal) == 0 && grounding.NoPoint != nil {
element["confidence"] = 1 - *grounding.NoPoint
}
element["grounding_id"] = len(doc.MultiModal) + 1
element["text"] = strings.Replace(answer[tag[0]:tag[1]], coords, extended, 1)
text.WriteString(answer[on:tag[0]])
fmt.Fprintf(&text, `<%s id="%d">%s</%s>`, marker, len(doc.MultiModal)+1, label, marker)
on = tag[1]
doc.MultiModal = append(doc.MultiModal, element)
}
if documentTokenRE.MatchString(answer[checked:]) {
return nil, fmt.Errorf("molmo3: orphan grounding token")
}
if len(grounding.Points) < pointAt || len(grounding.Points)-pointAt > droppedPoints || len(grounding.MaskAnchors) < maskAt || len(grounding.MaskAnchors)-maskAt > droppedMasks || len(grounding.MaskScores) != len(grounding.MaskAnchors) {
return nil, fmt.Errorf("molmo3: grounding selection counts do not match output")
}
text.WriteString(answer[on:])
doc.Text = text.String()
return doc, nil
}
const documentPointPatch = "<|POINT_PATCH|>"
// documentMaskRLE encodes a nonempty rectangular mask in COCO column-major order.
func documentMaskRLE(mask [][]bool) map[string]any {
h, w := len(mask), len(mask[0])
runs := []int{}
previous, run := false, 0
for x := range w {
for y := range h {
if mask[y][x] != previous {
runs = append(runs, run)
run = 0
previous = mask[y][x]
}
run++
}
}
runs = append(runs, run)
var counts strings.Builder
for i, value := range runs {
if i > 2 {
value -= runs[i-2]
}
for {
c := value & 31
value >>= 5
more := value != 0
if c&16 != 0 {
more = value != -1
}
if more {
c |= 32
}
counts.WriteByte(byte(c + 48))
if !more {
break
}
}
}
return map[string]any{"size": []int{h, w}, "counts": counts.String()}
}
const (
documentPointBlock = documentPointPatch + "<|POINT_SUBPATCH|><|POINT_LOC|>"
documentMaskBlock = documentPointPatch + "<|SEG_MASK|>"
)
var (
documentTagRE = regexp.MustCompile(`(?s)<(points|trace|seg) coords="([^"]+)"(?:/>|>(?:([^<]*)</(?:points?|trace|seg)>)?)`)
documentPointBlockRE = regexp.MustCompile(regexp.QuoteMeta(documentPointBlock) + ` ?[0-9]+`)
documentPointCoordsRE = regexp.MustCompile(`^\s*(?:` + regexp.QuoteMeta(documentPointBlock) + ` ?[0-9]+\s*)*(?:` + regexp.QuoteMeta(documentPointPatch) + `)?\s*$`)
documentMaskCoordsRE = regexp.MustCompile(`^\s*(?:` + regexp.QuoteMeta(documentMaskBlock) + `\s*)*(?:` + regexp.QuoteMeta(documentPointPatch) + `)?\s*$`)
documentTokenRE = regexp.MustCompile(`<\|(?:POINT_PATCH|POINT_SUBPATCH|POINT_LOC|SEG_MASK|CENTER_PATCH|CORRESPONDING_PATCH)\|>`)
)
func validateDocumentImages(images []DocumentImage) (int, error) {
total := 0
for i, image := range images {
ph, pw := image.MappingShape[0], image.MappingShape[1]
nt, ns := image.TokenPoolingShape[0], image.TokenPoolingShape[1]
if image.Width <= 0 || image.Height <= 0 || image.Width > math.MaxInt/image.Height || image.Width > math.MaxInt/32 || image.Height > math.MaxInt/32 {
return 0, fmt.Errorf("molmo3: image %d has invalid dimensions", i)
}
if nt <= 0 || ns != 4 || len(image.TokenPooling)%4 != 0 || len(image.TokenPooling)/4 != nt || nt > math.MaxInt-total {
return 0, fmt.Errorf("molmo3: image %d has invalid token pooling shape", i)
}
if ph <= 0 || pw <= 0 || ph > math.MaxInt/pw || ph*pw != len(image.Mapping) || len(image.Mapping) > math.MaxInt/64 {
return 0, fmt.Errorf("molmo3: image %d has invalid mapping shape", i)
}
if image.NumGlobalTokens < 0 || image.NumGlobalTokens > nt || ((ph+1)/2)*((pw+1)/2) != nt-image.NumGlobalTokens {
return 0, fmt.Errorf("molmo3: image %d has invalid global token geometry", i)
}
seen := make(map[int32]bool, len(image.Mapping))
for _, v := range image.Mapping {
if v < 0 || seen[v] {
return 0, fmt.Errorf("molmo3: image %d has invalid mapping index %d", i, v)
}
seen[v] = true
}
for _, v := range image.TokenPooling {
if v < -1 {
return 0, fmt.Errorf("molmo3: image %d has invalid pooling index %d", i, v)
}
}
total += nt
}
return total, nil
}
func documentPointCoordinate(point GroundingPoint, images []DocumentImage) (map[string]any, error) {
token := point.Patch
for i, image := range images {
if token >= image.TokenPoolingShape[0] {
token -= image.TokenPoolingShape[0]
continue
}
if token < 0 || point.Subpatch < 0 || point.Subpatch >= image.TokenPoolingShape[1] || point.Location < 0 || point.Location >= 16 {
break
}
at := token*image.TokenPoolingShape[1] + point.Subpatch
if at >= len(image.TokenPooling) {
break
}
patch := image.TokenPooling[at]
for j, value := range image.Mapping {
if value != patch {
continue
}
x := (float64(j%image.MappingShape[1]) + (float64(point.Location/4)+0.5)/4) / float64(image.MappingShape[1]) * float64(image.Width)
y := (float64(j/image.MappingShape[1]) + (float64(point.Location%4)+0.5)/4) / float64(image.MappingShape[0]) * float64(image.Height)
return map[string]any{"mm_ix": i, "x": x, "y": y, "x_norm": x / float64(image.Width), "y_norm": y / float64(image.Height)}, nil
}
break
}
return nil, fmt.Errorf("molmo3: invalid point selection %d/%d/%d", point.Patch, point.Subpatch, point.Location)
}
func documentImageOfToken(token int, images []DocumentImage) (int, int, error) {
offset := 0
for i, image := range images {
if token >= offset && token-offset < image.TokenPoolingShape[0] {
return i, offset, nil
}
offset += image.TokenPoolingShape[0]
}
return 0, 0, fmt.Errorf("molmo3: invalid mask anchor %d", token)
}
func documentDecodeMask(scores DocumentMaskScores, offset int, image DocumentImage) ([][]bool, error) {
if scores.Shape[0] <= 0 || scores.Shape[1] != 4 || scores.Shape[2] != 16 || len(scores.Values)/64 != scores.Shape[0] || len(scores.Values)%64 != 0 {
return nil, fmt.Errorf("molmo3: incompatible mask score shape %v", scores.Shape)
}
for _, v := range scores.Values {
if math.IsNaN(float64(v)) || math.IsInf(float64(v), 0) {
return nil, fmt.Errorf("molmo3: non-finite mask score")
}
}
ph, pw := image.MappingShape[0], image.MappingShape[1]
gh, gw := (ph+1)/2, (pw+1)/2
lo := offset + image.NumGlobalTokens
if lo < 0 || gh*gw > scores.Shape[0]-lo {
return nil, fmt.Errorf("molmo3: mask scores do not cover image geometry")
}
srcH, srcW := ph*4, pw*4
raster := make([]float32, srcH*srcW)
for y := range srcH {
for x := range srcW {
token := lo + (y/8)*gw + x/8
subpatch := (y/4%2)*2 + x/4%2
raster[y*srcW+x] = scores.Values[token*64+subpatch*16+(y%4)*4+x%4]
}
}
// Unlike the RGB image resize, the reference mask kernel rounds each
// weighted product before addition. Do not fuse or widen these operations.
blend := func(a, b, w float32) float32 { return float32(float32((1-w)*a) + float32(w*b)) }
xs, ys := bilinearAxis(srcW, image.Width), bilinearAxis(srcH, image.Height)
mask := make([][]bool, image.Height)
for y, ya := range ys {
mask[y] = make([]bool, image.Width)
for x, xa := range xs {
top := blend(raster[ya.lo*srcW+xa.lo], raster[ya.lo*srcW+xa.hi], xa.w1)
bottom := blend(raster[ya.hi*srcW+xa.lo], raster[ya.hi*srcW+xa.hi], xa.w1)
mask[y][x] = blend(top, bottom, ya.w1) > 0.5
}
}
return mask, nil
}
+428
View File
@@ -0,0 +1,428 @@
package molmo3
import (
"encoding/json"
"fmt"
"math"
"reflect"
"strings"
"testing"
)
func assertDocumentJSON(t *testing.T, got *Document, want string) {
t.Helper()
data, err := json.Marshal(got)
if err != nil {
t.Fatal(err)
}
var actual, expected any
if err := json.Unmarshal(data, &actual); err != nil {
t.Fatal(err)
}
if err := json.Unmarshal([]byte(want), &expected); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(actual, expected) {
t.Fatalf("document = %s\nwant %s", data, want)
}
}
func TestDocumentPlainProse(t *testing.T) {
for _, answer := range []string{"", "A café <b>here</b>.\n"} {
doc, err := DecodeDocument(answer, nil, nil, DocumentDecodeOptions{})
if err != nil {
t.Fatal(err)
}
text, _ := json.Marshal(answer)
assertDocumentJSON(t, doc, `{"text":`+string(text)+`,"multi_modal":[],"type":"text"}`)
}
}
const (
testPatch = "<|POINT_PATCH|>"
testBlock = testPatch + "<|POINT_SUBPATCH|><|POINT_LOC|>"
)
func TestDocumentCoordinateWhitespace(t *testing.T) {
for _, mask := range []bool{false, true} {
t.Run(fmt.Sprint(mask), func(t *testing.T) {
im := testDocumentImage()
im.Width, im.Height = 3, 2
g := &DocumentGrounding{Points: []GroundingPoint{{1, 3, 6}, {1, 0, 0}}}
raw := `<points coords=" ` + testBlock + ` 1 ` + testBlock + `2` + testPatch + ` ">dots</points>`
want := `<points coords=" <|PATCH_1|><|SUBPATCH_3|><|LOC_6|> 1 <|PATCH_1|><|SUBPATCH_0|><|LOC_0|>2<|PATCH_32768|> ">dots</points>`
if mask {
g = &DocumentGrounding{MaskAnchors: []int{1}, MaskScores: []DocumentMaskScores{testMaskScores(2, 4)}}
raw = `<seg coords="` + testPatch + `<|SEG_MASK|> ` + testPatch + ` ">blob</seg>`
want = `<seg coords="<|PATCH_1|><|MASK|> <|PATCH_32768|> ">blob</seg>`
}
doc, err := DecodeDocument(raw, g, []DocumentImage{im}, DocumentDecodeOptions{})
if err != nil {
t.Fatal(err)
}
if len(doc.MultiModal) != 1 || doc.MultiModal[0]["text"] != want {
t.Fatalf("extended text = %+v, want %s", doc.MultiModal, want)
}
})
}
}
func TestDocumentTruncated(t *testing.T) {
complete := `<points coords="` + testBlock + `1` + testPatch + `">dot</points>`
for _, tail := range []string{`<points coords="` + testBlock + `1`, `<trace coords="` + testBlock + `1`, `<seg coords="` + testPatch + `<|SEG_MASK|>`} {
t.Run(tail, func(t *testing.T) {
g := &DocumentGrounding{Points: []GroundingPoint{{1, 3, 6}}}
if strings.Contains(tail, "SEG_MASK") {
g.MaskAnchors = []int{1}
g.MaskScores = []DocumentMaskScores{testMaskScores(2, 2)}
} else {
g.Points = append(g.Points, GroundingPoint{1, 0, 0})
}
doc, err := DecodeDocument(complete+" kept "+tail, g, []DocumentImage{testDocumentImage()}, DocumentDecodeOptions{Truncated: true})
if err != nil {
t.Fatal(err)
}
if doc.Text != `<points id="1">dot</points> kept ` || len(doc.MultiModal) != 1 {
t.Fatalf("truncated document = %+v", doc)
}
})
}
doc, err := DecodeDocument(`kept <points coords="`+testBlock+`1`, &DocumentGrounding{Points: []GroundingPoint{{1, 0, 0}}}, []DocumentImage{testDocumentImage()}, DocumentDecodeOptions{Truncated: true})
if err != nil {
t.Fatal(err)
}
assertDocumentJSON(t, doc, `{"text":"kept ","multi_modal":[],"type":"text"}`)
}
func TestDocumentMalformedGrounding(t *testing.T) {
valid := `<points coords="` + testBlock + `1` + testPatch + `">dot</points>`
seg := `<seg coords="` + testPatch + `<|SEG_MASK|>` + testPatch + `">blob</seg>`
for _, tc := range []struct {
name string
change func(*string, **DocumentGrounding, *[]DocumentImage)
}{
{"missing_point", func(_ *string, g **DocumentGrounding, _ *[]DocumentImage) { (*g).Points = nil }},
{"nil_grounding", func(_ *string, g **DocumentGrounding, _ *[]DocumentImage) { *g = nil }},
{"extra_point", func(_ *string, g **DocumentGrounding, _ *[]DocumentImage) {
(*g).Points = append((*g).Points, GroundingPoint{1, 0, 0})
}},
{"no_images", func(_ *string, _ **DocumentGrounding, im *[]DocumentImage) { *im = nil }},
{"orphan_location", func(s *string, _ **DocumentGrounding, _ *[]DocumentImage) { *s = "<|POINT_LOC|>" }},
{"orphan_patch", func(s *string, _ **DocumentGrounding, _ *[]DocumentImage) { *s = testPatch }},
{"orphan_subpatch", func(s *string, _ **DocumentGrounding, _ *[]DocumentImage) { *s = "<|POINT_SUBPATCH|>" }},
{"orphan_mask", func(s *string, _ **DocumentGrounding, _ *[]DocumentImage) { *s = "<|SEG_MASK|>" }},
{"missing_subpatch", func(s *string, _ **DocumentGrounding, _ *[]DocumentImage) {
*s = strings.Replace(*s, "<|POINT_SUBPATCH|>", "", 1)
}},
{"missing_patch", func(s *string, _ **DocumentGrounding, _ *[]DocumentImage) { *s = strings.Replace(*s, testPatch, "", 1) }},
{"missing_id", func(s *string, _ **DocumentGrounding, _ *[]DocumentImage) { *s = strings.Replace(*s, "1", "", 1) }},
{"id_overflow", func(s *string, _ **DocumentGrounding, _ *[]DocumentImage) {
*s = strings.Replace(*s, "1", strings.Repeat("9", 40), 1)
}},
{"double_terminator", func(s *string, _ **DocumentGrounding, _ *[]DocumentImage) {
*s = strings.Replace(*s, `">`, testPatch+`">`, 1)
}},
{"extra_mask_anchor", func(_ *string, g **DocumentGrounding, _ *[]DocumentImage) { (*g).MaskAnchors = []int{1} }},
{"negative_patch", func(_ *string, g **DocumentGrounding, _ *[]DocumentImage) { (*g).Points[0].Patch = -1 }},
{"patch_out_of_range", func(_ *string, g **DocumentGrounding, _ *[]DocumentImage) { (*g).Points[0].Patch = 2 }},
{"low_resolution_point", func(_ *string, g **DocumentGrounding, _ *[]DocumentImage) { (*g).Points[0].Patch = 0 }},
{"negative_subpatch", func(_ *string, g **DocumentGrounding, _ *[]DocumentImage) { (*g).Points[0].Subpatch = -1 }},
{"subpatch_out_of_range", func(_ *string, g **DocumentGrounding, _ *[]DocumentImage) { (*g).Points[0].Subpatch = 4 }},
{"negative_location", func(_ *string, g **DocumentGrounding, _ *[]DocumentImage) { (*g).Points[0].Location = -1 }},
{"location_out_of_range", func(_ *string, g **DocumentGrounding, _ *[]DocumentImage) { (*g).Points[0].Location = 16 }},
{"padded_subpatch", func(_ *string, _ **DocumentGrounding, im *[]DocumentImage) { (*im)[0].TokenPooling[7] = -1 }},
{"pool_shape", func(_ *string, _ **DocumentGrounding, im *[]DocumentImage) { (*im)[0].TokenPoolingShape = [2]int{2, 3} }},
{"pool_overflow", func(_ *string, _ **DocumentGrounding, im *[]DocumentImage) {
(*im)[0].TokenPoolingShape = [2]int{math.MaxInt, 4}
}},
{"mapping_shape", func(_ *string, _ **DocumentGrounding, im *[]DocumentImage) { (*im)[0].MappingShape = [2]int{1, 2} }},
{"mapping_overflow", func(_ *string, _ **DocumentGrounding, im *[]DocumentImage) {
(*im)[0].MappingShape = [2]int{math.MaxInt, 2}
}},
{"negative_mapping", func(_ *string, _ **DocumentGrounding, im *[]DocumentImage) { (*im)[0].Mapping[0] = -1 }},
{"duplicate_mapping", func(_ *string, _ **DocumentGrounding, im *[]DocumentImage) { (*im)[0].Mapping[0] = 757 }},
{"negative_pool_value", func(_ *string, _ **DocumentGrounding, im *[]DocumentImage) { (*im)[0].TokenPooling[0] = -2 }},
{"negative_global", func(_ *string, _ **DocumentGrounding, im *[]DocumentImage) { (*im)[0].NumGlobalTokens = -1 }},
{"global_geometry", func(_ *string, _ **DocumentGrounding, im *[]DocumentImage) { (*im)[0].NumGlobalTokens = 2 }},
{"zero_width", func(_ *string, _ **DocumentGrounding, im *[]DocumentImage) { (*im)[0].Width = 0 }},
{"size_overflow", func(_ *string, _ **DocumentGrounding, im *[]DocumentImage) { (*im)[0].Width = math.MaxInt }},
{"confidence_nan", func(_ *string, g **DocumentGrounding, _ *[]DocumentImage) { p := math.NaN(); (*g).NoPoint = &p }},
{"confidence_range", func(_ *string, g **DocumentGrounding, _ *[]DocumentImage) { p := 1.1; (*g).NoPoint = &p }},
{"mask_missing_anchor", func(s *string, g **DocumentGrounding, _ *[]DocumentImage) {
*s = seg
*g = &DocumentGrounding{MaskScores: []DocumentMaskScores{testMaskScores(2, 2)}}
}},
{"mask_missing_scores", func(s *string, g **DocumentGrounding, _ *[]DocumentImage) {
*s = seg
*g = &DocumentGrounding{MaskAnchors: []int{1}}
}},
{"mask_orphan_patch", func(s *string, g **DocumentGrounding, _ *[]DocumentImage) {
*s = strings.Replace(seg, testPatch, "", 1)
*g = &DocumentGrounding{MaskAnchors: []int{1}, MaskScores: []DocumentMaskScores{testMaskScores(2, 2)}}
}},
} {
t.Run(tc.name, func(t *testing.T) {
s := valid
g := &DocumentGrounding{Points: []GroundingPoint{{1, 3, 6}}}
images := []DocumentImage{testDocumentImage()}
tc.change(&s, &g, &images)
doc, err := DecodeDocument(s, g, images, DocumentDecodeOptions{})
if err == nil || doc != nil {
t.Fatalf("malformed input accepted: doc=%+v err=%v", doc, err)
}
})
}
}
func TestDocumentMalformedMask(t *testing.T) {
for _, tc := range []struct {
name string
change func(*DocumentGrounding)
}{
{"negative_anchor", func(g *DocumentGrounding) { g.MaskAnchors[0] = -1 }},
{"anchor_out_of_range", func(g *DocumentGrounding) { g.MaskAnchors[0] = 2 }},
{"extra_scores", func(g *DocumentGrounding) { g.MaskScores = append(g.MaskScores, testMaskScores(2, 2)) }},
{"extra_anchors", func(g *DocumentGrounding) { g.MaskAnchors = append(g.MaskAnchors, 1) }},
{"score_shape", func(g *DocumentGrounding) { g.MaskScores[0].Shape = [3]int{2, 4, 15} }},
{"score_overflow", func(g *DocumentGrounding) { g.MaskScores[0].Shape = [3]int{math.MaxInt, 4, 16} }},
{"score_length", func(g *DocumentGrounding) { g.MaskScores[0].Values = g.MaskScores[0].Values[:127] }},
{"missing_image_rows", func(g *DocumentGrounding) { g.MaskScores[0] = testMaskScores(1, 2) }},
{"extra_image_rows", func(g *DocumentGrounding) { g.MaskScores[0] = testMaskScores(3, 2) }},
{"score_nan", func(g *DocumentGrounding) { g.MaskScores[0].Values[70] = float32(math.NaN()) }},
{"score_infinite", func(g *DocumentGrounding) { g.MaskScores[0].Values[70] = float32(math.Inf(1)) }},
} {
t.Run(tc.name, func(t *testing.T) {
g := &DocumentGrounding{MaskAnchors: []int{1}, MaskScores: []DocumentMaskScores{testMaskScores(2, 2)}}
tc.change(g)
doc, err := DecodeDocument(`<seg coords="`+testPatch+`<|SEG_MASK|>`+testPatch+`">blob</seg>`, g, []DocumentImage{testDocumentImage()}, DocumentDecodeOptions{})
if err == nil || doc != nil {
t.Fatalf("malformed mask accepted: %+v, %v", doc, err)
}
})
}
}
func testMaskScores(tokens, highSubpatches int) DocumentMaskScores {
s := DocumentMaskScores{Shape: [3]int{tokens, 4, 16}, Values: make([]float32, tokens*64)}
for i := range s.Values {
s.Values[i] = 0.1
if i/16%4 < highSubpatches {
s.Values[i] = 0.9
}
}
return s
}
func TestDocumentMixedFirstConfidence(t *testing.T) {
im := testDocumentImage()
im.Width, im.Height = 3, 2
p := 0.125
g := &DocumentGrounding{Points: []GroundingPoint{{1, 3, 6}}, MaskAnchors: []int{1}, MaskScores: []DocumentMaskScores{testMaskScores(2, 4)}, NoPoint: &p}
raw := `<points coords="` + testPatch + `">none</points> <seg coords="` + testPatch + `<|SEG_MASK|>` + testPatch + `">blob</seg> <points coords="` + testBlock + `1` + testPatch + `">dot</points>`
doc, err := DecodeDocument(raw, g, []DocumentImage{im}, DocumentDecodeOptions{})
if err != nil {
t.Fatal(err)
}
assertDocumentJSON(t, doc, `{"text":"<points coords=\"<|POINT_PATCH|>\">none</points> <seg id=\"1\">blob</seg> <points id=\"2\">dot</points>","type":"text","multi_modal":[{"masks":[{"size":[2,3],"counts":"06"}],"annotation_image_size":null,"label":"blob","mm_ids":null,"confidence":0.875,"type":"segmentation","grounding_id":1,"text":"<seg coords=\"<|PATCH_1|><|MASK|><|PATCH_32768|>\">blob</seg>"},{"coordinates":[{"mm_ix":0,"x":2.0625,"y":1.625,"x_norm":0.6875,"y_norm":0.8125}],"label":"dot","scale":null,"clip_points":false,"format_as":null,"corresponding":"none","confidence":null,"fov":null,"measurable":null,"ordered":false,"type":"points","grounding_id":2,"text":"<points coords=\"<|PATCH_1|><|SUBPATCH_3|><|LOC_6|>1<|PATCH_32768|>\">dot</points>"}]}`)
}
func TestDocumentMaskOddOffset(t *testing.T) {
first := testDocumentImage()
first.Width, first.Height = 3, 2
// Nonidentity raster IDs, odd right/bottom padding, nonzero image and global offsets.
im := DocumentImage{Width: 7, Height: 5, MappingShape: [2]int{3, 5}, TokenPoolingShape: [2]int{7, 4}, NumGlobalTokens: 1}
for i := range 15 {
im.Mapping = append(im.Mapping, int32(900+i*7%15))
}
im.TokenPooling = []int32{0, 1, 27, 28, 900, 907, 905, 912, 914, 906, 904, 911, 913, -1, 903, -1, 910, 902, -1, -1, 909, 901, -1, -1, 908, -1, -1, -1}
s := DocumentMaskScores{Shape: [3]int{9, 4, 16}, Values: make([]float32, 9*64)}
for i := range s.Values {
s.Values[i] = float32(float64((i*37+11)%101) / 100)
}
doc, err := DecodeDocument(`<seg coords="`+testPatch+`<|SEG_MASK|>`+testPatch+`">odd</seg>`, &DocumentGrounding{MaskAnchors: []int{3}, MaskScores: []DocumentMaskScores{s}}, []DocumentImage{first, im}, DocumentDecodeOptions{})
if err != nil {
t.Fatal(err)
}
assertDocumentJSON(t, doc, `{"text":"<seg id=\"1\">odd</seg>","type":"text","multi_modal":[{"masks":[{"size":[5,7],"counts":"541N0O22ON0030N"}],"annotation_image_size":null,"label":"odd","mm_ids":[1],"confidence":null,"type":"segmentation","grounding_id":1,"text":"<seg coords=\"<|PATCH_3|><|MASK|><|PATCH_32768|>\">odd</seg>"}]}`)
}
func TestDocumentSegmentation(t *testing.T) {
for _, tc := range []struct {
name string
anchors []int
sizes [][2]int
rle, ids, extended string
}{
{"one", []int{1}, [][2]int{{3, 2}}, `[{"size":[2,3],"counts":"0110000"}]`, "null", `<|PATCH_1|><|MASK|><|PATCH_32768|>`},
{"multiple", []int{1, 1}, [][2]int{{3, 2}}, `[{"size":[2,3],"counts":"0110000"},{"size":[2,3],"counts":"015"}]`, "null", `<|PATCH_1|><|MASK|><|PATCH_1|><|MASK|><|PATCH_32768|>`},
{"multi_image", []int{3, 1}, [][2]int{{3, 2}, {4, 3}}, `[{"size":[3,4],"counts":"012000000"},{"size":[2,3],"counts":"015"}]`, `[1,0]`, `<|PATCH_3|><|MASK|><|PATCH_1|><|MASK|><|PATCH_32768|>`},
} {
t.Run(tc.name, func(t *testing.T) {
var images []DocumentImage
for _, size := range tc.sizes {
im := testDocumentImage()
im.Width, im.Height = size[0], size[1]
images = append(images, im)
}
p := 0.25
g := &DocumentGrounding{MaskAnchors: tc.anchors, NoPoint: &p}
for i := range tc.anchors {
g.MaskScores = append(g.MaskScores, testMaskScores(len(images)*2, 2-i))
}
raw := `<seg coords="` + strings.Repeat(testPatch+"<|SEG_MASK|>", len(tc.anchors)) + testPatch + `">blob</seg>`
doc, err := DecodeDocument(raw, g, images, DocumentDecodeOptions{})
if err != nil {
t.Fatal(err)
}
extended, _ := json.Marshal(`<seg coords="` + tc.extended + `">blob</seg>`)
assertDocumentJSON(t, doc, fmt.Sprintf(`{"text":"<seg id=\"1\">blob</seg>","type":"text","multi_modal":[{"masks":%s,"annotation_image_size":null,"label":"blob","mm_ids":%s,"confidence":0.75,"type":"segmentation","grounding_id":1,"text":%s}]}`, tc.rle, tc.ids, extended))
})
}
}
func TestDocumentMaskFloat32Boundary(t *testing.T) {
im := DocumentImage{Width: 3, Height: 1, TokenPooling: []int32{729, 730, -1, -1}, TokenPoolingShape: [2]int{1, 4}, Mapping: []int32{729, 730}, MappingShape: [2]int{1, 2}}
s := testMaskScores(1, 4)
for _, y := range []int{1, 2} {
s.Values[y*4+3] = 0.2
s.Values[16+y*4] = 0.8
}
doc, err := DecodeDocument(`<seg coords="`+testPatch+`<|SEG_MASK|>`+testPatch+`">edge</seg>`, &DocumentGrounding{MaskAnchors: []int{0}, MaskScores: []DocumentMaskScores{s}}, []DocumentImage{im}, DocumentDecodeOptions{})
if err != nil {
t.Fatal(err)
}
assertDocumentJSON(t, doc, `{"text":"<seg id=\"1\">edge</seg>","type":"text","multi_modal":[{"masks":[{"size":[1,3],"counts":"0110"}],"annotation_image_size":null,"label":"edge","mm_ids":null,"confidence":null,"type":"segmentation","grounding_id":1,"text":"<seg coords=\"<|PATCH_0|><|MASK|><|PATCH_32768|>\">edge</seg>"}]}`)
}
func TestDocumentRLE(t *testing.T) {
for _, tc := range []struct {
h, w int
empty, full, checker string
}{
{1, 1, "1", "01", "01"}, {3, 5, "?", "0?", "0110000000000000"}, {4, 7, "l0", "0l0", "011010O10O10O10O10O10O0"},
} {
for mode, want := range []string{tc.empty, tc.full, tc.checker} {
t.Run(fmt.Sprintf("%dx%d/%d", tc.h, tc.w, mode), func(t *testing.T) {
mask := make([][]bool, tc.h)
for y := range mask {
mask[y] = make([]bool, tc.w)
for x := range mask[y] {
mask[y][x] = mode == 1 || mode == 2 && (x+y)%2 == 0
}
}
rle := documentMaskRLE(mask)
if rle["counts"] != want || !reflect.DeepEqual(rle["size"], []int{tc.h, tc.w}) {
t.Fatalf("RLE = %v, want %q", rle, want)
}
if got := decodeTestRLE(t, want, tc.h, tc.w); !reflect.DeepEqual(got, mask) {
t.Fatalf("decoded RLE = %v, want %v", got, mask)
}
})
}
}
}
// Independent COCO signed/delta varint decoder used only to check output pixels.
func decodeTestRLE(t *testing.T, s string, h, w int) [][]bool {
t.Helper()
var runs []int
for at := 0; at < len(s); {
value, shift := 0, uint(0)
for {
if at >= len(s) {
t.Fatal("incomplete RLE")
}
c := int(s[at]) - 48
at++
value |= (c & 31) << shift
shift += 5
if c&32 == 0 {
if c&16 != 0 {
value |= -1 << shift
}
break
}
}
if len(runs) > 2 {
value += runs[len(runs)-2]
}
runs = append(runs, value)
}
mask := make([][]bool, h)
for y := range mask {
mask[y] = make([]bool, w)
}
pos := 0
for i, n := range runs {
if n < 0 || n > h*w-pos {
t.Fatal("invalid RLE run")
}
for range n {
mask[pos%h][pos/h] = i%2 == 1
pos++
}
}
if pos != h*w {
t.Fatal("incomplete RLE mask")
}
return mask
}
// Synthetic CPU codec inputs, captured independently with molmo3-hf
// bf3b580d0f694d3851553f3974f54bbe349ce2f8; these are not model outputs.
func testDocumentImage() DocumentImage {
return DocumentImage{Width: 80, Height: 40, TokenPooling: []int32{0, 1, 27, 28, 729, 730, 756, 757}, TokenPoolingShape: [2]int{2, 4}, Mapping: []int32{729, 730, 756, 757}, MappingShape: [2]int{2, 2}, NumGlobalTokens: 1}
}
func TestDocumentNoPoint(t *testing.T) {
answer := `<points coords="` + testPatch + `">none</points>`
p := 1.0
doc, err := DecodeDocument(answer, &DocumentGrounding{NoPoint: &p}, []DocumentImage{testDocumentImage()}, DocumentDecodeOptions{})
if err != nil {
t.Fatal(err)
}
text, _ := json.Marshal(answer)
assertDocumentJSON(t, doc, `{"text":`+string(text)+`,"multi_modal":[],"type":"text"}`)
}
func TestDocumentPoints(t *testing.T) {
for _, tc := range []struct {
name, kind, label, coords string
points []GroundingPoint
images []DocumentImage
wantCoords, extended, confidence, format string
ordered bool
}{
{"single", "points", "dot", testBlock + "1" + testPatch, []GroundingPoint{{1, 3, 6}}, []DocumentImage{testDocumentImage()}, `[{"mm_ix":0,"x":55,"y":32.5,"x_norm":0.6875,"y_norm":0.8125}]`, `<|PATCH_1|><|SUBPATCH_3|><|LOC_6|>1<|PATCH_32768|>`, "0.875", "null", false},
{"multiple", "points", "dots", testBlock + "1" + testBlock + "2" + testPatch, []GroundingPoint{{1, 3, 6}, {1, 0, 0}}, []DocumentImage{testDocumentImage()}, `[{"mm_ix":0,"x":55,"y":32.5,"x_norm":0.6875,"y_norm":0.8125},{"mm_ix":0,"x":5,"y":2.5,"x_norm":0.0625,"y_norm":0.0625}]`, `<|PATCH_1|><|SUBPATCH_3|><|LOC_6|>1<|PATCH_1|><|SUBPATCH_0|><|LOC_0|>2<|PATCH_32768|>`, "null", "null", false},
{"trace", "trace", "route", testBlock + "1" + testBlock + "2" + testPatch, []GroundingPoint{{1, 3, 6}, {1, 0, 0}}, []DocumentImage{testDocumentImage()}, `[{"mm_ix":0,"x":55,"y":32.5,"x_norm":0.6875,"y_norm":0.8125},{"mm_ix":0,"x":5,"y":2.5,"x_norm":0.0625,"y_norm":0.0625}]`, `<|PATCH_1|><|SUBPATCH_3|><|LOC_6|>1<|PATCH_1|><|SUBPATCH_0|><|LOC_0|>2<|PATCH_32768|>`, "null", `"trace"`, true},
{"two_images", "points", "dots", testBlock + "1" + testBlock + "2" + testPatch, []GroundingPoint{{3, 3, 6}, {1, 0, 0}}, []DocumentImage{testDocumentImage(), testDocumentImage()}, `[{"mm_ix":1,"x":110,"y":65,"x_norm":0.6875,"y_norm":0.8125},{"mm_ix":0,"x":5,"y":2.5,"x_norm":0.0625,"y_norm":0.0625}]`, `<|PATCH_3|><|SUBPATCH_3|><|LOC_6|>1<|PATCH_1|><|SUBPATCH_0|><|LOC_0|>2<|PATCH_32768|>`, "null", "null", false},
{"defaults", "points", "", testBlock + "1" + testPatch, []GroundingPoint{{1, 3, 6}}, []DocumentImage{testDocumentImage()}, `[{"mm_ix":0,"x":55,"y":32.5,"x_norm":0.6875,"y_norm":0.8125}]`, `<|PATCH_1|><|SUBPATCH_3|><|LOC_6|>1<|PATCH_32768|>`, "null", "null", false},
} {
t.Run(tc.name, func(t *testing.T) {
if len(tc.images) > 1 {
tc.images[1].Width, tc.images[1].Height = 160, 80
}
raw := fmt.Sprintf(`<%s coords="%s">%s</%s>`, tc.kind, tc.coords, tc.label, tc.kind)
extended := strings.Replace(raw, tc.coords, tc.extended, 1)
labelJSON, _ := json.Marshal(tc.label)
if tc.label == "" {
raw = fmt.Sprintf(`<%s coords="%s"/>`, tc.kind, tc.coords)
extended = strings.Replace(raw, tc.coords, tc.extended, 1)
labelJSON = []byte("null")
}
grounding := &DocumentGrounding{Points: tc.points}
if tc.confidence != "null" {
p := 0.125
grounding.NoPoint = &p
}
doc, err := DecodeDocument(raw, grounding, tc.images, DocumentDecodeOptions{})
if err != nil {
t.Fatal(err)
}
textJSON, _ := json.Marshal(`<points id="1">` + tc.label + `</points>`)
extJSON, _ := json.Marshal(extended)
assertDocumentJSON(t, doc, fmt.Sprintf(`{"text":%s,"type":"text","multi_modal":[{"coordinates":%s,"label":%s,"scale":null,"clip_points":false,"format_as":%s,"corresponding":"none","confidence":%s,"fov":null,"measurable":null,"ordered":%t,"type":"points","grounding_id":1,"text":%s}]}`, textJSON, tc.wantCoords, labelJSON, tc.format, tc.confidence, tc.ordered, extJSON))
})
}
}
+14 -6
View File
@@ -20,12 +20,15 @@ const DefaultMaxCrops = 8
// 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]
OriginalWidth, OriginalHeight int
Mapping []int32 // high-resolution raster to crop patch index
MappingShape [2]int // [patch rows, patch columns]
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
@@ -189,6 +192,8 @@ const (
)
type molmo3ImageLayout struct {
mapping []int32
mappingShape [2]int
tiling [2]int
resizedHW [2]int
window int
@@ -264,6 +269,7 @@ func makeMolmo3ImageLayout(height, width, maxCrops int) molmo3ImageLayout {
gridH := (mappingH + molmo3ImagePool - 1) / molmo3ImagePool
gridW := (mappingW + molmo3ImagePool - 1) / molmo3ImagePool
return molmo3ImageLayout{
mapping: mapping, mappingShape: [2]int{mappingH, mappingW},
tiling: tiling, resizedHW: [2]int{resizedH, resizedW}, window: window,
tokenPooling: tokenPooling, patchPosIDs: positions,
numGlobalTokens: nGlobal * nGlobal, grid: [4]int{nGlobal, nGlobal, gridH, gridW},
@@ -444,6 +450,8 @@ func ProcessImage(src image.Image, maxCrops int) (*ImageProcessorResult, error)
}
cropCount := len(crops)
return &ImageProcessorResult{
OriginalWidth: rgb.width, OriginalHeight: rgb.height,
Mapping: layout.mapping, MappingShape: layout.mappingShape,
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},
+23
View File
@@ -13,6 +13,29 @@ import (
const transparentGIFHex = "47494638396101000100810000d2214d00000000000000000021f90401000000002c000000000100010000080400010404003b"
func TestProcessImageDocumentMetadata(t *testing.T) {
var images []DocumentImage
for _, size := range [][2]int{{500, 300}, {640, 480}} {
p, err := ProcessImage(image.NewNRGBA(image.Rect(7, 11, 7+size[0], 11+size[1])), 8)
if err != nil {
t.Fatal(err)
}
if p.OriginalWidth != size[0] || p.OriginalHeight != size[1] {
t.Fatalf("original dimensions = %dx%d, want %v", p.OriginalWidth, p.OriginalHeight, size)
}
if len(p.Mapping) != p.MappingShape[0]*p.MappingShape[1] || len(p.Mapping) == 0 {
t.Fatalf("mapping shape = %v, length %d", p.MappingShape, len(p.Mapping))
}
images = append(images, DocumentImage{Width: p.OriginalWidth, Height: p.OriginalHeight, TokenPooling: p.TokenPooling, TokenPoolingShape: p.TokenPoolingShape, Mapping: p.Mapping, MappingShape: p.MappingShape, NumGlobalTokens: p.NumGlobalTokens})
}
// Independently captured HF selections and coordinates with max_crops=8.
doc, err := DecodeDocument(`<points coords="`+testBlock+`1`+testBlock+`2`+testPatch+`">dots</points>`, &DocumentGrounding{Points: []GroundingPoint{{306, 2, 12}, {968, 3, 11}}}, images, DocumentDecodeOptions{})
if err != nil {
t.Fatal(err)
}
assertDocumentJSON(t, doc, `{"text":"<points id=\"1\">dots</points>","type":"text","multi_modal":[{"coordinates":[{"mm_ix":0,"x":400.8152173913043,"y":101.38888888888889,"x_norm":0.8016304347826086,"y_norm":0.33796296296296297},{"mm_ix":1,"x":50.434782608695656,"y":249.13043478260872,"x_norm":0.07880434782608696,"y_norm":0.5190217391304348}],"label":"dots","scale":null,"clip_points":false,"format_as":null,"corresponding":"none","confidence":null,"fov":null,"measurable":null,"ordered":false,"type":"points","grounding_id":1,"text":"<points coords=\"<|PATCH_306|><|SUBPATCH_2|><|LOC_12|>1<|PATCH_968|><|SUBPATCH_3|><|LOC_11|>2<|PATCH_32768|>\">dots</points>"}]}`)
}
func transparentGIF(t *testing.T, localPalette bool) []byte {
t.Helper()
data, err := hex.DecodeString(transparentGIFHex)
+20
View File
@@ -23,6 +23,26 @@ func (r *Molmo3Renderer) Render(messages []api.Message, tools []api.Tool, think
return message.Role == "system"
})
// Treat adjacent user fragments as one turn before validating roles.
merged := make([]api.Message, 0, len(messages))
for i := 0; i < len(messages); {
message := messages[i]
i++
if message.Role == "user" && len(message.ToolCalls) == 0 {
var content strings.Builder
content.WriteString(message.Content)
message.Images = slices.Clone(message.Images)
for i < len(messages) && messages[i].Role == "user" && len(messages[i].ToolCalls) == 0 {
content.WriteString(messages[i].Content)
message.Images = append(message.Images, messages[i].Images...)
i++
}
message.Content = content.String()
}
merged = append(merged, message)
}
messages = merged
totalImages := 0
for _, message := range messages {
totalImages += len(message.Images)
+126
View File
@@ -0,0 +1,126 @@
package renderers
import (
"reflect"
"slices"
"strconv"
"strings"
"testing"
"github.com/ollama/ollama/api"
)
func TestMolmo3RendererUserFragments(t *testing.T) {
toolCall := api.ToolCall{Function: api.ToolCallFunction{Name: "noop"}}
for _, tc := range []struct {
name string
messages []api.Message
want string
wantErr string
}{
{
name: "text image text",
messages: []api.Message{
{Role: "user", Content: "Describe "},
{Role: "user", Images: []api.ImageData{api.ImageData("image-a")}},
{Role: "user", Content: "this image."},
},
want: "<|im_start|>user\n[img-0]Describe this image.<|im_end|>\n<|im_start|>assistant\n",
},
{
name: "images across fragments and turns",
messages: []api.Message{
{Role: "user", Content: "Compare ", Images: []api.ImageData{api.ImageData("image-a")}},
{Role: "user", Content: "these.", Images: []api.ImageData{api.ImageData("image-b")}},
{Role: "assistant", Content: "Different."},
{Role: "user", Content: "And "},
{Role: "system", Content: "<|video|>", Images: []api.ImageData{api.ImageData("ignored")}, ToolCalls: []api.ToolCall{toolCall}},
{Role: "user", Content: "this?", Images: []api.ImageData{api.ImageData("image-c")}},
{Role: "assistant", Content: "This is"},
},
want: "<|im_start|>user\nImage 1[img-0]Image 2[img-1]Compare these.<|im_end|>\n<|im_start|>assistant\nDifferent.<|im_end|>\n<|im_start|>user\nImage 3[img-2]And this?<|im_end|>\n<|im_start|>assistant\nThis is",
},
{
name: "empty fragments preserve whitespace",
messages: []api.Message{
{Role: "user"},
{Role: "user", Content: " a\n"},
{Role: "user"},
{Role: "user", Content: "b "},
},
want: "<|im_start|>user\n a\nb <|im_end|>\n<|im_start|>assistant\n",
},
{
name: "tool calls in later fragment",
messages: []api.Message{
{Role: "user", Content: "Hi"},
{Role: "user", ToolCalls: []api.ToolCall{toolCall}},
},
wantErr: "tools are not supported",
},
{
name: "tool calls in first fragment",
messages: []api.Message{
{Role: "user", ToolCalls: []api.ToolCall{toolCall}},
{Role: "user", Content: "Hi"},
},
wantErr: "tools are not supported",
},
{
name: "video in later fragment",
messages: []api.Message{
{Role: "user", Content: "Describe "},
{Role: "user", Content: "<|video|>"},
},
wantErr: "video is not supported",
},
{
name: "consecutive assistants remain invalid",
messages: []api.Message{
{Role: "user", Content: "Hi"},
{Role: "user", Content: "!"},
{Role: "assistant", Content: "Hello"},
{Role: "assistant", Content: "again"},
},
wantErr: "roles must alternate user/assistant",
},
} {
for _, renderer := range []Molmo3Renderer{{}, {useImgTags: true}} {
t.Run(tc.name+"/tags="+strconv.FormatBool(renderer.useImgTags), func(t *testing.T) {
got, err := renderer.Render(tc.messages, nil, nil)
if tc.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tc.wantErr) || got != "" {
t.Fatalf("Render = %q, %v; want empty prompt and %q", got, err, tc.wantErr)
}
return
}
want := tc.want
if !renderer.useImgTags {
want = strings.NewReplacer("[img-0]", "<|image|>", "[img-1]", "<|image|>", "[img-2]", "<|image|>").Replace(want)
}
if err != nil || got != want {
t.Fatalf("Render = %q, %v; want %q", got, err, want)
}
})
}
}
}
func TestMolmo3RendererUserFragmentsDoNotMutateInputs(t *testing.T) {
images := []api.ImageData{api.ImageData("first"), api.ImageData("sentinel")}
messages := []api.Message{
{Role: "system", Content: "ignored"},
{Role: "user", Content: "Describe ", Images: images[:1]},
{Role: "user", Content: "these.", Images: []api.ImageData{api.ImageData("second")}},
}
originalMessages := slices.Clone(messages)
originalImages := slices.Clone(images)
for range 2 {
if _, err := (&Molmo3Renderer{}).Render(messages, nil, nil); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(messages, originalMessages) || !reflect.DeepEqual(images, originalImages) {
t.Fatal("Render mutated the input messages or image backing array")
}
}
}
+7
View File
@@ -85,6 +85,13 @@ func TestMolmo3RendererMatchesPublisher(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if tc.referenceError != "" {
// User-fragment coalescing is a serving policy, not reference behavior.
if got != tc.want {
t.Fatalf("normalized prompt = %q, want %q", got, tc.want)
}
return
}
if got != reference.Prompt {
t.Fatalf("renderer differs from publisher\n got: %q\nwant: %q", got, reference.Prompt)
}
+1 -1
View File
@@ -113,7 +113,7 @@ func molmo3TestCases() []molmo3TestCase {
{Role: "user", Content: "One"},
{Role: "user", Content: "Two"},
},
wantErr: "roles must alternate user/assistant",
want: "<|im_start|>user\nOneTwo<|im_end|>\n<|im_start|>assistant\n",
referenceError: "roles must alternate user/assistant",
},
{
+7
View File
@@ -3257,6 +3257,12 @@ func (s *Server) ChatHandler(c *gin.Context) {
}
}
jsonDocument := m.IsMLX() && m.Config.Renderer == "molmo3" && string(req.Format) == `"json"`
if jsonDocument && req.Logprobs {
c.JSON(http.StatusBadRequest, gin.H{"error": "logprobs are not supported with grounding JSON output"})
return
}
caps := []model.Capability{model.CapabilityCompletion}
if len(req.Tools) > 0 {
caps = append(caps, model.CapabilityTools)
@@ -3401,6 +3407,7 @@ func (s *Server) ChatHandler(c *gin.Context) {
Prompt: prompt,
Media: media,
Format: req.Format,
JSONDocument: jsonDocument,
Options: opts,
Shift: req.Shift == nil || *req.Shift,
Truncate: truncate,
+195
View File
@@ -0,0 +1,195 @@
package server
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/llm"
"github.com/ollama/ollama/manifest"
"github.com/ollama/ollama/middleware"
"github.com/ollama/ollama/openai"
"github.com/ollama/ollama/types/model"
)
func TestChatGroundingJSON(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, tt := range []struct {
name string
family string
renderer string
format string
stream bool
logprobs bool
topLogprobs int
gguf bool
generate bool
jsonObject bool
want bool
wantStatus int
}{
{name: "document", family: "molmo3", format: `"json"`, want: true},
{name: "packaged model without family", renderer: "molmo3", format: `"json"`, want: true},
{name: "document ignores unused top logprobs", family: "molmo3", format: `"json"`, topLogprobs: 5, want: true},
{name: "non MLX", family: "molmo3", format: `"json"`, gguf: true},
{name: "streaming document", family: "molmo3", format: `"json"`, stream: true, want: true},
{name: "json_object mapping", family: "molmo3", jsonObject: true, want: true},
{name: "plain", family: "molmo3"},
{name: "schema", family: "molmo3", format: `{"type":"object"}`},
{name: "other model", family: "qwen3", format: `"json"`},
{name: "generate", family: "molmo3", format: `"json"`, generate: true},
{name: "reject document logprobs", family: "molmo3", format: `"json"`, logprobs: true, wantStatus: http.StatusBadRequest},
{name: "plain logprobs", family: "molmo3", logprobs: true},
{name: "schema logprobs", family: "molmo3", format: `{"type":"object"}`, logprobs: true},
} {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("OLLAMA_MODELS", t.TempDir())
const name = "grounding-test"
renderer := "molmo3"
if tt.family != "molmo3" {
renderer = "qwen3-coder"
}
if tt.renderer != "" {
renderer = tt.renderer
}
runner, format := manifest.RunnerMLX, manifest.FormatSafetensors
if tt.gguf {
runner, format = manifest.RunnerLlamaCPP, manifest.FormatGGUF
}
writeShowManifestVariant(t, name, runner, format, model.ConfigV2{
ModelFormat: format, ModelFamily: tt.family, Renderer: renderer,
Capabilities: []string{"completion"},
}, map[string]any{"general.architecture": "llama"})
// This fixture checks transport, not model inference or decoding.
const document = `{"text":"猫 <&>","multi_modal":[],"type":"text"}`
requests := make(chan llm.CompletionRequest, 1)
mock := &mockRunner{CompletionFn: func(_ context.Context, req llm.CompletionRequest, fn func(llm.CompletionResponse)) error {
requests <- req
split := strings.Index(document, `,"multi_modal"`)
fn(llm.CompletionResponse{Content: document[:split]})
fn(llm.CompletionResponse{Content: document[split:], Done: true, DoneReason: llm.DoneReasonStop})
return nil
}}
s := newServerWithMockRunner(t, mock)
req := api.ChatRequest{
Model: name, Messages: []api.Message{{Role: "user", Content: "Say hello."}},
Format: json.RawMessage(tt.format), Stream: &tt.stream, Logprobs: tt.logprobs, TopLogprobs: tt.topLogprobs,
}
if tt.jsonObject {
mapped, err := openai.FromChatRequest(openai.ChatCompletionRequest{
ResponseFormat: &openai.ResponseFormat{Type: "json_object"},
})
if err != nil {
t.Fatal(err)
}
req.Format = mapped.Format
}
var w *httptest.ResponseRecorder
if tt.generate {
w = createRequest(t, s.GenerateHandler, api.GenerateRequest{
Model: name, Prompt: "Say hello.", Format: req.Format, Stream: &tt.stream,
})
} else {
w = createRequest(t, s.ChatHandler, req)
}
status := tt.wantStatus
if status == 0 {
status = http.StatusOK
}
if w.Code != status {
t.Fatalf("status = %d, want %d: %s", w.Code, status, w.Body.String())
}
if status != http.StatusOK {
select {
case <-requests:
t.Fatal("rejected request reached completion")
default:
}
return
}
select {
case got := <-requests:
if got.JSONDocument != tt.want || string(got.Format) != string(req.Format) || got.Logprobs != tt.logprobs {
t.Fatalf("completion mode/format/logprobs = %t/%s/%t, want %t/%s/%t", got.JSONDocument, got.Format, got.Logprobs, tt.want, req.Format, tt.logprobs)
}
default:
t.Fatal("completion was not called")
}
if tt.generate {
return
}
var content strings.Builder
decoder := json.NewDecoder(w.Body)
done := false
for {
var response api.ChatResponse
if err := decoder.Decode(&response); err == io.EOF {
break
} else if err != nil {
t.Fatal(err)
}
if done {
t.Fatal("response after Done")
}
content.WriteString(response.Message.Content)
done = response.Done
}
if !done || content.String() != document {
t.Fatalf("content = %q, done = %t", content.String(), done)
}
})
}
}
func TestChatGroundingOpenAIImageParts(t *testing.T) {
gin.SetMode(gin.TestMode)
t.Setenv("OLLAMA_MODELS", t.TempDir())
writeShowManifestVariant(t, "grounding-parts", manifest.RunnerMLX, manifest.FormatSafetensors, model.ConfigV2{
ModelFormat: manifest.FormatSafetensors, Renderer: "molmo3", Capabilities: []string{"completion", "vision"},
}, nil)
requests := make(chan llm.CompletionRequest, 1)
const document = `{"text":"result","multi_modal":[],"type":"text"}`
mock := &mockRunner{CompletionFn: func(_ context.Context, req llm.CompletionRequest, fn func(llm.CompletionResponse)) error {
requests <- req
fn(llm.CompletionResponse{Content: document, Done: true})
return nil
}}
s := newServerWithMockRunner(t, mock)
router := gin.New()
router.POST("/v1/chat/completions", middleware.ChatMiddleware(), s.ChatHandler)
// The adapter emits a separate user message for each text/image part.
body := `{"model":"grounding-parts","stream":false,"response_format":{"type":"json_object"},"messages":[{"role":"user","content":[{"type":"text","text":"Point to "},{"type":"image_url","image_url":{"url":"data:image/png;base64,Zmlyc3Q="}},{"type":"text","text":"the red region."},{"type":"image_url","image_url":{"url":"data:image/png;base64,c2Vjb25k"}}]}]}`
w := NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(body)))
if w.Code != http.StatusOK {
t.Fatalf("status = %d: %s", w.Code, w.Body.String())
}
select {
case req := <-requests:
want := "<|im_start|>user\nImage 1[img-0]Image 2[img-1]Point to the red region.<|im_end|>\n<|im_start|>assistant\n"
if !req.JSONDocument || req.Prompt != want {
t.Fatalf("document=%t, prompt=%q, want %q", req.JSONDocument, req.Prompt, want)
}
if len(req.Media) != 2 || !bytes.Equal(req.Media[0].Data, []byte("first")) || !bytes.Equal(req.Media[1].Data, []byte("second")) {
t.Fatalf("media order changed: %+v", req.Media)
}
default:
t.Fatal("completion was not called")
}
var response struct {
Choices []struct{ Message struct{ Content string } }
}
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
if len(response.Choices) != 1 || response.Choices[0].Message.Content != document {
t.Fatalf("document content changed: %s", w.Body.String())
}
}
+109
View File
@@ -0,0 +1,109 @@
package server
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/ollama/ollama/llm"
"github.com/ollama/ollama/manifest"
"github.com/ollama/ollama/middleware"
"github.com/ollama/ollama/types/model"
)
func TestChatMolmo3OpenAIUserFragments(t *testing.T) {
gin.SetMode(gin.TestMode)
t.Setenv("OLLAMA_MODELS", t.TempDir())
writeShowManifestVariant(t, "molmo3-parts", manifest.RunnerMLX, manifest.FormatSafetensors, model.ConfigV2{
ModelFormat: manifest.FormatSafetensors, Renderer: "molmo3", Capabilities: []string{"completion", "vision"},
}, nil)
for _, tc := range []struct {
name string
responseFormat string
wantFormat string
}{
{name: "ordinary"},
{name: "schema", responseFormat: `,"response_format":{"type":"json_schema","json_schema":{"name":"color","schema":{"type":"object"}}}`, wantFormat: `{"type":"object"}`},
} {
for _, stream := range []bool{false, true} {
t.Run(fmt.Sprintf("%s/stream=%t", tc.name, stream), func(t *testing.T) {
// Exercise the adapter, prompt and transport; inference is mocked.
const output = `{"color":"red"}`
requests := make(chan llm.CompletionRequest, 1)
mock := &mockRunner{CompletionFn: func(_ context.Context, req llm.CompletionRequest, fn func(llm.CompletionResponse)) error {
requests <- req
fn(llm.CompletionResponse{Content: output[:9]})
fn(llm.CompletionResponse{Content: output[9:], Done: true, DoneReason: llm.DoneReasonStop})
return nil
}}
s := newServerWithMockRunner(t, mock)
router := gin.New()
router.POST("/v1/chat/completions", middleware.ChatMiddleware(), s.ChatHandler)
body := fmt.Sprintf(`{"model":"molmo3-parts","stream":%t%s,"messages":[{"role":"user","content":[{"type":"text","text":"Compare "},{"type":"image_url","image_url":{"url":"data:image/png;base64,Zmlyc3Q="}},{"type":"text","text":"these."},{"type":"image_url","image_url":{"url":"data:image/png;base64,c2Vjb25k"}}]}]}`, stream, tc.responseFormat)
w := NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(body)))
if w.Code != http.StatusOK {
t.Fatalf("status = %d: %s", w.Code, w.Body.String())
}
select {
case req := <-requests:
want := "<|im_start|>user\nImage 1[img-0]Image 2[img-1]Compare these.<|im_end|>\n<|im_start|>assistant\n"
if req.Prompt != want || string(req.Format) != tc.wantFormat {
t.Fatalf("prompt/format = %q/%s, want %q/%s", req.Prompt, req.Format, want, tc.wantFormat)
}
if len(req.Media) != 2 || req.Media[0].ID != 0 || req.Media[1].ID != 1 || !bytes.Equal(req.Media[0].Data, []byte("first")) || !bytes.Equal(req.Media[1].Data, []byte("second")) {
t.Fatalf("media order changed: %+v", req.Media)
}
default:
t.Fatal("completion was not called")
}
var content strings.Builder
done := false
for _, line := range strings.Split(strings.TrimSpace(w.Body.String()), "\n") {
if line == "" {
continue
}
if stream {
if !strings.HasPrefix(line, "data: ") {
t.Fatalf("invalid SSE line: %q", line)
}
line = strings.TrimPrefix(line, "data: ")
if line == "[DONE]" {
done = true
continue
}
}
if done {
t.Fatal("response after stream completion")
}
var response struct {
Choices []struct {
Message struct{ Content string }
Delta struct{ Content string }
}
}
if err := json.Unmarshal([]byte(line), &response); err != nil {
t.Fatal(err)
}
if len(response.Choices) != 1 {
t.Fatalf("expected one choice: %s", line)
}
if stream {
content.WriteString(response.Choices[0].Delta.Content)
} else {
content.WriteString(response.Choices[0].Message.Content)
}
}
if content.String() != output || stream && !done {
t.Fatalf("content = %q, stream done = %t", content.String(), done)
}
})
}
}
}