Add AutoTrust decision model to MLX (#19399)

* Add AutoTrust decision scoring to MLX

* address comments

* Support AutoTrust 35B decision models in MLX

* Resolve AutoTrust choice limits during config loading

Apply publisher-specific defaults and validate requests against the resolved limit.
This commit is contained in:
Daniel Hiltgen authored and GitHub committed 2026-11-04 09:47:37 -08:00
1 parent e9fde36d75
commit d666cdb246
16 files changed
+841 -19

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
package create
import (
"context"
"os"
"path/filepath"
"testing"
st "github.com/ollama/ollama/fs/safetensors"
)
func TestAutoTrustDecisionImportExcludesBuildNotes(t *testing.T) {
dir := t.TempDir()
writeConfigJSON(t, dir, `{"architectures":["AutoTrustDecision"],"model_type":"qwen3_5_text"}`)
createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{
st.NewTensorDataFromBytes("model.embed_tokens.weight", "BF16", []int32{8, 8}, make([]byte, 128)),
})
for name, data := range map[string]string{
"decision_head.json": `{"slots":{}}`,
"calibration.json": `{"version":1}`,
"preprocessor_config.json": `{}`,
"video_preprocessor_config.json": `{}`,
"hf_quant_config.json": `{"quantization":{"quant_algo":"W4A16_NVFP4"}}`,
"build-notes.json": `{"source":"/tank/private-models","token":"fixture-secret"}`,
} {
if err := os.WriteFile(filepath.Join(dir, name), []byte(data), 0o600); err != nil {
t.Fatal(err)
}
}
store := newCaptureStore()
var renderer string
err := Create(t.Context(), "autotrust-decision-fixture", dir, testPipelineOptions(), store,
func(_ context.Context, _ string, info ManifestInfo) error {
renderer = info.ModelConfig.Renderer
return nil
}, func(string) {})
if err != nil {
t.Fatal(err)
}
if renderer != "autotrust-decision" {
t.Fatalf("renderer = %q, want autotrust-decision", renderer)
}
if _, ok := store.blobs["build-notes.json"]; ok {
t.Fatal("internal source notes were packaged")
}
for _, name := range []string{"config.json", "decision_head.json", "calibration.json", "preprocessor_config.json", "video_preprocessor_config.json", "hf_quant_config.json"} {
if _, ok := store.blobs[name]; !ok {
t.Errorf("required AutoTrust decision metadata %s was omitted", name)
}
}
}
+1
View File
@@ -429,6 +429,7 @@ type tensorImportTransformFactory func(rawConfig json.RawMessage) (quantizePolic
var tensorImportTransformRegistry = map[string]tensorImportTransformFactory{
"Qwen3_5Model": newPplxImportTransform,
"KevForDecision": newQwen35DecisionImportTransform,
"AutoTrustDecision": newQwen35DecisionImportTransform,
"StrandsDeciderForDecision": newQwen35DecisionImportTransform,
"ClefForDecision": newQwen35DecisionImportTransform,
"Qwen3_5ForCausalLM": newQwen35ImportTransform,
+22 -9
View File
@@ -236,22 +236,21 @@ func SafetensorsConfigFiles(dir string) ([]string, error) {
if err != nil {
return nil, err
}
if !hasSidecar {
hasAutoTrustDecisionSidecar := slices.Contains(names, "decision_head.json")
if !hasSidecar && !hasAutoTrustDecisionSidecar {
return names, nil
}
cfg, _, err := readSourceModelConfig(dir)
if err != nil {
return nil, err
}
if cfg.Architecture() != "Qwen3_5Model" {
autoTrustDecisionSource := cfg.Architecture() == "AutoTrustDecision"
qwenDecisionSource := hasSidecar && cfg.Architecture() == "Qwen3_5Model"
if !autoTrustDecisionSource && !qwenDecisionSource {
return names, nil
}
format, err := qwenDecisionFormat(dir)
if err != nil {
return nil, err
}
// This checkpoint has extra JSON that does not configure inference. Keep
// only the files the importer or runner consumes.
// These decision checkpoints may have extra JSON that does not configure
// inference. Keep only the files the importer or runner consumes.
modelMetadata := map[string]bool{
"config.json": true,
"decision_config.json": true,
@@ -266,11 +265,25 @@ func SafetensorsConfigFiles(dir string) ([]string, error) {
"hf_quant_config.json": true,
"quantization_config.json": true,
}
if format == d3FormatID {
if autoTrustDecisionSource {
modelMetadata["adapter_config.json"] = true
modelMetadata["calibration.json"] = true
modelMetadata["decision_head.json"] = true
modelMetadata["preprocessor_config.json"] = true
modelMetadata["video_preprocessor_config.json"] = true
modelMetadata["vocab.json"] = true
}
if qwenDecisionSource {
format, err := qwenDecisionFormat(dir)
if err != nil {
return nil, err
}
if format == d3FormatID {
modelMetadata["preprocessor_config.json"] = true
modelMetadata["video_preprocessor_config.json"] = true
modelMetadata["vocab.json"] = true
}
}
return slices.DeleteFunc(names, func(name string) bool {
return filepath.Ext(name) == ".json" && !modelMetadata[name]
}), nil
+5
View File
@@ -51,6 +51,11 @@ func inferSafetensorsConfig(modelDir string, cfg sourceModelConfig, parserOverri
rendererName, decisionModel = "strands", true
case "KevForDecision":
rendererName, decisionModel = "kev", true
// The staged architecture ID selects AutoTrust's decision runner for the
// publisher's Qwen3.5 checkpoint.
case "AutoTrustDecision":
rendererName, decisionModel = "autotrust-decision", true
decisionVision = cfg.VisionConfig != nil
case "LayaForDecision":
decisionModel = true
case "D1Model":
+1 -1
View File
@@ -3,7 +3,7 @@ package create
import "testing"
func TestQwen35DecisionQuantizationPolicy(t *testing.T) {
for _, arch := range []string{"ClefForDecision", "StrandsDeciderForDecision", "KevForDecision"} {
for _, arch := range []string{"ClefForDecision", "StrandsDeciderForDecision", "KevForDecision", "AutoTrustDecision"} {
inv := Inventory{Config: sourceModelConfig{Architectures: []string{arch}}}
policy, err := newTensorImportTransform(inv)
if err != nil {
+69
View File
@@ -0,0 +1,69 @@
package decision
import (
"encoding/json"
"fmt"
"strings"
"testing"
)
func TestIndependentQwenChoiceCapacity(t *testing.T) {
for _, encoding := range []string{"d3", "autotrust-decision"} {
for _, count := range []int{1, 2, 255, 256, 257} {
t.Run(fmt.Sprintf("%s/%d", encoding, count), func(t *testing.T) {
var criteria []string
for i := range count {
criteria = append(criteria, fmt.Sprintf("%q:null", fmt.Sprintf("option-%03d", i)))
}
input := fmt.Sprintf(`{"model":"test","state":"x","questions":{"pick":{"type":"choice","instructions":"Pick one","criteria":{%s}}}}`, strings.Join(criteria, ","))
var req Request
if err := json.Unmarshal([]byte(input), &req); err != nil {
t.Fatal(err)
}
compiled, err := Compile(req, encoding)
minimum := 1
if encoding == "autotrust-decision" {
minimum = 2
}
if count < minimum || count > 255 {
if err == nil {
t.Fatalf("accepted %d options", count)
}
return
}
if err != nil {
t.Fatalf("rejected %d options: %v", count, err)
}
if got := len(compiled.Request.Rows[0].Question.Options); got != count {
t.Fatalf("compiled %d of %d options", got, count)
}
})
}
}
}
func TestIndependentQwenScoreLevels(t *testing.T) {
for _, encoding := range []string{"d3", "autotrust-decision"} {
for _, count := range []int{1, 2, 5, 6, 7, 10, 11} {
t.Run(fmt.Sprintf("%s/%d", encoding, count), func(t *testing.T) {
levels := make([]string, count)
for i := range levels {
levels[i] = fmt.Sprintf("%q", fmt.Sprintf("level-%d", i))
}
input := fmt.Sprintf(`{"model":"test","state":"x","questions":{"rating":{"type":"score","criteria":[%s]}}}`, strings.Join(levels, ","))
var req Request
if err := json.Unmarshal([]byte(input), &req); err != nil {
t.Fatal(err)
}
_, err := Compile(req, encoding)
valid := count >= 2 && count <= 10
if encoding == "autotrust-decision" {
valid = count == 6
}
if (err == nil) != valid {
t.Fatalf("score levels %d: unexpected error %v", count, err)
}
})
}
}
}
+22 -2
View File
@@ -12,6 +12,20 @@ import (
// encodeD3 retains the publisher's question and option order. The Qwen
// backbone scores a complete prompt independently for each question.
func encodeD3(req Request, c *Compiled) error {
return encodeIndependentQwen(req, c, qwenDecisionLimits{minChoices: 1, minScore: 2, maxScore: 10})
}
func encodeAutoTrustDecision(req Request, c *Compiled) error {
return encodeIndependentQwen(req, c, qwenDecisionLimits{minChoices: 2, minScore: 6, maxScore: 6})
}
type qwenDecisionLimits struct {
minChoices int
minScore int
maxScore int
}
func encodeIndependentQwen(req Request, c *Compiled, limits qwenDecisionLimits) error {
if n := req.Questions.Len(); n < 1 || n > 64 {
return fmt.Errorf("questions must contain 1–64 fields")
}
@@ -39,8 +53,11 @@ func encodeD3(req Request, c *Compiled) error {
return fmt.Errorf("question %q: %w", name, err)
}
if question.Type == "score" {
if len(field.Choices) > 10 {
return fmt.Errorf("question %q: score criteria must contain 2–10 levels", name)
if len(field.Choices) < limits.minScore || len(field.Choices) > limits.maxScore {
if limits.minScore == limits.maxScore {
return fmt.Errorf("question %q: score criteria must contain exactly %d levels", name, limits.minScore)
}
return fmt.Errorf("question %q: score criteria must contain %d–%d levels", name, limits.minScore, limits.maxScore)
}
seen := make(map[string]bool, len(descriptions))
for _, description := range descriptions {
@@ -62,6 +79,9 @@ func encodeD3(req Request, c *Compiled) error {
}
}
}
if question.Type == "choice" && len(field.Choices) < limits.minChoices {
return fmt.Errorf("question %q: choice criteria must contain at least %d options", name, limits.minChoices)
}
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: descriptions,
+8 -1
View File
@@ -66,7 +66,7 @@ func validateImages(images []api.ImageData) error {
func Compile(req Request, encoding string) (*Compiled, error) {
switch encoding {
case "", "tev1", "clef", "strands", "kev", "pplx", "d3", "d1":
case "", "tev1", "clef", "strands", "kev", "pplx", "d3", "autotrust-decision", "d1":
default:
return nil, fmt.Errorf("unsupported decision encoding %q", encoding)
}
@@ -110,6 +110,13 @@ func Compile(req Request, encoding string) (*Compiled, error) {
}
return c, nil
}
if encoding == "autotrust-decision" {
c := &Compiled{encoding: encoding}
if err := encodeAutoTrustDecision(req, c); err != nil {
return nil, err
}
return c, nil
}
if err := ValidateLimits(req, encoding); err != nil {
return nil, err
}
@@ -1,6 +1,7 @@
package architectures
import (
_ "github.com/ollama/ollama/mlxrunner/model/autotrustdecision"
_ "github.com/ollama/ollama/mlxrunner/model/clef"
_ "github.com/ollama/ollama/mlxrunner/model/cohere2_moe"
_ "github.com/ollama/ollama/mlxrunner/model/d1"
@@ -0,0 +1,30 @@
package autotrustdecision
import (
"encoding/json"
"fmt"
)
type config struct {
ModelType string `json:"model_type"`
MaxChoices int `json:"max_choices"`
}
func parseConfig(data []byte, head decisionHead) (config, error) {
var cfg config
if err := json.Unmarshal(data, &cfg); err != nil {
return config{}, fmt.Errorf("parse AutoTrust decision config: %w", err)
}
if cfg.MaxChoices == 0 {
choiceRange := head.Slots.Ranges["choice"]
cfg.MaxChoices = choiceRange[1] - choiceRange[0]
// The 27B-VL checkpoint supports wide labels despite its compact head.
if cfg.ModelType == "qwen3_5" {
cfg.MaxChoices = 256
}
}
if cfg.MaxChoices < 2 || cfg.MaxChoices > 256 {
return config{}, fmt.Errorf("invalid AutoTrust decision max_choices %d: must be between 2 and 256", cfg.MaxChoices)
}
return cfg, nil
}
@@ -0,0 +1,142 @@
package autotrustdecision
import (
"encoding/json"
"strings"
"testing"
"github.com/ollama/ollama/llm"
"github.com/ollama/ollama/manifest"
"github.com/ollama/ollama/mlxrunner/model"
)
func TestParseConfigChoiceDefaults(t *testing.T) {
for _, tt := range []struct {
name string
data string
trained int
maxChoices int
}{
{name: "compact text", data: `{"model_type":"qwen3_5_text"}`, trained: 16, maxChoices: 16},
{name: "wide MoE", data: `{"model_type":"qwen3_5_moe"}`, trained: 256, maxChoices: 256},
{name: "compact VL", data: `{"model_type":"qwen3_5"}`, trained: 16, maxChoices: 256},
{name: "zero uses default", data: `{"max_choices":0}`, trained: 16, maxChoices: 16},
{name: "zero uses VL default", data: `{"model_type":"qwen3_5","max_choices":0}`, trained: 16, maxChoices: 256},
{name: "explicit wide inference", data: `{"max_choices":256}`, trained: 16, maxChoices: 256},
{name: "explicit lower VL limit", data: `{"model_type":"qwen3_5","max_choices":8}`, trained: 16, maxChoices: 8},
{name: "nested backbone config", data: `{"model_type":"qwen3_5","text_config":{"hidden_size":5120}}`, trained: 16, maxChoices: 256},
} {
t.Run(tt.name, func(t *testing.T) {
var head decisionHead
head.Slots.Ranges = map[string][2]int{"choice": {8, 8 + tt.trained}}
cfg, err := parseConfig([]byte(tt.data), head)
if err != nil {
t.Fatal(err)
}
if cfg.MaxChoices != tt.maxChoices {
t.Fatalf("max_choices = %d, want %d", cfg.MaxChoices, tt.maxChoices)
}
})
}
}
func TestLoadModelChoiceLimits(t *testing.T) {
for _, tt := range []struct {
name string
modelType string
trained int
override int
maxChoices int
}{
{name: "compact text default", modelType: "qwen3_5_text", trained: 16, maxChoices: 16},
{name: "wide MoE default", modelType: "qwen3_5_moe_text", trained: 256, maxChoices: 255},
{name: "compact VL default", modelType: "qwen3_5", trained: 16, maxChoices: 255},
{name: "explicit wide inference", modelType: "qwen3_5_text", trained: 16, override: 256, maxChoices: 255},
{name: "explicit lower VL limit", modelType: "qwen3_5", trained: 16, override: 8, maxChoices: 8},
} {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("OLLAMA_MODELS", t.TempDir())
var head decisionHead
head.Bias = make([]float32, 8+tt.trained)
head.VerbalizerIDs = make([]int32, len(head.Bias))
head.Slots.Verbalizers = make([]string, len(head.Bias))
head.Slots.Ranges = map[string][2]int{"noul": {0, 2}, "score": {2, 8}, "choice": {8, len(head.Bias)}}
head.Slots.Template = "bare-v1"
if tt.trained == 256 {
head.Slots.Template = "bare-v1-wide256"
}
for i := range head.VerbalizerIDs {
head.VerbalizerIDs[i] = int32(i)
}
var added []map[string]any
for i := range 256 {
label := string(rune('A' + i))
if i >= 26 {
label = string([]rune{rune('A' + (i-26)/26), rune('A' + (i-26)%26)})
}
added = append(added, map[string]any{"id": i + 8, "content": label})
}
tokenizer := map[string]any{"model": map[string]any{"type": "BPE", "vocab": map[string]int{"x": 0}, "merges": []string{}}, "added_tokens": added}
backbone := map[string]any{
"model_type": tt.modelType, "hidden_size": 8, "num_hidden_layers": 1,
"num_attention_heads": 1, "num_key_value_heads": 1, "head_dim": 8, "vocab_size": 264,
"linear_num_value_heads": 1, "linear_num_key_heads": 1, "linear_key_head_dim": 8, "linear_value_head_dim": 8,
}
if tt.override != 0 {
backbone["max_choices"] = tt.override
}
root := &model.Root{Manifest: &manifest.Manifest{}}
for name, value := range map[string]any{
"config.json": backbone, "decision_head.json": head, "tokenizer.json": tokenizer,
"calibration.json": map[string]any{"per_kind": map[string]int{"choice": 1, "noul": 1, "score": 1}},
} {
data, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
layer, err := manifest.NewLayer(strings.NewReader(string(data)), manifest.MediaTypeImageJSON)
if err != nil {
t.Fatal(err)
}
layer.Name = name
root.Manifest.Layers = append(root.Manifest.Layers, layer)
}
loaded, err := newModel(root)
if err != nil {
t.Fatal(err)
}
m := loaded.(*Model)
if len(m.choiceIDs) != tt.maxChoices || len(m.choiceCodes) != tt.maxChoices {
t.Fatalf("loaded %d IDs and %d labels, want %d", len(m.choiceIDs), len(m.choiceCodes), tt.maxChoices)
}
q := &llm.ScoreQuestion{Type: "choice", Options: make([]string, tt.maxChoices)}
if _, _, _, _, err := m.prompt(llm.ScoreRequest{}, q); err != nil {
t.Fatalf("exact limit: %v", err)
}
q.Options = append(q.Options, "extra")
if _, _, _, _, err := m.prompt(llm.ScoreRequest{}, q); err == nil {
t.Fatal("accepted more choices than the resolved limit")
}
})
}
}
func TestParseConfigRejectsInvalidChoices(t *testing.T) {
for _, data := range []string{
`{"max_choices":-1}`,
`{"max_choices":1}`,
`{"max_choices":257}`,
`{"max_choices":2.5}`,
`{"max_choices":"256"}`,
`{"max_choices":`,
} {
t.Run(data, func(t *testing.T) {
var head decisionHead
head.Slots.Ranges = map[string][2]int{"choice": {8, 24}}
if _, err := parseConfig([]byte(data), head); err == nil {
t.Fatalf("accepted invalid config %s", data)
}
})
}
}
+159
View File
@@ -0,0 +1,159 @@
// Package autotrustdecision serves AutoTrust slot-readout decision checkpoints.
package autotrustdecision
import (
"fmt"
"math"
"slices"
"strings"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/model"
"github.com/ollama/ollama/mlxrunner/model/qwen3_5"
)
type decisionHead struct {
Bias []float32 `json:"bias"`
VerbalizerIDs []int32 `json:"verbalizer_ids"`
Slots struct {
Ranges map[string][2]int `json:"ranges"`
Verbalizers []string `json:"verbalizers"`
Template string `json:"template_version"`
} `json:"slots"`
}
type calibration struct {
PerKind map[string]float32 `json:"per_kind"`
}
type adapterConfig struct {
Rank int `json:"r"`
Alpha float32 `json:"lora_alpha"`
}
type Model struct {
*qwen3_5.Model
head decisionHead
temperature map[string]float32
adapter adapterConfig
choiceIDs []int32
choiceCodes []string
}
func init() { model.Register("AutoTrustDecision", newModel) }
func newModel(root *model.Root) (model.Model, error) {
var head decisionHead
if err := root.Manifest.ReadConfigJSON("decision_head.json", &head); err != nil {
return nil, fmt.Errorf("read AutoTrust decision head: %w", err)
}
slots := len(head.VerbalizerIDs)
compact := slots == 24 && head.Slots.Template == "bare-v1"
wide := slots == 264 && head.Slots.Template == "bare-v1-wide256"
if len(head.Bias) != slots || len(head.Slots.Verbalizers) != slots ||
(!compact && !wide) {
return nil, fmt.Errorf("unsupported AutoTrust decision slot head")
}
if head.Slots.Ranges["noul"] != [2]int{0, 2} ||
head.Slots.Ranges["score"] != [2]int{2, 8} || head.Slots.Ranges["choice"] != [2]int{8, slots} {
return nil, fmt.Errorf("unsupported AutoTrust decision slot ranges")
}
data, err := root.Manifest.ReadConfig("config.json")
if err != nil {
return nil, fmt.Errorf("read AutoTrust decision config: %w", err)
}
cfg, err := parseConfig(data, head)
if err != nil {
return nil, err
}
var cal calibration
if err := root.Manifest.ReadConfigJSON("calibration.json", &cal); err != nil {
return nil, fmt.Errorf("read AutoTrust decision calibration: %w", err)
}
for _, kind := range []string{"noul", "score", "choice"} {
t := cal.PerKind[kind]
if t <= 0 || math.IsNaN(float64(t)) || math.IsInf(float64(t), 0) {
return nil, fmt.Errorf("invalid AutoTrust decision %s temperature %g", kind, t)
}
}
backbone, err := qwen3_5.NewModel(root)
if err != nil {
return nil, err
}
m := &Model{Model: backbone.(*qwen3_5.Model), head: head, temperature: cal.PerKind}
switch m.Config.ModelType {
case "qwen3_5", "qwen3_5_text", "qwen3_5_moe", "qwen3_5_moe_text":
default:
return nil, fmt.Errorf("unsupported AutoTrust decision backbone %q", m.Config.ModelType)
}
for _, id := range head.VerbalizerIDs {
if id < 0 || id >= m.Config.VocabSize {
return nil, fmt.Errorf("AutoTrust decision verbalizer token %d is outside the vocabulary", id)
}
}
// A missing adapter config denotes a checkpoint with the adapter fused into
// the backbone. A present but unreadable config must fail model loading.
if _, ok := root.Manifest.ConfigLayer("adapter_config.json"); ok {
if err := root.Manifest.ReadConfigJSON("adapter_config.json", &m.adapter); err != nil {
return nil, fmt.Errorf("read AutoTrust decision adapter config: %w", err)
}
if m.adapter.Rank <= 0 || m.adapter.Alpha <= 0 {
return nil, fmt.Errorf("invalid AutoTrust decision adapter rank %d or alpha %g", m.adapter.Rank, m.adapter.Alpha)
}
}
m.choiceCodes, m.choiceIDs = choiceLabels(m.Tokenizer())
// The System One API accepts at most 255 of the wide head's 256 labels.
headChoices := min(slots-8, 255)
if len(m.choiceIDs) < 255 || !slices.Equal(m.choiceIDs[:headChoices], head.VerbalizerIDs[8:8+headChoices]) {
return nil, fmt.Errorf("AutoTrust decision tokenizer choice labels do not match the trained head")
}
maxChoices := min(cfg.MaxChoices, len(m.choiceIDs))
m.choiceCodes = m.choiceCodes[:maxChoices]
m.choiceIDs = m.choiceIDs[:maxChoices]
return m, nil
}
// The publisher's LoRA applies to the System 1 backbone and lm_head only.
// Merge into the loaded BF16 tensors before Qwen packs its linear-attention
// projections. An already fused checkpoint has no adapter tensors.
func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
const prefix = "base_model.model."
const aSuffix = ".lora_A.weight"
pairs := 0
for name, a := range tensors {
if !strings.HasPrefix(name, prefix) || !strings.HasSuffix(name, aSuffix) {
continue
}
if m.adapter.Rank <= 0 || m.adapter.Alpha <= 0 {
return fmt.Errorf("AutoTrust decision adapter tensors require adapter_config.json")
}
stem := strings.TrimSuffix(strings.TrimPrefix(name, prefix), aSuffix)
baseName := stem + ".weight"
bName := strings.TrimSuffix(name, aSuffix) + ".lora_B.weight"
w, b := tensors[baseName], tensors[bName]
if w == nil || b == nil || w.NumDims() != 2 || a.NumDims() != 2 || b.NumDims() != 2 ||
a.Dim(0) != m.adapter.Rank || b.Dim(1) != m.adapter.Rank ||
a.Dim(1) != w.Dim(1) || b.Dim(0) != w.Dim(0) {
return fmt.Errorf("AutoTrust decision adapter pair %s does not match base projection", stem)
}
// Each merge finishes before the next pair so its FP32 intermediates
// do not accumulate across the checkpoint's adapter projections.
updated := mlx.ScopedEval(func() []*mlx.Array {
return []*mlx.Array{mlx.Add(w.AsType(mlx.DTypeFloat32),
mlx.MulScalar(mlx.Matmul(b.AsType(mlx.DTypeFloat32), a.AsType(mlx.DTypeFloat32)), m.adapter.Alpha/float32(m.adapter.Rank))).AsType(w.DType())}
})[0]
tensors[baseName] = updated
delete(tensors, name)
delete(tensors, bName)
pairs++
}
for name := range tensors {
if strings.HasPrefix(name, prefix) && strings.HasSuffix(name, ".lora_B.weight") {
return fmt.Errorf("AutoTrust decision adapter %s has no matching A tensor", name)
}
}
if m.adapter.Rank > 0 && pairs == 0 {
return fmt.Errorf("AutoTrust decision adapter configuration has no weights")
}
return m.Model.LoadWeights(tensors)
}
+178
View File
@@ -0,0 +1,178 @@
package autotrustdecision
import (
"context"
"fmt"
"net/http"
"slices"
"strings"
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/llm"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/model"
"github.com/ollama/ollama/mlxrunner/tokenizer"
)
var _ model.CachedScorer = (*Model)(nil)
// The publisher's bare-v1 prompt has no chat delimiters or generation suffix.
const imageMarker = "<|vision_start|><|image_pad|><|vision_end|>"
// A request body cap alone still permits many tiny images and prompt markers.
const maxAutoTrustDecisionImages = 64
func choiceLabels(tok *tokenizer.Tokenizer) ([]string, []int32) {
var codes []string
var ids []int32
labels := make([]string, 0, 702)
for a := 'A'; a <= 'Z'; a++ {
labels = append(labels, string(a))
}
for a := 'A'; a <= 'Z'; a++ {
for b := 'A'; b <= 'Z'; b++ {
labels = append(labels, string(a)+string(b))
}
}
for _, code := range labels {
candidate := tok.Encode(code, false)
if len(candidate) != 1 || !slices.Contains(tok.Encode("x\n"+code+") y", false), candidate[0]) {
continue
}
codes = append(codes, code)
ids = append(ids, candidate[0])
if len(ids) == 255 {
return codes, ids
}
}
return codes, ids
}
func (m *Model) prompt(input llm.ScoreRequest, q *llm.ScoreQuestion) (string, string, []int32, []float32, error) {
if q == nil {
return "", "", nil, nil, fmt.Errorf("missing AutoTrust decision question")
}
if len(input.Images) > maxAutoTrustDecisionImages {
return "", "", nil, nil, fmt.Errorf("AutoTrust decision supports at most %d images", maxAutoTrustDecisionImages)
}
var options []string
var ids []int32
var bias []float32
switch q.Type {
case "noul":
if len(q.Options) != 2 {
return "", "", nil, nil, fmt.Errorf("AutoTrust decision noul requires two options")
}
options = []string{"false", "true"}
ids = m.head.VerbalizerIDs[:2]
bias = m.head.Bias[:2]
case "score":
if len(q.Options) != 6 {
return "", "", nil, nil, fmt.Errorf("AutoTrust decision score requires six levels")
}
options = []string{"0", "1", "2", "3", "4", "5"}
ids = m.head.VerbalizerIDs[2:8]
bias = m.head.Bias[2:8]
case "choice":
maxChoices := len(m.choiceIDs)
if len(q.Options) < 2 || len(q.Options) > maxChoices {
return "", "", nil, nil, fmt.Errorf("AutoTrust decision choice requires 2–%d options", maxChoices)
}
options = make([]string, len(q.Options))
for i, option := range q.Options {
options[i] = m.choiceCodes[i] + ") " + option
}
ids = m.choiceIDs[:len(options)]
bias = make([]float32, len(options))
copy(bias, m.head.Bias[8:])
default:
return "", "", nil, nil, fmt.Errorf("unsupported AutoTrust decision question type %q", q.Type)
}
prefix := fmt.Sprintf("[kind] %s\n[state] ", q.Type)
if len(input.Images) > 0 {
prefix += strings.Repeat(imageMarker, len(input.Images))
}
prefix += input.State + "\n[question] "
full := prefix + q.Instructions + "\n[options]\n" + strings.Join(options, "\n") + "\n[decision]:"
return full, prefix, ids, bias, nil
}
func (m *Model) prepareRow(input llm.ScoreRequest, q *llm.ScoreQuestion) (*model.PreparedRequest, []model.Segment, []int32, []float32, error) {
full, prefix, ids, bias, err := m.prompt(input, q)
if err != nil {
return nil, nil, nil, nil, err
}
tok := m.Tokenizer()
if len(input.Images) == 0 {
prepared, err := m.PrepareMedia([]model.Segment{{Tokens: tok.Encode(full, false)}})
if err != nil {
return nil, nil, nil, nil, err
}
want := tok.Encode(prefix, false)
for prepared.ScorePrefix < len(want) && prepared.ScorePrefix < len(prepared.Tokens) && want[prepared.ScorePrefix] == prepared.Tokens[prepared.ScorePrefix] {
prepared.ScorePrefix++
}
return prepared, nil, ids, bias, nil
}
before := fmt.Sprintf("[kind] %s\n[state] ", q.Type)
segments := []model.Segment{{Tokens: tok.Encode(before, false)}}
for _, data := range input.Images {
segments = append(segments, model.Segment{Kind: "image", Data: data})
}
after := full[len(before)+len(input.Images)*len(imageMarker):]
segments = append(segments, model.Segment{Tokens: tok.Encode(after, false)})
prepared, err := m.PrepareMedia(segments)
if err != nil {
return nil, nil, nil, nil, err
}
// The cache still recognizes identical media requests and safe boundaries.
// The text-only prefix boundary is omitted here because multimodal token
// expansion changes it and the caller's images are separate from state.
return prepared, segments, ids, bias, nil
}
func (m *Model) finishScore(hidden *mlx.Array, n int, ids []int32, bias []float32, kind string) []float32 {
last := hidden.Slice(mlx.Slice(), mlx.Slice(n-1, n), mlx.Slice())
selected := m.Model.UnembedCandidates(last, mlx.FromValues(ids, len(ids)))
logits := mlx.DivScalar(mlx.Add(selected, mlx.FromValues(bias, len(bias))), m.temperature[kind])
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
badRequest := func(err error) (llm.ScoreResponse, error) {
return result, api.StatusError{StatusCode: http.StatusBadRequest, ErrorMessage: err.Error()}
}
if len(input.Rows) < 1 || len(input.Rows) > 64 || input.MaxTokens < 1 || input.MaxTokens > m.MaxContextLength() {
return badRequest(fmt.Errorf("invalid AutoTrust decision question count or context limit"))
}
for i, row := range input.Rows {
if err := ctx.Err(); err != nil {
return result, err
}
prepared, segments, ids, bias, err := m.prepareRow(input, row.Question)
if err != nil {
return badRequest(fmt.Errorf("question %d: %w", i, err))
}
if len(prepared.Tokens) > input.MaxTokens {
return badRequest(fmt.Errorf("question %d needs %d tokens; limit is %d", i, len(prepared.Tokens), input.MaxTokens))
}
mlx.Scoped(func() {
var hidden *mlx.Array
var restored int
hidden, restored, err = forward(ctx, prepared, segments)
cached += restored
if err == nil {
result.Logits = append(result.Logits, m.finishScore(hidden, len(prepared.Tokens), ids, bias, row.Question.Type))
}
})
if err != nil {
return result, err
}
result.InputTokens += len(prepared.Tokens)
}
return result, ctx.Err()
}
@@ -0,0 +1,130 @@
package autotrustdecision
import (
"fmt"
"math"
"slices"
"strings"
"testing"
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/llm"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
"github.com/ollama/ollama/mlxrunner/model/qwen3_5"
"github.com/ollama/ollama/mlxrunner/nn"
)
func TestBareDecisionPrompt(t *testing.T) {
m := &Model{Model: &qwen3_5.Model{}, choiceCodes: []string{"A", "B", "C"}, choiceIDs: []int32{10, 11, 12}}
m.head.Bias = make([]float32, 24)
m.head.VerbalizerIDs = make([]int32, 24)
got, prefix, ids, bias, err := m.prompt(llm.ScoreRequest{State: "Customer was charged twice."}, &llm.ScoreQuestion{
Type: "choice", Instructions: "Which team should handle this?", Options: []string{"billing", "shipping", "support"},
})
if err != nil {
t.Fatal(err)
}
want := "[kind] choice\n[state] Customer was charged twice.\n[question] Which team should handle this?\n[options]\nA) billing\nB) shipping\nC) support\n[decision]:"
if got != want || prefix != "[kind] choice\n[state] Customer was charged twice.\n[question] " {
t.Fatalf("publisher bare-v1 prompt = %q, prefix = %q", got, prefix)
}
if !slices.Equal(ids, []int32{10, 11, 12}) || len(bias) != 3 {
t.Fatalf("choice readout ids = %v, bias = %v", ids, bias)
}
}
func TestImageCountLimit(t *testing.T) {
m := &Model{}
images := make([]api.ImageData, maxAutoTrustDecisionImages+1)
_, _, _, _, err := m.prompt(llm.ScoreRequest{Images: images}, &llm.ScoreQuestion{Type: "noul"})
if err == nil {
t.Fatal("accepted more than the maximum image count")
}
}
func TestCompactHeadSupportsConfiguredWideLabels(t *testing.T) {
const maxChoices = 255
m := &Model{
Model: &qwen3_5.Model{},
choiceCodes: make([]string, maxChoices),
choiceIDs: make([]int32, maxChoices),
}
m.head.Bias = make([]float32, 24)
m.head.VerbalizerIDs = make([]int32, 24)
for i := range m.choiceCodes {
m.choiceCodes[i] = fmt.Sprintf("option-%d", i)
m.choiceIDs[i] = int32(i)
}
q := &llm.ScoreQuestion{Type: "choice", Options: make([]string, maxChoices)}
_, _, ids, _, err := m.prompt(llm.ScoreRequest{}, q)
if err != nil || len(ids) != maxChoices {
t.Fatalf("255 options: ids = %d, err = %v", len(ids), err)
}
q.Options = append(q.Options, "extra")
if _, _, _, _, err := m.prompt(llm.ScoreRequest{}, q); err == nil {
t.Fatal("accepted 256 options")
}
}
func TestCompactHeadUsesResolvedChoiceLimit(t *testing.T) {
m := &Model{Model: &qwen3_5.Model{Vision: &qwen3_5.VisionConfig{}}, choiceCodes: make([]string, 16), choiceIDs: make([]int32, 16)}
m.head.Bias = make([]float32, 24)
m.head.VerbalizerIDs = make([]int32, 24)
q := &llm.ScoreQuestion{Type: "choice", Options: make([]string, 16)}
if _, _, _, _, err := m.prompt(llm.ScoreRequest{}, q); err != nil {
t.Fatalf("16 options: %v", err)
}
q.Options = append(q.Options, "extra")
if _, _, _, _, err := m.prompt(llm.ScoreRequest{}, q); err == nil || !strings.Contains(err.Error(), "2–16 options") {
t.Fatalf("17 options: got %v, want 2–16 limit", err)
}
}
func TestWideChoiceHeadUsesAllAvailableBiases(t *testing.T) {
const maxChoices = 255
m := &Model{choiceCodes: make([]string, maxChoices), choiceIDs: make([]int32, maxChoices)}
m.head.Bias = make([]float32, 264)
m.head.VerbalizerIDs = make([]int32, 264)
for i := range m.choiceCodes {
m.choiceCodes[i] = fmt.Sprintf("option-%d", i)
m.choiceIDs[i] = int32(i)
m.head.Bias[8+i] = float32(i + 1)
}
q := &llm.ScoreQuestion{Type: "choice", Options: make([]string, maxChoices)}
_, _, ids, bias, err := m.prompt(llm.ScoreRequest{}, q)
if err != nil || len(ids) != maxChoices || len(bias) != maxChoices {
t.Fatalf("wide head readout: ids = %d, biases = %d, err = %v", len(ids), len(bias), err)
}
if bias[maxChoices-1] != maxChoices {
t.Fatalf("last choice bias = %g, want %d", bias[maxChoices-1], maxChoices)
}
}
func TestFinishScoreUsesLastPositionBiasAndTemperature(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
mlx.Scoped(func() {
weight := mlx.FromValues([]float32{
1, 0, 0, // token 0
0, 1, 0, // token 1
0, 0, 1, // token 2
1, 1, 1, // token 3
}, 4, 3)
m := &Model{
Model: &qwen3_5.Model{LMHead: nn.NewLinear(weight, nil)},
temperature: map[string]float32{"choice": 2},
}
hidden := mlx.FromValues([]float32{99, 99, 99, 2, 3, 5}, 1, 2, 3)
got := m.finishScore(hidden, 2, []int32{3, 1, 0}, []float32{2, -1, 4}, "choice")
want := []float32{6, 1, 3}
if len(got) != len(want) {
t.Fatalf("score count = %d, want %d", len(got), len(want))
}
for i, value := range got {
if math.Abs(float64(value-want[i])) > 1e-6 {
t.Fatalf("candidate %d: score = %g, want %g", i, value, want[i])
}
}
})
})
}
+1 -1
View File
@@ -1021,7 +1021,7 @@ func (s *Server) SystemOneHandler(c *gin.Context) {
}
var encoding string
switch m.Config.Renderer {
case "tev1", "clef", "strands", "kev", "pplx", "d3", "d1":
case "tev1", "clef", "strands", "kev", "pplx", "d3", "autotrust-decision", "d1":
encoding = m.Config.Renderer
}
compiled, err := decision.Compile(req, encoding)
+20 -5
View File
@@ -173,6 +173,10 @@ func TestSystemOneHandler(t *testing.T) {
createSafetensorsTestModel(t, "safetensors-decision-only", config, []manifest.Layer{params})
config.Renderer = "tev1"
createSafetensorsTestModel(t, "safetensors-tev1", config, []manifest.Layer{params})
config.Renderer = "d3"
createSafetensorsTestModel(t, "safetensors-d3", config, []manifest.Layer{params})
config.Renderer = "autotrust-decision"
createSafetensorsTestModel(t, "safetensors-autotrust-decision", config, []manifest.Layer{params})
config.Renderer = "strands"
createSafetensorsTestModel(t, "safetensors-strands", config, []manifest.Layer{params})
config.Renderer = "clef"
@@ -280,6 +284,9 @@ func TestSystemOneHandler(t *testing.T) {
{"missing model", `{"model":"missing","state":"x","questions":{"x":{"type":"noul","instructions":"q"}}}`, nil, 404, 0, false},
{"cloud", `{"model":"decision:cloud","state":"x","questions":{"x":{"type":"noul","instructions":"q"}}}`, nil, 400, 0, false},
{"safetensors success", `{"model":"safetensors-decision","state":"x","questions":{"refund":{"type":"noul","instructions":"q"}}}`, nil, 200, 1, false},
{"D3 safetensors", `{"model":"safetensors-d3","state":"x","questions":{"pick":{"type":"choice","instructions":"q","criteria":{"a":null,"b":null}}}}`, nil, 200, 1, false},
{"AutoTrust decision safetensors", `{"model":"safetensors-autotrust-decision","state":"x","questions":{"pick":{"type":"choice","instructions":"q","criteria":{"a":null,"b":null}}}}`, nil, 200, 1, false},
{"AutoTrust decision needs six score levels", `{"model":"safetensors-autotrust-decision","state":"x","questions":{"rating":{"type":"score","instructions":"q","criteria":[0,1,2,3,4]}}}`, nil, 400, 0, false},
{"safetensors decision only", `{"model":"safetensors-decision-only","state":"x","questions":{"refund":{"type":"noul","instructions":"q"}}}`, nil, 200, 1, false},
{"Perplexity native scorer receives system", `{"model":"safetensors-pplx","state":"x","questions":{"refund":{"type":"noul","instructions":"q"}}}`, nil, 200, 1, false},
{"Perplexity requires model system", `{"model":"safetensors-pplx-no-system","state":"x","questions":{"refund":{"type":"noul","instructions":"q"}}}`, nil, 400, 0, false},
@@ -393,18 +400,22 @@ func TestSystemOneHandler(t *testing.T) {
}
var response struct {
Answers map[string]struct {
Noul float64 `json:"noul"`
Noul float64 `json:"noul"`
Choice string `json:"choice"`
} `json:"answers"`
Usage decision.Usage `json:"usage"`
}
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
choiceCase := tt.name == "D3 safetensors" || tt.name == "AutoTrust decision safetensors"
outputTokens := 2
if len(runner.request.Fields) > 0 || runner.native || ref.model.Load().Config.Renderer == "kev" || ref.model.Load().Config.Renderer == "pplx" {
if len(runner.request.Fields) > 0 || runner.native || ref.model.Load().Config.Renderer == "kev" || ref.model.Load().Config.Renderer == "pplx" || choiceCase {
outputTokens = 0
}
if response.Answers["refund"].Noul < 0.88 || response.Usage.InputTokens != 123 || response.Usage.OutputTokens != outputTokens {
if response.Usage.InputTokens != 123 || response.Usage.OutputTokens != outputTokens ||
(choiceCase && response.Answers["pick"].Choice != "b") ||
(!choiceCase && response.Answers["refund"].Noul < 0.88) {
t.Fatalf("incorrect scoring response: %s", w.Body)
}
if runner.native {
@@ -424,6 +435,10 @@ func TestSystemOneHandler(t *testing.T) {
if ref.model.Load().Config.Renderer == "pplx" && (runner.request.System != "Model-specific scoring instructions." || len(runner.request.Rows) != 1 || runner.request.Rows[0].Question == nil) {
t.Fatalf("Perplexity scorer lost its system prompt or native question: %+v", runner.request)
}
if (ref.model.Load().Config.Renderer == "d3" || ref.model.Load().Config.Renderer == "autotrust-decision") &&
(len(runner.request.Rows) != 1 || runner.request.Rows[0].Question == nil) {
t.Fatalf("native scorer lost its question: %+v", runner.request)
}
var prompt string
if len(runner.request.Rows) > 0 {
prompt = runner.request.Rows[0].Prompt
@@ -443,9 +458,9 @@ 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.Load().Config.Renderer == "pplx" {
} else if ref.model.Load().Config.Renderer == "pplx" || ref.model.Load().Config.Renderer == "d3" || ref.model.Load().Config.Renderer == "autotrust-decision" {
if prompt != "" {
t.Fatalf("Perplexity scorer received a generic rendered prompt: %q", prompt)
t.Fatalf("native scorer received a generic rendered prompt: %q", prompt)
}
} else if ref.model.Load().Config.Renderer == "kev" {
if prompt != "" || len(runner.request.State) != 70<<10 || runner.request.Rows[0].Question == nil {