Skip to content

Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.

model: add multimodal embeddings (#18820)

Patrick Devineefe43c556104
diff --git a/api/types.go b/api/types.go
index 0a34ac905..e19de536f 100644
--- a/api/types.go
+++ b/api/types.go
@@ -609,7 +609,12 @@ type EmbedRequest struct {
// Runner selects a runner variant from a manifest list.
Runner string `json:"runner,omitempty"`
- // Input is the input to embed.
+ // Input is the input to embed. Three shapes are accepted:
+ // - a string, or a []string — one text entry per item
+ // - a map with any of "text", "image", "audio" — one multimodal item
+ // (image/audio values are base64-encoded blobs)
+ // - a list mixing strings and those maps — a batch where each item
+ // owns its own media
Input any `json:"input"`
// KeepAlive controls how long the model will stay loaded in memory following
diff --git a/create/create.go b/create/create.go
index 508e4f1e1..128b3b1f7 100644
--- a/create/create.go
+++ b/create/create.go
@@ -449,6 +449,7 @@ var tensorImportTransformRegistry = map[string]tensorImportTransformFactory{
"NemotronH_Nano_VL_V2": newNemotronHImportTransform,
"NemotronH_Nano_Omni_Reasoning_V3": newNemotronHImportTransform,
"NemotronHForCausalLM": newNemotronHImportTransform,
+ "EmbeddingGemma2Model": newGemma4EmbeddingImportTransform,
}
func newTensorImportTransform(inv Inventory) (quantizePolicy, error) {
diff --git a/create/gemma4embedding.go b/create/gemma4embedding.go
new file mode 100644
index 000000000..47f896283
--- /dev/null
+++ b/create/gemma4embedding.go
@@ -0,0 +1,85 @@
+package create
+
+import (
+ "encoding/json"
+ "fmt"
+
+ "github.com/ollama/ollama/types/model"
+)
+
+// Gemma4Embedding (EmbeddingGemma v2) quantization policy. The trunk is a
+// 24-layer bidirectional encoder; the embedding_projection output head feeds
+// mean-pooling + L2-norm downstream in the runner, so keep it unquantized
+// (a low-rank 512→768 projection is cheap and precision-sensitive).
+type gemma4EmbeddingImportTransform struct {
+ embeddingDim int
+ contextLen int
+ hasVision bool
+ hasAudio bool
+}
+
+func newGemma4EmbeddingImportTransform(rawConfig json.RawMessage) (quantizePolicy, error) {
+ // The arch's config carries both fields under text_config; parse them
+ // here so the shared sourceModelConfig doesn't grow fields only this
+ // arch reads.
+ var cfg struct {
+ TextConfig struct {
+ EmbeddingDim int `json:"embedding_dim"`
+ MaxPositionEmbeddings int `json:"max_position_embeddings"`
+ } `json:"text_config"`
+ VisionConfig json.RawMessage `json:"vision_config"`
+ AudioConfig json.RawMessage `json:"audio_config"`
+ }
+ if err := json.Unmarshal(rawConfig, &cfg); err != nil {
+ return nil, fmt.Errorf("gemma4embedding: parse config.json: %w", err)
+ }
+ return gemma4EmbeddingImportTransform{
+ embeddingDim: cfg.TextConfig.EmbeddingDim,
+ contextLen: cfg.TextConfig.MaxPositionEmbeddings,
+ // A null tower config means the checkpoint ships without it; a
+ // present (even empty) object means the tower is there.
+ hasVision: len(cfg.VisionConfig) > 0 && string(cfg.VisionConfig) != "null",
+ hasAudio: len(cfg.AudioConfig) > 0 && string(cfg.AudioConfig) != "null",
+ }, nil
+}
+
+// augmentConfig fills the manifest fields inferSafetensorsConfig can't
+// derive. Embedding is the arch's one unconditional capability (no lm_head,
+// pooled output); vision/audio are advertised per checkpoint, following the
+// towers it ships.
+func (t gemma4EmbeddingImportTransform) augmentConfig(cfg *model.ConfigV2) error {
+ if t.embeddingDim <= 0 {
+ return fmt.Errorf("missing text_config.embedding_dim")
+ }
+ if t.contextLen <= 0 {
+ return fmt.Errorf("missing text_config.max_position_embeddings")
+ }
+ cfg.EmbedLen = t.embeddingDim
+ // The checkpoint's max_position_embeddings (262144) is a Gemma 4
+ // backbone artifact: the RoPE encoding is mechanically sound to that
+ // span, but the embedding model is trained and validated at 8K. The
+ // manifest advertises the validated window; the runner enforces the
+ // same constant (gemma4embedding.maxContextLength).
+ cfg.ContextLen = min(t.contextLen, 8192)
+ cfg.Capabilities = []string{"embedding"}
+ if t.hasVision {
+ cfg.Capabilities = append(cfg.Capabilities, "vision")
+ }
+ if t.hasAudio {
+ cfg.Capabilities = append(cfg.Capabilities, "audio")
+ }
+ return nil
+}
+
+func (t gemma4EmbeddingImportTransform) quantizationType(name string, shape []int32, quantize string) string {
+ switch {
+ case name == "embedding_projection.weight" ||
+ name == "model.embedding_projection.weight" ||
+ name == "language_model.embedding_projection.weight":
+ // Output head feeding pooled/normalized embedding: keep at source
+ // precision regardless of the requested type.
+ return ""
+ default:
+ return GetTensorQuantization(name, shape, quantize)
+ }
+}
diff --git a/create/gemma4embedding_test.go b/create/gemma4embedding_test.go
new file mode 100644
index 000000000..6e132e224
--- /dev/null
+++ b/create/gemma4embedding_test.go
@@ -0,0 +1,113 @@
+package create
+
+import (
+ "encoding/json"
+ "slices"
+ "testing"
+
+ "github.com/ollama/ollama/types/model"
+)
+
+// The registered factory parses the arch's own config.json fields
+// (text_config.embedding_dim, text_config.max_position_embeddings) and
+// augmentConfig fills the manifest fields the shared inference can't derive.
+// Capabilities follow the towers the checkpoint ships.
+func TestGemma4EmbeddingAugmentConfig(t *testing.T) {
+ tests := []struct {
+ name string
+ raw string
+ want []string
+ }{
+ {
+ name: "text only",
+ raw: `{"text_config":{"embedding_dim":768,"max_position_embeddings":262144}}`,
+ want: []string{"embedding"},
+ },
+ {
+ name: "null towers",
+ raw: `{"text_config":{"embedding_dim":768,"max_position_embeddings":262144},"vision_config":null,"audio_config":null}`,
+ want: []string{"embedding"},
+ },
+ {
+ name: "vision tower",
+ raw: `{"text_config":{"embedding_dim":768,"max_position_embeddings":262144},"vision_config":{"model_type":"gemma4_vision"}}`,
+ want: []string{"embedding", "vision"},
+ },
+ {
+ name: "audio tower",
+ raw: `{"text_config":{"embedding_dim":768,"max_position_embeddings":262144},"audio_config":{"model_type":"gemma4_audio"}}`,
+ want: []string{"embedding", "audio"},
+ },
+ {
+ name: "both towers",
+ raw: `{"text_config":{"embedding_dim":768,"max_position_embeddings":262144},"vision_config":{"model_type":"gemma4_vision"},"audio_config":{"model_type":"gemma4_audio"}}`,
+ want: []string{"embedding", "vision", "audio"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ p, err := newGemma4EmbeddingImportTransform(json.RawMessage(tt.raw))
+ if err != nil {
+ t.Fatal(err)
+ }
+ aug, ok := p.(interface{ augmentConfig(*model.ConfigV2) error })
+ if !ok {
+ t.Fatal("policy does not implement augmentConfig")
+ }
+ var cfg model.ConfigV2
+ if err := aug.augmentConfig(&cfg); err != nil {
+ t.Fatal(err)
+ }
+ if cfg.EmbedLen != 768 {
+ t.Errorf("EmbedLen = %d, want 768", cfg.EmbedLen)
+ }
+ if cfg.ContextLen != 8192 {
+ t.Errorf("ContextLen = %d, want 8192", cfg.ContextLen)
+ }
+ if !slices.Equal(cfg.Capabilities, tt.want) {
+ t.Errorf("Capabilities = %v, want %v", cfg.Capabilities, tt.want)
+ }
+ })
+ }
+
+ // Missing keys must fail loudly, not write zeros into the manifest.
+ for name, raw := range map[string]json.RawMessage{
+ "no embedding_dim": json.RawMessage(`{"text_config":{"max_position_embeddings":262144}}`),
+ "no max_position_embeddings": json.RawMessage(`{"text_config":{"embedding_dim":768}}`),
+ } {
+ p, err := newGemma4EmbeddingImportTransform(raw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ aug := p.(interface{ augmentConfig(*model.ConfigV2) error })
+ var got model.ConfigV2
+ if err := aug.augmentConfig(&got); err == nil {
+ t.Errorf("%s: augmentConfig succeeded, want error", name)
+ }
+ }
+}
+
+// The output head stays at source precision under every arch spelling,
+// including the new-arch language_model.embedding_projection nesting.
+func TestGemma4EmbeddingProjectionExcluded(t *testing.T) {
+ p, err := newGemma4EmbeddingImportTransform(json.RawMessage(
+ `{"text_config":{"embedding_dim":768,"max_position_embeddings":262144}}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ shape := []int32{768, 512} // rows, cols — above the 1024-element floor
+ for _, name := range []string{
+ "embedding_projection.weight",
+ "model.embedding_projection.weight",
+ "language_model.embedding_projection.weight",
+ } {
+ if got := p.quantizationType(name, shape, "nvfp4"); got != "" {
+ t.Errorf("quantizationType(%q) = %q, want \"\"", name, got)
+ }
+ }
+ // A trunk tensor still quantizes.
+ if got := p.quantizationType("language_model.layers.0.mlp.gate_proj.weight", []int32{2048, 512}, "nvfp4"); got != "nvfp4" {
+ t.Errorf("trunk tensor quantization = %q, want nvfp4", got)
+ }
+}
diff --git a/create/metadata.go b/create/metadata.go
index 39ea1f46b..a12f2f44c 100644
--- a/create/metadata.go
+++ b/create/metadata.go
@@ -44,13 +44,14 @@ func inferSafetensorsConfig(modelDir string, cfg sourceModelConfig, parserOverri
return model.ConfigV2{}, err
}
- return model.ConfigV2{
+ config := model.ConfigV2{
ModelFormat: "safetensors",
Parser: parserName,
Renderer: rendererName,
Capabilities: capabilities,
GenerationDefaults: generationDefaults,
- }, nil
+ }
+ return config, nil
}
func readHFGenerationDefaults(modelDir string) (model.GenerationDefaults, error) {
diff --git a/create/pipeline.go b/create/pipeline.go
index 35d990f05..d0f7cd46d 100644
--- a/create/pipeline.go
+++ b/create/pipeline.go
@@ -9,6 +9,8 @@ import (
"os"
"path/filepath"
"strings"
+
+ "github.com/ollama/ollama/types/model"
)
// PipelineOptions controls the source-specific stages of a safetensors import.
@@ -71,6 +73,13 @@ func Create(ctx context.Context, modelName, modelDir string, opts PipelineOption
if err != nil {
return fmt.Errorf("build quantization policy for %q: %w", inv.Config.Architecture(), err)
}
+ // Arch-specific policies may fill manifest-config fields the shared
+ // inference can't derive from an arch-specific config layout.
+ if aug, ok := policy.(interface{ augmentConfig(*model.ConfigV2) error }); ok {
+ if err := aug.augmentConfig(&modelConfig); err != nil {
+ return fmt.Errorf("augment config for %q: %w", inv.Config.Architecture(), err)
+ }
+ }
specs, err := Plan(inv, class, policy)
if err != nil {
return fmt.Errorf("plan model: %w", err)
diff --git a/docs/api.md b/docs/api.md
index 5ffc16e25..595f7857e 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -1674,7 +1674,7 @@ Generate embeddings from a model
### Parameters
- `model`: name of model to generate embeddings from
-- `input`: text or list of text to generate embeddings for
+- `input`: text or list of text to generate embeddings for. To embed media (images or audio) alongside text on models that accept multimodal embeddings, each entry may instead be an object with any of `text` (string), `image` (base64-encoded bytes), `audio` (base64-encoded bytes). In a list, entries can mix plain strings and such objects; each object owns its own media. `video` is not currently accepted.
Advanced parameters:
@@ -1738,6 +1738,28 @@ curl http://localhost:11434/api/embed -d '{
}
```
+#### Request (With image)
+
+```shell
+curl http://localhost:11434/api/embed -d '{
+ "model": "embeddinggemma2",
+ "input": {"text": "a cat sitting on a windowsill", "image": "iVBORw0KGgo..."}
+}'
+```
+
+#### Request (Batched, mixed modalities)
+
+```shell
+curl http://localhost:11434/api/embed -d '{
+ "model": "embeddinggemma2",
+ "input": [
+ "a plain text query",
+ {"image": "iVBORw0KGgo..."},
+ {"audio": "UklGRiQAAABXQVZF..."}
+ ]
+}'
+```
+
## List Running Models
```
diff --git a/llm/llama_server.go b/llm/llama_server.go
index f11a6d5dd..c7cd91518 100644
--- a/llm/llama_server.go
+++ b/llm/llama_server.go
@@ -2547,7 +2547,10 @@ func normalizeEmbeddingError(statusCode int, body []byte) (int, string) {
}
if isEmbeddingInputLimitError(errMsg) || isEmbeddingInputLimitError(raw) {
- return http.StatusBadRequest, "the input length exceeds the context length"
+ // 413 (Request Entity Too Large) distinguishes "input too long" from
+ // other 400s so the server's truncate-and-retry path can tell a real
+ // length problem apart from unrelated validation.
+ return http.StatusRequestEntityTooLarge, "the input length exceeds the context length"
}
return statusCode, errMsg
diff --git a/llm/llama_server_test.go b/llm/llama_server_test.go
index 9b5e57df6..2025e5a6c 100644
--- a/llm/llama_server_test.go
+++ b/llm/llama_server_test.go
@@ -1855,13 +1855,13 @@ func TestLlamaServerEmbeddingTooLargeError(t *testing.T) {
if err == nil {
t.Fatal("expected error, got nil")
}
- // Should be normalized to 400 for the embed handler's truncation retry
+ // Should be normalized to 413 for the embed handler's truncation retry
var statusErr api.StatusError
if !errors.As(err, &statusErr) {
t.Fatalf("expected api.StatusError, got %T: %v", err, err)
}
- if statusErr.StatusCode != 400 {
- t.Errorf("status code = %d, want 400", statusErr.StatusCode)
+ if statusErr.StatusCode != 413 {
+ t.Errorf("status code = %d, want 413", statusErr.StatusCode)
}
}
@@ -2703,21 +2703,21 @@ func TestNormalizeEmbeddingError(t *testing.T) {
name: "physical batch size",
statusCode: http.StatusInternalServerError,
body: `{"error":{"code":500,"message":"input (103 tokens) is too large to process. increase the physical batch size (current batch size: 30)"}}`,
- wantStatus: http.StatusBadRequest,
+ wantStatus: http.StatusRequestEntityTooLarge,
wantMsg: "the input length exceeds the context length",
},
{
name: "context length string error",
statusCode: http.StatusInternalServerError,
body: `{"error":"input length exceeds the context length"}`,
- wantStatus: http.StatusBadRequest,
+ wantStatus: http.StatusRequestEntityTooLarge,
wantMsg: "the input length exceeds the context length",
},
{
name: "available context",
statusCode: http.StatusBadRequest,
body: `{"error":{"message":"request (302 tokens) exceeds the available context size (256 tokens), try increasing it"}}`,
- wantStatus: http.StatusBadRequest,
+ wantStatus: http.StatusRequestEntityTooLarge,
wantMsg: "the input length exceeds the context length",
},
{
diff --git a/mlxrunner/client.go b/mlxrunner/client.go
index 9cfb84775..f255c21bd 100644
--- a/mlxrunner/client.go
+++ b/mlxrunner/client.go
@@ -2,7 +2,9 @@ package mlxrunner
import (
"bufio"
+ "bytes"
"context"
+ "encoding/base64"
"encoding/json"
"errors"
"fmt"
@@ -33,18 +35,19 @@ import (
// Client wraps an MLX runner subprocess to implement llm.LlamaServer for LLM models.
type Client struct {
- port int
- modelName string
- contextLength atomic.Int64
- softContextLength int // recommended limit to avoid poor performance
- memory atomic.Uint64
- done chan struct{}
- doneErr error // valid after done is closed
- client *http.Client
- status *llm.StatusWriter
- mu sync.Mutex
- cmd *exec.Cmd
- closed bool
+ port int
+ modelName string
+ contextLength atomic.Int64
+ softContextLength int // recommended limit to avoid poor performance
+ memory atomic.Uint64
+ embeddingDimensions atomic.Value // []int
+ done chan struct{}
+ doneErr error // valid after done is closed
+ client *http.Client
+ status *llm.StatusWriter
+ mu sync.Mutex
+ cmd *exec.Cmd
+ closed bool
}
var ErrRuntimeUnavailable = errors.New("MLX runtime is not available")
@@ -292,12 +295,90 @@ func (c *Client) reportedContextLength(modelContextLength int) int {
// Detokenize implements llm.LlamaServer.
func (c *Client) Detokenize(ctx context.Context, tokens []int) (string, error) {
- return "", errors.New("not supported")
+ ids32 := make([]int32, len(tokens))
+ for i, t := range tokens {
+ ids32[i] = int32(t)
+ }
+ var buf bytes.Buffer
+ if err := json.NewEncoder(&buf).Encode(ids32); err != nil {
+ return "", err
+ }
+ req, err := http.NewRequestWithContext(ctx, "POST",
+ fmt.Sprintf("http://127.0.0.1:%d/v1/detokenize", c.port), &buf)
+ if err != nil {
+ return "", err
+ }
+ req.Header.Set("Content-Type", "application/json")
+
+ resp, err := c.client.Do(req)
+ if err != nil {
+ return "", err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(resp.Body)
+ return "", api.StatusError{
+ StatusCode: resp.StatusCode,
+ ErrorMessage: strings.TrimSpace(string(body)),
+ }
+ }
+
+ var s string
+ if err := json.NewDecoder(resp.Body).Decode(&s); err != nil {
+ return "", err
+ }
+ return s, nil
}
// Embedding implements llm.LlamaServer.
func (c *Client) Embedding(ctx context.Context, input string) ([]float32, int, error) {
- return nil, 0, errors.New("not supported")
+ return c.embed(ctx, embedWireRequest{Content: input})
+}
+
+// EmbedWithMedia embeds a single text input with media blobs alongside.
+func (c *Client) EmbedWithMedia(ctx context.Context, input string, media [][]byte) ([]float32, int, error) {
+ if len(media) == 0 {
+ return c.Embedding(ctx, input)
+ }
+ wire := embedWireRequest{Content: input, Media: make([]string, len(media))}
+ for i, blob := range media {
+ wire.Media[i] = base64.StdEncoding.EncodeToString(blob)
+ }
+ return c.embed(ctx, wire)
+}
+
+func (c *Client) embed(ctx context.Context, wire embedWireRequest) ([]float32, int, error) {
+ var buf bytes.Buffer
+ if err := json.NewEncoder(&buf).Encode(wire); err != nil {
+ return nil, 0, err
+ }
+ req, err := http.NewRequestWithContext(ctx, "POST",
+ fmt.Sprintf("http://127.0.0.1:%d/v1/embeddings", c.port), &buf)
+ if err != nil {
+ return nil, 0, err
+ }
+ req.Header.Set("Content-Type", "application/json")
+
+ resp, err := c.client.Do(req)
+ if err != nil {
+ return nil, 0, err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(resp.Body)
+ return nil, 0, api.StatusError{
+ StatusCode: resp.StatusCode,
+ ErrorMessage: strings.TrimSpace(string(body)),
+ }
+ }
+
+ var er embedWireResponse
+ if err := json.NewDecoder(resp.Body).Decode(&er); err != nil {
+ return nil, 0, err
+ }
+ return er.Embedding, er.PromptEvalCount, nil
}
// GetDeviceInfos implements llm.LlamaServer.
@@ -480,6 +561,20 @@ type statusResponse struct {
Progress int
ContextLength int
Memory uint64
+
+ // EmbeddingDimensions lists the model's trained matryoshka truncation
+ // sizes, when it declares any.
+ EmbeddingDimensions []int
+}
+
+// EmbeddingDimensions returns the runner's declared matryoshka set, cached
+// from the last successful status response. Empty when the runner doesn't
+// advertise one.
+func (c *Client) EmbeddingDimensions() []int {
+ if v := c.embeddingDimensions.Load(); v != nil {
+ return v.([]int)
+ }
+ return nil
}
// Ping implements llm.LlamaServer.
@@ -505,6 +600,7 @@ func (c *Client) Ping(ctx context.Context) error {
c.contextLength.Store(int64(c.reportedContextLength(status.ContextLength)))
c.memory.Store(status.Memory)
+ c.embeddingDimensions.Store(status.EmbeddingDimensions)
return nil
}
diff --git a/mlxrunner/embed.go b/mlxrunner/embed.go
new file mode 100644
index 000000000..cfd310018
--- /dev/null
+++ b/mlxrunner/embed.go
@@ -0,0 +1,421 @@
+package mlxrunner
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+
+ "github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/mlx"
+ "github.com/ollama/ollama/mlxrunner/batch"
+ "github.com/ollama/ollama/mlxrunner/model"
+)
+
+// EmbeddingRequest is a short-lived embedding request carried on the
+// runner's EmbedRequests channel from the HTTP handler to the runner
+// goroutine (same lifecycle shape as completions' Request/Requests).
+type EmbeddingRequest struct {
+ Content string
+ Dimensions int
+ Media [][]byte
+ EmbedResponses chan EmbedResponse
+ Ctx context.Context //nolint:containedctx // Queued requests carry caller cancellation to the runner.
+}
+
+// EmbedResponse carries one embedding, its prompt token count, or an error.
+type EmbedResponse struct {
+ Embedding []float32
+ PromptEvalCount int
+ Error *api.StatusError
+}
+
+// embedWireRequest / embedWireResponse are the HTTP wire shapes, matching the
+// old ollamarunner's llm.EmbeddingRequest/EmbeddingResponse keys, plus the
+// ollama-side extension for matryoshka dimension selection.
+type embedWireRequest struct {
+ Content string `json:"content"`
+ Dimensions int `json:"dimensions,omitempty"`
+ Media []string `json:"media,omitempty"`
+}
+
+type embedWireResponse struct {
+ Embedding []float32 `json:"embedding"`
+ PromptEvalCount int `json:"prompt_eval_count"`
+}
+
+// handleEmbed serves POST /v1/embeddings. Requests flow to the runner
+// goroutine via EmbedRequests, which serializes with completions on the
+// single consumer of the MLX thread (the same lifecycle as the text
+// pipeline).
+func (r *Runner) handleEmbed(w http.ResponseWriter, req *http.Request) {
+ if r.Model == nil {
+ http.Error(w, "model not loaded", http.StatusServiceUnavailable)
+ return
+ }
+ if _, ok := r.Model.(interface{ EmbeddingDim() int }); !ok {
+ // Mirrors the old ollamarunner's pooling_type gate.
+ http.Error(w, "this model does not support embeddings", http.StatusNotImplemented)
+ return
+ }
+
+ var wire embedWireRequest
+ if err := json.NewDecoder(req.Body).Decode(&wire); err != nil {
+ http.Error(w, "Bad Request", http.StatusBadRequest)
+ return
+ }
+ // An item with neither text nor media has nothing to embed.
+ if wire.Content == "" && len(wire.Media) == 0 {
+ http.Error(w, "empty content", http.StatusBadRequest)
+ return
+ }
+
+ // Matryoshka dimension validation against the model's declared set.
+ if wire.Dimensions > 0 {
+ em := r.Model.(interface {
+ EmbeddingDim() int
+ EmbeddingDimensions() []int
+ })
+ valid := em.EmbeddingDimensions()
+ if len(valid) > 0 {
+ ok := false
+ for _, d := range valid {
+ if wire.Dimensions == d {
+ ok = true
+ break
+ }
+ }
+ if !ok {
+ http.Error(w, fmt.Sprintf("dimensions %d not supported; valid values are %v", wire.Dimensions, valid), http.StatusBadRequest)
+ return
+ }
+ }
+ if wire.Dimensions >= em.EmbeddingDim() {
+ http.Error(w, fmt.Sprintf("dimensions %d exceeds the model's embedding dimension %d", wire.Dimensions, em.EmbeddingDim()), http.StatusBadRequest)
+ return
+ }
+ }
+
+ request := EmbeddingRequest{
+ Content: wire.Content,
+ Dimensions: wire.Dimensions,
+ EmbedResponses: make(chan EmbedResponse, 1),
+ Ctx: req.Context(),
+ }
+
+ if len(wire.Media) > 0 {
+ request.Media = make([][]byte, len(wire.Media))
+ for i, entry := range wire.Media {
+ raw, err := base64.StdEncoding.DecodeString(entry)
+ if err != nil {
+ http.Error(w, fmt.Sprintf("media[%d]: %v", i, err), http.StatusBadRequest)
+ return
+ }
+ request.Media[i] = raw
+ }
+ }
+
+ select {
+ case <-req.Context().Done():
+ return
+ case r.EmbedRequests <- request:
+ }
+
+ var resp EmbedResponse
+ select {
+ case <-req.Context().Done():
+ return
+ case resp = <-request.EmbedResponses:
+ }
+
+ if resp.Error != nil {
+ http.Error(w, resp.Error.ErrorMessage, resp.Error.StatusCode)
+ return
+ }
+
+ if err := json.NewEncoder(w).Encode(embedWireResponse{
+ Embedding: resp.Embedding,
+ PromptEvalCount: resp.PromptEvalCount,
+ }); err != nil {
+ slog.Error("failed to encode embedding response", "error", err)
+ }
+}
+
+// embedBudgetFraction reserves headroom for transient MLX buffers the
+// estimate does not model.
+const embedBudgetFraction = 0.5
+
+// embedFallbackBudgetBytes is the budget when the device's recommended
+// working-set size is unavailable (no GPU).
+const embedFallbackBudgetBytes = 1 << 30
+
+// PredictedEmbedAllocationBytes estimates the forward's dominant
+// allocations: the attention mask (L*L float32, worst case), the hidden
+// output [1, L, D] float32, and the token row.
+func PredictedEmbedAllocationBytes(tokens int, hidden int32) int64 {
+ if tokens < 0 {
+ tokens = 0
+ }
+ L := int64(tokens)
+ const f32 = 4
+ mask := L * L * f32
+ hiddenOut := L * int64(hidden) * f32
+ tokenRow := L * f32
+ return mask + hiddenOut + tokenRow
+}
+
+// EmbedCapacityBudget is the byte budget a single embed request's
+// predicted allocations must fit within.
+func EmbedCapacityBudget() int64 {
+ budget := int64(embedFallbackBudgetBytes)
+ if limit, err := mlx.MaxRecommendedWorkingSetSize(); err == nil && limit > 0 {
+ budget = int64(limit)
+ }
+ return int64(float64(budget) * embedBudgetFraction)
+}
+
+// embedHiddenSize is the model's hidden width for the allocation estimate;
+// 0 when the model doesn't expose it (the hidden term is minor — the mask
+// dominates).
+func embedHiddenSize(m any) int32 {
+ type hiddenSizer interface{ HiddenSize() int32 }
+ if h, ok := m.(hiddenSizer); ok {
+ return h.HiddenSize()
+ }
+ return 0
+}
+
+// runEmbed executes one embedding request on the runner goroutine (the MLX
+// thread): tokenize (+ media expansion if Media entries ride along) → single
+// bidirectional forward → masked mean pool → L2. Media kind sniffing happens
+// here because the runner has already dropped the original base64 framing;
+// deeper validation is the model's PrepareMedia.
+func (r *Runner) runEmbed(ctx context.Context, request EmbeddingRequest) error {
+ defer close(request.EmbedResponses)
+
+ fail := func(code int, err error) error {
+ request.EmbedResponses <- EmbedResponse{Error: &api.StatusError{StatusCode: code, ErrorMessage: err.Error()}}
+ return nil
+ }
+
+ // EmbedMedia is the narrow surface gemma4embedding (and any future
+ // multimodal embedding arch) exposes to the runner. Text-only models
+ // don't implement it and media requests 501 here.
+ type embedMedia interface {
+ PrepareMedia(segments []model.Segment) (*model.PreparedRequest, error)
+ EncodeMedia(prepared *model.PreparedRequest) ([]batch.MediaItem, error)
+ MediaTokenStrings() (boi, eoi, image, boa, eoa, audio string)
+ SupportsImages() bool
+ SupportsAudio() bool
+ }
+
+ var tokens []int32
+ var prepared *model.PreparedRequest
+
+ if len(request.Media) == 0 {
+ // Embedding encoders trained with the HF TemplateProcessing
+ // post-processor (not honored by the Go tokenizer) expect explicit
+ // BOS + EOS around the text. Append both unconditionally when the
+ // vocab defines them.
+ tokens = r.Tokenizer.Encode(request.Content, true)
+ if len(tokens) == 0 {
+ return fail(http.StatusBadRequest, errors.New("empty token sequence"))
+ }
+ if eos := r.Tokenizer.EOS(); eos >= 0 {
+ tokens = append(tokens, eos)
+ }
+ } else {
+ em, ok := r.Model.(embedMedia)
+ if !ok {
+ return fail(http.StatusNotImplemented, errors.New("media embedding not supported on this model"))
+ }
+
+ // Mirror sentence-transformers: it never rewrites the caller's text;
+ // it appends one placeholder per media entry and feeds
+ // caller-text+appended-placeholders to the model. The bracketed
+ // expansions the model sees (BOI...EOI with the soft-token run) are
+ // produced by PrepareMedia per segment, not by rewriting the text.
+ var segments []model.Segment
+ if tt := r.Tokenizer.Encode(request.Content, false); len(tt) > 0 {
+ segments = append(segments, model.Segment{Tokens: tt})
+ }
+ for i, raw := range request.Media {
+ var kind string
+ if looksLikeImage(raw) {
+ kind = "image"
+ } else if looksLikeAudio(raw) {
+ kind = "audio"
+ } else {
+ return fail(http.StatusBadRequest, fmt.Errorf("media[%d]: not a PNG/JPEG/GIF/WebP or wav/ogg blob", i))
+ }
+ switch kind {
+ case "image":
+ if !em.SupportsImages() {
+ return fail(http.StatusBadRequest, errors.New("model has no vision tower but media contains an image"))
+ }
+ case "audio":
+ if !em.SupportsAudio() {
+ return fail(http.StatusBadRequest, errors.New("model has no audio tower but media contains audio"))
+ }
+ }
+ segments = append(segments, model.Segment{Kind: kind, Data: raw})
+ }
+
+ pr, err := em.PrepareMedia(segments)
+ if err != nil {
+ return fail(http.StatusBadRequest, err)
+ }
+ prepared = pr
+ // BOS in front, EOS at end, matching the no-media path.
+ bos := r.Tokenizer.BOS()
+ if bos >= 0 {
+ tokens = append([]int32{bos}, prepared.Tokens...)
+ } else {
+ tokens = prepared.Tokens
+ }
+ if eos := r.Tokenizer.EOS(); eos >= 0 {
+ tokens = append(tokens, eos)
+ }
+ }
+
+ if maxLen := r.Model.MaxContextLength(); maxLen > 0 && len(tokens) > maxLen {
+ // 413 distinguishes "input too long" from other 400s so the server's
+ // truncate-and-retry path can tell a real length problem apart from
+ // unrelated validation (media sniffing, marker counts, etc.).
+ return fail(http.StatusRequestEntityTooLarge,
+ fmt.Errorf("the input length (%d tokens) exceeds the context length (%d)", len(tokens), maxLen))
+ }
+
+ // Pre-flight: reject before MLX panics at metal::malloc on a forward
+ // that cannot fit. 413, like the token-count gate, so the server's
+ // truncate retry applies.
+ if budget := EmbedCapacityBudget(); budget > 0 {
+ if need := PredictedEmbedAllocationBytes(len(tokens), embedHiddenSize(r.Model)); need > budget {
+ return fail(http.StatusRequestEntityTooLarge,
+ fmt.Errorf("embedding request would allocate %d bytes (budget %d); reduce input length or parallel load", need, budget))
+ }
+ }
+
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ default:
+ }
+
+ // Per-request hygiene, mirroring the completion pipeline (see
+ // TextGenerationPipeline): without the scope + ClearCache, freed
+ // buffers accumulate across embeds until metal::malloc panics.
+ // EncodeMedia runs inside the scope: its feature graphs are lazy
+ // and consumed by Forward, so they must share one scope lifetime.
+ mlx.ResetPeakMemory()
+ mlx.Scoped(func() {
+ var media []batch.MediaItem
+ if prepared != nil {
+ em := r.Model.(embedMedia)
+ mi, err := em.EncodeMedia(prepared)
+ if err != nil {
+ fail(http.StatusBadRequest, err)
+ return
+ }
+ // Re-base media Pos onto the final stream when a BOS was prepended
+ // after PrepareMedia computed them against a BOS-less token list.
+ if r.Tokenizer.BOS() >= 0 {
+ for i := range mi {
+ mi[i].Pos++
+ }
+ }
+ media = mi
+ }
+ inputIDs := mlx.FromValues(tokens, 1, len(tokens))
+ hidden, _ := r.Model.Forward(&batch.Batch{
+ InputIDs: inputIDs,
+ SeqOffsets: []int32{0},
+ SeqQueryLens: []int32{int32(len(tokens))},
+ Media: media,
+ }, nil)
+
+ L := int32(hidden.Dim(1))
+ D := int32(hidden.Dim(2))
+ rows := mlx.Reshape(hidden, L, D)
+ // The embedding is plain floats by now, so it escapes the
+ // scope as CPU data; every GPU intermediate is freed at exit.
+ embedding := meanPoolAndNormalize(rows, len(tokens))
+ request.EmbedResponses <- EmbedResponse{Embedding: embedding, PromptEvalCount: len(tokens)}
+ })
+ mlx.ClearCache()
+ return nil
+}
+
+// looksLikeImage / looksLikeAudio sniff the container headers the runner
+// sees from embedding clients. The model does deeper format validation in
+// PrepareMedia; these exist to reject obviously-wrong blobs with an
+// actionable message before the tower runs. gemma4's own path has no
+// exported sniffer; if that changes, drop these.
+func looksLikeImage(b []byte) bool {
+ if len(b) < 4 {
+ return false
+ }
+ switch {
+ case b[0] == 0x89 && b[1] == 'P' && b[2] == 'N' && b[3] == 'G':
+ return true
+ case b[0] == 0xff && b[1] == 0xd8:
+ return true
+ case b[0] == 'G' && b[1] == 'I' && b[2] == 'F':
+ return true
+ case len(b) >= 12 && string(b[0:4]) == "RIFF" && string(b[8:12]) == "WEBP":
+ return true
+ }
+ return false
+}
+
+func looksLikeAudio(b []byte) bool {
+ if len(b) < 4 {
+ return false
+ }
+ switch {
+ case string(b[0:4]) == "RIFF" && len(b) >= 12 && string(b[8:12]) == "WAVE":
+ return true
+ case string(b[0:4]) == "OggS":
+ return true
+ }
+ return false
+}
+
+// meanPoolAndNormalize implements the sentence-transformers module chain for
+// this model (1_Pooling mean + 2_Normalize L2): masked mean over token
+// embeddings, then L2 normalization. hidden is [L, D] for a single padded
+// row; seqLen is the row's real token count.
+func meanPoolAndNormalize(hidden *mlx.Array, seqLen int) []float32 {
+ L := hidden.Dim(0)
+ D := hidden.Dim(1)
+
+ maskVals := make([]float32, L)
+ for i := range maskVals {
+ if i < seqLen {
+ maskVals[i] = 1
+ }
+ }
+ mask := mlx.FromValues(maskVals, L, 1)
+
+ // Mean over real tokens only (compute in fp32).
+ h32 := hidden.AsType(mlx.DTypeFloat32)
+ sum := h32.Multiply(mask).SumAxis(0, false)
+ count := mlx.FromValue(float32(seqLen))
+ pooled := sum.Divide(count)
+
+ // L2 normalize.
+ sq := pooled.Multiply(pooled)
+ norm := sq.SumAxis(0, false).Sqrt()
+ normed := pooled.Divide(mlx.Maximum(norm, mlx.FromValue(float32(1e-12))))
+
+ mlx.Eval(normed)
+ vals := normed.Floats()
+ if len(vals) != D {
+ // Shouldn't happen; Floats returns the full flattened buffer.
+ return vals
+ }
+ return vals
+}
diff --git a/mlxrunner/embed_test.go b/mlxrunner/embed_test.go
new file mode 100644
index 000000000..13c0b302f
--- /dev/null
+++ b/mlxrunner/embed_test.go
@@ -0,0 +1,489 @@
+package mlxrunner
+
+import (
+ "context"
+ "fmt"
+ "math"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "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/tokenizer"
+)
+
+// stubModel is a generative-only model.Model (no EmbeddingDim).
+type stubModel struct{}
+
+func (s *stubModel) LoadWeights(map[string]*mlx.Array) error { return nil }
+func (s *stubModel) NewCaches() []cache.Cache { return nil }
+func (s *stubModel) Forward(*batch.Batch, []cache.Cache) (*mlx.Array, *mlx.Array) {
+ return nil, nil
+}
+func (s *stubModel) Unembed(*mlx.Array) *mlx.Array { return nil }
+func (s *stubModel) Tokenizer() *tokenizer.Tokenizer { return nil }
+func (s *stubModel) MaxContextLength() int { return 8 }
+
+// stubEmbeddingModel adds EmbeddingDim so the handler's gate passes.
+type stubEmbeddingModel struct{ stubModel }
+
+func (s *stubEmbeddingModel) EmbeddingDim() int { return 768 }
+
+func TestHandleEmbedGate(t *testing.T) {
+ // Generative-only model: expect 501.
+ r := &Runner{Model: &stubModel{}}
+ req := httptest.NewRequest("POST", "/v1/embeddings", strings.NewReader(`{"content":"hi"}`))
+ w := httptest.NewRecorder()
+ r.handleEmbed(w, req)
+ if w.Code != http.StatusNotImplemented {
+ t.Fatalf("gate: got %d, want 501; body=%q", w.Code, w.Body.String())
+ }
+
+ // Embedding-capable model but nil channels: expect goroutine-safe write
+ // path. We can't fully run the handler without the runner loop, so stop
+ // at decoding validation: bad JSON -> 400; empty content -> 400.
+ for _, body := range []string{`{`, `{"content":""}`} {
+ r := &Runner{Model: &stubEmbeddingModel{}}
+ req := httptest.NewRequest("POST", "/v1/embeddings", strings.NewReader(body))
+ w := httptest.NewRecorder()
+ r.handleEmbed(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("body %q: got %d, want 400; resp=%q", body, w.Code, w.Body.String())
+ }
+ }
+}
+
+func TestEmbeddingRequestChannelContext(t *testing.T) {
+ // Cancellation before the runner consumes: the handler must not panic or
+ // hang when the request context is already done.
+ r := &Runner{
+ Model: &stubEmbeddingModel{},
+ EmbedRequests: make(chan EmbeddingRequest),
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ req := httptest.NewRequest("POST", "/v1/embeddings", strings.NewReader(`{"content":"hi"}`)).WithContext(ctx)
+ w := httptest.NewRecorder()
+ done := make(chan struct{})
+ go func() { r.handleEmbed(w, req); close(done) }()
+ select {
+ case <-done:
+ case <-time.After(2 * time.Second):
+ t.Fatal("handleEmbed hung on cancelled context")
+ }
+}
+
+// TestEmbedMediaWireDecode covers the base64 boundary in handleEmbed: the
+// runner is never reached on decode failure, and a valid entry is queued
+// onto EmbedRequests untouched for the model side to reject (runEmbed 501s
+// until Task 4). A stub consumer drains the channel so the handler returns.
+func TestEmbedMediaWireDecode(t *testing.T) {
+ t.Run("bad base64 rejected with index", func(t *testing.T) {
+ r := &Runner{Model: &stubEmbeddingModel{}, EmbedRequests: make(chan EmbeddingRequest, 1)}
+ body := `{"content":"hi","media":["aGVsbG8=","!!!not base64!!!","d29ybGQ="]}`
+ req := httptest.NewRequest("POST", "/v1/embeddings", strings.NewReader(body))
+ w := httptest.NewRecorder()
+ r.handleEmbed(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("got %d, want 400; body=%q", w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "media[1]") {
+ t.Errorf("400 body should name media[1], got %q", w.Body.String())
+ }
+ })
+
+ t.Run("valid base64 reaches runner then 501s", func(t *testing.T) {
+ r := &Runner{Model: &stubEmbeddingModel{}, EmbedRequests: make(chan EmbeddingRequest, 1)}
+ // Drain the channel in the background and run the current 501 stub.
+ go func() {
+ for req := range r.EmbedRequests {
+ _ = r.runEmbed(req.Ctx, req)
+ }
+ }()
+ body := `{"content":"hi","media":["aGVsbG8="]}`
+ req := httptest.NewRequest("POST", "/v1/embeddings", strings.NewReader(body))
+ w := httptest.NewRecorder()
+ r.handleEmbed(w, req)
+ if w.Code != http.StatusNotImplemented {
+ t.Fatalf("got %d, want 501; body=%q", w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "media embedding not supported") {
+ t.Errorf("501 body should say media is not supported, got %q", w.Body.String())
+ }
+ })
+
+ t.Run("no media flows through untouched", func(t *testing.T) {
+ r := &Runner{Model: &stubEmbeddingModel{}, EmbedRequests: make(chan EmbeddingRequest, 1)}
+ captured := make(chan EmbeddingRequest, 1)
+ go func() {
+ for req := range r.EmbedRequests {
+ captured <- req
+ req.EmbedResponses <- EmbedResponse{Embedding: []float32{0}, PromptEvalCount: 1}
+ }
+ }()
+ body := `{"content":"hi"}`
+ req := httptest.NewRequest("POST", "/v1/embeddings", strings.NewReader(body))
+ w := httptest.NewRecorder()
+ r.handleEmbed(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("got %d, want 200; body=%q", w.Code, w.Body.String())
+ }
+ select {
+ case got := <-captured:
+ if len(got.Media) != 0 {
+ t.Errorf("expected empty Media, got %d entries", len(got.Media))
+ }
+ case <-time.After(time.Second):
+ t.Fatal("runner consumer never received request")
+ }
+ })
+}
+
+// miniEmbedTokenizer builds the smallest BPE tokenizer runEmbed can drive:
+// byte-level, no merges, lowercase letters + space, BOS=0 EOS=1.
+func miniEmbedTokenizer(t *testing.T) *tokenizer.Tokenizer {
+ t.Helper()
+ var sb strings.Builder
+ sb.WriteString(`{"model": {"type": "BPE", "vocab": {`)
+ id := 0
+ add := func(s string) {
+ if id > 0 {
+ sb.WriteString(", ")
+ }
+ fmt.Fprintf(&sb, "%q: %d", s, id)
+ id++
+ }
+ add("<bos>")
+ add("<eos>")
+ for c := 'a'; c <= 'z'; c++ {
+ add(string(c))
+ }
+ add(" ")
+ add("<img_placeholder>") // id 29: reserved ID so tests can distinguish placeholder rows
+ sb.WriteString(`}, "merges": []}}`)
+ tok, err := tokenizer.LoadFromBytesWithConfig([]byte(sb.String()), &tokenizer.TokenizerConfig{
+ GenerationConfigJSON: []byte(`{"bos_token_id": 0, "eos_token_id": 1}`),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ return tok
+}
+
+// stubEmbedMediaModel is a stubEmbeddingModel that also implements the embedMedia
+// surface runEmbed dispatchers on. Placeholder expansion: each image segment
+// becomes one token per entry of placeholderTokens. The Forward capture lets
+// tests assert the runner spliced media at the right positions.
+type stubEmbedMediaModel struct {
+ stubEmbeddingModel
+
+ lastBatch *batch.Batch
+ prepared *model.PreparedRequest
+ // runEmbed scopes the forward: batch arrays are freed at scope exit,
+ // so the stub materializes its captures as CPU data instead.
+ capturedTokens []int32
+ capturedMedia []batch.MediaItem
+}
+
+const (
+ stubPlaceholderToken = 29 // <img_placeholder> in miniEmbedTokenizer's vocab
+ stubPlaceholdersN = 2
+)
+
+func (s *stubEmbedMediaModel) MediaTokenStrings() (boi, eoi, image, boa, eoa, audio string) {
+ return "<boi>", "<eoi>", "<img>", "<boa>", "<eoa>", "<aud>"
+}
+
+func (s *stubEmbedMediaModel) SupportsImages() bool { return true }
+func (s *stubEmbedMediaModel) SupportsAudio() bool { return false }
+
+func (s *stubEmbedMediaModel) PrepareMedia(segments []model.Segment) (*model.PreparedRequest, error) {
+ prepared := &model.PreparedRequest{}
+ for _, seg := range segments {
+ switch seg.Kind {
+ case "":
+ prepared.Tokens = append(prepared.Tokens, seg.Tokens...)
+ case "image":
+ start := len(prepared.Tokens)
+ for range stubPlaceholdersN {
+ prepared.Tokens = append(prepared.Tokens, stubPlaceholderToken)
+ }
+ prepared.Items = append(prepared.Items, model.PreparedItem{
+ Range: [2]int{start, start + stubPlaceholdersN},
+ Source: 0,
+ })
+ default:
+ return nil, fmt.Errorf("unsupported segment kind %q", seg.Kind)
+ }
+ }
+ s.prepared = prepared
+ return prepared, nil
+}
+
+func (s *stubEmbedMediaModel) EncodeMedia(prepared *model.PreparedRequest) ([]batch.MediaItem, error) {
+ items := make([]batch.MediaItem, len(prepared.Items))
+ for i, item := range prepared.Items {
+ rows := item.Range[1] - item.Range[0]
+ vals := make([]float32, rows*s.EmbeddingDim())
+ for j := range vals {
+ vals[j] = float32((j*13)%31) / 31
+ }
+ items[i] = batch.MediaItem{
+ Seq: 0,
+ Pos: item.Range[0],
+ Features: mlx.FromValues(vals, rows, s.EmbeddingDim()),
+ }
+ }
+ return items, nil
+}
+
+func (s *stubEmbedMediaModel) Forward(b *batch.Batch, _ []cache.Cache) (*mlx.Array, *mlx.Array) {
+ s.lastBatch = b
+ // Scope-safe capture: runEmbed frees the batch's arrays at scope exit,
+ // so copy what the assertions need as CPU data now.
+ ids := b.InputIDs.AsType(mlx.DTypeInt32)
+ mlx.Eval(ids)
+ s.capturedTokens = append(s.capturedTokens[:0], ids.Ints()...)
+ for _, item := range b.Media {
+ cp := item
+ cp.Features = nil // shapes are captured separately below
+ s.capturedMedia = append(s.capturedMedia, cp)
+ }
+ L := b.InputIDs.Dim(1)
+ D := s.EmbeddingDim()
+ vals := make([]float32, L*D)
+ for i := range vals {
+ vals[i] = float32((i*7)%29) / 29
+ }
+ return mlx.FromValues(vals, 1, L, D), nil
+}
+
+// pngSniff passable blob: only the 8-byte PNG magic is checked runner-side.
+var stubPNG = []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n', 0, 0, 0, 0}
+
+// TestEmbedMediaRunEmbedExercises covers the media branch of runEmbed end to
+// end with a stub embedMedia model: a marker-less caller text plus image blob
+// must reach Forward with BOS + caller tokens + one placeholder run + EOS, at
+// the position the runner computed. Placeholder expansion per blob is now
+// unconditional; caller text is never scanned for markers.
+func TestEmbedMediaRunEmbedExercises(t *testing.T) {
+ tok := miniEmbedTokenizer(t)
+
+ t.Run("marker-less text plus one image blob", func(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ m := &stubEmbedMediaModel{}
+ r := &Runner{Model: m, Tokenizer: tok}
+ req := EmbeddingRequest{
+ Content: "ab",
+ Media: [][]byte{stubPNG},
+ EmbedResponses: make(chan EmbedResponse, 1),
+ Ctx: context.Background(),
+ }
+ if err := r.runEmbed(req.Ctx, req); err != nil {
+ t.Fatalf("runEmbed: %v", err)
+ }
+ resp := <-req.EmbedResponses
+ if resp.Error != nil {
+ t.Fatalf("unexpected error: %+v", resp.Error)
+ }
+ if len(resp.Embedding) != m.EmbeddingDim() {
+ t.Fatalf("embedding len %d, want %d", len(resp.Embedding), m.EmbeddingDim())
+ }
+
+ if m.prepared == nil || len(m.prepared.Items) != 1 {
+ t.Fatalf("PrepareMedia items = %+v, want exactly one", m.prepared)
+ }
+ if m.lastBatch == nil {
+ t.Fatal("model Forward was never called")
+ }
+ if len(m.capturedMedia) != 1 {
+ t.Fatalf("Forward batch Media len %d, want 1", len(m.capturedMedia))
+ }
+ item := m.capturedMedia[0]
+ // The prepared tokens carry the placeholder run at item.Range;
+ // the batch's media Pos must point at that run's start, offset by
+ // the BOS token the runner prepends.
+ rng := m.prepared.Items[0].Range
+ wantPos := rng[0] + 1 // +1 for BOS
+ if item.Pos != wantPos {
+ t.Errorf("media Pos = %d, want %d (placeholder start after BOS)", item.Pos, wantPos)
+ }
+ // The token stream reaching Forward must be exactly BOS + prepared
+ // tokens + EOS, with the placeholder IDs at the media position.
+ // (Captured as CPU data inside the stub: runEmbed frees the batch
+ // arrays at scope exit.)
+ gotToks := m.capturedTokens
+ wantLen := 1 + len(m.prepared.Tokens) + 1 // BOS + prepared + EOS
+ if len(gotToks) != wantLen {
+ t.Fatalf("forward token len %d, want %d", len(gotToks), wantLen)
+ }
+ for i := rng[0]; i < rng[1]; i++ {
+ if gotToks[i+1] != stubPlaceholderToken {
+ t.Errorf("token at placeholder %d = %d, want %d", i+1, gotToks[i+1], stubPlaceholderToken)
+ }
+ }
+ if gotToks[0] != tok.BOS() {
+ t.Errorf("first token %d, want BOS %d", gotToks[0], tok.BOS())
+ }
+ if gotToks[len(gotToks)-1] != tok.EOS() {
+ t.Errorf("last token %d, want EOS %d", gotToks[len(gotToks)-1], tok.EOS())
+ }
+ // Feature rows must equal the placeholder-run length. runEmbed
+ // frees the feature arrays at scope exit, so the stub captured
+ // only CPU data; assert the run length it was sliced from.
+ if got := rng[1] - rng[0]; got != stubPlaceholdersN {
+ t.Errorf("placeholder run %d, want %d", got, stubPlaceholdersN)
+ }
+ })
+ })
+}
+
+// TestRunEmbedMediaNotSupported: a runner model that implements
+// EmbeddingDim but not embedMedia must 501 a media request (the wire-level
+// twin of this gate is already covered in TestEmbedMediaWireDecode).
+func TestEmbedMediaRunEmbedNotSupported(t *testing.T) {
+ r := &Runner{Model: &stubEmbeddingModel{}, Tokenizer: miniEmbedTokenizer(t)}
+ req := EmbeddingRequest{
+ Content: "a<boi><eoi>b",
+ Media: [][]byte{stubPNG},
+ EmbedResponses: make(chan EmbedResponse, 1),
+ Ctx: context.Background(),
+ }
+ if err := r.runEmbed(req.Ctx, req); err != nil {
+ t.Fatalf("runEmbed: %v", err)
+ }
+ resp := <-req.EmbedResponses
+ if resp.Error == nil || resp.Error.StatusCode != http.StatusNotImplemented {
+ t.Fatalf("resp = %+v, want 501", resp)
+ }
+ if !strings.Contains(resp.Error.ErrorMessage, "media embedding not supported") {
+ t.Errorf("501 body %q, want 'media embedding not supported'", resp.Error.ErrorMessage)
+ }
+}
+
+// TestMeanPoolAndNormalize checks the ST module chain's math directly: mean
+// over the first seqLen token rows (pads excluded), then L2.
+func TestMeanPoolAndNormalize(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ // rows = [[1,0],[3,0],[99,99]] L=3 D=2, seqLen=2 → mean = [2,0], L2 → [1,0]
+ rows := mlx.FromValues([]float32{1, 0, 3, 0, 99, 99}, 3, 2)
+ got := meanPoolAndNormalize(rows, 2)
+ if len(got) != 2 {
+ t.Fatalf("len %d, want 2", len(got))
+ }
+ if got[0] < 0.9999 || got[1] > 1e-4 {
+ t.Errorf("got %v, want ~[1, 0]", got)
+ }
+ })
+}
+
+// stubLongEmbedModel raises MaxContextLength so the token-count gate passes
+// and the allocation pre-flight is what fires. Forward returns a minimal
+// real hidden state so the unguarded path completes (and the test's
+// assertion fires) when the gate is absent.
+type stubLongEmbedModel struct{ stubEmbeddingModel }
+
+func (s *stubLongEmbedModel) MaxContextLength() int { return 1 << 24 }
+
+func (s *stubLongEmbedModel) Forward(b *batch.Batch, _ []cache.Cache) (*mlx.Array, *mlx.Array) {
+ L := b.InputIDs.Dim(1)
+ h := mlx.Zeros(mlx.DTypeFloat32, len(b.SeqOffsets), L, 1)
+ return h, h
+}
+
+// TestRunEmbedRejectsOversizedAllocation: a token count whose predicted
+// allocations exceed the capacity budget must 413 BEFORE any forward work —
+// the failure mode that used to panic at metal::malloc.
+func TestRunEmbedRejectsOversizedAllocation(t *testing.T) {
+ tok := miniEmbedTokenizer(t)
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ r := &Runner{Model: &stubLongEmbedModel{}, Tokenizer: tok}
+
+ // Token count guaranteeing predicted > budget: solve
+ // L*L*4 > budget for L (mask dominates).
+ budget := EmbedCapacityBudget()
+ L := int(math.Sqrt(float64(budget)/4)) + 64
+ content := strings.Repeat("ab ", L/2+1) // ~L tokens for this vocab
+
+ req := EmbeddingRequest{
+ Content: content,
+ EmbedResponses: make(chan EmbedResponse, 1),
+ Ctx: context.Background(),
+ }
+ if err := r.runEmbed(req.Ctx, req); err != nil {
+ t.Fatalf("runEmbed: %v", err)
+ }
+ resp := <-req.EmbedResponses
+ if resp.Error == nil {
+ t.Fatal("oversized request produced no error")
+ }
+ if resp.Error.StatusCode != http.StatusRequestEntityTooLarge {
+ t.Errorf("status = %d, want 413; msg=%q", resp.Error.StatusCode, resp.Error.ErrorMessage)
+ }
+ if !strings.Contains(resp.Error.ErrorMessage, "would allocate") {
+ t.Errorf("message should name the allocation: %q", resp.Error.ErrorMessage)
+ }
+
+ // A small request on the same runner still succeeds — the gate does
+ // not wedge the runner after a rejection.
+ ok := EmbeddingRequest{
+ Content: "hello",
+ EmbedResponses: make(chan EmbedResponse, 1),
+ Ctx: context.Background(),
+ }
+ if err := r.runEmbed(ok.Ctx, ok); err != nil {
+ t.Fatalf("runEmbed after reject: %v", err)
+ }
+ okResp := <-ok.EmbedResponses
+ if okResp.Error != nil {
+ t.Errorf("small request failed after rejection: %+v", okResp.Error)
+ }
+ })
+}
+
+// TestPredictedEmbedAllocationBytes pins the dominant-allocation formula:
+// attention mask B*L*L + hidden output [1,L,D] + token row, all float32.
+func TestPredictedEmbedAllocationBytes(t *testing.T) {
+ tests := []struct {
+ name string
+ tok int
+ hid int32
+ want int64 // exact value for the formula
+ }{
+ {"empty", 0, 512, 0},
+ {"tiny", 8, 512, int64(8*8*4 + 8*512*4 + 8*4)},
+ {"300tok mteb shape", 300, 512, int64(300*300*4 + 300*512*4 + 300*4)},
+ }
+ for _, tt := range tests {
+ if got := PredictedEmbedAllocationBytes(tt.tok, tt.hid); got != tt.want {
+ t.Errorf("%s: got %d, want %d", tt.name, got, tt.want)
+ }
+ }
+ if got := PredictedEmbedAllocationBytes(-5, 512); got != 0 {
+ t.Errorf("negative tokens: got %d, want 0", got)
+ }
+}
+
+// TestEmbedCapacityBudget must always return a usable positive budget with a
+// live MLX device: its recommended working set halved for transient headroom.
+// Without a device the function falls back to a constant; CI boxes have no
+// MLX dylib, so SkipIfUnavailable short-circuits before any cgo call.
+func TestEmbedCapacityBudget(t *testing.T) {
+ mlxtest.SkipIfUnavailable(t)
+
+ b := EmbedCapacityBudget()
+ if b <= 0 {
+ t.Fatalf("budget %d, want > 0", b)
+ }
+ if limit, err := mlx.MaxRecommendedWorkingSetSize(); err == nil && limit > 0 {
+ if want := int64(float64(limit) * embedBudgetFraction); b != want {
+ t.Errorf("budget = %d, want working set %d * fraction = %d", b, limit, want)
+ }
+ }
+}
diff --git a/mlxrunner/model/architectures/architectures.go b/mlxrunner/model/architectures/architectures.go
index b7c6a452b..45127dc14 100644
--- a/mlxrunner/model/architectures/architectures.go
+++ b/mlxrunner/model/architectures/architectures.go
@@ -5,6 +5,7 @@ import (
_ "github.com/ollama/ollama/mlxrunner/model/cohere2_moe"
_ "github.com/ollama/ollama/mlxrunner/model/dflash"
_ "github.com/ollama/ollama/mlxrunner/model/gemma4"
+ _ "github.com/ollama/ollama/mlxrunner/model/gemma4embedding"
_ "github.com/ollama/ollama/mlxrunner/model/glimmer"
_ "github.com/ollama/ollama/mlxrunner/model/glm4_moe_lite"
_ "github.com/ollama/ollama/mlxrunner/model/laguna"
diff --git a/mlxrunner/model/gemma4/audio.go b/mlxrunner/model/gemma4/audio.go
index 0c8d89561..1dcdc680d 100644
--- a/mlxrunner/model/gemma4/audio.go
+++ b/mlxrunner/model/gemma4/audio.go
@@ -159,11 +159,23 @@ func (m *Model) loadAudioWeights(tensors map[string]*mlx.Array, linears model.Li
if m.Audio.unified() {
return m.loadUnifiedAudioWeights(tensors, linears)
}
- a := m.Audio
- root, err := audioWeightRoot(tensors)
+ tower, proj, err := LoadAudioTower(tensors, m.Audio, linears)
if err != nil {
return err
}
+ m.AudioTower = tower
+ m.EmbedAudio = proj
+ return nil
+}
+
+// LoadAudioTower loads the gemma4_audio conformer tower and its embed_audio
+// projection from the tensor map. The projection stays separate from the
+// tower so the caller decides where to keep it.
+func LoadAudioTower(tensors map[string]*mlx.Array, a *AudioConfig, linears model.LinearFactory) (tower *AudioTower, proj *MultimodalEmbedder, err error) {
+ root, err := audioWeightRoot(tensors)
+ if err != nil {
+ return nil, nil, err
+ }
at := root + "audio_tower."
requiredNorm := func(name string) (*mlx.Array, error) {
@@ -174,7 +186,7 @@ func (m *Model) loadAudioWeights(tensors map[string]*mlx.Array, linears model.Li
return w, nil
}
- tower := &AudioTower{
+ tower = &AudioTower{
SubsampleConv: make([]*AudioSubsampleConv, 2),
Layers: make([]*AudioLayer, a.NumHiddenLayers),
}
@@ -182,17 +194,17 @@ func (m *Model) loadAudioWeights(tensors map[string]*mlx.Array, linears model.Li
sp := fmt.Sprintf("%ssubsample_conv_projection.layer%d.", at, i)
conv := tensors[sp+"conv.weight"]
if conv == nil {
- return fmt.Errorf("missing audio weight: %sconv.weight", sp)
+ return nil, nil, fmt.Errorf("missing audio weight: %sconv.weight", sp)
}
norm, err := requiredNorm(sp + "norm.weight")
if err != nil {
- return err
+ return nil, nil, err
}
// Conv weights arrive [out, in, kH, kW]; mlx wants channels last.
tower.SubsampleConv[i] = &AudioSubsampleConv{Conv: mlx.Transpose(conv, 0, 2, 3, 1), Norm: norm}
}
if tower.InputProj, err = makeClippableLinear(linears, tensors, at+"subsample_conv_projection.input_proj_linear"); err != nil {
- return err
+ return nil, nil, err
}
table := audioRelPosTable(a)
@@ -213,39 +225,39 @@ func (m *Model) loadAudioWeights(tensors map[string]*mlx.Array, linears model.Li
}{{layer.FFW1, "feed_forward1."}, {layer.FFW2, "feed_forward2."}} {
fp := lp + ffw.name
if ffw.f.PreNorm, err = requiredNorm(fp + "pre_layer_norm.weight"); err != nil {
- return err
+ return nil, nil, err
}
if ffw.f.Up, err = makeClippableLinear(linears, tensors, fp+"ffw_layer_1"); err != nil {
- return err
+ return nil, nil, err
}
if ffw.f.Down, err = makeClippableLinear(linears, tensors, fp+"ffw_layer_2"); err != nil {
- return err
+ return nil, nil, err
}
if ffw.f.PostNorm, err = requiredNorm(fp + "post_layer_norm.weight"); err != nil {
- return err
+ return nil, nil, err
}
}
attn := layer.Attention
if attn.QProj, err = makeClippableLinear(linears, tensors, lp+"self_attn.q_proj"); err != nil {
- return err
+ return nil, nil, err
}
if attn.KProj, err = makeClippableLinear(linears, tensors, lp+"self_attn.k_proj"); err != nil {
- return err
+ return nil, nil, err
}
if attn.VProj, err = makeClippableLinear(linears, tensors, lp+"self_attn.v_proj"); err != nil {
- return err
+ return nil, nil, err
}
if attn.Post, err = makeClippableLinear(linears, tensors, lp+"self_attn.post"); err != nil {
- return err
+ return nil, nil, err
}
perDimScale, err := requiredNorm(lp + "self_attn.per_dim_scale")
if err != nil {
- return err
+ return nil, nil, err
}
relProj, err := makeClippableLinear(linears, tensors, lp+"self_attn.relative_k_proj")
if err != nil {
- return err
+ return nil, nil, err
}
// The reference applies softplus and the rel-position projection in
// the checkpoint dtype and lifts the results to f32 with q.
@@ -257,49 +269,48 @@ func (m *Model) loadAudioWeights(tensors map[string]*mlx.Array, linears model.Li
lc := layer.LConv
if lc.PreNorm, err = requiredNorm(lp + "lconv1d.pre_layer_norm.weight"); err != nil {
- return err
+ return nil, nil, err
}
if lc.Start, err = makeClippableLinear(linears, tensors, lp+"lconv1d.linear_start"); err != nil {
- return err
+ return nil, nil, err
}
dw := tensors[lp+"lconv1d.depthwise_conv1d.weight"]
if dw == nil {
- return fmt.Errorf("missing audio weight: %slconv1d.depthwise_conv1d.weight", lp)
+ return nil, nil, fmt.Errorf("missing audio weight: %slconv1d.depthwise_conv1d.weight", lp)
}
lc.DWConv = mlx.Transpose(dw, 0, 2, 1)
if lc.ConvNorm, err = requiredNorm(lp + "lconv1d.conv_norm.weight"); err != nil {
- return err
+ return nil, nil, err
}
if lc.End, err = makeClippableLinear(linears, tensors, lp+"lconv1d.linear_end"); err != nil {
- return err
+ return nil, nil, err
}
if layer.PreAttnNorm, err = requiredNorm(lp + "norm_pre_attn.weight"); err != nil {
- return err
+ return nil, nil, err
}
if layer.PostAttnNorm, err = requiredNorm(lp + "norm_post_attn.weight"); err != nil {
- return err
+ return nil, nil, err
}
if layer.OutNorm, err = requiredNorm(lp + "norm_out.weight"); err != nil {
- return err
+ return nil, nil, err
}
tower.Layers[i] = layer
}
if tower.OutputProj, err = makeClippableLinear(linears, tensors, at+"output_proj"); err != nil {
- return err
+ return nil, nil, err
}
projection, err := makeClippableLinear(linears, tensors, root+"embed_audio.embedding_projection")
if err != nil {
- return err
+ return nil, nil, err
}
tower.ClipMin = mlx.FromValue(-a.GradientClipping).AsType(mlx.DTypeBFloat16)
tower.ClipMax = mlx.FromValue(a.GradientClipping).AsType(mlx.DTypeBFloat16)
- m.AudioTower = tower
- m.EmbedAudio = &MultimodalEmbedder{Projection: projection}
- return nil
+ proj = &MultimodalEmbedder{Projection: projection}
+ return tower, proj, nil
}
// loadUnifiedAudioWeights loads the encoder-free variant, whose only audio
@@ -331,7 +342,13 @@ func (t *AudioTower) clip(x *mlx.Array) *mlx.Array {
// over n frames: block b's context slot j holds frame b*chunk + j -
// (ContextLeft-1), attendable when it exists and lies within the window.
func (m *Model) audioAttentionMask(n int) *mlx.Array {
- a := m.Audio
+ return audioAttentionMask(n, m.Audio)
+}
+
+// audioAttentionMask builds the boolean [blocks, 1, chunk, context] mask
+// over n frames: block b's context slot j holds frame b*chunk + j -
+// (ContextLeft-1), attendable when it exists and lies within the window.
+func audioAttentionMask(n int, a *AudioConfig) *mlx.Array {
chunk, left, right := int(a.ChunkSize), int(a.ContextLeft-1), int(a.ContextRight)
ctx := chunk + left + right
blocks := (n + chunk - 1) / chunk
@@ -355,8 +372,7 @@ func (m *Model) audioAttentionMask(n int) *mlx.Array {
// audioContextIndices maps block b's context slot j to index b*chunk+j of
// the padded key/value sequence.
-func (m *Model) audioContextIndices(blocks int) *mlx.Array {
- a := m.Audio
+func audioContextIndices(blocks int, a *AudioConfig) *mlx.Array {
ctx := int(a.ChunkSize + a.ContextLeft - 1 + a.ContextRight)
idx := make([]int32, blocks*ctx)
for b := range blocks {
@@ -483,8 +499,12 @@ func (l *AudioLayer) Forward(t *AudioTower, h, mask, indices *mlx.Array, a *Audi
// encodeAudio runs the conformer over one chunk's [frames, melBins] log-mel
// features, returning the lazy [numTokens, hidden] features.
func (m *Model) encodeAudio(data *mlx.Array) *mlx.Array {
- a := m.Audio
- t := m.AudioTower
+ return m.AudioTower.Encode(data, m.Audio, m.EmbedAudio)
+}
+
+// Encode runs the conformer over one chunk's [frames, melBins] log-mel
+// features, returning the lazy [numTokens, hidden] features.
+func (t *AudioTower) Encode(data *mlx.Array, a *AudioConfig, proj *MultimodalEmbedder) *mlx.Array {
frames := data.Dim(0)
h := mlx.Reshape(data, 1, int32(frames), audioMelBins, 1).AsType(mlx.DTypeBFloat16)
@@ -497,15 +517,15 @@ func (m *Model) encodeAudio(data *mlx.Array) *mlx.Array {
h = mlx.Reshape(h, int32(n), int32(w*c))
h = t.InputProj.Forward(h)
- mask := m.audioAttentionMask(n)
- indices := m.audioContextIndices((n + int(a.ChunkSize) - 1) / int(a.ChunkSize))
+ mask := audioAttentionMask(n, a)
+ indices := audioContextIndices((n+int(a.ChunkSize)-1)/int(a.ChunkSize), a)
for _, layer := range t.Layers {
h = layer.Forward(t, h, mask, indices, a)
}
h = t.OutputProj.Forward(h)
h = mlx.RMSNormFn(h, nil, a.RMSNormEps)
- return m.EmbedAudio.Projection.Forward(h)
+ return proj.Projection.Forward(h)
}
// encodeUnifiedAudio projects raw waveform frames straight into the text
diff --git a/mlxrunner/model/gemma4/gemma4.go b/mlxrunner/model/gemma4/gemma4.go
index 48fa0a8c9..2c50fc281 100644
--- a/mlxrunner/model/gemma4/gemma4.go
+++ b/mlxrunner/model/gemma4/gemma4.go
@@ -547,6 +547,14 @@ func parseTextConfig(configData []byte) (TextConfig, error) {
cfg.FullRopeDims = int(cfg.HeadDim) // default: full rotation
cfg.FullRopeBase = 1000000
+ for lt, rp := range cfg.RopeParameters {
+ switch rp.RopeType {
+ case "", "default", "proportional":
+ default:
+ return TextConfig{}, fmt.Errorf("unsupported rope_type %q for %s", rp.RopeType, lt)
+ }
+ }
+
if rp := cfg.RopeParameters; rp != nil {
if sp := rp["sliding_attention"]; sp != nil && sp.RopeTheta > 0 {
cfg.SlidingRopeBase = sp.RopeTheta
diff --git a/mlxrunner/model/gemma4/media.go b/mlxrunner/model/gemma4/media.go
index d50612149..b1c2ef966 100644
--- a/mlxrunner/model/gemma4/media.go
+++ b/mlxrunner/model/gemma4/media.go
@@ -179,16 +179,16 @@ func (m *Model) PrepareMedia(segments []model.Segment) (*model.PreparedRequest,
// A chunk's MediaData rows are mel frames for the conformer
// and one raw waveform frame per soft token for the unified
// embedder.
- var chunks []audioChunk
+ var chunks []AudioChunk
if m.Audio.unified() {
frames, tokens, err := processUnifiedAudio(seg.Data, int(m.Audio.SamplesPerToken))
if err != nil {
return nil, err
}
- chunks = []audioChunk{{data: frames, frames: tokens, numTokens: tokens}}
+ chunks = []AudioChunk{{Data: frames, Frames: tokens, NumTokens: tokens}}
} else {
var err error
- if chunks, err = processAudio(seg.Data); err != nil {
+ if chunks, err = ProcessAudio(seg.Data); err != nil {
return nil, err
}
}
@@ -196,15 +196,15 @@ func (m *Model) PrepareMedia(segments []model.Segment) (*model.PreparedRequest,
prepared.Tokens = append(prepared.Tokens, m.MM.BOATokenID)
for _, chunk := range chunks {
start := len(prepared.Tokens)
- for range chunk.numTokens {
+ for range chunk.NumTokens {
prepared.Tokens = append(prepared.Tokens, m.MM.AudioTokenID)
}
prepared.Items = append(prepared.Items, model.PreparedItem{
Range: [2]int{start, len(prepared.Tokens)},
Source: s,
- MediaData: chunk.data,
- Dims: []int{chunk.frames, len(chunk.data) / chunk.frames},
- Opaque: preparedAudio{numTokens: int32(chunk.numTokens)},
+ MediaData: chunk.Data,
+ Dims: []int{chunk.Frames, len(chunk.Data) / chunk.Frames},
+ Opaque: preparedAudio{numTokens: int32(chunk.NumTokens)},
Causal: true,
})
}
diff --git a/mlxrunner/model/gemma4/media_test.go b/mlxrunner/model/gemma4/media_test.go
index 1bcb3332a..389d4bc5d 100644
--- a/mlxrunner/model/gemma4/media_test.go
+++ b/mlxrunner/model/gemma4/media_test.go
@@ -80,6 +80,12 @@ func TestParseMultimodalConfig(t *testing.T) {
if textOnly.VisionConfig != nil {
t.Fatal("text-only checkpoint grew a vision config")
}
+ if err := ValidateVisionSoftTokenBudget(280); err != nil {
+ t.Fatal(err)
+ }
+ if err := ValidateVisionSoftTokenBudget(300); err == nil {
+ t.Fatal("budget 300 accepted")
+ }
}
func visionTestModel() *Model {
diff --git a/mlxrunner/model/gemma4/multimodal_export_test.go b/mlxrunner/model/gemma4/multimodal_export_test.go
new file mode 100644
index 000000000..2ff8f6cf8
--- /dev/null
+++ b/mlxrunner/model/gemma4/multimodal_export_test.go
@@ -0,0 +1,31 @@
+package gemma4
+
+import "testing"
+
+// VisionSoftTokenBudget: explicit override wins, otherwise the default 280.
+func TestVisionSoftTokenBudgetFreeFunction(t *testing.T) {
+ cfg := &VisionConfig{ModelType: "gemma4_vision"}
+ if got := VisionSoftTokenBudget(0, cfg); got != 280 {
+ t.Errorf("default: %d, want 280", got)
+ }
+ if got := VisionSoftTokenBudget(70, cfg); got != 70 {
+ t.Errorf("override: %d, want 70", got)
+ }
+ if got := VisionSoftTokenBudget(1120, cfg); got != 1120 {
+ t.Errorf("override: %d, want 1120", got)
+ }
+}
+
+// ValidateVisionSoftTokenBudget accepts only the reference processor's set.
+func TestValidateVisionSoftTokenBudget(t *testing.T) {
+ for _, want := range []int32{70, 140, 280, 560, 1120} {
+ if err := ValidateVisionSoftTokenBudget(want); err != nil {
+ t.Errorf("budget %d rejected", want)
+ }
+ }
+ for _, bad := range []int32{0, 71, 300, 1121} {
+ if err := ValidateVisionSoftTokenBudget(bad); err == nil {
+ t.Errorf("budget %d accepted", bad)
+ }
+ }
+}
diff --git a/mlxrunner/model/gemma4/process_audio.go b/mlxrunner/model/gemma4/process_audio.go
index 225060fba..3ec5ee83d 100644
--- a/mlxrunner/model/gemma4/process_audio.go
+++ b/mlxrunner/model/gemma4/process_audio.go
@@ -26,18 +26,25 @@ const (
audioChunkSeconds = 30
)
-// audioChunk is one span of the clip: its encoder input rows — log-mel
+// AudioChunk is one span of the clip: its encoder input rows — log-mel
// frames for the conformer, one raw waveform frame per soft token for the
// unified embedder — and the soft-token count they reduce to.
-type audioChunk struct {
- data []float32 // [frames, len/frames]
- frames int
- numTokens int
+type AudioChunk struct {
+ Data []float32 // [frames, len/frames]
+ Frames int
+ NumTokens int
}
// processAudio decodes an audio container into per-chunk log-mel features,
// resampled to 16 kHz.
-func processAudio(data []byte) ([]audioChunk, error) {
+func processAudio(data []byte) ([]AudioChunk, error) {
+ return ProcessAudio(data)
+}
+
+// ProcessAudio decodes an audio container into per-chunk log-mel features,
+// resampled to 16 kHz. Clips longer than 30 s split into independent chunks
+// of at most 30 s, one soft-token run each.
+func ProcessAudio(data []byte) ([]AudioChunk, error) {
samples, rate, err := audio.Decode(data)
if err != nil {
return nil, err
@@ -49,14 +56,14 @@ func processAudio(data []byte) ([]audioChunk, error) {
return nil, errors.New("audio too short")
}
- var chunks []audioChunk
+ var chunks []AudioChunk
for _, chunk := range audio.Split(samples, audioSampleRate, audioChunkSeconds) {
mel, frames := melSpectrogram(chunk)
tokens := frames
for range 2 {
tokens = (tokens-1)/2 + 1
}
- chunks = append(chunks, audioChunk{data: mel, frames: frames, numTokens: tokens})
+ chunks = append(chunks, AudioChunk{Data: mel, Frames: frames, NumTokens: tokens})
}
return chunks, nil
}
diff --git a/mlxrunner/model/gemma4/process_audio_test.go b/mlxrunner/model/gemma4/process_audio_test.go
index 4cfdb6161..f1bc62e16 100644
--- a/mlxrunner/model/gemma4/process_audio_test.go
+++ b/mlxrunner/model/gemma4/process_audio_test.go
@@ -86,15 +86,15 @@ func TestProcessAudioTokenCounts(t *testing.T) {
}
for i, c := range chunks {
if tt.frames[i] < 0 {
- if c.frames <= 0 || c.frames > 2999 || c.numTokens > 750 {
- t.Errorf("chunk %d: frames %d tokens %d exceed one 30 s chunk", i, c.frames, c.numTokens)
+ if c.Frames <= 0 || c.Frames > 2999 || c.NumTokens > 750 {
+ t.Errorf("chunk %d: frames %d tokens %d exceed one 30 s chunk", i, c.Frames, c.NumTokens)
}
- } else if c.frames != tt.frames[i] || c.numTokens != tt.tokens[i] {
+ } else if c.Frames != tt.frames[i] || c.NumTokens != tt.tokens[i] {
t.Errorf("chunk %d: frames %d tokens %d, want %d %d",
- i, c.frames, c.numTokens, tt.frames[i], tt.tokens[i])
+ i, c.Frames, c.NumTokens, tt.frames[i], tt.tokens[i])
}
- if len(c.data) != c.frames*audioMelBins {
- t.Errorf("chunk %d: %d mel values for %d frames", i, len(c.data), c.frames)
+ if len(c.Data) != c.Frames*audioMelBins {
+ t.Errorf("chunk %d: %d mel values for %d frames", i, len(c.Data), c.Frames)
}
}
})
diff --git a/mlxrunner/model/gemma4/process_image.go b/mlxrunner/model/gemma4/process_image.go
index f7d10b4a2..99a82a81b 100644
--- a/mlxrunner/model/gemma4/process_image.go
+++ b/mlxrunner/model/gemma4/process_image.go
@@ -81,32 +81,50 @@ func dynamicVisionTargetSize(height, width int, patch, pool int32) (int32, int32
// preprocessImage decodes and prepares one image: aspect-preserving
// resize, rescale to [0,1], and patchify. The [-1,1] normalization stays
// in the patch embedder, so pixels here match the reference
-// pixel_values.
+// pixel_values. Budget 0 selects the dynamic per-image resolution the
+// generative path uses (#18603).
func (m *Model) preprocessImage(data []byte) (pixels []float32, positions []int32, geom ImageGeometry, err error) {
+ return ProcessImage(data, m.Vision, 0)
+}
+
+// ProcessImage decodes and prepares one image: aspect-preserving
+// resize, rescale to [0,1], and patchify under the given per-image
+// soft-token budget. The [-1,1] normalization stays in the patch
+// embedder, so pixels here match the reference pixel_values.
+func ProcessImage(data []byte, cfg *VisionConfig, softTokenBudget int32) (pixels []float32, positions []int32, geom ImageGeometry, err error) {
img, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
return nil, nil, ImageGeometry{}, fmt.Errorf("decode image: %w", err)
}
- patch, pool := m.Vision.PatchSize, m.Vision.PoolingKernelSize
+ patch, pool := cfg.PatchSize, cfg.PoolingKernelSize
bounds := img.Bounds()
- targetH, targetW, err := dynamicVisionTargetSize(bounds.Dy(), bounds.Dx(), patch, pool)
+ // A declared budget fixes the resize grid (the embedding models'
+ // reference processor resizes to the budget's grid, not the closest
+ // fit); budget 0 keeps the dynamic per-image selection the generative
+ // path uses (#18603).
+ var targetH, targetW int32
+ if softTokenBudget > 0 {
+ targetH, targetW, err = visionTargetSize(bounds.Dy(), bounds.Dx(), patch, pool, softTokenBudget)
+ } else {
+ targetH, targetW, err = dynamicVisionTargetSize(bounds.Dy(), bounds.Dx(), patch, pool)
+ }
if err != nil {
return nil, nil, ImageGeometry{}, err
}
positionPatch := patch
- if m.Vision.unified() {
+ if cfg.unified() {
positionPatch *= pool
}
- if int(max(targetH, targetW)/positionPatch) > m.Vision.positionEmbeddingSize {
- return nil, nil, ImageGeometry{}, fmt.Errorf("image patch grid exceeds vision position embedding size %d", m.Vision.positionEmbeddingSize)
+ if int(max(targetH, targetW)/positionPatch) > cfg.positionEmbeddingSize {
+ return nil, nil, ImageGeometry{}, fmt.Errorf("image patch grid exceeds vision position embedding size %d", cfg.positionEmbeddingSize)
}
img = dropAlpha(img, bounds)
resized := image.NewRGBA(image.Rect(0, 0, int(targetW), int(targetH)))
draw.CatmullRom.Scale(resized, resized.Bounds(), img, bounds, draw.Src, nil)
- if m.Vision.unified() {
+ if cfg.unified() {
// One raster patch of pool*patchSize pixels per soft token: the
// reference merge rearranges its intermediate 16px patches back
// into this layout, with positions on the merged grid.
diff --git a/mlxrunner/model/gemma4/process_image_test.go b/mlxrunner/model/gemma4/process_image_test.go
new file mode 100644
index 000000000..650e53d86
--- /dev/null
+++ b/mlxrunner/model/gemma4/process_image_test.go
@@ -0,0 +1,50 @@
+package gemma4
+
+import (
+ "bytes"
+ "image"
+ "image/png"
+ "testing"
+)
+
+// TestProcessImageHonorsDeclaredBudget pins the resize contract: a
+// declared soft-token budget fixes the grid (the embedding reference
+// processor, max_soft_tokens=280 for embeddinggemma2, resizes every image
+// to the budget's grid), while budget 0 keeps the dynamic per-image
+// selection the generative path uses (#18603). The dynamic sweep
+// regressed embeddings to the closest-fit grid — a 320x240 photo went
+// from the reference's 280 soft tokens to 63, costing 0.02-0.04 cosine
+// vs sentence-transformers.
+func TestProcessImageHonorsDeclaredBudget(t *testing.T) {
+ cfg := &VisionConfig{
+ ModelType: "gemma4_vision",
+ PatchSize: 2,
+ PoolingKernelSize: 1,
+ RMSNormEps: 1e-6,
+ }
+ cfg.positionEmbeddingSize = 10240
+
+ // 64x64 discriminates the two policies: the declared 70-budget grid
+ // is 8x8 patches (64 soft tokens); dynamic selection upscales to the
+ // largest covering grid (33x33 patches, 1089 soft tokens).
+ var buf bytes.Buffer
+ if err := png.Encode(&buf, image.NewRGBA(image.Rect(0, 0, 64, 64))); err != nil {
+ t.Fatal(err)
+ }
+
+ _, _, fixed, err := ProcessImage(buf.Bytes(), cfg, 70)
+ if err != nil {
+ t.Fatalf("ProcessImage budget 70: %v", err)
+ }
+ if fixed.NumSoftTokens != 64 {
+ t.Errorf("budget 70: soft tokens = %d, want 64 (the declared grid)", fixed.NumSoftTokens)
+ }
+
+ _, _, dyn, err := ProcessImage(buf.Bytes(), cfg, 0)
+ if err != nil {
+ t.Fatalf("ProcessImage budget 0: %v", err)
+ }
+ if dyn.NumSoftTokens != 1089 {
+ t.Errorf("budget 0 (dynamic): soft tokens = %d, want 1089 (largest covering grid)", dyn.NumSoftTokens)
+ }
+}
diff --git a/mlxrunner/model/gemma4/vision.go b/mlxrunner/model/gemma4/vision.go
index 872069778..538b88754 100644
--- a/mlxrunner/model/gemma4/vision.go
+++ b/mlxrunner/model/gemma4/vision.go
@@ -3,6 +3,7 @@ package gemma4
import (
"fmt"
"math"
+ "slices"
"strings"
"github.com/ollama/ollama/mlx"
@@ -35,6 +36,21 @@ func (v *VisionConfig) unified() bool {
return v.ModelType == "gemma4_unified_vision"
}
+// visionSoftTokenBudgets are the soft-token counts the reference processor
+// supports; the budget fixes the patch budget as budget*pooling².
+var visionSoftTokenBudgets = []int32{70, 140, 280, 560, 1120}
+
+// VisionSoftTokenBudget returns the per-image soft-token budget: the caller's
+// explicit override when set, else the default 280 (the budget the EAP
+// embeddinggemma-2 config ships in vision_soft_tokens_per_image).
+func VisionSoftTokenBudget(softTokensPerImage int32, cfg *VisionConfig) int32 {
+ if softTokensPerImage > 0 {
+ return softTokensPerImage
+ }
+ _ = cfg // held for future "read from config" without breaking callers
+ return 280
+}
+
// VisionTower is the Gemma 4 image encoder: a bidirectional transformer over
// patch embeddings with 2D positions, pooled 3x3 into soft tokens.
type VisionTower struct {
@@ -88,12 +104,24 @@ func (m *Model) loadVisionWeights(tensors map[string]*mlx.Array, linears model.L
if m.Vision.unified() {
return m.loadUnifiedVisionWeights(tensors, linears)
}
- root, err := visionWeightRoot(tensors)
+ tower, proj, err := LoadVisionTower(tensors, m.Vision, linears)
if err != nil {
return err
}
+ m.VisionTower = tower
+ m.EmbedVision = proj
+ return nil
+}
+
+// LoadVisionTower loads the gemma4_vision transformer tower and its
+// embed_vision projection from the tensor map. The projection stays separate
+// from the tower so the caller decides where to keep it.
+func LoadVisionTower(tensors map[string]*mlx.Array, v *VisionConfig, linears model.LinearFactory) (tower *VisionTower, proj *MultimodalEmbedder, err error) {
+ root, err := visionWeightRoot(tensors)
+ if err != nil {
+ return nil, nil, err
+ }
vt := root + "vision_tower."
- v := m.Vision
requiredNorm := func(name string) (*mlx.Array, error) {
w := tensors[name]
@@ -105,13 +133,19 @@ func (m *Model) loadVisionWeights(tensors map[string]*mlx.Array, linears model.L
inputProj, err := makeClippableLinear(linears, tensors, vt+"patch_embedder.input_proj")
if err != nil {
- return err
+ return nil, nil, err
}
table := tensors[vt+"patch_embedder.position_embedding_table"]
if table == nil {
- return fmt.Errorf("missing vision weight: %spatch_embedder.position_embedding_table", vt)
+ return nil, nil, fmt.Errorf("missing vision weight: %spatch_embedder.position_embedding_table", vt)
}
- tower := &VisionTower{
+ // process_image bounds the patch grid against the position table's
+ // capacity; without this every image fails the grid check. The table
+ // is [2, positions, hidden] (x and y rows), so capacity is Dim(1).
+ if v.positionEmbeddingSize == 0 {
+ v.positionEmbeddingSize = table.Dim(1)
+ }
+ tower = &VisionTower{
PatchEmbedder: &PatchEmbedder{InputProj: inputProj, PositionEmbeddingTable: table},
Layers: make([]*VisionLayer, v.NumHiddenLayers),
}
@@ -121,65 +155,63 @@ func (m *Model) loadVisionWeights(tensors map[string]*mlx.Array, linears model.L
layer := &VisionLayer{Attention: &VisionAttention{}, MLP: &MLP{}}
if layer.InputNorm, err = requiredNorm(lp + "input_layernorm.weight"); err != nil {
- return err
+ return nil, nil, err
}
if layer.PostAttnNorm, err = requiredNorm(lp + "post_attention_layernorm.weight"); err != nil {
- return err
+ return nil, nil, err
}
if layer.PreFFNorm, err = requiredNorm(lp + "pre_feedforward_layernorm.weight"); err != nil {
- return err
+ return nil, nil, err
}
if layer.PostFFNorm, err = requiredNorm(lp + "post_feedforward_layernorm.weight"); err != nil {
- return err
+ return nil, nil, err
}
if layer.Attention.QNorm, err = requiredNorm(lp + "self_attn.q_norm.weight"); err != nil {
- return err
+ return nil, nil, err
}
if layer.Attention.KNorm, err = requiredNorm(lp + "self_attn.k_norm.weight"); err != nil {
- return err
+ return nil, nil, err
}
if layer.Attention.QProj, err = makeClippableLinear(linears, tensors, lp+"self_attn.q_proj"); err != nil {
- return err
+ return nil, nil, err
}
if layer.Attention.KProj, err = makeClippableLinear(linears, tensors, lp+"self_attn.k_proj"); err != nil {
- return err
+ return nil, nil, err
}
if layer.Attention.VProj, err = makeClippableLinear(linears, tensors, lp+"self_attn.v_proj"); err != nil {
- return err
+ return nil, nil, err
}
if layer.Attention.OProj, err = makeClippableLinear(linears, tensors, lp+"self_attn.o_proj"); err != nil {
- return err
+ return nil, nil, err
}
if layer.MLP.GateProj, err = makeClippableLinear(linears, tensors, lp+"mlp.gate_proj"); err != nil {
- return err
+ return nil, nil, err
}
if layer.MLP.UpProj, err = makeClippableLinear(linears, tensors, lp+"mlp.up_proj"); err != nil {
- return err
+ return nil, nil, err
}
if layer.MLP.DownProj, err = makeClippableLinear(linears, tensors, lp+"mlp.down_proj"); err != nil {
- return err
+ return nil, nil, err
}
tower.Layers[i] = layer
}
if v.Standardize {
if tower.StdBias, err = requiredNorm(vt + "std_bias"); err != nil {
- return err
+ return nil, nil, err
}
if tower.StdScale, err = requiredNorm(vt + "std_scale"); err != nil {
- return err
+ return nil, nil, err
}
}
projection, err := makeClippableLinear(linears, tensors, root+"embed_vision.embedding_projection")
if err != nil {
- return err
+ return nil, nil, err
}
- m.VisionTower = tower
- m.EmbedVision = &MultimodalEmbedder{Projection: projection}
- v.positionEmbeddingSize = table.Dim(1)
- return nil
+ proj = &MultimodalEmbedder{Projection: projection}
+ return tower, proj, nil
}
// loadUnifiedVisionWeights loads the encoder-free embedder. Its projections
@@ -332,15 +364,20 @@ func (a *VisionAttention) Forward(x *mlx.Array, cosX, sinX, cosY, sinY *mlx.Arra
// encodeImage runs the tower over one whole image. One image per call, no
// padding; the graph is lazy and evaluates with the consuming forward.
func (m *Model) encodeImage(pixels *mlx.Array, positions []int32, geom ImageGeometry) *mlx.Array {
- v := m.Vision
+ return m.VisionTower.Encode(pixels, positions, geom, m.Vision, m.EmbedVision)
+}
+
+// Encode runs the tower over one whole image. One image per call, no
+// padding; the graph is lazy and evaluates with the consuming forward.
+func (t *VisionTower) Encode(pixels *mlx.Array, positions []int32, geom ImageGeometry, v *VisionConfig, proj *MultimodalEmbedder) *mlx.Array {
n := geom.PatchesH * geom.PatchesW
// The processor rescales to [0,1]; the reference folds the [-1,1]
// normalization into the patch embedder, in f32 before the cast.
x := mlx.MulScalar(mlx.AddScalar(pixels, -0.5), 2).AsType(mlx.DTypeBFloat16)
- h := m.VisionTower.PatchEmbedder.InputProj.Forward(x)
+ h := t.PatchEmbedder.InputProj.Forward(x)
- table := m.VisionTower.PatchEmbedder.PositionEmbeddingTable
+ table := t.PatchEmbedder.PositionEmbeddingTable
for axis := range 2 {
pos := make([]int32, n)
for i := range int(n) {
@@ -354,7 +391,7 @@ func (m *Model) encodeImage(pixels *mlx.Array, positions []int32, geom ImageGeom
cosX, sinX := visionRopeTables(positions, 0, n, v.HeadDim, v.RopeTheta)
cosY, sinY := visionRopeTables(positions, 1, n, v.HeadDim, v.RopeTheta)
- for _, l := range m.VisionTower.Layers {
+ for _, l := range t.Layers {
x1 := mlx.RMSNormFn(h, l.InputNorm, v.RMSNormEps)
attn := l.Attention.Forward(x1, cosX, sinX, cosY, sinY, n, v)
h = mlx.Add(h, mlx.RMSNormFn(attn, l.PostAttnNorm, v.RMSNormEps))
@@ -373,11 +410,20 @@ func (m *Model) encodeImage(pixels *mlx.Array, positions []int32, geom ImageGeom
f = mlx.Reshape(f, n/(pool*pool), v.HiddenSize)
f = f.AsType(mlx.DTypeBFloat16).AsType(mlx.DTypeFloat32)
f = mlx.MulScalar(f, float32(math.Sqrt(float64(v.HiddenSize))))
- if m.VisionTower.StdBias != nil {
- f = mlx.Mul(mlx.Sub(f, m.VisionTower.StdBias.AsType(mlx.DTypeFloat32)), m.VisionTower.StdScale.AsType(mlx.DTypeFloat32))
+ if t.StdBias != nil {
+ f = mlx.Mul(mlx.Sub(f, t.StdBias.AsType(mlx.DTypeFloat32)), t.StdScale.AsType(mlx.DTypeFloat32))
}
f = f.AsType(mlx.DTypeBFloat16)
f = mlx.RMSNormFn(f, nil, v.RMSNormEps)
- return m.EmbedVision.Projection.Forward(f)
+ return proj.Projection.Forward(f)
+}
+
+// ValidateVisionSoftTokenBudget reports whether the budget is one the
+// reference processor supports.
+func ValidateVisionSoftTokenBudget(budget int32) error {
+ if !slices.Contains(visionSoftTokenBudgets, budget) {
+ return fmt.Errorf("unsupported vision soft token budget %d", budget)
+ }
+ return nil
}
diff --git a/mlxrunner/model/gemma4embedding/forward.go b/mlxrunner/model/gemma4embedding/forward.go
new file mode 100644
index 000000000..fa87da173
--- /dev/null
+++ b/mlxrunner/model/gemma4embedding/forward.go
@@ -0,0 +1,310 @@
+package gemma4embedding
+
+import (
+ "fmt"
+ "log/slog"
+ "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/model/gemma4"
+ "github.com/ollama/ollama/mlxrunner/nn"
+)
+
+// preparedImage / preparedAudio are gemma4embedding's model-private media
+// state: PreparedItem.Opaque values round-tripped untouched from
+// PrepareMedia into Forward's scatter.
+type preparedImage struct {
+ positions []int32
+ geom gemma4.ImageGeometry
+}
+
+type preparedAudio struct {
+ numTokens int32
+}
+
+// Forward runs the bidirectional encoder and returns (projected hidden,
+// unused aux). The returned hidden is [B, L, embedding_dim]: final RMSNorm
+// followed by the per-token embedding_projection. Pooling and L2
+// normalization are the runner pipeline's job.
+func (m *Model) Forward(b *batch.Batch, caches []cache.Cache) (hidden, auxHidden *mlx.Array) {
+ dims := b.InputIDs.Dims()
+ B, L := int32(dims[0]), int32(dims[1])
+ positions := mlx.FromValues(b.SeqOffsets, len(b.SeqOffsets))
+
+ h := m.EmbedTokens.Forward(b.InputIDs)
+ h = mlx.MulScalar(h, m.Cfg.EmbedScale)
+
+ if len(b.Media) > 0 {
+ if scattered, err := m.scatterMedia(h, b); err != nil {
+ // Forward has no error return on model.Model; misconfigured
+ // media means the request itself is bad, and runEmbed
+ // validates before reaching here. A leftover nil-Features
+ // entry is the only realistic path and is a no-op.
+ slog.Error("gemma4embedding media scatter", "error", err)
+ } else {
+ h = scattered
+ }
+ }
+
+ var perLayerInputs *mlx.Array
+ if m.Cfg.HiddenSizePerLayer > 0 {
+ perLayerInputs = m.computePLEInputs(h, B, L)
+ }
+
+ slidingMask, fullMask := m.buildMasks(b)
+
+ for i, layer := range m.Layers {
+ var pleInput *mlx.Array
+ if perLayerInputs != nil {
+ pleInput = sliceLayerDim(perLayerInputs, int32(i), B, L, m.Cfg.HiddenSizePerLayer)
+ }
+
+ mask := fullMask
+ if layer.IsSliding {
+ mask = slidingMask
+ }
+
+ h = layer.Forward(h, b, positions, B, L, m.Cfg, pleInput, mask)
+ }
+
+ out := mlx.RMSNormFn(h, m.NormScaled, m.Cfg.RMSNormEps)
+ out = m.EmbeddingProjection.Forward(out)
+ return out, nil
+}
+
+// Unembed is unused for embedding models; the runner taps Forward output
+// directly. Implemented to satisfy model.Model.
+func (m *Model) Unembed(x *mlx.Array) *mlx.Array { return x }
+
+// buildMasks returns the per-layer-type masks. Embeddings are bidirectional:
+// full layers return the zero mask (SDPA composes padding itself), sliding
+// layers attend |q-kv| <= sliding_window+1 inclusive — the reference does
+// config.sliding_window + 1 (modeling_embedding_gemma2) over an inclusive
+// abs() overlay (masking_utils).
+func (m *Model) buildMasks(b *batch.Batch) (sliding, full nn.AttentionMask) {
+ window := int(m.Cfg.SlidingWindow) + 1
+ return BidirectionalSlidingWindowMask(b, window, mlx.DTypeFloat32), nn.AttentionMask{}
+}
+
+// BidirectionalSlidingWindowMask returns an additive [B, 1, L, L] mask that
+// blocks keys k for query q when |q-k| > window; window is the inclusive
+// max attended distance. Padding columns are left to SDPA's kLens handling.
+func BidirectionalSlidingWindowMask(b *batch.Batch, window int, dtype mlx.DType) nn.AttentionMask {
+ if window <= 0 {
+ return nn.AttentionMask{}
+ }
+ B := len(b.SeqOffsets)
+ L := b.InputIDs.Dim(1)
+
+ // If every row is short enough that no pair exceeds the window, the
+ // mask is all-attending: skip materializing it.
+ needed := false
+ for i := range B {
+ if int(b.SeqQueryLens[i]) > window {
+ needed = true
+ break
+ }
+ }
+ if !needed {
+ return nn.AttentionMask{}
+ }
+
+ negInf := float32(math.Inf(-1))
+ vals := make([]float32, B*L*L)
+ for i := range B {
+ qlen := int(b.SeqQueryLens[i])
+ base := i * L * L
+ for q := range qlen {
+ row := base + q*L
+ for k := range qlen {
+ d := q - k
+ if d < 0 {
+ d = -d
+ }
+ if d > window {
+ vals[row+k] = negInf
+ }
+ }
+ }
+ }
+ out := mlx.FromValues(vals, B, 1, L, L)
+ if dtype != mlx.DTypeFloat32 {
+ out = out.AsType(dtype)
+ }
+ return nn.ArrayMask(out)
+}
+
+// Forward runs one decoder layer: attn residual, MLP residual, PLE
+// injection (projection-only), then the trained per-layer scalar.
+func (l *DecoderLayer) Forward(x *mlx.Array, b *batch.Batch, positions *mlx.Array, B, L int32, cfg *Config, pleInput *mlx.Array, mask nn.AttentionMask) *mlx.Array {
+ tc := &cfg.TextConfig
+ normed := mlx.RMSNormFn(x, l.InputNormScaled, tc.RMSNormEps)
+ attnOut := l.Attention.Forward(normed, b, positions, B, L, l, cfg, mask)
+ attnOut = mlx.RMSNormFn(attnOut, l.PostAttnNormScaled, tc.RMSNormEps)
+ h := mlx.Add(x, attnOut)
+
+ normed = mlx.RMSNormFn(h, l.PreFFNormScaled, tc.RMSNormEps)
+ mlpOut := l.MLP.Forward(normed)
+ mlpOut = mlx.RMSNormFn(mlpOut, l.PostFFNormScaled, tc.RMSNormEps)
+ h = mlx.Add(h, mlpOut)
+
+ if l.PLE != nil && pleInput != nil {
+ residual := h
+ gated := mlx.GELUApprox(l.PLE.InputGate.Forward(h))
+ gated = mlx.Mul(gated, pleInput)
+ projected := l.PLE.Projection.Forward(gated)
+ projected = mlx.RMSNormFn(projected, l.PLE.PostNormScaled, tc.RMSNormEps)
+ h = mlx.Add(residual, projected)
+ }
+
+ h = mlx.Mul(h, l.LayerScalar)
+
+ return h
+}
+
+func (a *Attention) Forward(x *mlx.Array, b *batch.Batch, positions *mlx.Array, B, L int32, layer *DecoderLayer, cfg *Config, mask nn.AttentionMask) *mlx.Array {
+ tc := &cfg.TextConfig
+ headDim := tc.layerHeadDim(layer.LayerIdx)
+ kvHeads := tc.layerKVHeads(layer.LayerIdx)
+
+ q := a.QProj.Forward(x)
+ q = mlx.Reshape(q, B, L, tc.NumAttentionHeads, headDim)
+ q = mlx.Transpose(q, 0, 2, 1, 3)
+ q = mlx.RMSNormFn(q, a.QNormScaled, tc.RMSNormEps)
+
+ k := a.KProj.Forward(x)
+ k = mlx.Reshape(k, B, L, kvHeads, headDim)
+ k = mlx.Transpose(k, 0, 2, 1, 3)
+
+ v := a.VProj.Forward(x)
+ v = mlx.Reshape(v, B, L, kvHeads, headDim)
+ v = mlx.Transpose(v, 0, 2, 1, 3)
+
+ k = mlx.RMSNormFn(k, a.KNormScaled, tc.RMSNormEps)
+
+ ropeBase := cfg.FullRopeBase
+ ropeDims := cfg.FullRopeDims
+ if layer.IsSliding {
+ ropeBase = cfg.SlidingRopeBase
+ ropeDims = int(headDim)
+ }
+ q = mlx.RoPEWithFreqs(q, ropeDims, false, ropeBase, 1.0, positions, nil)
+ k = mlx.RoPEWithFreqs(k, ropeDims, false, ropeBase, 1.0, positions, nil)
+
+ // Weightless V RMS norm (scale-free in the checkpoint).
+ v = mlx.RMSNormFn(v, nil, tc.RMSNormEps)
+
+ out := nn.ScaledDotProductAttention(b, q, 1.0, nn.WithKV(k, v, b.SeqQueryLens), nn.WithMask(mask))
+ out = mlx.Reshape(mlx.Transpose(out, 0, 2, 1, 3), B, L, tc.NumAttentionHeads*headDim)
+ return a.OProj.Forward(out)
+}
+
+// Forward runs the GELU-tanh MLP.
+func (m *MLP) Forward(x *mlx.Array) *mlx.Array {
+ gate := m.GateProj.Forward(x)
+ up := m.UpProj.Forward(x)
+ return m.DownProj.Forward(mlx.GeGLU(gate, up))
+}
+
+// computePLEInputs builds per-layer inputs for the projection-only PLE:
+// per_layer_model_projection of the input hidden, scaled, normed, then
+// reshaped to [B, L, NumLayers, HiddenSizePerLayer].
+func (m *Model) computePLEInputs(h *mlx.Array, B, L int32) *mlx.Array {
+ tc := &m.Cfg.TextConfig
+ pleProj := m.PerLayerModelProj.Forward(h)
+ pleProj = mlx.MulScalar(pleProj, float32(1.0/math.Sqrt(float64(tc.HiddenSize))))
+ pleProj = mlx.Reshape(pleProj, B, L, tc.NumHiddenLayers, tc.HiddenSizePerLayer)
+ return mlx.RMSNormFn(pleProj, m.PerLayerProjNormWeight, tc.RMSNormEps)
+}
+
+// sliceLayerDim extracts a single layer's PLE input from the combined
+// [B, L, NumLayers, HiddenSizePerLayer] tensor.
+func sliceLayerDim(combined *mlx.Array, layerIdx, B, L, pleDim int32) *mlx.Array {
+ sliced := mlx.SliceStartStop(combined,
+ []int32{0, 0, layerIdx, 0},
+ []int32{B, L, layerIdx + 1, pleDim},
+ )
+ return mlx.Squeeze(sliced, 2)
+}
+
+// scatterMedia writes the tower-encoded features into the placeholder rows
+// the runner spliced into InputIDs. Embedding forward is a single bidirectional
+// pass over the whole request, so gemma4's chunk-window bookkeeping reduces
+// to direct row replacement; nil Features means the item arrived without
+// preprocessing (a caller bug) and is skipped.
+func (m *Model) scatterMedia(h *mlx.Array, b *batch.Batch) (*mlx.Array, error) {
+ for i, item := range b.Media {
+ if item.Features == nil {
+ continue
+ }
+ if item.Seq != 0 {
+ return h, fmt.Errorf("media item %d: seq %d, embed pipeline sends exactly one row", i, item.Seq)
+ }
+ var rows int
+ switch p := item.Opaque.(type) {
+ case preparedAudio:
+ rows = int(p.numTokens)
+ case preparedImage:
+ rows = int(p.geom.NumSoftTokens)
+ default:
+ return h, fmt.Errorf("media item %d: unknown opaque %T", i, item.Opaque)
+ }
+ if got := item.Features.Dim(0); got != rows {
+ return h, fmt.Errorf("media item %d: features rows %d, want %d", i, got, rows)
+ }
+ if item.Pos+rows > int(b.SeqQueryLens[0]) {
+ return h, fmt.Errorf("media item %d: [%d,%d) runs past the query tail %d", i, item.Pos, item.Pos+rows, b.SeqQueryLens[0])
+ }
+ feat := mlx.Reshape(item.Features.AsType(h.DType()), 1, int32(rows), m.Cfg.HiddenSize)
+ h = h.SliceUpdate(feat, mlx.Slice(0, 1), mlx.Slice(item.Pos, item.Pos+rows), mlx.Slice())
+ }
+ return h, nil
+}
+
+// encodePreparedItem runs the right tower over one PreparedItem's
+// preprocessed data. Called from the runner before Forward so the tower
+// graph is built while the request-goroutine's preprocess values are still
+// in scope; the array stays lazy until the text forward pulls it.
+func (m *Model) encodePreparedItem(item *model.PreparedItem, data *mlx.Array) (*mlx.Array, error) {
+ switch p := item.Opaque.(type) {
+ case preparedImage:
+ if m.VisionTower == nil {
+ return nil, fmt.Errorf("model has no vision tower")
+ }
+ return m.VisionTower.Encode(data, p.positions, p.geom, m.Cfg.VisionConfig, m.EmbedVision), nil
+ case preparedAudio:
+ if m.AudioTower == nil {
+ return nil, fmt.Errorf("model has no audio tower")
+ }
+ return m.AudioTower.Encode(data, m.Cfg.AudioConfig, m.EmbedAudio), nil
+ }
+ return nil, fmt.Errorf("unknown prepared media opaque %T", item.Opaque)
+}
+
+// EncodeMedia is the runner's single entry point after PrepareMedia: walk
+// the prepared items, run each through its tower, and attach the lazy
+// feature arrays to the batch. Kept separate from scatterMedia so the batch
+// stays a pure description of token positions.
+func (m *Model) EncodeMedia(prepared *model.PreparedRequest) ([]batch.MediaItem, error) {
+ if len(prepared.Items) == 0 {
+ return nil, nil
+ }
+ items := make([]batch.MediaItem, len(prepared.Items))
+ for i, item := range prepared.Items {
+ data := mlx.FromValues(item.MediaData, item.Dims...)
+ feat, err := m.encodePreparedItem(&item, data)
+ if err != nil {
+ return nil, fmt.Errorf("media item %d: %w", i, err)
+ }
+ items[i] = batch.MediaItem{
+ Seq: 0,
+ Pos: item.Range[0],
+ Features: feat,
+ Opaque: item.Opaque,
+ }
+ }
+ return items, nil
+}
diff --git a/mlxrunner/model/gemma4embedding/gemma4embedding.go b/mlxrunner/model/gemma4embedding/gemma4embedding.go
new file mode 100644
index 000000000..ac260f036
--- /dev/null
+++ b/mlxrunner/model/gemma4embedding/gemma4embedding.go
@@ -0,0 +1,727 @@
+// Package gemma4embedding implements the Gemma4Embedding (EmbeddingGemma v2)
+// text embedding model for MLX.
+//
+// Unlike the generative Gemma 4, every layer attends bidirectionally:
+// full_attention layers are padding-mask-only and sliding_attention layers
+// use a symmetric ±window/2 band. There is no KV cache and no lm_head —
+// the output head is an in-model embedding_projection applied per token.
+// Pooling and L2 normalization happen in the runner pipeline, matching
+// sentence-transformers' 1_Pooling + 2_Normalize modules.
+package gemma4embedding
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "math"
+ "strings"
+
+ "github.com/ollama/ollama/mlx"
+ "github.com/ollama/ollama/mlxrunner/cache"
+ "github.com/ollama/ollama/mlxrunner/model"
+ "github.com/ollama/ollama/mlxrunner/model/gemma4"
+ "github.com/ollama/ollama/mlxrunner/nn"
+ "github.com/ollama/ollama/mlxrunner/tokenizer"
+)
+
+func init() {
+ model.Register("EmbeddingGemma2Model", newModel)
+}
+
+var _ model.Model = (*Model)(nil)
+
+// Attention scaling is 1.0: q/k RMS norms handle magnitude control.
+
+// RopeParams holds per-layer-type RoPE settings.
+type RopeParams struct {
+ PartialRotaryFactor float32 `json:"partial_rotary_factor"`
+ RopeTheta float32 `json:"rope_theta"`
+ RopeType string `json:"rope_type"`
+}
+
+// PerLayerConfig is the per-layer-type override table keyed by layer index
+// as a string ("05", "11", ...) in config.json.
+type PerLayerConfig struct {
+ HeadDim int32 `json:"head_dim"`
+ NumKeyValueHeads int32 `json:"num_key_value_heads"`
+}
+
+// Config is the Gemma4Embedding config; the text stack lives under
+// text_config.
+type Config struct {
+ Architectures []string `json:"architectures"`
+ EmbeddingDimensions []int `json:"embedding_dimensions"`
+
+ TextConfig `json:"text_config"`
+
+ // Multimodal subtrees. Every embeddinggemma-2 checkpoint carries both
+ // blocks regardless of which towers the safetensors blob actually
+ // contains, so tensor presence — not config presence — decides whether
+ // a tower is loaded.
+ VisionConfig *gemma4.VisionConfig `json:"vision_config"`
+ AudioConfig *gemma4.AudioConfig `json:"audio_config"`
+
+ // Media token IDs and the per-image soft-token budget the embed
+ // pipeline splices into the token stream. eoa falls back to the
+ // eoa_token_index spelling some checkpoints use (same as gemma4).
+ ImageTokenID int32 `json:"image_token_id"`
+ AudioTokenID int32 `json:"audio_token_id"`
+ BOITokenID int32 `json:"boi_token_id"`
+ EOITokenID int32 `json:"eoi_token_id"`
+ BOATokenID int32 `json:"boa_token_id"`
+ EOATokenID int32 `json:"eoa_token_id"`
+ EOATokenIndex int32 `json:"eoa_token_index"`
+ VisionSoftTokensPerImage int32 `json:"vision_soft_tokens_per_image"`
+
+ // Token strings for the bracket markers and soft placeholders; filled
+ // in parseConfig so the runner can expand user text that names one.
+ TokenStrings MediaTokenStrings `json:"-"`
+
+ // Quantization parameters (populated at load).
+ QuantGroupSize int `json:"-"`
+ QuantBits int `json:"-"`
+ QuantMode string `json:"-"`
+ TensorQuant map[string]*model.TensorQuantInfo `json:"-"`
+
+ // Computed fields.
+ EmbedScale float32 `json:"-"` // sqrt(hidden_size)
+ SlidingRopeBase float32 `json:"-"`
+ FullRopeBase float32 `json:"-"`
+ FullRopeDims int `json:"-"` // rotary rank for full layers (head_dim of full layers)
+}
+
+// MediaTokenStrings are the tokenizer spellings of the media marker and
+// placeholder tokens; the runner expands these in user content before
+// tokenizing.
+type MediaTokenStrings struct {
+ BOI, EOI, Image string
+ BOA, EOA, Audio string
+}
+
+type TextConfig struct {
+ HiddenSize int32 `json:"hidden_size"`
+ NumHiddenLayers int32 `json:"num_hidden_layers"`
+ IntermediateSize int32 `json:"intermediate_size"`
+ NumAttentionHeads int32 `json:"num_attention_heads"`
+ NumKeyValueHeads int32 `json:"num_key_value_heads"`
+ HeadDim int32 `json:"head_dim"`
+ VocabSize int32 `json:"vocab_size"`
+ RMSNormEps float32 `json:"rms_norm_eps"`
+ MaxPositionEmbeddings int32 `json:"max_position_embeddings"`
+ SlidingWindow int32 `json:"sliding_window"`
+ LayerTypes []string `json:"layer_types"`
+ HiddenSizePerLayer int32 `json:"hidden_size_per_layer_input"`
+ VocabSizePerLayer int32 `json:"vocab_size_per_layer_input"`
+ EmbeddingDim int32 `json:"embedding_dim"`
+ RopeParameters map[string]*RopeParams `json:"rope_parameters"`
+ PerLayerConfig map[string]*PerLayerConfig `json:"per_layer_config"`
+ UseBidirectionalAttention string `json:"use_bidirectional_attention"`
+
+ // Computed.
+ PerLayerHeadDim map[int32]int32 `json:"-"` // layer -> head_dim override
+ PerLayerKVHeads map[int32]int32 `json:"-"` // layer -> num_key_value_heads override
+}
+
+func parseConfig(configData []byte) (*Config, error) {
+ var cfg Config
+ if err := json.Unmarshal(configData, &cfg); err != nil {
+ return nil, fmt.Errorf("parse config: %w", err)
+ }
+
+ tc := &cfg.TextConfig
+ if tc.HeadDim == 0 {
+ tc.HeadDim = 256
+ }
+ if tc.NumAttentionHeads == 0 {
+ tc.NumAttentionHeads = 4
+ }
+ if tc.NumKeyValueHeads == 0 {
+ tc.NumKeyValueHeads = 1
+ }
+ if tc.RMSNormEps == 0 {
+ tc.RMSNormEps = 1e-6
+ }
+
+ // vocab_size_per_layer_input is the token-identity half of PLE. We only
+ // implement the projection-only half (used when it's 0); HF combines both
+ // as (proj + identity) * 2^-0.5. Fail loudly for checkpoints that ship a
+ // non-zero value rather than emitting silently-wrong embeddings.
+ if tc.VocabSizePerLayer > 0 {
+ return nil, fmt.Errorf("vocab_size_per_layer_input > 0 (token-identity PLE) is not implemented; got %d", tc.VocabSizePerLayer)
+ }
+
+ // VisionConfig.RopeTheta is json:"-" (derived in gemma4's
+ // parseMultimodalConfig, which gemma4embedding does not call), so
+ // rebuild it here the same way: base 100, checkpoint override wins.
+ // The VisionTower.Encode RoPE tables consume it; leaving it zero would
+ // silently corrupt vision embeddings. Zero-field defaults for the
+ // remaining vision/audio config fields are NOT mirrored: the shipped
+ // embeddinggemma-2 configs populate them all.
+ if v := cfg.VisionConfig; v != nil && v.ModelType == "gemma4_vision" {
+ if v.HeadDim == 0 && v.NumAttentionHeads > 0 {
+ v.HeadDim = v.HiddenSize / v.NumAttentionHeads
+ }
+ v.RopeTheta = 100
+ if v.RopeParameters != nil && v.RopeParameters.RopeTheta > 0 {
+ v.RopeTheta = v.RopeParameters.RopeTheta
+ }
+ }
+
+ // The runner substitutes friendly spellings for the raw special-token
+ // text; both exist in embeddinggemma-2's vocab, and sentence-transformers
+ // accepts either (its prompt template emits the bracketed forms, while
+ // users typing into a curl payload reach the angle forms more easily).
+ cfg.TokenStrings = MediaTokenStrings{
+ BOI: "<|image>", EOI: "<image|>", Image: "<|image|>",
+ BOA: "<|audio>", EOA: "<audio|>", Audio: "<|audio|>",
+ }
+ if cfg.EOATokenID == 0 {
+ cfg.EOATokenID = cfg.EOATokenIndex
+ }
+
+ cfg.EmbedScale = float32(math.Sqrt(float64(tc.HiddenSize)))
+ cfg.SlidingRopeBase = 10000
+ cfg.FullRopeBase = 1000000
+ cfg.FullRopeDims = int(tc.HeadDim) // default; overridden per-layer in forward
+
+ // Per-layer overrides first: RoPE dims for full layers key off them.
+ tc.PerLayerHeadDim = make(map[int32]int32)
+ tc.PerLayerKVHeads = make(map[int32]int32)
+ for k, pl := range tc.PerLayerConfig {
+ if pl == nil {
+ continue
+ }
+ var idx int
+ if _, err := fmt.Sscanf(k, "%d", &idx); err != nil {
+ continue
+ }
+ if pl.HeadDim > 0 {
+ tc.PerLayerHeadDim[int32(idx)] = pl.HeadDim
+ }
+ if pl.NumKeyValueHeads > 0 {
+ tc.PerLayerKVHeads[int32(idx)] = pl.NumKeyValueHeads
+ }
+ }
+
+ for lt, rp := range tc.RopeParameters {
+ if rp.RopeType != "" && rp.RopeType != "default" {
+ return nil, fmt.Errorf("unsupported rope_type %q for %s", rp.RopeType, lt)
+ }
+ }
+
+ if rp := tc.RopeParameters; rp != nil {
+ if sp := rp["sliding_attention"]; sp != nil && sp.RopeTheta > 0 {
+ cfg.SlidingRopeBase = sp.RopeTheta
+ }
+ if fp := rp["full_attention"]; fp != nil && fp.RopeTheta > 0 {
+ cfg.FullRopeBase = fp.RopeTheta
+ }
+ }
+ cfg.FullRopeDims = int(tc.fullHeadDim())
+
+ return &cfg, nil
+}
+
+// fullHeadDim is the head_dim of full_attention layers, per the override
+// table (any full layer with an override; they all share one value in the
+// shipped configs).
+func (tc *TextConfig) fullHeadDim() int32 {
+ for i := range tc.NumHiddenLayers {
+ if tc.IsSliding(i) {
+ continue
+ }
+ if d, ok := tc.PerLayerHeadDim[i]; ok {
+ return d
+ }
+ }
+ return tc.HeadDim
+}
+
+func (tc *TextConfig) IsSliding(layer int32) bool {
+ if int(layer) < len(tc.LayerTypes) {
+ return tc.LayerTypes[layer] == "sliding_attention"
+ }
+ return false
+}
+
+func (tc *TextConfig) layerHeadDim(layer int32) int32 {
+ if d, ok := tc.PerLayerHeadDim[layer]; ok {
+ return d
+ }
+ return tc.HeadDim
+}
+
+func (tc *TextConfig) layerKVHeads(layer int32) int32 {
+ if h, ok := tc.PerLayerKVHeads[layer]; ok {
+ return h
+ }
+ return tc.NumKeyValueHeads
+}
+
+// Attention is the per-layer attention block with Q/K norms and a
+// weightless V norm.
+type Attention struct {
+ QProj, KProj, VProj, OProj nn.LinearLayer
+ QNorm, KNorm *nn.RMSNorm
+ QNormScaled, KNormScaled *mlx.Array
+}
+
+// MLP is the GELU-tanh feed-forward block.
+type MLP struct {
+ GateProj, UpProj, DownProj nn.LinearLayer
+}
+
+// PLELayer holds the per-layer PLE (per-layer embedding) weights.
+type PLELayer struct {
+ InputGate nn.LinearLayer
+ Projection nn.LinearLayer
+ PostNorm *nn.RMSNorm
+ PostNormScaled *mlx.Array
+}
+
+// DecoderLayer is a single transformer block.
+type DecoderLayer struct {
+ InputNorm, PostAttnNorm, PreFFNorm, PostFFNorm *nn.RMSNorm
+ Attention *Attention
+ MLP *MLP
+ PLE *PLELayer
+
+ InputNormScaled, PostAttnNormScaled *mlx.Array
+ PreFFNormScaled, PostFFNormScaled *mlx.Array
+
+ // LayerScalar multiplies the layer output (trained, e.g. 0.39/0.17 in
+ // the embeddinggemma-2 checkpoint — not all-ones).
+ LayerScalar *mlx.Array
+
+ IsSliding bool
+ LayerIdx int32
+}
+
+// Model is the Gemma4Embedding text tower + embedding projection, with
+// optional vision/audio towers for the multimodal checkpoints.
+type Model struct {
+ EmbedTokens nn.EmbeddingLayer
+ Layers []*DecoderLayer
+ Norm *nn.RMSNorm
+ EmbeddingProjection nn.LinearLayer
+
+ // Multimodal towers; nil unless the checkpoint carries their weights.
+ // The embedders hold the tower-to-text projection and are applied
+ // inside the towers' Encode methods.
+ VisionTower *gemma4.VisionTower
+ AudioTower *gemma4.AudioTower
+ EmbedVision *gemma4.MultimodalEmbedder
+ EmbedAudio *gemma4.MultimodalEmbedder
+
+ // Projection-only PLE (no per-layer embedding table when
+ // vocab_size_per_layer_input == 0).
+ PerLayerModelProj nn.LinearLayer
+ PerLayerProjNorm *nn.RMSNorm
+
+ NormScaled *mlx.Array
+ PerLayerProjNormWeight *mlx.Array
+
+ tok *tokenizer.Tokenizer
+
+ // Cfg must stay exported: mlx.Collect walks only exported fields.
+ Cfg *Config
+}
+
+func newModel(root *model.Root) (model.Model, error) {
+ configData, err := root.Manifest.ReadConfig("config.json")
+ if err != nil {
+ return nil, fmt.Errorf("load config: %w", err)
+ }
+
+ cfg, err := parseConfig(configData)
+ if err != nil {
+ return nil, err
+ }
+
+ if qt := root.QuantType(); qt != "" {
+ cfg.QuantGroupSize, cfg.QuantBits, cfg.QuantMode = model.QuantizationParams(qt)
+ if gs := root.GroupSize(); gs > 0 {
+ cfg.QuantGroupSize = gs
+ }
+ } else {
+ cfg.QuantGroupSize, cfg.QuantBits, cfg.QuantMode = model.QuantizationParams("")
+ }
+ cfg.TensorQuant = root.AllTensorQuant()
+
+ tokData, err := root.Manifest.ReadConfig("tokenizer.json")
+ if err != nil {
+ return nil, fmt.Errorf("load tokenizer config: %w", err)
+ }
+ tokConfig := &tokenizer.TokenizerConfig{ConfigJSON: configData}
+ if tokConfigData, err := root.Manifest.ReadConfig("tokenizer_config.json"); err == nil {
+ tokConfig.TokenizerConfigJSON = tokConfigData
+ }
+ tok, err := tokenizer.LoadFromBytesWithConfig(tokData, tokConfig)
+ if err != nil {
+ return nil, fmt.Errorf("parse tokenizer: %w", err)
+ }
+
+ return &Model{
+ Layers: make([]*DecoderLayer, cfg.NumHiddenLayers),
+ Cfg: cfg,
+ tok: tok,
+ }, nil
+}
+
+// resolveWeightPrefix finds the language_model prefix used by the safetensors
+// blob (with or without the "model." root that the HF class nesting adds).
+func resolveWeightPrefix(tensors map[string]*mlx.Array) string {
+ for _, prefix := range []string{"language_model.", "model.language_model.", ""} {
+ if tensors[prefix+"embed_tokens.weight"] != nil {
+ return prefix
+ }
+ }
+ return ""
+}
+
+func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
+ prefix := resolveWeightPrefix(tensors)
+ tc := &m.Cfg.TextConfig
+ linears := model.NewLinearFactory(tensors, m.Cfg.QuantGroupSize, m.Cfg.QuantBits, m.Cfg.QuantMode, m.Cfg.TensorQuant)
+
+ embedTokens := model.MakeEmbeddingLayer(tensors, prefix+"embed_tokens", m.Cfg.QuantGroupSize, m.Cfg.QuantBits, m.Cfg.QuantMode, m.Cfg.TensorQuant)
+ if embedTokens == nil {
+ return fmt.Errorf("missing embedding weight: %sembed_tokens.weight", prefix)
+ }
+ m.EmbedTokens = embedTokens
+
+ if w := tensors[prefix+"norm.weight"]; w != nil {
+ m.Norm = nn.NewRMSNorm(w, tc.RMSNormEps)
+ } else {
+ return fmt.Errorf("missing final norm weight: %snorm.weight", prefix)
+ }
+
+ // embedding_projection may sit alongside the language model (new
+ // checkpoint: language_model.embedding_projection) or one level above
+ // (older spelling: model.embedding_projection). Try both.
+ for _, cand := range []string{prefix + "embedding_projection", stringSuffix(prefix, "language_model.") + "embedding_projection"} {
+ if p := linears.Make(cand); p != nil {
+ m.EmbeddingProjection = p
+ break
+ }
+ }
+ if m.EmbeddingProjection == nil {
+ return fmt.Errorf("missing embedding_projection weight")
+ }
+
+ // Projection-only PLE. Current checkpoints nest the shared projection
+ // under .ple.*; older spellings kept it at .per_layer_*.
+ if tc.HiddenSizePerLayer > 0 {
+ m.PerLayerModelProj = linears.Make(prefix + "ple.per_layer_model_projection")
+ if m.PerLayerModelProj == nil {
+ m.PerLayerModelProj = linears.Make(prefix + "per_layer_model_projection")
+ }
+ if m.PerLayerModelProj == nil {
+ return fmt.Errorf("missing per_layer_model_projection weight")
+ }
+ if w := tensors[prefix+"ple.per_layer_projection_norm.weight"]; w != nil {
+ m.PerLayerProjNorm = nn.NewRMSNorm(w, tc.RMSNormEps)
+ } else if w := tensors[prefix+"per_layer_projection_norm.weight"]; w != nil {
+ m.PerLayerProjNorm = nn.NewRMSNorm(w, tc.RMSNormEps)
+ } else {
+ return fmt.Errorf("missing per_layer_projection_norm weight")
+ }
+ }
+
+ for i := range tc.NumHiddenLayers {
+ layerPrefix := fmt.Sprintf("%slayers.%d", prefix, i)
+ layer := &DecoderLayer{
+ LayerIdx: i,
+ IsSliding: tc.IsSliding(i),
+ Attention: &Attention{},
+ MLP: &MLP{},
+ }
+
+ if w := tensors[layerPrefix+".input_layernorm.weight"]; w != nil {
+ layer.InputNorm = nn.NewRMSNorm(w, tc.RMSNormEps)
+ }
+ if w := tensors[layerPrefix+".post_attention_layernorm.weight"]; w != nil {
+ layer.PostAttnNorm = nn.NewRMSNorm(w, tc.RMSNormEps)
+ }
+ if w := tensors[layerPrefix+".pre_feedforward_layernorm.weight"]; w != nil {
+ layer.PreFFNorm = nn.NewRMSNorm(w, tc.RMSNormEps)
+ }
+ if w := tensors[layerPrefix+".post_feedforward_layernorm.weight"]; w != nil {
+ layer.PostFFNorm = nn.NewRMSNorm(w, tc.RMSNormEps)
+ }
+
+ layer.Attention.QProj = linears.Make(layerPrefix + ".self_attn.q_proj")
+ layer.Attention.KProj = linears.Make(layerPrefix + ".self_attn.k_proj")
+ layer.Attention.VProj = linears.Make(layerPrefix + ".self_attn.v_proj")
+ layer.Attention.OProj = linears.Make(layerPrefix + ".self_attn.o_proj")
+ if w := tensors[layerPrefix+".self_attn.q_norm.weight"]; w != nil {
+ layer.Attention.QNorm = nn.NewRMSNorm(w, tc.RMSNormEps)
+ }
+ if w := tensors[layerPrefix+".self_attn.k_norm.weight"]; w != nil {
+ layer.Attention.KNorm = nn.NewRMSNorm(w, tc.RMSNormEps)
+ }
+
+ layer.MLP.GateProj = linears.Make(layerPrefix + ".mlp.gate_proj")
+ layer.MLP.UpProj = linears.Make(layerPrefix + ".mlp.up_proj")
+ layer.MLP.DownProj = linears.Make(layerPrefix + ".mlp.down_proj")
+
+ if w := tensors[layerPrefix+".layer_scalar"]; w != nil {
+ layer.LayerScalar = w
+ } else {
+ return fmt.Errorf("layer %d: missing layer_scalar", i)
+ }
+
+ if tc.HiddenSizePerLayer > 0 {
+ // Current checkpoints nest PLE under .ple_block.*; older
+ // spellings kept them flat at .per_layer_*.
+ layer.PLE = &PLELayer{
+ InputGate: linears.Make(layerPrefix + ".ple_block.per_layer_input_gate"),
+ Projection: linears.Make(layerPrefix + ".ple_block.per_layer_projection"),
+ }
+ if layer.PLE.InputGate == nil {
+ layer.PLE.InputGate = linears.Make(layerPrefix + ".per_layer_input_gate")
+ }
+ if layer.PLE.Projection == nil {
+ layer.PLE.Projection = linears.Make(layerPrefix + ".per_layer_projection")
+ }
+ if w := tensors[layerPrefix+".ple_block.post_per_layer_input_norm.weight"]; w != nil {
+ layer.PLE.PostNorm = nn.NewRMSNorm(w, tc.RMSNormEps)
+ } else if w := tensors[layerPrefix+".post_per_layer_input_norm.weight"]; w != nil {
+ layer.PLE.PostNorm = nn.NewRMSNorm(w, tc.RMSNormEps)
+ }
+ if layer.PLE.InputGate == nil || layer.PLE.Projection == nil || layer.PLE.PostNorm == nil {
+ return fmt.Errorf("layer %d: missing PLE weights", i)
+ }
+ }
+
+ if layer.InputNorm == nil || layer.PostAttnNorm == nil || layer.PreFFNorm == nil || layer.PostFFNorm == nil {
+ return fmt.Errorf("layer %d: missing norms", i)
+ }
+ if layer.Attention.QProj == nil || layer.Attention.KProj == nil || layer.Attention.VProj == nil || layer.Attention.OProj == nil {
+ return fmt.Errorf("layer %d: missing attention projections", i)
+ }
+ if layer.Attention.QNorm == nil || layer.Attention.KNorm == nil {
+ return fmt.Errorf("layer %d: missing q/k norms", i)
+ }
+ if layer.MLP.GateProj == nil || layer.MLP.UpProj == nil || layer.MLP.DownProj == nil {
+ return fmt.Errorf("layer %d: missing mlp projections", i)
+ }
+
+ m.Layers[i] = layer
+ }
+
+ if err := m.loadMediaTowers(tensors, linears); err != nil {
+ return err
+ }
+
+ m.precomputeScaledWeights()
+ return nil
+}
+
+// hasTensorsWithPrefix reports whether the tensor map carries any key under
+// a (possibly model.-rooted) subtree, e.g. "vision_tower.". Prefix scan
+// rather than a single sentinel because the caller needn't know which of
+// the root spellings the blob uses.
+func hasTensorsWithPrefix(tensors map[string]*mlx.Array, subtrees ...string) bool {
+ for k, v := range tensors {
+ if v == nil {
+ continue
+ }
+ for _, sub := range subtrees {
+ if strings.HasPrefix(k, sub) || strings.HasPrefix(k, "model."+sub) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+// loadMediaTowers loads the optional vision and audio towers. The tower
+// loaders re-derive the blob's root prefix themselves; here we only decide
+// presence. A tower's weights with a missing config subtree is a hard
+// error — embeddinggemma-2 checkpoints always ship both subtrees, so this
+// can only trip on a hand-built manifest.
+func (m *Model) loadMediaTowers(tensors map[string]*mlx.Array, linears model.LinearFactory) error {
+ if hasTensorsWithPrefix(tensors, "vision_tower.", "embed_vision.") {
+ if m.Cfg.VisionConfig == nil {
+ return fmt.Errorf("checkpoint carries vision_tower weights but config.json has no vision_config")
+ }
+ tower, proj, err := gemma4.LoadVisionTower(tensors, m.Cfg.VisionConfig, linears)
+ if err != nil {
+ return fmt.Errorf("load vision tower: %w", err)
+ }
+ m.VisionTower, m.EmbedVision = tower, proj
+ }
+ if hasTensorsWithPrefix(tensors, "audio_tower.", "embed_audio.") {
+ if m.Cfg.AudioConfig == nil {
+ return fmt.Errorf("checkpoint carries audio_tower weights but config.json has no audio_config")
+ }
+ tower, proj, err := gemma4.LoadAudioTower(tensors, m.Cfg.AudioConfig, linears)
+ if err != nil {
+ return fmt.Errorf("load audio tower: %w", err)
+ }
+ m.AudioTower, m.EmbedAudio = tower, proj
+ }
+ return nil
+}
+
+func stringSuffix(s, suffix string) string {
+ if len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix {
+ return s[:len(s)-len(suffix)]
+ }
+ return s
+}
+
+// precomputeScaledWeights assigns raw norm weights to the scaled fields
+// (Gemma 4 norms use scale_shift=0, so the raw weight is the scale).
+func (m *Model) precomputeScaledWeights() {
+ m.NormScaled = m.Norm.Weight
+ if m.PerLayerProjNorm != nil {
+ m.PerLayerProjNormWeight = m.PerLayerProjNorm.Weight
+ }
+ for _, l := range m.Layers {
+ l.InputNormScaled = l.InputNorm.Weight
+ l.PostAttnNormScaled = l.PostAttnNorm.Weight
+ l.PreFFNormScaled = l.PreFFNorm.Weight
+ l.PostFFNormScaled = l.PostFFNorm.Weight
+ l.Attention.QNormScaled = l.Attention.QNorm.Weight
+ l.Attention.KNormScaled = l.Attention.KNorm.Weight
+ if l.PLE != nil {
+ l.PLE.PostNormScaled = l.PLE.PostNorm.Weight
+ }
+ }
+}
+
+func (m *Model) Tokenizer() *tokenizer.Tokenizer { return m.tok }
+
+// maxContextLength is the vendor-validated context window. The checkpoint
+// config declares 262144 max_position_embeddings because the RoPE math
+// machinery is sound out to that span (it's the Gemma 4 backbone's default),
+// but the model itself is trained and evaluated at 8K. The 8192 cap gates
+// the runner's pre-flight budget and the server's truncation behavior.
+// Override via options.num_ctx for longer spans at the operator's discretion.
+const maxContextLength = 8192
+
+// MaxContextLength returns the model's validated context window. The
+// checkpoint's max_position_embeddings (262144) is a Gemma 4 backbone
+// artifact — see maxContextLength.
+func (m *Model) MaxContextLength() int { return maxContextLength }
+
+// NewCaches returns nil slots per layer: embedding forward is a single
+// cache-free bidirectional pass.
+func (m *Model) NewCaches() []cache.Cache {
+ return make([]cache.Cache, m.Cfg.NumHiddenLayers)
+}
+
+// EmbeddingDim returns the output embedding size (after projection).
+func (m *Model) EmbeddingDim() int { return int(m.Cfg.TextConfig.EmbeddingDim) }
+
+// HiddenSize reports the text stack's hidden width for allocation estimates.
+func (m *Model) HiddenSize() int32 { return m.Cfg.TextConfig.HiddenSize }
+
+// MediaTokenStrings returns the special-token spellings the runner expands
+// in user content when media is present.
+func (m *Model) MediaTokenStrings() (boi, eoi, image, boa, eoa, audio string) {
+ t := m.Cfg.TokenStrings
+ return t.BOI, t.EOI, t.Image, t.BOA, t.EOA, t.Audio
+}
+
+// SupportsImages / SupportsAudio report tower presence; the runner 400s a
+// media request against a text-only checkpoint.
+func (m *Model) SupportsImages() bool { return m.VisionTower != nil }
+func (m *Model) SupportsAudio() bool { return m.AudioTower != nil }
+
+// VisionSoftTokenBudget resolves the per-image budget (request override
+// wins, else the config default) and validates it against the processor's
+// supported set — so a checkpoint declaring an odd budget fails at startup.
+func (m *Model) VisionSoftTokenBudget() (int32, error) {
+ if m.Cfg.VisionConfig == nil {
+ return 0, errors.New("no vision_config")
+ }
+ budget := gemma4.VisionSoftTokenBudget(m.Cfg.VisionSoftTokensPerImage, m.Cfg.VisionConfig)
+ if err := gemma4.ValidateVisionSoftTokenBudget(budget); err != nil {
+ return 0, err
+ }
+ return budget, nil
+}
+
+// PrepareMedia implements a narrow slice of model.MediaModel for the embed
+// pipeline: caller-supplied segment slices (tokenized text between media),
+// expanded to the full token stream with boi/eoi and boa/eoa brackets and
+// soft-token placeholder runs.
+func (m *Model) PrepareMedia(segments []model.Segment) (*model.PreparedRequest, error) {
+ c := m.Cfg
+ prepared := &model.PreparedRequest{}
+ for s, seg := range segments {
+ switch seg.Kind {
+ case "":
+ prepared.Tokens = append(prepared.Tokens, seg.Tokens...)
+ case "image":
+ budget, err := m.VisionSoftTokenBudget()
+ if err != nil {
+ return nil, err
+ }
+ // ProcessImage runs here (CPU) rather than on the MLX thread;
+ // the tower call in Forward consumes the patch grid.
+ pixels, positions, geom, err := gemma4.ProcessImage(seg.Data, c.VisionConfig, budget)
+ if err != nil {
+ return nil, err
+ }
+ prepared.Tokens = append(prepared.Tokens, c.BOITokenID)
+ start := len(prepared.Tokens)
+ for range geom.NumSoftTokens {
+ prepared.Tokens = append(prepared.Tokens, c.ImageTokenID)
+ }
+ prepared.Tokens = append(prepared.Tokens, c.EOITokenID)
+ n := int(geom.PatchesH * geom.PatchesW)
+ prepared.Items = append(prepared.Items, model.PreparedItem{
+ Range: [2]int{start, len(prepared.Tokens)},
+ Source: s,
+ MediaData: pixels,
+ Dims: []int{n, len(pixels) / n},
+ Opaque: preparedImage{positions: positions, geom: geom},
+ })
+ case "audio":
+ chunks, err := gemma4.ProcessAudio(seg.Data)
+ if err != nil {
+ return nil, err
+ }
+ prepared.Tokens = append(prepared.Tokens, c.BOATokenID)
+ for _, chunk := range chunks {
+ start := len(prepared.Tokens)
+ for range chunk.NumTokens {
+ prepared.Tokens = append(prepared.Tokens, c.AudioTokenID)
+ }
+ end := len(prepared.Tokens)
+ prepared.Items = append(prepared.Items, model.PreparedItem{
+ Range: [2]int{start, end},
+ Source: s,
+ MediaData: chunk.Data,
+ Dims: []int{chunk.Frames, len(chunk.Data) / chunk.Frames},
+ Opaque: preparedAudio{numTokens: int32(chunk.NumTokens)},
+ })
+ }
+ prepared.Tokens = append(prepared.Tokens, c.EOATokenID)
+ default:
+ return nil, fmt.Errorf("gemma4embedding does not support %s input", seg.Kind)
+ }
+ }
+ return prepared, nil
+}
+
+// EmbeddingDimensions returns the trained matryoshka truncation sizes from
+// this checkpoint (128/256/512/768 for embeddinggemma-2), or nil if the
+// checkpoint's config declares none.
+func (m *Model) EmbeddingDimensions() []int {
+ if len(m.Cfg.EmbeddingDimensions) > 0 {
+ return m.Cfg.EmbeddingDimensions
+ }
+ // Not declared in the EAP config.json; this is the set the DeepMind team
+ // documents for embeddinggemma-2. Future embedding arch revisions that
+ // carry the key in config.json override it; other architectures surface
+ // nil through the model interface and skip validation at the runner.
+ if m.Cfg.TextConfig.EmbeddingDim == 768 {
+ return []int{128, 256, 512, 768}
+ }
+ return nil
+}
diff --git a/mlxrunner/model/gemma4embedding/gemma4embedding_test.go b/mlxrunner/model/gemma4embedding/gemma4embedding_test.go
new file mode 100644
index 000000000..f2f314fc3
--- /dev/null
+++ b/mlxrunner/model/gemma4embedding/gemma4embedding_test.go
@@ -0,0 +1,109 @@
+package gemma4embedding
+
+import (
+ "math"
+ "testing"
+
+ "github.com/ollama/ollama/mlx"
+ "github.com/ollama/ollama/mlx/mlxtest"
+ "github.com/ollama/ollama/mlxrunner/batch"
+)
+
+// TestBidirectionalSlidingWindowMask verifies the band geometry against the
+// reference (transformers masking_utils): a pair (q,k) is attended iff
+// |q-k| <= window, inclusive. window=3 attends d<=3, blocks d>=4.
+// Padding columns are not masked here (SDPA's kLens handles those).
+func TestBidirectionalSlidingWindowMask(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ L := 10
+ b := &batch.Batch{
+ InputIDs: mlx.FromValues(make([]int32, L), 1, L),
+ SeqOffsets: []int32{0},
+ SeqQueryLens: []int32{int32(L)},
+ }
+ const window = 3 // inclusive max attended distance
+ mask := BidirectionalSlidingWindowMask(b, window, mlx.DTypeFloat32)
+ if mask.IsZero() {
+ t.Fatal("expected array mask")
+ }
+ arr := mask.AsArray(b, L, mlx.DTypeFloat32)
+ mlx.Eval(arr)
+ vals := arr.Floats() // [B=1, 1, L, L]
+ if len(vals) != L*L {
+ t.Fatalf("got %d mask values, want %d", len(vals), L*L)
+ }
+ for q := range L {
+ for k := range L {
+ got := vals[q*L+k]
+ d := q - k
+ if d < 0 {
+ d = -d
+ }
+ wantBlocked := d > window
+ isBlocked := math.IsInf(float64(got), -1)
+ if wantBlocked != isBlocked {
+ t.Errorf("q=%d k=%d (d=%d): blocked=%v want %v (val %v)", q, k, d, isBlocked, wantBlocked, got)
+ }
+ }
+ }
+
+ // Short batch: window larger than any row's furthest pair -> the
+ // mask is all-attending, so skip materializing it.
+ short := &batch.Batch{
+ InputIDs: mlx.FromValues(make([]int32, 2), 1, 2),
+ SeqOffsets: []int32{0},
+ SeqQueryLens: []int32{2},
+ }
+ if m := BidirectionalSlidingWindowMask(short, 513, mlx.DTypeFloat32); !m.IsZero() {
+ t.Error("expected zero mask for short rows")
+ }
+ // A row of length window+1 has its furthest pair at exactly the
+ // boundary: d == window is attended, so the mask must exist.
+ edge := &batch.Batch{
+ InputIDs: mlx.FromValues(make([]int32, window+1), 1, window+1),
+ SeqOffsets: []int32{0},
+ SeqQueryLens: []int32{window + 1},
+ }
+ if m := BidirectionalSlidingWindowMask(edge, window, mlx.DTypeFloat32); m.IsZero() {
+ t.Error("expected materialized mask at the d==window boundary")
+ }
+ })
+}
+
+// TestBuildMasksWindow pins the reference window derivation: config
+// sliding_window (512) plus one, so a sliding layer attends |q-kv| <= 513
+// inclusive — matching transformers' config.sliding_window + 1 overlay.
+func TestBuildMasksWindow(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ m := &Model{Cfg: tinyTextConfig()}
+ m.Cfg.SlidingWindow = 512
+ L := 600
+ b := &batch.Batch{
+ InputIDs: mlx.FromValues(make([]int32, L), 1, L),
+ SeqOffsets: []int32{0},
+ SeqQueryLens: []int32{int32(L)},
+ }
+ sliding, _ := m.buildMasks(b)
+ if sliding.IsZero() {
+ t.Fatal("expected a materialized sliding mask at 600 tokens")
+ }
+ arr := sliding.AsArray(b, L, mlx.DTypeFloat32)
+ mlx.Eval(arr)
+ vals := arr.Floats()
+
+ // Reference: attend |q-kv| <= 513.
+ probe := func(q, k int) bool {
+ v := vals[q*L+k]
+ return math.IsInf(float64(v), -1) // blocked?
+ }
+ if probe(0, 513) {
+ t.Error("d=513 must be attended (reference: abs <= sliding_window+1)")
+ }
+ if !probe(0, 514) {
+ t.Error("d=514 must be blocked")
+ }
+ if probe(0, 512) {
+ t.Error("d=512 must be attended")
+ }
+ })
+}
diff --git a/mlxrunner/model/gemma4embedding/gemma4embedding_towers_test.go b/mlxrunner/model/gemma4embedding/gemma4embedding_towers_test.go
new file mode 100644
index 000000000..bb884a99a
--- /dev/null
+++ b/mlxrunner/model/gemma4embedding/gemma4embedding_towers_test.go
@@ -0,0 +1,558 @@
+package gemma4embedding
+
+import (
+ "bytes"
+ "image"
+ "image/png"
+ "math"
+ "strconv"
+ "testing"
+
+ "github.com/ollama/ollama/mlx"
+ "github.com/ollama/ollama/mlx/mlxtest"
+ "github.com/ollama/ollama/mlxrunner/batch"
+ "github.com/ollama/ollama/mlxrunner/model"
+ "github.com/ollama/ollama/mlxrunner/model/gemma4"
+)
+
+// tinyTextConfig is the smallest Config that still exercises the load path:
+// one sliding layer, one full layer, PLE projections on.
+func tinyTextConfig() *Config {
+ cfgJSON := `{
+ "text_config": {
+ "hidden_size": 16,
+ "num_hidden_layers": 2,
+ "intermediate_size": 32,
+ "num_attention_heads": 2,
+ "num_key_value_heads": 1,
+ "head_dim": 8,
+ "vocab_size": 32,
+ "rms_norm_eps": 1e-6,
+ "max_position_embeddings": 64,
+ "sliding_window": 4,
+ "layer_types": ["sliding_attention", "full_attention"],
+ "hidden_size_per_layer_input": 8,
+ "vocab_size_per_layer_input": 0,
+ "embedding_dim": 8
+ }
+ }`
+ cfg, err := parseConfig([]byte(cfgJSON))
+ if err != nil {
+ panic(err)
+ }
+ return cfg
+}
+
+func towerTestMat(seed, rows, cols int) *mlx.Array {
+ v := make([]float32, rows*cols)
+ for i := range v {
+ v[i] = float32(((seed*97+i*31)%89)-44) / 89
+ }
+ return mlx.FromValues(v, rows, cols)
+}
+
+func towerTestVec(seed, n int) *mlx.Array {
+ v := make([]float32, n)
+ for i := range v {
+ v[i] = float32(((seed*53+i*17)%67)+1) / 34
+ }
+ return mlx.FromValues(v, n)
+}
+
+// tinyTextTensors builds the full tensor set tinyTextConfig's LoadWeights
+// consumes, with the "model." root the HF class nesting adds.
+func tinyTextTensors(cfg *Config) map[string]*mlx.Array {
+ tc := &cfg.TextConfig
+ hidden := int(tc.HiddenSize)
+ headDim := int(tc.HeadDim)
+ kvHeads := int(tc.NumKeyValueHeads)
+ heads := int(tc.NumAttentionHeads)
+ vocab := int(tc.VocabSize)
+ inter := int(tc.IntermediateSize)
+ pleHidden := int(tc.HiddenSizePerLayer)
+ embDim := int(cfg.TextConfig.EmbeddingDim)
+
+ prefix := "model.language_model."
+ tensors := map[string]*mlx.Array{
+ prefix + "embed_tokens.weight": towerTestMat(1, vocab, hidden),
+ prefix + "norm.weight": towerTestVec(2, hidden),
+ "model.embedding_projection.weight": towerTestMat(3, embDim, hidden),
+ }
+ if pleHidden > 0 {
+ tensors[prefix+"per_layer_model_projection.weight"] = towerTestMat(4, int(tc.NumHiddenLayers)*pleHidden, hidden)
+ tensors[prefix+"per_layer_projection_norm.weight"] = towerTestVec(5, pleHidden)
+ }
+ for i := range int(tc.NumHiddenLayers) {
+ lp := prefix + "layers." + strconv.Itoa(i) + "."
+ tensors[lp+"input_layernorm.weight"] = towerTestVec(10+i, hidden)
+ tensors[lp+"post_attention_layernorm.weight"] = towerTestVec(20+i, hidden)
+ tensors[lp+"pre_feedforward_layernorm.weight"] = towerTestVec(30+i, hidden)
+ tensors[lp+"post_feedforward_layernorm.weight"] = towerTestVec(40+i, hidden)
+ tensors[lp+"self_attn.q_proj.weight"] = towerTestMat(50+i, heads*headDim, hidden)
+ tensors[lp+"self_attn.k_proj.weight"] = towerTestMat(60+i, kvHeads*headDim, hidden)
+ tensors[lp+"self_attn.v_proj.weight"] = towerTestMat(70+i, kvHeads*headDim, hidden)
+ tensors[lp+"self_attn.o_proj.weight"] = towerTestMat(80+i, hidden, heads*headDim)
+ tensors[lp+"self_attn.q_norm.weight"] = towerTestVec(90+i, headDim)
+ tensors[lp+"self_attn.k_norm.weight"] = towerTestVec(100+i, headDim)
+ tensors[lp+"mlp.gate_proj.weight"] = towerTestMat(110+i, inter, hidden)
+ tensors[lp+"mlp.up_proj.weight"] = towerTestMat(120+i, inter, hidden)
+ tensors[lp+"mlp.down_proj.weight"] = towerTestMat(130+i, hidden, inter)
+ tensors[lp+"layer_scalar"] = towerTestVec(140+i, 1)
+ if pleHidden > 0 {
+ // InputGate: hidden -> pleHidden; Projection: pleHidden -> hidden.
+ // PostNorm is hidden-wide (it norms the projected, hidden-dim
+ // residual), matching the real checkpoint's [hidden] shape.
+ tensors[lp+"per_layer_input_gate.weight"] = towerTestMat(150+i, pleHidden, hidden)
+ tensors[lp+"per_layer_projection.weight"] = towerTestMat(160+i, hidden, pleHidden)
+ tensors[lp+"post_per_layer_input_norm.weight"] = towerTestVec(170+i, hidden)
+ }
+ }
+ return tensors
+}
+
+// tinyVisionTensors adds a one-layer gemma4_vision tower (hidden 8, one
+// head) plus its embed_vision projection, matching the key naming and
+// shapes gemma4.LoadVisionTower consumes.
+func tinyVisionTensors(tensors map[string]*mlx.Array, embDim int) *gemma4.VisionConfig {
+ const hidden = 8
+ cfg := &gemma4.VisionConfig{
+ ModelType: "gemma4_vision",
+ HiddenSize: hidden,
+ NumHiddenLayers: 1,
+ NumAttentionHeads: 1,
+ HeadDim: hidden,
+ PatchSize: 2,
+ PoolingKernelSize: 1,
+ RMSNormEps: 1e-6,
+ Standardize: true,
+ }
+
+ posRows := 8
+ tensors["vision_tower.patch_embedder.input_proj.weight"] = towerTestMat(201, hidden, 2*2*3)
+ {
+ v := make([]float32, 2*posRows*hidden)
+ for i := range v {
+ v[i] = float32(((202*97+i*31)%89)-44) / 89
+ }
+ tensors["vision_tower.patch_embedder.position_embedding_table"] = mlx.FromValues(v, 2, posRows, hidden)
+ }
+ lp := "vision_tower.encoder.layers.0."
+ for _, name := range []string{
+ "input_layernorm.weight", "post_attention_layernorm.weight",
+ "pre_feedforward_layernorm.weight", "post_feedforward_layernorm.weight",
+ "self_attn.q_norm.weight", "self_attn.k_norm.weight",
+ } {
+ tensors[lp+name] = towerTestVec(203, hidden)
+ }
+ for i, name := range []string{
+ "self_attn.q_proj.weight", "self_attn.k_proj.weight",
+ "self_attn.v_proj.weight", "self_attn.o_proj.weight",
+ "mlp.gate_proj.weight", "mlp.up_proj.weight", "mlp.down_proj.weight",
+ } {
+ tensors[lp+name] = towerTestMat(210+i, hidden, hidden)
+ }
+ tensors["vision_tower.std_bias"] = towerTestVec(220, hidden)
+ tensors["vision_tower.std_scale"] = towerTestVec(221, hidden)
+ tensors["embed_vision.embedding_projection.weight"] = towerTestMat(222, embDim, hidden)
+ return cfg
+}
+
+// tinyAudioTensors adds a one-layer gemma4_audio tower (hidden 128 to keep
+// the mel subsample arithmetic intact) plus embed_audio, matching
+// gemma4.LoadAudioTower's key naming and the wrapper test's shapes.
+func tinyAudioTensors(tensors map[string]*mlx.Array, embDim int) *gemma4.AudioConfig {
+ const hidden = 128
+ cfg := &gemma4.AudioConfig{
+ ModelType: "gemma4_audio",
+ HiddenSize: hidden,
+ NumHiddenLayers: 1,
+ NumAttentionHeads: 8,
+ ConvKernelSize: 5,
+ ResidualWeight: 0.5,
+ ChunkSize: 12,
+ ContextLeft: 13,
+ LogitCap: 50,
+ InvalidLogit: -1e9,
+ RMSNormEps: 1e-6,
+ GradientClipping: 1e10,
+ }
+
+ {
+ v := make([]float32, (hidden/4)*1*3*3)
+ for i := range v {
+ v[i] = float32(((301*97+i*31)%89)-44) / (89 * 3)
+ }
+ tensors["audio_tower.subsample_conv_projection.layer0.conv.weight"] = mlx.FromValues(v, hidden/4, 1, 3, 3)
+ }
+ tensors["audio_tower.subsample_conv_projection.layer0.norm.weight"] = towerTestVec(302, hidden/4)
+ {
+ v := make([]float32, hidden*3*3*(hidden/4))
+ for i := range v {
+ v[i] = float32(((303*97+i*31)%89)-44) / (89 * 20)
+ }
+ tensors["audio_tower.subsample_conv_projection.layer1.conv.weight"] = mlx.FromValues(v, hidden, hidden/4, 3, 3)
+ }
+ tensors["audio_tower.subsample_conv_projection.layer1.norm.weight"] = towerTestVec(304, hidden)
+ // After two stride-2 convs over the 128-bin mel axis: 128 -> 32.
+ tensors["audio_tower.subsample_conv_projection.input_proj_linear.weight"] = towerTestMat(305, hidden, 32*hidden)
+
+ lp := "audio_tower.layers.0."
+ headDim := hidden / int(cfg.NumAttentionHeads)
+ for _, name := range []string{
+ "feed_forward1.pre_layer_norm.weight", "feed_forward1.post_layer_norm.weight",
+ "feed_forward2.pre_layer_norm.weight", "feed_forward2.post_layer_norm.weight",
+ "lconv1d.pre_layer_norm.weight", "lconv1d.conv_norm.weight",
+ "norm_pre_attn.weight", "norm_post_attn.weight", "norm_out.weight",
+ } {
+ tensors[lp+name] = towerTestVec(306, hidden)
+ }
+ tensors[lp+"self_attn.per_dim_scale"] = towerTestVec(307, headDim)
+ for i, name := range []string{
+ "feed_forward1.ffw_layer_1.weight", "feed_forward1.ffw_layer_2.weight",
+ "feed_forward2.ffw_layer_1.weight", "feed_forward2.ffw_layer_2.weight",
+ "self_attn.q_proj.weight", "self_attn.k_proj.weight",
+ "self_attn.v_proj.weight", "self_attn.post.weight",
+ "self_attn.relative_k_proj.weight",
+ } {
+ tensors[lp+name] = towerTestMat(310+i, hidden, hidden)
+ }
+ tensors[lp+"lconv1d.linear_start.weight"] = towerTestMat(320, 2*hidden, hidden)
+ {
+ v := make([]float32, hidden*int(cfg.ConvKernelSize))
+ for i := range v {
+ v[i] = float32(((321*97+i*31)%89)-44) / 445
+ }
+ tensors[lp+"lconv1d.depthwise_conv1d.weight"] = mlx.FromValues(v, hidden, 1, int(cfg.ConvKernelSize))
+ }
+ tensors[lp+"lconv1d.linear_end.weight"] = towerTestMat(322, hidden, hidden)
+ tensors["audio_tower.output_proj.weight"] = towerTestMat(323, hidden, hidden)
+ tensors["embed_audio.embedding_projection.weight"] = towerTestMat(324, embDim, hidden)
+ return cfg
+}
+
+// loadModelTensors wires a Model from cfg + tensors the way LoadWeights
+// expects, and returns the load error (nil on success).
+func loadModelTensors(cfg *Config, tensors map[string]*mlx.Array) (*Model, error) {
+ m := &Model{Layers: make([]*DecoderLayer, cfg.NumHiddenLayers), Cfg: cfg}
+ m.Cfg.QuantGroupSize, m.Cfg.QuantBits, m.Cfg.QuantMode = model.QuantizationParams("")
+ err := m.LoadWeights(tensors)
+ return m, err
+}
+
+// TestTowerLoadingVariants covers all four embeddinggemma-2 variant shapes
+// with synthetic tensors: text-only, text-vision, text-audio, full.
+func TestTowerLoadingVariants(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ withVision, withAudio bool
+ }{
+ {"text-only", false, false},
+ {"text-vision", true, false},
+ {"text-audio", false, true},
+ {"full", true, true},
+ } {
+ mlxtest.RunSubtest(t, tc.name, func(t *mlxtest.T) {
+ cfg := tinyTextConfig()
+ tensors := tinyTextTensors(cfg)
+ if tc.withVision {
+ cfg.VisionConfig = tinyVisionTensors(tensors, int(cfg.TextConfig.EmbeddingDim))
+ }
+ if tc.withAudio {
+ cfg.AudioConfig = tinyAudioTensors(tensors, int(cfg.TextConfig.EmbeddingDim))
+ }
+
+ m, err := loadModelTensors(cfg, tensors)
+ if err != nil {
+ t.Errorf("LoadWeights: %v", err)
+ return
+ }
+
+ if got := m.VisionTower != nil; got != tc.withVision {
+ t.Errorf("VisionTower non-nil = %v, want %v", got, tc.withVision)
+ }
+ if got := m.EmbedVision != nil; got != tc.withVision {
+ t.Errorf("EmbedVision non-nil = %v, want %v", got, tc.withVision)
+ }
+ if got := m.AudioTower != nil; got != tc.withAudio {
+ t.Errorf("AudioTower non-nil = %v, want %v", got, tc.withAudio)
+ }
+ if got := m.EmbedAudio != nil; got != tc.withAudio {
+ t.Errorf("EmbedAudio non-nil = %v, want %v", got, tc.withAudio)
+ }
+ })
+ }
+}
+
+// TestTextForwardUnchangedWithoutTowers pins the no-tower text path: a
+// forward through the synthetic text-only model must succeed and produce
+// finite outputs of the expected shape, proving tower wiring didn't disturb
+// the existing path.
+func TestTextForwardUnchangedWithoutTowers(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ cfg := tinyTextConfig()
+ m, err := loadModelTensors(cfg, tinyTextTensors(cfg))
+ if err != nil {
+ t.Errorf("LoadWeights: %v", err)
+ return
+ }
+ if m.VisionTower != nil || m.AudioTower != nil || m.EmbedVision != nil || m.EmbedAudio != nil {
+ t.Error("towers should be nil on a text-only tensor set")
+ return
+ }
+
+ toks := []int32{1, 5, 9, 2}
+ out, _ := m.Forward(&batch.Batch{
+ InputIDs: mlx.FromValues(toks, 1, len(toks)),
+ SeqOffsets: []int32{0},
+ SeqQueryLens: []int32{int32(len(toks))},
+ }, nil)
+ mlx.Eval(out)
+ dims := out.Dims()
+ if len(dims) != 3 || dims[1] != len(toks) || dims[2] != int(cfg.TextConfig.EmbeddingDim) {
+ t.Errorf("output dims %v, want [1 %d %d]", dims, len(toks), cfg.TextConfig.EmbeddingDim)
+ return
+ }
+ for i, v := range out.AsType(mlx.DTypeFloat32).Floats() {
+ if math.IsNaN(float64(v)) || math.IsInf(float64(v), 0) {
+ t.Errorf("non-finite output at %d: %v", i, v)
+ return
+ }
+ }
+ })
+}
+
+// TestTowerLoadErrors checks the hard-error path (tower weights without the
+// matching config subtree) and the inverse (config subtrees with no tower
+// tensors must load text-only — presence of config never triggers a load).
+func TestTowerLoadErrors(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ // Vision weights but no vision_config: must error.
+ cfg := tinyTextConfig()
+ tensors := tinyTextTensors(cfg)
+ tinyVisionTensors(tensors, int(cfg.TextConfig.EmbeddingDim))
+ if _, err := loadModelTensors(cfg, tensors); err == nil {
+ t.Error("expected error for vision weights without vision_config")
+ }
+
+ // Audio weights but no audio_config: must error.
+ cfg = tinyTextConfig()
+ tensors = tinyTextTensors(cfg)
+ tinyAudioTensors(tensors, int(cfg.TextConfig.EmbeddingDim))
+ if _, err := loadModelTensors(cfg, tensors); err == nil {
+ t.Error("expected error for audio weights without audio_config")
+ }
+
+ // Configs present but no tower tensors: loads text-only.
+ cfg2 := tinyTextConfig()
+ cfg2.VisionConfig = &gemma4.VisionConfig{ModelType: "gemma4_vision"}
+ cfg2.AudioConfig = &gemma4.AudioConfig{ModelType: "gemma4_audio"}
+ m2, err := loadModelTensors(cfg2, tinyTextTensors(cfg2))
+ if err != nil {
+ t.Errorf("LoadWeights with config-only subtrees: %v", err)
+ return
+ }
+ if m2.VisionTower != nil || m2.AudioTower != nil {
+ t.Error("config-only subtrees must not trigger tower loads")
+ }
+ })
+}
+
+// TestMediaForwardDiffsFromTextOnly is the Task 4 model-side prove-out: a
+// text-vision variant must (a) encode a synthetic image through the vision
+// tower and (b) splice the tower features into the token stream, changing
+// the forward output relative to the same token stream run without media.
+// The image is hand-built patch data (PrepareMedia's PNG decode is covered
+// in gemma4's own tests); the PreparedRequest the runner would get is
+// rebuilt by hand so EncodeMedia is the code path under test.
+func TestMediaForwardDiffsFromTextOnly(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ cfg := tinyTextConfig()
+ tensors := tinyTextTensors(cfg)
+ // embed_vision must project into the token-embedding stream, i.e.
+ // the text hidden size — that is what scatterMedia rewires rows
+ // with. (The tiny text config's EmbeddingDim is the OUTPUT dim,
+ // applied later by model.embedding_projection.)
+ textHidden := int(cfg.TextConfig.HiddenSize)
+ cfg.VisionConfig = tinyVisionTensors(tensors, textHidden)
+ // parseConfig fills RopeTheta only for configs that come through
+ // its JSON unmarshal; the helper-built subtree needs it set the
+ // same way (0 would trip 1/Pow(0, i) in the RoPE tables).
+ cfg.VisionConfig.RopeTheta = 100
+
+ m, err := loadModelTensors(cfg, tensors)
+ if err != nil {
+ t.Errorf("LoadWeights: %v", err)
+ return
+ }
+ if m.VisionTower == nil || m.EmbedVision == nil {
+ t.Error("vision tower/embedder must be loaded for the media path")
+ return
+ }
+
+ // One synthetic image: a 4x4 patch grid (16 patches over a PatchSize
+ // 2 tower, PoolingKernelSize 1 keeps NumSoftTokens == 16), with
+ // deterministic pixel values.
+ const grid = 4
+ const patchD = 2 * 2 * 3
+ const patches = grid * grid
+ pixels := make([]float32, patches*patchD)
+ positions := make([]int32, 2*patches)
+ for p := range patches {
+ positions[2*p] = int32(p % grid)
+ positions[2*p+1] = int32(p / grid)
+ for d := range patchD {
+ pixels[p*patchD+d] = float32((p*31+d*7)%97) / 97
+ }
+ }
+ geom := gemma4.ImageGeometry{PatchesW: grid, PatchesH: grid, NumSoftTokens: patches}
+
+ // Token stream: one text token, then the 16 image soft-token
+ // placeholders at positions [1,17), then two more text tokens.
+ // Input token values only matter for the embedding lookup; every id
+ // stays inside the tiny vocab (32).
+ const mediaPos = 1
+ toks := make([]int32, 0, 3+patches)
+ toks = append(toks, 3)
+ for range patches {
+ toks = append(toks, 7)
+ }
+ toks = append(toks, 11, 13)
+
+ // EncodeMedia is the runner-facing entry: hand it the PreparedRequest
+ // PrepareMedia would have produced for this image at position 1.
+ prepared := &model.PreparedRequest{
+ Tokens: toks,
+ Items: []model.PreparedItem{{
+ Range: [2]int{mediaPos, mediaPos + patches},
+ Source: 0,
+ MediaData: pixels,
+ Dims: []int{patches, patchD},
+ Opaque: preparedImage{positions: positions, geom: geom},
+ }},
+ }
+ media, err := m.EncodeMedia(prepared)
+ if err != nil {
+ t.Errorf("EncodeMedia: %v", err)
+ return
+ }
+ if len(media) != 1 {
+ t.Errorf("EncodeMedia returned %d items, want 1", len(media))
+ return
+ }
+ if media[0].Pos != mediaPos || media[0].Seq != 0 {
+ t.Errorf("media item pos/seq = (%d,%d), want (%d,0)", media[0].Pos, media[0].Seq, mediaPos)
+ }
+ // The tower code path must actually have run: the feature array is
+ // [NumSoftTokens, text hidden] with finite values.
+ feats := media[0].Features
+ if feats == nil {
+ t.Error("EncodeMedia returned nil features; tower did not run")
+ return
+ }
+ mlx.Eval(feats)
+ if got := feats.Dims(); len(got) != 2 || got[0] != patches || got[1] != textHidden {
+ t.Errorf("feature dims %v, want [%d %d]", got, patches, textHidden)
+ return
+ }
+ for i, v := range feats.AsType(mlx.DTypeFloat32).Floats() {
+ if math.IsNaN(float64(v)) || math.IsInf(float64(v), 0) {
+ t.Errorf("non-finite tower feature at %d: %v", i, v)
+ return
+ }
+ }
+
+ newBatch := func(withMedia bool) *batch.Batch {
+ b := &batch.Batch{
+ InputIDs: mlx.FromValues(toks, 1, len(toks)),
+ SeqOffsets: []int32{0},
+ SeqQueryLens: []int32{int32(len(toks))},
+ }
+ if withMedia {
+ b.Media = media
+ }
+ return b
+ }
+
+ plain, _ := m.Forward(newBatch(false), nil)
+ withMedia, _ := m.Forward(newBatch(true), nil)
+ plain = plain.AsType(mlx.DTypeFloat32)
+ withMedia = withMedia.AsType(mlx.DTypeFloat32)
+ mlx.Eval(plain, withMedia)
+
+ pDims, mDims := plain.Dims(), withMedia.Dims()
+ if len(pDims) != 3 || pDims[1] != len(toks) || pDims[2] != int(cfg.TextConfig.EmbeddingDim) {
+ t.Errorf("plain output dims %v, want [1 %d %d]", pDims, len(toks), cfg.TextConfig.EmbeddingDim)
+ return
+ }
+ if len(mDims) != 3 || mDims[1] != len(toks) || mDims[2] != int(cfg.TextConfig.EmbeddingDim) {
+ t.Errorf("media output dims %v, want [1 %d %d]", mDims, len(toks), cfg.TextConfig.EmbeddingDim)
+ return
+ }
+
+ pv, mv := plain.Floats(), withMedia.Floats()
+ if len(pv) != len(mv) {
+ t.Errorf("output lengths %d vs %d", len(pv), len(mv))
+ return
+ }
+ embDim := int(cfg.TextConfig.EmbeddingDim)
+ rowChanged := make([]bool, len(toks))
+ anyChange := false
+ for row := range toks {
+ for d := range embDim {
+ i := row*embDim + d
+ if math.Abs(float64(pv[i]-mv[i])) > 1e-5 {
+ rowChanged[row] = true
+ anyChange = true
+ break
+ }
+ }
+ }
+ // (a) The media run differs: the scatter path had an effect.
+ if !anyChange {
+ t.Error("forward output identical with and without media; scatter is a no-op")
+ }
+ // (b) The replaced rows themselves changed (the tower features
+ // landed at Pos..Pos+NumSoftTokens).
+ for row := mediaPos; row < mediaPos+patches; row++ {
+ if !rowChanged[row] {
+ t.Errorf("media row %d unchanged; scatter missed it", row)
+ }
+ }
+ // Bidirectional attention means text rows see the media too: the
+ // leading text row must change, proving the spliced features
+ // propagated through the encoder rather than sitting in dead rows.
+ if !rowChanged[0] {
+ t.Error("text row 0 unchanged; spliced media did not propagate through attention")
+ }
+ })
+}
+
+// TestVisionTowerLoadSeedsPositionCapacity: LoadVisionTower must seed the
+// config's position-table capacity (the [2, positions, hidden] table's
+// positions axis), or ProcessImage rejects every image with "patch grid
+// exceeds vision position embedding size 0" — the failure that shipped the
+// dict-form media path broken.
+func TestVisionTowerLoadSeedsPositionCapacity(t *testing.T) {
+ mlxtest.RunSubtest(t, "seed", func(t *mlxtest.T) {
+ cfg := tinyTextConfig()
+ tensors := tinyTextTensors(cfg)
+ vcfg := tinyVisionTensors(tensors, int(cfg.TextConfig.EmbeddingDim))
+ cfg.VisionConfig = vcfg
+
+ linears := model.NewLinearFactory(tensors, cfg.QuantGroupSize, cfg.QuantBits, cfg.QuantMode, cfg.TensorQuant)
+ if _, _, err := gemma4.LoadVisionTower(tensors, vcfg, linears); err != nil {
+ t.Fatalf("LoadVisionTower: %v", err)
+ }
+
+ // A tiny PNG must clear the grid check. Budget 70 is the smallest
+ // the reference processor supports; patch 2/pool 1 keeps the grid
+ // inside the 8-position table for small inputs.
+ var buf bytes.Buffer
+ if err := png.Encode(&buf, image.NewRGBA(image.Rect(0, 0, 8, 8))); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, _, err := gemma4.ProcessImage(buf.Bytes(), vcfg, 70); err != nil {
+ t.Errorf("ProcessImage after load: %v", err)
+ }
+ })
+}
diff --git a/mlxrunner/runner.go b/mlxrunner/runner.go
index 251cc97df..1af2856bf 100644
--- a/mlxrunner/runner.go
+++ b/mlxrunner/runner.go
@@ -46,6 +46,7 @@ type Runner struct {
weights *mlx.Scope
Tokenizer *tokenizer.Tokenizer
Requests chan Request
+ EmbedRequests chan EmbeddingRequest
Sampler *sample.Sampler
cache *prefixCache
scoreCache *prefixCache
@@ -311,6 +312,17 @@ func (r *Runner) Run(host, port string, mux http.Handler) error {
}
close(request.Responses)
+ case erequest := <-r.EmbedRequests:
+ run := func() error { return r.runEmbed(erequest.Ctx, erequest) }
+ var err error
+ if r.mlxThread == nil {
+ err = run()
+ } else {
+ err = r.mlxThread.Do(erequest.Ctx, run)
+ }
+ if err != nil {
+ slog.Info("Embedding request terminated", "error", err)
+ }
}
}
})
diff --git a/mlxrunner/server.go b/mlxrunner/server.go
index 36385a849..c8c349a4d 100644
--- a/mlxrunner/server.go
+++ b/mlxrunner/server.go
@@ -58,8 +58,9 @@ func Execute(args []string) error {
defer cancelRunner()
runner := Runner{
- Requests: make(chan Request),
- mlxThread: worker,
+ Requests: make(chan Request),
+ EmbedRequests: make(chan EmbeddingRequest),
+ mlxThread: worker,
}
if err := worker.Do(context.Background(), func() error {
@@ -89,12 +90,16 @@ func Execute(args []string) error {
mux := http.NewServeMux()
mux.HandleFunc("POST /v1/score", runner.scoreHandler)
mux.HandleFunc("GET /v1/status", func(w http.ResponseWriter, r *http.Request) {
- if err := json.NewEncoder(w).Encode(statusResponse{
+ resp := statusResponse{
Status: 0,
Progress: 100,
ContextLength: runner.contextLength,
Memory: memoryCache.Memory(),
- }); err != nil {
+ }
+ if em, ok := runner.Model.(interface{ EmbeddingDimensions() []int }); ok {
+ resp.EmbeddingDimensions = em.EmbeddingDimensions()
+ }
+ if err := json.NewEncoder(w).Encode(resp); err != nil {
slog.Error("Failed to encode response", "error", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
@@ -206,6 +211,20 @@ func Execute(args []string) error {
}
})
+ mux.HandleFunc("POST /v1/detokenize", func(w http.ResponseWriter, r *http.Request) {
+ var tokens []int32
+ if err := json.NewDecoder(r.Body).Decode(&tokens); err != nil {
+ http.Error(w, "Bad Request", http.StatusBadRequest)
+ return
+ }
+ if err := json.NewEncoder(w).Encode(runner.Tokenizer.Decode(tokens)); err != nil {
+ slog.Error("Failed to encode response", "error", err)
+ http.Error(w, "Internal Server Error", http.StatusInternalServerError)
+ }
+ })
+
+ mux.HandleFunc("POST /v1/embeddings", runner.handleEmbed)
+
for source, target := range map[string]string{
"GET /health": "/v1/status",
"POST /load": "/v1/models",
diff --git a/server/routes.go b/server/routes.go
index d4ed69897..501d04d06 100644
--- a/server/routes.go
+++ b/server/routes.go
@@ -1039,20 +1039,77 @@ func (s *Server) EmbedHandler(c *gin.Context) {
req.Runner = runner
}
- var input []string
+ // embedInput is one item from the input list: its text plus whatever
+ // media blobs it carries. Items without media go through the plain
+ // text embed path; items with media go through the runner's media-aware
+ // embed.
+ type embedInput struct {
+ text string
+ media [][]byte
+ }
+
+ var input []embedInput
+
+ // parseMultimodalItem reads one map-shaped input item. Any of "text",
+ // "image", "audio" are accepted (short names, base64-encoded blobs for
+ // media); "video" exists in the config but the runner has no video tower
+ // yet, so it's a hard error rather than silently ignored.
+ parseMultimodalItem := func(m map[string]any) (embedInput, error) {
+ var item embedInput
+ for key, v := range m {
+ str, ok := v.(string)
+ if !ok {
+ return item, fmt.Errorf("input.%s must be a string", key)
+ }
+ switch key {
+ case "text":
+ item.text = str
+ case "image", "audio":
+ raw, err := base64.StdEncoding.DecodeString(str)
+ if err != nil {
+ return item, fmt.Errorf("input.%s: %v", key, err)
+ }
+ item.media = append(item.media, raw)
+ case "video":
+ return item, fmt.Errorf("input.video not supported")
+ default:
+ return item, fmt.Errorf("unknown input field %q", key)
+ }
+ }
+ if item.text == "" && len(item.media) == 0 {
+ return item, errors.New("input item has no text, image, or audio")
+ }
+ return item, nil
+ }
switch i := req.Input.(type) {
case string:
- if len(i) > 0 {
- input = append(input, i)
+ if i != "" {
+ input = append(input, embedInput{text: i})
+ }
+ case map[string]any:
+ item, err := parseMultimodalItem(i)
+ if err != nil {
+ c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
}
+ input = append(input, item)
case []any:
for _, v := range i {
- if _, ok := v.(string); !ok {
+ switch v := v.(type) {
+ case string:
+ input = append(input, embedInput{text: v})
+ case map[string]any:
+ item, err := parseMultimodalItem(v)
+ if err != nil {
+ c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ }
+ input = append(input, item)
+ default:
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid input type"})
return
}
- input = append(input, v.(string))
}
default:
if req.Input != nil {
@@ -1082,6 +1139,33 @@ func (s *Server) EmbedHandler(c *gin.Context) {
ctx := c.Request.Context()
+ // mediaEmbedder is the runner's media-aware embed if it supports one.
+ // Resolved once before the per-item goroutines fan out: an all-text
+ // batch pays nothing either way, and the lazy write below is not
+ // safe to race on.
+ var mediaEmbedder interface {
+ EmbedWithMedia(ctx context.Context, input string, media [][]byte) ([]float32, int, error)
+ }
+ var mediaErr error
+ resolveMediaEmbedder := func() bool {
+ if mediaEmbedder != nil || mediaErr != nil {
+ return mediaErr == nil
+ }
+ me, ok := r.(interface {
+ EmbedWithMedia(ctx context.Context, input string, media [][]byte) ([]float32, int, error)
+ })
+ if !ok {
+ mediaErr = errors.New("model does not support media embeddings")
+ return false
+ }
+ mediaEmbedder = me
+ return true
+ }
+ // Resolve once here, before the per-item goroutines below fan out:
+ // the lazy path above reads and writes these closures' captured vars
+ // and is not safe to run concurrently.
+ resolveMediaEmbedder()
+
adjustTokenLimit := func(tokens []int, limit int) int {
if bos := m.metadata.Int("tokenizer.ggml.bos_token_id"); len(tokens) > 0 && tokens[0] != int(bos) && m.metadata.Bool("add_bos_token", true) {
limit--
@@ -1098,8 +1182,13 @@ func (s *Server) EmbedHandler(c *gin.Context) {
return nil, 0, err
}
- // TODO @nicolepardal: avoid reaching into kvData here; pass required tokenizer metadata via model/options instead
+ // GGUF metadata carries the GGUF context length; safetensors (MLX)
+ // models never populate ggufMetadata, so fall back to the manifest
+ // config's context_length written by create/ from the HF config.
ctxLen := int(m.metadata.Int("context_length"))
+ if ctxLen == 0 && m.Config.ModelFormat == "safetensors" {
+ ctxLen = m.Config.ContextLen
+ }
if opts.NumCtx > 0 {
ctxLen = min(opts.NumCtx, ctxLen)
}
@@ -1134,7 +1223,8 @@ func (s *Server) EmbedHandler(c *gin.Context) {
return truncateInputToLimit(text, 0)
}
- embedWithRetry := func(text string) ([]float32, int, error) {
+ embedWithRetry := func(item embedInput) ([]float32, int, error) {
+ text := item.text
if req.Truncate != nil && !*req.Truncate {
tokens, ctxLen, err := inputTokensAndContext(text)
if err != nil {
@@ -1157,36 +1247,51 @@ func (s *Server) EmbedHandler(c *gin.Context) {
}
}
- emb, tokCount, err := r.Embedding(ctx, text)
+ run := func(ctx context.Context, text string) ([]float32, int, error) {
+ if len(item.media) == 0 {
+ return r.Embedding(ctx, text)
+ }
+ if !resolveMediaEmbedder() {
+ return nil, 0, api.StatusError{StatusCode: http.StatusNotImplemented, ErrorMessage: mediaErr.Error()}
+ }
+ return mediaEmbedder.EmbedWithMedia(ctx, text, item.media)
+ }
+
+ emb, tokCount, err := run(ctx, text)
if err == nil {
return emb, tokCount, nil
}
+ // Only a runner 413 (input over context length) justifies a truncation
+ // retry. Everything else — 400 media validation, marker mismatches,
+ // malformed payloads — belongs to the caller unchanged.
var serr api.StatusError
- if !errors.As(err, &serr) || serr.StatusCode != http.StatusBadRequest {
+ if !errors.As(err, &serr) || serr.StatusCode != http.StatusRequestEntityTooLarge {
return nil, 0, err
}
if req.Truncate != nil && !*req.Truncate {
return nil, 0, err
}
- truncated, ok, err := truncateInputToLimit(text, opts.NumBatch)
- if err != nil {
- return nil, 0, err
+ truncated, ok, terr := truncateInputToLimit(text, opts.NumBatch)
+ if terr != nil {
+ return nil, 0, terr
}
if !ok {
- return nil, 0, fmt.Errorf("input exceeds maximum context length and cannot be truncated further")
+ // Nothing to truncate (e.g. the text fits but media expansion
+ // overflowed the runner): the original 413 stands.
+ return nil, 0, err
}
- return r.Embedding(ctx, truncated)
+ return run(ctx, truncated)
}
var g errgroup.Group
embeddings := make([][]float32, len(input))
var totalTokens uint64
- for i, text := range input {
+ for i, item := range input {
g.Go(func() error {
- embedding, tokenCount, err := embedWithRetry(text)
+ embedding, tokenCount, err := embedWithRetry(item)
if err != nil {
return err
}
@@ -1195,10 +1300,24 @@ func (s *Server) EmbedHandler(c *gin.Context) {
if err != nil {
return err
}
- if req.Dimensions > 0 && req.Dimensions < len(embedding) {
- embedding, err = normalize(embedding[:req.Dimensions])
- if err != nil {
- return err
+ if req.Dimensions > 0 {
+ if req.Dimensions > len(embedding) {
+ return fmt.Errorf("dimensions %d exceeds embedding length %d", req.Dimensions, len(embedding))
+ }
+ // If the runner declares a trained matryoshka set, restrict to it.
+ if ed, ok := r.(interface{ EmbeddingDimensions() []int }); ok {
+ if valid := ed.EmbeddingDimensions(); len(valid) > 0 && !slices.Contains(valid, req.Dimensions) {
+ return api.StatusError{
+ StatusCode: http.StatusBadRequest,
+ ErrorMessage: fmt.Sprintf("dimensions %d not supported by this model; valid values are %v", req.Dimensions, valid),
+ }
+ }
+ }
+ if req.Dimensions < len(embedding) {
+ embedding, err = normalize(embedding[:req.Dimensions])
+ if err != nil {
+ return err
+ }
}
}
embeddings[i] = embedding
@@ -1839,6 +1958,23 @@ func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
return resp, nil
}
+ // Safetensors embedding models (e.g. Gemma4Embedding) likewise have no
+ // GGUF model layer to introspect; withoutCompletion=false and the image
+ // fallback above don't cover them, so mirror that branch rather than
+ // falling through to a GGUF read that returns os.ErrNotExist on an empty
+ // path list.
+ if m.Config.ModelFormat == "safetensors" && slices.Contains(m.Capabilities(), model.CapabilityEmbedding) {
+ if info, err := getSafetensorsLLMInfoForRunner(name, req.Runner); err == nil {
+ resp.ModelInfo = info
+ }
+ if req.Verbose {
+ if tensors, err := getSafetensorsTensorInfoForRunner(name, req.Runner); err == nil {
+ resp.Tensors = tensors
+ }
+ }
+ return resp, nil
+ }
+
kvData, tensors, err := getModelData(m.modelPaths(), req.Verbose)
if err != nil {
return nil, err