Skip to content

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

Add decision model integration tests and benchmarks (#18746)

Daniel Hiltgen72f61ca4128c
diff --git a/cmd/bench/README.md b/cmd/bench/README.md
index 789267733..36cd87f75 100644
--- a/cmd/bench/README.md
+++ b/cmd/bench/README.md
@@ -83,6 +83,46 @@ Limits:
## Command Line Options
+### Decision models
+
+```sh
+go run ./cmd/bench -model tev1:latest -decision cases.jsonl -format csv
+```
+
+Each JSONL line supplies a request and expected answers; datasets are external:
+
+```json
+{"id":"message","dataset":"example","request":{"state":"I am angry.","questions":{"angry":{"type":"noul","instructions":"Is the speaker angry?","criteria":{}}}},"expected":{"angry":{"noul":true}}}
+```
+
+Omit `request.model` and `keep_alive`. Each question needs an expectation:
+`{"choice":"label"}`, `{"noul":true}`, `{"level":2}` (unique most probable score
+class), or `{"min":1.5,"max":2}` (inclusive expected-score range). Optional
+`image_files` paths are relative to the JSONL; inline `request.images` also works.
+
+`-epochs` replays the corpus unchanged; `-warmup` counts untimed requests.
+`score` reports accuracy; `regression` requires 100%. HTTP/invalid-response errors
+fail either mode. Stderr summaries report accuracy, latency percentiles and
+requests/questions per second; CSV retains per-request results and input sizes.
+CSV separates label `mismatches` from HTTP/invalid-response `error` values.
+Summary percentiles use HTTP round-trip latency, including server queueing.
+Compare identical corpora, model artifacts and settings on the same host. HTTP
+latency includes model lookup and request setup, so warm runs capture routing and
+metadata-cache improvements as well as inference. Use `-k 0 -concurrency 1` and a
+warmup pass (`-warmup` equal to the corpus length) for this comparison. A warm
+model does not imply uncached prompts: replay may reuse prefixes; inspect
+`cached_input_tokens`. Group latency by input size and question count when
+comparing different workloads.
+
+`-concurrency` currently requires `-decision`: 1 sends back-to-back requests;
+higher values keep that many requests in flight. Cold runs (`-k > 0`) require 1.
+Integration uses the same file via `OLLAMA_TEST_DECISION_FILE`, defaults to
+`.cache/decision-data/regression.jsonl` in the repo, and skips when absent.
+`OLLAMA_TEST_MODEL` selects the model. Integration requires every case to pass;
+use bench in score mode with the broad corpus to evaluate model quality.
+
+### Options
+
| Option | Description | Default |
|----------|-------------|---------|
| -model | Comma-separated list of models to benchmark | (required) |
@@ -98,6 +138,10 @@ Limits:
| -output | Output file for results | "" (stdout) |
| -warmup | Number of warmup requests before timing | 1 |
| -prompt-tokens | Generate a prompt of exactly N tokens (0 = use -p) | 0 |
+| -decision | External decision JSONL corpus instead of chat | "" |
+| -decision-url | External System One endpoint; server manages loading | "" |
+| -decision-mode | `score` reports accuracy; `regression` requires 100% | score |
+| -concurrency | Maximum in-flight requests (currently requires `-decision`) | 1 |
| -num-ctx | Context size (0 = server default) | 0 |
| -openai | OpenAI-compatible API base URL | "" |
| -api-key | API key for OpenAI endpoint (or OPENAI_API_KEY) | "" |
@@ -164,3 +208,9 @@ Additionally, the model info comment line (displayed once per model before epoch
* **Family**: Model family (e.g., gemma3)
* **Size**: Total model memory in bytes
* **VRAM**: GPU memory used by the loaded model (when Size > VRAM, the difference is CPU spill)
+
+Decision JSONL cases may include `"cache":{"min":0.95}` (and/or `"max"`) to assert
+the reused fraction of input tokens. Run ordered cache scenarios with
+`-concurrency 1 -k 0 -warmup 0`; missing telemetry or failed assertions fail the run
+in either scoring mode. For a cold-cache first case, unload the model before the
+run and use `-epochs 1`. CSV includes `cached_input_tokens` when the server reports it.
diff --git a/cmd/bench/bench.go b/cmd/bench/bench.go
index b77243626..56739257d 100644
--- a/cmd/bench/bench.go
+++ b/cmd/bench/bench.go
@@ -43,6 +43,10 @@ type flagOptions struct {
numCtx *int
openaiURL *string
apiKey *string
+ decisionFile *string
+ decisionMode *string
+ decisionURL *string
+ concurrency *int
}
type Metrics struct {
@@ -580,6 +584,9 @@ func OutputMetrics(w io.Writer, format string, metrics []Metrics, verbose bool)
func BenchmarkModel(fOpt flagOptions) error {
models := strings.Split(*fOpt.models, ",")
useOpenAI := fOpt.openaiURL != nil && *fOpt.openaiURL != ""
+ if fOpt.decisionFile != nil && *fOpt.decisionFile != "" {
+ return benchmarkDecision(fOpt, models, os.Stdout)
+ }
var out io.Writer = os.Stdout
if fOpt.outputFile != nil && *fOpt.outputFile != "" {
@@ -838,7 +845,7 @@ func BenchmarkModel(fOpt flagOptions) error {
return nil
}
-func unloadModel(client *api.Client, model string, timeout int) {
+func unloadModel(client *api.Client, model string, timeout int) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
defer cancel()
@@ -847,7 +854,7 @@ func unloadModel(client *api.Client, model string, timeout int) {
Model: model,
KeepAlive: &zero,
}
- _ = client.Generate(ctx, req, func(resp api.GenerateResponse) error {
+ return client.Generate(ctx, req, func(resp api.GenerateResponse) error {
return nil
})
}
@@ -1255,6 +1262,10 @@ func main() {
numCtx: flag.Int("num-ctx", 0, "Context size (0 = server default)"),
openaiURL: flag.String("openai", "", "OpenAI-compatible API base URL (e.g. http://localhost:11434/v1)"),
apiKey: flag.String("api-key", "", "API key for OpenAI endpoint (default: OPENAI_API_KEY env)"),
+ decisionURL: flag.String("decision-url", "", "External System One endpoint (server manages model loading)"),
+ decisionFile: flag.String("decision", "", "Decision JSONL corpus for /v1/systemone (instead of chat)"),
+ decisionMode: flag.String("decision-mode", "score", "Decision label policy: score reports accuracy; regression requires 100%"),
+ concurrency: flag.Int("concurrency", 1, "Maximum in-flight requests (currently requires -decision; 1 = serial)"),
}
flag.Usage = func() {
@@ -1269,6 +1280,22 @@ func main() {
fmt.Fprintf(os.Stderr, " bench -model gemma3 -openai http://localhost:11434/v1\n")
}
flag.Parse()
+ if *fOpt.decisionFile != "" {
+ flag.Visit(func(f *flag.Flag) {
+ switch f.Name {
+ case "p", "max-tokens", "temperature", "seed", "api-key":
+ fmt.Fprintf(os.Stderr, "ERROR: -%s does not apply to -decision\n", f.Name)
+ os.Exit(1)
+ }
+ })
+ } else {
+ flag.Visit(func(f *flag.Flag) {
+ if f.Name == "concurrency" || f.Name == "decision-mode" || f.Name == "decision-url" {
+ fmt.Fprintf(os.Stderr, "ERROR: -%s requires -decision\n", f.Name)
+ os.Exit(1)
+ }
+ })
+ }
if !slices.Contains([]string{"benchstat", "csv"}, *fOpt.format) {
fmt.Fprintf(os.Stderr, "ERROR: Unknown format '%s'\n", *fOpt.format)
@@ -1278,8 +1305,11 @@ func main() {
if len(*fOpt.models) == 0 {
fmt.Fprintf(os.Stderr, "ERROR: No model(s) specified to benchmark.\n")
flag.Usage()
- return
+ os.Exit(1)
}
- BenchmarkModel(fOpt)
+ if err := BenchmarkModel(fOpt); err != nil {
+ fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
+ os.Exit(1)
+ }
}
diff --git a/cmd/bench/decision.go b/cmd/bench/decision.go
new file mode 100644
index 000000000..15449ca37
--- /dev/null
+++ b/cmd/bench/decision.go
@@ -0,0 +1,307 @@
+package main
+
+import (
+ "bufio"
+ "context"
+ "encoding/csv"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "math"
+ "net/url"
+ "os"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/envconfig"
+ "github.com/ollama/ollama/internal/decisiontest"
+)
+
+type decisionSample struct {
+ Case decisiontest.Case
+ Epoch int
+ Response decisiontest.Response
+ Duration time.Duration
+ Wrong []string
+ Err error
+}
+
+func benchmarkDecision(opts flagOptions, models []string, out io.Writer) error {
+ if *opts.openaiURL != "" || *opts.imageFile != "" || *opts.promptTokens != 0 || *opts.numCtx != 0 {
+ return fmt.Errorf("-decision cannot be combined with -openai, -image, -prompt-tokens, or -num-ctx; put images in the corpus")
+ }
+ if *opts.epochs < 1 || *opts.warmup < 0 || *opts.timeout <= 0 || *opts.concurrency < 1 {
+ return fmt.Errorf("decision benchmark requires positive epochs, timeout, concurrency and nonnegative warmup")
+ }
+ if *opts.keepAlive > 0 && *opts.concurrency > 1 {
+ return fmt.Errorf("cold-load measurements (-k > 0) require -concurrency 1")
+ }
+ for _, name := range models {
+ if strings.TrimSpace(name) == "" {
+ return fmt.Errorf("empty model name")
+ }
+ }
+ if opts.decisionURL != nil && *opts.decisionURL != "" {
+ endpoint, err := url.Parse(*opts.decisionURL)
+ if err != nil || endpoint.Host == "" || endpoint.Scheme != "http" && endpoint.Scheme != "https" {
+ return fmt.Errorf("invalid -decision-url")
+ }
+ if *opts.keepAlive > 0 {
+ return fmt.Errorf("-decision-url does not support Ollama model unloads (-k > 0)")
+ }
+ }
+ mode, err := decisiontest.Mode(*opts.decisionMode)
+ if err != nil {
+ return err
+ }
+ corpus, err := decisiontest.Load(*opts.decisionFile)
+ if err != nil {
+ return err
+ }
+ for _, c := range corpus.Cases {
+ if c.Cache != nil && (*opts.concurrency != 1 || *opts.keepAlive > 0 || *opts.warmup != 0) {
+ return fmt.Errorf("cache assertions require ordered warm requests: -concurrency 1 -k 0 -warmup 0")
+ }
+ }
+ if *opts.epochs > math.MaxInt/len(corpus.Cases) {
+ return fmt.Errorf("epochs times corpus length exceeds the maximum request count")
+ }
+ if opts.outputFile != nil && *opts.outputFile != "" {
+ // Check inode identity too: a symlink or hardlink must not destroy input.
+ if err := checkDecisionOutput(*opts.decisionFile, *opts.outputFile, corpus); err != nil {
+ return err
+ }
+ f, err := os.Create(*opts.outputFile)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ out = f
+ }
+ client, err := api.ClientFromEnvironment()
+ if err != nil {
+ return err
+ }
+ buffered := bufio.NewWriter(out)
+ out = buffered
+ var csvOut *csv.Writer
+ if *opts.format == "csv" {
+ csvOut = csv.NewWriter(out)
+ defer csvOut.Flush()
+ if err := csvOut.Write([]string{"model", "corpus_sha256", "dataset", "case", "epoch", "concurrency", "input_tokens", "output_tokens", "state_bytes", "questions", "options", "images", "image_bytes", "image_pixels", "latency_ns", "correct_questions", "correct_case", "error", "mismatches", "cached_input_tokens"}); err != nil {
+ return err
+ }
+ } else {
+ outputFormatHeader(out, *opts.format, *opts.verbose)
+ }
+ var failures []error
+ for _, name := range models {
+ name = strings.TrimSpace(name)
+ if err := benchmarkDecisionModel(opts, client, name, corpus, mode, out, csvOut); err != nil {
+ failures = append(failures, err)
+ }
+ if opts.decisionURL != nil && *opts.decisionURL != "" {
+ continue
+ }
+ if err := unloadModel(client, name, *opts.timeout); err != nil {
+ failures = append(failures, fmt.Errorf("%s unload: %w", name, err))
+ break
+ }
+ }
+ if csvOut != nil {
+ csvOut.Flush()
+ failures = append(failures, csvOut.Error())
+ }
+ failures = append(failures, buffered.Flush())
+ return errors.Join(failures...)
+}
+
+func benchmarkDecisionModel(opts flagOptions, client *api.Client, name string, corpus decisiontest.Corpus, mode string, out io.Writer, csvOut *csv.Writer) error {
+ ctx, cancel := context.WithCancelCause(context.Background())
+ defer cancel(nil)
+ endpoint := envconfig.Host().JoinPath("v1/systemone").String()
+ if opts.decisionURL != nil && *opts.decisionURL != "" {
+ endpoint = *opts.decisionURL
+ }
+ keepAlive := benchmarkKeepAlive(opts)
+ one := func(index int) decisionSample {
+ c := corpus.Cases[index%len(corpus.Cases)]
+ if *opts.keepAlive > 0 {
+ // Include the first measured request: warmup or a previous run may
+ // have left the model loaded. Waiting for expiry alone is racy.
+ if err := unloadModel(client, name, *opts.timeout); err != nil {
+ return decisionSample{Case: c, Epoch: index / len(corpus.Cases), Err: fmt.Errorf("unload before cold request: %w", err)}
+ }
+ }
+ req := c.Request
+ req.Model, req.KeepAlive = name, keepAlive
+ requestCtx, cancel := context.WithTimeout(ctx, time.Duration(*opts.timeout)*time.Second)
+ defer cancel()
+ response, duration, err := decisiontest.Do(requestCtx, endpoint, req)
+ if err == nil {
+ err = c.CheckCache(response)
+ }
+ s := decisionSample{Case: c, Epoch: index / len(corpus.Cases), Response: response, Duration: duration, Err: err}
+ if err == nil {
+ s.Wrong = c.Mismatches(response)
+ }
+ return s
+ }
+ for i := range *opts.warmup {
+ if sample := one(i); sample.Err != nil {
+ return fmt.Errorf("%s warmup: %w", name, sample.Err)
+ }
+ }
+ if csvOut == nil {
+ fmt.Fprintf(out, "# API: systemone | Corpus: %s | SHA256: %s | Mode: %s | Concurrency: %d | Cache: unchanged corpus replay\n", *opts.decisionFile, corpus.SHA256, mode, *opts.concurrency)
+ }
+ // Workers submit their next request immediately after a response. This is a
+ // closed-loop concurrency test, not an offered-rate/open-loop load generator.
+ total := len(corpus.Cases) * *opts.epochs
+ concurrency := min(*opts.concurrency, total)
+ results := make(chan decisionSample, concurrency)
+ var next atomic.Int64
+ var workers sync.WaitGroup
+ start := time.Now()
+ for range concurrency {
+ workers.Go(func() {
+ for ctx.Err() == nil {
+ i := int(next.Add(1)) - 1
+ if i >= total {
+ return
+ }
+ sample := one(i)
+ results <- sample
+ if sample.Err != nil {
+ cancel(sample.Err)
+ return
+ }
+ if *opts.keepAlive > 0 && i+1 < total {
+ time.Sleep(time.Duration(*opts.keepAlive*float64(time.Second)) + 200*time.Millisecond)
+ }
+ }
+ })
+ }
+ go func() { workers.Wait(); close(results) }()
+ var samples []decisionSample
+ for s := range results {
+ samples = append(samples, s)
+ }
+ elapsed := time.Since(start)
+ wrongCases := 0
+ for _, s := range samples {
+ if len(s.Wrong) > 0 {
+ wrongCases++
+ }
+ if csvOut != nil {
+ var message string
+ correct := s.Case.Request.Questions.Len() - len(s.Wrong)
+ if s.Err != nil {
+ message, correct = s.Err.Error(), 0
+ }
+ row := []string{name, corpus.SHA256, s.Case.Dataset, s.Case.ID, strconv.Itoa(s.Epoch), strconv.Itoa(*opts.concurrency), strconv.Itoa(s.Response.Usage.InputTokens), strconv.Itoa(s.Response.Usage.OutputTokens), strconv.Itoa(len(s.Case.Request.State)), strconv.Itoa(s.Case.Request.Questions.Len()), strconv.Itoa(s.Case.Options()), strconv.Itoa(len(s.Case.Request.Images)), strconv.Itoa(s.Case.ImageBytes), strconv.FormatInt(s.Case.ImagePixels, 10), strconv.FormatInt(s.Duration.Nanoseconds(), 10), strconv.Itoa(correct), strconv.FormatBool(s.Err == nil && len(s.Wrong) == 0), message}
+ cached := ""
+ if s.Response.PromptEvalCachedCount != nil {
+ cached = strconv.Itoa(*s.Response.PromptEvalCachedCount)
+ }
+ row = append(row, strings.Join(s.Wrong, "; "), cached)
+ if err := csvOut.Write(row); err != nil {
+ return err
+ }
+ } else if s.Err == nil {
+ step := fmt.Sprintf("decision/case=%s/input=%d/questions=%d/images=%d/concurrency=%d", url.PathEscape(s.Case.ID), s.Response.Usage.InputTokens, s.Case.Request.Questions.Len(), len(s.Case.Request.Images), *opts.concurrency)
+ OutputMetrics(out, *opts.format, []Metrics{{Model: name, Step: step + "/metric=http", Count: 1, Duration: s.Duration}}, *opts.verbose)
+ }
+ }
+ writeDecisionSummary(os.Stderr, name, samples, total, elapsed)
+ if err := context.Cause(ctx); err != nil {
+ return fmt.Errorf("%s: %w", name, err)
+ }
+ if mode == "regression" && wrongCases > 0 {
+ return fmt.Errorf("%s: %d/%d cases failed", name, wrongCases, total)
+ }
+ return nil
+}
+
+func writeDecisionSummary(out io.Writer, model string, samples []decisionSample, total int, elapsed time.Duration) {
+ type accuracy struct {
+ decisiontest.Tally
+ CaseAccuracy float64 `json:"case_accuracy_pct"`
+ QuestionAccuracy float64 `json:"question_accuracy_pct"`
+ }
+ type summary struct {
+ accuracy
+ Model string `json:"model"`
+ Expected int `json:"expected_requests"`
+ Complete bool `json:"complete"`
+ RequestsPerSecond float64 `json:"requests_per_second"`
+ QuestionsPerSecond float64 `json:"questions_per_second"`
+ P50 float64 `json:"p50_ms"`
+ P95 float64 `json:"p95_ms"`
+ P99 float64 `json:"p99_ms"`
+ Datasets map[string]accuracy `json:"datasets"`
+ }
+ s := summary{Model: model, Expected: total, Datasets: make(map[string]accuracy)}
+ var durations []time.Duration
+ var questions int
+ for _, sample := range samples {
+ s.Tally.Add(sample.Case, sample.Wrong, sample.Err)
+ d := s.Datasets[sample.Case.Dataset]
+ d.Tally.Add(sample.Case, sample.Wrong, sample.Err)
+ d.CaseAccuracy, d.QuestionAccuracy = d.Tally.CaseAccuracy(), d.Tally.QuestionAccuracy()
+ s.Datasets[sample.Case.Dataset] = d
+ if sample.Err != nil {
+ continue
+ }
+ durations = append(durations, sample.Duration)
+ questions += len(sample.Case.Expected)
+ }
+ s.Complete = len(samples) == total && s.Errors == 0
+ s.CaseAccuracy, s.QuestionAccuracy = s.Tally.CaseAccuracy(), s.Tally.QuestionAccuracy()
+ if elapsed > 0 {
+ s.RequestsPerSecond = float64(len(durations)) / elapsed.Seconds()
+ s.QuestionsPerSecond = float64(questions) / elapsed.Seconds()
+ }
+ slices.Sort(durations)
+ if len(durations) > 0 {
+ percentile := func(p float64) float64 {
+ return float64(durations[int(math.Ceil(p*float64(len(durations))))-1]) / float64(time.Millisecond)
+ }
+ s.P50, s.P95, s.P99 = percentile(.5), percentile(.95), percentile(.99)
+ }
+ data, _ := json.Marshal(s)
+ fmt.Fprintln(out, string(data))
+}
+
+func checkDecisionOutput(input, output string, corpus decisiontest.Corpus) error {
+ dest, err := os.Stat(output)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ paths := []string{input}
+ for _, c := range corpus.Cases {
+ for _, image := range c.ImageFiles {
+ paths = append(paths, filepath.Join(filepath.Dir(input), image))
+ }
+ }
+ for _, path := range paths {
+ source, err := os.Stat(path)
+ if err != nil {
+ return err
+ }
+ if os.SameFile(source, dest) {
+ return fmt.Errorf("output would overwrite decision input %s", path)
+ }
+ }
+ return nil
+}
diff --git a/cmd/bench/decision_test.go b/cmd/bench/decision_test.go
new file mode 100644
index 000000000..1dab6d968
--- /dev/null
+++ b/cmd/bench/decision_test.go
@@ -0,0 +1,307 @@
+package main
+
+import (
+ "bytes"
+ "encoding/csv"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/decision"
+ "github.com/ollama/ollama/internal/decisiontest"
+)
+
+func TestDecisionBenchmarkPolicies(t *testing.T) {
+ for _, test := range []struct {
+ name, mode, answer string
+ wantErr bool
+ cold bool
+ unloadStatus int
+ }{
+ {"correct regression", "regression", `"noul":1`, false, false, 0},
+ {"wrong regression", "regression", `"noul":0`, true, false, 0},
+ {"wrong score", "score", `"noul":0`, false, false, 0},
+ {"broken score response", "score", `"noul":null`, true, false, 0},
+ {"cold after warmup", "regression", `"noul":1`, false, true, 0},
+ {"unload failure", "score", `"noul":1`, true, false, http.StatusInternalServerError},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ var requests, unloads atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/generate":
+ unloads.Add(1)
+ if test.unloadStatus != 0 {
+ http.Error(w, "unload failed", test.unloadStatus)
+ return
+ }
+ writeJSON(w, api.GenerateResponse{Done: true})
+ case "/v1/systemone":
+ requests.Add(1)
+ if test.cold && unloads.Load() != requests.Load() {
+ t.Error("cold request was not preceded by an unload")
+ }
+ var req decision.Request
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ t.Error(err)
+ }
+ if string(req.State) != `"An ordinary message."` || req.Model != "test-model" {
+ t.Errorf("request changed: %+v", req)
+ }
+ if !test.cold && req.KeepAlive != nil {
+ t.Error("warm request overrode the server keep_alive default")
+ }
+ fmt.Fprintf(w, `{"model":"test-model","usage":{"input_tokens":42,"output_tokens":0},"answers":{"result":{"type":"noul",%s}}}`, test.answer)
+ default:
+ t.Errorf("unexpected endpoint %s", r.URL.Path)
+ }
+ }))
+ defer server.Close()
+ t.Setenv("OLLAMA_HOST", server.URL)
+ path := filepath.Join(t.TempDir(), "cases.jsonl")
+ if err := os.WriteFile(path, []byte(`{"id":"test,case","dataset":"test","request":{"state":"An ordinary message.","questions":{"result":{"type":"noul","instructions":"Is this a message?"}}},"expected":{"result":{"noul":true}}}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ opts := createTestFlagOptions()
+ concurrency := 1
+ opts.decisionFile, opts.decisionMode, opts.concurrency = &path, &test.mode, &concurrency
+ *opts.format, *opts.epochs = "csv", 2
+ if test.cold {
+ *opts.keepAlive, *opts.epochs, *opts.warmup = .001, 1, 1
+ }
+ var out bytes.Buffer
+ err := benchmarkDecision(opts, []string{"test-model"}, &out)
+ if (err != nil) != test.wantErr {
+ t.Fatalf("error=%v, wantErr=%v", err, test.wantErr)
+ }
+ rows, err := csv.NewReader(&out).ReadAll()
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantUnloads := int32(1)
+ if test.cold {
+ wantUnloads += requests.Load()
+ }
+ if unloads.Load() != wantUnloads || len(rows) != int(requests.Load())-*opts.warmup+1 {
+ t.Fatalf("unloads=%d requests=%d csv rows=%d", unloads.Load(), requests.Load(), len(rows))
+ }
+ if rows[1][3] != "test,case" || rows[1][6] != "42" {
+ t.Fatalf("missing per-request metadata or CSV escaping: %v", rows[1])
+ }
+ if test.answer == `"noul":0` && (rows[1][17] != "" || len(rows[1]) <= 18 || rows[1][18] == "") {
+ t.Fatalf("label mismatch conflated with request error: %v", rows[1])
+ }
+ })
+ }
+}
+
+func TestDecisionBenchmarkOutputError(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/api/generate" {
+ writeJSON(w, api.GenerateResponse{Done: true})
+ return
+ }
+ fmt.Fprint(w, `{"model":"test-model","usage":{"input_tokens":20,"output_tokens":0},"answers":{"result":{"type":"noul","noul":1}}}`)
+ }))
+ t.Cleanup(server.Close)
+ t.Setenv("OLLAMA_HOST", server.URL)
+ path := filepath.Join(t.TempDir(), "cases.jsonl")
+ if err := os.WriteFile(path, []byte(`{"id":"one","dataset":"test","request":{"state":"Message.","questions":{"result":{"type":"noul"}}},"expected":{"result":{"noul":true}}}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ output, err := os.CreateTemp(t.TempDir(), "closed-output")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := output.Close(); err != nil {
+ t.Fatal(err)
+ }
+ for _, format := range []string{"csv", "benchstat"} {
+ t.Run(format, func(t *testing.T) {
+ opts := createTestFlagOptions()
+ concurrency, mode := 1, "score"
+ opts.decisionFile, opts.decisionMode, opts.concurrency = &path, &mode, &concurrency
+ *opts.format, *opts.epochs = format, 1
+ if err := benchmarkDecision(opts, []string{"test-model"}, output); !errors.Is(err, os.ErrClosed) {
+ t.Fatalf("got %v, want output write error", err)
+ }
+ })
+ }
+}
+
+func TestDecisionOutputPreservesInputs(t *testing.T) {
+ dir := t.TempDir()
+ input := filepath.Join(dir, "cases.jsonl")
+ data := []byte(`{"id":"one","dataset":"test","request":{"state":"Message.","questions":{"result":{"type":"noul"}}},"expected":{"result":{"noul":true}}}`)
+ if err := os.WriteFile(input, data, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ alias := filepath.Join(dir, "alias")
+ if err := os.Link(input, alias); err != nil {
+ t.Fatal(err)
+ }
+ for _, output := range []string{input, alias} {
+ opts := createTestFlagOptions()
+ mode, concurrency := "score", 1
+ opts.decisionFile, opts.decisionMode, opts.concurrency, opts.outputFile = &input, &mode, &concurrency, &output
+ if err := BenchmarkModel(opts); err == nil || !strings.Contains(err.Error(), "overwrite") {
+ t.Fatalf("output %s: got %v, want overwrite error", output, err)
+ }
+ got, err := os.ReadFile(input)
+ if err != nil || !bytes.Equal(got, data) {
+ t.Fatalf("input changed: %s, %v", got, err)
+ }
+ }
+}
+
+func TestDecisionSummaryPartialRun(t *testing.T) {
+ c := decisiontest.Case{Dataset: "a", Expected: map[string]decisiontest.Expected{"one": {}, "two": {}}}
+ samples := []decisionSample{
+ {Case: c, Duration: 10 * time.Millisecond},
+ {Case: c, Duration: 30 * time.Millisecond, Wrong: []string{"two"}},
+ {Case: decisiontest.Case{Dataset: "b", Expected: map[string]decisiontest.Expected{"one": {}}}, Err: errors.New("HTTP 500")},
+ }
+ var out bytes.Buffer
+ writeDecisionSummary(&out, "test", samples, 5, time.Second)
+ var got struct {
+ decisiontest.Tally
+ Expected int `json:"expected_requests"`
+ Complete bool `json:"complete"`
+ QuestionAccuracy float64 `json:"question_accuracy_pct"`
+ P50 float64 `json:"p50_ms"`
+ P95 float64 `json:"p95_ms"`
+ Rate float64 `json:"requests_per_second"`
+ QuestionsRate float64 `json:"questions_per_second"`
+ Datasets map[string]decisiontest.Tally `json:"datasets"`
+ }
+ if err := json.Unmarshal(out.Bytes(), &got); err != nil {
+ t.Fatal(err)
+ }
+ if got.Complete || got.Expected != 5 || got.Requests != 3 || got.Errors != 1 || got.Questions != 5 || got.CorrectQuestions != 3 || got.QuestionAccuracy != 60 || got.P50 != 10 || got.P95 != 30 || got.Rate != 2 || got.QuestionsRate != 4 || got.Datasets["a"].CorrectCases != 1 || got.Datasets["b"].Errors != 1 {
+ t.Fatalf("incorrect partial-run summary: %s", out.String())
+ }
+}
+
+func TestDecisionBenchmarkConcurrency(t *testing.T) {
+ var requests atomic.Int32
+ both := make(chan struct{})
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/generate":
+ writeJSON(w, api.GenerateResponse{Done: true})
+ case "/v1/systemone":
+ _, _ = io.Copy(io.Discard, r.Body)
+ if requests.Add(1) == 2 {
+ close(both)
+ }
+ select {
+ case <-both:
+ case <-r.Context().Done():
+ return
+ case <-t.Context().Done():
+ return
+ }
+ fmt.Fprint(w, `{"model":"test-model","usage":{"input_tokens":20,"output_tokens":0},"answers":{"result":{"type":"noul","noul":1}}}`)
+ }
+ }))
+ t.Cleanup(server.Close)
+ t.Setenv("OLLAMA_HOST", server.URL)
+ path := filepath.Join(t.TempDir(), "cases.jsonl")
+ if err := os.WriteFile(path, []byte(`{"id":"one","dataset":"test","request":{"state":"Message.","questions":{"result":{"type":"noul"}}},"expected":{"result":{"noul":true}}}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ opts := createTestFlagOptions()
+ concurrency, mode := 2, "regression"
+ opts.decisionFile, opts.decisionMode, opts.concurrency = &path, &mode, &concurrency
+ *opts.epochs, *opts.timeout = 4, 5
+ var out bytes.Buffer
+ if err := benchmarkDecision(opts, []string{"test-model"}, &out); err != nil {
+ t.Fatal(err)
+ }
+ if requests.Load() != 4 || strings.Count(out.String(), "step=decision/") != 4 {
+ t.Fatalf("requests=%d output=%s", requests.Load(), out.String())
+ }
+}
+
+func TestDecisionBenchmarkCancelsPeers(t *testing.T) {
+ var requests atomic.Int32
+ started, canceled := make(chan struct{}), make(chan struct{})
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/generate":
+ writeJSON(w, api.GenerateResponse{Done: true})
+ case "/v1/systemone":
+ _, _ = io.Copy(io.Discard, r.Body)
+ if requests.Add(1) == 1 {
+ close(started)
+ select {
+ case <-r.Context().Done():
+ close(canceled)
+ case <-t.Context().Done():
+ }
+ return
+ }
+ <-started
+ http.Error(w, "runner failed", http.StatusInternalServerError)
+ }
+ }))
+ t.Cleanup(server.Close)
+ t.Setenv("OLLAMA_HOST", server.URL)
+ path := filepath.Join(t.TempDir(), "cases.jsonl")
+ if err := os.WriteFile(path, []byte(`{"id":"one","dataset":"test","request":{"state":"Message.","questions":{"result":{"type":"noul"}}},"expected":{"result":{"noul":true}}}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ opts := createTestFlagOptions()
+ concurrency, mode := 2, "score"
+ opts.decisionFile, opts.decisionMode, opts.concurrency = &path, &mode, &concurrency
+ *opts.epochs, *opts.timeout = 100, 5
+ var out bytes.Buffer
+ err := benchmarkDecision(opts, []string{"test-model"}, &out)
+ if err == nil || !strings.Contains(err.Error(), "runner failed") || requests.Load() != 2 {
+ t.Fatalf("error=%v requests=%d, want original failure and only two requests", err, requests.Load())
+ }
+ select {
+ case <-canceled:
+ case <-time.After(5 * time.Second):
+ t.Fatal("in-flight peer was not canceled")
+ }
+}
+
+func TestDecisionBenchmarkCacheChecks(t *testing.T) {
+ for _, cached := range []int{0, 42} {
+ t.Run(fmt.Sprint(cached), func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/systemone" {
+ t.Errorf("external benchmark attempted %s", r.URL.Path)
+ http.NotFound(w, r)
+ return
+ }
+ fmt.Fprintf(w, `{"model":"test-model","prompt_eval_cached_count":%d,"usage":{"input_tokens":42,"output_tokens":0},"answers":{"result":{"type":"noul","noul":1}}}`, cached)
+ }))
+ defer server.Close()
+ path := filepath.Join(t.TempDir(), "cases.jsonl")
+ if err := os.WriteFile(path, []byte(`{"id":"repeat","dataset":"test","request":{"state":"Message.","questions":{"result":{"type":"noul"}}},"expected":{"result":{"noul":true}},"cache":{"min":1}}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ opts := createTestFlagOptions()
+ mode, concurrency, endpoint := "score", 1, server.URL+"/systemone"
+ opts.decisionFile, opts.decisionMode, opts.concurrency, opts.decisionURL = &path, &mode, &concurrency, &endpoint
+ *opts.epochs, *opts.warmup, *opts.keepAlive = 1, 0, 0
+ var out bytes.Buffer
+ err := benchmarkDecision(opts, []string{"test-model"}, &out)
+ if (err != nil) != (cached == 0) {
+ t.Fatalf("benchmark error=%v, cached=%d", err, cached)
+ }
+ })
+ }
+}
diff --git a/integration/reg_groups_test.go b/integration/reg_groups_test.go
index 67c8304b5..32f92d3c9 100644
--- a/integration/reg_groups_test.go
+++ b/integration/reg_groups_test.go
@@ -40,6 +40,7 @@ func TestAPI(t *testing.T) {
"generate-logprobs",
"chat-logprobs",
"system-one",
+ "system-one-vision",
)
}
diff --git a/integration/reg_release_test.go b/integration/reg_release_test.go
index b87f04e4c..dba576c35 100644
--- a/integration/reg_release_test.go
+++ b/integration/reg_release_test.go
@@ -75,6 +75,7 @@ func init() {
registerIntegrationCases(
integrationTestCase("api-generate", smol, runAPIGenerate),
integrationTestCase("api-chat", smol, runAPIChat),
+ integrationModelTestCase("system-one-vision", defaultTestModel("clef-flash:9b"), runAPISystemOneVision),
integrationTestCase("api-list-models", "", runAPIListModels),
integrationTestCase("api-show-model", "llama3.2", runAPIShowModel),
integrationTestCase("generate-logprobs", smol, runAPIGenerateLogprobs),
diff --git a/integration/systemone_test.go b/integration/systemone_test.go
index 2ad6b486c..bdbb4880f 100644
--- a/integration/systemone_test.go
+++ b/integration/systemone_test.go
@@ -3,198 +3,182 @@
package integration
import (
- "bytes"
"context"
"encoding/json"
"errors"
"fmt"
- "io"
- "math"
- "net/http"
+ "maps"
+ "os"
"slices"
+ "strings"
"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/internal/decisiontest"
"github.com/ollama/ollama/types/model"
)
-func postSystemOne(ctx context.Context, endpoint string, input any) ([]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
+func runAPISystemOne(t *testing.T, modelName string) {
+ path := os.Getenv("OLLAMA_TEST_DECISION_FILE")
+ if path == "" {
+ path = "../.cache/decision-data/regression.jsonl"
}
- req.Header.Set("Content-Type", "application/json")
- resp, err := http.DefaultClient.Do(req)
- if err != nil {
- return nil, 0, err
+ runDecisionCorpus(t, modelName, path)
+}
+
+func runAPISystemOneVision(t *testing.T, modelName string) {
+ abbeyRoad, docs, _ := decodeTestImages(t)
+ var cases []decisiontest.Case
+ for _, fixture := range []struct {
+ name string
+ images []api.ImageData
+ choice string
+ laptop bool
+ }{
+ {"road", []api.ImageData{abbeyRoad}, "crossing", false},
+ {"desk", []api.ImageData{docs}, "working", true},
+ {"road_then_desk", []api.ImageData{abbeyRoad, docs}, "crossing", false},
+ {"desk_then_road", []api.ImageData{docs, abbeyRoad}, "working", true},
+ } {
+ var req decision.Request
+ if err := json.Unmarshal([]byte(`{
+ "state":"Inspect the first attached image.",
+ "questions":{
+ "activity":{"type":"choice","instructions":"What are the animals doing in the first image?","criteria":{"crossing":"Walking across a road","working":"Working or resting at a desk"}},
+ "laptop":{"type":"noul","instructions":"Is there a laptop computer in the first image?","criteria":{}}
+ }
+ }`), &req); err != nil {
+ t.Fatal(err)
+ }
+ req.Images = fixture.images
+ cases = append(cases, decisiontest.Case{ID: fixture.name, Dataset: "ollama-vision", Request: req, Expected: map[string]decisiontest.Expected{
+ "activity": {Choice: &fixture.choice}, "laptop": {Noul: &fixture.laptop},
+ }})
}
- defer resp.Body.Close()
- body, err = io.ReadAll(io.LimitReader(resp.Body, 1<<20))
- return body, resp.StatusCode, err
+ runDecisionCases(t, modelName, decisiontest.Corpus{Cases: cases})
}
-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 {
+func runDecisionCorpus(t *testing.T, modelName, path string) {
+ if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
+ t.Skipf("decision corpus unavailable: %s", path)
+ } else if err != nil {
t.Fatal(err)
}
- info, err := client.Show(ctx, &api.ShowRequest{Model: modelName})
+ corpus, err := decisiontest.Load(path)
if err != nil {
t.Fatal(err)
}
- if !slices.Contains(info.Capabilities, model.CapabilityDecision) {
- t.Fatalf("model %q does not declare the decision capability", modelName)
- }
- isKev := info.Details.Family == "kev"
+ t.Logf("decision corpus=%s sha256=%s", path, corpus.SHA256)
+ runDecisionCases(t, modelName, corpus)
+}
- 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
+func runDecisionCases(t *testing.T, modelName string, corpus decisiontest.Corpus) {
+ ctx := t.Context()
+ client, endpoint, cleanup := InitServerConnection(ctx, t)
+ defer cleanup()
+ loadCtx, cancel := context.WithTimeout(ctx, apiTestTimeout)
+ defer cancel()
+ requireCapability(loadCtx, t, client, modelName, model.CapabilityDecision)
+ skipIfModelTooLargeForVRAM(loadCtx, t, client, modelName)
+ if corpus.HasImages() {
+ requireCapability(loadCtx, t, client, modelName, model.CapabilityVision)
}
- score := func(t *testing.T, req decision.Request) response {
+ endpoint = "http://" + endpoint + "/v1/systemone"
+ score := func(t *testing.T, req decision.Request) decisiontest.Response {
t.Helper()
- body, status, err := postSystemOne(ctx, endpoint, req)
+ req.Model = modelName
+ requestCtx, cancel := context.WithTimeout(ctx, apiTestTimeout)
+ defer cancel()
+ result, _, err := decisiontest.Do(requestCtx, 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)
+ return result
+ }
+ var tally decisiontest.Tally
+ datasets := make(map[string]decisiontest.Tally)
+ t.Logf("decision regression cases=%d", len(corpus.Cases))
+ t.Run("corpus", func(t *testing.T) {
+ for _, c := range corpus.Cases {
+ t.Run(c.ID, func(t *testing.T) {
+ req := c.Request
+ req.Model = modelName
+ requestCtx, cancel := context.WithTimeout(t.Context(), apiTestTimeout)
+ defer cancel()
+ result, _, err := decisiontest.Do(requestCtx, endpoint, req)
+ var wrong []string
+ if err == nil {
+ err = c.CheckCache(result)
+ if err == nil {
+ wrong = c.Mismatches(result)
+ }
}
- sum += p
- }
- // 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)
- }
- }
- 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)
+ tally.Add(c, wrong, err)
+ d := datasets[c.Dataset]
+ d.Add(c, wrong, err)
+ datasets[c.Dataset] = d
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(wrong) == 0 {
+ return
+ }
+ t.Error(strings.Join(wrong, "; "))
+ })
}
- 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)
+ })
+ t.Logf("decision score: %s, expected cases=%d", tally, len(corpus.Cases))
+ for _, name := range slices.Sorted(maps.Keys(datasets)) {
+ t.Logf("decision dataset=%s: %s", name, datasets[name])
+ }
+ if t.Failed() {
+ return
+ }
+ input := corpus.Cases[0].Request
+ input.Questions = &decision.Questions{}
+ for _, c := range corpus.Cases {
+ for _, q := range c.Request.Questions.All() {
+ if _, ok := input.Questions.Get(q.Type); !ok {
+ input.Questions.Set(q.Type, q)
+ }
}
- 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)
+ // Cache/prefill shapes can shift BF16 probabilities slightly; choices
+ // must stay identical while numbers retain the existing 0.01 tolerance.
+ if diff := cmp.Diff(baseline.Answers, got.Answers, cmpopts.EquateApprox(0, .01)); diff != "" {
+ t.Errorf("answers changed (-baseline +got): %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.Errorf("input tokens changed: %d -> %d", baseline.Usage.InputTokens, got.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(fmt.Sprint(i), func(t *testing.T) { t.Parallel(); unchanged(t) })
}
})
t.Run("after_generation", func(t *testing.T) {
+ info, err := client.Show(ctx, &api.ShowRequest{Model: modelName})
+ if err != nil {
+ t.Fatal(err)
+ }
noStream := false
- err := client.Generate(ctx, &api.GenerateRequest{
+ 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 {
+ if !errors.As(err, &status) || status.StatusCode != 400 {
t.Fatalf("decision-only generation: got %v, want HTTP 400", err)
}
} else if err != nil {
@@ -202,23 +186,16 @@ func runAPISystemOne(t *testing.T, modelName string) {
}
unchanged(t)
})
-
- t.Run("invalid_state", func(t *testing.T) {
- 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)
- }
- if status != http.StatusBadRequest {
- t.Fatalf("got HTTP %d, want %d: %s", status, http.StatusBadRequest, body)
+ t.Run("invalid_request", func(t *testing.T) {
+ invalid := input
+ invalid.Model = modelName
+ invalid.Questions = nil
+ requestCtx, cancel := context.WithTimeout(ctx, apiTestTimeout)
+ defer cancel()
+ _, _, err := decisiontest.Do(requestCtx, endpoint, invalid)
+ var status api.StatusError
+ if !errors.As(err, &status) || status.StatusCode != 400 {
+ t.Fatalf("missing questions: got %v, want HTTP 400", err)
}
unchanged(t)
})
diff --git a/internal/decisiontest/corpus.go b/internal/decisiontest/corpus.go
new file mode 100644
index 000000000..923e6ed65
--- /dev/null
+++ b/internal/decisiontest/corpus.go
@@ -0,0 +1,257 @@
+// Package decisiontest reads and scores external System One evaluation corpora.
+package decisiontest
+
+import (
+ "bufio"
+ "bytes"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "image"
+ _ "image/jpeg"
+ _ "image/png"
+ "io"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ "github.com/ollama/ollama/decision"
+ _ "golang.org/x/image/webp"
+)
+
+type Case struct {
+ ID string `json:"id"`
+ Dataset string `json:"dataset"`
+ Request decision.Request `json:"request"`
+ ImageFiles []string `json:"image_files,omitempty"`
+ Expected map[string]Expected `json:"expected"`
+ Cache *CacheExpectation `json:"cache,omitempty"`
+ ImageBytes int `json:"-"`
+ ImagePixels int64 `json:"-"`
+}
+
+// CacheExpectation bounds the fraction of input tokens reused in an ordered run.
+// Omitted telemetry is an error whenever a case requests a cache assertion.
+type CacheExpectation struct {
+ Min *float64 `json:"min,omitempty"`
+ Max *float64 `json:"max,omitempty"`
+}
+
+func (c Case) CheckCache(response Response) error {
+ if c.Cache == nil {
+ return nil
+ }
+ n := response.PromptEvalCachedCount
+ if n == nil {
+ return fmt.Errorf("cache assertion requires prompt_eval_cached_count")
+ }
+ ratio := float64(*n) / float64(response.Usage.InputTokens)
+ if c.Cache.Min != nil && ratio < *c.Cache.Min || c.Cache.Max != nil && ratio > *c.Cache.Max {
+ return fmt.Errorf("cache assertion failed: reused %d/%d input tokens", *n, response.Usage.InputTokens)
+ }
+ return nil
+}
+
+type Expected struct {
+ Choice *string `json:"choice,omitempty"`
+ Noul *bool `json:"noul,omitempty"`
+ Min *float64 `json:"min,omitempty"`
+ Max *float64 `json:"max,omitempty"`
+ Level *int `json:"level,omitempty"`
+}
+
+type Corpus struct {
+ Cases []Case
+ SHA256 string
+}
+
+// Load resolves image_files relative to the JSONL file, before any timed requests.
+// The digest covers both the JSONL bytes and the referenced image contents.
+func Load(path string) (Corpus, error) {
+ var corpus Corpus
+ f, err := os.Open(path)
+ if err != nil {
+ return corpus, err
+ }
+ defer f.Close()
+ hash := sha256.New()
+ scanner := bufio.NewScanner(io.TeeReader(f, hash))
+ scanner.Buffer(make([]byte, 4096), 16<<20)
+ ids := make(map[string]bool)
+ for line := 1; scanner.Scan(); line++ {
+ if len(bytes.TrimSpace(scanner.Bytes())) == 0 {
+ continue
+ }
+ var c Case
+ decoder := json.NewDecoder(bytes.NewReader(scanner.Bytes()))
+ decoder.DisallowUnknownFields()
+ if err := decoder.Decode(&c); err != nil {
+ return corpus, fmt.Errorf("%s:%d: %w", path, line, err)
+ }
+ if err := decoder.Decode(new(any)); err != io.EOF {
+ return corpus, fmt.Errorf("%s:%d: expected one JSON object", path, line)
+ }
+ if c.ID == "" || c.Dataset == "" || ids[c.ID] {
+ return corpus, fmt.Errorf("%s:%d: require dataset and unique nonempty id", path, line)
+ }
+ ids[c.ID] = true
+ if err := c.validate(); err != nil {
+ return corpus, fmt.Errorf("%s:%d (%s): %w", path, line, c.ID, err)
+ }
+ corpus.Cases = append(corpus.Cases, c)
+ }
+ if err := scanner.Err(); err != nil {
+ return corpus, fmt.Errorf("%s: %w", path, err)
+ }
+ if len(corpus.Cases) == 0 {
+ return corpus, fmt.Errorf("%s: empty decision corpus", path)
+ }
+ for i := range corpus.Cases {
+ c := &corpus.Cases[i]
+ for _, name := range c.ImageFiles {
+ if !filepath.IsLocal(name) {
+ return corpus, fmt.Errorf("%s: image path must be relative to the corpus: %q", c.ID, name)
+ }
+ data, err := os.ReadFile(filepath.Join(filepath.Dir(path), name))
+ if err != nil {
+ return corpus, fmt.Errorf("%s: %w", c.ID, err)
+ }
+ c.Request.Images = append(c.Request.Images, data)
+ // Frame each image so different file boundaries cannot hash alike.
+ _, _ = fmt.Fprintf(hash, "\x00%d:", len(data))
+ _, _ = hash.Write(data)
+ }
+ for _, data := range c.Request.Images {
+ config, _, err := image.DecodeConfig(bytes.NewReader(data))
+ if err != nil {
+ return corpus, fmt.Errorf("%s: image: %w", c.ID, err)
+ }
+ c.ImageBytes += len(data)
+ c.ImagePixels += int64(config.Width) * int64(config.Height)
+ }
+ }
+ corpus.SHA256 = hex.EncodeToString(hash.Sum(nil))
+ return corpus, nil
+}
+
+func (c Case) validate() error {
+ if c.Cache != nil {
+ lo, hi := c.Cache.Min, c.Cache.Max
+ if lo == nil && hi == nil || lo != nil && (*lo < 0 || *lo > 1) || hi != nil && (*hi < 0 || *hi > 1) || lo != nil && hi != nil && *lo > *hi {
+ return fmt.Errorf("cache requires min and/or max fractions in [0,1], with min <= max")
+ }
+ }
+ req := c.Request
+ if req.Model != "" || req.KeepAlive != nil {
+ return fmt.Errorf("model and keep_alive belong to the test invocation, not the corpus")
+ }
+ // Validate the corpus, not a particular model's prompt schema. The server
+ // owns model-specific limits and accepted state/criteria values.
+ if len(req.State) == 0 || req.Questions.Len() == 0 {
+ return fmt.Errorf("request requires state and questions")
+ }
+ if len(c.Expected) != req.Questions.Len() {
+ return fmt.Errorf("require an expectation for every question")
+ }
+ for name, q := range req.Questions.All() {
+ want, ok := c.Expected[name]
+ if !ok {
+ return fmt.Errorf("missing expectation for %q", name)
+ }
+ keys := criteria(q)
+ valid := false
+ switch q.Type {
+ case "choice":
+ if want.Choice != nil {
+ _, valid = keys[*want.Choice]
+ }
+ valid = valid && want.Noul == nil && want.Min == nil && want.Max == nil && want.Level == nil
+ case "noul":
+ valid = want.Noul != nil && want.Choice == nil && want.Min == nil && want.Max == nil && want.Level == nil
+ case "score":
+ valid = want.Min != nil && want.Max != nil && want.Level == nil && *want.Min >= 0 && *want.Min <= *want.Max && *want.Max <= float64(len(keys)-1)
+ if want.Level != nil {
+ valid = want.Min == nil && want.Max == nil && *want.Level >= 0 && *want.Level < len(keys)
+ }
+ valid = valid && want.Choice == nil && want.Noul == nil
+ }
+ if !valid {
+ return fmt.Errorf("invalid %s expectation for %q", q.Type, name)
+ }
+ }
+ return nil
+}
+
+// Invalid criteria produce no candidate keys and fail expectation validation.
+func criteria(q decision.Question) map[string]any {
+ keys := make(map[string]any)
+ switch q.Type {
+ case "choice":
+ _ = json.Unmarshal(q.Criteria, &keys)
+ case "score":
+ var labels []any
+ _ = json.Unmarshal(q.Criteria, &labels)
+ for i, label := range labels {
+ keys[strconv.Itoa(i)] = label
+ }
+ case "noul":
+ keys["false"], keys["true"] = "No", "Yes"
+ }
+ return keys
+}
+
+func (c Case) Options() int {
+ var n int
+ for _, q := range c.Request.Questions.All() {
+ n += len(criteria(q))
+ }
+ return n
+}
+
+// Mismatches compares labels, never the model's confidence in those labels.
+// result must have passed response validation in Do.
+func (c Case) Mismatches(result Response) []string {
+ var wrong []string
+ for name, want := range c.Expected {
+ a := result.Answers[name]
+ switch {
+ case want.Choice != nil && a.Choice != *want.Choice:
+ wrong = append(wrong, fmt.Sprintf("%s: choice %q, want %q", name, a.Choice, *want.Choice))
+ case want.Noul != nil && (*a.Noul == .5 || (*a.Noul > .5) != *want.Noul):
+ wrong = append(wrong, fmt.Sprintf("%s: noul %g, want %v", name, *a.Noul, *want.Noul))
+ case want.Min != nil && (*a.Score < *want.Min || *a.Score > *want.Max):
+ wrong = append(wrong, fmt.Sprintf("%s: score %g, want [%g,%g]", name, *a.Score, *want.Min, *want.Max))
+ case want.Level != nil:
+ key := strconv.Itoa(*want.Level)
+ for other, p := range a.Probabilities {
+ if other != key && *p >= *a.Probabilities[key] {
+ wrong = append(wrong, fmt.Sprintf("%s: most probable level is not uniquely %d", name, *want.Level))
+ break
+ }
+ }
+ }
+ }
+ return wrong
+}
+
+func (c Corpus) HasImages() bool {
+ for _, row := range c.Cases {
+ if len(row.Request.Images) > 0 {
+ return true
+ }
+ }
+ return false
+}
+
+// Mode validates the benchmark's label policy.
+func Mode(value string) (string, error) {
+ if value == "" {
+ value = "regression"
+ }
+ if value != "regression" && value != "score" {
+ return "", fmt.Errorf("decision mode must be regression or score, got %q", strings.TrimSpace(value))
+ }
+ return value, nil
+}
diff --git a/internal/decisiontest/corpus_test.go b/internal/decisiontest/corpus_test.go
new file mode 100644
index 000000000..a3d8b4785
--- /dev/null
+++ b/internal/decisiontest/corpus_test.go
@@ -0,0 +1,180 @@
+package decisiontest
+
+import (
+ "bytes"
+ "encoding/json"
+ "image"
+ "image/png"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/ollama/ollama/decision"
+)
+
+const fixture = `{"id":"one","dataset":"test","request":{"state":"A test message.","questions":{"answer":{"type":"noul","instructions":"Is this a message?"}}},"expected":{"answer":{"noul":true}}}`
+
+func FuzzResponse(f *testing.F) {
+ var c Case
+ if err := json.Unmarshal([]byte(fixture), &c); err != nil {
+ f.Fatal(err)
+ }
+ c.Request.Model = "test"
+ f.Add([]byte(`{"model":"test","usage":{"input_tokens":1,"output_tokens":0},"answers":{"answer":{"type":"noul","noul":1}}}`))
+ f.Add([]byte(`{"model":"test","answers":{"answer":{"type":"noul","noul":null}}}`))
+ f.Fuzz(func(t *testing.T, body []byte) {
+ if response, err := decode(c.Request, body); err == nil {
+ c.Mismatches(response)
+ p := response.Answers["answer"].Noul
+ if p == nil || *p < 0 || *p > 1 {
+ t.Fatalf("accepted invalid probability: %v", p)
+ }
+ }
+ })
+}
+
+func TestLoadCorpus(t *testing.T) {
+ dir := t.TempDir()
+ var pngData bytes.Buffer
+ if err := png.Encode(&pngData, image.NewRGBA(image.Rect(0, 0, 2, 3))); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "image.png"), pngData.Bytes(), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ file := filepath.Join(dir, "cases.jsonl")
+ withImage := strings.TrimSuffix(fixture, "}") + `,"image_files":["image.png"]}`
+ if err := os.WriteFile(file, []byte(withImage+"\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ c, err := Load(file)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !c.HasImages() || c.Cases[0].ImagePixels != 6 || c.Cases[0].ImageBytes != pngData.Len() || c.Cases[0].Options() != 2 {
+ t.Fatalf("bad image metadata: %+v", c.Cases[0])
+ }
+ if !bytes.Equal(c.Cases[0].Request.Images[0], pngData.Bytes()) {
+ t.Fatal("image contents changed")
+ }
+ firstHash := c.SHA256
+ if err := os.WriteFile(filepath.Join(dir, "image.png"), append(pngData.Bytes(), 0), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ c, err = Load(file)
+ if err != nil || c.SHA256 == firstHash {
+ t.Fatalf("image change was not fingerprinted: %v", err)
+ }
+}
+
+func TestRejectInvalidCorpus(t *testing.T) {
+ for name, data := range map[string]string{
+ "empty": "\n",
+ "missing questions": `{"id":"empty","dataset":"test","request":{"state":"A test.","questions":{}},"expected":{}}`,
+ "duplicate id": fixture + "\n" + fixture,
+ "trailing object": fixture + `{}`,
+ "unknown field": strings.TrimSuffix(fixture, "}") + `,"unexpected":{}}`,
+ "missing expectation": strings.Replace(fixture, `"answer":{"noul":true}`, `"other":{"noul":true}`, 1),
+ "wrong expectation type": strings.Replace(fixture, `"noul":true`, `"choice":"yes"`, 1),
+ "model in data": strings.Replace(fixture, `"state":`, `"model":"ignored","state":`, 1),
+ "missing image": strings.TrimSuffix(fixture, "}") + `,"image_files":["missing.png"]}`,
+ "escaping image": strings.TrimSuffix(fixture, "}") + `,"image_files":["../private.png"]}`,
+ } {
+ t.Run(name, func(t *testing.T) {
+ file := filepath.Join(t.TempDir(), "cases.jsonl")
+ if err := os.WriteFile(file, []byte(data), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := Load(file); err == nil {
+ t.Fatal("accepted invalid corpus")
+ }
+ })
+ }
+}
+
+func TestCorpusHashFramesImageContents(t *testing.T) {
+ dir := t.TempDir()
+ var data bytes.Buffer
+ if err := png.Encode(&data, image.NewRGBA(image.Rect(0, 0, 2, 3))); err != nil {
+ t.Fatal(err)
+ }
+ file := filepath.Join(dir, "cases.jsonl")
+ if err := os.WriteFile(file, []byte(strings.TrimSuffix(fixture, "}")+`,"image_files":["a.png","b.png"]}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ var hashes []string
+ for _, sizes := range [][2]int{{1, 2}, {2, 1}} {
+ for i, name := range []string{"a.png", "b.png"} {
+ if err := os.WriteFile(filepath.Join(dir, name), bytes.Repeat(data.Bytes(), sizes[i]), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ corpus, err := Load(file)
+ if err != nil {
+ t.Fatal(err)
+ }
+ hashes = append(hashes, corpus.SHA256)
+ }
+ if hashes[0] == hashes[1] {
+ t.Fatal("different image inputs with the same concatenated bytes have the same corpus hash")
+ }
+}
+
+func TestResponseContractAndLabels(t *testing.T) {
+ var req decision.Request
+ if err := json.Unmarshal([]byte(`{"model":"test","state":"A test.","questions":{
+ "yes":{"type":"noul"},
+ "topic":{"type":"choice","criteria":{"a":"A","b":"B"}},
+ "rating":{"type":"score","criteria":["Low","High"]}}}`), &req); err != nil {
+ t.Fatal(err)
+ }
+ valid := `{"model":"test","usage":{"input_tokens":10,"output_tokens":0},"answers":{
+ "yes":{"type":"noul","noul":0},
+ "topic":{"type":"choice","choice":"a","probabilities":{"a":1,"b":0},"confidence":1},
+ "rating":{"type":"score","score":0,"probabilities":{"0":1,"1":0},"confidence":1,"legend":{"0":"Low","1":"High"}}}}`
+ for _, mutation := range []struct{ old, replacement string }{
+ {`"noul":0`, `"noul":null`},
+ {`"input_tokens":10,`, ""},
+ {`"output_tokens":0`, `"output_tokens":null`},
+ {`"a":1`, `"a":0.7`},
+ {`"choice":"a"`, `"choice":"b"`},
+ {`"confidence":1`, `"confidence":null`},
+ {`"score":0`, `"score":1`},
+ {`"0":"Low"`, `"0":"Wrong"`},
+ } {
+ t.Run(mutation.old, func(t *testing.T) {
+ if _, err := decode(req, []byte(strings.Replace(valid, mutation.old, mutation.replacement, 1))); err == nil {
+ t.Fatal("accepted broken response contract")
+ }
+ })
+ }
+ result, err := decode(req, []byte(valid))
+ if err != nil {
+ t.Fatal(err)
+ }
+ no, a, low := false, "a", 0
+ c := Case{Expected: map[string]Expected{"yes": {Noul: &no}, "topic": {Choice: &a}, "rating": {Level: &low}}}
+ if wrong := c.Mismatches(result); len(wrong) != 0 {
+ t.Fatalf("correct labels failed: %v", wrong)
+ }
+ a = "b"
+ if wrong := c.Mismatches(result); len(wrong) != 1 {
+ t.Fatalf("wrong label did not fail: %v", wrong)
+ }
+ if _, err := Mode("skip-low-confidence"); err == nil {
+ t.Fatal("accepted an unknown evaluation policy")
+ }
+}
+
+func TestCorpusDefersModelLimits(t *testing.T) {
+ // Kev accepts null state and one option; these are not Clef inputs.
+ file := filepath.Join(t.TempDir(), "cases.jsonl")
+ data := `{"id":"one","dataset":"test","request":{"state":null,"questions":{"label":{"type":"choice","criteria":{"a":null}}}},"expected":{"label":{"choice":"a"}}}`
+ if err := os.WriteFile(file, []byte(data), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := Load(file); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/internal/decisiontest/response.go b/internal/decisiontest/response.go
new file mode 100644
index 000000000..5b13707a6
--- /dev/null
+++ b/internal/decisiontest/response.go
@@ -0,0 +1,144 @@
+package decisiontest
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "math"
+ "net/http"
+ "reflect"
+ "strconv"
+ "time"
+
+ "github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/decision"
+)
+
+type Response struct {
+ Model string `json:"model"`
+ Answers map[string]Answer `json:"answers"`
+ Usage decision.Usage `json:"usage"`
+ PromptEvalCachedCount *int `json:"prompt_eval_cached_count"`
+}
+
+// Pointers distinguish missing/null numbers from valid zero values.
+type Answer struct {
+ Type string `json:"type"`
+ Choice string `json:"choice"`
+ Noul *float64 `json:"noul"`
+ Score *float64 `json:"score"`
+ Confidence *float64 `json:"confidence"`
+ Probabilities map[string]*float64 `json:"probabilities"`
+ Legend map[string]any `json:"legend"`
+}
+
+// Do measures the complete HTTP round trip, excluding request encoding and
+// response validation. The elapsed time includes network and server queueing.
+func Do(ctx context.Context, endpoint string, input decision.Request) (Response, time.Duration, error) {
+ var result Response
+ body, err := json.Marshal(input)
+ if err != nil {
+ return result, 0, err
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
+ if err != nil {
+ return result, 0, err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ start := time.Now()
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ return result, time.Since(start), err
+ }
+ defer resp.Body.Close()
+ const limit = 8 << 20
+ body, err = io.ReadAll(io.LimitReader(resp.Body, limit+1))
+ elapsed := time.Since(start)
+ if err != nil {
+ return result, elapsed, err
+ }
+ if len(body) > limit {
+ return result, elapsed, fmt.Errorf("decision response exceeds %d bytes", limit)
+ }
+ if resp.StatusCode != http.StatusOK {
+ return result, elapsed, api.StatusError{StatusCode: resp.StatusCode, Status: resp.Status, ErrorMessage: string(body)}
+ }
+ result, err = decode(input, body)
+ return result, elapsed, err
+}
+
+func decode(input decision.Request, body []byte) (Response, error) {
+ result := Response{Usage: decision.Usage{InputTokens: -1, OutputTokens: -1}}
+ if err := json.Unmarshal(body, &result); err != nil {
+ return result, err
+ }
+ if result.Model != input.Model || len(result.Answers) != input.Questions.Len() || result.Usage.InputTokens <= 0 || result.Usage.OutputTokens < 0 {
+ return result, fmt.Errorf("invalid response model, answer count, or token usage")
+ }
+ if n := result.PromptEvalCachedCount; n != nil && (*n < 0 || *n > result.Usage.InputTokens) {
+ return result, fmt.Errorf("cached token count outside input token range")
+ }
+ for name, q := range input.Questions.All() {
+ if err := result.Answers[name].validate(q); err != nil {
+ return result, fmt.Errorf("answer %q: %w", name, err)
+ }
+ }
+ return result, nil
+}
+
+func probability(p *float64) bool {
+ return p != nil && *p >= 0 && *p <= 1
+}
+
+func (a Answer) validate(q decision.Question) error {
+ if a.Type != q.Type {
+ return fmt.Errorf("type %q, want %q", a.Type, q.Type)
+ }
+ if q.Type == "noul" {
+ if !probability(a.Noul) {
+ return fmt.Errorf("missing or invalid noul probability")
+ }
+ return nil
+ }
+ keys := criteria(q)
+ if len(a.Probabilities) != len(keys) || !probability(a.Confidence) {
+ return fmt.Errorf("missing or invalid probabilities or confidence")
+ }
+ var sum, weighted, best float64
+ for key := range keys {
+ p := a.Probabilities[key]
+ if !probability(p) {
+ return fmt.Errorf("missing or invalid probability for %q", key)
+ }
+ sum += *p
+ best = max(best, *p)
+ if q.Type == "score" {
+ i, _ := strconv.Atoi(key)
+ weighted += float64(i) * *p
+ }
+ }
+ // Some implementations report four decimal places. Account for rounding
+ // each probability independently; confidence is model-defined.
+ const rounding = 0.5e-4
+ if math.Abs(sum-1) > 1e-6+float64(len(keys))*rounding {
+ return fmt.Errorf("probabilities sum to %g, want 1", sum)
+ }
+ if q.Type == "choice" {
+ if p := a.Probabilities[a.Choice]; p == nil || *p < best {
+ return fmt.Errorf("choice %q is not a probability maximum", a.Choice)
+ }
+ } else {
+ // Include rounding of the score and its weighted probabilities.
+ n := len(keys)
+ tolerance := 1e-6 + rounding*float64(1+n*(n-1)/2)
+ if a.Score == nil || *a.Score < 0 || *a.Score > float64(n-1) || math.Abs(*a.Score-weighted) > tolerance {
+ return fmt.Errorf("score does not match probabilities")
+ }
+ if !reflect.DeepEqual(a.Legend, keys) {
+ return fmt.Errorf("legend does not match criteria")
+ }
+ }
+ return nil
+}
diff --git a/internal/decisiontest/response_test.go b/internal/decisiontest/response_test.go
new file mode 100644
index 000000000..5403e80d0
--- /dev/null
+++ b/internal/decisiontest/response_test.go
@@ -0,0 +1,72 @@
+package decisiontest
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/ollama/ollama/decision"
+ "github.com/ollama/ollama/llm"
+)
+
+func TestCacheExpectation(t *testing.T) {
+ zero, half, one := 0.0, 0.5, 1.0
+ full, partial := 100, 1
+ for _, tt := range []struct {
+ name string
+ expectation *CacheExpectation
+ cached *int
+ wantErr bool
+ }{
+ {"unreported without requirement", nil, nil, false},
+ {"missing telemetry", &CacheExpectation{Min: &half}, nil, true},
+ {"broken reuse", &CacheExpectation{Min: &half}, new(int), true},
+ {"full hit", &CacheExpectation{Min: &one}, &full, false},
+ {"unexpected hit", &CacheExpectation{Max: &zero}, &partial, true},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ c := Case{Cache: tt.expectation}
+ response := Response{PromptEvalCachedCount: tt.cached}
+ response.Usage.InputTokens = 100
+ if err := c.CheckCache(response); (err != nil) != tt.wantErr {
+ t.Fatalf("CheckCache=%v, wantErr=%v", err, tt.wantErr)
+ }
+ })
+ }
+}
+
+// Exercise actual API responses so the test harness does not impose one model's
+// confidence formula or output precision on other decision models.
+func TestResponseEncodings(t *testing.T) {
+ var req decision.Request
+ if err := json.Unmarshal([]byte(`{"model":"test","state":"An ordinary message.","questions":{
+ "topic":{"type":"choice","instructions":"Classify the message.","criteria":{"a":"A","b":"B","c":"C"}},
+ "rating":{"type":"score","instructions":"Rate the message.","criteria":["Low","Medium","High"]},
+ "message":{"type":"noul","instructions":"Is this a message?","criteria":{}}
+ }}`), &req); err != nil {
+ t.Fatal(err)
+ }
+ for _, encoding := range []string{"", "tev1", "clef", "strands", "kev"} {
+ t.Run(encoding, func(t *testing.T) {
+ compiled, err := decision.Compile(req, encoding)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, logits := range [][][]float32{
+ {{0, 0, 0}, {0, 0, 0}, {0, 0}},
+ {{1, 2, 3}, {1, 2, 3}, {1, 2}},
+ } {
+ response, err := compiled.Answer(req.Model, llm.ScoreResponse{InputTokens: 42, Logits: logits})
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, err := json.Marshal(response)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := decode(req, body); err != nil {
+ t.Fatalf("rejected valid API response: %v: %s", err, body)
+ }
+ }
+ })
+ }
+}
diff --git a/internal/decisiontest/tally.go b/internal/decisiontest/tally.go
new file mode 100644
index 000000000..1e8e09552
--- /dev/null
+++ b/internal/decisiontest/tally.go
@@ -0,0 +1,37 @@
+package decisiontest
+
+import "fmt"
+
+// Tally keeps failed requests in the denominator, including malformed responses.
+type Tally struct {
+ Requests int `json:"attempted_requests"`
+ Errors int `json:"errors"`
+ CorrectCases int `json:"correct_cases"`
+ Questions int `json:"questions"`
+ CorrectQuestions int `json:"correct_questions"`
+}
+
+func (t *Tally) Add(c Case, wrong []string, err error) {
+ t.Requests++
+ t.Questions += len(c.Expected)
+ if err != nil {
+ t.Errors++
+ return
+ }
+ t.CorrectQuestions += len(c.Expected) - len(wrong)
+ if len(wrong) == 0 {
+ t.CorrectCases++
+ }
+}
+
+func (t Tally) CaseAccuracy() float64 {
+ return 100 * float64(t.CorrectCases) / float64(max(t.Requests, 1))
+}
+
+func (t Tally) QuestionAccuracy() float64 {
+ return 100 * float64(t.CorrectQuestions) / float64(max(t.Questions, 1))
+}
+
+func (t Tally) String() string {
+ return fmt.Sprintf("cases=%d/%d (%.2f%%), questions=%d/%d (%.2f%%), errors=%d", t.CorrectCases, t.Requests, t.CaseAccuracy(), t.CorrectQuestions, t.Questions, t.QuestionAccuracy(), t.Errors)
+}