Skip to content

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

mlx: System one support (#18701)

Daniel Hiltgena00d083bb543
diff --git a/cmd/create_safetensors_remote.go b/cmd/create_safetensors_remote.go
index f3ca59186..254e9f8f7 100644
--- a/cmd/create_safetensors_remote.go
+++ b/cmd/create_safetensors_remote.go
@@ -86,21 +86,12 @@ func prepareRemoteSourceFiles(ctx context.Context, dir string, draft bool) ([]re
if err != nil {
return nil, err
}
- entries, err := os.ReadDir(dir)
+ configs, err := create.SafetensorsConfigFiles(dir)
if err != nil {
return nil, err
}
- names := append([]string(nil), weightFiles...)
- for _, entry := range entries {
- if entry.IsDir() {
- continue
- }
- name := entry.Name()
- if filepath.Ext(name) == ".json" || name == "chat_template.jinja" {
- names = append(names, name)
- }
- }
+ names := append(weightFiles, configs...)
slices.Sort(names)
files := make([]remoteSourceFile, 0, len(names))
diff --git a/create/clef.go b/create/clef.go
new file mode 100644
index 000000000..0b8dc76f3
--- /dev/null
+++ b/create/clef.go
@@ -0,0 +1,100 @@
+package create
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "slices"
+
+ "github.com/ollama/ollama/fs/safetensors"
+)
+
+// Clef's config and shard index describe only its backbone. RENDERER clef adds
+// the joint head and normalizes the output architecture without changing source files.
+func prepareClefInventory(inv Inventory) (Inventory, error) {
+ if inv.Config.Architecture() != "Qwen3_5ForConditionalGeneration" {
+ return Inventory{}, fmt.Errorf("unsupported Clef backbone %q", inv.Config.Architecture())
+ }
+ var backbone struct {
+ TextConfig struct {
+ HiddenSize int `json:"hidden_size"`
+ } `json:"text_config"`
+ }
+ if err := json.Unmarshal(inv.RawConfig, &backbone); err != nil {
+ return Inventory{}, err
+ }
+ var cfg struct {
+ HiddenSize int `json:"hidden_size"`
+ Width int `json:"width"`
+ RoutingLayers int `json:"routing_layers"`
+ Layers int `json:"layers"`
+ Heads int `json:"heads"`
+ Feedforward int `json:"feedforward"`
+ }
+ data, err := os.ReadFile(filepath.Join(inv.Dir, "joint_head_config.json"))
+ if err != nil {
+ return Inventory{}, fmt.Errorf("read Clef joint head config: %w", err)
+ }
+ if err := json.Unmarshal(data, &cfg); err != nil {
+ return Inventory{}, fmt.Errorf("parse Clef joint head config: %w", err)
+ }
+ if cfg.HiddenSize <= 0 || cfg.HiddenSize != backbone.TextConfig.HiddenSize || cfg.Width <= 0 || cfg.Heads <= 0 || cfg.Width%cfg.Heads != 0 || cfg.Feedforward <= 0 || cfg.Layers < 1 || cfg.Layers > 16 || cfg.RoutingLayers < 1 || cfg.RoutingLayers > 16 {
+ return Inventory{}, fmt.Errorf("invalid Clef joint head configuration for backbone")
+ }
+ head, err := safetensors.OpenForExtraction(filepath.Join(inv.Dir, "joint_head.safetensors"))
+ if err != nil {
+ return Inventory{}, fmt.Errorf("read Clef joint head: %w", err)
+ }
+ defer head.Close()
+ for name, shape := range map[string][]int32{
+ "memory_projection.weight": {int32(cfg.Width), int32(cfg.HiddenSize)},
+ "type_embedding.weight": {3, int32(cfg.Width)},
+ } {
+ tensor, err := head.GetTensor(name)
+ if err != nil || !slices.Equal(tensor.Shape, shape) {
+ return Inventory{}, fmt.Errorf("Clef joint head requires %s with shape %v", name, shape)
+ }
+ }
+ for _, name := range head.ListTensors() {
+ if tensor, ok := inv.Tensors[name]; ok && tensor.File != "joint_head.safetensors" {
+ return Inventory{}, fmt.Errorf("Clef head duplicates backbone tensor %q", name)
+ }
+ tensor, err := head.GetTensor(name)
+ if err != nil {
+ return Inventory{}, fmt.Errorf("read Clef head tensor %s: %w", name, err)
+ }
+ inv.Tensors[name] = SourceTensor{Name: name, Dtype: tensor.Dtype, Shape: tensor.Shape, File: "joint_head.safetensors"}
+ }
+ var output map[string]json.RawMessage
+ if err := json.Unmarshal(inv.RawConfig, &output); err != nil {
+ return Inventory{}, err
+ }
+ output["architectures"] = json.RawMessage(`["ClefForDecision"]`)
+ inv.RawConfig, err = json.Marshal(output)
+ if err != nil {
+ return Inventory{}, err
+ }
+ inv.Config.Architectures = []string{"ClefForDecision"}
+ return inv, nil
+}
+
+// The publisher's head is not in the shard index. Transfer it without using
+// its presence to select a model architecture.
+func clefWeightFiles(dir string, files []string) ([]string, error) {
+ info, err := os.Stat(filepath.Join(dir, "joint_head.safetensors"))
+ if os.IsNotExist(err) {
+ return files, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ if !info.Mode().IsRegular() {
+ return nil, fmt.Errorf("Clef joint_head.safetensors must be a regular file")
+ }
+ if !slices.Contains(files, "joint_head.safetensors") {
+ files = append(files, "joint_head.safetensors")
+ slices.Sort(files)
+ }
+ return files, nil
+}
diff --git a/create/clef_test.go b/create/clef_test.go
new file mode 100644
index 000000000..dc250a53b
--- /dev/null
+++ b/create/clef_test.go
@@ -0,0 +1,257 @@
+package create
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "reflect"
+ "slices"
+ "strings"
+ "testing"
+
+ st "github.com/ollama/ollama/fs/safetensors"
+)
+
+func writeClefSource(t *testing.T, dir string) {
+ t.Helper()
+ writeConfigJSON(t, dir, `{"architectures":["Qwen3_5ForConditionalGeneration"],"model_type":"qwen3_5","text_config":{"hidden_size":4},"publisher_extension":{"large_integer":123456789012345678901234567890,"scale":1e6}}`)
+ for name, data := range map[string]string{
+ "joint_head_config.json": `{"hidden_size":4,"width":2,"heads":1,"layers":1,"routing_layers":1,"feedforward":4}`,
+ "model.safetensors.index.json": `{"weight_map":{"model.weight":"model.safetensors"}}`,
+ } {
+ if err := os.WriteFile(filepath.Join(dir, name), []byte(data), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{
+ st.NewTensorDataFromBytes("model.weight", "BF16", []int32{2, 4}, make([]byte, 16)),
+ })
+ createTestSafetensors(t, filepath.Join(dir, "joint_head.safetensors"), []*st.TensorData{
+ st.NewTensorDataFromBytes("memory_projection.weight", "BF16", []int32{2, 4}, make([]byte, 16)),
+ st.NewTensorDataFromBytes("type_embedding.weight", "BF16", []int32{3, 2}, make([]byte, 12)),
+ })
+}
+
+func TestClefInventory(t *testing.T) {
+ for _, tc := range []struct{ name, remove, config, index, wantError string }{
+ {name: "complete"},
+ {name: "monolithic backbone", remove: "model.safetensors.index.json"},
+ {name: "head already indexed", index: `{"weight_map":{"model.weight":"model.safetensors","memory_projection.weight":"joint_head.safetensors","type_embedding.weight":"joint_head.safetensors"}}`},
+ {name: "missing config", remove: "joint_head_config.json", wantError: "read Clef joint head config"},
+ {name: "missing head", remove: "joint_head.safetensors", wantError: "read Clef joint head"},
+ {name: "different backbone", config: `{"architectures":["Qwen3ForCausalLM"]}`, wantError: "unsupported Clef backbone"},
+ {name: "different hidden size", config: `{"architectures":["Qwen3_5ForConditionalGeneration"],"text_config":{"hidden_size":8}}`, wantError: "invalid Clef joint head configuration"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ dir := t.TempDir()
+ writeClefSource(t, dir)
+ if tc.remove != "" {
+ if err := os.Remove(filepath.Join(dir, tc.remove)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if tc.config != "" {
+ writeConfigJSON(t, dir, tc.config)
+ }
+ if tc.index != "" {
+ if err := os.WriteFile(filepath.Join(dir, "model.safetensors.index.json"), []byte(tc.index), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ inv, err := ReadInventory(dir)
+ if err == nil {
+ inv, err = prepareClefInventory(inv)
+ }
+ if tc.wantError != "" {
+ if err == nil || !strings.Contains(err.Error(), tc.wantError) {
+ t.Fatalf("prepareClefInventory() error=%v, want %q", err, tc.wantError)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if inv.Config.Architecture() != "ClefForDecision" || len(inv.Tensors) != 3 || inv.Tensors["memory_projection.weight"].File != "joint_head.safetensors" {
+ t.Fatalf("incorrect composite inventory: %+v", inv)
+ }
+ files, err := SafetensorsWeightFiles(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(files, []string{"joint_head.safetensors", "model.safetensors"}) {
+ t.Fatalf("source files=%v", files)
+ }
+ })
+ }
+}
+
+func TestClefImportPreservesSourceConfig(t *testing.T) {
+ dir := t.TempDir()
+ writeClefSource(t, dir)
+ original, err := os.ReadFile(filepath.Join(dir, "config.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ ordinary, err := ReadInventory(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if ordinary.Config.Architecture() != "Qwen3_5ForConditionalGeneration" || ordinary.Has("memory_projection.weight") {
+ t.Fatalf("filenames selected Clef without explicit intent: %+v", ordinary)
+ }
+ store := newCaptureStore()
+ var result ManifestInfo
+ err = Create(t.Context(), "clef-test", dir, PipelineOptions{
+ Renderer: "clef",
+ Validation: MLXValidationOptions{Force: true, Warning: func(string) {}},
+ }, store, func(_ context.Context, _ string, info ManifestInfo) error {
+ result = info
+ return nil
+ }, func(string) {})
+ if err != nil {
+ t.Fatal(err)
+ }
+ unchanged, err := os.ReadFile(filepath.Join(dir, "config.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(unchanged, original) {
+ t.Fatal("publisher source config changed during import")
+ }
+ var source, output map[string]json.RawMessage
+ if err := json.Unmarshal(original, &source); err != nil {
+ t.Fatal(err)
+ }
+ if err := json.Unmarshal(store.blobs["config.json"], &output); err != nil {
+ t.Fatal(err)
+ }
+ source["architectures"] = json.RawMessage(`["ClefForDecision"]`)
+ if !reflect.DeepEqual(output, source) {
+ t.Fatalf("output config changed fields other than architectures: %s", store.blobs["config.json"])
+ }
+ var configLayers int
+ for _, layer := range result.Layers {
+ if layer.Name == "config.json" {
+ configLayers++
+ }
+ }
+ if configLayers != 1 {
+ t.Fatalf("got %d config.json layers, want 1", configLayers)
+ }
+ if result.ModelConfig.Renderer != "clef" || result.ModelConfig.Parser != "" || !slices.Equal(result.ModelConfig.Capabilities, []string{"decision"}) {
+ t.Fatalf("incorrect manifest config: %+v", result.ModelConfig)
+ }
+ if _, ok := store.blobs["memory_projection.weight"]; !ok {
+ t.Fatal("head tensor was omitted")
+ }
+}
+
+func TestClefMetadata(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ vision bool
+ capabilities []string
+ }{
+ {"text", false, []string{"decision"}},
+ {"vision", true, []string{"decision", "vision"}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ dir := t.TempDir()
+ writeClefSource(t, dir)
+ inv, err := ReadInventory(dir)
+ if err == nil {
+ inv, err = prepareClefInventory(inv)
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if tc.vision {
+ v := map[string]any{}
+ inv.Config.VisionConfig = &v
+ }
+ cfg, err := inferSafetensorsConfig(dir, inv.Config, "", "clef")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(cfg.Capabilities, tc.capabilities) || cfg.Parser != "" || cfg.Renderer != "clef" {
+ t.Fatalf("incorrect Clef metadata: %+v", cfg)
+ }
+ })
+ }
+}
+
+func TestClefImportRejectsIncompleteSource(t *testing.T) {
+ for _, missing := range []string{"joint_head_config.json", "joint_head.safetensors"} {
+ t.Run(missing, func(t *testing.T) {
+ dir := t.TempDir()
+ writeClefSource(t, dir)
+ if err := os.Remove(filepath.Join(dir, missing)); err != nil {
+ t.Fatal(err)
+ }
+ store := newCaptureStore()
+ err := Create(t.Context(), "clef-test", dir, PipelineOptions{Renderer: "clef"}, store, func(context.Context, string, ManifestInfo) error {
+ t.Fatal("incomplete source reached manifest writer")
+ return nil
+ }, func(string) {})
+ if err == nil || len(store.blobs) != 0 {
+ t.Fatalf("incomplete source: error=%v, wrote %d blobs", err, len(store.blobs))
+ }
+ })
+ }
+}
+
+func TestClefWeightFiles(t *testing.T) {
+ for _, tc := range []struct {
+ name, head string
+ indexed bool
+ wantError bool
+ }{
+ {name: "absent"},
+ {name: "unindexed", head: "file"},
+ {name: "already indexed", head: "file", indexed: true},
+ {name: "directory", head: "directory", wantError: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ dir := t.TempDir()
+ index := `{"weight_map":{"model.weight":"model.safetensors"}}`
+ if tc.indexed {
+ index = `{"weight_map":{"model.weight":"model.safetensors","head.weight":"joint_head.safetensors"}}`
+ }
+ if err := os.WriteFile(filepath.Join(dir, "model.safetensors.index.json"), []byte(index), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "consolidated.safetensors"), nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ head := filepath.Join(dir, "joint_head.safetensors")
+ if tc.head == "file" {
+ if err := os.WriteFile(head, nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ } else if tc.head == "directory" {
+ if err := os.Mkdir(head, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ files, err := SafetensorsWeightFiles(dir)
+ if tc.wantError {
+ if err == nil || !strings.Contains(err.Error(), "regular file") {
+ t.Fatalf("got %v, want regular-file error", err)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []string{"model.safetensors"}
+ if tc.head == "file" {
+ want = []string{"joint_head.safetensors", "model.safetensors"}
+ }
+ if !slices.Equal(files, want) {
+ t.Fatalf("files=%v, want %v", files, want)
+ }
+ })
+ }
+}
diff --git a/create/create.go b/create/create.go
index f8236eb7c..508e4f1e1 100644
--- a/create/create.go
+++ b/create/create.go
@@ -23,8 +23,7 @@ import (
// safetensors-backed models.
const SafetensorsMinOllamaVersion = "0.19.0"
-// IsSafetensorsLLMModel checks if a model is a safetensors LLM model
-// (has completion capability, not image generation).
+// IsSafetensorsLLMModel checks for a safetensors completion or decision model.
func IsSafetensorsLLMModel(modelName string) bool {
name := model.ParseName(modelName)
if !name.IsValid() {
@@ -44,15 +43,18 @@ func IsSafetensorsLLMModel(modelName string) bool {
if err := json.NewDecoder(f).Decode(&config); err != nil {
return false
}
- return config.ModelFormat == "safetensors" && slices.Contains(config.Capabilities, "completion")
+ return config.ModelFormat == "safetensors" && (slices.Contains(config.Capabilities, "completion") || slices.Contains(config.Capabilities, "decision"))
}
-// IsSafetensorsModelDir checks if the directory contains a standard safetensors model
-// by looking for config.json and at least one .safetensors file.
+// IsSafetensorsModelDir checks for a supported model config and safetensors weights.
func IsSafetensorsModelDir(dir string) bool {
- // Must have config.json
if _, err := os.Stat(filepath.Join(dir, "config.json")); err != nil {
- return false
+ if !os.IsNotExist(err) {
+ return false
+ }
+ if _, err := os.Stat(filepath.Join(dir, "rl_agent_config.json")); err != nil {
+ return false
+ }
}
// Must have at least one .safetensors file
@@ -322,6 +324,9 @@ type sourceModelConfig struct {
func readSourceModelConfig(modelDir string) (sourceModelConfig, json.RawMessage, error) {
configPath := filepath.Join(modelDir, "config.json")
data, err := os.ReadFile(configPath)
+ if os.IsNotExist(err) {
+ return readLayaConfig(modelDir)
+ }
if err != nil {
return sourceModelConfig{}, nil, fmt.Errorf("read %s: %w", configPath, err)
}
@@ -418,6 +423,8 @@ func (cfg sourceModelConfig) HFFP8WeightBlockSize() (rows, cols int32, ok bool)
type tensorImportTransformFactory func(rawConfig json.RawMessage) (quantizePolicy, error)
var tensorImportTransformRegistry = map[string]tensorImportTransformFactory{
+ "StrandsDeciderForDecision": newQwen35DecisionImportTransform,
+ "ClefForDecision": newQwen35DecisionImportTransform,
"Qwen3_5ForCausalLM": newQwen35ImportTransform,
"Qwen3_5ForConditionalGeneration": newQwen35ImportTransform,
"Qwen3NextForCausalLM": newQwen35ImportTransform,
diff --git a/create/draft.go b/create/draft.go
index 84802b8bd..81c6ef013 100644
--- a/create/draft.go
+++ b/create/draft.go
@@ -61,7 +61,7 @@ func createDraftLayers(ctx context.Context, modelDir, tensorPrefix, configPrefix
return nil, err
}
- configLayers, _, err := importConfigBlobs(ctx, modelDir, configPrefix, store, fn)
+ configLayers, _, err := importConfigBlobs(ctx, modelDir, configPrefix, nil, store, fn)
if err != nil {
return nil, err
}
diff --git a/create/inventory.go b/create/inventory.go
index eea8a2e5a..cad2bae9c 100644
--- a/create/inventory.go
+++ b/create/inventory.go
@@ -112,12 +112,48 @@ func ReadInventory(dir string) (Inventory, error) {
return Inventory{Dir: dir, Config: cfg, RawConfig: rawConfig, Tensors: tensors}, nil
}
-// SafetensorsWeightFiles returns the weight shards selected by the same index
-// rules used by ReadInventory. Callers that transfer a source model should use
-// this list rather than guessing shard names.
+// SafetensorsWeightFiles returns the source shards and supported sidecars for
+// transfer. Importing a sidecar still requires its model-specific importer.
func SafetensorsWeightFiles(dir string) ([]string, error) {
_, files, err := safetensorsWeightFiles(dir)
- return files, err
+ if err != nil {
+ return nil, err
+ }
+ return clefWeightFiles(dir, files)
+}
+
+// SafetensorsConfigFiles lists source metadata for remote transfer and local
+// JSON import. Auxiliary checkpoint subfolders are excluded.
+func SafetensorsConfigFiles(dir string) ([]string, error) {
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ return nil, err
+ }
+ var names []string
+ var hasLaya bool
+ for _, entry := range entries {
+ if entry.IsDir() {
+ continue
+ }
+ name := entry.Name()
+ hasLaya = hasLaya || name == "rl_agent_config.json"
+ if filepath.Ext(name) == ".json" || name == "chat_template.jinja" {
+ names = append(names, name)
+ }
+ }
+ if hasLaya {
+ for _, name := range []string{"encoder/config.json", "tokenizer/tokenizer.json", "tokenizer/tokenizer_config.json"} {
+ info, err := os.Stat(filepath.Join(dir, filepath.FromSlash(name)))
+ if err != nil {
+ return nil, err
+ }
+ if !info.Mode().IsRegular() {
+ return nil, fmt.Errorf("Laya metadata %s is not a regular file", name)
+ }
+ names = append(names, name)
+ }
+ }
+ return names, nil
}
func safetensorsWeightFiles(dir string) (map[string]string, []string, error) {
diff --git a/create/laya.go b/create/laya.go
new file mode 100644
index 000000000..e6398116a
--- /dev/null
+++ b/create/laya.go
@@ -0,0 +1,50 @@
+package create
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+)
+
+// Laya ships an encoder config and a decision config rather than a root HF
+// config. Keep both verbatim and add only the descriptor Ollama uses to dispatch.
+func readLayaConfig(dir string) (sourceModelConfig, json.RawMessage, error) {
+ var decision struct {
+ Encoder string `json:"encoder"`
+ MaxLen int `json:"max_len"`
+ HeadLayers *int `json:"head_layers"`
+ }
+ data, err := os.ReadFile(filepath.Join(dir, "rl_agent_config.json"))
+ if err != nil {
+ return sourceModelConfig{}, nil, err
+ }
+ if err := json.Unmarshal(data, &decision); err != nil {
+ return sourceModelConfig{}, nil, fmt.Errorf("parse rl_agent_config.json: %w", err)
+ }
+ var encoder struct {
+ ModelType string `json:"model_type"`
+ HiddenSize int `json:"hidden_size"`
+ NumHiddenLayers int `json:"num_hidden_layers"`
+ NumAttentionHeads int `json:"num_attention_heads"`
+ VocabSize int `json:"vocab_size"`
+ }
+ data, err = os.ReadFile(filepath.Join(dir, "encoder", "config.json"))
+ if err != nil {
+ return sourceModelConfig{}, nil, err
+ }
+ if err := json.Unmarshal(data, &encoder); err != nil {
+ return sourceModelConfig{}, nil, fmt.Errorf("parse encoder/config.json: %w", err)
+ }
+ if decision.Encoder == "" || decision.MaxLen <= 0 || decision.HeadLayers == nil || encoder.ModelType != "modernbert" {
+ return sourceModelConfig{}, nil, fmt.Errorf("unsupported Laya source configuration")
+ }
+ cfg := sourceModelConfig{ModelType: "laya", Architectures: []string{"LayaForDecision"}}
+ data, err = json.Marshal(map[string]any{
+ "architectures": cfg.Architectures, "model_type": cfg.ModelType,
+ "hidden_size": encoder.HiddenSize, "num_hidden_layers": encoder.NumHiddenLayers,
+ "num_attention_heads": encoder.NumAttentionHeads, "vocab_size": encoder.VocabSize,
+ "max_position_embeddings": decision.MaxLen,
+ })
+ return cfg, data, err
+}
diff --git a/create/laya_test.go b/create/laya_test.go
new file mode 100644
index 000000000..89e2d17a3
--- /dev/null
+++ b/create/laya_test.go
@@ -0,0 +1,94 @@
+package create
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+
+ st "github.com/ollama/ollama/fs/safetensors"
+)
+
+func TestCreateLaya(t *testing.T) {
+ dir := t.TempDir()
+ configs := map[string]string{
+ "rl_agent_config.json": `{"encoder":"answerdotai/ModernBERT-large","max_len":512,"head_layers":2}`,
+ "encoder/config.json": `{"model_type":"modernbert","hidden_size":1024,"num_hidden_layers":28,"num_attention_heads":16,"vocab_size":50368}`,
+ "tokenizer/tokenizer.json": `{"model":{"type":"BPE"}}`,
+ "tokenizer/tokenizer_config.json": `{"cls_token":"[CLS]","sep_token":"[SEP]","mask_token":"[MASK]"}`,
+ }
+ for name, data := range configs {
+ path := filepath.Join(dir, name)
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(data), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{
+ st.NewTensorDataFromBytes("encoder.final_norm.weight", "F16", []int32{8}, make([]byte, 16)),
+ })
+ if !IsSafetensorsModelDir(dir) {
+ t.Fatal("publisher layout was not recognized")
+ }
+ store := newCaptureStore()
+ var info ManifestInfo
+ write := func(_ context.Context, _ string, got ManifestInfo) error { info = got; return nil }
+ if err := Create(t.Context(), "laya", dir, testPipelineOptions(), store, write, func(string) {}); err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(info.ModelConfig.Capabilities, []string{"decision"}) {
+ t.Fatalf("capabilities: %v", info.ModelConfig.Capabilities)
+ }
+ for name, data := range configs {
+ if !bytes.Equal(store.blobs[name], []byte(data)) {
+ t.Errorf("publisher metadata changed: %s", name)
+ }
+ }
+ var descriptor struct {
+ Architectures []string `json:"architectures"`
+ MaxLen int `json:"max_position_embeddings"`
+ }
+ if err := json.Unmarshal(store.blobs["config.json"], &descriptor); err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(descriptor.Architectures, []string{"LayaForDecision"}) || descriptor.MaxLen != 512 {
+ t.Fatalf("descriptor: %+v", descriptor)
+ }
+ if _, err := os.Stat(filepath.Join(dir, "config.json")); !os.IsNotExist(err) {
+ t.Fatalf("import changed source: %v", err)
+ }
+ // A prepared source with the root descriptor still needs its nested metadata.
+ if err := os.WriteFile(filepath.Join(dir, "config.json"), store.blobs["config.json"], 0o644); err != nil {
+ t.Fatal(err)
+ }
+ store = newCaptureStore()
+ if err := Create(t.Context(), "laya", dir, testPipelineOptions(), store, write, func(string) {}); err != nil {
+ t.Fatal(err)
+ }
+ for name, data := range configs {
+ if !bytes.Equal(store.blobs[name], []byte(data)) {
+ t.Errorf("prepared source lost metadata: %s", name)
+ }
+ }
+ opts := testPipelineOptions()
+ opts.Quantize = "int4"
+ store = newCaptureStore()
+ if err := Create(t.Context(), "laya", dir, opts, store, write, func(string) {}); err == nil || !strings.Contains(err.Error(), "unquantized") {
+ t.Fatalf("quantization: %v", err)
+ }
+ if len(store.blobs) != 0 {
+ t.Fatal("unsupported quantization wrote blobs")
+ }
+ if err := os.Remove(filepath.Join(dir, "tokenizer/tokenizer.json")); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := SafetensorsConfigFiles(dir); err == nil {
+ t.Fatal("accepted incomplete tokenizer")
+ }
+}
diff --git a/create/metadata.go b/create/metadata.go
index d662000f9..39ea1f46b 100644
--- a/create/metadata.go
+++ b/create/metadata.go
@@ -97,6 +97,16 @@ func readChatTemplateStrict(modelDir string) (string, error) {
}
func inferSafetensorsCapabilitiesFromConfig(cfg sourceModelConfig, chatTemplate, parserName string) []string {
+ if cfg.Architecture() == "ClefForDecision" {
+ capabilities := []string{"decision"}
+ if cfg.VisionConfig != nil {
+ capabilities = append(capabilities, "vision")
+ }
+ return capabilities
+ }
+ if cfg.Architecture() == "LayaForDecision" || cfg.Architecture() == "StrandsDeciderForDecision" {
+ return []string{"decision"}
+ }
capabilities := []string{"completion"}
caps := detectCapabilitiesFromConfig(cfg, chatTemplate)
@@ -207,6 +217,9 @@ func sourceConfigIdentifiers(cfg sourceModelConfig) []string {
}
func parserNameForConfig(modelDir string, cfg sourceModelConfig, chatTemplate string) (string, error) {
+ if cfg.Architecture() == "ClefForDecision" || cfg.Architecture() == "StrandsDeciderForDecision" {
+ return "", nil
+ }
for _, id := range sourceConfigIdentifiers(cfg) {
name, err := parserNameForIdentifier(modelDir, id, chatTemplate)
if err != nil || name != "" {
@@ -255,6 +268,10 @@ func rendererNameForConfig(modelDir string, cfg sourceModelConfig, chatTemplate
func rendererNameForIdentifier(modelDir, s, chatTemplate string) (string, error) {
s = strings.ToLower(s)
switch {
+ case s == "strandsdeciderfordecision":
+ return "strands", nil
+ case s == "cleffordecision":
+ return "clef", nil
case strings.HasPrefix(s, "museglimmer") || s == "muse_glimmer":
return "glimmer", nil
case strings.Contains(s, "laguna"):
diff --git a/create/metadata_test.go b/create/metadata_test.go
index 0ab28f762..a93c3e12b 100644
--- a/create/metadata_test.go
+++ b/create/metadata_test.go
@@ -283,3 +283,15 @@ func inferConfigForTest(t *testing.T, modelDir, parser, renderer string) model.C
}
return config
}
+
+func TestStrandsDecisionMetadata(t *testing.T) {
+ cfg := sourceModelConfig{Architectures: []string{"StrandsDeciderForDecision"}, ModelType: "qwen3_5"}
+ // The Qwen backbone must not advertise chat or thinking for a pointer head.
+ got, err := inferSafetensorsConfig(t.TempDir(), cfg, "", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.Parser != "" || got.Renderer != "strands" || len(got.Capabilities) != 1 || got.Capabilities[0] != "decision" {
+ t.Fatalf("unexpected Strands metadata: %+v", got)
+ }
+}
diff --git a/create/pipeline.go b/create/pipeline.go
index f9058a027..35d990f05 100644
--- a/create/pipeline.go
+++ b/create/pipeline.go
@@ -1,8 +1,11 @@
package create
import (
+ "bytes"
"context"
+ "encoding/json"
"fmt"
+ "io"
"os"
"path/filepath"
"strings"
@@ -35,6 +38,12 @@ func Create(ctx context.Context, modelName, modelDir string, opts PipelineOption
if err != nil {
return fmt.Errorf("read model: %w", err)
}
+ if opts.Renderer == "clef" {
+ inv, err = prepareClefInventory(inv)
+ if err != nil {
+ return err
+ }
+ }
modelConfig, err := inferSafetensorsConfig(modelDir, inv.Config, opts.Parser, opts.Renderer)
if err != nil {
return err
@@ -51,6 +60,9 @@ func Create(ctx context.Context, modelName, modelDir string, opts PipelineOption
if err := checkContext(ctx); err != nil {
return err
}
+ if inv.Config.Architecture() == "LayaForDecision" && opts.Quantize != "" {
+ return fmt.Errorf("Laya currently requires unquantized weights")
+ }
class, err := Classify(inv, opts.Quantize)
if err != nil {
return err
@@ -79,14 +91,18 @@ func Create(ctx context.Context, modelName, modelDir string, opts PipelineOption
}
// Import config files (config.json, tokenizer, etc.) as JSON blobs.
- configLayers, configLayer, err := importConfigBlobs(ctx, modelDir, "", store, fn)
+ configLayers, configLayer, err := importConfigBlobs(ctx, modelDir, "", inv.RawConfig, store, fn)
if err != nil {
return err
}
layers = append(layers, configLayers...)
layers = append(layers, draftLayers...)
if configLayer.Digest == "" {
- return fmt.Errorf("config.json not found in %s", modelDir)
+ configLayer, err = store.WriteBlob(bytes.NewReader(inv.RawConfig), mediaTypeImageJSON, "config.json")
+ if err != nil {
+ return err
+ }
+ layers = append(layers, configLayer)
}
if err := checkContext(ctx); err != nil {
return err
@@ -113,26 +129,31 @@ const mediaTypeImageJSON = "application/vnd.ollama.image.json"
// image.json blob, prefixing each blob name with namePrefix, and returns the
// resulting layers along with the config.json layer (zero value if absent). The
// target import passes "" for namePrefix; a draft import passes "draft/" so its
-// config sits beside the target's.
-func importConfigBlobs(ctx context.Context, modelDir, namePrefix string, store BlobStore, fn func(status string)) ([]LayerInfo, LayerInfo, error) {
- entries, err := os.ReadDir(modelDir)
+// config sits beside the target's. configOverride replaces only config.json
+// when an importer has normalized its contents.
+func importConfigBlobs(ctx context.Context, modelDir, namePrefix string, configOverride json.RawMessage, store BlobStore, fn func(status string)) ([]LayerInfo, LayerInfo, error) {
+ names, err := SafetensorsConfigFiles(modelDir)
if err != nil {
return nil, LayerInfo{}, err
}
var layers []LayerInfo
var configLayer LayerInfo
- for _, entry := range entries {
+ for _, name := range names {
if err := checkContext(ctx); err != nil {
return nil, LayerInfo{}, err
}
- if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") || entry.Name() == "model.safetensors.index.json" {
+ if !strings.HasSuffix(name, ".json") || name == "model.safetensors.index.json" {
continue
}
- name := entry.Name()
fn(fmt.Sprintf("importing config %s", name))
- f, err := os.Open(filepath.Join(modelDir, name))
- if err != nil {
- return nil, LayerInfo{}, fmt.Errorf("open %s: %w", name, err)
+ var f io.ReadCloser
+ if name == "config.json" && configOverride != nil {
+ f = io.NopCloser(bytes.NewReader(configOverride))
+ } else {
+ f, err = os.Open(filepath.Join(modelDir, name))
+ if err != nil {
+ return nil, LayerInfo{}, fmt.Errorf("open %s: %w", name, err)
+ }
}
layer, err := store.WriteBlob(ReaderWithContext(ctx, f), mediaTypeImageJSON, namePrefix+name)
closeErr := f.Close()
diff --git a/create/qwen35_decision.go b/create/qwen35_decision.go
new file mode 100644
index 000000000..4df7e5cd3
--- /dev/null
+++ b/create/qwen35_decision.go
@@ -0,0 +1,21 @@
+package create
+
+import (
+ "encoding/json"
+ "strings"
+)
+
+type qwen35DecisionImportTransform struct{}
+
+func newQwen35DecisionImportTransform(json.RawMessage) (quantizePolicy, error) {
+ return qwen35DecisionImportTransform{}, nil
+}
+
+func (qwen35DecisionImportTransform) quantizationType(name string, shape []int32, requested string) string {
+ // Only backbone tensors are quantized. Decision heads and any
+ // lexical output embeddings retain source precision.
+ if !strings.HasPrefix(name, "model.") {
+ return ""
+ }
+ return qwen35ImportTransform{}.quantizationType(name, shape, requested)
+}
diff --git a/create/qwen35_decision_test.go b/create/qwen35_decision_test.go
new file mode 100644
index 000000000..4dfbde229
--- /dev/null
+++ b/create/qwen35_decision_test.go
@@ -0,0 +1,35 @@
+package create
+
+import "testing"
+
+func TestQwen35DecisionQuantizationPolicy(t *testing.T) {
+ for _, arch := range []string{"ClefForDecision", "StrandsDeciderForDecision"} {
+ inv := Inventory{Config: sourceModelConfig{Architectures: []string{arch}}}
+ policy, err := newTensorImportTransform(inv)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, tc := range []struct {
+ name string
+ want string
+ }{
+ {"memory_proj.weight", ""},
+ {"q.weight", ""},
+ {"k.weight", ""},
+ {"norm.weight", ""},
+ {"lm_head.weight", ""},
+ {"model.language_model.layers.0.linear_attn.in_proj_a.weight", ""},
+ {"model.language_model.layers.0.mlp.gate_proj.weight", "mxfp8"},
+ } {
+ t.Run(arch+"/"+tc.name, func(t *testing.T) {
+ if got := policy.quantizationType(tc.name, []int32{1024, 1024}, "mxfp8"); got != tc.want {
+ t.Errorf("quantization = %q, want %q", got, tc.want)
+ }
+ })
+ }
+ }
+ ordinary := qwen35ImportTransform{}
+ if got := ordinary.quantizationType("lm_head.weight", []int32{1024, 1024}, "mxfp8"); got != "mxfp8" {
+ t.Errorf("ordinary Qwen output quantization = %q, want mxfp8", got)
+ }
+}
diff --git a/decision/clef.go b/decision/clef.go
index 31d0b419a..f8766e946 100644
--- a/decision/clef.go
+++ b/decision/clef.go
@@ -10,6 +10,7 @@ import (
"strconv"
"strings"
+ "github.com/ollama/ollama/internal/orderedmap"
"github.com/ollama/ollama/llm"
)
@@ -58,6 +59,13 @@ func encodeClef(req Request, c *Compiled) error {
}
add("END FIELD\n")
input.Fields = append(input.Fields, field)
+ if len(f.order) > 0 {
+ choices := make([]Choice, len(f.Choices))
+ for j, index := range f.order {
+ choices[index] = f.Choices[j]
+ }
+ f.Choices = choices
+ }
c.fields = append(c.fields, f)
}
add("\n<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\nJOINT SCHEMA DECISIONS:")
@@ -111,11 +119,20 @@ func clefField(name string, q Question) (compiledField, error) {
if !ok {
return f, fmt.Errorf("choice criteria must be an object")
}
+ ordered := orderedmap.New[string, json.RawMessage]()
+ if err := json.Unmarshal(q.Criteria, ordered); err != nil {
+ return f, err
+ }
+ var original []string
+ for key := range ordered.All() {
+ original = append(original, key)
+ }
for _, key := range slices.Sorted(maps.Keys(values)) {
if strings.TrimSpace(key) == "" {
return f, fmt.Errorf("choice keys must not be empty")
}
add(key, values[key])
+ f.order = append(f.order, slices.Index(original, key))
}
case "score":
values, ok := criteria.([]any)
diff --git a/decision/clef_test.go b/decision/clef_test.go
index 891cf323e..706cbef9b 100644
--- a/decision/clef_test.go
+++ b/decision/clef_test.go
@@ -3,6 +3,7 @@ package decision
import (
"encoding/json"
"math"
+ "reflect"
"strings"
"testing"
@@ -15,7 +16,7 @@ func TestCompileClef(t *testing.T) {
if err := json.Unmarshal([]byte(`{"model":"renamed-model","state":{"z":2,"a":"café & <x>"},"questions":{"team":{"type":"choice","instructions":"Route it","criteria":{"z":null,"a":"First"}},"yes":{"type":"noul","instructions":{"z":2,"a":1}},"rating":{"type":"score","instructions":"Rate it","criteria":["Low","High"]}}}`), &req); err != nil {
t.Fatal(err)
}
- c, err := CompileWithEncoder(req, "clef")
+ c, err := Compile(req, "clef")
if err != nil {
t.Fatal(err)
}
@@ -61,14 +62,14 @@ func TestCompileClef(t *testing.T) {
func TestCompileClefImages(t *testing.T) {
req := testRequest(t)
req.Images = []api.ImageData{[]byte("first image"), []byte("second image")}
- c, err := CompileWithEncoder(req, "clef")
+ c, err := Compile(req, "clef")
if err != nil {
t.Fatal(err)
}
if c.Request.ImagePosition != 1 || len(c.Request.Images) != 2 || string(c.Request.Images[1]) != "second image" {
t.Fatalf("images were not preserved before state: %+v", c.Request)
}
- if _, err := Compile(req); err == nil {
+ if _, err := Compile(req, ""); err == nil {
t.Fatal("candidate scoring silently ignored images")
}
}
@@ -107,7 +108,7 @@ func TestClefSchema(t *testing.T) {
if err := json.Unmarshal([]byte(`{"model":"clef","state":null,"questions":{"team":{"type":"choice","criteria":{"z":null,"a":{"text":"First","weight":1e6}}},"yes":{"type":"noul","instructions":null,"criteria":{"true":null}},"rating":{"type":"score","instructions":"","criteria":[null,{"text":"High"}]}}}`), &req); err != nil {
t.Fatal(err)
}
- c, err := CompileWithEncoder(req, "clef")
+ c, err := Compile(req, "clef")
if err != nil {
t.Fatal(err)
}
@@ -143,7 +144,7 @@ func TestClefSchema(t *testing.T) {
if err != nil || string(legend) != `{"0":null,"1":{"text":"High"}}` {
t.Fatalf("legend = %s, %v", legend, err)
}
- if _, err := Compile(req); err == nil {
+ if _, err := Compile(req, ""); err == nil {
t.Fatal("broadened the candidate-scoring schema")
}
}
@@ -163,7 +164,7 @@ func TestClefValidation(t *testing.T) {
if err := json.Unmarshal([]byte(raw), &req); err != nil {
t.Fatal(err)
}
- if _, err := CompileWithEncoder(req, "clef"); err == nil {
+ if _, err := Compile(req, "clef"); err == nil {
t.Fatalf("accepted invalid request %s", raw)
}
}
@@ -173,12 +174,137 @@ func TestDecisionRejectsVideo(t *testing.T) {
for _, encoding := range []string{"", "clef"} {
req := testRequest(t)
req.Videos = []json.RawMessage{json.RawMessage(`"video.mp4"`)}
- if _, err := CompileWithEncoder(req, encoding); err == nil || !strings.Contains(err.Error(), "video") {
+ if _, err := Compile(req, encoding); err == nil || !strings.Contains(err.Error(), "video") {
t.Fatalf("encoding %q silently accepted video: %v", encoding, err)
}
req.Videos = nil
- if _, err := CompileWithEncoder(req, encoding); err != nil {
+ if _, err := Compile(req, encoding); err != nil {
t.Fatal(err)
}
}
}
+
+func TestClefInvalidCriteria(t *testing.T) {
+ for _, question := range []string{
+ `{"type":"choice"}`,
+ `{"type":"choice","criteria":{"":"empty","valid":"valid"}}`,
+ `{"type":"noul","criteria":{"yes":"invalid"}}`,
+ `{"type":"noul","criteria":[]}`,
+ `{"type":"score","criteria":{"a":"invalid"}}`,
+ `{"type":"score","criteria":["one"]}`,
+ `{"type":"score","criteria":["x"` + strings.Repeat(`,"x"`, 26) + `]}`,
+ `{"type":"unknown"}`,
+ } {
+ var req Request
+ if err := json.Unmarshal([]byte(`{"model":"clef","state":"x","questions":{"q":`+question+`}}`), &req); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := Compile(req, "clef"); err == nil {
+ t.Errorf("accepted invalid question %s", question)
+ }
+ }
+}
+
+func TestDecisionMedia(t *testing.T) {
+ for _, tc := range []struct {
+ name, renderer, media, wantError string
+ }{
+ {"images", "clef", `"images":["Zmlyc3Q=","c2Vjb25k"]`, ""},
+ {"empty image", "clef", `"images":[""]`, "must not be empty"},
+ {"null image", "clef", `"images":[null]`, "must not be empty"},
+ {"other model", "tev1", `"images":["Zmlyc3Q="]`, "not supported"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var req Request
+ if err := json.Unmarshal([]byte(`{"model":"clef-flash","state":"x","questions":{"q":{"type":"noul","instructions":"q"}},`+tc.media+`}`), &req); err != nil {
+ t.Fatal(err)
+ }
+ compiled, err := Compile(req, tc.renderer)
+ if tc.wantError != "" {
+ if err == nil || !strings.Contains(err.Error(), tc.wantError) {
+ t.Fatalf("Compile() error = %v, want %q", err, tc.wantError)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if tc.name == "images" {
+ data, err := json.Marshal(compiled.Request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var wire llm.ScoreRequest
+ if err := json.Unmarshal(data, &wire); err != nil {
+ t.Fatal(err)
+ }
+ if want := []api.ImageData{[]byte("first"), []byte("second")}; !reflect.DeepEqual(wire.Images, want) {
+ t.Fatalf("runner images = %q, want %q", wire.Images, want)
+ }
+ if wire.ImagePosition != 1 {
+ t.Fatalf("images must follow prefix segment, got boundary %d", wire.ImagePosition)
+ }
+ }
+ })
+ }
+}
+
+func TestCompileClefRejectsEmptyQuestion(t *testing.T) {
+ for _, name := range []string{"", " "} {
+ for _, instructions := range []json.RawMessage{nil, json.RawMessage(`null`), json.RawMessage(`""`)} {
+ req := Request{Model: "clef-flash", State: json.RawMessage(`"state"`), Questions: &Questions{}}
+ req.Questions.Set(name, Question{Type: "noul", Instructions: instructions})
+ if _, err := Compile(req, "clef"); err == nil {
+ t.Errorf("accepted empty question %q with instructions %s", name, instructions)
+ }
+ }
+ }
+}
+
+func TestCompileClefImageOnlyState(t *testing.T) {
+ var req Request
+ if err := json.Unmarshal([]byte(`{"model":"clef-flash","state":"","images":["aW1hZ2U="],"questions":{"q":{"type":"noul"}}}`), &req); err != nil {
+ t.Fatal(err)
+ }
+ compiled, err := Compile(req, "clef")
+ if err != nil || compiled.Request.Segments[1] != "" || len(compiled.Request.Images) != 1 {
+ t.Fatalf("image-only request = %+v, error = %v", compiled, err)
+ }
+ req.Images = nil
+ if _, err := Compile(req, "clef"); err == nil {
+ t.Fatal("accepted empty state without an image")
+ }
+}
+
+func TestClefAnswerOrder(t *testing.T) {
+ var req Request
+ if err := json.Unmarshal([]byte(`{"model":"clef","state":"x","questions":{"choice":{"type":"choice","criteria":{"z":"Last","a":"First"}},"noul":{"type":"noul"}}}`), &req); err != nil {
+ t.Fatal(err)
+ }
+ c, err := Compile(req, "clef")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, logits := range [][]float32{{0, 2}, {0, 0}} {
+ answer, err := c.Answer(req.Model, llm.ScoreResponse{Logits: [][]float32{logits, {2, 0}}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ value, _ := answer.Answers.Get("choice")
+ choice := value.(ChoiceAnswer)
+ if choice.Choice != "z" {
+ t.Fatalf("winner must use original option IDs and request order for ties: %+v", choice)
+ }
+ var keys []string
+ for key := range choice.Probabilities.All() {
+ keys = append(keys, key)
+ }
+ if !reflect.DeepEqual(keys, []string{"z", "a"}) {
+ t.Fatalf("response reordered probabilities: %v", keys)
+ }
+ value, _ = answer.Answers.Get("noul")
+ if value.(NoulAnswer).Noul < 0.88 {
+ t.Fatalf("true-first model logit was assigned to false: %+v", value)
+ }
+ }
+}
diff --git a/decision/prompts.go b/decision/prompts.go
new file mode 100644
index 000000000..1801b22dc
--- /dev/null
+++ b/decision/prompts.go
@@ -0,0 +1,94 @@
+package decision
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "strings"
+
+ "github.com/ollama/ollama/model/renderers"
+)
+
+func decisionPrompts(context string, fields []compiledField, renderer string) ([]string, error) {
+ var prompts []string
+ if renderer == "tev1" {
+ for _, f := range fields {
+ if len(f.Choices) > 24 {
+ return nil, fmt.Errorf("question %q: Tev1 supports at most 24 candidates", f.Name)
+ }
+ type option struct {
+ Label string `json:"label"`
+ Key string `json:"key"`
+ Description string `json:"description"`
+ }
+ var options []option
+ for _, c := range f.Choices {
+ description, ok := c.Description.(string)
+ if !ok || strings.TrimSpace(description) == "" {
+ return nil, fmt.Errorf("question %q: Tev1 requires nonempty candidate descriptions", f.Name)
+ }
+ options = append(options, option{c.Code, fmt.Sprint(c.Value), description})
+ }
+ prompt, err := promptJSON(struct {
+ State string `json:"state"`
+ Question string `json:"question"`
+ Options []option `json:"options"`
+ }{context, f.Description, options})
+ if err != nil {
+ return nil, err
+ }
+ prompts = append(prompts, prompt)
+ }
+ return prompts, nil
+ }
+
+ data, err := promptJSON(struct {
+ Context string `json:"context"`
+ Schema []compiledField `json:"schema"`
+ }{context, fields})
+ if err != nil {
+ return nil, err
+ }
+ // Nimble escapes chat delimiters in both the schema and the requested name.
+ escape := strings.NewReplacer("<", `\u003c`, ">", `\u003e`)
+ for _, f := range fields {
+ name, err := promptJSON(f.Name)
+ if err != nil {
+ return nil, err
+ }
+ prompts = append(prompts, escape.Replace(data)+"\n\nRequested field: "+escape.Replace(name))
+ }
+ return prompts, nil
+}
+
+// Both publishers serialize prompts with Python's json.dumps(ensure_ascii=False).
+func promptJSON(v any) (string, error) {
+ var b bytes.Buffer
+ enc := json.NewEncoder(&b)
+ enc.SetEscapeHTML(false)
+ if err := enc.Encode(v); err != nil {
+ return "", err
+ }
+ data := renderers.AddJSONSpaces(bytes.TrimSuffix(b.Bytes(), []byte{'\n'}))
+ var out strings.Builder
+ for i := 0; i < len(data); i++ {
+ // encoding/json always escapes these two runes. Leave literal backslash
+ // sequences alone by consuming each escape as a unit.
+ if data[i] == '\\' && i+1 < len(data) {
+ if bytes.HasPrefix(data[i:], []byte(`\u2028`)) {
+ out.WriteRune('\u2028')
+ i += 5
+ continue
+ }
+ if bytes.HasPrefix(data[i:], []byte(`\u2029`)) {
+ out.WriteRune('\u2029')
+ i += 5
+ continue
+ }
+ out.WriteByte(data[i])
+ i++
+ }
+ out.WriteByte(data[i])
+ }
+ return out.String(), nil
+}
diff --git a/decision/prompts_test.go b/decision/prompts_test.go
new file mode 100644
index 000000000..c452384b3
--- /dev/null
+++ b/decision/prompts_test.go
@@ -0,0 +1,79 @@
+package decision
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "github.com/ollama/ollama/api"
+)
+
+func TestPublisherPrompts(t *testing.T) {
+ var req Request
+ if err := json.Unmarshal([]byte(`{"model":"decision","state":"Paid €20 & <tag>. Literal \\u2028, quote \" and colon: comma,","questions":{"refund":{"type":"noul","instructions":"Refund requested?"}}}`), &req); err != nil {
+ t.Fatal(err)
+ }
+ // Publisher contracts: Together's examples/decide.py payload() and Bespoke's
+ // parallel_schema.prepare_prompts(), with false/true mapped to No/Yes.
+ for _, tc := range []struct{ renderer, want string }{
+ {"tev1", `{"state": "Paid €20 & <tag>. Literal \\u2028, quote \" and colon: comma,", "question": "Refund requested?", "options": [{"label": "A", "key": "false", "description": "No"}, {"label": "B", "key": "true", "description": "Yes"}]}`},
+ {"", `{"context": "Paid €20 & \u003ctag\u003e. Literal \\u2028, quote \" and colon: comma,", "schema": [{"name": "refund", "description": "Refund requested?", "choices": [{"code": "A", "value": false, "description": "No"}, {"code": "B", "value": true, "description": "Yes"}]}]}` + "\n\nRequested field: \"refund\""},
+ } {
+ t.Run(tc.renderer, func(t *testing.T) {
+ compiled, err := Compile(req, tc.renderer)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := compiled.Render(func(messages []api.Message) (string, error) { return messages[0].Content, nil }); err != nil {
+ t.Fatal(err)
+ }
+ if got := compiled.Request.Rows[0].Prompt; got != tc.want {
+ t.Fatalf("prompt differs from publisher format:\ngot %s\nwant %s", got, tc.want)
+ }
+ })
+ }
+ got, err := promptJSON("\u2028\u2029\\u2028\\u2029")
+ if want := "\"\u2028\u2029\\\\u2028\\\\u2029\""; err != nil || got != want {
+ t.Fatalf("Unicode escaping = %q, %v; want %q", got, err, want)
+ }
+}
+
+func TestTevQuestions(t *testing.T) {
+ req := testRequest(t)
+ req.State = json.RawMessage(`{"frames":["first","second"]}`)
+ compiled, err := Compile(req, "tev1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := compiled.Render(func(messages []api.Message) (string, error) { return messages[0].Content, nil }); err != nil {
+ t.Fatal(err)
+ }
+ for i, row := range compiled.Request.Rows {
+ var payload struct {
+ State string
+ Question string
+ Options []struct{ Label, Key, Description string }
+ }
+ if err := json.Unmarshal([]byte(row.Prompt), &payload); err != nil {
+ t.Fatal(err)
+ }
+ f := compiled.fields[i]
+ if payload.State != `{"frames":["first","second"]}` || payload.Question != f.Description || len(payload.Options) != len(f.Choices) {
+ t.Fatalf("question %d was not compiled independently: %s", i, row.Prompt)
+ }
+ for j, option := range payload.Options {
+ if option.Label != row.Candidates[j] || option.Description != f.Choices[j].Description || option.Key == "" {
+ t.Fatalf("question %d option %d: %+v", i, j, option)
+ }
+ }
+ }
+ for _, count := range []int{24, 25, 26} {
+ q, _ := req.Questions.Get("urgency")
+ q.Criteria = json.RawMessage(`["x"` + strings.Repeat(`,"x"`, count-1) + `]`)
+ req.Questions.Set("urgency", q)
+ _, err := Compile(req, "tev1")
+ if (err == nil) != (count == 24) {
+ t.Errorf("Tev1 accepted %d candidates: %v", count, err)
+ }
+ }
+}
diff --git a/decision/strands.go b/decision/strands.go
new file mode 100644
index 000000000..b356b1df0
--- /dev/null
+++ b/decision/strands.go
@@ -0,0 +1,176 @@
+package decision
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "strconv"
+ "strings"
+
+ "github.com/ollama/ollama/internal/orderedmap"
+ "github.com/ollama/ollama/llm"
+)
+
+// Strands Decider's pointer head reads each question independently. Its prompt
+// and option boundaries follow strands_decider/prompting.py (Apache-2.0).
+func encodeStrands(req Request, c *Compiled) error {
+ state, err := strandsContent(req.State)
+ if err != nil || strings.TrimSpace(state) == "" {
+ return fmt.Errorf("state must be a nonempty string, object, or array")
+ }
+ for name, q := range req.Questions.All() {
+ f, err := strandsField(name, q)
+ if err != nil {
+ return fmt.Errorf("question %q: %w", name, err)
+ }
+ header, typ := "Decide whether the statement is true of the state.", 0
+ if q.Type == "choice" {
+ header, typ = "Select exactly one option.", 1
+ } else if q.Type == "score" {
+ header, typ = "Rate the state against the ordered levels below (lowest first).", 2
+ }
+ var prompt strings.Builder
+ fmt.Fprintf(&prompt, "<question type=\"%s\">\n%s\n%s\n<options>\n", q.Type, header, f.Description)
+ row := llm.ScorePointerRow{Prefix: "<state>\n" + state + "\n</state>\n", Type: typ}
+ for i, option := range f.Choices {
+ start := prompt.Len()
+ fmt.Fprintf(&prompt, "%d. %v", i+1, option.Value)
+ description := strings.Join(strings.Fields(option.Description.(string)), " ")
+ if description != "" {
+ prompt.WriteString(" — " + description)
+ }
+ row.Options = append(row.Options, [2]int{start, prompt.Len()})
+ prompt.WriteByte('\n')
+ }
+ prompt.WriteString("</options>\n</question>\n<answer>")
+ row.Prompt = prompt.String()
+ c.Request.PointerRows = append(c.Request.PointerRows, row)
+ c.fields = append(c.fields, f)
+ }
+ return nil
+}
+
+func strandsField(name string, q Question) (compiledField, error) {
+ f := compiledField{Field: Field{Name: name}, typ: q.Type}
+ if strings.TrimSpace(name) == "" {
+ return f, fmt.Errorf("field name must not be empty")
+ }
+ var err error
+ f.Description, err = strandsContent(q.Instructions)
+ if err != nil || strings.TrimSpace(f.Description) == "" {
+ return f, fmt.Errorf("instructions must be a nonempty string, object, or array")
+ }
+ add := func(value any, description string) {
+ f.Choices = append(f.Choices, Choice{Value: value, Description: strings.TrimSpace(description)})
+ }
+ limit := 255
+ switch q.Type {
+ case "noul":
+ criteria := map[string]string{
+ "false": "the statement does not hold for this state",
+ "true": "the statement holds for this state",
+ }
+ if raw := bytes.TrimSpace(q.Criteria); len(raw) > 0 && string(raw) != "null" {
+ var values map[string]*string
+ if err := json.Unmarshal(raw, &values); err != nil {
+ return f, fmt.Errorf("noul criteria must be an object of true/false descriptions")
+ }
+ for k, v := range values {
+ if (k != "true" && k != "false") || v == nil {
+ return f, fmt.Errorf("noul criteria must contain only true/false string descriptions")
+ }
+ criteria[k] = *v
+ }
+ }
+ add(false, criteria["false"])
+ add(true, criteria["true"])
+ case "choice":
+ criteria := orderedmap.New[string, *string]()
+ if err := json.Unmarshal(q.Criteria, criteria); err != nil {
+ return f, fmt.Errorf("choice criteria must map option keys to descriptions or null")
+ }
+ for k, v := range criteria.All() {
+ if strings.TrimSpace(k) == "" {
+ return f, fmt.Errorf("choice keys must not be empty")
+ }
+ description := ""
+ if v != nil {
+ description = *v
+ }
+ add(k, description)
+ }
+ case "score":
+ limit = 10
+ var criteria []*string
+ if err := json.Unmarshal(q.Criteria, &criteria); err != nil {
+ return f, fmt.Errorf("score criteria must be an array of descriptions")
+ }
+ for i, v := range criteria {
+ if v == nil {
+ return f, fmt.Errorf("score descriptions must be strings")
+ }
+ add(strconv.Itoa(i), *v)
+ }
+ default:
+ return f, fmt.Errorf("type must be choice, noul, or score")
+ }
+ if len(f.Choices) < 2 || len(f.Choices) > limit {
+ return f, fmt.Errorf("criteria must contain 2–%d candidates", limit)
+ }
+ return f, nil
+}
+
+const maxStrandsContentDepth = 64
+
+// Match json.dumps(indent=2, ensure_ascii=False, sort_keys=False), preserving
+// object order and Python's number formatting as well as literal Unicode.
+func strandsContent(raw json.RawMessage) (string, error) {
+ if _, err := content(raw); err != nil {
+ return "", err
+ }
+ dec := json.NewDecoder(bytes.NewReader(raw))
+ dec.UseNumber()
+ var render func(int) (string, error)
+ render = func(depth int) (string, error) {
+ // Bound both recursion and indentation expansion of nested request data.
+ if depth > maxStrandsContentDepth {
+ return "", fmt.Errorf("content nesting exceeds %d levels", maxStrandsContentDepth)
+ }
+ token, err := dec.Token()
+ if err != nil {
+ return "", err
+ }
+ if delim, ok := token.(json.Delim); ok {
+ var parts []string
+ for dec.More() {
+ prefix := strings.Repeat(" ", depth+1)
+ if delim == '{' {
+ key, err := dec.Token()
+ if err != nil {
+ return "", err
+ }
+ quoted, _ := clefJSON(key)
+ prefix += quoted + ": "
+ }
+ value, err := render(depth + 1)
+ if err != nil {
+ return "", err
+ }
+ parts = append(parts, prefix+value)
+ }
+ end, err := dec.Token()
+ if err != nil {
+ return "", err
+ }
+ if len(parts) == 0 {
+ return fmt.Sprint(delim.String(), end), nil
+ }
+ return delim.String() + "\n" + strings.Join(parts, ",\n") + "\n" + strings.Repeat(" ", depth) + fmt.Sprint(end), nil
+ }
+ if depth == 0 {
+ return strings.TrimSpace(token.(string)), nil
+ }
+ return clefJSON(token)
+ }
+ return render(0)
+}
diff --git a/decision/strands_test.go b/decision/strands_test.go
new file mode 100644
index 000000000..81af7ebf2
--- /dev/null
+++ b/decision/strands_test.go
@@ -0,0 +1,176 @@
+package decision
+
+import (
+ "encoding/json"
+ "fmt"
+ "math"
+ "strings"
+ "testing"
+
+ "github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/llm"
+)
+
+func TestCompileStrands(t *testing.T) {
+ var req Request
+ err := json.Unmarshal([]byte(`{"model":"renamed","state":{"z":1e6,"a":["café & <x>",true,null]},"questions":{"team":{"type":"choice","instructions":" Route it ","criteria":{"z":" Last\n team ","a":null}},"yes":{"type":"noul","instructions":"Is it urgent?"},"rating":{"type":"score","instructions":["Rate it"],"criteria":["Low","High"]}}}`), &req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ c, err := Compile(req, "strands")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := c.Render(func([]api.Message) (string, error) { t.Fatal("unexpected chat template"); return "", nil }); err != nil {
+ t.Fatal(err)
+ }
+ if len(c.Request.PointerRows) != 3 || len(c.Request.Rows) != 0 || len(c.Request.Fields) != 0 {
+ t.Fatal("expected three independent pointer rows")
+ }
+ row := c.Request.PointerRows[0]
+ if want := "<state>\n{\n \"z\": 1000000.0,\n \"a\": [\n \"café & <x>\",\n true,\n null\n ]\n}\n</state>\n"; row.Prefix != want {
+ t.Fatalf("prefix = %q", row.Prefix)
+ }
+ want := "<question type=\"choice\">\nSelect exactly one option.\nRoute it\n<options>\n1. z — Last team\n2. a\n</options>\n</question>\n<answer>"
+ if row.Prompt != want {
+ t.Fatalf("prompt = %q", row.Prompt)
+ }
+ for i, want := range []string{"1. z — Last team", "2. a"} {
+ span := row.Options[i]
+ if got := row.Prompt[span[0]:span[1]]; got != want {
+ t.Fatalf("option = %q", got)
+ }
+ }
+ if c.Request.PointerRows[0].Type != 1 || c.Request.PointerRows[1].Type != 0 || c.Request.PointerRows[2].Type != 2 {
+ t.Fatal("incorrect question types")
+ }
+ if !strings.Contains(c.Request.PointerRows[1].Prompt, "1. false — the statement does not hold for this state\n2. true — the statement holds for this state") {
+ t.Fatal("wrong noul defaults")
+ }
+ answer, err := c.Answer(req.Model, llm.ScoreResponse{Logits: [][]float32{{0, 2}, {0, 2}, {0, 2}}, InputTokens: 99})
+ if err != nil {
+ t.Fatal(err)
+ }
+ v, _ := answer.Answers.Get("team")
+ choice := v.(ChoiceAnswer)
+ if choice.Choice != "a" || math.Abs(choice.Confidence-0.4729346589968384) > 1e-8 {
+ t.Fatalf("wrong choice: %+v", choice)
+ }
+ v, _ = answer.Answers.Get("rating")
+ score := v.(ScoreAnswer)
+ if math.Abs(score.Score-0.8807970779778823) > 1e-8 || math.Abs(score.Confidence-choice.Confidence) > 1e-8 {
+ t.Fatalf("wrong score: %+v", score)
+ }
+ if answer.Usage.InputTokens != 99 || answer.Usage.OutputTokens != 0 {
+ t.Fatal(answer.Usage)
+ }
+}
+
+func TestStrandsChoiceWithoutDescriptions(t *testing.T) {
+ for _, description := range []string{`null`, `""`} {
+ t.Run(description, func(t *testing.T) {
+ var req Request
+ input := fmt.Sprintf(`{"model":"strands-decider:2b-mlx-bf16","state":"Our checkout has returned 500 errors since 9am.","questions":{"label":{"type":"choice","instructions":"Which label fits this ticket?","criteria":{"billing":%s,"bug":%s,"account":%s}}}}`, description, description, description)
+ if err := json.Unmarshal([]byte(input), &req); err != nil {
+ t.Fatal(err)
+ }
+ c, err := Compile(req, "strands")
+ if err != nil {
+ t.Fatal(err)
+ }
+ row := c.Request.PointerRows[0]
+ want := "<question type=\"choice\">\nSelect exactly one option.\nWhich label fits this ticket?\n<options>\n1. billing\n2. bug\n3. account\n</options>\n</question>\n<answer>"
+ if row.Prompt != want {
+ t.Fatalf("prompt = %q, want %q", row.Prompt, want)
+ }
+ if len(row.Options) != 3 {
+ t.Fatalf("option count = %d, want 3", len(row.Options))
+ }
+ for i, want := range []string{"1. billing", "2. bug", "3. account"} {
+ span := row.Options[i]
+ if got := row.Prompt[span[0]:span[1]]; got != want {
+ t.Fatalf("option %d = %q, want %q", i, got, want)
+ }
+ }
+ })
+ }
+}
+
+func TestStrandsContent(t *testing.T) {
+ depth := maxStrandsContentDepth + 1
+ if _, err := strandsContent(json.RawMessage(strings.Repeat("[", depth) + "0" + strings.Repeat("]", depth))); err == nil {
+ t.Fatal("accepted excessive content nesting")
+ }
+ for _, tt := range []struct{ input, want string }{
+ {`" text\n"`, "text"},
+ {`[]`, "[]"},
+ {`{}`, "{}"},
+ {`{"z":{},"a":[1.0,-0.0,1e-5]}`, "{\n \"z\": {},\n \"a\": [\n 1.0,\n -0.0,\n 1e-05\n ]\n}"},
+ } {
+ got, err := strandsContent(json.RawMessage(tt.input))
+ if err != nil || got != tt.want {
+ t.Fatalf("%s: got %q, %v; want %q", tt.input, got, err, tt.want)
+ }
+ }
+}
+
+func TestStrandsValidation(t *testing.T) {
+ for _, q := range []string{
+ `{"type":"noul"}`, `{"type":"noul","instructions":null}`, `{"type":"unknown","instructions":"x"}`,
+ `{"type":"noul","instructions":""}`,
+ `{"type":"noul","instructions":" \t\n "}`,
+ `{"type":"choice","instructions":" \t\n ","criteria":{"a":"one","b":"two"}}`,
+ `{"type":"score","instructions":" \t\n ","criteria":["one","two"]}`,
+ `{"type":"noul","instructions":"x","criteria":{"true":null}}`,
+ `{"type":"noul","instructions":"x","criteria":{"maybe":"yes"}}`,
+ `{"type":"choice","instructions":"x","criteria":{"a":"only"}}`,
+ `{"type":"choice","instructions":"x","criteria":{"a":42,"b":"two"}}`,
+ `{"type":"choice","instructions":"x","criteria":{"":"one","valid":"two"}}`,
+ `{"type":"choice","instructions":"x","criteria":{" \t\n ":"one","valid":"two"}}`,
+ `{"type":"score","instructions":"x","criteria":["one",null]}`,
+ `{"type":"score","instructions":"x","criteria":["0","1","2","3","4","5","6","7","8","9","10"]}`,
+ } {
+ var req Request
+ if err := json.Unmarshal([]byte(`{"model":"s","state":"x","questions":{"q":`+q+`}}`), &req); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := Compile(req, "strands"); err == nil {
+ t.Fatalf("accepted %s", q)
+ }
+ }
+ for _, n := range []int{26, 27, 255, 256} {
+ criteria := make([]string, n)
+ for i := range criteria {
+ criteria[i] = fmt.Sprintf(`"%d":""`, i)
+ }
+ q := Question{Type: "choice", Instructions: json.RawMessage(`"choose"`), Criteria: json.RawMessage("{" + strings.Join(criteria, ",") + "}")}
+ _, err := strandsField("q", q)
+ if (err == nil) != (n <= 255) {
+ t.Fatalf("%d options: %v", n, err)
+ }
+ }
+ req := testRequest(t)
+ req.Images = []api.ImageData{[]byte("image")}
+ if _, err := Compile(req, "strands"); err == nil {
+ t.Fatal("accepted images")
+ }
+}
+
+func FuzzStrandsContent(f *testing.F) {
+ for _, seed := range []string{`"text"`, `{"z":1e6,"a":["café",true,null]}`, `[]`, `{"x":[[[0]]]}`, `null`, `{"x":`} {
+ f.Add(seed)
+ }
+ f.Fuzz(func(t *testing.T, input string) {
+ if len(input) > 64<<10 {
+ t.Skip()
+ }
+ output, err := strandsContent(json.RawMessage(input))
+ if err != nil {
+ return
+ }
+ raw := strings.TrimSpace(input)
+ if (strings.HasPrefix(raw, "{") || strings.HasPrefix(raw, "[")) && !json.Valid([]byte(output)) {
+ t.Fatalf("rendered invalid JSON: %q", output)
+ }
+ })
+}
diff --git a/decision/systemone.go b/decision/systemone.go
index 0fb4279ba..e401c3b2b 100644
--- a/decision/systemone.go
+++ b/decision/systemone.go
@@ -18,7 +18,9 @@ import (
type compiledField struct {
Field
- typ string
+ typ string
+ options []string
+ order []int // Model option index to original API option index, when different.
}
type Compiled struct {
@@ -27,14 +29,12 @@ type Compiled struct {
messages [][]api.Message
}
-// Compile validates the request and prepares candidate scoring for Nimble and Tev.
-func Compile(req Request) (*Compiled, error) {
- return CompileWithEncoder(req, "")
-}
-
-// CompileWithEncoder validates the request and encodes it using the named input format.
-// An empty encoding uses the candidate-scoring format shared by Nimble and Tev.
-func CompileWithEncoder(req Request, encoding string) (*Compiled, error) {
+func Compile(req Request, encoding string) (*Compiled, error) {
+ switch encoding {
+ case "", "tev1", "clef", "strands":
+ default:
+ return nil, fmt.Errorf("unsupported decision encoding %q", encoding)
+ }
if strings.TrimSpace(req.Model) == "" {
return nil, fmt.Errorf("model is required")
}
@@ -44,28 +44,40 @@ func CompileWithEncoder(req Request, encoding string) (*Compiled, error) {
if len(req.Videos) > 0 {
return nil, fmt.Errorf("video inputs are not supported")
}
- switch encoding {
- case "":
- if len(req.Images) > 0 {
- return nil, fmt.Errorf("this decision model does not support images")
- }
- case "clef":
- c := &Compiled{}
- if err := encodeClef(req, c); err != nil {
- return nil, err
+ if len(req.Images) != 0 && encoding != "clef" {
+ return nil, fmt.Errorf("image inputs are not supported by this decision model")
+ }
+ for i, image := range req.Images {
+ if len(image) == 0 {
+ return nil, fmt.Errorf("image %d must not be empty", i)
}
- return c, nil
- default:
- return nil, fmt.Errorf("unsupported decision encoding %q", encoding)
}
- context, err := content(req.State)
+ var context string
+ var err error
+ if encoding == "clef" {
+ context, err = clefContent(req.State)
+ } else {
+ context, err = content(req.State)
+ }
if err != nil {
return nil, fmt.Errorf("state: %w", err)
}
- if strings.TrimSpace(context) == "" {
+ if strings.TrimSpace(context) == "" && len(req.Images) == 0 {
return nil, fmt.Errorf("state must not be empty")
}
- c := &Compiled{}
+ c := &Compiled{Request: llm.ScoreRequest{State: context, Images: req.Images}}
+ if encoding == "strands" {
+ if err := encodeStrands(req, c); err != nil {
+ return nil, err
+ }
+ return c, nil
+ }
+ if encoding == "clef" {
+ if err := encodeClef(req, c); err != nil {
+ return nil, err
+ }
+ return c, nil
+ }
for name, q := range req.Questions.All() {
f, err := compileField(name, q)
if err != nil {
@@ -73,22 +85,15 @@ func CompileWithEncoder(req Request, encoding string) (*Compiled, error) {
}
c.fields = append(c.fields, f)
}
- data, err := json.Marshal(struct {
- Context string `json:"context"`
- Schema []compiledField `json:"schema"`
- }{context, c.fields})
+ prompts, err := decisionPrompts(context, c.fields, encoding)
if err != nil {
return nil, err
}
- for _, f := range c.fields {
- name, err := json.Marshal(f.Name)
- if err != nil {
- return nil, err
- }
+ for i, f := range c.fields {
c.messages = append(c.messages, []api.Message{
- {Role: "user", Content: string(data) + "\n\nRequested field: " + string(name)},
+ {Role: "user", Content: prompts[i]},
})
- var row llm.ScoreRow
+ row := llm.ScoreRow{Question: &llm.ScoreQuestion{Type: f.typ, Instructions: f.Description, Options: f.options}}
for _, choice := range f.Choices {
row.Candidates = append(row.Candidates, choice.Code)
}
@@ -166,6 +171,14 @@ func compileField(name string, q Question) (compiledField, error) {
}
add(false, no)
add(true, yes)
+ // Keep the decoder's established labels while retaining the richer
+ // descriptions used by encoder decision models.
+ f.options = []string{"false: no, the statement does not hold", "true: yes, the statement holds"}
+ for i, key := range []string{"false", "true"} {
+ if value, ok := criteria.Get(key); ok && *value != "" {
+ f.options[i] = key + ": " + *value
+ }
+ }
case "choice":
criteria := orderedmap.New[string, *string]()
if err := json.Unmarshal(q.Criteria, criteria); err != nil {
@@ -180,6 +193,11 @@ func compileField(name string, q Question) (compiledField, error) {
description = *value
}
add(key, description)
+ option := key
+ if value != nil && *value != "" {
+ option += ": " + *value
+ }
+ f.options = append(f.options, option)
}
case "score":
var criteria []*string
@@ -191,6 +209,7 @@ func compileField(name string, q Question) (compiledField, error) {
return f, fmt.Errorf("score descriptions must be strings")
}
add(strconv.Itoa(i), *description)
+ f.options = append(f.options, fmt.Sprintf("level %d: %s", i, *description))
}
default:
return f, fmt.Errorf("type must be choice, noul, or score")
@@ -202,7 +221,11 @@ func compileField(name string, q Question) (compiledField, error) {
}
func (c *Compiled) Answer(model string, result llm.ScoreResponse) (Response, error) {
- response := Response{Model: model, Answers: &Answers{}, Usage: Usage{InputTokens: result.InputTokens, OutputTokens: result.OutputTokens}}
+ response := Response{
+ Model: model, Answers: &Answers{},
+ Usage: Usage{InputTokens: result.InputTokens, OutputTokens: result.OutputTokens},
+ PromptEvalCachedCount: result.CachedTokens,
+ }
if len(result.Logits) != len(c.fields) {
return response, fmt.Errorf("scorer returned %d rows for %d questions", len(result.Logits), len(c.fields))
}
@@ -211,6 +234,13 @@ func (c *Compiled) Answer(model string, result llm.ScoreResponse) (Response, err
if len(logits) != len(f.Choices) {
return response, fmt.Errorf("scorer returned the wrong number of candidates for %q", f.Name)
}
+ if len(f.order) > 0 {
+ ordered := make([]float32, len(logits))
+ for j, index := range f.order {
+ ordered[index] = logits[j]
+ }
+ logits = ordered
+ }
peak := slices.Max(logits)
p := make([]float64, len(logits))
var sum float64
diff --git a/decision/systemone_test.go b/decision/systemone_test.go
index 663a091c7..4a15f87ac 100644
--- a/decision/systemone_test.go
+++ b/decision/systemone_test.go
@@ -31,7 +31,7 @@ func testRequest(t *testing.T) Request {
func TestCompile(t *testing.T) {
req := testRequest(t)
- compiled, err := Compile(req)
+ compiled, err := Compile(req, "")
if err != nil {
t.Fatal(err)
}
@@ -91,7 +91,7 @@ func TestCompile(t *testing.T) {
}
func TestCompileUnsupportedEncoding(t *testing.T) {
- if _, err := CompileWithEncoder(testRequest(t), "unknown"); err == nil {
+ if _, err := Compile(testRequest(t), "unknown"); err == nil {
t.Fatal("accepted unsupported decision encoding")
}
}
@@ -99,7 +99,7 @@ func TestCompileUnsupportedEncoding(t *testing.T) {
func TestStructuredStateFrames(t *testing.T) {
req := testRequest(t)
req.State = json.RawMessage(`{"frames":["first","second"],"position":7}`)
- compiled, err := Compile(req)
+ compiled, err := Compile(req, "")
if err != nil {
t.Fatal(err)
}
@@ -109,14 +109,14 @@ func TestStructuredStateFrames(t *testing.T) {
t.Fatal(err)
}
for _, row := range compiled.Request.Rows {
- if !strings.Contains(row.Prompt, `"context":"{\"frames\":[\"first\",\"second\"],\"position\":7}"`) {
+ if !strings.Contains(row.Prompt, `"context": "{\"frames\":[\"first\",\"second\"],\"position\":7}"`) {
t.Fatalf("structured state was not preserved in the text prompt: %q", row.Prompt)
}
}
}
func TestRenderError(t *testing.T) {
- compiled, err := Compile(testRequest(t))
+ compiled, err := Compile(testRequest(t), "")
if err != nil {
t.Fatal(err)
}
@@ -128,12 +128,14 @@ func TestRenderError(t *testing.T) {
func TestAnswers(t *testing.T) {
req := testRequest(t)
- c, err := Compile(req)
+ c, err := Compile(req, "")
if err != nil {
t.Fatal(err)
}
+ cached := 450
result, err := c.Answer("nimble", llm.ScoreResponse{
Logits: [][]float32{{0, 0}, {-1000, 1000}, {1000, 1000, 1000}}, InputTokens: 900,
+ CachedTokens: &cached,
})
if err != nil {
t.Fatal(err)
@@ -154,6 +156,9 @@ func TestAnswers(t *testing.T) {
if result.Usage.InputTokens != 900 || result.Usage.OutputTokens != 0 {
t.Fatalf("bad direct-scoring usage: %+v", result.Usage)
}
+ if result.PromptEvalCachedCount == nil || *result.PromptEvalCachedCount != cached {
+ t.Fatalf("cached tokens = %v, want %d", result.PromptEvalCachedCount, cached)
+ }
for _, logits := range [][][]float32{nil, {{1}, {1, 2}, {1, 2, 3}}, {{float32(math.NaN()), 0}, {0, 1}, {1, 2, 3}}} {
if _, err := c.Answer("nimble", llm.ScoreResponse{Logits: logits}); err == nil {
t.Errorf("accepted malformed runner result: %v", logits)
@@ -162,7 +167,7 @@ func TestAnswers(t *testing.T) {
}
func TestAnswerLogprobs(t *testing.T) {
- c, err := Compile(testRequest(t))
+ c, err := Compile(testRequest(t), "")
if err != nil {
t.Fatal(err)
}
@@ -204,7 +209,7 @@ func TestInvalidRequests(t *testing.T) {
if err := json.Unmarshal([]byte(data), &req); err != nil {
t.Fatal(err)
}
- if _, err := Compile(req); err == nil {
+ if _, err := Compile(req, ""); err == nil {
t.Fatal("accepted invalid request")
}
})
@@ -214,7 +219,7 @@ func TestInvalidRequests(t *testing.T) {
q.Criteria = json.RawMessage(`["x"` + strings.Repeat(`,"x"`, 26) + `]`)
req.Questions.Set("urgency", q)
for _, encoding := range []string{"", "clef"} {
- if _, err := CompileWithEncoder(req, encoding); err == nil {
+ if _, err := Compile(req, encoding); err == nil {
t.Fatalf("encoding %q accepted 27 candidates", encoding)
}
}
@@ -237,3 +242,23 @@ func TestContent(t *testing.T) {
}
}
}
+
+func TestEncoderOptions(t *testing.T) {
+ for _, tc := range []struct {
+ typ, criteria string
+ want []string
+ }{
+ {"choice", `{"z":null,"a":"","b":"described"}`, []string{"z", "a", "b: described"}},
+ {"score", `["low","high"]`, []string{"level 0: low", "level 1: high"}},
+ {"noul", `{}`, []string{"false: no, the statement does not hold", "true: yes, the statement holds"}},
+ {"noul", `{"true":"present","false":"absent"}`, []string{"false: absent", "true: present"}},
+ } {
+ f, err := compileField("answer", Question{Type: tc.typ, Instructions: json.RawMessage(`"Question?"`), Criteria: json.RawMessage(tc.criteria)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(tc.want, f.options) {
+ t.Errorf("%s options = %v, want %v", tc.typ, f.options, tc.want)
+ }
+ }
+}
diff --git a/decision/types.go b/decision/types.go
index 9b09fbfdd..1cebf8699 100644
--- a/decision/types.go
+++ b/decision/types.go
@@ -47,9 +47,10 @@ type (
)
type Response struct {
- Model string `json:"model"`
- Answers *Answers `json:"answers"`
- Usage Usage `json:"usage"`
+ Model string `json:"model"`
+ Answers *Answers `json:"answers"`
+ Usage Usage `json:"usage"`
+ PromptEvalCachedCount *int `json:"prompt_eval_cached_count,omitempty"`
}
type Usage struct {
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 60ea409ef..c66ffaa40 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -849,9 +849,9 @@ components:
$ref: "#/components/schemas/SystemOneContent"
criteria:
type: object
- description: Option keys mapped to descriptions. A null description uses the key itself. Keys must not be blank; ties follow the model's option order.
+ description: Option keys mapped to descriptions, or null for a bare label. Keys must not be blank; ties follow the model's option order. The option limit depends on the model.
minProperties: 2
- maxProperties: 26
+ maxProperties: 255
propertyNames:
pattern: '\S'
additionalProperties:
@@ -868,7 +868,7 @@ components:
$ref: "#/components/schemas/SystemOneContent"
criteria:
type: object
- description: Optional descriptions for the two outcomes. Omitted entries use No and Yes.
+ description: Optional descriptions for the two outcomes. Omitted entries use model-specific defaults.
properties:
"false":
type: string
@@ -889,7 +889,7 @@ components:
$ref: "#/components/schemas/SystemOneContent"
criteria:
type: array
- description: Descriptions ordered from the lowest score (index 0) to the highest. Defines a scale from 0 to the number of criteria minus 1.
+ description: Descriptions ordered from the lowest score (index 0) to the highest. Defines a scale from 0 to the number of criteria minus 1. The maximum number of levels depends on the model.
minItems: 2
maxItems: 26
items:
diff --git a/integration/reg_groups_test.go b/integration/reg_groups_test.go
index 3a2f86563..8306d6f40 100644
--- a/integration/reg_groups_test.go
+++ b/integration/reg_groups_test.go
@@ -39,6 +39,7 @@ func TestAPI(t *testing.T) {
"api-show-model",
"generate-logprobs",
"chat-logprobs",
+ "system-one",
)
}
diff --git a/integration/reg_release_test.go b/integration/reg_release_test.go
index 893b6c828..35e4bcdc0 100644
--- a/integration/reg_release_test.go
+++ b/integration/reg_release_test.go
@@ -79,6 +79,8 @@ func init() {
integrationTestCase("api-show-model", "llama3.2", runAPIShowModel),
integrationTestCase("generate-logprobs", smol, runAPIGenerateLogprobs),
integrationTestCase("chat-logprobs", smol, runAPIChatLogprobs),
+ // Keep the public tag so manifest lists select the platform's model.
+ integrationModelTestCase("system-one", defaultTestModel("nimble:latest"), runAPISystemOne),
integrationTestCase("blue-sky", smol, runBlueSky),
integrationModelTestCase("unicode-input", releaseUnicodeInputModel.Name, runUnicode),
diff --git a/integration/systemone_test.go b/integration/systemone_test.go
new file mode 100644
index 000000000..d430b0f9e
--- /dev/null
+++ b/integration/systemone_test.go
@@ -0,0 +1,211 @@
+//go:build integration && release
+
+package integration
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "math"
+ "net/http"
+ "slices"
+ "testing"
+
+ "github.com/google/go-cmp/cmp"
+ "github.com/google/go-cmp/cmp/cmpopts"
+ "github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/decision"
+ "github.com/ollama/ollama/types/model"
+)
+
+func postSystemOne(ctx context.Context, endpoint string, input decision.Request) ([]byte, int, error) {
+ body, err := json.Marshal(input)
+ if err != nil {
+ return nil, 0, err
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://"+endpoint+"/v1/systemone", bytes.NewReader(body))
+ if err != nil {
+ return nil, 0, err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ return nil, 0, err
+ }
+ defer resp.Body.Close()
+ body, err = io.ReadAll(io.LimitReader(resp.Body, 1<<20))
+ return body, resp.StatusCode, err
+}
+
+func runAPISystemOne(t *testing.T, modelName string) {
+ ctx, cancel := context.WithTimeout(t.Context(), apiTestTimeout)
+ defer cancel()
+ client, endpoint, cleanup := InitServerConnection(ctx, t)
+ defer cleanup()
+ if err := PullIfMissing(ctx, client, modelName); err != nil {
+ t.Fatal(err)
+ }
+ info, err := client.Show(ctx, &api.ShowRequest{Model: modelName})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Contains(info.Capabilities, model.CapabilityDecision) {
+ t.Fatalf("model %q does not declare the decision capability", modelName)
+ }
+
+ var input decision.Request
+ if err := json.Unmarshal([]byte(`{
+ "state":"Returns are allowed within 30 days. This item was bought 12 days ago. It arrived undamaged.",
+ "questions":{
+ "eligible":{"type":"noul","instructions":"Is this item within the store return window?","criteria":{}},
+ "department":{"type":"choice","instructions":"Which department handles a return?","criteria":{"returns":"Product returns and refunds","technical":"Software installation"}},
+ "damage":{"type":"score","instructions":"How damaged was the item?","criteria":["Undamaged","Minor damage","Destroyed"]}
+ }
+ }`), &input); err != nil {
+ t.Fatal(err)
+ }
+ input.Model = modelName
+ type response struct {
+ Model string
+ Answers struct {
+ Eligible decision.NoulAnswer
+ Department decision.ChoiceAnswer
+ Damage decision.ScoreAnswer
+ }
+ Usage decision.Usage
+ }
+ score := func(t *testing.T, req decision.Request) response {
+ t.Helper()
+ body, status, err := postSystemOne(ctx, endpoint, req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if status != http.StatusOK {
+ t.Fatalf("System One returned HTTP %d: %s", status, body)
+ }
+ // Missing or null numbers must not pass as legitimate zero values.
+ result := response{Usage: decision.Usage{InputTokens: -1, OutputTokens: -1}}
+ result.Answers.Eligible.Noul = math.NaN()
+ result.Answers.Department.Confidence = math.NaN()
+ result.Answers.Damage = decision.ScoreAnswer{Score: math.NaN(), Confidence: math.NaN()}
+ if err := json.Unmarshal(body, &result); err != nil {
+ t.Fatalf("decode System One response: %v: %s", err, body)
+ }
+ if result.Model != modelName {
+ t.Fatalf("unexpected model or answer fields: %s", body)
+ }
+ // MLX scores without generating; llama.cpp can report primer/answer
+ // tokens. Neither backend may omit input accounting or report negatives.
+ if result.Usage.InputTokens <= 0 || result.Usage.OutputTokens < 0 {
+ t.Fatalf("missing or invalid usage: %s", body)
+ }
+ answers := result.Answers
+ if answers.Eligible.Type != "noul" || answers.Department.Type != "choice" || answers.Damage.Type != "score" {
+ t.Fatalf("unexpected answer types: %s", body)
+ }
+ for _, answer := range []struct {
+ name string
+ probabilities *decision.Probabilities
+ confidence float64
+ keys []string
+ }{
+ {"department", answers.Department.Probabilities, answers.Department.Confidence, []string{"returns", "technical"}},
+ {"damage", answers.Damage.Probabilities, answers.Damage.Confidence, []string{"0", "1", "2"}},
+ } {
+ if answer.probabilities.Len() != len(answer.keys) {
+ t.Fatalf("%s probabilities: got %v, want keys %v", answer.name, answer.probabilities, answer.keys)
+ }
+ var sum float64
+ for _, key := range answer.keys {
+ p, ok := answer.probabilities.Get(key)
+ if !ok || !(p >= 0 && p <= 1) {
+ t.Fatalf("%s probability %q missing or invalid: %s", answer.name, key, body)
+ }
+ sum += p
+ }
+ if math.Abs(sum-1) > 1e-6 || !(answer.confidence >= 0 && answer.confidence <= 1) {
+ t.Fatalf("%s: probability sum=%v or missing/invalid confidence: %s", answer.name, sum, body)
+ }
+ }
+ if p := answers.Eligible.Noul; !(p >= 0 && p <= 1) {
+ t.Fatalf("missing or invalid eligible probability: %s", body)
+ }
+ if value := answers.Damage.Score; !(value >= 0 && value <= 2) {
+ t.Fatalf("missing or invalid damage score: %s", body)
+ }
+ if diff := cmp.Diff(map[string]any{"0": "Undamaged", "1": "Minor damage", "2": "Destroyed"}, answers.Damage.Legend.ToMap()); diff != "" {
+ t.Fatalf("damage legend (-want +got):\n%s", diff)
+ }
+ return result
+ }
+
+ baseline := score(t, input)
+ t.Run("decisions", func(t *testing.T) {
+ if baseline.Answers.Eligible.Noul <= 0.5 || baseline.Answers.Department.Choice != "returns" || baseline.Answers.Damage.Score >= 0.5 {
+ t.Fatalf("unexpected decisions for an undamaged, in-window return: %+v", baseline.Answers)
+ }
+ late := input
+ late.State = json.RawMessage(`"Returns are allowed within 30 days. This item was bought 90 days ago. It arrived undamaged."`)
+ if result := score(t, late); result.Answers.Eligible.Noul >= 0.5 {
+ t.Fatalf("late return should be ineligible: %+v", result.Answers.Eligible)
+ }
+ })
+
+ unchanged := func(t *testing.T) {
+ t.Helper()
+ got := score(t, input)
+ // Allow 0.01 absolute probability drift from different BF16 cache/prefill
+ // shapes while requiring identical choices.
+ if diff := cmp.Diff(baseline.Answers, got.Answers, cmpopts.EquateApprox(0, 0.01),
+ cmpopts.AcyclicTransformer("probabilities", (*decision.Probabilities).ToMap),
+ cmpopts.AcyclicTransformer("legend", (*decision.Legend).ToMap),
+ ); diff != "" {
+ t.Errorf("scoring changed (-baseline +got):\n%s", diff)
+ }
+ if got.Usage.InputTokens != baseline.Usage.InputTokens {
+ t.Errorf("input token count changed: got %d, want %d", got.Usage.InputTokens, baseline.Usage.InputTokens)
+ }
+ }
+ t.Run("repeat", unchanged)
+ t.Run("concurrent", func(t *testing.T) {
+ for i := range 4 {
+ t.Run(fmt.Sprint(i), func(t *testing.T) {
+ t.Parallel()
+ unchanged(t)
+ })
+ }
+ })
+ t.Run("after_generation", func(t *testing.T) {
+ noStream := false
+ err := client.Generate(ctx, &api.GenerateRequest{
+ Model: modelName, Prompt: "Reply with one word: hello", Stream: &noStream,
+ Think: &api.ThinkValue{Value: false},
+ Options: map[string]any{"temperature": 0, "num_predict": 8},
+ }, func(api.GenerateResponse) error { return nil })
+ if !slices.Contains(info.Capabilities, model.CapabilityCompletion) {
+ var status api.StatusError
+ if !errors.As(err, &status) || status.StatusCode != http.StatusBadRequest {
+ t.Fatalf("decision-only generation: got %v, want HTTP 400", err)
+ }
+ } else if err != nil {
+ t.Fatal(err)
+ }
+ unchanged(t)
+ })
+
+ t.Run("invalid_state", func(t *testing.T) {
+ invalid := input
+ invalid.State = json.RawMessage(`""`)
+ body, status, err := postSystemOne(ctx, endpoint, invalid)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if status != http.StatusBadRequest {
+ t.Fatalf("got HTTP %d, want %d: %s", status, http.StatusBadRequest, body)
+ }
+ unchanged(t)
+ })
+}
diff --git a/llm/score.go b/llm/score.go
index a1bedb332..328a9b24f 100644
--- a/llm/score.go
+++ b/llm/score.go
@@ -12,19 +12,29 @@ type Scorer interface {
Score(context.Context, ScoreRequest) (ScoreResponse, error)
}
-// ScoreRequest uses either prompt Rows or Segments and Fields for a decision head.
+// ScoreRequest carries prompt rows or model-native decision head inputs.
type ScoreRequest struct {
- Rows []ScoreRow `json:"rows,omitempty"`
- Segments []string `json:"segments,omitempty"`
- Fields []ScoreField `json:"fields,omitempty"`
- MaxTokens int `json:"max_tokens"`
- Images []api.ImageData `json:"images,omitempty"`
- ImagePosition int `json:"image_position,omitempty"` // Segment boundary at which images are inserted.
+ PointerRows []ScorePointerRow `json:"pointer_rows,omitempty"`
+ State string `json:"state,omitempty"`
+ Rows []ScoreRow `json:"rows,omitempty"`
+ Segments []string `json:"segments,omitempty"`
+ Fields []ScoreField `json:"fields,omitempty"`
+ MaxTokens int `json:"max_tokens"`
+ Images []api.ImageData `json:"images,omitempty"`
+ ImagePosition int `json:"image_position,omitempty"` // Segment boundary at which images are inserted.
}
type ScoreRow struct {
- Prompt string `json:"prompt"`
- Candidates []string `json:"candidates"`
+ Prompt string `json:"prompt"`
+ Candidates []string `json:"candidates"`
+ Question *ScoreQuestion `json:"question,omitempty"`
+}
+
+// ScoreQuestion preserves a field's schema for model-native decision heads.
+type ScoreQuestion struct {
+ Type string `json:"type"`
+ Instructions string `json:"instructions"`
+ Options []string `json:"options"`
}
type ScoreResponse struct {
@@ -33,6 +43,7 @@ type ScoreResponse struct {
Logits [][]float32 `json:"logits"`
InputTokens int `json:"input_tokens"` // Sum of complete prompt lengths, including shared tokens.
OutputTokens int `json:"output_tokens,omitempty"` // Tokens generated internally to obtain candidate scores.
+ CachedTokens *int `json:"cached_tokens,omitempty"` // Subset of InputTokens restored instead of evaluated; nil when unavailable.
}
// ScoreField identifies a question and its allowed options for a decision head.
@@ -43,3 +54,12 @@ type ScoreField struct {
Question [2]int `json:"question"`
Options [][2]int `json:"options"`
}
+
+// ScorePointerRow is an independent state/question pair for a pointer head.
+// Options are byte spans in Prompt; Type is 0 for noul, 1 for choice, 2 for score.
+type ScorePointerRow struct {
+ Prefix string `json:"prefix"`
+ Prompt string `json:"prompt"`
+ Type int `json:"type"`
+ Options [][2]int `json:"options"`
+}
diff --git a/mlx/mlxtest/mlxtest.go b/mlx/mlxtest/mlxtest.go
index 506125614..2cea4a7e1 100644
--- a/mlx/mlxtest/mlxtest.go
+++ b/mlx/mlxtest/mlxtest.go
@@ -7,6 +7,7 @@ import (
"testing"
"github.com/ollama/ollama/mlx"
+ "github.com/ollama/ollama/mlx/mlxthread"
"github.com/ollama/ollama/mlx/mlxthread/mlxthreadtest"
)
@@ -25,6 +26,17 @@ var testThread = sync.OnceValues(func() (*mlxthreadtest.Thread, error) {
// T is the test state available to callbacks running on the MLX thread.
type T = mlxthreadtest.T
+// Worker returns the shared worker for handlers that dispatch their own MLX
+// jobs. Call them outside Run; the shared worker must not be stopped by a test.
+func Worker(t testing.TB) *mlxthread.Thread {
+ t.Helper()
+ thread, err := testThread()
+ if err != nil {
+ t.Skipf("MLX not available: %v", err)
+ }
+ return thread.Worker()
+}
+
// SkipIfUnavailable skips the test when the MLX dynamic library cannot be
// loaded (e.g. no MLX backend built for this platform).
func SkipIfUnavailable(t *testing.T) {
diff --git a/mlx/mlxthread/mlxthreadtest/mlxthreadtest.go b/mlx/mlxthread/mlxthreadtest/mlxthreadtest.go
index 2ee75d512..b321c5b96 100644
--- a/mlx/mlxthread/mlxthreadtest/mlxthreadtest.go
+++ b/mlx/mlxthread/mlxthreadtest/mlxthreadtest.go
@@ -14,6 +14,10 @@ type Thread struct {
id uint64
}
+// Worker returns the worker for handlers that dispatch their own MLX jobs.
+// Call those handlers from the test goroutine, not from Run's callback.
+func (t *Thread) Worker() *mlxthread.Thread { return t.worker }
+
// Start creates a pinned test worker.
func Start(name string, init func() error) (*Thread, error) {
t := &Thread{}
diff --git a/mlxrunner/batch/batch.go b/mlxrunner/batch/batch.go
index a96153ef7..7d4f9b90e 100644
--- a/mlxrunner/batch/batch.go
+++ b/mlxrunner/batch/batch.go
@@ -26,7 +26,7 @@ type Batch struct {
// ride featureless. Nil at decode and for text-only requests.
Media []MediaItem
- // Layout carries each row's opaque layout state from PrepareMedia,
+ // Layout carries each row's opaque model-owned metadata,
// identical on every forward of the request; the runner never reads
// it. Nil entries derive nothing from layout.
Layout []any
diff --git a/mlxrunner/cache/cache.go b/mlxrunner/cache/cache.go
index c75c63ade..6268fee28 100644
--- a/mlxrunner/cache/cache.go
+++ b/mlxrunner/cache/cache.go
@@ -14,8 +14,9 @@ type Cache interface {
Free()
Offset() int
- // Snapshot copies cache state from fromOffset to current offset into
- // owned VRAM arrays. The active cache is unchanged.
+ // Snapshot retains state from fromOffset to the current offset without
+ // changing the active cache. Storage may be copied, shared immutably, or
+ // copied lazily before the active cache overwrites it.
Snapshot(fromOffset int) Snapshot
// PrepareSnapshots schedules the cache to capture a snapshot as its
@@ -32,15 +33,13 @@ type Cache interface {
// TakeSnapshots returns the snapshots captured since PrepareSnapshots,
// one per scheduled offset in the caller's order, and clears the
- // schedule. An entry is nil when its scheduled offset captured a
- // zero-width range (the offset equalled the previous boundary, e.g. an
- // offset scheduled at the current position): rolling back there needs
- // only a live rewind, so there is nothing to page out.
+ // schedule. An entry may be nil for an empty range or an offset that
+ // writes never reached, for example after cancellation.
TakeSnapshots() []Snapshot
// Restore brings the cache to target. If snapshot is nil, rewinds
- // using the cache's own live state. Returns false if the target is
- // unreachable (e.g. target > current offset, or negative).
+ // using the cache's own live state. Returns false if the requested state
+ // is unavailable or target is negative.
Restore(snapshot Snapshot, target int) bool
// Merge combines two sequential snapshots [a,b) and [b,c) into [a,c).
@@ -55,7 +54,8 @@ type Cache interface {
// Snapshot is paged-out cache state that can be restored later.
type Snapshot interface {
- // Size returns the byte size of the paged-out data (in VRAM). A lazy
+ // Size returns the retained VRAM bytes charged to the snapshot. Immutable
+ // views may conservatively charge shared backing storage more than once. A lazy
// snapshot that still indexes a live cache buffer returns 0 — it owns
// no extra memory yet. Once materialized (the cache copies the range
// out before overwriting its slots), Size returns the owned bytes.
@@ -67,14 +67,13 @@ type Snapshot interface {
// never lazy may treat this as a no-op.
SetMaterializeHook(func(delta int))
- // Close frees the snapshot's arrays.
+ // Close releases the snapshot's ownership of retained arrays.
Close()
}
-// pendingSnapshots holds the per-token snapshot capture state shared by all
-// cache kinds. The owning cache calls capture(offset) from its write path
-// after each token's storage is in place; capture materializes a snapshot
-// for every scheduled offset that the write has now reached.
+// pendingSnapshots holds the scheduled snapshot capture state shared by all
+// cache kinds. The owning cache calls captureReached from its write path
+// to retain state at each scheduled offset the write reaches.
type pendingSnapshots struct {
offsets []int // scheduled storage offsets, in caller order
captured []Snapshot // captured[i] corresponds to offsets[i]; nil until reached
@@ -102,16 +101,15 @@ func (p *pendingSnapshots) prepare(currentOffset int, offsets []int) {
}
// take returns the captured snapshots and clears the schedule. See
-// Cache.TakeSnapshots. Captures fire in ascending offset order, so by take time
-// every scheduled offset the writes crossed has been visited; a nil entry is a
-// zero-width capture, not a missed one.
+// Cache.TakeSnapshots. Captures fire in ascending offset order; offsets beyond
+// the last completed write remain nil.
func (p *pendingSnapshots) take() []Snapshot {
out := p.captured
p.offsets, p.captured = nil, nil
return out
}
-// captureReached materializes a snapshot for every scheduled offset that equals
+// captureReached captures a snapshot for every scheduled offset that equals
// reached and hasn't been captured yet, using snap to produce the rollback
// state. The capture cursor base holds the previous scheduled boundary: snap
// reads it (yielding a [base, reached) range for position-sliceable caches),
diff --git a/mlxrunner/cache/hidden.go b/mlxrunner/cache/hidden.go
new file mode 100644
index 000000000..d504cb13c
--- /dev/null
+++ b/mlxrunner/cache/hidden.go
@@ -0,0 +1,161 @@
+package cache
+
+import "github.com/ollama/ollama/mlx"
+
+// HiddenCache retains backbone outputs for heads that read earlier tokens.
+// It follows the same prefix snapshots as the attention and recurrent caches.
+// Arrays are immutable: appending or restoring builds a new view or concatenation,
+// so a snapshot never observes a later request's writes.
+type HiddenCache struct {
+ hidden *mlx.Array
+ scope *mlx.Scope
+ backingBytes int
+ snapshots pendingSnapshots
+}
+
+func NewHiddenCache() *HiddenCache { return &HiddenCache{scope: mlx.NewScope()} }
+
+func (c *HiddenCache) Append(hidden *mlx.Array) {
+ start := c.Offset()
+ if c.hidden != nil {
+ hidden = mlx.Concatenate([]*mlx.Array{c.hidden, hidden}, 1)
+ }
+ c.replace(hidden, hidden.NumBytes())
+ for _, offset := range c.snapshots.scheduledIn(start, c.Offset()) {
+ c.snapshots.captureReached(offset, func(int) Snapshot {
+ return c.snapshot(c.snapshots.base, offset)
+ })
+ }
+}
+
+func (c *HiddenCache) replace(hidden *mlx.Array, backingBytes int) {
+ if c.hidden == nil {
+ c.hidden = hidden
+ c.scope.Attach(hidden)
+ } else {
+ c.hidden.Set(hidden)
+ }
+ c.backingBytes = backingBytes
+}
+
+func (c *HiddenCache) State() []*mlx.Array {
+ if c.hidden == nil {
+ return nil
+ }
+ return []*mlx.Array{c.hidden}
+}
+
+func (c *HiddenCache) Offset() int {
+ if c.hidden == nil {
+ return 0
+ }
+ return c.hidden.Dim(1)
+}
+
+func (c *HiddenCache) Free() {
+ for _, s := range c.TakeSnapshots() {
+ if s != nil {
+ s.Close()
+ }
+ }
+ c.scope.Close()
+ c.scope = mlx.NewScope()
+ c.hidden = nil
+ c.backingBytes = 0
+}
+
+func (c *HiddenCache) PrepareSnapshots(offsets []int) { c.snapshots.prepare(c.Offset(), offsets) }
+func (c *HiddenCache) TakeSnapshots() []Snapshot { return c.snapshots.take() }
+
+type hiddenSnapshot struct {
+ hidden *mlx.Array
+ scope *mlx.Scope
+ start int
+ backingBytes int
+}
+
+// Charge the whole backing array even for a view. This may overcount shared
+// storage, but eviction must never undercount a small slice retaining a full row.
+func (s *hiddenSnapshot) Size() int { return s.backingBytes }
+func (s *hiddenSnapshot) Close() { s.scope.Close() }
+func (s *hiddenSnapshot) SetMaterializeHook(func(int)) {}
+
+func newHiddenSnapshot(hidden *mlx.Array, start, backingBytes int) *hiddenSnapshot {
+ s := &hiddenSnapshot{hidden: hidden, scope: mlx.NewScope(), start: start, backingBytes: backingBytes}
+ s.scope.Attach(hidden)
+ return s
+}
+
+func (c *HiddenCache) snapshot(start, end int) Snapshot {
+ if start == end {
+ return nil
+ }
+ return newHiddenSnapshot(c.hidden.Slice(mlx.Slice(), mlx.Slice(start, end), mlx.Slice()), start, c.backingBytes)
+}
+
+func (c *HiddenCache) Snapshot(start int) Snapshot { return c.snapshot(start, c.Offset()) }
+
+func (c *HiddenCache) Restore(snapshot Snapshot, target int) bool {
+ if target < 0 {
+ return false
+ }
+ if target == 0 {
+ c.Free()
+ return true
+ }
+ if target <= c.Offset() {
+ c.replace(c.hidden.Slice(mlx.Slice(), mlx.Slice(0, target), mlx.Slice()), c.backingBytes)
+ return true
+ }
+ if snapshot == nil {
+ return false
+ }
+ s := snapshot.(*hiddenSnapshot)
+ if s.start > c.Offset() || target > s.start+s.hidden.Dim(1) {
+ return false
+ }
+ part := s.hidden.Slice(mlx.Slice(), mlx.Slice(c.Offset()-s.start, target-s.start), mlx.Slice())
+ if c.hidden == nil {
+ c.replace(part, s.backingBytes)
+ } else {
+ c.Append(part)
+ }
+ return true
+}
+
+func (c *HiddenCache) Split(snapshot Snapshot, at int) (Snapshot, Snapshot) {
+ if snapshot == nil {
+ return nil, nil
+ }
+ s := snapshot.(*hiddenSnapshot)
+ n := at - s.start
+ if n <= 0 {
+ return nil, s
+ }
+ if n >= s.hidden.Dim(1) {
+ return s, nil
+ }
+ left := newHiddenSnapshot(s.hidden.Slice(mlx.Slice(), mlx.Slice(0, n), mlx.Slice()), s.start, s.backingBytes)
+ right := newHiddenSnapshot(s.hidden.Slice(mlx.Slice(), mlx.Slice(n, mlx.End), mlx.Slice()), at, s.backingBytes)
+ s.Close()
+ return left, right
+}
+
+func (c *HiddenCache) Merge(parent, child Snapshot) Snapshot {
+ if parent == nil || child == nil {
+ if parent != nil {
+ parent.Close()
+ }
+ if child != nil {
+ child.Close()
+ }
+ return nil
+ }
+ a, b := parent.(*hiddenSnapshot), child.(*hiddenSnapshot)
+ joined := mlx.Concatenate([]*mlx.Array{a.hidden, b.hidden}, 1)
+ s := newHiddenSnapshot(joined, a.start, joined.NumBytes())
+ mlx.AsyncEval(joined)
+ a.Close()
+ b.Close()
+ return s
+}
diff --git a/mlxrunner/cache/hidden_test.go b/mlxrunner/cache/hidden_test.go
new file mode 100644
index 000000000..aba2805d8
--- /dev/null
+++ b/mlxrunner/cache/hidden_test.go
@@ -0,0 +1,54 @@
+package cache
+
+import (
+ "slices"
+ "testing"
+
+ "github.com/ollama/ollama/mlx"
+ "github.com/ollama/ollama/mlx/mlxtest"
+)
+
+func TestHiddenCacheSnapshots(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ c := NewHiddenCache()
+ defer c.Free()
+ c.PrepareSnapshots([]int{2, 3})
+ c.Append(mlx.FromValues([]float32{1, 2, 3, 4}, 1, 4, 1))
+ captured := c.TakeSnapshots()
+ whole := c.Snapshot(0)
+ defer whole.Close()
+ if !c.Restore(nil, 2) {
+ t.Fatal("could not rewind")
+ }
+ c.Append(mlx.FromValues([]float32{30, 40}, 1, 2, 1))
+ mlx.Eval(c.State()...)
+ if got := c.State()[0].Floats(); !slices.Equal(got, []float32{1, 2, 30, 40}) {
+ t.Fatalf("branch = %v", got)
+ }
+ c.Free()
+ if !c.Restore(captured[0], 2) || !c.Restore(captured[1], 3) || !c.Restore(whole, 4) {
+ t.Fatal("could not restore captured prefix")
+ }
+ for _, s := range captured {
+ s.Close()
+ }
+ mlx.Eval(c.State()...)
+ if got := c.State()[0].Floats(); !slices.Equal(got, []float32{1, 2, 3, 4}) {
+ t.Fatalf("restored original = %v", got)
+ }
+ left, right := c.Split(c.Snapshot(0), 1)
+ if left.Size() < 16 || right.Size() < 16 {
+ t.Fatal("snapshot view undercounts backing storage")
+ }
+ joined := c.Merge(left, right)
+ defer joined.Close()
+ c.Free()
+ if !c.Restore(joined, 4) || c.Restore(nil, 5) || c.Restore(nil, -1) {
+ t.Fatal("incorrect restore bounds")
+ }
+ mlx.Eval(c.State()...)
+ if got := c.State()[0].Floats(); !slices.Equal(got, []float32{1, 2, 3, 4}) {
+ t.Fatalf("merged original = %v", got)
+ }
+ })
+}
diff --git a/mlxrunner/client_score.go b/mlxrunner/client_score.go
new file mode 100644
index 000000000..4e0a8b4ae
--- /dev/null
+++ b/mlxrunner/client_score.go
@@ -0,0 +1,46 @@
+package mlxrunner
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+
+ "github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/llm"
+)
+
+var _ llm.Scorer = (*Client)(nil)
+
+func (c *Client) Score(ctx context.Context, input llm.ScoreRequest) (llm.ScoreResponse, error) {
+ var result llm.ScoreResponse
+ data, err := json.Marshal(input)
+ if err != nil {
+ return result, err
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/v1/score", c.port), bytes.NewReader(data))
+ if err != nil {
+ return result, err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ res, err := c.client.Do(req)
+ if err != nil {
+ if errMsg := c.status.LastError(); errMsg != "" {
+ return result, fmt.Errorf("mlx runner failed: %s", errMsg)
+ }
+ return result, err
+ }
+ defer res.Body.Close()
+ if res.StatusCode != http.StatusOK {
+ body, err := io.ReadAll(res.Body)
+ if err != nil {
+ return result, err
+ }
+ return result, api.StatusError{StatusCode: res.StatusCode, ErrorMessage: strings.TrimSpace(string(body))}
+ }
+ err = json.NewDecoder(res.Body).Decode(&result)
+ return result, err
+}
diff --git a/mlxrunner/client_score_test.go b/mlxrunner/client_score_test.go
new file mode 100644
index 000000000..9a82dbd2b
--- /dev/null
+++ b/mlxrunner/client_score_test.go
@@ -0,0 +1,100 @@
+package mlxrunner
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/llm"
+)
+
+func TestClientScore(t *testing.T) {
+ input := llm.ScoreRequest{MaxTokens: 2048, Rows: []llm.ScoreRow{{Prompt: "prompt", Candidates: []string{"A", "B"}}}}
+ for _, status := range []int{http.StatusOK, http.StatusBadRequest} {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/v1/score" || r.Method != "POST" {
+ t.Errorf("wrong endpoint: %s %s", r.Method, r.URL.Path)
+ }
+ var got llm.ScoreRequest
+ if err := json.NewDecoder(r.Body).Decode(&got); err != nil || !reflect.DeepEqual(got, input) {
+ t.Errorf("request changed: %+v, %v", got, err)
+ }
+ if status != http.StatusOK {
+ http.Error(w, "prompt too long", status)
+ return
+ }
+ _ = json.NewEncoder(w).Encode(llm.ScoreResponse{Logits: [][]float32{{-1, 2}}, InputTokens: 3})
+ }))
+ client := &Client{port: srv.Listener.Addr().(*net.TCPAddr).Port, client: srv.Client()}
+ result, err := client.Score(context.Background(), input)
+ srv.Close()
+ if status == http.StatusOK {
+ if err != nil || result.InputTokens != 3 || !reflect.DeepEqual(result.Logits, [][]float32{{-1, 2}}) {
+ t.Fatalf("unexpected result: %+v, %v", result, err)
+ }
+ } else {
+ var statusErr api.StatusError
+ if !errors.As(err, &statusErr) || statusErr.StatusCode != status || statusErr.ErrorMessage != "prompt too long" {
+ t.Fatalf("status error not preserved: %v", err)
+ }
+ }
+ }
+}
+
+func TestClientScoreTransportError(t *testing.T) {
+ for _, message := range []string{"", "MLX: failed to allocate memory"} {
+ t.Run(message, func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ conn, _, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ conn.Close()
+ }))
+ defer srv.Close()
+ status := &llm.StatusWriter{}
+ status.SetLastError(message)
+ client := &Client{port: srv.Listener.Addr().(*net.TCPAddr).Port, client: srv.Client(), status: status}
+ _, err := client.Score(t.Context(), llm.ScoreRequest{})
+ if message == "" {
+ if !errors.Is(err, io.EOF) {
+ t.Fatalf("transport error lost: %v", err)
+ }
+ } else if !llm.IsOutOfMemory(err) || !strings.Contains(err.Error(), message) {
+ t.Fatalf("runner OOM diagnostic lost: %v", err)
+ }
+ })
+ }
+}
+
+func TestClientScoreCancellation(t *testing.T) {
+ started := make(chan struct{})
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = io.Copy(io.Discard, r.Body)
+ close(started)
+ <-r.Context().Done()
+ }))
+ defer srv.Close()
+ client := &Client{port: srv.Listener.Addr().(*net.TCPAddr).Port, client: srv.Client()}
+ ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ done := make(chan error, 1)
+ go func() {
+ _, err := client.Score(ctx, llm.ScoreRequest{})
+ done <- err
+ }()
+ <-started
+ cancel()
+ if err := <-done; !errors.Is(err, context.Canceled) {
+ t.Fatalf("got %v, want context cancellation", err)
+ }
+}
diff --git a/mlxrunner/grammar.go b/mlxrunner/grammar.go
index 8e45ddc56..eeb97e174 100644
--- a/mlxrunner/grammar.go
+++ b/mlxrunner/grammar.go
@@ -50,15 +50,18 @@ type grammarEngine struct {
}
func newGrammarEngine(logitsWidth int, tokenizer *tokenizer.Tokenizer) *grammarEngine {
- library, err := mlx.LoadedLibraryPath()
- if err != nil {
- slog.Warn("Structured output is unavailable", "error", err)
+ if tokenizer == nil {
return nil
}
if err := validateGrammarVocab(logitsWidth, tokenizer.VocabSize()); err != nil {
slog.Warn("Structured output is unavailable", "error", err)
return nil
}
+ library, err := mlx.LoadedLibraryPath()
+ if err != nil {
+ slog.Warn("Structured output is unavailable", "error", err)
+ return nil
+ }
pieces := make([]string, logitsWidth)
for id := range logitsWidth {
pieces[id] = tokenizer.Decode([]int32{int32(id)})
@@ -85,8 +88,9 @@ func validateGrammarVocab(logitsWidth, tokenizerSize int) error {
if tokenizerSize <= 0 {
return fmt.Errorf("invalid tokenizer vocabulary size %d", tokenizerSize)
}
- if logitsWidth <= 0 {
- return fmt.Errorf("invalid model logits width %d", logitsWidth)
+ // A scalar scoring head has no token vocabulary for a grammar to constrain.
+ if logitsWidth <= 1 {
+ return fmt.Errorf("model has no token vocabulary (logits width %d)", logitsWidth)
}
return nil
}
diff --git a/mlxrunner/grammar_test.go b/mlxrunner/grammar_test.go
index 1efdeb452..cf08bf11b 100644
--- a/mlxrunner/grammar_test.go
+++ b/mlxrunner/grammar_test.go
@@ -129,6 +129,7 @@ func TestValidateGrammarVocab(t *testing.T) {
{name: "input-only tokens past the head", logits: 31, tokenizer: 32},
{name: "invalid tokenizer", logits: 32, tokenizer: -1, wantErr: true},
{name: "invalid logits width", logits: 0, tokenizer: 32, wantErr: true},
+ {name: "scalar scoring head", logits: 1, tokenizer: 32, wantErr: true},
} {
t.Run(tt.name, func(t *testing.T) {
err := validateGrammarVocab(tt.logits, tt.tokenizer)
@@ -139,6 +140,13 @@ func TestValidateGrammarVocab(t *testing.T) {
}
}
+func TestNewGrammarEngineWithoutTokenizer(t *testing.T) {
+ if e := newGrammarEngine(32, nil); e != nil {
+ e.close()
+ t.Fatal("expected no grammar engine without a tokenizer")
+ }
+}
+
// resolvedGrammarCompilation wraps an already-built matcher as a finished
// compilation.
func resolvedGrammarCompilation(m *xgrammar.Matcher) *grammarCompilation {
diff --git a/mlxrunner/model/architectures/architectures.go b/mlxrunner/model/architectures/architectures.go
index 168a5bb62..b7c6a452b 100644
--- a/mlxrunner/model/architectures/architectures.go
+++ b/mlxrunner/model/architectures/architectures.go
@@ -1,16 +1,19 @@
package architectures
import (
+ _ "github.com/ollama/ollama/mlxrunner/model/clef"
_ "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/glimmer"
_ "github.com/ollama/ollama/mlxrunner/model/glm4_moe_lite"
_ "github.com/ollama/ollama/mlxrunner/model/laguna"
+ _ "github.com/ollama/ollama/mlxrunner/model/laya"
_ "github.com/ollama/ollama/mlxrunner/model/llama"
_ "github.com/ollama/ollama/mlxrunner/model/nemotron_h"
_ "github.com/ollama/ollama/mlxrunner/model/qwen3"
_ "github.com/ollama/ollama/mlxrunner/model/qwen3_5"
_ "github.com/ollama/ollama/mlxrunner/model/qwen3_5_moe"
_ "github.com/ollama/ollama/mlxrunner/model/qwen4_exp"
+ _ "github.com/ollama/ollama/mlxrunner/model/strands"
)
diff --git a/mlxrunner/model/clef/encode.go b/mlxrunner/model/clef/encode.go
new file mode 100644
index 000000000..0d9c9a015
--- /dev/null
+++ b/mlxrunner/model/clef/encode.go
@@ -0,0 +1,77 @@
+package clef
+
+import (
+ "fmt"
+
+ "github.com/ollama/ollama/llm"
+ "github.com/ollama/ollama/mlxrunner/tokenizer"
+)
+
+type tokenSpan struct{ start, end int }
+
+type encodedQuestion struct {
+ kind int32
+ instruction tokenSpan
+ options []tokenSpan
+}
+
+type encodedRecord struct {
+ ids []int32
+ questions []encodedQuestion
+}
+
+// Clef's shared encoder supplies prefix, state, then schema and suffix segments.
+// The prepared prefix may include images; only state tokens may be truncated.
+func encode(tok *tokenizer.Tokenizer, input llm.ScoreRequest, prefix []int32) (encodedRecord, error) {
+ var record encodedRecord
+ if len(input.Segments) < 3 {
+ return record, fmt.Errorf("Clef requires prefix, state, and schema segments")
+ }
+ tokens := make([][]int32, len(input.Segments))
+ tokens[0] = prefix
+ fixed := len(prefix)
+ for i := 1; i < len(tokens); i++ {
+ tokens[i] = tok.Encode(input.Segments[i], false)
+ if i != 1 {
+ fixed += len(tokens[i])
+ }
+ }
+ if fixed > input.MaxTokens {
+ return record, fmt.Errorf("Clef schema exceeds the %d-token context", input.MaxTokens)
+ }
+ tokens[1] = tokens[1][:min(len(tokens[1]), input.MaxTokens-fixed)]
+ offsets := make([]int, len(tokens)+1)
+ for i, segment := range tokens {
+ record.ids = append(record.ids, segment...)
+ offsets[i+1] = len(record.ids)
+ }
+ span := func(bounds [2]int) (tokenSpan, error) {
+ if bounds[0] < 2 || bounds[0] >= bounds[1] || bounds[1] > len(tokens) {
+ return tokenSpan{}, fmt.Errorf("Clef question span is outside the schema")
+ }
+ s := tokenSpan{offsets[bounds[0]], offsets[bounds[1]]}
+ if s.start == s.end {
+ return tokenSpan{}, fmt.Errorf("Clef question span has no tokens")
+ }
+ return s, nil
+ }
+ for _, field := range input.Fields {
+ if field.Type < 0 || field.Type > 2 || len(field.Options) < 2 || len(field.Options) > 26 {
+ return record, fmt.Errorf("invalid Clef question type or option count")
+ }
+ question, err := span(field.Question)
+ if err != nil {
+ return record, err
+ }
+ q := encodedQuestion{kind: int32(field.Type), instruction: question}
+ for _, bounds := range field.Options {
+ option, err := span(bounds)
+ if err != nil {
+ return record, err
+ }
+ q.options = append(q.options, option)
+ }
+ record.questions = append(record.questions, q)
+ }
+ return record, nil
+}
diff --git a/mlxrunner/model/clef/encode_test.go b/mlxrunner/model/clef/encode_test.go
new file mode 100644
index 000000000..5d841c758
--- /dev/null
+++ b/mlxrunner/model/clef/encode_test.go
@@ -0,0 +1,56 @@
+package clef
+
+import (
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/ollama/ollama/llm"
+ "github.com/ollama/ollama/mlxrunner/tokenizer"
+)
+
+func TestEncodeTruncatesOnlyState(t *testing.T) {
+ tok, err := tokenizer.LoadFromBytes([]byte(`{"model":{"type":"BPE","vocab":{"x":0},"merges":[]}}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Fixed prompt tokens must survive truncation along with the schema.
+ prefix := []int32{100, 101, 101, 101, 102}
+ input := llm.ScoreRequest{
+ MaxTokens: 12,
+ Segments: []string{"prefix", strings.Repeat("x", 100), "xx", "x", "x"},
+ Fields: []llm.ScoreField{{Type: 0, Question: [2]int{2, 3}, Options: [][2]int{{3, 4}, {4, 5}}}},
+ }
+ got, err := encode(tok, input, prefix)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if want := []int32{100, 101, 101, 101, 102, 0, 0, 0, 0, 0, 0, 0}; !slices.Equal(got.ids, want) {
+ t.Fatalf("tokens = %v, want %v", got.ids, want)
+ }
+ q := got.questions[0]
+ if q.instruction != (tokenSpan{8, 10}) || !slices.Equal(q.options, []tokenSpan{{10, 11}, {11, 12}}) {
+ t.Fatalf("schema spans shifted incorrectly: %+v", q)
+ }
+ input.MaxTokens = 8
+ if _, err := encode(tok, input, prefix); err == nil {
+ t.Fatal("prefix and schema exceeding the context must be rejected")
+ }
+}
+
+func TestEncodeRejectsInvalidSpan(t *testing.T) {
+ tok, err := tokenizer.LoadFromBytes([]byte(`{"model":{"type":"BPE","vocab":{"x":0},"merges":[]}}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, bounds := range [][2]int{{-1, 2}, {0, 1}, {2, 2}, {2, 7}, {5, 6}} {
+ input := llm.ScoreRequest{
+ MaxTokens: 32,
+ Segments: []string{"prefix", "state", "x", "x", "x", ""},
+ Fields: []llm.ScoreField{{Question: bounds, Options: [][2]int{{3, 4}, {4, 5}}}},
+ }
+ if _, err := encode(tok, input, []int32{100}); err == nil {
+ t.Errorf("accepted invalid or empty span %v", bounds)
+ }
+ }
+}
diff --git a/mlxrunner/model/clef/head.go b/mlxrunner/model/clef/head.go
new file mode 100644
index 000000000..e166ca2e0
--- /dev/null
+++ b/mlxrunner/model/clef/head.go
@@ -0,0 +1,195 @@
+package clef
+
+import (
+ "fmt"
+ "math"
+ "slices"
+
+ "github.com/ollama/ollama/mlx"
+ "github.com/ollama/ollama/mlxrunner/nn"
+)
+
+type attention struct {
+ Q, K, V, Out *nn.Linear
+ heads int
+}
+
+type evidenceLayer struct {
+ QueryNorm, MemoryNorm, FFNorm *nn.LayerNorm
+ Attention attention
+ Up, Down *nn.Linear
+}
+
+type fieldLayer struct {
+ Norm1, Norm2, Norm3 *nn.LayerNorm
+ Self, Cross attention
+ Up, Down *nn.Linear
+}
+
+type head struct {
+ HiddenNorm, SummaryNorm, FieldNorm, OptionNorm *nn.LayerNorm
+ Memory, Question, OptionQuestion, Global, OptionContext, OptionLexical *nn.Linear
+ Types *mlx.Array
+ Evidence []evidenceLayer
+ Fields []fieldLayer
+ ResidualIn, ResidualOut *nn.Linear
+ PriorScale, JointScale, ResidualGate *mlx.Array
+}
+
+func (h *head) load(tensors map[string]*mlx.Array, c config) error {
+ var loadErr error
+ weight := func(name string, shape ...int) *mlx.Array {
+ w := tensors[name]
+ if w == nil || !slices.Equal(w.Dims(), shape) {
+ if loadErr == nil {
+ loadErr = fmt.Errorf("Clef weight %s: expected shape %v", name, shape)
+ }
+ return nil
+ }
+ if w.DType() != mlx.DTypeBFloat16 && w.DType() != mlx.DTypeFloat16 && w.DType() != mlx.DTypeFloat32 {
+ if loadErr == nil {
+ loadErr = fmt.Errorf("Clef head requires floating-point weights: %s", name)
+ }
+ return nil
+ }
+ return w
+ }
+ linear := func(name string, out, in int, bias bool) *nn.Linear {
+ l := &nn.Linear{Weight: weight(name+".weight", out, in)}
+ if bias {
+ l.Bias = weight(name+".bias", out)
+ }
+ return l
+ }
+ norm := func(name string, size int) *nn.LayerNorm {
+ return &nn.LayerNorm{Weight: weight(name+".weight", size), Bias: weight(name+".bias", size), Eps: 1e-5}
+ }
+ attn := func(name string) attention {
+ a := attention{Out: linear(name+".out_proj", c.Width, c.Width, true), heads: c.Heads}
+ w, b := weight(name+".in_proj_weight", 3*c.Width, c.Width), weight(name+".in_proj_bias", 3*c.Width)
+ if w != nil && b != nil {
+ projections := []*nn.Linear{}
+ for i := range 3 {
+ projections = append(projections, &nn.Linear{Weight: w.Slice(mlx.Slice(i*c.Width, (i+1)*c.Width), mlx.Slice()), Bias: b.Slice(mlx.Slice(i*c.Width, (i+1)*c.Width))})
+ }
+ a.Q, a.K, a.V = projections[0], projections[1], projections[2]
+ }
+ return a
+ }
+ h.HiddenNorm = norm("hidden_norm", c.HiddenSize)
+ h.SummaryNorm = norm("option_summary_norm", c.Width)
+ h.FieldNorm = norm("field_norm", c.Width)
+ h.OptionNorm = norm("option_norm", c.Width)
+ h.Memory = linear("memory_projection", c.Width, c.HiddenSize, false)
+ h.Question = linear("question_projection", c.Width, c.HiddenSize, false)
+ h.OptionQuestion = linear("option_question_projection", c.Width, c.HiddenSize, false)
+ h.Global = linear("global_projection", c.Width, c.HiddenSize, false)
+ h.OptionContext = linear("option_context_projection", c.Width, c.HiddenSize, false)
+ h.OptionLexical = linear("option_lexical_projection", c.Width, c.HiddenSize, false)
+ h.Types = weight("type_embedding.weight", 3, c.Width)
+ h.ResidualIn = linear("residual_scorer.0", c.Width, 4*c.Width, true)
+ h.ResidualOut = linear("residual_scorer.3", 1, c.Width, true)
+ h.PriorScale = weight("prior_logit_scale")
+ h.JointScale = weight("joint_logit_scale")
+ h.ResidualGate = weight("residual_gate")
+ h.Evidence = make([]evidenceLayer, c.RoutingLayers)
+ for i := range h.Evidence {
+ p := fmt.Sprintf("evidence_layers.%d", i)
+ h.Evidence[i] = evidenceLayer{QueryNorm: norm(p+".query_norm", c.Width), MemoryNorm: norm(p+".memory_norm", c.Width), FFNorm: norm(p+".feedforward_norm", c.Width), Attention: attn(p + ".attention"), Up: linear(p+".feedforward.0", c.Feedforward, c.Width, true), Down: linear(p+".feedforward.3", c.Width, c.Feedforward, true)}
+ }
+ h.Fields = make([]fieldLayer, c.Layers)
+ for i := range h.Fields {
+ p := fmt.Sprintf("layers.%d", i)
+ h.Fields[i] = fieldLayer{Norm1: norm(p+".norm1", c.Width), Norm2: norm(p+".norm2", c.Width), Norm3: norm(p+".norm3", c.Width), Self: attn(p + ".self_attn"), Cross: attn(p + ".multihead_attn"), Up: linear(p+".linear1", c.Feedforward, c.Width, true), Down: linear(p+".linear2", c.Width, c.Feedforward, true)}
+ }
+ return loadErr
+}
+
+func (a attention) forward(query, memory *mlx.Array) *mlx.Array {
+ project := func(l *nn.Linear, x *mlx.Array) *mlx.Array {
+ y := l.Forward(x)
+ return y.Reshape(y.Dim(0), y.Dim(1), a.heads, -1).Transpose(0, 2, 1, 3)
+ }
+ q, k, v := project(a.Q, query), project(a.K, memory), project(a.V, memory)
+ out := mlx.FastScaledDotProductAttention(q, k, v, 1/float32(math.Sqrt(float64(q.Dim(3)))), "", nil)
+ return a.Out.Forward(out.Transpose(0, 2, 1, 3).Reshape(query.Dim(0), query.Dim(1), -1))
+}
+
+func normalize(x *mlx.Array, eps float32) *mlx.Array {
+ f := x.AsType(mlx.DTypeFloat32)
+ norm := mlx.Sum(mlx.Mul(f, f), -1, true).Sqrt().AsType(x.DType())
+ return mlx.Div(x, mlx.Maximum(norm, mlx.FromValue(eps).AsType(x.DType())))
+}
+
+func meanSpan(x *mlx.Array, span tokenSpan) *mlx.Array {
+ return mlx.Mean(x.Slice(mlx.Slice(span.start, span.end), mlx.Slice()), 0, false)
+}
+
+// forward scores the complete schema jointly. The backbone states are causal;
+// the head attends to all state tokens and across all questions without a mask.
+func (h *head) forward(hidden, ids *mlx.Array, questions []encodedQuestion, embedding nn.EmbeddingLayer) []*mlx.Array {
+ sequence := h.HiddenNorm.Forward(hidden).Squeeze(0)
+ memory := h.Memory.Forward(sequence).ExpandDims(0)
+ global := sequence.Slice(mlx.Slice(sequence.Dim(0)-1, sequence.Dim(0)), mlx.Slice()).Squeeze(0)
+ var questionVectors, lexical, queries []*mlx.Array
+ var types []int32
+ for _, q := range questions {
+ questionVectors = append(questionVectors, meanSpan(sequence, q.instruction))
+ types = append(types, q.kind)
+ }
+ question := mlx.Stack(questionVectors, 0)
+ for i, q := range questions {
+ var contexts, words []*mlx.Array
+ for _, span := range q.options {
+ contexts = append(contexts, meanSpan(sequence, span))
+ tokens := ids.Slice(mlx.Slice(span.start, span.end))
+ words = append(words, mlx.Mean(embedding.Forward(tokens), 0, false))
+ }
+ lexical = append(lexical, mlx.Stack(words, 0))
+ queries = append(queries, mlx.Add(mlx.Add(h.OptionContext.Forward(mlx.Stack(contexts, 0)), h.OptionLexical.Forward(lexical[i])), h.OptionQuestion.Forward(questionVectors[i]).ExpandDims(0)))
+ }
+ routed := mlx.Concatenate(queries, 0).ExpandDims(0)
+ for _, l := range h.Evidence {
+ routed = mlx.Add(routed, l.Attention.forward(l.QueryNorm.Forward(routed), l.MemoryNorm.Forward(memory)))
+ routed = mlx.Add(routed, l.Down.Forward(mlx.GELU(l.Up.Forward(l.FFNorm.Forward(routed)))))
+ }
+ routed = routed.Squeeze(0)
+ base := h.Question.Forward(question)
+ var options, summaries []*mlx.Array
+ offset := 0
+ for i, q := range questions {
+ option := routed.Slice(mlx.Slice(offset, offset+len(q.options)), mlx.Slice())
+ options = append(options, option)
+ field := base.Slice(mlx.Slice(i, i+1), mlx.Slice()).Squeeze(0)
+ weights := mlx.SoftmaxAxis(mlx.DivScalar(mlx.Matmul(option, field), float32(math.Sqrt(float64(option.Dim(1))))), 0, true)
+ summaries = append(summaries, mlx.Sum(mlx.Mul(weights.ExpandDims(-1), option), 0, false))
+ offset += len(q.options)
+ }
+ fields := mlx.Add(base, h.SummaryNorm.Forward(mlx.Stack(summaries, 0)))
+ fields = mlx.Add(fields, h.Global.Forward(global).ExpandDims(0))
+ fields = mlx.Add(fields, h.Types.TakeAxis(mlx.FromValues(types, len(types)), 0)).ExpandDims(0)
+ for _, l := range h.Fields {
+ norm := l.Norm1.Forward(fields)
+ fields = mlx.Add(fields, l.Self.forward(norm, norm))
+ fields = mlx.Add(fields, l.Cross.forward(l.Norm2.Forward(fields), memory))
+ fields = mlx.Add(fields, l.Down.Forward(mlx.GELU(l.Up.Forward(l.Norm3.Forward(fields)))))
+ }
+ fields = h.FieldNorm.Forward(fields.Squeeze(0))
+ scale := func(x *mlx.Array) *mlx.Array {
+ return mlx.Exp(mlx.Minimum(x, mlx.FromValue(float32(math.Log(100))).AsType(x.DType())))
+ }
+ var logits []*mlx.Array
+ for i := range questions {
+ anchor := normalize(mlx.Add(questionVectors[i], global), 1e-12)
+ prior := mlx.Mul(scale(h.PriorScale), mlx.Matmul(normalize(lexical[i], 1e-12), anchor))
+ option := h.OptionNorm.Forward(options[i])
+ field := fields.Slice(mlx.Slice(i, i+1), mlx.Slice())
+ field = mlx.BroadcastTo(field, int32(option.Dim(0)), int32(option.Dim(1)))
+ cosine := mlx.Sum(mlx.Mul(normalize(field, 1e-8), normalize(option, 1e-8)), -1, false)
+ features := mlx.Concatenate([]*mlx.Array{field, option, mlx.Mul(field, option), mlx.Sub(field, option).Abs()}, -1)
+ residual := h.ResidualOut.Forward(mlx.GELU(h.ResidualIn.Forward(features))).Squeeze(-1)
+ joint := mlx.Add(mlx.Mul(scale(h.JointScale), cosine), residual)
+ logits = append(logits, mlx.Add(prior, mlx.Mul(h.ResidualGate.Sigmoid(), joint)))
+ }
+ return logits
+}
diff --git a/mlxrunner/model/clef/model.go b/mlxrunner/model/clef/model.go
new file mode 100644
index 000000000..476cffe5d
--- /dev/null
+++ b/mlxrunner/model/clef/model.go
@@ -0,0 +1,69 @@
+// Package clef implements Cloudflare's Qwen3.5 joint-schema decision model.
+package clef
+
+import (
+ "fmt"
+
+ "github.com/ollama/ollama/mlx"
+ "github.com/ollama/ollama/mlxrunner/model"
+ "github.com/ollama/ollama/mlxrunner/model/qwen3_5"
+ "github.com/ollama/ollama/mlxrunner/nn"
+)
+
+type config struct {
+ HiddenSize int `json:"hidden_size"`
+ Width int `json:"width"`
+ RoutingLayers int `json:"routing_layers"`
+ Layers int `json:"layers"`
+ Heads int `json:"heads"`
+ Feedforward int `json:"feedforward"`
+}
+
+type Model struct {
+ *qwen3_5.Model
+ Head head
+ OutputEmbedding nn.EmbeddingLayer
+ config config
+}
+
+func init() { model.Register("ClefForDecision", newModel) }
+
+func newModel(root *model.Root) (model.Model, error) {
+ var backboneConfig struct {
+ ModelType string `json:"model_type"`
+ }
+ if err := root.Manifest.ReadConfigJSON("config.json", &backboneConfig); err != nil {
+ return nil, err
+ }
+ if backboneConfig.ModelType != "qwen3_5" {
+ return nil, fmt.Errorf("unsupported Clef backbone %q", backboneConfig.ModelType)
+ }
+ var cfg config
+ if err := root.Manifest.ReadConfigJSON("joint_head_config.json", &cfg); err != nil {
+ return nil, err
+ }
+ if cfg.HiddenSize <= 0 || cfg.Width <= 0 || cfg.Heads <= 0 || cfg.Width%cfg.Heads != 0 || cfg.Feedforward <= 0 || cfg.Layers < 1 || cfg.Layers > 16 || cfg.RoutingLayers < 1 || cfg.RoutingLayers > 16 {
+ return nil, fmt.Errorf("invalid Clef joint head configuration")
+ }
+ backbone, err := qwen3_5.NewModel(root)
+ if err != nil {
+ return nil, err
+ }
+ m := &Model{Model: backbone.(*qwen3_5.Model), config: cfg}
+ if cfg.HiddenSize != int(m.Config.HiddenSize) {
+ return nil, fmt.Errorf("Clef head and backbone hidden sizes differ")
+ }
+ return m, nil
+}
+
+func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
+ if err := m.Model.LoadWeights(tensors); err != nil {
+ return err
+ }
+ c := m.Config
+ m.OutputEmbedding = model.MakeEmbeddingLayer(tensors, "lm_head", c.QuantGroupSize, c.QuantBits, c.QuantMode, c.TensorQuant)
+ if m.OutputEmbedding == nil {
+ return fmt.Errorf("Clef requires its untied output embedding")
+ }
+ return m.Head.load(tensors, m.config)
+}
diff --git a/mlxrunner/model/clef/score.go b/mlxrunner/model/clef/score.go
new file mode 100644
index 000000000..133623815
--- /dev/null
+++ b/mlxrunner/model/clef/score.go
@@ -0,0 +1,109 @@
+package clef
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+
+ "github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/llm"
+ "github.com/ollama/ollama/mlx"
+ "github.com/ollama/ollama/mlxrunner/model"
+)
+
+var _ model.CachedScorer = (*Model)(nil)
+
+// ScorePlan holds one schema. Its questions interact in the joint head, so a
+// complete schema is one backbone row even when it contains many questions.
+type ScorePlan struct {
+ Tokens []int32
+ prepared *model.PreparedRequest
+ segments []model.Segment
+ questions []encodedQuestion
+}
+
+// PrepareScore is CPU-only and needs no MLX thread or array scope, allowing
+// preparation to overlap GPU work. Score currently calls it serially.
+func (m *Model) PrepareScore(ctx context.Context, input llm.ScoreRequest) (*ScorePlan, error) {
+ if len(input.Segments) < 3 || len(input.Fields) < 1 || len(input.Fields) > 64 || input.MaxTokens < 1 || input.MaxTokens > m.MaxContextLength() {
+ return nil, api.StatusError{StatusCode: http.StatusBadRequest, ErrorMessage: "invalid Clef question count or context limit"}
+ }
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ if len(input.Images) > 0 && input.ImagePosition != 1 {
+ return nil, api.StatusError{StatusCode: http.StatusBadRequest, ErrorMessage: "Clef images must precede the state"}
+ }
+ segments := []model.Segment{{Tokens: m.Tokenizer().Encode(input.Segments[0], false)}}
+ for _, image := range input.Images {
+ if len(image) == 0 {
+ return nil, api.StatusError{StatusCode: http.StatusBadRequest, ErrorMessage: "image must not be empty"}
+ }
+ segments = append(segments, model.Segment{Kind: "image", Data: image})
+ }
+ if len(input.Images) > 0 {
+ segments = append(segments, model.Segment{Tokens: m.Tokenizer().Encode("\n", false)})
+ }
+ prepared, err := m.PrepareMedia(segments)
+ if err != nil {
+ return nil, api.StatusError{StatusCode: http.StatusBadRequest, ErrorMessage: err.Error()}
+ }
+ // Reserve the entire image prefix before truncating only the state.
+ record, err := encode(m.Tokenizer(), input, prepared.Tokens)
+ if err != nil {
+ return nil, api.StatusError{StatusCode: http.StatusBadRequest, ErrorMessage: err.Error()}
+ }
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ prepared.Tokens = record.ids
+ return &ScorePlan{Tokens: record.ids, prepared: prepared, segments: segments, questions: record.questions}, nil
+}
+
+// FinishScore runs the unpadded joint head for this schema. The backbone can
+// batch compatible text rows, but the head's attention is schema-local.
+// Call it on the MLX thread, within the caller's scope, with one complete hidden row.
+func (m *Model) FinishScore(plan *ScorePlan, hidden *mlx.Array) [][]float32 {
+ ids := mlx.FromValues(plan.Tokens, len(plan.Tokens))
+ outputs := mlx.ScopedEval(func() []*mlx.Array {
+ outputs := m.Head.forward(hidden, ids, plan.questions, m.OutputEmbedding)
+ for i := range outputs {
+ outputs[i] = outputs[i].AsType(mlx.DTypeFloat32)
+ }
+ return outputs
+ })
+ result := make([][]float32, len(outputs))
+ for i, output := range outputs {
+ result[i] = output.Floats()
+ }
+ return result
+}
+
+// Score retains the serial runner path while sharing preparation and readout.
+// Keep preparation and readout model-owned and separate from forward execution
+// so scheduling can evolve without duplicating model logic.
+func (m *Model) Score(ctx context.Context, input llm.ScoreRequest, forward model.ScoreForward) (llm.ScoreResponse, error) {
+ var result llm.ScoreResponse
+ cached := 0
+ result.CachedTokens = &cached
+ plan, err := m.PrepareScore(ctx, input)
+ if err != nil {
+ return result, err
+ }
+ mlx.Scoped(func() {
+ var hidden *mlx.Array
+ hidden, cached, err = forward(ctx, plan.prepared, plan.segments)
+ if err != nil {
+ return
+ }
+ result.Logits = m.FinishScore(plan, hidden)
+ })
+ if err != nil {
+ return result, err
+ }
+ if len(result.Logits) != len(input.Fields) {
+ return result, fmt.Errorf("Clef returned an incomplete schema")
+ }
+ result.InputTokens = len(plan.Tokens)
+ return result, ctx.Err()
+}
diff --git a/mlxrunner/model/laya/attention_test.go b/mlxrunner/model/laya/attention_test.go
new file mode 100644
index 000000000..edbd9bea8
--- /dev/null
+++ b/mlxrunner/model/laya/attention_test.go
@@ -0,0 +1,110 @@
+package laya
+
+import (
+ "math"
+ "testing"
+
+ "github.com/ollama/ollama/mlx"
+ "github.com/ollama/ollama/mlx/mlxtest"
+ "github.com/ollama/ollama/mlxrunner/batch"
+ "github.com/ollama/ollama/mlxrunner/nn"
+)
+
+func TestBidirectionalAttention(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ local bool
+ want []float32
+ }{
+ {"global", false, []float32{3, 13, 3, 13, 3, 13, 3, 13}},
+ {"local", true, []float32{1, 11, 2, 12, 4, 14, 5, 15}},
+ } {
+ mlxtest.RunSubtest(t, tc.name, func(t *mlxtest.T) {
+ mlx.Scoped(func() {
+ // Zero queries/keys give uniform attention. The two heads average
+ // values [0,2,4,6] and [10,12,14,16], either over all positions
+ // or over the current position and its immediate neighbors.
+ qkv := mlx.FromValues([]float32{
+ 0, 0, 0, 0, 0, 10,
+ 0, 0, 0, 0, 2, 12,
+ 0, 0, 0, 0, 4, 14,
+ 0, 0, 0, 0, 6, 16,
+ }, 1, 4, 6)
+ b := &batch.Batch{
+ InputIDs: mlx.FromValues([]int32{0, 1, 2, 3}, 1, 4),
+ SeqOffsets: []int32{0},
+ SeqQueryLens: []int32{4},
+ }
+ var mask nn.AttentionMask
+ if tc.local {
+ blocked := float32(math.Inf(-1))
+ mask = nn.ArrayMask(mlx.FromValues([]float32{
+ 0, 0, blocked, blocked,
+ 0, 0, 0, blocked,
+ blocked, 0, 0, 0,
+ blocked, blocked, 0, 0,
+ }, 4, 4))
+ }
+ out := attention(b, qkv, 2, 0, mask).Reshape(-1)
+ mlx.Eval(out)
+ for i, got := range out.Floats() {
+ if !(math.Abs(float64(got-tc.want[i])) <= 1e-5) {
+ t.Fatalf("output %d = %g, want %g", i, got, tc.want[i])
+ }
+ }
+ })
+ })
+ }
+}
+
+func TestBatchMatchesIndividualDecisions(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ mlx.Scoped(func() {
+ // A small encoder with global and local layers followed by the
+ // decision head. Batch rows and their question types stay independent.
+ weight := func(rows, cols int) *mlx.Array {
+ return mlx.Sin(mlx.Arange(0, float64(rows*cols), 1, mlx.DTypeFloat32)).Reshape(rows, cols)
+ }
+ linear := func(out, in int) *nn.Linear { return &nn.Linear{Weight: weight(out, in)} }
+ norm := &nn.LayerNorm{Weight: mlx.FromValues([]float32{1, 1, 1, 1}, 4), Eps: 1e-5}
+ m := Model{
+ encoder: encoderConfig{HiddenSize: 4, Heads: 2, GlobalEvery: 2, LocalAttention: 2, GlobalTheta: 160000, LocalTheta: 10000},
+ Embeddings: weight(8, 4), TypeEmbedding: weight(3, 4), EmbeddingNorm: norm, FinalNorm: norm,
+ Layers: []encoderLayer{
+ {MLPNorm: norm, QKV: linear(12, 4), Out: linear(4, 4), In: linear(16, 4), Down: linear(4, 8)},
+ {AttentionNorm: norm, MLPNorm: norm, QKV: linear(12, 4), Out: linear(4, 4), In: linear(16, 4), Down: linear(4, 8)},
+ },
+ Head: []headLayer{{Norm1: norm, Norm2: norm, QKV: linear(12, 4), Out: linear(4, 4), In: linear(16, 4), Down: linear(4, 16)}},
+ ScoreNorm: norm, ScoreIn: linear(4, 4), ScoreOut: linear(1, 4),
+ }
+ rows := [][]int32{{1, 2, 3, 4}, {5, 6, 7, 5}}
+ types := []int32{0, 2}
+ b := &batch.Batch{
+ InputIDs: mlx.FromValues([]int32{1, 2, 3, 4, 5, 6, 7, 5}, 2, 4),
+ SeqOffsets: []int32{0, 0},
+ SeqQueryLens: []int32{4, 4},
+ Layout: []any{types[0], types[1]},
+ }
+ hidden, _ := m.Forward(b, nil)
+ out := m.Unembed(hidden).Reshape(-1)
+ mlx.Eval(out)
+ got := out.Floats()
+ for i, ids := range rows {
+ single := &batch.Batch{
+ InputIDs: mlx.FromValues(ids, 1, len(ids)),
+ SeqOffsets: []int32{0},
+ SeqQueryLens: []int32{int32(len(ids))},
+ Layout: []any{types[i]},
+ }
+ one, _ := m.Forward(single, nil)
+ scores := m.Unembed(one).Reshape(-1)
+ mlx.Eval(scores)
+ for j, want := range scores.Floats() {
+ if !(math.Abs(float64(got[i*4+j]-want)) <= 1e-5) {
+ t.Fatalf("row %d token %d: batched score %g, individual score %g", i, j, got[i*4+j], want)
+ }
+ }
+ }
+ })
+ })
+}
diff --git a/mlxrunner/model/laya/config.go b/mlxrunner/model/laya/config.go
new file mode 100644
index 000000000..64d8e461e
--- /dev/null
+++ b/mlxrunner/model/laya/config.go
@@ -0,0 +1,118 @@
+// Package laya implements the ModernBERT decision model from
+// https://github.com/NandhaKishorM/laya (Apache-2.0).
+package laya
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+
+ "github.com/ollama/ollama/mlxrunner/model"
+ "github.com/ollama/ollama/mlxrunner/tokenizer"
+)
+
+type encoderConfig struct {
+ ModelType string `json:"model_type"`
+ HiddenSize int `json:"hidden_size"`
+ IntermediateSize int `json:"intermediate_size"`
+ Layers int `json:"num_hidden_layers"`
+ Heads int `json:"num_attention_heads"`
+ VocabSize int `json:"vocab_size"`
+ GlobalEvery int `json:"global_attn_every_n_layers"`
+ LocalAttention int `json:"local_attention"`
+ NormEps float32 `json:"norm_eps"`
+ Activation string `json:"hidden_activation"`
+ AttentionBias bool `json:"attention_bias"`
+ MLPBias bool `json:"mlp_bias"`
+ NormBias bool `json:"norm_bias"`
+ GlobalTheta float32 `json:"global_rope_theta"`
+ LocalTheta float32 `json:"local_rope_theta"`
+ RopeParameters map[string]struct {
+ Theta float32 `json:"rope_theta"`
+ Type string `json:"rope_type"`
+ } `json:"rope_parameters"`
+}
+
+type config struct {
+ HeadLayers int `json:"head_layers"`
+ MaxLen int `json:"max_len"`
+ HeadMaxLen int `json:"head_max_len"`
+ Temperature []float32 `json:"temperature"`
+ TemperatureByOptions map[string]float32 `json:"temperature_by_options"`
+}
+
+func init() { model.Register("LayaForDecision", newModel) }
+
+func newModel(root *model.Root) (model.Model, error) {
+ // Laya needs extra precision.
+ if err := os.Setenv("MLX_ENABLE_TF32", "0"); err != nil {
+ return nil, err
+ }
+
+ m := &Model{}
+ if err := root.Manifest.ReadConfigJSON("encoder/config.json", &m.encoder); err != nil {
+ return nil, err
+ }
+ if err := root.Manifest.ReadConfigJSON("rl_agent_config.json", &m.config); err != nil {
+ return nil, err
+ }
+ e := &m.encoder
+ if e.ModelType != "modernbert" || e.HiddenSize <= 0 || e.Heads <= 0 || e.HiddenSize%e.Heads != 0 || (e.HiddenSize/e.Heads)%2 != 0 || e.Layers <= 0 || e.GlobalEvery <= 0 || e.IntermediateSize <= 0 || e.LocalAttention <= 0 || e.VocabSize <= 0 || e.AttentionBias || e.MLPBias || e.NormBias || (e.Activation != "" && e.Activation != "gelu") {
+ return nil, fmt.Errorf("unsupported Laya encoder configuration")
+ }
+ for _, rope := range e.RopeParameters {
+ if rope.Type != "" && rope.Type != "default" {
+ return nil, fmt.Errorf("unsupported Laya rotary embedding type %q", rope.Type)
+ }
+ }
+ if m.config.HeadLayers < 0 || m.config.HeadLayers > 8 || m.config.MaxLen <= 0 || m.config.MaxLen > 8192 || m.config.HeadMaxLen < 16 || m.config.HeadMaxLen >= m.config.MaxLen || len(m.config.Temperature) != 3 {
+ return nil, fmt.Errorf("invalid Laya decision configuration")
+ }
+ if e.NormEps == 0 {
+ e.NormEps = 1e-5
+ }
+ if e.GlobalTheta == 0 {
+ e.GlobalTheta = 160000
+ }
+ if e.LocalTheta == 0 {
+ e.LocalTheta = 10000
+ }
+ if v := e.RopeParameters["full_attention"].Theta; v != 0 {
+ e.GlobalTheta = v
+ }
+ if v := e.RopeParameters["sliding_attention"].Theta; v != 0 {
+ e.LocalTheta = v
+ }
+ data, err := root.Manifest.ReadConfig("tokenizer/tokenizer.json")
+ if err != nil {
+ return nil, err
+ }
+ m.tok, err = tokenizer.LoadFromBytes(data)
+ if err != nil {
+ return nil, err
+ }
+ var tokens struct {
+ CLS string `json:"cls_token"`
+ SEP string `json:"sep_token"`
+ Mask string `json:"mask_token"`
+ }
+ data, err = root.Manifest.ReadConfig("tokenizer/tokenizer_config.json")
+ if err != nil {
+ return nil, err
+ }
+ if err := json.Unmarshal(data, &tokens); err != nil {
+ return nil, err
+ }
+ for _, token := range []struct {
+ name string
+ dest *int32
+ }{{tokens.CLS, &m.cls}, {tokens.SEP, &m.sep}, {tokens.Mask, &m.mask}} {
+ id, ok := m.tok.GetSpecialToken(token.name)
+ if !ok || token.name == "" {
+ return nil, fmt.Errorf("missing Laya special token %q", token.name)
+ }
+ *token.dest = id
+ }
+ m.maskToken = tokens.Mask
+ return m, nil
+}
diff --git a/mlxrunner/model/laya/model.go b/mlxrunner/model/laya/model.go
new file mode 100644
index 000000000..92ad77d29
--- /dev/null
+++ b/mlxrunner/model/laya/model.go
@@ -0,0 +1,190 @@
+package laya
+
+import (
+ "fmt"
+ "math"
+
+ "github.com/ollama/ollama/mlx"
+ "github.com/ollama/ollama/mlxrunner/batch"
+ "github.com/ollama/ollama/mlxrunner/cache"
+ "github.com/ollama/ollama/mlxrunner/nn"
+ "github.com/ollama/ollama/mlxrunner/tokenizer"
+)
+
+type Model struct {
+ Embeddings *mlx.Array
+ TypeEmbedding *mlx.Array
+ EmbeddingNorm *nn.LayerNorm
+ FinalNorm *nn.LayerNorm
+ Layers []encoderLayer
+ Head []headLayer
+ ScoreNorm *nn.LayerNorm
+ ScoreIn *nn.Linear
+ ScoreOut *nn.Linear
+
+ encoder encoderConfig
+ config config
+ tok *tokenizer.Tokenizer
+ cls, sep, mask int32
+ maskToken string
+}
+
+type encoderLayer struct {
+ AttentionNorm, MLPNorm *nn.LayerNorm
+ QKV, Out, In, Down *nn.Linear
+}
+
+type headLayer struct {
+ Norm1, Norm2 *nn.LayerNorm
+ QKV, Out, In, Down *nn.Linear
+}
+
+func (m *Model) Tokenizer() *tokenizer.Tokenizer { return m.tok }
+func (m *Model) MaxContextLength() int { return m.config.MaxLen }
+func (m *Model) NewCaches() []cache.Cache { return nil }
+
+func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
+ var loadErr error
+ weight := func(name string, shape ...int) *mlx.Array {
+ w := tensors[name]
+ if w == nil {
+ if loadErr == nil {
+ loadErr = fmt.Errorf("missing Laya weight %s", name)
+ }
+ return nil
+ }
+ valid := w.NumDims() == len(shape)
+ if valid {
+ for i, n := range shape {
+ valid = valid && w.Dim(i) == n
+ }
+ }
+ if !valid {
+ if loadErr == nil {
+ loadErr = fmt.Errorf("invalid shape for Laya weight %s: want %v", name, shape)
+ }
+ return nil
+ }
+ if w.DType() != mlx.DTypeFloat16 && w.DType() != mlx.DTypeBFloat16 && w.DType() != mlx.DTypeFloat32 {
+ if loadErr == nil {
+ loadErr = fmt.Errorf("Laya requires unquantized floating-point weights: %s", name)
+ }
+ return nil
+ }
+ return w
+ }
+ d := m.encoder.HiddenSize
+ norm := func(name string, bias bool, eps float32) *nn.LayerNorm {
+ l := &nn.LayerNorm{Weight: weight(name+".weight", d), Eps: eps}
+ if bias {
+ l.Bias = weight(name+".bias", d)
+ }
+ return l
+ }
+ linear := func(name string, out, in int, bias bool) *nn.Linear {
+ l := &nn.Linear{Weight: weight(name+".weight", out, in)}
+ if bias {
+ l.Bias = weight(name+".bias", out)
+ }
+ return l
+ }
+ m.Embeddings = weight("encoder.embeddings.tok_embeddings.weight", m.encoder.VocabSize, d)
+ m.TypeEmbedding = weight("type_emb.weight", 3, d)
+ m.EmbeddingNorm = norm("encoder.embeddings.norm", false, m.encoder.NormEps)
+ m.FinalNorm = norm("encoder.final_norm", false, m.encoder.NormEps)
+ m.Layers = make([]encoderLayer, m.encoder.Layers)
+ for i := range m.Layers {
+ p := fmt.Sprintf("encoder.layers.%d", i)
+ l := &m.Layers[i]
+ if i != 0 {
+ l.AttentionNorm = norm(p+".attn_norm", false, m.encoder.NormEps)
+ }
+ l.MLPNorm = norm(p+".mlp_norm", false, m.encoder.NormEps)
+ l.QKV, l.Out = linear(p+".attn.Wqkv", 3*d, d, false), linear(p+".attn.Wo", d, d, false)
+ l.In = linear(p+".mlp.Wi", 2*m.encoder.IntermediateSize, d, false)
+ l.Down = linear(p+".mlp.Wo", d, m.encoder.IntermediateSize, false)
+ }
+ m.Head = make([]headLayer, m.config.HeadLayers)
+ for i := range m.Head {
+ p := fmt.Sprintf("head.layers.%d", i)
+ l := &m.Head[i]
+ l.Norm1, l.Norm2 = norm(p+".norm1", true, 1e-5), norm(p+".norm2", true, 1e-5)
+ l.QKV = &nn.Linear{Weight: weight(p+".self_attn.in_proj_weight", 3*d, d), Bias: weight(p+".self_attn.in_proj_bias", 3*d)}
+ l.Out = linear(p+".self_attn.out_proj", d, d, true)
+ l.In, l.Down = linear(p+".linear1", 4*d, d, true), linear(p+".linear2", d, 4*d, true)
+ }
+ m.ScoreNorm = norm("scorer.0", true, 1e-5)
+ m.ScoreIn, m.ScoreOut = linear("scorer.1", d, d, true), linear("scorer.3", 1, d, true)
+ return loadErr
+}
+
+// attention is bidirectional. Only the encoder's local layers use a window;
+// the learned decision head attends to every token without rotary positions.
+func attention(b *batch.Batch, qkv *mlx.Array, heads int, theta float32, mask nn.AttentionMask) *mlx.Array {
+ B, n, width := qkv.Dim(0), qkv.Dim(1), qkv.Dim(2)/3
+ part := func(i int) *mlx.Array {
+ return qkv.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(i*width, (i+1)*width)).Reshape(B, n, heads, width/heads).Transpose(0, 2, 1, 3)
+ }
+ q, k, v := part(0), part(1), part(2)
+ if theta != 0 {
+ offset := mlx.FromValues(b.SeqOffsets, B)
+ q = mlx.RoPEWithBase(q, width/heads, false, theta, 1, offset)
+ k = mlx.RoPEWithBase(k, width/heads, false, theta, 1, offset)
+ }
+ return nn.ScaledDotProductAttention(b, q, float32(1/math.Sqrt(float64(width/heads))), nn.WithKV(k, v, b.SeqQueryLens), nn.WithMask(mask)).Transpose(0, 2, 1, 3).Reshape(B, n, width)
+}
+
+func (m *Model) Forward(b *batch.Batch, _ []cache.Cache) (*mlx.Array, *mlx.Array) {
+ h := m.encoderForward(b)
+ // The question type is model-owned row metadata. A missing layout denotes
+ // the choice type for load-time probes.
+ types := make([]int32, b.InputIDs.Dim(0))
+ for i, layout := range b.Layout {
+ if layout != nil {
+ types[i] = layout.(int32)
+ }
+ }
+ h = h.Add(m.TypeEmbedding.TakeAxis(mlx.FromValues(types, len(types)), 0).ExpandDims(1))
+ for _, l := range m.Head {
+ h = l.forward(b, h, max(1, m.encoder.HiddenSize/64))
+ }
+ return h, nil
+}
+
+func (m *Model) encoderForward(b *batch.Batch) *mlx.Array {
+ h := m.EmbeddingNorm.Forward(m.Embeddings.TakeAxis(b.InputIDs, 0))
+ // Build the quadratic mask on the device; host input remains linear in n.
+ positions := mlx.Arange(0, float64(b.InputIDs.Dim(1)), 1, mlx.DTypeInt32)
+ local := positions.ExpandDims(0).Subtract(positions.ExpandDims(1)).Abs().LessEqual(mlx.NewScalarArray(float32(m.encoder.LocalAttention / 2)))
+ localMask := nn.ArrayMask(mlx.Where(local, mlx.FromValue(float32(0)), mlx.FromValue(float32(math.Inf(-1)))))
+ for i, l := range m.Layers {
+ theta, mask := m.encoder.GlobalTheta, nn.AttentionMask{}
+ if i%m.encoder.GlobalEvery != 0 {
+ theta, mask = m.encoder.LocalTheta, localMask
+ }
+ h = l.forward(b, h, m.encoder.Heads, theta, mask)
+ }
+ return m.FinalNorm.Forward(h)
+}
+
+func (l encoderLayer) forward(b *batch.Batch, h *mlx.Array, heads int, theta float32, mask nn.AttentionMask) *mlx.Array {
+ x := h
+ if l.AttentionNorm != nil {
+ x = l.AttentionNorm.Forward(x)
+ }
+ h = h.Add(l.Out.Forward(attention(b, l.QKV.Forward(x), heads, theta, mask)))
+ up := l.In.Forward(l.MLPNorm.Forward(h))
+ d := up.Dim(2) / 2
+ activated := mlx.GELU(up.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(0, d))).Multiply(up.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(d, 2*d)))
+ return h.Add(l.Down.Forward(activated))
+}
+
+func (l headLayer) forward(b *batch.Batch, h *mlx.Array, heads int) *mlx.Array {
+ h = h.Add(l.Out.Forward(attention(b, l.QKV.Forward(l.Norm1.Forward(h)), heads, 0, nn.AttentionMask{})))
+ // PyTorch TransformerEncoderLayer defaults to ReLU, not GELU.
+ return h.Add(l.Down.Forward(mlx.ReLU(l.In.Forward(l.Norm2.Forward(h)))))
+}
+
+func (m *Model) Unembed(h *mlx.Array) *mlx.Array {
+ return m.ScoreOut.Forward(mlx.GELU(m.ScoreIn.Forward(m.ScoreNorm.Forward(h))))
+}
diff --git a/mlxrunner/model/laya/score.go b/mlxrunner/model/laya/score.go
new file mode 100644
index 000000000..d9506d182
--- /dev/null
+++ b/mlxrunner/model/laya/score.go
@@ -0,0 +1,168 @@
+package laya
+
+import (
+ "context"
+ "fmt"
+ "math"
+ "net/http"
+ "strings"
+
+ "github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/llm"
+ "github.com/ollama/ollama/mlx"
+ "github.com/ollama/ollama/mlxrunner/batch"
+)
+
+var _ llm.Scorer = (*Model)(nil)
+
+// ScoreRow is a complete bidirectional input. Its marker positions refer to
+// real tokens, not to a padded batch tail.
+type ScoreRow struct {
+ Tokens []int32
+ Markers []int32
+ Type int32
+}
+
+func (m *Model) sequence(state string, q llm.ScoreQuestion, maxLen int) (ids, markers []int32, qtype int32, err error) {
+ switch q.Type {
+ case "choice":
+ qtype = 0
+ case "score":
+ qtype = 1
+ case "noul":
+ qtype = 2
+ default:
+ return nil, nil, 0, fmt.Errorf("unknown decision type %q", q.Type)
+ }
+ if len(q.Options) < 2 || len(q.Options) > 26 {
+ return nil, nil, 0, fmt.Errorf("decision requires 2–26 options")
+ }
+ encode := func(s string) []int32 { return m.tok.Encode(strings.ReplaceAll(s, m.maskToken, " "), false) }
+ head := encode(q.Type + " question: " + q.Instructions)
+ opts := make([][]int32, len(q.Options))
+ budget := m.config.HeadMaxLen
+ for i, text := range q.Options {
+ tokens := encode(" " + text)
+ opts[i] = append([]int32{m.mask}, tokens[:min(48, len(tokens))]...)
+ budget -= len(opts[i])
+ }
+ if budget < 16 {
+ per := max(4, (m.config.HeadMaxLen-16)/len(opts))
+ budget = m.config.HeadMaxLen
+ for i := range opts {
+ opts[i] = opts[i][:min(per, len(opts[i]))]
+ budget -= len(opts[i])
+ }
+ }
+ ids = append([]int32{m.cls}, head[:min(len(head), max(8, budget))]...)
+ ids = append(ids, m.sep)
+ for _, tokens := range opts {
+ markers = append(markers, int32(len(ids)))
+ ids = append(ids, tokens...)
+ }
+ ids = append(ids, m.sep)
+ if len(ids)+1 > maxLen {
+ return nil, nil, 0, fmt.Errorf("decision options exceed the %d-token context", maxLen)
+ }
+ stateTokens := encode(state)
+ // Match the publisher's question/state budget: options and instructions
+ // have their own cap, then state is truncated on the right to fit.
+ ids = append(ids, stateTokens[:min(len(stateTokens), maxLen-len(ids)-1)]...)
+ ids = append(ids, m.sep)
+ return ids, markers, qtype, nil
+}
+
+func (m *Model) temperature(qtype int32, count int) float32 {
+ size := "11+"
+ switch {
+ case count <= 2:
+ size = "2"
+ case count <= 5:
+ size = "3-5"
+ case count <= 10:
+ size = "6-10"
+ }
+ t := m.config.Temperature[qtype]
+ if v, ok := m.config.TemperatureByOptions[[]string{"choice", "score", "noul"}[qtype]+":"+size]; ok {
+ t = v
+ }
+ // This is the current author SDK's calibration clamp.
+ if math.IsNaN(float64(t)) || math.IsInf(float64(t), 0) {
+ return 1
+ }
+ return max(0.5, min(5, t))
+}
+
+// PrepareScore is CPU-only and needs no MLX thread or array scope, allowing
+// preparation to overlap GPU work. Score currently calls it serially.
+// Encoder rows cannot use causal prefix snapshots:
+// changing an option changes every bidirectional hidden state.
+func (m *Model) PrepareScore(ctx context.Context, input llm.ScoreRequest) ([]ScoreRow, error) {
+ badRequest := func(err error) ([]ScoreRow, error) {
+ return nil, api.StatusError{StatusCode: http.StatusBadRequest, ErrorMessage: err.Error()}
+ }
+ if len(input.Rows) < 1 || len(input.Rows) > 64 || input.MaxTokens < 1 || input.MaxTokens > m.config.MaxLen {
+ return badRequest(fmt.Errorf("invalid Laya row count or context limit"))
+ }
+ rows := make([]ScoreRow, len(input.Rows))
+ for i, row := range input.Rows {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ if row.Question == nil {
+ return badRequest(fmt.Errorf("Laya requires structured decision inputs"))
+ }
+ ids, markers, qtype, err := m.sequence(input.State, *row.Question, input.MaxTokens)
+ if err != nil {
+ return badRequest(fmt.Errorf("question %d: %w", i, err))
+ }
+ rows[i] = ScoreRow{Tokens: ids, Markers: markers, Type: qtype}
+ }
+ return rows, nil
+}
+
+// FinishScore reads only real marker positions from a completed row.
+// Call it on the MLX thread, within the caller's scope, with one complete hidden row.
+func (m *Model) FinishScore(row ScoreRow, hidden *mlx.Array) []float32 {
+ selected := hidden.TakeAxis(mlx.FromValues(row.Markers, len(row.Markers)), 1)
+ output := mlx.DivScalar(m.Unembed(selected).AsType(mlx.DTypeFloat32), m.temperature(row.Type, len(row.Markers))).Reshape(-1)
+ mlx.Eval(output)
+ return output.Floats()
+}
+
+// Score retains the serial runner path while sharing preparation and readout.
+// Keep preparation and readout model-owned and separate from forward execution
+// so scheduling can evolve without duplicating model logic.
+func (m *Model) Score(ctx context.Context, input llm.ScoreRequest) (llm.ScoreResponse, error) {
+ var result llm.ScoreResponse
+ // Bidirectional attention makes every hidden position depend on the suffix.
+ // Causal prefix state cannot be reused across these rows or requests.
+ cached := 0
+ result.CachedTokens = &cached
+ if err := ctx.Err(); err != nil {
+ return result, err
+ }
+ rows, err := m.PrepareScore(ctx, input)
+ if err != nil {
+ return result, err
+ }
+ for _, row := range rows {
+ if err := ctx.Err(); err != nil {
+ return result, err
+ }
+ var logits []float32
+ mlx.Scoped(func() {
+ b := &batch.Batch{
+ InputIDs: mlx.FromValues(row.Tokens, 1, len(row.Tokens)),
+ SeqOffsets: []int32{0},
+ SeqQueryLens: []int32{int32(len(row.Tokens))},
+ Layout: []any{row.Type},
+ }
+ hidden, _ := m.Forward(b, nil)
+ logits = m.FinishScore(row, hidden)
+ })
+ result.Logits = append(result.Logits, logits)
+ result.InputTokens += len(row.Tokens)
+ }
+ return result, ctx.Err()
+}
diff --git a/mlxrunner/model/laya/score_test.go b/mlxrunner/model/laya/score_test.go
new file mode 100644
index 000000000..7047f036d
--- /dev/null
+++ b/mlxrunner/model/laya/score_test.go
@@ -0,0 +1,63 @@
+package laya
+
+import (
+ "context"
+ "errors"
+ "math"
+ "net/http"
+ "testing"
+
+ "github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/llm"
+)
+
+func TestTemperature(t *testing.T) {
+ m := Model{config: config{Temperature: []float32{2, 3, 4}, TemperatureByOptions: map[string]float32{"choice:2": 1.5, "choice:11+": 0.1, "score:3-5": 7, "noul:2": float32(math.NaN())}}}
+ for _, tc := range []struct {
+ kind int32
+ count int
+ want float32
+ }{
+ {0, 2, 1.5}, {0, 6, 2}, {0, 26, 0.5}, {1, 3, 5}, {2, 2, 1},
+ } {
+ if got := m.temperature(tc.kind, tc.count); got != tc.want {
+ t.Errorf("type=%d count=%d: got %v want %v", tc.kind, tc.count, got, tc.want)
+ }
+ }
+}
+
+func TestScoreRejectsInvalidInputs(t *testing.T) {
+ m := Model{config: config{MaxLen: 512}}
+ for _, input := range []llm.ScoreRequest{
+ {},
+ {MaxTokens: 512, Rows: make([]llm.ScoreRow, 65)},
+ {MaxTokens: 513, Rows: []llm.ScoreRow{{}}},
+ {MaxTokens: 512, Rows: []llm.ScoreRow{{}}},
+ {MaxTokens: 512, Rows: []llm.ScoreRow{{Question: &llm.ScoreQuestion{Type: "chat"}}}},
+ {MaxTokens: 512, Rows: []llm.ScoreRow{{Question: &llm.ScoreQuestion{Type: "choice", Options: []string{"one"}}}}},
+ } {
+ _, err := m.Score(t.Context(), input)
+ var status api.StatusError
+ if !errors.As(err, &status) || status.StatusCode != http.StatusBadRequest {
+ t.Errorf("Score(%+v) error = %v, want bad request", input, err)
+ }
+ }
+ ctx, cancel := context.WithCancel(t.Context())
+ cancel()
+ if _, err := m.Score(ctx, llm.ScoreRequest{MaxTokens: 512, Rows: []llm.ScoreRow{{}}}); !errors.Is(err, context.Canceled) {
+ t.Errorf("cancelled score: %v", err)
+ }
+}
+
+func TestPrepareScoreCancellation(t *testing.T) {
+ m := Model{config: config{MaxLen: 512}}
+ ctx, cancel := context.WithCancel(t.Context())
+ cancel()
+ rows, err := m.PrepareScore(ctx, llm.ScoreRequest{
+ MaxTokens: 512,
+ Rows: []llm.ScoreRow{{Question: &llm.ScoreQuestion{Type: "choice", Options: []string{"yes", "no"}}}},
+ })
+ if !errors.Is(err, context.Canceled) || rows != nil {
+ t.Fatalf("cancelled preparation: rows=%v, err=%v", rows, err)
+ }
+}
diff --git a/mlxrunner/model/qwen3_5/score.go b/mlxrunner/model/qwen3_5/score.go
new file mode 100644
index 000000000..58be6bdf1
--- /dev/null
+++ b/mlxrunner/model/qwen3_5/score.go
@@ -0,0 +1,23 @@
+package qwen3_5
+
+import (
+ "github.com/ollama/ollama/mlx"
+ "github.com/ollama/ollama/mlxrunner/nn"
+)
+
+// UnembedCandidates scores one hidden position. For dense heads, gather before
+// casting so the output stays in FP32 without allocating an
+// FP32 copy of the full vocabulary head. This also covers tied dense embeddings.
+func (m *Model) UnembedCandidates(hidden, candidates *mlx.Array) *mlx.Array {
+ if head, ok := m.LMHead.(*nn.Linear); ok {
+ weight := head.Weight.TakeAxis(candidates, 0).AsType(mlx.DTypeFloat32)
+ logits := hidden.AsType(mlx.DTypeFloat32).Matmul(weight.Transpose(1, 0)).Reshape(-1)
+ if head.Bias != nil {
+ logits = logits.Add(head.Bias.TakeAxis(candidates, 0).AsType(mlx.DTypeFloat32))
+ }
+ return logits
+ }
+ // Retain existing quantization, bias, and global-scale handling. Selected-row
+ // dequantization can be added separately when its formats are validated.
+ return m.Unembed(hidden).Reshape(-1).TakeAxis(candidates, 0)
+}
diff --git a/mlxrunner/model/qwen3_5/score_test.go b/mlxrunner/model/qwen3_5/score_test.go
new file mode 100644
index 000000000..af1e90b7c
--- /dev/null
+++ b/mlxrunner/model/qwen3_5/score_test.go
@@ -0,0 +1,79 @@
+package qwen3_5
+
+import (
+ "math"
+ "testing"
+
+ "github.com/ollama/ollama/mlx"
+ "github.com/ollama/ollama/mlx/mlxtest"
+ "github.com/ollama/ollama/mlxrunner/nn"
+)
+
+func TestUnembedCandidates(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ mlx.Scoped(func() {
+ values := make([]float32, 7*8)
+ for i := range values {
+ values[i] = float32(math.Sin(float64(i)))
+ }
+ weight := mlx.FromValues(values, 7, 8).AsType(mlx.DTypeBFloat16)
+ hidden := mlx.FromValues([]float32{0.7, 1.3, -2.9, 3.1, 0.06, 1.01, -5.03, 2.17}, 1, 1, 8).AsType(mlx.DTypeBFloat16)
+ ids := mlx.FromValues([]int32{6, 2, 0}, 3)
+ bias := mlx.FromValues([]float32{0.1, 1.2, 2.3, 3.4, 4.5, 5.6, 6.7}, 7).AsType(mlx.DTypeBFloat16)
+ for _, b := range []*mlx.Array{nil, bias} {
+ m := &Model{LMHead: nn.NewLinear(weight, b)}
+ got := m.UnembedCandidates(hidden, ids)
+ full := hidden.AsType(mlx.DTypeFloat32).Matmul(weight.AsType(mlx.DTypeFloat32).Transpose(1, 0)).Reshape(-1)
+ if b != nil {
+ full = full.Add(b.AsType(mlx.DTypeFloat32))
+ }
+ want := full.TakeAxis(ids, 0)
+ mlx.Eval(got, want)
+ if got.DType() != mlx.DTypeFloat32 || got.Dim(0) != 3 {
+ t.Fatal("candidate logits must retain FP32 precision")
+ }
+ actual, expected := got.Floats(), want.Floats()
+ for i, v := range actual {
+ if math.Abs(float64(v-expected[i])) > 1e-6 {
+ t.Fatalf("candidate %d: selected=%g full=%g", i, v, expected[i])
+ }
+ }
+ }
+ })
+ })
+}
+
+func TestUnembedQuantizedCandidates(t *testing.T) {
+ for _, mode := range []string{"affine", "nvfp4"} {
+ mlxtest.RunSubtest(t, mode, func(t *mlxtest.T) {
+ mlx.Scoped(func() {
+ values := make([]float32, 32*64)
+ for i := range values {
+ values[i] = float32(math.Sin(float64(i)))
+ }
+ weight := mlx.FromValues(values, 32, 64).AsType(mlx.DTypeBFloat16)
+ groupSize := 64
+ if mode == "nvfp4" {
+ groupSize = 16
+ }
+ bias := mlx.FromValues(values[:32], 32).AsType(mlx.DTypeBFloat16)
+ head := nn.NewQuantizedLinear(weight, bias, groupSize, 4, mode)
+ if mode == "nvfp4" {
+ head.GlobalScale = mlx.FromValues([]float32{0.5}, 1)
+ }
+ m := &Model{LMHead: head}
+ hidden := mlx.FromValues(values[:64], 1, 1, 64).AsType(mlx.DTypeBFloat16)
+ ids := mlx.FromValues([]int32{31, 2, 0}, 3)
+ got := m.UnembedCandidates(hidden, ids).AsType(mlx.DTypeFloat32)
+ want := m.Unembed(hidden).Reshape(-1).TakeAxis(ids, 0).AsType(mlx.DTypeFloat32)
+ mlx.Eval(got, want)
+ actual, expected := got.Floats(), want.Floats()
+ for i, v := range actual {
+ if v != expected[i] {
+ t.Fatalf("candidate %d: selected=%g full=%g", i, v, expected[i])
+ }
+ }
+ })
+ })
+ }
+}
diff --git a/mlxrunner/model/score.go b/mlxrunner/model/score.go
new file mode 100644
index 000000000..2a8dcc786
--- /dev/null
+++ b/mlxrunner/model/score.go
@@ -0,0 +1,19 @@
+package model
+
+import (
+ "context"
+
+ "github.com/ollama/ollama/llm"
+ "github.com/ollama/ollama/mlx"
+)
+
+// ScoreForward evaluates a causal backbone through the runner's prefix cache,
+// returning the complete hidden row and the number of restored tokens. Segments supply
+// the original media bytes for cache identity. Call within an MLX scope.
+type ScoreForward func(context.Context, *PreparedRequest, []Segment) (*mlx.Array, int, error)
+
+// CachedScorer owns decision preparation and readout; the runner owns forward
+// execution and retained state. Bidirectional encoders cannot use this path.
+type CachedScorer interface {
+ Score(context.Context, llm.ScoreRequest, ScoreForward) (llm.ScoreResponse, error)
+}
diff --git a/mlxrunner/model/strands/model.go b/mlxrunner/model/strands/model.go
new file mode 100644
index 000000000..9f62890b9
--- /dev/null
+++ b/mlxrunner/model/strands/model.go
@@ -0,0 +1,97 @@
+// Package strands implements Strands Decider's Qwen3.5 pointer-head model.
+package strands
+
+import (
+ "fmt"
+ "math"
+ "slices"
+
+ "github.com/ollama/ollama/mlx"
+ "github.com/ollama/ollama/mlxrunner/model"
+ "github.com/ollama/ollama/mlxrunner/model/qwen3_5"
+ "github.com/ollama/ollama/mlxrunner/nn"
+)
+
+type config struct {
+ HeadType string `json:"head_type"`
+ PointerDim int `json:"pointer_dim"`
+ MaxLength int `json:"max_length"`
+ Temperature float32 `json:"temperature"`
+ TemperatureByKind map[string]float32 `json:"temperature_by_kind"`
+}
+
+type Model struct {
+ *qwen3_5.Model
+ HeadNorm *nn.LayerNorm
+ Query, Key *nn.Linear
+ config config
+}
+
+func init() { model.Register("StrandsDeciderForDecision", newModel) }
+
+func newModel(root *model.Root) (model.Model, error) {
+ cfg := config{Temperature: 1}
+ name := "strands_decider_config.json"
+ if _, ok := root.Manifest.ConfigLayer(name); !ok {
+ name = "hobson_config.json"
+ }
+ if err := root.Manifest.ReadConfigJSON(name, &cfg); err != nil {
+ return nil, err
+ }
+ if cfg.HeadType != "pointer" || cfg.PointerDim <= 0 || cfg.MaxLength <= 0 {
+ return nil, fmt.Errorf("unsupported Strands Decider head configuration")
+ }
+ validTemperature := func(t float32) bool { return t > 0 && !math.IsNaN(float64(t)) && !math.IsInf(float64(t), 0) }
+ if !validTemperature(cfg.Temperature) {
+ return nil, fmt.Errorf("invalid Strands Decider temperature")
+ }
+ for kind, t := range cfg.TemperatureByKind {
+ if !validTemperature(t) {
+ return nil, fmt.Errorf("invalid Strands Decider %s temperature", kind)
+ }
+ }
+ backbone, err := qwen3_5.NewModel(root)
+ if err != nil {
+ return nil, err
+ }
+ m := &Model{Model: backbone.(*qwen3_5.Model), config: cfg}
+ if m.Config.ModelType != "qwen3_5_text" && m.Config.ModelType != "qwen3_5" {
+ return nil, fmt.Errorf("unsupported Strands Decider backbone %q", m.Config.ModelType)
+ }
+ return m, nil
+}
+
+func (m *Model) MaxContextLength() int { return min(m.config.MaxLength, m.Model.MaxContextLength()) }
+
+func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
+ if err := m.Model.LoadWeights(tensors); err != nil {
+ return err
+ }
+ hidden, dim := int(m.Config.HiddenSize), m.config.PointerDim
+ for name, shape := range map[string][]int{
+ "norm.weight": {hidden}, "norm.bias": {hidden},
+ "q.weight": {dim, hidden}, "q.bias": {dim},
+ "k.weight": {dim, hidden}, "k.bias": {dim},
+ } {
+ w := tensors[name]
+ if w == nil || !slices.Equal(w.Dims(), shape) || w.DType() != mlx.DTypeFloat32 {
+ return fmt.Errorf("Strands Decider head requires FP32 %s with shape %v", name, shape)
+ }
+ }
+ m.HeadNorm = &nn.LayerNorm{Weight: tensors["norm.weight"], Bias: tensors["norm.bias"], Eps: 1e-5}
+ m.Query = &nn.Linear{Weight: tensors["q.weight"], Bias: tensors["q.bias"]}
+ m.Key = &nn.Linear{Weight: tensors["k.weight"], Bias: tensors["k.bias"]}
+ return nil
+}
+
+// The publisher keeps the pointer head in FP32, including its input normalization.
+func (m *Model) pointer(query, options *mlx.Array, kind int) *mlx.Array {
+ q := m.Query.Forward(m.HeadNorm.Forward(query.AsType(mlx.DTypeFloat32)))
+ k := m.Key.Forward(m.HeadNorm.Forward(options.AsType(mlx.DTypeFloat32)))
+ temperature := m.config.Temperature
+ if t, ok := m.config.TemperatureByKind[[]string{"noul", "choice", "score"}[kind]]; ok {
+ temperature = t
+ }
+ scale := float32(math.Sqrt(float64(m.config.PointerDim))) * max(temperature, 1e-6)
+ return mlx.DivScalar(mlx.Matmul(k, q.Transpose(0, 2, 1)).Squeeze(-1), scale)
+}
diff --git a/mlxrunner/model/strands/model_test.go b/mlxrunner/model/strands/model_test.go
new file mode 100644
index 000000000..9fdbe8cb3
--- /dev/null
+++ b/mlxrunner/model/strands/model_test.go
@@ -0,0 +1,53 @@
+package strands
+
+import (
+ "math"
+ "testing"
+
+ "github.com/ollama/ollama/mlx"
+ "github.com/ollama/ollama/mlx/mlxtest"
+ "github.com/ollama/ollama/mlxrunner/nn"
+)
+
+func TestPointerHead(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ mlx.Scoped(func() {
+ var m *Model
+ mlx.ScopedArrays(func() []*mlx.Array {
+ identity := mlx.FromValues([]float32{1, 0, 0, 1}, 2, 2)
+ m = &Model{
+ HeadNorm: &nn.LayerNorm{Weight: mlx.FromValues([]float32{1, 1}, 2), Bias: mlx.FromValues([]float32{0, 0}, 2), Eps: 1e-5},
+ Query: nn.NewLinear(identity, nil), Key: nn.NewLinear(identity, nil),
+ config: config{PointerDim: 2, Temperature: 1, TemperatureByKind: map[string]float32{"choice": 2}},
+ }
+ return mlx.Collect(m)
+ })
+ // Two independent rows have opposite queries and the same ordered options.
+ query := mlx.FromValues([]float32{1, -1, -1, 1}, 2, 1, 2).AsType(mlx.DTypeBFloat16)
+ options := mlx.FromValues([]float32{1, -1, -1, 1, 1, -1, -1, 1}, 2, 2, 2).AsType(mlx.DTypeBFloat16)
+ for _, kind := range []int{0, 1, 2} {
+ got := m.pointer(query, options, kind)
+ mlx.Eval(got)
+ if got.DType() != mlx.DTypeFloat32 {
+ t.Fatalf("pointer output dtype = %v", got.DType())
+ }
+ magnitude := math.Sqrt(2) / (1 + 1e-5)
+ if kind == 1 {
+ magnitude /= 2
+ }
+ for i, want := range []float64{magnitude, -magnitude, -magnitude, magnitude} {
+ if v := float64(got.Floats()[i]); math.IsNaN(v) || math.Abs(v-want) > 2e-3 {
+ t.Fatalf("kind %d output %d = %g, want %g", kind, i, v, want)
+ }
+ }
+ }
+ row := ScoreRow{Tokens: []int32{0, 0, 0}, Pointers: []int32{1, 0}, Type: 0}
+ hidden := mlx.FromValues([]float32{1, -1, -1, 1, 1, -1, 99, -99}, 1, 4, 2)
+ got := m.FinishScore(row, hidden)
+ magnitude := math.Sqrt(2) / (1 + 1e-5)
+ if math.Abs(float64(got[0])+magnitude) > 2e-3 || math.Abs(float64(got[1])-magnitude) > 2e-3 {
+ t.Fatalf("wrong pointer order or query position with padded tail: %v", got)
+ }
+ })
+ })
+}
diff --git a/mlxrunner/model/strands/score.go b/mlxrunner/model/strands/score.go
new file mode 100644
index 000000000..5559463b1
--- /dev/null
+++ b/mlxrunner/model/strands/score.go
@@ -0,0 +1,124 @@
+package strands
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "strings"
+
+ "github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/llm"
+ "github.com/ollama/ollama/mlx"
+ "github.com/ollama/ollama/mlxrunner/model"
+ "github.com/ollama/ollama/mlxrunner/tokenizer"
+)
+
+var _ model.CachedScorer = (*Model)(nil)
+
+// ScoreRow is one independent question. Pointers refer to real option tokens;
+// the query is the final real token, even when the forward row is padded.
+type ScoreRow struct {
+ Tokens []int32
+ Pointers []int32
+ Type int
+}
+
+// PrepareScore needs no MLX thread or array scope and can overlap GPU execution.
+func (m *Model) PrepareScore(ctx context.Context, input llm.ScoreRequest) ([]ScoreRow, error) {
+ if len(input.PointerRows) < 1 || len(input.PointerRows) > 64 || len(input.Images) != 0 || input.MaxTokens < 1 || input.MaxTokens > m.MaxContextLength() {
+ return nil, api.StatusError{StatusCode: http.StatusBadRequest, ErrorMessage: "invalid Strands Decider rows, images, or context limit"}
+ }
+ rows := make([]ScoreRow, len(input.PointerRows))
+ for i, row := range input.PointerRows {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ encoded, err := encode(m.Tokenizer(), row, input.MaxTokens)
+ if err != nil {
+ return nil, api.StatusError{StatusCode: http.StatusBadRequest, ErrorMessage: fmt.Sprintf("question %d: %v", i, err)}
+ }
+ rows[i] = encoded
+ }
+ return rows, nil
+}
+
+func encode(tok *tokenizer.Tokenizer, row llm.ScorePointerRow, limit int) (ScoreRow, error) {
+ result := ScoreRow{Type: row.Type}
+ count := len(row.Options)
+ if row.Type < 0 || row.Type > 2 || count < 2 || count > 255 || (row.Type == 0 && count != 2) || (row.Type == 2 && count > 10) {
+ return result, fmt.Errorf("invalid pointer question type or option count")
+ }
+ prefix := tok.Encode(row.Prefix, true)
+ suffix := tok.Encode(row.Prompt, false)
+ if len(suffix) == 0 || len(prefix)+len(suffix) > limit {
+ return result, fmt.Errorf("decision input exceeds the %d-token context or has no question", limit)
+ }
+ // Tokenize the entire question once. Encoding options separately changes BPE
+ // boundaries, and the head reads the last token wholly inside each option.
+ ends := make([]int, len(suffix))
+ var decoded strings.Builder
+ for i, id := range suffix {
+ decoded.WriteString(tok.Decode([]int32{id}))
+ ends[i] = decoded.Len()
+ }
+ if decoded.String() != row.Prompt {
+ return result, fmt.Errorf("cannot map decision option spans to tokenizer bytes")
+ }
+ previous := 0
+ for _, span := range row.Options {
+ if span[0] < previous || span[0] >= span[1] || span[1] > len(row.Prompt) {
+ return result, fmt.Errorf("invalid decision option span")
+ }
+ pointer, start := -1, 0
+ for j, end := range ends {
+ if start >= span[0] && end <= span[1] && end > start {
+ pointer = j
+ }
+ start = end
+ }
+ if pointer < 0 {
+ return result, fmt.Errorf("decision option contains no complete token")
+ }
+ result.Pointers = append(result.Pointers, int32(len(prefix)+pointer))
+ previous = span[1]
+ }
+ result.Tokens = append(prefix, suffix...)
+ return result, nil
+}
+
+// FinishScore reads the option pointers and final query from one complete row.
+// Call on the MLX thread within the caller's scope; padded tail states are ignored.
+func (m *Model) FinishScore(row ScoreRow, hidden *mlx.Array) []float32 {
+ options := hidden.TakeAxis(mlx.FromValues(row.Pointers, len(row.Pointers)), 1)
+ n := len(row.Tokens)
+ query := hidden.Slice(mlx.Slice(), mlx.Slice(n-1, n), mlx.Slice())
+ output := m.pointer(query, options, row.Type).Reshape(-1)
+ mlx.Eval(output)
+ return output.Floats()
+}
+
+func (m *Model) Score(ctx context.Context, input llm.ScoreRequest, forward model.ScoreForward) (llm.ScoreResponse, error) {
+ var result llm.ScoreResponse
+ cached := 0
+ result.CachedTokens = &cached
+ rows, err := m.PrepareScore(ctx, input)
+ if err != nil {
+ return result, err
+ }
+ for _, row := range rows {
+ mlx.Scoped(func() {
+ var hidden *mlx.Array
+ var restored int
+ hidden, restored, err = forward(ctx, &model.PreparedRequest{Tokens: row.Tokens}, nil)
+ cached += restored
+ if err == nil {
+ result.Logits = append(result.Logits, m.FinishScore(row, hidden))
+ }
+ })
+ if err != nil {
+ return result, err
+ }
+ result.InputTokens += len(row.Tokens)
+ }
+ return result, ctx.Err()
+}
diff --git a/mlxrunner/model/strands/score_test.go b/mlxrunner/model/strands/score_test.go
new file mode 100644
index 000000000..78f075cab
--- /dev/null
+++ b/mlxrunner/model/strands/score_test.go
@@ -0,0 +1,58 @@
+package strands
+
+import (
+ "context"
+ "errors"
+ "slices"
+ "testing"
+
+ "github.com/ollama/ollama/llm"
+ "github.com/ollama/ollama/mlxrunner/model/qwen3_5"
+ "github.com/ollama/ollama/mlxrunner/tokenizer"
+)
+
+func TestPointerTokens(t *testing.T) {
+ // A merged token may straddle the end of an option; it must be excluded.
+ tok, err := tokenizer.LoadFromBytes([]byte(`{"model":{"type":"BPE","vocab":{"x":0,"a":1,"b":2,"Ċ":3,"ab":4,"abĊ":5,"Ã":6,"©":7},"merges":["a b","ab Ċ"]}}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, tc := range []struct {
+ name, prompt string
+ spans [][2]int
+ pointers []int32
+ }{
+ {"merged", "xab\nxab\nx", [][2]int{{0, 2}, {4, 6}}, []int32{1, 4}},
+ {"unicode", "xé\nxé\nx", [][2]int{{0, 3}, {4, 7}}, []int32{3, 7}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := encode(tok, llm.ScorePointerRow{Prefix: "x", Prompt: tc.prompt, Type: 1, Options: tc.spans}, 32)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(got.Pointers, tc.pointers) {
+ t.Fatalf("pointers = %v, want %v (tokens %v)", got.Pointers, tc.pointers, got.Tokens)
+ }
+ })
+ }
+ for _, spans := range [][][2]int{
+ {{-1, 1}, {1, 2}}, {{1, 1}, {1, 2}}, {{0, 2}, {1, 3}}, {{0, 1}, {2, 99}}, {{1, 2}, {3, 4}},
+ } {
+ if _, err := encode(tok, llm.ScorePointerRow{Prompt: "xab\nx", Type: 1, Options: spans}, 32); err == nil {
+ t.Fatalf("accepted invalid or tokenless spans %v", spans)
+ }
+ }
+ if _, err := encode(tok, llm.ScorePointerRow{Prefix: "xxx", Prompt: "x\nx", Type: 1, Options: [][2]int{{0, 1}, {2, 3}}}, 5); err == nil {
+ t.Fatal("accepted input over context")
+ }
+}
+
+func TestPrepareScoreCanceled(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ m := &Model{Model: &qwen3_5.Model{Config: &qwen3_5.Config{MaxPositionEmbeddings: 4096}}, config: config{MaxLength: 4096}}
+ _, err := m.PrepareScore(ctx, llm.ScoreRequest{MaxTokens: 4096, PointerRows: []llm.ScorePointerRow{{}}})
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("error = %v, want cancellation before tokenization", err)
+ }
+}
diff --git a/mlxrunner/pipeline.go b/mlxrunner/pipeline.go
index 7ac38c58a..7d7b3dd97 100644
--- a/mlxrunner/pipeline.go
+++ b/mlxrunner/pipeline.go
@@ -154,9 +154,8 @@ func (r *Runner) prefill(ctx context.Context, session *cacheSession, spec *specu
// Request periodic snapshots during prefill and near the end of the
// prompt so that long prompts can be partially restored and
// thinking/generation can be retried without full reprocessing.
- const snapshotInterval = 8192
var snapshotOffsets []int
- for offset := snapshotInterval; offset < len(inputs); offset += snapshotInterval {
+ for offset := prefillSnapshotInterval; offset < len(inputs); offset += prefillSnapshotInterval {
snapshotOffsets = append(snapshotOffsets, offset)
}
diff --git a/mlxrunner/prefix_cache.go b/mlxrunner/prefix_cache.go
index 0cf0742be..02259ba63 100644
--- a/mlxrunner/prefix_cache.go
+++ b/mlxrunner/prefix_cache.go
@@ -6,8 +6,8 @@
// Invariants:
// - Only one path through the trie is "active" (backed by live MLX arrays)
// at a time. Switching paths pages in the new path from its snapshots.
-// - Sliceable (KV) layers: every node holds a snapshot covering exactly its
-// edge, so the layer's history is complete along any path from the root.
+// - Sliceable (KV, hidden-output) snapshots cover their node's edge. Restoring
+// a prefix requires continuous history from the root for these caches.
// - Whole-state (recurrent, rotating) layers: what a node holds is the
// state at its end offset. A node may hold none.
// - Whole-state is captured only while the live caches sit at that offset
@@ -23,8 +23,8 @@
// boundary or resume point lies strictly inside them.
// - Sibling edges must not share a common token prefix (compressed trie
// invariant).
-// - begin() always re-evaluates at least one token so the pipeline can seed
-// generation, even on a full prefix match.
+// - Generation re-evaluates at least one token to seed decoding. Scoring
+// retains hidden outputs and may restore the complete prompt.
package mlxrunner
@@ -40,6 +40,8 @@ import (
"github.com/ollama/ollama/mlxrunner/cache"
)
+const prefillSnapshotInterval = 8192
+
const maxPagedOutBytes int64 = 8 << 30 // 8 GiB eviction threshold for paged-out snapshot memory
type prefixCache struct {
@@ -59,9 +61,9 @@ type pendingSnapshot struct {
user bool
}
-// cacheSession manages caches for a single pipeline run.
-// Callers should append generated tokens to outputs and
-// defer close to save the cache state.
+// cacheSession manages caches for one generation or scoring run.
+// Generation appends generated tokens to outputs; both paths defer close
+// to save the evaluated state.
type cacheSession struct {
cache *prefixCache
inputs []int32
@@ -95,6 +97,15 @@ func (c *prefixCache) ensureRoot() {
// begin prepares caches for a new request. It finds the nearest
// matching cache or creates new caches if none match.
func (c *prefixCache) begin(inputs []int32, items []mediaItem) *cacheSession {
+ return c.beginAt(inputs, items, max(0, len(inputs)-1))
+}
+
+// Scoring retains backbone outputs, so an exact hit needs no decode seed.
+func (c *prefixCache) beginScore(inputs []int32, items []mediaItem) *cacheSession {
+ return c.beginAt(inputs, items, len(inputs))
+}
+
+func (c *prefixCache) beginAt(inputs []int32, items []mediaItem, maxReuse int) *cacheSession {
c.ensureRoot()
effInputs := effectiveKeyTokens(inputs, items)
@@ -102,10 +113,9 @@ func (c *prefixCache) begin(inputs []int32, items []mediaItem) *cacheSession {
matchPath, matched := findBestMatch(c.root, keys)
originalMatched := matched
- // Always keep at least one token to re-evaluate so the
- // pipeline can seed token generation from it.
- if matched == len(inputs) && matched > 0 {
- matchPath, matched = findBestMatch(c.root, keys[:matched-1])
+ // Generation leaves a decode seed; scoring can reuse the full row.
+ if matched > maxReuse {
+ matchPath, matched = findBestMatch(c.root, keys[:maxReuse])
}
// A match ending inside a non-causal media item resumes before it.
if item := insideAtomicItem(items, matched); item != nil {
@@ -312,7 +322,8 @@ pageIn:
// schedulePrefillSnapshots schedules every cache to capture snapshots as the
// forward pass crosses the given absolute token offsets, so a single full-size
-// prefill records interior states without the caller breaking the batch. A
+// prefill records interior states without the caller breaking the batch.
+// Recurrent caches split their internal recurrence at these boundaries. A
// passed offset names a token prefix; the capture lands at the deepest
// state that prefix alone determines (offset - draftLookahead), which is where
// a prompt sharing exactly that prefix restores. An offset inside a non-causal
@@ -399,10 +410,9 @@ func (s *cacheSession) attachPrefillSnapshots() {
}
}
- // Prefill leaves one token unprocessed for decode seeding, so an offset
- // at or past the live cache position was never crossed by a write and has
- // no captured state. Skip it rather than materialize a node whose edge
- // claims tokens the cache never wrote. Closing its (nil) row is a no-op.
+ // Only attach offsets reached by a completed write. Generation prefill
+ // leaves a decode seed, scoring may evaluate the full prompt, and either
+ // path can stop early on cancellation.
reached := c.minCacheOffset()
stored := s.storedKeys()
for i, p := range pending {
@@ -539,6 +549,23 @@ func (c *prefixCache) freeAll() {
}
}
+func (c *prefixCache) close() {
+ if c == nil {
+ return
+ }
+ nodes := []*trieNode{c.root}
+ for len(nodes) > 0 {
+ n := nodes[len(nodes)-1]
+ nodes = nodes[:len(nodes)-1]
+ if n != nil {
+ nodes = append(nodes, n.children...)
+ n.setSnapshots(nil, nil)
+ }
+ }
+ c.freeAll()
+ c.root, c.activePath, c.pagedOutBytes = nil, nil, 0
+}
+
func (c *prefixCache) minCacheOffset() int {
offset := 0
found := false
diff --git a/mlxrunner/prefix_cache_test.go b/mlxrunner/prefix_cache_test.go
index ba71764b5..e163b0370 100644
--- a/mlxrunner/prefix_cache_test.go
+++ b/mlxrunner/prefix_cache_test.go
@@ -813,6 +813,30 @@ func TestExactMatchSeedBehavior(t *testing.T) {
})
}
+func TestPrefixCacheClose(t *testing.T) {
+ forEachEnv(t, func(t *testing.T, env *testEnv) {
+ pc := env.pc
+ simulateRequest(t, pc, []int32{1, 2, 3, 4, 5}, []int32{6, 7}, 2)
+ simulateRequest(t, pc, []int32{1, 2, 8, 9, 10}, []int32{11, 12}, 2)
+ if len(env.tracker.all) == 0 {
+ t.Fatal("requests produced no snapshots")
+ }
+ pc.close()
+ if pc.root != nil || len(pc.activePath) != 0 || pc.pagedOutBytes != 0 {
+ t.Fatal("closed cache retains trie state")
+ }
+ for i, c := range pc.caches {
+ if c != nil && c.Offset() != 0 {
+ t.Fatalf("cache %d retains offset %d after close", i, c.Offset())
+ }
+ }
+ checkSnapshotLeaks(t, env.tracker, pc.root)
+ // Repeated teardown must not close snapshots twice.
+ pc.close()
+ checkSnapshotLeaks(t, env.tracker, pc.root)
+ })
+}
+
// TestConversationResumption tests the most common pattern: user sends a message,
// gets a response, then sends a follow-up. The follow-up should reuse the cached
// prefix (system prompt + first turn + assistant response).
diff --git a/mlxrunner/runner.go b/mlxrunner/runner.go
index 79b8aee0e..251cc97df 100644
--- a/mlxrunner/runner.go
+++ b/mlxrunner/runner.go
@@ -48,6 +48,8 @@ type Runner struct {
Requests chan Request
Sampler *sample.Sampler
cache *prefixCache
+ scoreCache *prefixCache
+ scoreHidden *cache.HiddenCache
contextLength int
mlxThread *mlxthread.Thread
// grammarEngine is the structured-output subsystem; nil when the grammar
@@ -151,6 +153,8 @@ func (r *Runner) loadModel(modelName string) (weights []*mlx.Array, err error) {
}
func (r *Runner) Close() {
+ r.scoreCache.close()
+ r.scoreCache, r.scoreHidden = nil, nil
if r.grammarEngine != nil {
r.grammarEngine.close()
r.grammarEngine = nil
diff --git a/mlxrunner/score.go b/mlxrunner/score.go
new file mode 100644
index 000000000..b6cdef4e1
--- /dev/null
+++ b/mlxrunner/score.go
@@ -0,0 +1,229 @@
+package mlxrunner
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "slices"
+
+ "github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/llm"
+ "github.com/ollama/ollama/mlx"
+ "github.com/ollama/ollama/mlx/mlxthread"
+ "github.com/ollama/ollama/mlxrunner/batch"
+ "github.com/ollama/ollama/mlxrunner/cache"
+ "github.com/ollama/ollama/mlxrunner/model"
+)
+
+type scoreRow struct {
+ tokens []int32
+ candidates []int32
+}
+
+// Models may project just the requested vocabulary rows at higher precision.
+type candidateUnembedder interface {
+ UnembedCandidates(hidden, candidates *mlx.Array) *mlx.Array
+}
+
+func (r *Runner) scoreHandler(w http.ResponseWriter, req *http.Request) {
+ var input llm.ScoreRequest
+ if err := json.NewDecoder(req.Body).Decode(&input); err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ result, err := mlxthread.Call(req.Context(), r.mlxThread, func() (llm.ScoreResponse, error) {
+ defer mlx.ClearCache()
+ return r.score(req.Context(), input)
+ })
+ if err != nil {
+ status := http.StatusInternalServerError
+ var statusErr api.StatusError
+ if errors.As(err, &statusErr) {
+ status = statusErr.StatusCode
+ }
+ http.Error(w, err.Error(), status)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(result)
+}
+
+func (r *Runner) score(ctx context.Context, input llm.ScoreRequest) (llm.ScoreResponse, error) {
+ if scorer, ok := r.Model.(model.CachedScorer); ok {
+ return scorer.Score(ctx, input, r.scoreHiddenRow)
+ }
+ if scorer, ok := r.Model.(llm.Scorer); ok {
+ return scorer.Score(ctx, input)
+ }
+ var result llm.ScoreResponse
+ badRequest := func(format string, args ...any) (llm.ScoreResponse, error) {
+ return result, api.StatusError{StatusCode: http.StatusBadRequest, ErrorMessage: fmt.Sprintf(format, args...)}
+ }
+ if len(input.Rows) < 1 || len(input.Rows) > 64 {
+ return badRequest("scoring requires 1–64 prompts")
+ }
+ if input.MaxTokens < 1 || input.MaxTokens > r.contextLength {
+ return badRequest("max_tokens must be between 1 and %d", r.contextLength)
+ }
+ rows := make([]scoreRow, len(input.Rows))
+ for i, row := range input.Rows {
+ if err := ctx.Err(); err != nil {
+ return result, err
+ }
+ tokens := r.Tokenizer.Encode(row.Prompt, false)
+ if len(tokens) == 0 || len(tokens) > input.MaxTokens {
+ return badRequest("prompt %d has %d tokens; expected 1–%d (input is never truncated)", i, len(tokens), input.MaxTokens)
+ }
+ if len(row.Candidates) < 1 || len(row.Candidates) > 26 {
+ return badRequest("prompt %d requires 1–26 candidates", i)
+ }
+ rows[i].tokens = tokens
+ result.InputTokens += len(tokens)
+ for _, candidate := range row.Candidates {
+ joined := r.Tokenizer.Encode(row.Prompt+candidate, false)
+ _, special := r.Tokenizer.GetSpecialToken(candidate)
+ if special || len(joined) != len(tokens)+1 || !slices.Equal(joined[:len(tokens)], tokens) {
+ return badRequest("candidate %q must append exactly one ordinary token to prompt %d", candidate, i)
+ }
+ id := joined[len(tokens)]
+ if id < 0 || int(id) >= r.Tokenizer.VocabSize() || slices.Contains(rows[i].candidates, id) {
+ return badRequest("prompt %d has invalid or duplicate candidate tokens", i)
+ }
+ rows[i].candidates = append(rows[i].candidates, id)
+ }
+ }
+ logits, cached, err := r.scoreRows(ctx, rows, scorePrefixLength(rows))
+ result.CachedTokens = &cached
+ result.Logits = logits
+ return result, err
+}
+
+// Shared boundaries retain both recurrent state and hidden outputs, including
+// the complete shorter row when one prompt is a prefix of another.
+func scorePrefixLength(rows []scoreRow) int {
+ if len(rows) < 2 {
+ return 0
+ }
+ n := len(rows[0].tokens)
+ for _, row := range rows[1:] {
+ n = min(n, len(row.tokens))
+ for i := 0; i < n; i++ {
+ if row.tokens[i] != rows[0].tokens[i] {
+ n = i
+ break
+ }
+ }
+ }
+ return max(0, n)
+}
+
+// Scoring has no draft writes. Keep its model caches separate from generation's
+// target/draft pair, using the same prefix matching, snapshots and eviction.
+func (r *Runner) scoringCache() *prefixCache {
+ if r.scoreCache == nil {
+ caches := r.Model.NewCaches()
+ r.scoreHidden = cache.NewHiddenCache()
+ caches = append(caches, r.scoreHidden)
+ r.scoreCache = newPrefixCache(caches)
+ }
+ return r.scoreCache
+}
+
+func (r *Runner) scoreRows(ctx context.Context, rows []scoreRow, prefix int) ([][]float32, int, error) {
+ result := make([][]float32, len(rows))
+ cached := 0
+ for i, row := range rows {
+ if err := ctx.Err(); err != nil {
+ return nil, 0, err
+ }
+ var err error
+ mlx.Scoped(func() {
+ session := r.scoringCache().beginScore(row.tokens, nil)
+ defer session.close()
+ session.schedulePrefillSnapshots(scoreSnapshots(len(row.tokens), prefix))
+ offset := len(row.tokens) - len(session.remaining)
+ cached += offset
+ err = r.scoreForward(ctx, session.remaining, offset, session.caches, nil)
+ if err != nil {
+ return
+ }
+ hidden := r.scoreHidden.State()[0]
+ last := hidden.Slice(mlx.Slice(), mlx.Slice(len(row.tokens)-1, len(row.tokens)), mlx.Slice())
+ ids := mlx.FromValues(row.candidates, len(row.candidates))
+ var selected *mlx.Array
+ if m, ok := r.Model.(candidateUnembedder); ok {
+ selected = m.UnembedCandidates(last, ids)
+ } else {
+ selected = r.Model.Unembed(last).Reshape(-1).TakeAxis(ids, 0)
+ }
+ result[i] = selected.AsType(mlx.DTypeFloat32).Floats()
+ })
+ if err != nil {
+ return nil, 0, err
+ }
+ }
+ return result, cached, ctx.Err()
+}
+
+func scoreSnapshots(length, shared int) []int {
+ offsets := []int{shared}
+ for n := prefillSnapshotInterval; n < length; n += prefillSnapshotInterval {
+ offsets = append(offsets, n)
+ }
+ return offsets
+}
+
+func (r *Runner) scoreHiddenRow(ctx context.Context, input *model.PreparedRequest, segments []model.Segment) (*mlx.Array, int, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, 0, err
+ }
+ items, err := bindItems(input, segments)
+ if err != nil {
+ return nil, 0, err
+ }
+ session := r.scoringCache().beginScore(input.Tokens, items)
+ defer session.close()
+ session.schedulePrefillSnapshots(scoreSnapshots(len(input.Tokens), 0))
+ media := r.openMedia(Request{Tokens: input.Tokens, MediaItems: items, Layout: input.Layout})
+ defer media.close()
+ offset := len(input.Tokens) - len(session.remaining)
+ media.free(offset)
+ if err := r.scoreForward(ctx, session.remaining, offset, session.caches, media); err != nil {
+ return nil, 0, err
+ }
+ return r.scoreHidden.State()[0].Slice(mlx.Slice(), mlx.Slice(), mlx.Slice()), offset, nil
+}
+
+func (r *Runner) scoreForward(ctx context.Context, tokens []int32, offset int, caches []cache.Cache, media *requestMedia) error {
+ for len(tokens) > 0 {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ n := media.extendChunk(offset, min(prefillChunkSize(), len(tokens)))
+ mlx.Scoped(func() {
+ mlx.Scoped(func() {
+ hidden, _ := r.Model.Forward(&batch.Batch{
+ InputIDs: mlx.FromValues(tokens[:n], 1, n),
+ SeqOffsets: []int32{int32(offset)},
+ SeqQueryLens: []int32{int32(n)},
+ Media: media.batchMedia(offset, n),
+ Layout: media.rowLayout(),
+ }, caches[:len(caches)-1])
+ r.scoreHidden.Append(hidden)
+ })
+ var state []*mlx.Array
+ for _, c := range caches {
+ if c != nil {
+ state = append(state, c.State()...)
+ }
+ }
+ mlx.Eval(state...)
+ })
+ tokens = tokens[n:]
+ offset += n
+ media.free(offset)
+ }
+ return ctx.Err()
+}
diff --git a/mlxrunner/score_hidden_test.go b/mlxrunner/score_hidden_test.go
new file mode 100644
index 000000000..338b78fed
--- /dev/null
+++ b/mlxrunner/score_hidden_test.go
@@ -0,0 +1,199 @@
+package mlxrunner
+
+import (
+ "context"
+ "errors"
+ "math"
+ "slices"
+ "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/clef"
+ "github.com/ollama/ollama/mlxrunner/model/qwen3_5"
+ "github.com/ollama/ollama/mlxrunner/nn"
+)
+
+// A small real backbone exercises both recurrent state and attention history.
+func prefillTestModel() *clef.Model {
+ seed := 0
+ weight := func(shape ...int) *mlx.Array {
+ n := 1
+ for _, d := range shape {
+ n *= d
+ }
+ values := make([]float32, n)
+ for i := range values {
+ seed++
+ values[i] = float32(math.Sin(float64(seed)*0.17)) * 0.1
+ }
+ return mlx.FromValues(values, shape...)
+ }
+ linear := func(out, in int) *nn.Linear { return nn.NewLinear(weight(out, in), nil) }
+ norm := func(n int) *nn.RMSNorm { return nn.NewRMSNorm(mlx.FromValues(slices.Repeat([]float32{1}, n), n), 1e-6) }
+ cfg := &qwen3_5.Config{
+ HiddenSize: 8, NumAttentionHeads: 1, NumKeyValueHeads: 1, HeadDim: 8,
+ RMSNormEps: 1e-6, RopeDim: 8, RopeTheta: 10000, Scale: 1 / float32(math.Sqrt(8)),
+ LinearNumKeyHeads: 1, LinearNumValueHeads: 1, LinearKeyHeadDim: 32,
+ LinearValueHeadDim: 32, LinearConvKernelDim: 4,
+ }
+ m := &qwen3_5.Model{Config: cfg, EmbedTokens: nn.NewEmbedding(weight(16, 8)), Norm: norm(8)}
+ for _, recurrent := range []bool{true, false} {
+ layer := &qwen3_5.Layer{
+ InputNorm: norm(8), PostAttentionNorm: norm(8), IsLinear: recurrent,
+ MLP: &qwen3_5.DenseMLP{GateProj: linear(16, 8), UpProj: linear(16, 8), DownProj: linear(8, 16)},
+ }
+ if recurrent {
+ layer.Linear = &qwen3_5.GatedDeltaNet{
+ InProjQKVZ: linear(128, 8), InProjBA: linear(2, 8), OutProj: linear(8, 32),
+ Conv1D: nn.NewConv1d(weight(96, 4, 1), nil, 1, 0, 1, 96),
+ NormWeight: mlx.FromValues(slices.Repeat([]float32{1}, 32), 32), DtBias: weight(1), AExp: mlx.FromValues([]float32{1}, 1),
+ }
+ } else {
+ layer.FullAttn = &qwen3_5.FullAttention{
+ QProj: linear(16, 8), KProj: linear(8, 8), VProj: linear(8, 8), OProj: linear(8, 8),
+ QNorm: norm(8), KNorm: norm(8),
+ }
+ }
+ m.Layers = append(m.Layers, layer)
+ }
+ return &clef.Model{Model: m}
+}
+
+func TestPrefillPreservesHiddenStates(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ mlx.Scoped(func() {
+ m := prefillTestModel()
+ for _, n := range []int{1, 2048, 2049, 4097} {
+ mlx.Scoped(func() {
+ tokens := make([]int32, n)
+ for i := range tokens {
+ tokens[i] = int32(i % 16)
+ }
+ ids := mlx.FromValues(tokens, 1, n)
+ want := mlx.ScopedEval(func() []*mlx.Array {
+ h, _ := m.Model.Forward(&batch.Batch{InputIDs: ids, SeqOffsets: []int32{0}, SeqQueryLens: []int32{int32(n)}}, nil)
+ return []*mlx.Array{h}
+ })[0]
+ r := &Runner{Model: m}
+ defer func() { r.scoreCache.close() }()
+ got, _, err := r.scoreHiddenRow(context.Background(), &model.PreparedRequest{Tokens: tokens}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(got.Dims(), want.Dims()) {
+ t.Fatalf("%d tokens: hidden shape %v, want %v", n, got.Dims(), want.Dims())
+ }
+ // Chunking changes the forward shapes and floating-point arithmetic.
+ values := want.Floats()
+ for i, v := range got.Floats() {
+ w := values[i]
+ if math.IsNaN(float64(v)) || math.Abs(float64(v-w)) > 1e-3*(1+math.Abs(float64(w))) {
+ t.Fatalf("%d tokens: hidden[%d] = %g, want %g", n, i, v, w)
+ }
+ }
+ })
+ }
+ })
+ })
+}
+
+// Cancel at an actual forward boundary without a timer or a production hook.
+type cancellingEmbedding struct {
+ nn.EmbeddingLayer
+ cancel context.CancelFunc
+ cancelAfter int
+ calls int
+}
+
+func (e *cancellingEmbedding) Forward(ids *mlx.Array) *mlx.Array {
+ e.calls++
+ if e.calls == e.cancelAfter {
+ e.cancel()
+ }
+ return e.EmbeddingLayer.Forward(ids)
+}
+
+func TestPrefillCancellation(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ mlx.Scoped(func() {
+ m := prefillTestModel()
+ embedding := &cancellingEmbedding{EmbeddingLayer: m.EmbedTokens}
+ m.EmbedTokens = embedding
+ prepared := &model.PreparedRequest{Tokens: make([]int32, 4097)}
+ r := &Runner{Model: m}
+ defer func() { r.scoreCache.close() }()
+ want, _, err := r.scoreHiddenRow(context.Background(), prepared, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ mlx.Eval(want)
+ for _, after := range []int{0, 1, 2, 3, 1, 2} {
+ r.scoreCache.close()
+ r.scoreCache, r.scoreHidden = nil, nil
+ ctx, cancel := context.WithCancel(context.Background())
+ embedding.calls, embedding.cancelAfter, embedding.cancel = 0, after, cancel
+ if after == 0 {
+ cancel()
+ }
+ got, _, err := r.scoreHiddenRow(ctx, prepared, nil)
+ cancel()
+ if !errors.Is(err, context.Canceled) || got != nil {
+ t.Fatalf("cancel after %d chunks: hidden=%v, err=%v", after, got, err)
+ }
+ if embedding.calls != after {
+ t.Fatalf("cancel after %d chunks ran %d forwards", after, embedding.calls)
+ }
+ embedding.cancelAfter = 0
+ mlx.Scoped(func() {
+ got, _, err := r.scoreHiddenRow(context.Background(), prepared, nil)
+ if err != nil {
+ t.Fatalf("request after cancellation: %v", err)
+ }
+ if !slices.Equal(got.Floats(), want.Floats()) {
+ t.Fatal("cancelled request changed the next request's hidden states")
+ }
+ })
+ }
+ })
+ })
+}
+
+// Reuse must preserve every earlier hidden state read by decision heads, not
+// just the final token used by ordinary vocabulary scoring.
+func TestScoreHiddenPrefixReuse(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ m := prefillTestModel()
+ r := &Runner{Model: m}
+ defer func() { r.scoreCache.close() }()
+ original := slices.Repeat([]int32{1, 2, 3, 4}, 520)
+ branch := slices.Clone(original)
+ branch[1024] = 5
+ rows := [][]int32{original, branch, original[:1024], branch, original}
+ for _, tokens := range rows {
+ cold := &Runner{Model: m}
+ want, _, err := cold.scoreHiddenRow(context.Background(), &model.PreparedRequest{Tokens: tokens}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantValues := want.Floats()
+ cold.scoreCache.close()
+ for repeat := range 2 {
+ got, cached, err := r.scoreHiddenRow(context.Background(), &model.PreparedRequest{Tokens: tokens}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if repeat == 1 && cached != len(tokens) {
+ t.Fatalf("exact hit reused %d/%d tokens", cached, len(tokens))
+ }
+ for i, v := range got.Floats() {
+ if math.IsNaN(float64(v)) || math.Abs(float64(v-wantValues[i])) > 1e-3*(1+math.Abs(float64(wantValues[i]))) {
+ t.Fatalf("cached hidden[%d]=%g, cold=%g", i, v, wantValues[i])
+ }
+ }
+ }
+ }
+ })
+}
diff --git a/mlxrunner/score_test.go b/mlxrunner/score_test.go
new file mode 100644
index 000000000..725a6ac68
--- /dev/null
+++ b/mlxrunner/score_test.go
@@ -0,0 +1,265 @@
+package mlxrunner
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/llm"
+ "github.com/ollama/ollama/mlx"
+ "github.com/ollama/ollama/mlx/mlxtest"
+ "github.com/ollama/ollama/mlx/mlxthread"
+ "github.com/ollama/ollama/mlxrunner/batch"
+ "github.com/ollama/ollama/mlxrunner/cache"
+)
+
+// This small stateful model uses real KV and recurrent caches. Its outputs
+// depend on both recurrent tensors, all KV values, and absolute positions, so a
+// missing restore or a branch that overwrites the prefix changes the answer.
+type scoringTestModel struct {
+ textOnlyModel
+ caches []cache.Cache
+ positions []int
+ lengths []int
+ projections int
+ cancel context.CancelFunc
+ cancelAfter int
+}
+
+func (m *scoringTestModel) NewCaches() []cache.Cache {
+ m.caches = []cache.Cache{cache.NewKVCache(), cache.NewRecurrentCache(1, 1, 1, 1, 1), nil}
+ return m.caches
+}
+
+func (m *scoringTestModel) Forward(b *batch.Batch, caches []cache.Cache) (*mlx.Array, *mlx.Array) {
+ n, offset := b.InputIDs.Dim(1), int(b.SeqOffsets[0])
+ m.positions = append(m.positions, offset)
+ m.lengths = append(m.lengths, n)
+ x := b.InputIDs.AsType(mlx.DTypeFloat32)
+ kv := caches[0].(*cache.KVCache).Update(b, x.Reshape(1, 1, n, 1), x.Multiply(x).Reshape(1, 1, n, 1))
+ rc := caches[1].(*cache.RecurrentCache)
+ history := rc.Get(b, mlx.DTypeFloat32)
+ positions := make([]float32, n)
+ for i := range positions {
+ positions[i] = float32(offset + i + 1)
+ }
+ convPrefix := history.ConvState().Reshape(1, 1).Add(x.Cumsum(1, false, true))
+ deltaPrefix := history.DeltaState().Reshape(1, 1).Add(x.Multiply(mlx.FromValues(positions, 1, n)).Cumsum(1, false, true))
+ valuePrefix := kv.V().Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(0, offset), mlx.Slice()).SumAxis(2, true).Reshape(1, 1).Add(x.Multiply(x).Cumsum(1, false, true))
+ var conv, delta *mlx.Array
+ var convStates, deltaStates []*mlx.Array
+ for _, end := range append(rc.SnapshotSplits(n), n) {
+ prefix := x.Slice(mlx.Slice(), mlx.Slice(0, end))
+ conv = history.ConvState().Add(prefix.SumAxis(1, true).Reshape(1, 1, 1))
+ delta = history.DeltaState().Add(prefix.Multiply(mlx.FromValues(positions[:end], 1, end)).SumAxis(1, true).Reshape(1, 1, 1, 1))
+ convStates = append(convStates, conv)
+ deltaStates = append(deltaStates, delta)
+ }
+ rc.Put(b, convStates, deltaStates)
+ hidden := mlx.Stack([]*mlx.Array{
+ valuePrefix, convPrefix, deltaPrefix, x,
+ mlx.FromValues(positions, 1, n),
+ mlx.AddScalar(mlx.Zeros(mlx.DTypeFloat32, 1, n), 1),
+ mlx.AddScalar(mlx.Zeros(mlx.DTypeFloat32, 1, n), 2),
+ mlx.AddScalar(mlx.Zeros(mlx.DTypeFloat32, 1, n), 3),
+ }, -1)
+ if m.cancel != nil && len(m.positions) == m.cancelAfter {
+ m.cancel()
+ }
+ return hidden, hidden
+}
+
+func (m *scoringTestModel) Unembed(hidden *mlx.Array) *mlx.Array {
+ if hidden.Dim(1) != 1 {
+ panic("scoring projected more than the final position")
+ }
+ m.projections++
+ return hidden
+}
+
+func TestScoreSharedPrefix(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ tokens [][]int32
+ }{
+ {"branch lengths and repeated restore", [][]int32{{1, 2, 3, 4}, {1, 2, 5}, {1, 2, 3, 6, 7}, {1, 2, 3, 4}}},
+ {"identical prompts", [][]int32{{1, 2, 3}, {1, 2, 3}}},
+ {"prompt is prefix", [][]int32{{1, 2}, {1, 2, 3, 4}}},
+ {"empty prefix", [][]int32{{1, 2}, {2, 1, 3}}},
+ {"one prompt", [][]int32{{1, 2, 3, 4}}},
+ {"one token", [][]int32{{1}, {1}, {2}}},
+ {"chunked prefix", [][]int32{append(slices.Repeat([]int32{1}, prefillChunkSize()+3), 2), append(slices.Repeat([]int32{1}, prefillChunkSize()+3), 3)}},
+ {"chunked suffix", [][]int32{append([]int32{1, 2}, slices.Repeat([]int32{3}, prefillChunkSize()+3)...), append([]int32{1, 2}, slices.Repeat([]int32{4}, prefillChunkSize()+3)...)}},
+ } {
+ mlxtest.RunSubtest(t, tt.name, func(t *mlxtest.T) {
+ m := &scoringTestModel{}
+ r := &Runner{Model: m}
+ rows := make([]scoreRow, len(tt.tokens))
+ for i, tokens := range tt.tokens {
+ rows[i] = scoreRow{tokens: tokens, candidates: []int32{2, 0, 1, 3, 4}}
+ }
+ independent := make([][]float32, len(rows))
+ for i, row := range rows {
+ cold := &Runner{Model: &scoringTestModel{}}
+ got, _, err := cold.scoreRows(context.Background(), []scoreRow{row}, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ independent[i] = got[0]
+ cold.scoreCache.close()
+ }
+ defer func() { r.scoreCache.close() }()
+ prefix := scorePrefixLength(rows)
+ for repeat := range 3 {
+ m.positions, m.lengths, m.projections = nil, nil, 0
+ got, cached, err := r.scoreRows(context.Background(), rows, prefix)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for i := range got {
+ if !slices.Equal(got[i], independent[i]) {
+ t.Fatalf("repeat %d row %d shared %v != independent %v", repeat, i, got[i], independent[i])
+ }
+ }
+ if m.projections != len(rows) {
+ t.Fatalf("got %d projections for %d rows", m.projections, len(rows))
+ }
+ if repeat > 0 {
+ total := 0
+ for _, n := range m.lengths {
+ total += n
+ }
+ input := 0
+ for _, row := range rows {
+ input += len(row.tokens)
+ }
+ if cached != input-total {
+ t.Fatalf("cached=%d, want %d", cached, input-total)
+ }
+ if total != 0 {
+ t.Fatalf("repeat forwarded %d tokens, want zero", total)
+ }
+ }
+ }
+ })
+ }
+}
+
+func TestScoreCancellation(t *testing.T) {
+ for _, cancelAfter := range []int{1, 2} {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ m := &scoringTestModel{cancel: cancel, cancelAfter: cancelAfter}
+ r := &Runner{Model: m}
+ defer func() { r.scoreCache.close() }()
+ rows := []scoreRow{{tokens: []int32{1, 2, 3}, candidates: []int32{0}}, {tokens: []int32{1, 2, 4}, candidates: []int32{0}}}
+ _, _, err := r.scoreRows(ctx, rows, 2)
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("got %v, want context cancellation", err)
+ }
+ if len(m.positions) != cancelAfter {
+ t.Fatal("cancellation did extra forwards")
+ }
+
+ m.cancel = nil
+ if _, _, err := r.scoreRows(context.Background(), rows, 2); err != nil {
+ t.Fatalf("request after cancellation: %v", err)
+ }
+ })
+ }
+}
+
+func TestScoreValidation(t *testing.T) {
+ tok := newTestTokenizer(t, []int32{7})
+ r := &Runner{Tokenizer: tok, contextLength: 10}
+ for _, input := range []llm.ScoreRequest{
+ {},
+ {MaxTokens: 10},
+ {MaxTokens: 10, Rows: make([]llm.ScoreRow, 65)},
+ {Rows: []llm.ScoreRow{{Prompt: "1", Candidates: []string{"2"}}}},
+ {MaxTokens: 11, Rows: []llm.ScoreRow{{Prompt: "1", Candidates: []string{"2"}}}},
+ {MaxTokens: 1, Rows: []llm.ScoreRow{{Prompt: "12", Candidates: []string{"3"}}}},
+ {MaxTokens: 10, Rows: []llm.ScoreRow{{Prompt: "", Candidates: []string{"1"}}}},
+ {MaxTokens: 10, Rows: []llm.ScoreRow{{Prompt: "1"}}},
+ {MaxTokens: 10, Rows: []llm.ScoreRow{{Prompt: "1", Candidates: slices.Repeat([]string{"2"}, 27)}}},
+ {MaxTokens: 10, Rows: []llm.ScoreRow{{Prompt: "1", Candidates: []string{"23"}}}},
+ {MaxTokens: 10, Rows: []llm.ScoreRow{{Prompt: "1", Candidates: []string{"2", "2"}}}},
+ } {
+ _, err := r.score(context.Background(), input)
+ var status api.StatusError
+ if !errors.As(err, &status) || status.StatusCode != 400 {
+ t.Fatalf("expected validation error before model access, got %v", err)
+ }
+ }
+}
+
+func TestScoreHandlerClearsScratchCache(t *testing.T) {
+ worker := mlxtest.Worker(t)
+ if err := worker.Do(context.Background(), func() error {
+ if !mlx.GPUIsAvailable() {
+ return errors.New("GPU unavailable")
+ }
+ mlx.ClearCache()
+ return nil
+ }); err != nil {
+ t.Skipf("MLX GPU not available: %v", err)
+ }
+ r := &Runner{Tokenizer: newTestTokenizer(t, []int32{7}), contextLength: 512, mlxThread: worker}
+ defer worker.Do(context.Background(), func() error { r.Close(); return nil })
+ for _, n := range []int{16, 128, 512, 16} {
+ for _, cancelled := range []bool{false, true} {
+ // Model prior requests leaving differently sized scratch buffers.
+ // These CPU-filled arrays are freed synchronously into MLX's cache.
+ const scratchBytes = 4 << 20
+ if err := worker.Do(context.Background(), func() error {
+ r.Close()
+ mlx.Scoped(func() { mlx.FromValues(make([]int32, scratchBytes/4), scratchBytes/4) })
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ m := &scoringTestModel{}
+ if cancelled {
+ m.cancel, m.cancelAfter = cancel, 1
+ }
+ r.Model = m
+ input, err := json.Marshal(llm.ScoreRequest{
+ MaxTokens: 512,
+ Rows: []llm.ScoreRow{{Prompt: strings.Repeat("1", n), Candidates: []string{"2"}}},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ req := httptest.NewRequestWithContext(ctx, http.MethodPost, "/score", strings.NewReader(string(input)))
+ response := httptest.NewRecorder()
+ r.scoreHandler(response, req)
+ cancel()
+ wantStatus := http.StatusOK
+ if cancelled {
+ wantStatus = http.StatusInternalServerError
+ }
+ if response.Code != wantStatus {
+ t.Fatalf("tokens=%d cancelled=%t: status %d: %s", n, cancelled, response.Code, response.Body)
+ }
+ memory, err := mlxthread.Call(context.Background(), worker, func() (int, error) {
+ return mlx.CacheMemory(), nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ // The injected scratch buffer must be cleared. Active allocations
+ // belong to live model caches or other tests on the shared worker.
+ if memory >= scratchBytes {
+ t.Fatalf("tokens=%d cancelled=%t: retained %d scratch bytes", n, cancelled, memory)
+ }
+ }
+ }
+}
diff --git a/mlxrunner/server.go b/mlxrunner/server.go
index 0470f599b..36385a849 100644
--- a/mlxrunner/server.go
+++ b/mlxrunner/server.go
@@ -87,6 +87,7 @@ 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{
Status: 0,
diff --git a/mlxrunner/tokenizer/tokenizer.go b/mlxrunner/tokenizer/tokenizer.go
index b4c8a1c0e..1acfcd7bd 100644
--- a/mlxrunner/tokenizer/tokenizer.go
+++ b/mlxrunner/tokenizer/tokenizer.go
@@ -41,6 +41,14 @@ type Tokenizer struct {
specialTokens map[string]int32 // Special tokens for direct lookup
sortedSpecialTokens []string // Special tokens sorted by length, longest first
typ TokenizerType // Algorithm type
+ normalizeNFC bool
+ metaspace *metaspace
+}
+
+type metaspace struct {
+ Replacement string `json:"replacement"`
+ PrependScheme string `json:"prepend_scheme"`
+ Split bool `json:"split"`
}
// Precomputed GPT-2 byte-level encoding table
diff --git a/mlxrunner/tokenizer/tokenizer_encode.go b/mlxrunner/tokenizer/tokenizer_encode.go
index 5ee658083..7659bca8e 100644
--- a/mlxrunner/tokenizer/tokenizer_encode.go
+++ b/mlxrunner/tokenizer/tokenizer_encode.go
@@ -7,6 +7,8 @@ import (
"sync"
"unicode"
"unicode/utf8"
+
+ "golang.org/x/text/unicode/norm"
)
const (
@@ -131,6 +133,17 @@ func (t *Tokenizer) forEachPartChunk(part string, fn func(encodeChunk)) {
}
if t.pretokenizer == nil {
+ if t.metaspace != nil && t.metaspace.Split {
+ start := 0
+ for i, r := range part {
+ if i > 0 && r == '▁' {
+ fn(encodeChunk{text: part[start:i]})
+ start = i
+ }
+ }
+ fn(encodeChunk{text: part[start:]})
+ return
+ }
fn(encodeChunk{text: part, isSpecial: false})
return
}
@@ -182,6 +195,21 @@ func (t *Tokenizer) appendEncodedChunk(ids []int32, c encodeChunk) []int32 {
func (t *Tokenizer) Encode(s string, addBOS bool) []int32 {
// First: split by special tokens
parts := t.splitBySpecialTokens(s)
+ for i, part := range parts {
+ if _, ok := t.specialTokens[part]; ok {
+ continue
+ }
+ if t.normalizeNFC {
+ part = norm.NFC.String(part)
+ }
+ if t.metaspace != nil {
+ part = strings.ReplaceAll(part, " ", "▁")
+ if (t.metaspace.PrependScheme == "always" || (t.metaspace.PrependScheme == "first" && i == 0)) && !strings.HasPrefix(part, "▁") {
+ part = "▁" + part
+ }
+ }
+ parts[i] = part
+ }
// Fast path: encode sequentially without materializing chunk slices.
if len(s) < encodeParallelMinInputBytes {
diff --git a/mlxrunner/tokenizer/tokenizer_load.go b/mlxrunner/tokenizer/tokenizer_load.go
index c0b6bc25e..d79fb0716 100644
--- a/mlxrunner/tokenizer/tokenizer_load.go
+++ b/mlxrunner/tokenizer/tokenizer_load.go
@@ -51,8 +51,11 @@ func loadFromTokenizerJSON(data []byte) (*Tokenizer, error) {
Merges json.RawMessage `json:"merges"` // Can be []string or [][]string (BPE only)
} `json:"model"`
PreTokenizer json.RawMessage `json:"pre_tokenizer"`
- Decoder json.RawMessage `json:"decoder"`
- AddedTokens []struct {
+ Normalizer struct {
+ Type string `json:"type"`
+ } `json:"normalizer"`
+ Decoder json.RawMessage `json:"decoder"`
+ AddedTokens []struct {
ID int32 `json:"id"`
Content string `json:"content"`
Special bool `json:"special"`
@@ -141,7 +144,24 @@ func loadFromTokenizerJSON(data []byte) (*Tokenizer, error) {
t.typ = TokenizerBPE
}
- // Parse and compile pretokenizer pattern (BPE only - SentencePiece doesn't use pretokenizer)
+ t.normalizeNFC = raw.Normalizer.Type == "NFC"
+ var pre struct {
+ Type string `json:"type"`
+ metaspace
+ }
+ if len(raw.PreTokenizer) > 0 {
+ if err := json.Unmarshal(raw.PreTokenizer, &pre); err != nil {
+ return nil, fmt.Errorf("failed to parse pre_tokenizer: %w", err)
+ }
+ }
+ if pre.Type == "Metaspace" {
+ if pre.Replacement != "▁" || (pre.PrependScheme != "always" && pre.PrependScheme != "first" && pre.PrependScheme != "never") {
+ return nil, fmt.Errorf("unsupported Metaspace pretokenizer: %s", raw.PreTokenizer)
+ }
+ t.metaspace = &pre.metaspace
+ t.typ = TokenizerSentencePiece
+ }
+ // Parse and compile pretokenizer pattern (BPE only).
if t.typ == TokenizerBPE {
pattern := extractPretokenizer(raw.PreTokenizer)
if pattern == "" {
diff --git a/mlxrunner/tokenizer/tokenizer_load_test.go b/mlxrunner/tokenizer/tokenizer_load_test.go
index c0d52e1a4..7f9299677 100644
--- a/mlxrunner/tokenizer/tokenizer_load_test.go
+++ b/mlxrunner/tokenizer/tokenizer_load_test.go
@@ -2,6 +2,7 @@ package tokenizer
import (
"encoding/json"
+ "slices"
"strings"
"testing"
)
@@ -104,3 +105,52 @@ func TestLoadPretokenizerOptionalPunctuationSpace(t *testing.T) {
})
}
}
+
+func TestMetaspace(t *testing.T) {
+ data := []byte(`{
+ "model": {"type":"BPE", "vocab":{"▁":0,"a":1,"b":2,"▁a":3,"▁b":4,"▁▁":5,"<s>":6},"merges":["▁ a","▁ b","▁ ▁"]},
+ "pre_tokenizer":{"type":"Metaspace","replacement":"▁","prepend_scheme":"always","split":true},
+ "decoder":{"type":"Replace","pattern":{"String":"▁"},"content":" "},
+ "added_tokens":[{"id":6,"content":"<s>","special":true}]
+ }`)
+ for _, scheme := range []string{"always", "first", "never"} {
+ t.Run(scheme, func(t *testing.T) {
+ tok, err := LoadFromBytes([]byte(strings.ReplaceAll(string(data), `"always"`, `"`+scheme+`"`)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, tc := range []struct {
+ text string
+ always, first, never []int32
+ }{
+ {"", nil, nil, nil},
+ {"a b", []int32{3, 4}, []int32{3, 4}, []int32{1, 4}},
+ {" a", []int32{0, 3}, []int32{0, 3}, []int32{0, 3}},
+ {"a b", []int32{3, 0, 4}, []int32{3, 0, 4}, []int32{1, 0, 4}},
+ {"a<s>b", []int32{3, 6, 4}, []int32{3, 6, 2}, []int32{1, 6, 2}},
+ {"<s>a", []int32{6, 3}, []int32{6, 1}, []int32{6, 1}},
+ } {
+ want := map[string][]int32{"always": tc.always, "first": tc.first, "never": tc.never}[scheme]
+ if got := tok.Encode(tc.text, false); !slices.Equal(got, want) {
+ t.Errorf("Encode(%q) = %v, want %v", tc.text, got, want)
+ }
+ }
+ })
+ }
+}
+
+func TestNFCNormalization(t *testing.T) {
+ tok, err := LoadFromBytes([]byte(`{
+ "model":{"type":"BPE","vocab":{"Ã":0,"©":1,"é":2,"[é]":3},"merges":["à ©"]},
+ "normalizer":{"type":"NFC"},
+ "added_tokens":[{"id":3,"content":"[é]","special":true}]
+ }`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, text := range []string{"é[e\u0301]", "e\u0301[e\u0301]"} {
+ if got := tok.Encode(text, false); !slices.Equal(got, []int32{2, 3}) {
+ t.Errorf("Encode(%q) = %v, want [2 3]", text, got)
+ }
+ }
+}
diff --git a/model/renderers/glimmer.go b/model/renderers/glimmer.go
index 36cf952bf..4c3de997e 100644
--- a/model/renderers/glimmer.go
+++ b/model/renderers/glimmer.go
@@ -119,7 +119,7 @@ func glimmerJSON(v any) (string, error) {
if err := encoder.Encode(v); err != nil {
return "", err
}
- return string(addJSONSpaces(bytes.TrimSuffix(buf.Bytes(), []byte("\n")))), nil
+ return string(AddJSONSpaces(bytes.TrimSuffix(buf.Bytes(), []byte("\n")))), nil
}
func writeGlimmerToolDefinitions(sb *strings.Builder, tools []api.Tool) error {
diff --git a/model/renderers/json.go b/model/renderers/json.go
index 8dc71673c..325ebb727 100644
--- a/model/renderers/json.go
+++ b/model/renderers/json.go
@@ -10,10 +10,12 @@ func marshalWithSpaces(v any) ([]byte, error) {
if err != nil {
return nil, err
}
- return addJSONSpaces(b), nil
+ return AddJSONSpaces(b), nil
}
-func addJSONSpaces(b []byte) []byte {
+// AddJSONSpaces adds Python-style separator spaces to compact JSON without
+// changing string values or escaping.
+func AddJSONSpaces(b []byte) []byte {
out := make([]byte, 0, len(b)+len(b)/8)
inStr, esc := false, false
for _, c := range b {
diff --git a/model/renderers/renderer.go b/model/renderers/renderer.go
index 45b73e031..f344b3291 100644
--- a/model/renderers/renderer.go
+++ b/model/renderers/renderer.go
@@ -68,7 +68,7 @@ func rendererForName(name string) Renderer {
case "qwen3-vl-thinking":
renderer := &Qwen3VLRenderer{isThinking: true, useImgTags: RenderImgTags}
return renderer
- case "qwen3.5":
+ case "qwen3.5", "tev1":
renderer := &Qwen35Renderer{isThinking: true, emitEmptyThinkOnNoThink: true, useImgTags: RenderImgTags}
return renderer
case "qwen3.8":
diff --git a/server/capabilities_test.go b/server/capabilities_test.go
index 8eb25c635..5541c6cad 100644
--- a/server/capabilities_test.go
+++ b/server/capabilities_test.go
@@ -9,6 +9,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/manifest"
"github.com/ollama/ollama/parser"
"github.com/ollama/ollama/types/model"
)
@@ -67,7 +68,7 @@ func TestCreateCapabilities(t *testing.T) {
if !slices.Contains(shown.Capabilities, model.CapabilityDecision) || !strings.Contains(shown.Modelfile, "CAPABILITY decision\n") {
t.Fatalf("show %s lost capability: %+v", name, shown)
}
- if want := []model.Capability{model.CapabilityDecision}; !slices.Equal(shown.Capabilities, want) || shown.Thinking != nil {
+ if want := []model.Capability{model.CapabilityDecision, model.CapabilityVision}; !slices.Equal(shown.Capabilities, want) || shown.Thinking != nil {
t.Fatalf("show %s capabilities = %v thinking = %v, want only %v", name, shown.Capabilities, shown.Thinking, want)
}
m, err := GetModel(name)
@@ -87,7 +88,7 @@ func TestCreateCapabilities(t *testing.T) {
t.Fatal(err)
}
for _, m := range listed {
- want := []model.Capability{model.CapabilityDecision}
+ want := []model.Capability{model.CapabilityDecision, model.CapabilityVision}
if m.Name == "base:latest" {
want = []model.Capability{model.CapabilityCompletion, model.CapabilityVision}
}
@@ -111,3 +112,62 @@ func TestCreateRejectsUnknownCapability(t *testing.T) {
}
}
}
+
+func TestDecisionPublicCapabilities(t *testing.T) {
+ for _, format := range []string{"gguf", "safetensors"} {
+ for _, declaredVision := range []bool{false, true} {
+ name := format + "-decision"
+ if declaredVision {
+ name += "-vision"
+ }
+ t.Run(name, func(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+ cfg := model.ConfigV2{ModelFormat: format, Parser: "qwen3.5", Capabilities: []string{"decision"}}
+ want := []model.Capability{model.CapabilityDecision}
+ if declaredVision {
+ cfg.Capabilities = append(cfg.Capabilities, "vision")
+ want = append(want, model.CapabilityVision)
+ }
+ _, digest := createBinFile(t, map[string]any{
+ "general.architecture": "qwen35", "qwen35.vision.block_count": uint32(1),
+ }, nil)
+ if format == "gguf" {
+ config, err := createConfigLayer(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := manifest.WriteManifest(model.ParseName(name), *config, []manifest.Layer{{
+ MediaType: "application/vnd.ollama.image.model", Digest: digest,
+ }}); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ createSafetensorsTestModel(t, name, cfg, []manifest.Layer{{
+ MediaType: "application/vnd.ollama.image.projector", Digest: digest,
+ }})
+ }
+ m, err := GetModel(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := m.CheckCapabilities(model.CapabilityDecision, model.CapabilityVision, model.CapabilityThinking); err != nil {
+ t.Fatalf("fixture must retain runtime capabilities: %v", err)
+ }
+ shown, err := GetModelInfo(api.ShowRequest{Model: name})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(shown.Capabilities, want) || shown.Thinking != nil {
+ t.Fatalf("show capabilities = %v thinking = %v, want %v and no thinking", shown.Capabilities, shown.Thinking, want)
+ }
+ listed, err := listModels(t.Context())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(listed) != 1 || !slices.Equal(listed[0].Capabilities, want) {
+ t.Fatalf("list models = %+v, want one model with capabilities %v", listed, want)
+ }
+ })
+ }
+ }
+}
diff --git a/server/create.go b/server/create.go
index fd538c903..2a054fe03 100644
--- a/server/create.go
+++ b/server/create.go
@@ -485,7 +485,7 @@ func stageSafetensorsSourceFiles(ctx context.Context, files map[string]string) (
func isSafetensorsMetadataFile(filePath string) bool {
switch path.Base(filePath) {
- case "config.json", "generation_config.json", "model.safetensors.index.json", "tokenizer_config.json", "chat_template.jinja":
+ case "config.json", "rl_agent_config.json", "joint_head_config.json", "generation_config.json", "model.safetensors.index.json", "tokenizer_config.json", "chat_template.jinja":
return true
default:
return false
diff --git a/server/create_test.go b/server/create_test.go
index 6cfaea94d..27d8e8068 100644
--- a/server/create_test.go
+++ b/server/create_test.go
@@ -72,15 +72,19 @@ func TestStageSafetensorsSourceFilesRejectsOversizedMetadata(t *testing.T) {
t.Fatal(err)
}
- dir, cleanup, err := stageSafetensorsSourceFiles(t.Context(), map[string]string{"config.json": digest})
- if cleanup != nil {
- cleanup()
- }
- if err == nil {
- t.Fatalf("stageSafetensorsSourceFiles() = %q, nil, want size error", dir)
- }
- if !strings.Contains(err.Error(), "exceeds maximum") {
- t.Fatalf("stageSafetensorsSourceFiles() error = %v, want size error", err)
+ for _, name := range []string{"config.json", "joint_head_config.json"} {
+ t.Run(name, func(t *testing.T) {
+ dir, cleanup, err := stageSafetensorsSourceFiles(t.Context(), map[string]string{name: digest})
+ if cleanup != nil {
+ cleanup()
+ }
+ if err == nil {
+ t.Fatalf("stageSafetensorsSourceFiles() = %q, nil, want size error", dir)
+ }
+ if !strings.Contains(err.Error(), "exceeds maximum") {
+ t.Fatalf("stageSafetensorsSourceFiles() error = %v, want size error", err)
+ }
+ })
}
}
diff --git a/server/images.go b/server/images.go
index 25c4a8538..ffa755fc5 100644
--- a/server/images.go
+++ b/server/images.go
@@ -164,11 +164,16 @@ func (m *Model) Capabilities() []model.Capability {
return capabilities
}
-// publicCapabilities hides a decision model's other capabilities from show and
-// list so clients don't offer it for general chat. Serving still uses Capabilities.
-func publicCapabilities(capabilities []model.Capability) []model.Capability {
+// publicCapabilities limits decision models to decision and explicitly declared
+// vision support. Serving still uses Capabilities.
+func (m *Model) publicCapabilities() []model.Capability {
+ capabilities := m.Capabilities()
if slices.Contains(capabilities, model.CapabilityDecision) {
- return []model.Capability{model.CapabilityDecision}
+ public := []model.Capability{model.CapabilityDecision}
+ if slices.Contains(m.Config.Capabilities, "vision") && slices.Contains(capabilities, model.CapabilityVision) {
+ public = append(public, model.CapabilityVision)
+ }
+ return public
}
return capabilities
}
diff --git a/server/model_list.go b/server/model_list.go
index 9097204b0..9976b4b66 100644
--- a/server/model_list.go
+++ b/server/model_list.go
@@ -200,7 +200,7 @@ func describeModelFromManifest(name model.Name, mf *manifest.Manifest, runner st
return summary, nil
}
summary.Details.ParentModel = m.ParentModel
- summary.Capabilities = publicCapabilities(m.Capabilities())
+ summary.Capabilities = m.publicCapabilities()
if m.ModelPath != "" && m.isGGUF() {
if summary.Details.ContextLength == 0 {
diff --git a/server/routes.go b/server/routes.go
index e42236847..e7a70afe9 100644
--- a/server/routes.go
+++ b/server/routes.go
@@ -909,8 +909,17 @@ func (s *Server) SystemOneHandler(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
- if len(req.Images) == 0 && len(body) > 64<<10 {
- c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "request body must not exceed 64 KiB without images"})
+ textOnly := req
+ textOnly.Images = nil
+ var text bytes.Buffer
+ enc := json.NewEncoder(&text)
+ enc.SetEscapeHTML(false)
+ if err := enc.Encode(textOnly); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ }
+ if len(bytes.TrimSpace(text.Bytes())) > 64<<10 {
+ c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "text and schema must not exceed 64 KiB"})
return
}
ref, err := parseAndValidateModelRef(req.Model)
@@ -936,11 +945,11 @@ func (s *Server) SystemOneHandler(c *gin.Context) {
handleScheduleError(c, req.Model, err)
return
}
- if !m.isGGUF() {
- c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("model %q is not supported by System One; use a local GGUF model", req.Model)})
- return
+ encoding := m.metadata.String("decision.type")
+ if encoding == "" && (m.Config.Renderer == "tev1" || m.Config.Renderer == "clef" || m.Config.Renderer == "strands") {
+ encoding = m.Config.Renderer
}
- compiled, err := decision.CompileWithEncoder(req, m.metadata.String("decision.type"))
+ compiled, err := decision.Compile(req, encoding)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
@@ -1680,8 +1689,9 @@ func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
Runner: m.Runner,
}
- // For safetensors LLM models, populate details from config.json.
- if m.Config.ModelFormat == "safetensors" && slices.Contains(m.Config.Capabilities, "completion") {
+ // For safetensors completion and decision models, populate details from config.json.
+ isSafetensorsLLM := m.IsMLX() && (slices.Contains(m.Config.Capabilities, "completion") || slices.Contains(m.Config.Capabilities, "decision"))
+ if isSafetensorsLLM {
if info, err := getSafetensorsLLMInfoForRunner(name, req.Runner); err == nil {
if arch, ok := info["general.architecture"].(string); ok && arch != "" {
modelDetails.Family = arch
@@ -1718,7 +1728,7 @@ func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
Template: m.Template.String(),
Details: modelDetails,
Messages: msgs,
- Capabilities: publicCapabilities(m.Capabilities()),
+ Capabilities: m.publicCapabilities(),
ModifiedAt: mf.FileInfo().ModTime(),
Requires: m.Config.Requires,
// Several integrations crash on a nil/omitempty+empty ModelInfo, so by
@@ -1800,8 +1810,8 @@ func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
return resp, nil
}
- // For safetensors LLM models, populate ModelInfo from config.json.
- if m.Config.ModelFormat == "safetensors" && slices.Contains(m.Config.Capabilities, "completion") {
+ // For safetensors completion and decision models, populate ModelInfo from config.json.
+ if isSafetensorsLLM {
if info, err := getSafetensorsLLMInfoForRunner(name, req.Runner); err == nil {
resp.ModelInfo = info
}
diff --git a/server/routes_test.go b/server/routes_test.go
index d9c7219aa..32b480619 100644
--- a/server/routes_test.go
+++ b/server/routes_test.go
@@ -824,36 +824,36 @@ func TestGetModelInfoRepairsUnknownGGUFFileType(t *testing.T) {
func TestGetModelInfo_SafetensorsModelfileUsesShortName(t *testing.T) {
t.Setenv("OLLAMA_MODELS", t.TempDir())
+ for _, capability := range []string{"completion", "decision", "image"} {
+ t.Run(capability, func(t *testing.T) {
+ config, err := manifest.NewLayer(strings.NewReader(`{"model_type":"test","max_position_embeddings":512}`), manifest.MediaTypeImageJSON)
+ if err != nil {
+ t.Fatal(err)
+ }
+ config.Name = "config.json"
+ name := "show-safetensors-" + capability
+ createSafetensorsTestModel(t, name, model.ConfigV2{
+ ModelFormat: "safetensors", Capabilities: []string{capability},
+ }, []manifest.Layer{config})
- cfgData, err := json.Marshal(model.ConfigV2{
- ModelFormat: "safetensors",
- Capabilities: []string{"completion"},
- })
- if err != nil {
- t.Fatalf("failed to marshal config: %v", err)
- }
-
- configLayer, err := manifest.NewLayer(bytes.NewReader(cfgData), "application/vnd.docker.container.image.v1+json")
- if err != nil {
- t.Fatalf("failed to create config layer: %v", err)
- }
-
- name := model.ParseName("show-safetensors")
- if err := manifest.WriteManifest(name, configLayer, nil); err != nil {
- t.Fatalf("failed to write manifest: %v", err)
- }
-
- resp, err := GetModelInfo(api.ShowRequest{Model: name.String()})
- if err != nil {
- t.Fatalf("GetModelInfo() error = %v", err)
- }
-
- if !strings.Contains(resp.Modelfile, "FROM show-safetensors:latest\n") {
- t.Fatalf("Modelfile = %q, want FROM show-safetensors:latest", resp.Modelfile)
- }
-
- if strings.Contains(resp.Modelfile, "# To build a new Modelfile based on this, replace FROM with:") {
- t.Fatalf("Modelfile should not include replacement hint: %q", resp.Modelfile)
+ resp, err := GetModelInfo(api.ShowRequest{Model: name})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if want := "FROM " + name + ":latest\n"; !strings.Contains(resp.Modelfile, want) {
+ t.Fatalf("Modelfile = %q, want %q", resp.Modelfile, want)
+ }
+ if strings.Contains(resp.Modelfile, "# To build a new Modelfile based on this, replace FROM with:") {
+ t.Fatalf("Modelfile should not include replacement hint: %q", resp.Modelfile)
+ }
+ if capability == "image" {
+ if len(resp.ModelInfo) != 0 {
+ t.Fatalf("image model acquired LLM metadata: %v", resp.ModelInfo)
+ }
+ } else if resp.ModelInfo["test.context_length"] != 512 {
+ t.Fatalf("context_length = %v, want 512", resp.ModelInfo["test.context_length"])
+ }
+ })
}
}
diff --git a/server/show_safetensors.go b/server/show_safetensors.go
index e5ff10a1a..66909aee8 100644
--- a/server/show_safetensors.go
+++ b/server/show_safetensors.go
@@ -81,13 +81,17 @@ func getSafetensorsLLMInfoForRunner(name model.Name, runner string) (map[string]
func buildModelInfo(config modelConfig, totalTensorBytes, tensorCount int64) map[string]any {
// Determine architecture
arch := config.ModelType
- if arch == "" && len(config.Architectures) > 0 {
- // Convert HuggingFace architecture name to Ollama format
- // e.g., "Gemma3ForCausalLM" -> "gemma3"
+ if len(config.Architectures) > 0 {
hfArch := config.Architectures[0]
- arch = strings.ToLower(hfArch)
- arch = strings.TrimSuffix(arch, "forcausallm")
- arch = strings.TrimSuffix(arch, "forconditionalgeneration")
+ if decisionArch, ok := strings.CutSuffix(hfArch, "ForDecision"); ok {
+ // model_type can describe only the backbone, omitting the decision head.
+ arch = strings.ToLower(decisionArch)
+ } else if arch == "" {
+ // Convert HuggingFace architecture names, e.g. "Gemma3ForCausalLM" to "gemma3".
+ arch = strings.ToLower(hfArch)
+ arch = strings.TrimSuffix(arch, "forcausallm")
+ arch = strings.TrimSuffix(arch, "forconditionalgeneration")
+ }
}
// Use text_config values if they exist (for multimodal models)
diff --git a/server/show_safetensors_test.go b/server/show_safetensors_test.go
index ffa4981a0..6f1354bc0 100644
--- a/server/show_safetensors_test.go
+++ b/server/show_safetensors_test.go
@@ -197,6 +197,35 @@ func TestBuildModelInfo_ArchitectureConversion(t *testing.T) {
modelType: "custom",
wantArch: "custom",
},
+ {
+ name: "Strands decision architecture over backbone",
+ architectures: []string{"StrandsDeciderForDecision"},
+ modelType: "qwen3_5",
+ wantArch: "strandsdecider",
+ },
+ {
+ name: "Clef decision architecture over backbone",
+ architectures: []string{"ClefForDecision"},
+ modelType: "qwen3_5",
+ wantArch: "clef",
+ },
+ {
+ name: "Laya decision architecture",
+ architectures: []string{"LayaForDecision"},
+ modelType: "laya",
+ wantArch: "laya",
+ },
+ {
+ name: "decision architecture without model_type",
+ architectures: []string{"StrandsDeciderForDecision"},
+ wantArch: "strandsdecider",
+ },
+ {
+ name: "Qwen fine-tune retains backbone architecture",
+ architectures: []string{"Qwen3_5ForConditionalGeneration"},
+ modelType: "qwen3_5",
+ wantArch: "qwen3_5",
+ },
{
name: "empty architectures with model_type",
architectures: nil,
@@ -208,14 +237,22 @@ func TestBuildModelInfo_ArchitectureConversion(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
config := modelConfig{
- Architectures: tt.architectures,
- ModelType: tt.modelType,
+ Architectures: tt.architectures,
+ ModelType: tt.modelType,
+ MaxPositionEmbeddings: 4096,
+ HiddenSize: 2048,
+ NumHiddenLayers: 24,
}
info := buildModelInfo(config, 0, 0)
if arch, ok := info["general.architecture"].(string); !ok || arch != tt.wantArch {
t.Errorf("architecture = %v, want %v", info["general.architecture"], tt.wantArch)
}
+ for key, want := range map[string]int{"context_length": 4096, "embedding_length": 2048, "block_count": 24} {
+ if got := info[tt.wantArch+"."+key]; got != want {
+ t.Errorf("%s.%s = %v, want %d", tt.wantArch, key, got, want)
+ }
+ }
})
}
}
diff --git a/server/systemone_test.go b/server/systemone_test.go
index 3d4b041fc..d4f8f855e 100644
--- a/server/systemone_test.go
+++ b/server/systemone_test.go
@@ -1,6 +1,7 @@
package server
import (
+ "bytes"
"context"
"encoding/base64"
"encoding/json"
@@ -38,11 +39,62 @@ func (r *systemOneTestRunner) Score(ctx context.Context, input llm.ScoreRequest)
return llm.ScoreResponse{Logits: [][]float32{{0, 2}}, InputTokens: 123, OutputTokens: 2}, r.err
}
+func TestDecisionModelRejectsCompletion(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+ // No scheduler: capability rejection must happen before a runner is loaded.
+ s := &Server{}
+ for _, cfg := range []struct {
+ name string
+ capabilities []string
+ }{
+ {"decision-only", []string{"decision"}},
+ {"decision-vision", []string{"decision", "vision"}},
+ } {
+ createSafetensorsTestModel(t, cfg.name, model.ConfigV2{
+ ModelFormat: "safetensors", Capabilities: cfg.capabilities,
+ }, nil)
+ for _, tc := range []struct {
+ name string
+ handler gin.HandlerFunc
+ body any
+ }{
+ {"generate", s.GenerateHandler, api.GenerateRequest{Model: cfg.name, Prompt: "hello"}},
+ {"chat", s.ChatHandler, api.ChatRequest{Model: cfg.name, Messages: []api.Message{{Role: "user", Content: "hello"}}}},
+ } {
+ t.Run(cfg.name+"/"+tc.name, func(t *testing.T) {
+ w := createRequest(t, tc.handler, tc.body)
+ want := fmt.Sprintf("does not support %s", tc.name)
+ if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), want) {
+ t.Fatalf("status=%d body=%s, want 400 containing %q", w.Code, w.Body, want)
+ }
+ })
+ }
+ }
+}
+
func TestSystemOneHandler(t *testing.T) {
gin.SetMode(gin.TestMode)
t.Setenv("OLLAMA_MODELS", t.TempDir())
config := model.ConfigV2{ModelFormat: "safetensors", Renderer: "qwen3.5", Capabilities: []string{"completion", "decision"}}
- createSafetensorsTestModel(t, "safetensors-decision", config, nil)
+ params, err := manifest.NewLayer(strings.NewReader(`{"num_ctx":8192}`), "application/vnd.ollama.image.params")
+ if err != nil {
+ t.Fatal(err)
+ }
+ createSafetensorsTestModel(t, "safetensors-decision", config, []manifest.Layer{params})
+ config.Capabilities = []string{"decision"}
+ createSafetensorsTestModel(t, "safetensors-decision-only", config, []manifest.Layer{params})
+ config.Renderer = "tev1"
+ createSafetensorsTestModel(t, "safetensors-tev1", config, []manifest.Layer{params})
+ config.Renderer = "strands"
+ createSafetensorsTestModel(t, "safetensors-strands", config, []manifest.Layer{params})
+ config.Renderer = "clef"
+ createSafetensorsTestModel(t, "safetensors-clef-text", config, []manifest.Layer{params})
+ config.Capabilities = []string{"decision", "vision"}
+ createSafetensorsTestModel(t, "safetensors-clef", config, []manifest.Layer{params})
+ config.Renderer = "qwen3.5"
+ config.Capabilities = []string{"completion"}
+ createSafetensorsTestModel(t, "safetensors-undeclared", config, nil)
for _, modelConfig := range []struct {
name, architecture, renderer, system, template string
contextLength int
@@ -50,6 +102,7 @@ func TestSystemOneHandler(t *testing.T) {
}{
{"renamed-clef", "qwen35", "", "Ignored for the joint head", "", 1024, false},
{"decision-test", "qwen35", "qwen3.5", "Model-specific scoring instructions.", "", 1024, false},
+ {"gguf-tev1", "qwen35", "tev1", "Model-specific scoring instructions.", "", 1024, false},
{"gguf-decision", "qwen35", "", "Native model scoring instructions.", "", 4096, false},
{"go-template", "qwen35", "", "Model-specific scoring instructions.", "custom:{{ range .Messages }}{{ .Role }}:{{ .Content }}\n{{ end }}answer:", 1024, false},
{"no-system", "qwen35", "qwen3.5", "", "", 1024, false},
@@ -102,8 +155,11 @@ func TestSystemOneHandler(t *testing.T) {
}
const prefix = `{"model":"decision-test","state":"`
- const suffix = `","questions":{"refund":{"type":"noul","instructions":"Refund requested?"}}}`
+ const suffix = `","questions":{"refund":{"type":"noul","instructions":"Refund requested?","criteria":{}}}}`
stateLimit := (64 << 10) - len(prefix) - len(suffix)
+ image := base64.StdEncoding.EncodeToString(bytes.Repeat([]byte("image"), 16<<10))
+ const imagePrefix = `{"model":"safetensors-clef","state":"x","questions":{"refund":{"type":"noul","instructions":"q"}},"images":["`
+ largeText := strings.Replace(prefix+strings.Repeat("x", stateLimit+1)+suffix, "decision-test", "safetensors-clef", 1)
for _, tt := range []struct {
name string
body string
@@ -135,10 +191,25 @@ func TestSystemOneHandler(t *testing.T) {
{"blank model", `{"model":" ","state":"x","questions":{"x":{"type":"noul","instructions":"q"}}}`, nil, 400, 0, false},
{"missing model", `{"model":"missing","state":"x","questions":{"x":{"type":"noul","instructions":"q"}}}`, nil, 404, 0, false},
{"cloud", `{"model":"decision:cloud","state":"x","questions":{"x":{"type":"noul","instructions":"q"}}}`, nil, 400, 0, false},
- {"safetensors unsupported", `{"model":"safetensors-decision","state":"x","questions":{"x":{"type":"noul","instructions":"q"}}}`, nil, 400, 0, false},
+ {"safetensors success", `{"model":"safetensors-decision","state":"x","questions":{"refund":{"type":"noul","instructions":"q"}}}`, nil, 200, 1, false},
+ {"safetensors decision only", `{"model":"safetensors-decision-only","state":"x","questions":{"refund":{"type":"noul","instructions":"q"}}}`, nil, 200, 1, false},
+ {"Strands pointer head", `{"model":"safetensors-strands","state":"x","questions":{"refund":{"type":"noul","instructions":"q"}}}`, nil, 200, 1, false},
+ {"Clef decision only text", `{"model":"safetensors-clef-text","state":"x","questions":{"refund":{"type":"noul","instructions":"q"}}}`, nil, 200, 1, false},
+ {"Clef decision only image", strings.Replace(imagePrefix, "safetensors-clef", "safetensors-clef-text", 1) + `aW1hZ2U="]}`, nil, 400, 0, false},
+ {"Clef image above text limit", imagePrefix + image + `"]}`, nil, 200, 1, false},
+ {"other model image", `{"model":"decision-test","state":"x","questions":{"refund":{"type":"noul","instructions":"q"}},"images":["aW1hZ2U="]}`, nil, 400, 0, false},
+ {"invalid image base64", imagePrefix + `!not-base64"]}`, nil, 400, 0, false},
+ {"image data URL", imagePrefix + `data:image/png;base64,aW1hZ2U="]}`, nil, 400, 0, false},
+ {"Tev1 safetensors", `{"model":"safetensors-tev1","state":"x","questions":{"refund":{"type":"noul","instructions":"q"}}}`, nil, 200, 1, false},
+ {"Tev1 GGUF", `{"model":"gguf-tev1","state":"x","questions":{"refund":{"type":"noul","instructions":"q"}}}`, nil, 200, 1, false},
+ {"Tev1 too many candidates", `{"model":"safetensors-tev1","state":"x","questions":{"refund":{"type":"score","instructions":"q","criteria":["x"` + strings.Repeat(`,"x"`, 24) + `]}}}`, nil, 400, 0, false},
+ {"Tev1 empty description", `{"model":"gguf-tev1","state":"x","questions":{"refund":{"type":"choice","instructions":"q","criteria":{"a":"","b":"B"}}}}`, nil, 400, 0, false},
+ {"safetensors missing capability", `{"model":"safetensors-undeclared","state":"x","questions":{"x":{"type":"noul","instructions":"q"}}}`, nil, 400, 0, false},
{"bad JSON", `{`, nil, 400, 0, false},
- {"at body limit", prefix + strings.Repeat("x", stateLimit) + suffix, nil, 200, 1, false},
- {"over body limit", prefix + strings.Repeat("x", stateLimit+1) + suffix, nil, 413, 0, false},
+ {"at text limit", prefix + strings.Repeat("<", stateLimit) + suffix, nil, 200, 1, false},
+ {"over text limit", prefix + strings.Repeat("x", stateLimit+1) + suffix, nil, 413, 0, false},
+ {"image does not relax text limit", strings.TrimSuffix(largeText, "}") + `,"images":["aW1hZ2U="]}`, nil, 413, 0, false},
+ {"over transport limit", imagePrefix + strings.Repeat("A", 32<<20) + `"]}`, nil, 413, 0, false},
} {
t.Run(tt.name, func(t *testing.T) {
runner := &systemOneTestRunner{err: tt.err}
@@ -176,6 +247,9 @@ func TestSystemOneHandler(t *testing.T) {
if tt.calls == 0 && tt.err == nil && ref.model != nil {
t.Fatal("loaded a runner for a rejected request")
}
+ if tt.name == "Clef decision only image" && !strings.Contains(w.Body.String(), "vision") {
+ t.Fatalf("expected missing vision capability: %s", w.Body)
+ }
if tt.calls > 0 {
want := time.Hour
if tt.expire {
@@ -192,6 +266,18 @@ func TestSystemOneHandler(t *testing.T) {
t.Fatal("images were not passed to scoring")
}
if tt.status == 200 {
+ var sent decision.Request
+ if err := json.Unmarshal([]byte(tt.body), &sent); err != nil {
+ t.Fatal(err)
+ }
+ if len(runner.request.Images) != len(sent.Images) {
+ t.Fatalf("runner received %d images, want %d", len(runner.request.Images), len(sent.Images))
+ }
+ for i := range sent.Images {
+ if !bytes.Equal(runner.request.Images[i], sent.Images[i]) {
+ t.Fatalf("image %d changed during request compilation", i)
+ }
+ }
var response struct {
Answers map[string]struct {
Noul float64 `json:"noul"`
@@ -208,15 +294,32 @@ func TestSystemOneHandler(t *testing.T) {
if response.Answers["refund"].Noul < 0.88 || response.Usage.InputTokens != 123 || response.Usage.OutputTokens != outputTokens {
t.Fatalf("incorrect scoring response: %s", w.Body)
}
- if len(runner.request.Fields) > 0 {
- if len(runner.request.Rows) != 0 || len(runner.request.Fields) != 1 || runner.request.MaxTokens != 2048 {
- t.Fatal("invalid joint scoring request")
- }
- return
+ if ref.model.Config.Renderer == "strands" && (len(runner.request.PointerRows) != 1 || len(runner.request.Rows) != 0 || !strings.HasSuffix(runner.request.PointerRows[0].Prompt, "<answer>")) {
+ t.Fatalf("Strands did not receive pointer inputs: %+v", runner.request)
+ }
+ var prompt string
+ if len(runner.request.Rows) > 0 {
+ prompt = runner.request.Rows[0].Prompt
+ }
+ if ref.model.Config.Renderer == "tev1" && (!strings.Contains(prompt, `"state": "x", "question": "q", "options":`) || strings.Contains(prompt, "Requested field:")) {
+ t.Fatalf("Tev1 did not receive its per-question prompt: %q", prompt)
}
- prompt := runner.request.Rows[0].Prompt
wantContext := 1024
- if ref.model.HasGoTemplate {
+ if !ref.model.isGGUF() {
+ wantContext = 8192
+ }
+ if len(runner.request.Fields) > 0 {
+ if len(runner.request.Rows) != 0 || len(runner.request.Fields) != 1 || len(runner.request.Segments) < 3 {
+ t.Fatal("Clef scoring must preserve the segmented schema")
+ }
+ if ref.model.isGGUF() {
+ wantContext = 2048
+ }
+ } else if len(runner.request.PointerRows) > 0 {
+ if len(runner.request.Rows) != 0 {
+ t.Fatal("pointer head must bypass chat templates")
+ }
+ } else if ref.model.HasGoTemplate {
if !strings.HasPrefix(prompt, "custom:system:Model-specific scoring instructions.\nuser:") || !strings.HasSuffix(prompt, "answer:") {
t.Fatalf("scorer did not receive the Modelfile template output: %q", prompt)
}