Skip to content

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

Add Kev decision scoring to MLX (#18976)

Daniel Hiltgen665f9e074c99
diff --git a/create/create.go b/create/create.go
index 128b3b1f7..7cf2efc2f 100644
--- a/create/create.go
+++ b/create/create.go
@@ -423,6 +423,7 @@ func (cfg sourceModelConfig) HFFP8WeightBlockSize() (rows, cols int32, ok bool)
type tensorImportTransformFactory func(rawConfig json.RawMessage) (quantizePolicy, error)
var tensorImportTransformRegistry = map[string]tensorImportTransformFactory{
+ "KevForDecision": newQwen35DecisionImportTransform,
"StrandsDeciderForDecision": newQwen35DecisionImportTransform,
"ClefForDecision": newQwen35DecisionImportTransform,
"Qwen3_5ForCausalLM": newQwen35ImportTransform,
diff --git a/create/kev.go b/create/kev.go
new file mode 100644
index 000000000..8cbc4f0dd
--- /dev/null
+++ b/create/kev.go
@@ -0,0 +1,30 @@
+package create
+
+import (
+ "fmt"
+ "strings"
+)
+
+func kevFileType(inv Inventory) (string, error) {
+ // The pointer head is FP32; the text embedding records the backbone dtype.
+ var embedding string
+ for _, name := range sortedTensorNames(inv) {
+ if name != "embed_tokens.weight" && !strings.HasSuffix(name, ".embed_tokens.weight") {
+ continue
+ }
+ if embedding != "" {
+ return "", fmt.Errorf("Kev source has multiple text embedding tensors: %q and %q", embedding, name)
+ }
+ embedding = name
+ }
+ if embedding == "" {
+ return "", fmt.Errorf("Kev source has no text embedding tensor")
+ }
+ dtype := strings.ToUpper(inv.Tensors[embedding].Dtype)
+ switch dtype {
+ case "BF16", "F16", "F32":
+ return dtype, nil
+ default:
+ return "", fmt.Errorf("unsupported Kev text embedding dtype %q in %s", dtype, embedding)
+ }
+}
diff --git a/create/kev_test.go b/create/kev_test.go
new file mode 100644
index 000000000..934a80f2a
--- /dev/null
+++ b/create/kev_test.go
@@ -0,0 +1,88 @@
+package create
+
+import (
+ "context"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ st "github.com/ollama/ollama/fs/safetensors"
+ "github.com/ollama/ollama/types/model"
+)
+
+func TestKevPipelineFileType(t *testing.T) {
+ for _, tc := range []struct {
+ name, config, tensor, dtype, want string
+ }{
+ {"prefixed BF16", `{"architectures":["KevForDecision"]}`, "model.embed_tokens.weight", "BF16", "BF16"},
+ {"bare BF16", `{"architectures":["KevForDecision"]}`, "embed_tokens.weight", "BF16", "BF16"},
+ {"F16", `{"architectures":["KevForDecision"]}`, "embed_tokens.weight", "F16", "F16"},
+ {"F32", `{"architectures":["KevForDecision"]}`, "embed_tokens.weight", "F32", "F32"},
+ {"config disagrees with weights", `{"architectures":["KevForDecision"],"dtype":"float16"}`, "embed_tokens.weight", "BF16", "BF16"},
+ {"missing text embedding", `{"architectures":["KevForDecision"]}`, "model.norm.weight", "BF16", ""},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ dir := t.TempDir()
+ writeConfigJSON(t, dir, tc.config)
+ bytesPerElement := 2
+ if tc.dtype == "F32" {
+ bytesPerElement = 4
+ }
+ createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{
+ st.NewTensorDataFromBytes(tc.tensor, tc.dtype, []int32{8, 8}, make([]byte, 8*8*bytesPerElement)),
+ })
+ store := newCaptureStore()
+ var got model.ConfigV2
+ writeManifest := func(_ context.Context, _ string, info ManifestInfo) error {
+ got = info.ModelConfig
+ return nil
+ }
+ err := Create(t.Context(), "kev-test", dir, testPipelineOptions(), store, writeManifest, func(string) {})
+ if tc.want == "" {
+ if err == nil || !strings.Contains(err.Error(), "Kev source has no text embedding tensor") {
+ t.Fatalf("Create() error = %v, want missing text embedding", err)
+ }
+ if len(store.blobs) != 0 {
+ t.Fatalf("Create() wrote blobs for invalid dtype: %v", store.names())
+ }
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.FileType != tc.want {
+ t.Errorf("file type = %q, want %q", got.FileType, tc.want)
+ }
+ })
+ }
+}
+
+func TestKevQuantizationPreservesSensitiveTensors(t *testing.T) {
+ policy, err := newTensorImportTransform(Inventory{Config: sourceModelConfig{Architectures: []string{"KevForDecision"}}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ modes := [...]string{"mxfp8", "nvfp4"}
+ for _, tc := range []struct {
+ name string
+ want [2]string
+ }{
+ {"kev_head.q.weight", [2]string{"", ""}},
+ {"kev_head.k.weight", [2]string{"", ""}},
+ {"model.language_model.layers.0.linear_attn.in_proj_a.weight", [2]string{"", ""}},
+ {"layers.0.linear_attn.in_proj_b.weight", [2]string{"", ""}},
+ {"model.language_model.layers.0.mlp.gate_proj.weight", [2]string{"mxfp8", "nvfp4"}},
+ {"model.language_model.layers.0.mlp.down_proj.weight", [2]string{"mxfp8", "mxfp8"}},
+ {"layers.0.mlp.gate_proj.weight", [2]string{"mxfp8", "nvfp4"}},
+ {"layers.0.mlp.down_proj.weight", [2]string{"mxfp8", "mxfp8"}},
+ {"embed_tokens.weight", [2]string{"", ""}},
+ } {
+ for i, mode := range modes {
+ t.Run(mode+"/"+tc.name, func(t *testing.T) {
+ if got := policy.quantizationType(tc.name, []int32{1024, 1024}, mode); got != tc.want[i] {
+ t.Errorf("quantization = %q, want %q", got, tc.want[i])
+ }
+ })
+ }
+ }
+}
diff --git a/create/metadata.go b/create/metadata.go
index a12f2f44c..e8729e4c9 100644
--- a/create/metadata.go
+++ b/create/metadata.go
@@ -105,7 +105,7 @@ func inferSafetensorsCapabilitiesFromConfig(cfg sourceModelConfig, chatTemplate,
}
return capabilities
}
- if cfg.Architecture() == "LayaForDecision" || cfg.Architecture() == "StrandsDeciderForDecision" {
+ if cfg.Architecture() == "LayaForDecision" || cfg.Architecture() == "StrandsDeciderForDecision" || cfg.Architecture() == "KevForDecision" {
return []string{"decision"}
}
capabilities := []string{"completion"}
@@ -218,7 +218,7 @@ func sourceConfigIdentifiers(cfg sourceModelConfig) []string {
}
func parserNameForConfig(modelDir string, cfg sourceModelConfig, chatTemplate string) (string, error) {
- if cfg.Architecture() == "ClefForDecision" || cfg.Architecture() == "StrandsDeciderForDecision" {
+ if cfg.Architecture() == "ClefForDecision" || cfg.Architecture() == "StrandsDeciderForDecision" || cfg.Architecture() == "KevForDecision" {
return "", nil
}
for _, id := range sourceConfigIdentifiers(cfg) {
@@ -269,6 +269,8 @@ func rendererNameForConfig(modelDir string, cfg sourceModelConfig, chatTemplate
func rendererNameForIdentifier(modelDir, s, chatTemplate string) (string, error) {
s = strings.ToLower(s)
switch {
+ case s == "kevfordecision":
+ return "kev", nil
case s == "strandsdeciderfordecision":
return "strands", nil
case s == "cleffordecision":
diff --git a/create/pipeline.go b/create/pipeline.go
index d0f7cd46d..bec447f7a 100644
--- a/create/pipeline.go
+++ b/create/pipeline.go
@@ -69,6 +69,12 @@ func Create(ctx context.Context, modelName, modelDir string, opts PipelineOption
if err != nil {
return err
}
+ if inv.Config.Architecture() == "KevForDecision" && class.Kind == SourceFloat && class.Quantize == "" {
+ modelConfig.FileType, err = kevFileType(inv)
+ if err != nil {
+ return err
+ }
+ }
policy, err := newTensorImportTransform(inv)
if err != nil {
return fmt.Errorf("build quantization policy for %q: %w", inv.Config.Architecture(), err)
diff --git a/create/pipeline_test.go b/create/pipeline_test.go
index 9d4f244f9..9215432c2 100644
--- a/create/pipeline_test.go
+++ b/create/pipeline_test.go
@@ -22,7 +22,7 @@ func (f blobStoreFunc) WriteBlob(r io.Reader, mediaType, name string) (LayerInfo
func TestCreatePipeline(t *testing.T) {
dir := t.TempDir()
- writeConfigJSON(t, dir, `{"architectures":["TestModel"]}`)
+ writeConfigJSON(t, dir, `{"architectures":["TestModel"],"dtype":"bfloat16"}`)
createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{
st.NewTensorDataFromBytes("model.embed_tokens.weight", "BF16", []int32{8, 8}, make([]byte, 8*8*2)),
st.NewTensorDataFromBytes("model.norm.weight", "BF16", []int32{8}, make([]byte, 8*2)),
@@ -59,6 +59,9 @@ func TestCreatePipeline(t *testing.T) {
if gotModelConfig.Requires != "0.20.0" {
t.Errorf("requires = %q, want 0.20.0", gotModelConfig.Requires)
}
+ if gotModelConfig.FileType != "" {
+ t.Errorf("file type = %q, want empty for non-Kev source", gotModelConfig.FileType)
+ }
if gotClass.Kind != SourceFloat || gotClass.Quantize != "" {
t.Errorf("classification = {%s %q}, want {float %q}", gotClass.Kind, gotClass.Quantize, "")
}
@@ -150,7 +153,7 @@ func TestCreatePipelineIncludesDraftLayers(t *testing.T) {
func TestCreatePipelineReportsPrequantizedFileType(t *testing.T) {
dir := t.TempDir()
- writeConfigJSON(t, dir, `{"architectures":["TestModel"]}`)
+ writeConfigJSON(t, dir, `{"architectures":["TestModel"],"dtype":"bfloat16"}`)
createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{
st.NewTensorDataFromBytes("linear.weight", "U8", []int32{16, 8}, make([]byte, 16*8)),
st.NewTensorDataFromBytes("linear.weight_scale", "F8_E4M3", []int32{16, 1}, make([]byte, 16)),
@@ -159,8 +162,10 @@ func TestCreatePipelineReportsPrequantizedFileType(t *testing.T) {
store := newCaptureStore()
var got Classification
+ var gotModelConfig model.ConfigV2
writeManifest := func(_ context.Context, _ string, info ManifestInfo) error {
got = info.Class
+ gotModelConfig = info.ModelConfig
return nil
}
if err := Create(context.Background(), "mymodel", dir, testPipelineOptions(), store, writeManifest, func(string) {}); err != nil {
@@ -169,6 +174,9 @@ func TestCreatePipelineReportsPrequantizedFileType(t *testing.T) {
if got.Kind != SourcePrequantized || got.Quantize != "nvfp4" {
t.Errorf("classification = {%s %q}, want {prequantized nvfp4}", got.Kind, got.Quantize)
}
+ if gotModelConfig.FileType != "" {
+ t.Errorf("file type = %q, want empty before manifest writer selects NVFP4", gotModelConfig.FileType)
+ }
}
func TestCreatePipelineRejectsMalformedMetadata(t *testing.T) {
diff --git a/create/qwen35_decision.go b/create/qwen35_decision.go
index 4df7e5cd3..0b10fbf4f 100644
--- a/create/qwen35_decision.go
+++ b/create/qwen35_decision.go
@@ -14,7 +14,7 @@ func newQwen35DecisionImportTransform(json.RawMessage) (quantizePolicy, error) {
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.") {
+ if !strings.HasPrefix(name, "model.") && !strings.HasPrefix(name, "layers.") {
return ""
}
return qwen35ImportTransform{}.quantizationType(name, shape, requested)
diff --git a/create/qwen35_decision_test.go b/create/qwen35_decision_test.go
index 4dfbde229..270d28759 100644
--- a/create/qwen35_decision_test.go
+++ b/create/qwen35_decision_test.go
@@ -3,7 +3,7 @@ package create
import "testing"
func TestQwen35DecisionQuantizationPolicy(t *testing.T) {
- for _, arch := range []string{"ClefForDecision", "StrandsDeciderForDecision"} {
+ for _, arch := range []string{"ClefForDecision", "StrandsDeciderForDecision", "KevForDecision"} {
inv := Inventory{Config: sourceModelConfig{Architectures: []string{arch}}}
policy, err := newTensorImportTransform(inv)
if err != nil {
@@ -20,6 +20,8 @@ func TestQwen35DecisionQuantizationPolicy(t *testing.T) {
{"lm_head.weight", ""},
{"model.language_model.layers.0.linear_attn.in_proj_a.weight", ""},
{"model.language_model.layers.0.mlp.gate_proj.weight", "mxfp8"},
+ {"layers.0.linear_attn.in_proj_a.weight", ""},
+ {"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 {
diff --git a/decision/kev.go b/decision/kev.go
new file mode 100644
index 000000000..8438d951a
--- /dev/null
+++ b/decision/kev.go
@@ -0,0 +1,261 @@
+package decision
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "math"
+ "strconv"
+ "strings"
+ "unicode"
+
+ "github.com/ollama/ollama/internal/orderedmap"
+ "github.com/ollama/ollama/llm"
+)
+
+func validateKevLimits(req Request) error {
+ if req.Questions == nil || req.Questions.Len() < 1 || req.Questions.Len() > 64 {
+ return fmt.Errorf("questions must contain 1–64 fields")
+ }
+ if len(req.Images) != 0 || len(req.Videos) != 0 {
+ return fmt.Errorf("Kev accepts text state only")
+ }
+ if len(req.State) == 0 || !json.Valid(req.State) {
+ return fmt.Errorf("state must be a JSON value")
+ }
+ return nil
+}
+
+func encodeKev(req Request, c *Compiled) error {
+ state, err := kevContent(req.State)
+ if err != nil {
+ return fmt.Errorf("state: %w", err)
+ }
+ c.Request.State = state
+ for name, question := range req.Questions.All() {
+ field, err := kevField(name, question)
+ if err != nil {
+ return fmt.Errorf("question %q: %w", name, err)
+ }
+ c.fields = append(c.fields, field)
+ c.Request.Rows = append(c.Request.Rows, llm.ScoreRow{Question: &llm.ScoreQuestion{
+ Type: question.Type, Instructions: field.Description, Options: field.options,
+ }})
+ }
+ return nil
+}
+
+func kevField(name string, question Question) (compiledField, error) {
+ field := compiledField{Field: Field{Name: name}, typ: question.Type}
+ if strings.TrimSpace(name) == "" {
+ return field, fmt.Errorf("field name must not be empty")
+ }
+ if len(question.Instructions) != 0 {
+ var err error
+ field.Description, err = kevContent(question.Instructions)
+ if err != nil {
+ return field, fmt.Errorf("instructions: %w", err)
+ }
+ }
+ add := func(value any, description, option string) {
+ field.Choices = append(field.Choices, Choice{Value: value, Description: description})
+ field.options = append(field.options, option)
+ }
+ switch question.Type {
+ case "noul":
+ criteria := orderedmap.New[string, json.RawMessage]()
+ if len(question.Criteria) > 0 && string(question.Criteria) != "null" {
+ if err := json.Unmarshal(question.Criteria, criteria); err != nil {
+ return field, fmt.Errorf("noul criteria must be an object")
+ }
+ }
+ for _, item := range []struct {
+ key string
+ label string
+ value bool
+ }{{"false", "no", false}, {"true", "yes", true}} {
+ description := ""
+ if raw, ok := criteria.Get(item.key); ok {
+ var err error
+ description, err = kevContent(raw)
+ if err != nil {
+ return field, err
+ }
+ }
+ option := item.label
+ if description != "" {
+ option += ": " + description
+ }
+ add(item.value, description, option)
+ }
+ for key := range criteria.All() {
+ if key != "false" && key != "true" {
+ return field, fmt.Errorf("unknown noul criterion %q", key)
+ }
+ }
+ case "choice":
+ criteria := orderedmap.New[string, json.RawMessage]()
+ if err := json.Unmarshal(question.Criteria, criteria); err != nil {
+ return field, fmt.Errorf("choice criteria must be an object")
+ }
+ for key, raw := range criteria.All() {
+ if strings.TrimSpace(key) == "" {
+ return field, fmt.Errorf("choice keys must not be empty")
+ }
+ description, err := kevContent(raw)
+ if err != nil {
+ return field, err
+ }
+ option := key
+ if description != "" {
+ option += ": " + description
+ }
+ add(key, description, option)
+ }
+ case "score":
+ var criteria []json.RawMessage
+ if err := json.Unmarshal(question.Criteria, &criteria); err != nil {
+ return field, fmt.Errorf("score criteria must be an array")
+ }
+ for index, raw := range criteria {
+ text, err := kevContent(raw)
+ if err != nil {
+ return field, err
+ }
+ add(strconv.Itoa(index), text, text)
+ }
+ default:
+ return field, fmt.Errorf("type must be choice, noul, or score")
+ }
+ if len(field.options) < 1 || len(field.options) > 255 || (question.Type == "noul" && len(field.options) != 2) {
+ return field, fmt.Errorf("criteria must contain 1–255 options")
+ }
+ return field, nil
+}
+
+// kevContent renders JSON values as the labels and indented lines seen during
+// Kev training. A streaming decoder preserves object key order.
+func kevContent(raw json.RawMessage) (string, error) {
+ if len(raw) == 0 {
+ return "", nil
+ }
+ if !json.Valid(raw) {
+ return "", fmt.Errorf("invalid JSON value")
+ }
+ dec := json.NewDecoder(bytes.NewReader(raw))
+ dec.UseNumber()
+ value, _, err := kevValue(dec, 0)
+ if err != nil {
+ return "", err
+ }
+ if _, err = dec.Token(); err != io.EOF {
+ return "", fmt.Errorf("extra JSON input")
+ }
+ return value, nil
+}
+
+func kevValue(dec *json.Decoder, depth int) (string, bool, error) {
+ if depth > 64 {
+ return "", false, fmt.Errorf("content nesting exceeds 64 levels")
+ }
+ token, err := dec.Token()
+ if err != nil {
+ return "", false, err
+ }
+ delim, ok := token.(json.Delim)
+ if !ok {
+ return kevScalar(token), false, nil
+ }
+ pad := strings.Repeat(" ", depth)
+ var lines []string
+ switch delim {
+ case '{':
+ for dec.More() {
+ key, err := dec.Token()
+ if err != nil {
+ return "", false, err
+ }
+ value, nested, err := kevValue(dec, depth+1)
+ if err != nil {
+ return "", false, err
+ }
+ separator := ": "
+ if nested {
+ separator = ":\n"
+ }
+ lines = append(lines, pad+key.(string)+separator+value)
+ }
+ case '[':
+ for dec.More() {
+ value, _, err := kevValue(dec, depth+1)
+ if err != nil {
+ return "", false, err
+ }
+ lines = append(lines, pad+"- "+strings.TrimLeftFunc(value, unicode.IsSpace))
+ }
+ default:
+ return "", false, fmt.Errorf("unexpected JSON delimiter %q", delim)
+ }
+ if _, err := dec.Token(); err != nil {
+ return "", false, err
+ }
+ return strings.Join(lines, "\n"), true, nil
+}
+
+func kevScalar(value any) string {
+ switch v := value.(type) {
+ case nil:
+ return ""
+ case bool:
+ if v {
+ return "True"
+ }
+ return "False"
+ case string:
+ return v
+ case json.Number:
+ if !strings.ContainsAny(string(v), ".eE") {
+ return string(v)
+ }
+ f, err := strconv.ParseFloat(string(v), 64)
+ if err != nil {
+ return string(v)
+ }
+ if f == 0 || math.Abs(f) >= 1e-4 && math.Abs(f) < 1e16 {
+ out := strconv.FormatFloat(f, 'f', -1, 64)
+ if !strings.Contains(out, ".") {
+ out += ".0"
+ }
+ return out
+ }
+ return strconv.FormatFloat(f, 'e', -1, 64)
+ default:
+ return fmt.Sprint(v)
+ }
+}
+
+func roundKev(value float64) float64 { return math.RoundToEven(value*1e4) / 1e4 }
+
+func kevConfidence(probabilities []float64, kind string) float64 {
+ if len(probabilities) == 1 {
+ return 1
+ }
+ mode := 0
+ for i := 1; i < len(probabilities); i++ {
+ if probabilities[i] > probabilities[mode] {
+ mode = i
+ }
+ }
+ if kind == "choice" {
+ uniform := 1 / float64(len(probabilities))
+ return (probabilities[mode] - uniform) / (1 - uniform)
+ }
+ center := float64(len(probabilities)-1) / 2
+ var spread, deviation float64
+ for i, p := range probabilities {
+ spread += p * math.Abs(float64(i-mode))
+ deviation += math.Abs(float64(i) - center)
+ }
+ return max(0, 1-spread/(deviation/float64(len(probabilities))))
+}
diff --git a/decision/kev_test.go b/decision/kev_test.go
new file mode 100644
index 000000000..4c172458c
--- /dev/null
+++ b/decision/kev_test.go
@@ -0,0 +1,123 @@
+package decision
+
+import (
+ "encoding/json"
+ "fmt"
+ "math"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/llm"
+)
+
+func TestKevRequestAndAnswers(t *testing.T) {
+ var req Request
+ input := `{"model":"kev:test","state":{"subject":"Charged twice","details":["café",{"count":1e6,"urgent":true}]},"questions":{"team":{"type":"choice","instructions":{"goal":"Pick a team"},"criteria":{"billing":"Payments","shipping":null}},"urgent":{"type":"noul","instructions":"Urgent?","criteria":{"true":"escalate"}},"level":{"type":"score","instructions":"How urgent?","criteria":["low",null,{"high":true}]}}}`
+ if err := json.Unmarshal([]byte(input), &req); err != nil {
+ t.Fatal(err)
+ }
+ c, err := Compile(req, "kev")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := c.Render(func([]api.Message) (string, error) { t.Fatal("Kev does not use a chat renderer"); return "", nil }); err != nil {
+ t.Fatal(err)
+ }
+ if want := "subject: Charged twice\ndetails:\n - café\n - count: 1000000.0\n urgent: True"; c.Request.State != want {
+ t.Fatalf("state = %q, want %q", c.Request.State, want)
+ }
+ if got := c.Request.Rows[0].Question; got.Instructions != "goal: Pick a team" || !slices.Equal(got.Options, []string{"billing: Payments", "shipping"}) {
+ t.Fatalf("choice = %+v", got)
+ }
+ if got := c.Request.Rows[1].Question.Options; !slices.Equal(got, []string{"no", "yes: escalate"}) {
+ t.Fatalf("noul options = %v", got)
+ }
+ if got := c.Request.Rows[2].Question.Options; !slices.Equal(got, []string{"low", "", "high: True"}) {
+ t.Fatalf("score options = %v", got)
+ }
+ answer, err := c.Answer(req.Model, llm.ScoreResponse{Logits: [][]float32{{0, 2}, {0, 2}, {0, 1, 0}}, InputTokens: 123})
+ if err != nil {
+ t.Fatal(err)
+ }
+ team, _ := answer.Answers.Get("team")
+ choice := team.(ChoiceAnswer)
+ if choice.Choice != "shipping" || math.Abs(choice.Confidence-0.7616) > 1e-4 {
+ t.Fatalf("choice answer = %+v", choice)
+ }
+ urgent, _ := answer.Answers.Get("urgent")
+ if urgent.(NoulAnswer).Noul != 0.8808 {
+ t.Fatalf("noul answer = %+v", urgent)
+ }
+ level, _ := answer.Answers.Get("level")
+ score := level.(ScoreAnswer)
+ if score.Score != 1 || math.Abs(score.Confidence-0.3642) > 1e-4 {
+ t.Fatalf("score answer = %+v", score)
+ }
+ if answer.Usage.InputTokens != 123 {
+ t.Fatal(answer.Usage)
+ }
+}
+
+func TestKevLimits(t *testing.T) {
+ for _, state := range []string{`null`, `""`, `[]`} {
+ t.Run("state "+state, func(t *testing.T) {
+ var req Request
+ if err := json.Unmarshal([]byte(`{"model":"kev","state":`+state+`,"questions":{"q":{"type":"choice","criteria":{"a":null}}}}`), &req); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := Compile(req, "kev"); err != nil {
+ t.Fatalf("Compile() error = %v, want acceptance of state %s", err, state)
+ }
+ })
+ }
+ for _, count := range []int{1, 255, 256} {
+ t.Run(fmt.Sprintf("%d options", count), func(t *testing.T) {
+ var req Request
+ criteria := make([]string, count)
+ for i := range criteria {
+ criteria[i] = `"x"`
+ }
+ input := `{"model":"kev","state":"x","questions":{"q":{"type":"score","criteria":[` + strings.Join(criteria, ",") + `]}}}`
+ if err := json.Unmarshal([]byte(input), &req); err != nil {
+ t.Fatal(err)
+ }
+ _, err := Compile(req, "kev")
+ if (err == nil) != (count <= 255) {
+ t.Fatalf("Compile() error = %v for %d options", err, count)
+ }
+ })
+ }
+ for _, tc := range []struct {
+ name, input, want string
+ }{
+ {"blank question", `{"model":"kev","state":"x","questions":{" ":{"type":"noul"}}}`, "field name must not be empty"},
+ {"blank choice key", `{"model":"kev","state":"x","questions":{"q":{"type":"choice","criteria":{" ":null}}}}`, "choice keys must not be empty"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var req Request
+ if err := json.Unmarshal([]byte(tc.input), &req); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := Compile(req, "kev"); err == nil || !strings.Contains(err.Error(), tc.want) {
+ t.Fatalf("Compile() error = %v, want %q", err, tc.want)
+ }
+ })
+ }
+}
+
+func FuzzKevContent(f *testing.F) {
+ for _, seed := range []string{``, `"text"`, `{"subject":"café","details":[1e6,true,null]}`, `[]`, `{"x":[[[0]]]}`, `null`, `{"x":`} {
+ f.Add(seed)
+ }
+ f.Fuzz(func(t *testing.T, input string) {
+ if len(input) > 64<<10 {
+ t.Skip()
+ }
+ _, err := kevContent(json.RawMessage(input))
+ if err == nil && input != "" && !json.Valid([]byte(input)) {
+ t.Fatalf("accepted invalid JSON: %q", input)
+ }
+ })
+}
diff --git a/decision/systemone.go b/decision/systemone.go
index 3922d11ed..5ec736189 100644
--- a/decision/systemone.go
+++ b/decision/systemone.go
@@ -27,6 +27,7 @@ type Compiled struct {
Request llm.ScoreRequest
fields []compiledField
messages [][]api.Message
+ encoding string
}
// ValidateLimits checks request limits shared by all decision backends.
@@ -54,13 +55,23 @@ func ValidateLimits(req Request) error {
func Compile(req Request, encoding string) (*Compiled, error) {
switch encoding {
- case "", "tev1", "clef", "strands":
+ case "", "tev1", "clef", "strands", "kev":
default:
return nil, fmt.Errorf("unsupported decision encoding %q", encoding)
}
if strings.TrimSpace(req.Model) == "" {
return nil, fmt.Errorf("model is required")
}
+ if encoding == "kev" {
+ if err := validateKevLimits(req); err != nil {
+ return nil, err
+ }
+ c := &Compiled{encoding: encoding}
+ if err := encodeKev(req, c); err != nil {
+ return nil, err
+ }
+ return c, nil
+ }
if err := ValidateLimits(req); err != nil {
return nil, err
}
@@ -85,7 +96,7 @@ func Compile(req Request, encoding string) (*Compiled, error) {
if strings.TrimSpace(context) == "" && len(req.Images) == 0 {
return nil, fmt.Errorf("state must not be empty")
}
- c := &Compiled{Request: llm.ScoreRequest{State: context, Images: req.Images}}
+ c := &Compiled{Request: llm.ScoreRequest{State: context, Images: req.Images}, encoding: encoding}
if encoding == "strands" {
if err := encodeStrands(req, c); err != nil {
return nil, err
@@ -284,7 +295,11 @@ func (c *Compiled) Answer(model string, result llm.ScoreResponse) (Response, err
if f.typ == "noul" {
for j, choice := range f.Choices {
if choice.Value == true {
- response.Answers.Set(f.Name, NoulAnswer{Type: f.typ, Noul: p[j]})
+ value := p[j]
+ if c.encoding == "kev" {
+ value = roundKev(value)
+ }
+ response.Answers.Set(f.Name, NoulAnswer{Type: f.typ, Noul: value})
}
}
continue
@@ -293,10 +308,21 @@ func (c *Compiled) Answer(model string, result llm.ScoreResponse) (Response, err
legend := &Legend{}
for j, choice := range f.Choices {
key := choice.Value.(string)
- probabilities.Set(key, p[j])
+ value := p[j]
+ if c.encoding == "kev" {
+ value = roundKev(value)
+ }
+ probabilities.Set(key, value)
legend.Set(key, choice.Description)
}
- confidence := max(0, min(1, 1-entropy/math.Log(float64(len(p)))))
+ var confidence float64
+ if c.encoding == "kev" {
+ confidence = kevConfidence(p, f.typ)
+ confidence = roundKev(confidence)
+ score = roundKev(score)
+ } else {
+ confidence = max(0, min(1, 1-entropy/math.Log(float64(len(p)))))
+ }
if f.typ == "choice" {
winner := slices.Index(p, slices.Max(p))
response.Answers.Set(f.Name, ChoiceAnswer{f.typ, f.Choices[winner].Value.(string), probabilities, confidence})
diff --git a/integration/systemone_test.go b/integration/systemone_test.go
index d430b0f9e..2ad6b486c 100644
--- a/integration/systemone_test.go
+++ b/integration/systemone_test.go
@@ -21,7 +21,7 @@ import (
"github.com/ollama/ollama/types/model"
)
-func postSystemOne(ctx context.Context, endpoint string, input decision.Request) ([]byte, int, error) {
+func postSystemOne(ctx context.Context, endpoint string, input any) ([]byte, int, error) {
body, err := json.Marshal(input)
if err != nil {
return nil, 0, err
@@ -55,6 +55,7 @@ func runAPISystemOne(t *testing.T, modelName string) {
if !slices.Contains(info.Capabilities, model.CapabilityDecision) {
t.Fatalf("model %q does not declare the decision capability", modelName)
}
+ isKev := info.Details.Family == "kev"
var input decision.Request
if err := json.Unmarshal([]byte(`{
@@ -126,7 +127,13 @@ func runAPISystemOne(t *testing.T, modelName string) {
}
sum += p
}
- if math.Abs(sum-1) > 1e-6 || !(answer.confidence >= 0 && answer.confidence <= 1) {
+ // Kev publishes four-decimal probabilities. Each rounded option can
+ // contribute half a unit in the last reported decimal place.
+ tolerance := 1e-6
+ if isKev {
+ tolerance += float64(len(answer.keys)) * 0.5e-4
+ }
+ if math.Abs(sum-1) > tolerance || !(answer.confidence >= 0 && answer.confidence <= 1) {
t.Fatalf("%s: probability sum=%v or missing/invalid confidence: %s", answer.name, sum, body)
}
}
@@ -197,8 +204,15 @@ func runAPISystemOne(t *testing.T, modelName string) {
})
t.Run("invalid_state", func(t *testing.T) {
- invalid := input
- invalid.State = json.RawMessage(`""`)
+ var invalid any
+ if isKev {
+ // Kev accepts empty and null state; absence is invalid.
+ invalid = map[string]any{"model": modelName, "questions": input.Questions}
+ } else {
+ req := input
+ req.State = json.RawMessage(`""`)
+ invalid = req
+ }
body, status, err := postSystemOne(ctx, endpoint, invalid)
if err != nil {
t.Fatal(err)
diff --git a/mlx/gated_delta.go b/mlx/gated_delta.go
index 09cb05b7d..77a7ea944 100644
--- a/mlx/gated_delta.go
+++ b/mlx/gated_delta.go
@@ -172,7 +172,7 @@ type gatedDeltaRecurrenceDims struct {
// resolveGatedDeltaRecurrenceDims validates the inputs against the GPU
// kernels' contract and recovers the launch geometry. ok=false routes to
// the graph implementation: shapes that disagree, Dk not a multiple of the
-// 32-lane simd width, or mixed input dtypes.
+// 32-lane simd width, or unsupported input dtypes.
func resolveGatedDeltaRecurrenceDims(q, k, v, g, beta, state *Array) (gatedDeltaRecurrenceDims, bool) {
var dims gatedDeltaRecurrenceDims
if q == nil || k == nil || v == nil || g == nil || beta == nil || state == nil {
@@ -202,7 +202,8 @@ func resolveGatedDeltaRecurrenceDims(q, k, v, g, beta, state *Array) (gatedDelta
if sd[0] != dims.B || sd[1] != dims.Hv || sd[2] != dims.Dv || sd[3] != dims.Dk {
return dims, false
}
- if k.DType() != q.DType() || v.DType() != q.DType() || g.DType() != q.DType() || beta.DType() != q.DType() {
+ if k.DType() != q.DType() || v.DType() != q.DType() || beta.DType() != q.DType() ||
+ (g.DType() != q.DType() && g.DType() != DTypeFloat32) {
return dims, false
}
return dims, true
@@ -298,7 +299,8 @@ func gatedDeltaRecurrenceGraph(q, k, v, g, beta, state *Array) (y, nextState *Ar
// directly.
func gatedDeltaRecurrence(q, k, v, g, beta, state *Array) (y, nextState *Array) {
if dims, ok := resolveGatedDeltaRecurrenceDims(q, k, v, g, beta, state); ok {
- if supportsFastGatedDeltaUpdate(dims) {
+ // MLX's fast update casts the decay gate to the query dtype.
+ if supportsFastGatedDeltaUpdate(dims) && g.DType() == q.DType() {
return fastGatedDeltaUpdate(q, k, v, g, beta, state, nil)
}
outs := gatedDeltaRecurrenceKernel.run(gpuLaunch{
@@ -351,7 +353,7 @@ var (
},
fallback: func(launch gpuLaunch) []*Array {
in := launch.inputs
- y, end, _ := gatedDeltaGraph(in[0], in[1], in[2], in[3], in[5], false)
+ y, end, _ := gatedDeltaGraph(in[0], in[1], in[2], in[3], in[5], false, false)
return []*Array{y, end}
},
}
@@ -365,13 +367,46 @@ var (
},
fallback: func(launch gpuLaunch) []*Array {
in := launch.inputs
- y, end, interior := gatedDeltaGraph(in[0], in[1], in[2], in[3], in[5], true)
+ y, end, interior := gatedDeltaGraph(in[0], in[1], in[2], in[3], in[5], true, false)
for i, s := range interior {
interior[i] = ExpandDims(s, 0)
}
return []*Array{y, end, Concatenate(interior, 0)}
},
}
+ // Kev opts into FP32 decay without changing the default decision and
+ // generative model kernels.
+ gatedDeltaPrecise = &gpuKernel{
+ name: "gated_delta_precise",
+ inputs: []string{"packed", "ba", "dt_bias", "a_exp", "qk_scale", "state_in"},
+ outputs: []string{"y", "state_out"},
+ metal: gpuSource{
+ source: gatedDeltaMetalSource,
+ header: gatedDeltaMetalHeader + "#define GDN_PRECISE_DECAY\n#define GDN_STORE_INTERIOR(index, value)\n",
+ },
+ fallback: func(launch gpuLaunch) []*Array {
+ in := launch.inputs
+ y, end, _ := gatedDeltaGraph(in[0], in[1], in[2], in[3], in[5], false, true)
+ return []*Array{y, end}
+ },
+ }
+ gatedDeltaPreciseStates = &gpuKernel{
+ name: "gated_delta_precise_states",
+ inputs: []string{"packed", "ba", "dt_bias", "a_exp", "qk_scale", "state_in"},
+ outputs: []string{"y", "state_out", "state_seq"},
+ metal: gpuSource{
+ source: gatedDeltaMetalSource,
+ header: gatedDeltaMetalHeader + "#define GDN_PRECISE_DECAY\n#define GDN_STORE_INTERIOR(index, value) state_seq[index] = value\n",
+ },
+ fallback: func(launch gpuLaunch) []*Array {
+ in := launch.inputs
+ y, end, interior := gatedDeltaGraph(in[0], in[1], in[2], in[3], in[5], true, true)
+ for i, st := range interior {
+ interior[i] = ExpandDims(st, 0)
+ }
+ return []*Array{y, end, Concatenate(interior, 0)}
+ },
+ }
)
// gatedDeltaGraph is the graph implementation of the fused gated-delta step
@@ -379,7 +414,7 @@ var (
// gate, and the (per-token, for captureAll) scan. Geometry is recovered
// from the packed and state shapes, and the q/k scales are recomputed from
// Dk with the same bits the kernel input carries.
-func gatedDeltaGraph(packed, ba, dtBias, aExp, state *Array, captureAll bool) (y, nextState *Array, interior []*Array) {
+func gatedDeltaGraph(packed, ba, dtBias, aExp, state *Array, captureAll, preciseDecay bool) (y, nextState *Array, interior []*Array) {
B, T := int32(packed.Dim(0)), int32(packed.Dim(1))
sd := state.Dims()
Hv, Dv, Dk := int32(sd[1]), int32(sd[2]), int32(sd[3])
@@ -400,12 +435,16 @@ func gatedDeltaGraph(packed, ba, dtBias, aExp, state *Array, captureAll bool) (y
alpha := SliceStartStop(ba, []int32{0, 0, Hv}, []int32{B, T, 2 * Hv})
decay := Softplus(Add(alpha, dtBias))
decay = Mul(decay, aExp)
- decay = Exp(MulScalar(decay, -1)).AsType(alpha.DType())
+ decay = Exp(MulScalar(decay, -1))
+ if !preciseDecay {
+ decay = decay.AsType(alpha.DType())
+ }
betaGate := Sigmoid(beta)
if !captureAll || T == 1 {
y, nextState = gatedDeltaRecurrence(q, k, v, decay, betaGate, state)
- return y, nextState, nil
+ // The recurrent state uses FP32, but the projection consumes the packed dtype.
+ return y.AsType(packed.DType()), nextState, nil
}
sliceT := func(a *Array, t int32) *Array {
@@ -425,7 +464,7 @@ func gatedDeltaGraph(packed, ba, dtBias, aExp, state *Array, captureAll bool) (y
interior = append(interior, state)
}
}
- return Concatenate(outs, 1), state, interior
+ return Concatenate(outs, 1).AsType(packed.DType()), state, interior
}
// The fused scan consumes the activated causal-conv output rows [q | k | v]
@@ -447,7 +486,11 @@ auto value_tile = threadgroup_position_in_grid.y;
threadgroup InT q_cache[Dk];
threadgroup InT k_cache[Dk];
+#ifdef GDN_PRECISE_DECAY
+threadgroup float decay_cache[1];
+#else
threadgroup InT decay_cache[1];
+#endif
threadgroup InT beta_cache[1];
float state[ValuesPerSIMD][StatePerLane];
@@ -497,7 +540,11 @@ for (int t = 0; t < SeqT; ++t) {
InT gate_input = static_cast<InT>(ba[ba_row + Hv + hv_idx] + dt_bias[hv_idx]);
InT softplus = gdn_logaddexp(gate_input, static_cast<InT>(0));
float decay = metal::precise::exp(-static_cast<float>(softplus) * a_exp[hv_idx]);
+#ifdef GDN_PRECISE_DECAY
+ decay_cache[0] = decay;
+#else
decay_cache[0] = static_cast<InT>(decay);
+#endif
beta_cache[0] = gdn_sigmoid(ba[ba_row + hv_idx]);
}
}
@@ -597,6 +644,16 @@ type gatedDeltaDims struct {
// padded position is an identity step with zero output, exactly as on the
// recurrence path.
func GatedDelta(packed, ba, dtBias, aExp, state, mask *Array, captureAll bool) (y, nextState *Array, interior []*Array) {
+ return gatedDeltaStep(packed, ba, dtBias, aExp, state, mask, captureAll, false)
+}
+
+// GatedDeltaPrecise keeps the decay gate in FP32 for models trained with that
+// recurrence. Other models continue through GatedDelta's original path.
+func GatedDeltaPrecise(packed, ba, dtBias, aExp, state, mask *Array, captureAll bool) (y, nextState *Array, interior []*Array) {
+ return gatedDeltaStep(packed, ba, dtBias, aExp, state, mask, captureAll, true)
+}
+
+func gatedDeltaStep(packed, ba, dtBias, aExp, state, mask *Array, captureAll bool, preciseDecay bool) (y, nextState *Array, interior []*Array) {
if mask != nil {
mask3 := Reshape(mask, int32(mask.Dim(0)), int32(mask.Dim(1)), 1)
zero := FromValue(float32(0)).AsType(packed.DType())
@@ -607,7 +664,7 @@ func GatedDelta(packed, ba, dtBias, aExp, state, mask *Array, captureAll bool) (
dims, ok := resolveGatedDeltaDims(packed, ba, dtBias, aExp, state)
if !ok {
- return gatedDeltaGraph(packed, ba, dtBias, aExp, state, captureAll)
+ return gatedDeltaGraph(packed, ba, dtBias, aExp, state, captureAll, preciseDecay)
}
inv := gatedDeltaInvScale(dims.Dk)
@@ -619,12 +676,18 @@ func GatedDelta(packed, ba, dtBias, aExp, state, mask *Array, captureAll bool) (
}
useAllStates := captureAll && dims.T > 1
kernel := gatedDelta
+ if preciseDecay {
+ kernel = gatedDeltaPrecise
+ }
outputs := []gpuOutputSpec{
{"GATED_DELTA_Y", []int32{int32(dims.B), int32(dims.T), int32(dims.Hv), int32(dims.Dv)}, packed.DType()},
{"GATED_DELTA_STATE", []int32{int32(dims.B), int32(dims.Hv), int32(dims.Dv), int32(dims.Dk)}, DTypeFloat32},
}
if useAllStates {
kernel = gatedDeltaStates
+ if preciseDecay {
+ kernel = gatedDeltaPreciseStates
+ }
outputs = append(outputs, gpuOutputSpec{
"GATED_DELTA_STATE_SEQ", []int32{int32(dims.T - 1), int32(dims.B), int32(dims.Hv), int32(dims.Dv), int32(dims.Dk)}, DTypeFloat32,
})
diff --git a/mlx/gated_delta_test.go b/mlx/gated_delta_test.go
index eea40882f..5b9c17116 100644
--- a/mlx/gated_delta_test.go
+++ b/mlx/gated_delta_test.go
@@ -31,7 +31,7 @@ func gatedDeltaTestInputs36(g gatedDeltaTestGeometry, T int) gatedDeltaTestInput
// gatedDeltaReference runs the graph implementation the fused kernels fall
// back to; the test pins the kernels against it bit-for-bit.
func gatedDeltaReference(in gatedDeltaTestInputs, captureAll bool) (y, nextState *Array, interior []*Array) {
- return gatedDeltaGraph(in.packed, in.ba, in.dtBias, in.aExp, in.state, captureAll)
+ return gatedDeltaGraph(in.packed, in.ba, in.dtBias, in.aExp, in.state, captureAll, false)
}
// Exactness is per compiler pair: the metallib and the runtime JIT round
@@ -94,6 +94,81 @@ func TestGatedDeltaRecurrenceUsesFastUpdate(t *testing.T) {
})
}
+// The decay gate is FP32 even when the projection and output are BF16.
+// Rounding it to BF16 compounds across the recurrent state.
+func TestGatedDeltaDecayPrecision(t *testing.T) {
+ withMLXThread(t, func(t *mlxthreadtest.T) {
+ for _, tokens := range []int{1, gatedDeltaMaxTokens + 1} {
+ packed := Zeros(DTypeBFloat16, 1, tokens, 80)
+ ba := Zeros(DTypeBFloat16, 1, tokens, 2)
+ dtBias := Zeros(DTypeBFloat16, 1)
+ aExp := FromValues([]float32{0.00434}, 1)
+ state := AddScalar(Zeros(DTypeFloat32, 1, 1, 16, 32), 1)
+ _, got, _ := GatedDeltaPrecise(packed, ba, dtBias, aExp, state, nil, false)
+ Eval(got)
+ want := float32(math.Pow(math.Exp(-math.Ln2*0.00434), float64(tokens)))
+ if delta := float32(math.Abs(float64(got.Floats()[0] - want))); delta > 0.0002 {
+ t.Errorf("T=%d: state = %g, want %g (delta %g)", tokens, got.Floats()[0], want, delta)
+ }
+ if tokens > gatedDeltaMaxTokens {
+ _, original, _ := GatedDelta(packed, ba, dtBias, aExp, state, nil, false)
+ Eval(original)
+ if delta := math.Abs(float64(original.Floats()[0] - got.Floats()[0])); delta < 0.001 {
+ t.Errorf("T=%d: default and precise decay states differ by only %g", tokens, delta)
+ }
+ }
+ }
+ })
+}
+
+func TestGatedDeltaPreciseSkipsBF16FastUpdate(t *testing.T) {
+ withMLXThread(t, func(t *mlxthreadtest.T) {
+ if !MetalIsAvailable() {
+ t.Skip("requires Metal fast update")
+ }
+ const tokens, heads, width = 33, 16, 128
+ packed := Zeros(DTypeBFloat16, 1, tokens, 3*heads*width)
+ ba := Zeros(DTypeBFloat16, 1, tokens, 2*heads)
+ dtBias := Zeros(DTypeBFloat16, heads)
+ aExp := AddScalar(Zeros(DTypeFloat32, heads), 0.00434)
+ state := AddScalar(Zeros(DTypeFloat32, 1, heads, width, width), 1)
+ _, precise, _ := GatedDeltaPrecise(packed, ba, dtBias, aExp, state, nil, false)
+ _, original, _ := GatedDelta(packed, ba, dtBias, aExp, state, nil, false)
+ Eval(precise, original)
+ want := float32(math.Pow(math.Exp(-math.Ln2*0.00434), tokens))
+ if delta := math.Abs(float64(precise.Floats()[0] - want)); delta > 0.0005 {
+ t.Errorf("precise state = %g, want %g (delta %g)", precise.Floats()[0], want, delta)
+ }
+ if delta := math.Abs(float64(original.Floats()[0] - precise.Floats()[0])); delta < 0.005 {
+ t.Errorf("default and precise states differ by only %g", delta)
+ }
+ })
+}
+
+func TestGatedDeltaPreciseMatchesGraph(t *testing.T) {
+ withMLXThread(t, func(t *mlxthreadtest.T) {
+ in := gatedDeltaTestInputs36(gatedDeltaTestGeometry{Hk: 4, Dk: 64, Hv: 8, Dv: 32}, 3)
+ for _, captureAll := range []bool{false, true} {
+ refY, refState, refInterior := gatedDeltaGraph(in.packed, in.ba, in.dtBias, in.aExp, in.state, captureAll, true)
+ y, state, interior := GatedDeltaPrecise(in.packed, in.ba, in.dtBias, in.aExp, in.state, nil, captureAll)
+ if err := requireExact("y", y, refY); err != nil {
+ t.Fatalf("captureAll=%v: %v", captureAll, err)
+ }
+ if err := requireExact("state", state, refState); err != nil {
+ t.Fatalf("captureAll=%v: %v", captureAll, err)
+ }
+ if len(interior) != len(refInterior) {
+ t.Fatalf("captureAll=%v: interior count = %d, want %d", captureAll, len(interior), len(refInterior))
+ }
+ for i := range interior {
+ if err := requireExact(fmt.Sprintf("interior[%d]", i), interior[i], refInterior[i]); err != nil {
+ t.Fatalf("captureAll=%v: %v", captureAll, err)
+ }
+ }
+ }
+ })
+}
+
func TestGatedDeltaGraphRouting(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
testGatedDeltaGraphRouting(t)
diff --git a/mlxrunner/model/architectures/architectures.go b/mlxrunner/model/architectures/architectures.go
index 45127dc14..17453e562 100644
--- a/mlxrunner/model/architectures/architectures.go
+++ b/mlxrunner/model/architectures/architectures.go
@@ -8,6 +8,7 @@ import (
_ "github.com/ollama/ollama/mlxrunner/model/gemma4embedding"
_ "github.com/ollama/ollama/mlxrunner/model/glimmer"
_ "github.com/ollama/ollama/mlxrunner/model/glm4_moe_lite"
+ _ "github.com/ollama/ollama/mlxrunner/model/kev"
_ "github.com/ollama/ollama/mlxrunner/model/laguna"
_ "github.com/ollama/ollama/mlxrunner/model/laya"
_ "github.com/ollama/ollama/mlxrunner/model/llama"
diff --git a/mlxrunner/model/kev/model.go b/mlxrunner/model/kev/model.go
new file mode 100644
index 000000000..502e19bf3
--- /dev/null
+++ b/mlxrunner/model/kev/model.go
@@ -0,0 +1,90 @@
+// Package kev implements the Qwen3.5/Qwen3.8 Kev decision head.
+package kev
+
+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 {
+ HeadDim int `json:"head_dim"`
+ Temperature float32 `json:"temperature"`
+ MaxState int `json:"max_state"`
+ MaxRow int `json:"max_row"`
+}
+
+type Model struct {
+ *qwen3_5.Model
+ Query, Key *nn.Linear
+ config config
+}
+
+func init() { model.Register("KevForDecision", newModel) }
+
+func newModel(root *model.Root) (model.Model, error) {
+ var cfg config
+ if err := root.Manifest.ReadConfigJSON("kev_config.json", &cfg); err != nil {
+ return nil, err
+ }
+ if cfg.HeadDim < 1 {
+ return nil, fmt.Errorf("invalid Kev head_dim %d", cfg.HeadDim)
+ }
+ if cfg.MaxState < 1 || cfg.MaxState > 65536 {
+ return nil, fmt.Errorf("invalid Kev max_state %d", cfg.MaxState)
+ }
+ if cfg.MaxRow < cfg.MaxState || cfg.MaxRow > 73728 {
+ return nil, fmt.Errorf("invalid Kev max_row %d for max_state %d", cfg.MaxRow, cfg.MaxState)
+ }
+ if cfg.Temperature <= 0 || math.IsNaN(float64(cfg.Temperature)) || math.IsInf(float64(cfg.Temperature), 0) {
+ return nil, fmt.Errorf("invalid Kev temperature %g", cfg.Temperature)
+ }
+ backbone, err := qwen3_5.NewModel(root)
+ if err != nil {
+ return nil, err
+ }
+ m := &Model{Model: backbone.(*qwen3_5.Model), config: cfg}
+ m.Config.PreciseGatedDeltaDecay = true
+ if m.Config.ModelType != "qwen3_5" && m.Config.ModelType != "qwen3_5_text" {
+ return nil, fmt.Errorf("unsupported Kev backbone %q", m.Config.ModelType)
+ }
+ return m, nil
+}
+
+func (m *Model) MaxContextLength() int {
+ return min(m.config.MaxRow, 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.HeadDim
+ for name, shape := range map[string][]int{
+ "kev_head.q.weight": {dim, hidden},
+ "kev_head.q.bias": {dim},
+ "kev_head.k.weight": {dim, hidden},
+ "kev_head.k.bias": {dim},
+ } {
+ w := tensors[name]
+ if w == nil || w.DType() != mlx.DTypeFloat32 || !slices.Equal(w.Dims(), shape) {
+ return fmt.Errorf("Kev requires FP32 %s with shape %v", name, shape)
+ }
+ }
+ m.Query = &nn.Linear{Weight: tensors["kev_head.q.weight"], Bias: tensors["kev_head.q.bias"]}
+ m.Key = &nn.Linear{Weight: tensors["kev_head.k.weight"], Bias: tensors["kev_head.k.bias"]}
+ return nil
+}
+
+// The pointer head runs in FP32 and applies the checkpoint's fitted temperature.
+func (m *Model) pointer(query, options *mlx.Array) *mlx.Array {
+ q := m.Query.Forward(query.AsType(mlx.DTypeFloat32))
+ k := m.Key.Forward(options.AsType(mlx.DTypeFloat32))
+ scale := float32(math.Sqrt(float64(m.config.HeadDim))) * m.config.Temperature
+ return mlx.DivScalar(mlx.Matmul(k, q.Transpose(0, 2, 1)).Squeeze(-1), scale)
+}
diff --git a/mlxrunner/model/kev/score.go b/mlxrunner/model/kev/score.go
new file mode 100644
index 000000000..8464b39d6
--- /dev/null
+++ b/mlxrunner/model/kev/score.go
@@ -0,0 +1,116 @@
+package kev
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "regexp"
+
+ "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)
+
+// Callers cannot insert the tokens Kev uses to delimit its own fields.
+var controlToken = regexp.MustCompile(`<\|([A-Za-z0-9_]+)\|>`)
+
+func userTokens(tok *tokenizer.Tokenizer, value string) []int32 {
+ return tok.Encode(controlToken.ReplaceAllString(value, "<¦${1}¦>"), false)
+}
+
+type ScoreRow struct {
+ Tokens []int32
+ Pointers []int32
+ StateTokens int
+}
+
+func (m *Model) PrepareScore(ctx context.Context, input llm.ScoreRequest) ([]ScoreRow, error) {
+ badRequest := func(format string, args ...any) ([]ScoreRow, error) {
+ return nil, api.StatusError{StatusCode: http.StatusBadRequest, ErrorMessage: fmt.Sprintf(format, args...)}
+ }
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ if len(input.Rows) < 1 || len(input.Rows) > 64 || len(input.Images) != 0 || input.MaxTokens < 1 || input.MaxTokens > m.MaxContextLength() {
+ return badRequest("invalid Kev questions, images, or context limit")
+ }
+ tok := m.Tokenizer()
+ markers := [5]int32{}
+ for i, name := range [...]string{"<|fim_prefix|>", "<|fim_middle|>", "<|box_start|>", "<|box_end|>", "<|fim_suffix|>"} {
+ var ok bool
+ markers[i], ok = tok.GetSpecialToken(name)
+ if !ok {
+ return badRequest("Kev tokenizer is missing %s", name)
+ }
+ }
+ state := append([]int32{markers[0]}, userTokens(tok, input.State)...)
+ if len(state) > m.config.MaxState || len(state) > input.MaxTokens {
+ return badRequest("Kev state has %d tokens; limit is %d", len(state), min(m.config.MaxState, input.MaxTokens))
+ }
+ rows := make([]ScoreRow, len(input.Rows))
+ for i, request := range input.Rows {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ q := request.Question
+ if q == nil || (q.Type != "noul" && q.Type != "choice" && q.Type != "score") || len(q.Options) < 1 || len(q.Options) > 255 || (q.Type == "noul" && len(q.Options) != 2) {
+ return badRequest("question %d has an invalid type or option count", i)
+ }
+ row := ScoreRow{Tokens: append([]int32(nil), state...), StateTokens: len(state)}
+ row.Tokens = append(row.Tokens, markers[1])
+ row.Tokens = append(row.Tokens, userTokens(tok, q.Instructions)...)
+ for _, option := range q.Options {
+ row.Tokens = append(row.Tokens, markers[2])
+ row.Tokens = append(row.Tokens, userTokens(tok, option)...)
+ row.Pointers = append(row.Pointers, int32(len(row.Tokens)))
+ row.Tokens = append(row.Tokens, markers[3])
+ }
+ row.Tokens = append(row.Tokens, markers[4])
+ if len(row.Tokens) > m.config.MaxRow || len(row.Tokens) > input.MaxTokens {
+ return badRequest("question %d needs %d tokens; row limit is %d", i, len(row.Tokens), min(m.config.MaxRow, input.MaxTokens))
+ }
+ rows[i] = row
+ }
+ return rows, nil
+}
+
+// FinishScore reads the closing delimiter of each option and the final query.
+// It runs on the MLX thread, after the complete causal row has been evaluated.
+func (m *Model) FinishScore(row ScoreRow, hidden *mlx.Array) []float32 {
+ options := hidden.TakeAxis(mlx.FromValues(row.Pointers, len(row.Pointers)), 1)
+ last := len(row.Tokens) - 1
+ query := hidden.Slice(mlx.Slice(), mlx.Slice(last, last+1), mlx.Slice())
+ logits := m.pointer(query, options).Reshape(-1)
+ mlx.Eval(logits)
+ return logits.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, ScorePrefix: row.StateTokens}, 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/media.go b/mlxrunner/model/media.go
index e479993ae..60d7d3d1e 100644
--- a/mlxrunner/model/media.go
+++ b/mlxrunner/model/media.go
@@ -53,6 +53,9 @@ type PreparedItem struct {
type PreparedRequest struct {
Tokens []int32
Items []PreparedItem
+ // ScorePrefix is an optional token boundary shared by independent scoring
+ // rows. The scorer asks the runner to retain its cache state there.
+ ScorePrefix int
// Layout is an opaque request-scoped value computed in the one pass
// that sees every splice position; immutable, carried unread by the
diff --git a/mlxrunner/model/qwen3_5/qwen3_5.go b/mlxrunner/model/qwen3_5/qwen3_5.go
index 8a85e734f..ebb19fddc 100644
--- a/mlxrunner/model/qwen3_5/qwen3_5.go
+++ b/mlxrunner/model/qwen3_5/qwen3_5.go
@@ -80,10 +80,11 @@ type Config struct {
MropeSection []int32 `json:"-"`
// Quantization metadata.
- QuantGroupSize int `json:"-"`
- QuantBits int `json:"-"`
- QuantMode string `json:"-"`
- TensorQuant map[string]*model.TensorQuantInfo `json:"-"`
+ QuantGroupSize int `json:"-"`
+ QuantBits int `json:"-"`
+ QuantMode string `json:"-"`
+ TensorQuant map[string]*model.TensorQuantInfo `json:"-"`
+ PreciseGatedDeltaDecay bool `json:"-"`
// Computed fields.
Scale float32 `json:"-"`
@@ -350,6 +351,7 @@ func (l tensorPathLayout) modelPath(suffix string) string {
func resolveTensorPathLayout(tensors map[string]*mlx.Array) tensorPathLayout {
for _, layout := range []tensorPathLayout{
{containerPrefix: "", modelPrefix: "model."},
+ {containerPrefix: "", modelPrefix: ""},
{containerPrefix: "language_model.", modelPrefix: "model."},
{containerPrefix: "language_model.", modelPrefix: ""},
{containerPrefix: "model.language_model.", modelPrefix: "model."},
@@ -1167,6 +1169,9 @@ func (g *GatedDeltaNet) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, B,
var rc *cache.RecurrentCache
opts := make([]nn.RecurrentOption, 0, 3)
opts = append(opts, nn.WithConvSiLU())
+ if cfg.PreciseGatedDeltaDecay {
+ opts = append(opts, nn.WithPreciseGatedDeltaDecay())
+ }
if typed, ok := c.(*cache.RecurrentCache); ok {
rc = typed
opts = append(opts, nn.WithRecurrentHistory(rc.Get(b, x.DType())))
diff --git a/mlxrunner/model/qwen3_5/qwen3_5_test.go b/mlxrunner/model/qwen3_5/qwen3_5_test.go
index 5db6ce87a..939b2ffec 100644
--- a/mlxrunner/model/qwen3_5/qwen3_5_test.go
+++ b/mlxrunner/model/qwen3_5/qwen3_5_test.go
@@ -260,6 +260,12 @@ func TestResolveTensorPathLayout(t *testing.T) {
wantContainer: "",
wantModel: "model.",
},
+ {
+ name: "text-only full checkpoint",
+ key: "embed_tokens.weight",
+ wantContainer: "",
+ wantModel: "",
+ },
{
name: "nested language model with inner model",
key: "model.language_model.model.embed_tokens.weight",
diff --git a/mlxrunner/nn/recurrent.go b/mlxrunner/nn/recurrent.go
index ded8b55e7..a175e7870 100644
--- a/mlxrunner/nn/recurrent.go
+++ b/mlxrunner/nn/recurrent.go
@@ -14,11 +14,12 @@ type RecurrentOption func(*recurrentConfig)
// RecurrentOption. Exactly one of history or (convState/deltaState)
// must be supplied per call.
type recurrentConfig struct {
- history *RecurrentHistory
- convState *mlx.Array
- deltaState *mlx.Array
- splits []int
- convSiLU bool
+ history *RecurrentHistory
+ convState *mlx.Array
+ deltaState *mlx.Array
+ splits []int
+ convSiLU bool
+ preciseDecay bool
}
// WithRecurrentHistory supplies a cache's per-layer view of conv and
@@ -45,6 +46,12 @@ func WithConvSiLU() RecurrentOption {
return func(c *recurrentConfig) { c.convSiLU = true }
}
+// WithPreciseGatedDeltaDecay selects the FP32 decay gate for models trained
+// with that recurrence. Other recurrent wrappers ignore this option.
+func WithPreciseGatedDeltaDecay() RecurrentOption {
+ return func(c *recurrentConfig) { c.preciseDecay = true }
+}
+
// WithSnapshotSplits requests that the scan run in segments cut at the given
// offsets within this forward (0 < offset < L), capturing the recurrent state
// at each boundary. The wrapper returns those per-boundary states to the
@@ -232,12 +239,16 @@ func GatedDelta(b *batch.Batch, convOut, ba, dtBias, aExp *mlx.Array, opts ...Re
L := int32(convOut.Dim(1))
mask := paddingMask(b, L)
+ run := mlx.GatedDelta
+ if cfg.preciseDecay {
+ run = mlx.GatedDeltaPrecise
+ }
// No splits and per-token splits are both a single whole-forward call:
// len(splits) == L-1 means the sorted interior offsets are exactly
// 1..L-1, the kernels' captureAll shape.
if n := len(cfg.splits); n == 0 || n == int(L)-1 {
- y, end, interior := mlx.GatedDelta(convOut, ba, dtBias, aExp, prior, mask, n > 0)
+ y, end, interior := run(convOut, ba, dtBias, aExp, prior, mask, n > 0)
return y, append(interior, end)
}
@@ -247,7 +258,7 @@ func GatedDelta(b *batch.Batch, convOut, ba, dtBias, aExp *mlx.Array, opts ...Re
state := prior
for _, seg := range segs {
var y *mlx.Array
- y, state, _ = mlx.GatedDelta(sliceSeg(convOut, seg), sliceSeg(ba, seg), dtBias, aExp, state, sliceSeg(mask, seg), false)
+ y, state, _ = run(sliceSeg(convOut, seg), sliceSeg(ba, seg), dtBias, aExp, state, sliceSeg(mask, seg), false)
outs = append(outs, y)
states = append(states, state)
}
diff --git a/mlxrunner/nn/recurrent_test.go b/mlxrunner/nn/recurrent_test.go
index 4eef031f0..a12296c6d 100644
--- a/mlxrunner/nn/recurrent_test.go
+++ b/mlxrunner/nn/recurrent_test.go
@@ -221,11 +221,6 @@ func TestGatedDeltaSegmentEquivalence(t *testing.T) {
prior := mlx.Zeros(mlx.DTypeFloat32, B, Hv, Dv, Dk)
full := &batch.Batch{SeqOffsets: []int32{0}, SeqQueryLens: []int32{int32(T)}}
- refOut, refStates := GatedDelta(full, packed, ba, dtBias, aExp, WithRecurrentState(nil, prior))
- if len(refStates) != 1 {
- t.Fatalf("unsegmented call returned %d states, want 1", len(refStates))
- }
-
cases := []struct {
name string
splits []int
@@ -233,21 +228,36 @@ func TestGatedDeltaSegmentEquivalence(t *testing.T) {
{"perToken", []int{1, 2, 3, 4}},
{"sparse", []int{2}},
}
- for _, tc := range cases {
- segOut, segStates := GatedDelta(full, packed, ba, dtBias, aExp,
- WithRecurrentState(nil, prior), WithSnapshotSplits(tc.splits))
- mlx.Eval(refOut, segOut)
- floatsClose(t, tc.name+" out", segOut.Floats(), refOut.Floats(), 1e-4)
- if len(segStates) != len(tc.splits)+1 {
- t.Fatalf("%s: got %d boundary states, want %d", tc.name, len(segStates), len(tc.splits)+1)
+ for _, precise := range []bool{false, true} {
+ mode := "default"
+ opts := []RecurrentOption{WithRecurrentState(nil, prior)}
+ run := mlx.GatedDelta
+ if precise {
+ mode = "precise"
+ opts = append(opts, WithPreciseGatedDeltaDecay())
+ run = mlx.GatedDeltaPrecise
}
- boundaries := append(append([]int{}, tc.splits...), T)
- for i, n := range boundaries {
- _, want, _ := mlx.GatedDelta(
- slicePrefix(packed, 0, 1, int32(n)), slicePrefix(ba, 0, 1, int32(n)),
- dtBias, aExp, prior, nil, false)
- mlx.Eval(segStates[i], want)
- floatsClose(t, tc.name+" boundary delta", segStates[i].Floats(), want.Floats(), 1e-4)
+ refOut, refStates := GatedDelta(full, packed, ba, dtBias, aExp, opts...)
+ if len(refStates) != 1 {
+ t.Fatalf("%s unsegmented call returned %d states, want 1", mode, len(refStates))
+ }
+
+ for _, tc := range cases {
+ segOpts := append(append([]RecurrentOption{}, opts...), WithSnapshotSplits(tc.splits))
+ segOut, segStates := GatedDelta(full, packed, ba, dtBias, aExp, segOpts...)
+ mlx.Eval(refOut, segOut)
+ floatsClose(t, mode+"/"+tc.name+" out", segOut.Floats(), refOut.Floats(), 1e-4)
+ if len(segStates) != len(tc.splits)+1 {
+ t.Fatalf("%s/%s: got %d boundary states, want %d", mode, tc.name, len(segStates), len(tc.splits)+1)
+ }
+ boundaries := append(append([]int{}, tc.splits...), T)
+ for i, n := range boundaries {
+ _, want, _ := run(
+ slicePrefix(packed, 0, 1, int32(n)), slicePrefix(ba, 0, 1, int32(n)),
+ dtBias, aExp, prior, nil, false)
+ mlx.Eval(segStates[i], want)
+ floatsClose(t, mode+"/"+tc.name+" boundary delta", segStates[i].Floats(), want.Floats(), 1e-4)
+ }
}
}
})
diff --git a/mlxrunner/score.go b/mlxrunner/score.go
index 744b82fe9..c913cbcb5 100644
--- a/mlxrunner/score.go
+++ b/mlxrunner/score.go
@@ -203,7 +203,9 @@ func (r *Runner) scoreHiddenRow(ctx context.Context, input *model.PreparedReques
}
session := r.scoringCache().beginScore(input.Tokens, items)
defer session.close()
- session.schedulePrefillSnapshots(scoreSnapshots(len(input.Tokens), 0))
+ // Kev repeats the same state in each question row. Preserve that boundary
+ // for the next row; other scorers leave ScorePrefix at zero.
+ session.schedulePrefillSnapshots(scoreSnapshots(len(input.Tokens), input.ScorePrefix))
media := r.openMedia(Request{Tokens: input.Tokens, MediaItems: items, Layout: input.Layout})
defer media.close()
offset := len(input.Tokens) - len(session.remaining)
diff --git a/mlxrunner/score_hidden_test.go b/mlxrunner/score_hidden_test.go
index 338b78fed..db84b27a7 100644
--- a/mlxrunner/score_hidden_test.go
+++ b/mlxrunner/score_hidden_test.go
@@ -197,3 +197,39 @@ func TestScoreHiddenPrefixReuse(t *testing.T) {
}
})
}
+
+func TestScoreHiddenSharedStateSnapshot(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ m := prefillTestModel()
+ first := slices.Repeat([]int32{1, 2, 3, 4}, 520)
+ second := slices.Clone(first)
+ const shared = 1024
+ second[shared] = 5
+
+ cold := &Runner{Model: m}
+ want, _, err := cold.scoreHiddenRow(context.Background(), &model.PreparedRequest{Tokens: second}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantValues := want.Floats()
+ cold.scoreCache.close()
+
+ r := &Runner{Model: m}
+ defer func() { r.scoreCache.close() }()
+ if _, _, err := r.scoreHiddenRow(context.Background(), &model.PreparedRequest{Tokens: first, ScorePrefix: shared}, nil); err != nil {
+ t.Fatal(err)
+ }
+ got, cached, err := r.scoreHiddenRow(context.Background(), &model.PreparedRequest{Tokens: second, ScorePrefix: shared}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if cached != shared {
+ t.Fatalf("shared state reused %d/%d tokens", cached, shared)
+ }
+ 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/server/routes.go b/server/routes.go
index caedc1272..e14e036ab 100644
--- a/server/routes.go
+++ b/server/routes.go
@@ -948,7 +948,7 @@ func (s *Server) systemOneLlamaServer(c *gin.Context, m *Model, req decision.Req
// SystemOneHandler answers typed questions with probabilities.
func (s *Server) SystemOneHandler(c *gin.Context) {
// TODO(parthsareen): Check token limits before copying state and schema into
- // each question's prompt. This byte cap limits memory use until then.
+ // each question's prompt. Non-Kev models retain the 64 KiB byte cap until then.
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 32<<20)
body, err := io.ReadAll(c.Request.Body)
var req decision.Request
@@ -973,9 +973,9 @@ func (s *Server) SystemOneHandler(c *gin.Context) {
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
+ textSize := len(bytes.TrimSpace(text.Bytes()))
+ rejectText := func(limit int) {
+ c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": fmt.Sprintf("text and schema must not exceed %d KiB", limit>>10)})
}
ref, err := parseAndValidateModelRef(req.Model)
if err != nil {
@@ -999,12 +999,22 @@ func (s *Server) SystemOneHandler(c *gin.Context) {
handleScheduleError(c, req.Model, err)
return
}
+ textLimit := 64 << 10
+ if m.Config.Renderer == "kev" {
+ // Kev shares the state across question rows and admits up to 65,536
+ // state tokens, which can exceed the generic decision prompt cap.
+ textLimit = 1 << 20
+ }
+ if textSize > textLimit {
+ rejectText(textLimit)
+ return
+ }
if m.isGGUF() {
s.systemOneLlamaServer(c, m, req, body)
return
}
var encoding string
- if m.Config.Renderer == "tev1" || m.Config.Renderer == "clef" || m.Config.Renderer == "strands" {
+ if m.Config.Renderer == "tev1" || m.Config.Renderer == "clef" || m.Config.Renderer == "strands" || m.Config.Renderer == "kev" {
encoding = m.Config.Renderer
}
compiled, err := decision.Compile(req, encoding)
diff --git a/server/systemone_test.go b/server/systemone_test.go
index cd29ab6d2..50e0c4d89 100644
--- a/server/systemone_test.go
+++ b/server/systemone_test.go
@@ -56,14 +56,20 @@ func (r *systemOneTestRunner) Score(ctx context.Context, input llm.ScoreRequest)
return llm.ScoreResponse{Logits: [][]float32{{2, 0}}, InputTokens: 123}, r.err
}
logits := [][]float32{{0, 2}}
+ outputTokens := 2
if len(input.Rows) > 0 {
logits = make([][]float32, len(input.Rows))
for i, row := range input.Rows {
- logits[i] = make([]float32, len(row.Candidates))
- logits[i][len(row.Candidates)-1] = 2
+ options := len(row.Candidates)
+ if options == 0 && row.Question != nil {
+ options = len(row.Question.Options)
+ outputTokens = 0
+ }
+ logits[i] = make([]float32, options)
+ logits[i][options-1] = 2
}
}
- return llm.ScoreResponse{Logits: logits, InputTokens: 123, OutputTokens: 2}, r.err
+ return llm.ScoreResponse{Logits: logits, InputTokens: 123, OutputTokens: outputTokens}, r.err
}
func TestDecisionModelRejectsCompletion(t *testing.T) {
@@ -119,6 +125,9 @@ func TestSystemOneHandler(t *testing.T) {
createSafetensorsTestModel(t, "safetensors-clef-text", config, []manifest.Layer{params})
config.Capabilities = []string{"decision", "vision"}
createSafetensorsTestModel(t, "safetensors-clef", config, []manifest.Layer{params})
+ config.Renderer = "kev"
+ config.Capabilities = []string{"decision"}
+ createSafetensorsTestModel(t, "safetensors-kev", config, []manifest.Layer{params})
config.Renderer = "qwen3.5"
config.Capabilities = []string{"completion"}
createSafetensorsTestModel(t, "safetensors-undeclared", config, nil)
@@ -219,6 +228,9 @@ func TestSystemOneHandler(t *testing.T) {
{"bad JSON", `{`, nil, 400, 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},
+ {"oversized missing model returns not found", strings.Replace(prefix+strings.Repeat("x", stateLimit+32)+suffix, "decision-test", "missing", 1), nil, 404, 0, false},
+ {"Kev above default text limit", `{"model":"safetensors-kev","state":"` + strings.Repeat("x", 70<<10) + `","questions":{"refund":{"type":"noul","instructions":"q"}}}`, nil, 200, 1, false},
+ {"Kev above extended text limit", `{"model":"safetensors-kev","state":"` + strings.Repeat("x", 1<<20) + `","questions":{"refund":{"type":"noul","instructions":"q"}}}`, 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},
}
@@ -315,7 +327,7 @@ func TestSystemOneHandler(t *testing.T) {
t.Fatal(err)
}
outputTokens := 2
- if len(runner.request.Fields) > 0 || runner.native {
+ if len(runner.request.Fields) > 0 || runner.native || ref.model.Config.Renderer == "kev" {
outputTokens = 0
}
if response.Answers["refund"].Noul < 0.88 || response.Usage.InputTokens != 123 || response.Usage.OutputTokens != outputTokens {
@@ -349,6 +361,10 @@ func TestSystemOneHandler(t *testing.T) {
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)
}
+ } else if ref.model.Config.Renderer == "kev" {
+ if prompt != "" || len(runner.request.State) != 70<<10 || runner.request.Rows[0].Question == nil {
+ t.Fatalf("Kev scorer received a rendered prompt or lost the state/question")
+ }
} else {
wantPrefix := "<|im_start|>user\n"
if ref.model.System != "" {