mlxrunner: add Inkling 2 Mini (#19799)

* mlxrunner: add Inkling 2 Mini

* mlx: fuse Inkling 2 Mini residual mixing on Metal

Fuse RMS normalization and query scoring in one kernel. Apply the
softmax weights in a second kernel to avoid storing per-query products.

* create: expose Inkling 2 Mini context length in model metadata

Copy model_max_length to max_position_embeddings during import so
ollama show reports the checkpoint's context length. Reject configs
that specify conflicting limits.

* mlxrunner: reduce Metal dispatches in Inkling 2 Mini decode

Reuse the prefill mask shader to compute relative position bias in one
dispatch for single-query attention. On M3 Ultra with Metal 3, compute
the loop controller's gain and forget projections in one matrix multiply.
This commit is contained in:
Daniel Hiltgen authored and GitHub committed 2026-11-20 18:38:44 -08:00
1 parent afc7c06022
commit cecac8bf1b
93 files changed
+9572 -267

No files matched your search

+1
View File
@@ -13,3 +13,4 @@ llama/build-info.cpp linguist-generated
* text=auto
*.go text eol=lf
model/renderers/testdata/inkling2_chat_template.jinja text eol=lf
+14 -1
View File
@@ -50,8 +50,21 @@ func Classify(inv Inventory, requested string) (Classification, error) {
return Classification{}, fmt.Errorf("unsupported fp8 source: tensor %s is F8_E5M2; only F8_E4M3 block-FP8 sources are supported", name)
}
switch detectKind(inv) {
kind := detectKind(inv)
if inv.Config.Architecture() == inkling2Architecture {
kind, err = classifyInkling2Banks(inv, kind)
if err != nil {
return Classification{}, err
}
if kind == SourceFloat && requested != "" {
return Classification{}, fmt.Errorf("Inkling 2 requires importing the source weights without --quantize (requested %q)", requested)
}
}
switch kind {
case SourceFloat:
if requested != "" && inv.Config.Architecture() == "Inkling2ForConditionalGenerationMTP" {
return Classification{}, fmt.Errorf("Inkling 2 MTP requires importing the draft weights without --draft-quantize (requested %q)", requested)
}
return Classification{Kind: SourceFloat, Quantize: requested}, nil
case SourcePrequantized:
+93
View File
@@ -0,0 +1,93 @@
package create
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"strings"
"github.com/ollama/ollama/mlx/quant"
)
const inkling2Architecture = "Inkling2LoopForConditionalGeneration"
// Expose Inkling's model_max_length as max_position_embeddings for ollama show.
func inkling2ContextConfig(raw []byte) ([]byte, error) {
var config map[string]any
decoder := json.NewDecoder(bytes.NewReader(raw))
decoder.UseNumber()
if err := decoder.Decode(&config); err != nil {
return nil, err
}
text, _ := config["text_config"].(map[string]any)
limit, _ := text["model_max_length"].(json.Number)
if n, err := limit.Int64(); err != nil || n <= 0 {
return nil, fmt.Errorf("Inkling 2 requires a positive text_config.model_max_length")
}
if existing, ok := text["max_position_embeddings"]; ok {
if existing != limit {
return nil, fmt.Errorf("Inkling 2 text_config.max_position_embeddings disagrees with model_max_length")
}
return raw, nil
}
text["max_position_embeddings"] = limit
return json.Marshal(config)
}
func inkling2BankQuantization(name string, inv Inventory) (string, error) {
if !strings.HasSuffix(name, ".experts.w13_weight") && !strings.HasSuffix(name, ".experts.w2_weight") {
return "", nil
}
weight, scale := inv.Tensors[name], inv.Tensors[name+"_scale"]
var mode string
switch {
case strings.EqualFold(weight.Dtype, "U8") && isE4M3Dtype(scale.Dtype):
mode = "nvfp4"
case isE4M3Dtype(weight.Dtype) && strings.EqualFold(scale.Dtype, "U8"):
mode = "mxfp8"
default:
return "", nil
}
// Packing the last dimension into U32 words must preserve every byte.
if len(weight.Shape) != 3 || weight.Shape[2] <= 0 || weight.Shape[2]%4 != 0 {
return "", fmt.Errorf("packed Inkling2 expert bank %s has invalid shape %v", name, weight.Shape)
}
return mode, nil
}
func classifyInkling2Banks(inv Inventory, kind SourceKind) (SourceKind, error) {
for name := range inv.Tensors {
mode, err := inkling2BankQuantization(name, inv)
if err != nil {
return kind, err
}
if mode != "" {
kind = SourcePrequantized
}
}
return kind, nil
}
// Inkling ships stacked gate/up and down projections. The runtime looks up
// each bank and its scales by their publisher names. Only their headers change.
func inkling2ExpertBank(name string, inv Inventory) (BlobSpec, bool) {
mode, err := inkling2BankQuantization(name, inv)
if err != nil || mode == "" {
return BlobSpec{}, false
}
weight, scale := inv.Tensors[name], inv.Tensors[name+"_scale"]
w := TensorSpec{Name: name, Sources: []SourceTensor{weight}, OutDtype: "U32", OutShape: []int32{weight.Shape[0], weight.Shape[1], weight.Shape[2] / 4}}
s := TensorSpec{Name: scale.Name, Sources: []SourceTensor{scale}}
w.Transform = TransformRepackFP8
if mode == "nvfp4" {
w.Transform = TransformRepackFP4
s.Transform, s.OutDtype = TransformRelabelU8, "U8"
}
groupSize, _, _ := quant.Params(mode)
return BlobSpec{
Name: name,
Tensors: []TensorSpec{w, s},
Metadata: prequantMetadata(inv, mode, strconv.Itoa(groupSize)),
}, true
}
+196
View File
@@ -0,0 +1,196 @@
package create
import (
"bytes"
"context"
"io"
"path/filepath"
"strings"
"testing"
st "github.com/ollama/ollama/fs/safetensors"
)
func TestInkling2ExpertBankImport(t *testing.T) {
for _, tc := range []struct {
mode, bank, weightDtype, scaleDtype, groupSize string
width int32
}{
{"nvfp4", "w13_weight", "U8", "F8_E4M3", "16", 16},
{"mxfp8", "w2_weight", "F8_E4M3", "U8", "32", 64},
} {
t.Run(tc.mode, func(t *testing.T) {
bank := "model.llm.layers.6.mlp.experts." + tc.bank
weights := make([]byte, 2*tc.width)
for i := range weights {
weights[i] = byte(i*7 + 5)
}
scales := []byte{1, 9, 127, 254}
tensors := []*st.TensorData{
st.NewTensorDataFromBytes(bank, tc.weightDtype, []int32{2, 1, tc.width}, weights),
st.NewTensorDataFromBytes(bank+"_scale", tc.scaleDtype, []int32{2, 1, 2}, scales),
}
if tc.mode == "nvfp4" {
tensors = append(tensors,
st.NewTensorDataFromBytes(bank+"_amax", "F32", []int32{2}, encodeFloat32s(3, 5)),
st.NewTensorDataFromBytes(bank+"_outer_scale_denominator", "F32", []int32{1}, f32le(7)),
)
}
dir := t.TempDir()
writeConfigJSON(t, dir, `{"architectures":["Inkling2LoopForConditionalGeneration"],"text_config":{"model_max_length":32768}}`)
createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), tensors)
inv, err := ReadInventory(dir)
if err != nil {
t.Fatal(err)
}
class, err := Classify(inv, "")
if err != nil || class != (Classification{Kind: SourcePrequantized, Quantize: tc.mode}) {
t.Fatalf("Classify() = %+v, %v; want prequantized %s", class, err, tc.mode)
}
if _, err := Classify(inv, tc.mode); err == nil || !strings.Contains(err.Error(), "cannot requantize") {
t.Fatalf("Classify(%q) error = %v, want already-quantized source error", tc.mode, err)
}
store := newCaptureStore()
writeManifest := func(context.Context, string, ManifestInfo) error { return nil }
if err := Create(t.Context(), "inkling2", dir, testPipelineOptions(), store, writeManifest, func(string) {}); err != nil {
t.Fatal(err)
}
want := map[string]io.Reader{
"config.json": strings.NewReader(`{"architectures":["Inkling2LoopForConditionalGeneration"],"text_config":{"max_position_embeddings":32768,"model_max_length":32768}}`),
bank: st.BuildPackedSafetensorsReaderWithMetadata([]*st.TensorData{
st.NewTensorDataFromBytes(bank, "U32", []int32{2, 1, tc.width / 4}, weights),
st.NewTensorDataFromBytes(bank+"_scale", "U8", []int32{2, 1, 2}, scales),
}, map[string]string{"quant_type": tc.mode, "group_size": tc.groupSize}),
}
for _, calibration := range tensors[2:] {
want[calibration.Name] = st.BuildPackedSafetensorsReader([]*st.TensorData{calibration})
}
if len(store.blobs) != len(want) {
t.Fatalf("got blobs %v, want %d blobs", store.names(), len(want))
}
for name, reader := range want {
expected, err := io.ReadAll(reader)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(store.blobs[name], expected) {
t.Errorf("imported %s differs from the expected safetensors header or payload", name)
}
}
})
}
}
func TestCreateInkling2RejectsTargetQuantization(t *testing.T) {
dir := t.TempDir()
writeConfigJSON(t, dir, `{"architectures":["Inkling2LoopForConditionalGeneration"]}`)
createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{
st.NewTensorDataFromBytes("model.llm.layers.0.attn.wq_du.weight", "BF16", []int32{64, 64}, make([]byte, 64*64*2)),
})
for _, quantize := range []string{"nvfp4", "mxfp4", "mxfp8", "int4", "int8"} {
t.Run(quantize, func(t *testing.T) {
opts := testPipelineOptions()
opts.Quantize = quantize
store := newCaptureStore()
err := Create(t.Context(), "inkling2", dir, opts, store, func(context.Context, string, ManifestInfo) error {
t.Error("unexpected manifest write")
return nil
}, func(string) {})
if err == nil || !strings.Contains(err.Error(), "without --quantize") {
t.Fatalf("Create() error = %v, want advice to omit --quantize", err)
}
if len(store.blobs) != 0 {
t.Fatalf("Create() wrote blobs before rejecting target quantization: %v", store.names())
}
})
}
}
func TestInkling2DraftQuantization(t *testing.T) {
dir := t.TempDir()
writeConfigJSON(t, dir, `{"architectures":["Inkling2ForConditionalGenerationMTP"]}`)
const name = "layers.0.self_attn.q_proj.weight"
weights := make([]byte, 64*64*2)
tensor := st.NewTensorDataFromBytes(name, "BF16", []int32{64, 64}, weights)
createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{tensor})
validation := testPipelineOptions().Validation
for _, quantize := range []string{"nvfp4", "mxfp4", "mxfp8", "int4", "int8"} {
t.Run(quantize, func(t *testing.T) {
store := newCaptureStore()
_, err := CreateDraftLayers(t.Context(), dir, "draft.", "draft/", quantize, validation, store, func(string) {})
if err == nil || !strings.Contains(err.Error(), "without --draft-quantize") {
t.Fatalf("CreateDraftLayers(%q) error = %v, want advice to omit --draft-quantize", quantize, err)
}
if len(store.blobs) != 0 {
t.Fatalf("CreateDraftLayers(%q) wrote blobs: %v", quantize, store.names())
}
})
}
store := newCaptureStore()
if _, err := CreateDraftLayers(t.Context(), dir, "draft.", "draft/", "", validation, store, func(string) {}); err != nil {
t.Fatal(err)
}
const draftName = "draft." + name
want, err := io.ReadAll(st.BuildPackedSafetensorsReader([]*st.TensorData{tensor.WithName(draftName)}))
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(store.blobs[draftName], want) {
t.Errorf("raw import changed %s", draftName)
}
}
func TestInkling2BankScope(t *testing.T) {
for _, tc := range []struct{ arch, weight string }{
{"Qwen3ForCausalLM", "model.llm.layers.6.mlp.experts.w13_weight"},
{inkling2Architecture, "model.llm.layers.6.mlp_sconv.down_weight"},
} {
t.Run(tc.arch, func(t *testing.T) {
inv := newInventory(sourceModelConfig{Architectures: []string{tc.arch}}, map[string]string{
tc.weight: "U8", tc.weight + "_scale": "F8_E4M3",
})
weight := inv.Tensors[tc.weight]
weight.Shape = []int32{2, 1, 16}
inv.Tensors[tc.weight] = weight
class, err := Classify(inv, "")
if err != nil || class.Kind != SourceFloat {
t.Fatalf("Classify() = %+v, %v; want float", class, err)
}
// A different, ordinary prequantized weight in the same inventory
// must not cause the underscore names to fuse during planning.
inv.Tensors["linear.weight"] = SourceTensor{Name: "linear.weight", Dtype: "U32"}
inv.Tensors["linear.scales"] = SourceTensor{Name: "linear.scales", Dtype: "BF16"}
class, err = Classify(inv, "")
if err != nil || class.Kind != SourcePrequantized {
t.Fatalf("Classify() with MLX scales = %+v, %v; want prequantized", class, err)
}
specs, err := Plan(inv, class, nil)
if err != nil {
t.Fatal(err)
}
for _, name := range []string{tc.weight, tc.weight + "_scale"} {
blob, ok := specByName(specs, name)
if !ok || len(blob.Tensors) != 1 || blob.Tensors[0].Transform != TransformNone || blob.Metadata != nil {
t.Errorf("blob %q = %+v, want unchanged source tensor", name, blob)
}
}
})
}
}
func TestInkling2RejectsMalformedPackedBank(t *testing.T) {
const bank = "model.llm.layers.6.mlp.experts.w13_weight"
for _, shape := range [][]int32{{1, 16}, {1, 1, 7}} {
inv := newInventory(sourceModelConfig{Architectures: []string{inkling2Architecture}}, map[string]string{
bank: "U8", bank + "_scale": "F8_E4M3",
})
weight := inv.Tensors[bank]
weight.Shape = shape
inv.Tensors[bank] = weight
for _, request := range []string{"", "int4"} {
if _, err := Classify(inv, request); err == nil {
t.Errorf("Classify() accepted packed bank of shape %v for quantization %q", shape, request)
}
}
}
}
+6
View File
@@ -102,6 +102,12 @@ func Create(ctx context.Context, modelName, modelDir string, opts PipelineOption
if err != nil {
return err
}
if inv.Config.Architecture() == inkling2Architecture {
inv.RawConfig, err = inkling2ContextConfig(inv.RawConfig)
if err != nil {
return err
}
}
if inv.Config.Architecture() == "KevForDecision" && class.Kind == SourceFloat && class.Quantize == "" {
modelConfig.FileType, err = kevFileType(inv)
if err != nil {
+11 -6
View File
@@ -256,6 +256,11 @@ func planPrequantExpertGroup(group string, weights []SourceTensor, fused map[str
// ok=false when name is not a prequantized weight (a companion or a plain
// tensor).
func matchPrequant(name string, inv Inventory) (BlobSpec, []string, bool) {
if inv.Config.Architecture() == inkling2Architecture {
if spec, ok := inkling2ExpertBank(name, inv); ok {
return spec, []string{name + "_scale"}, true
}
}
for _, p := range prequantPatterns {
base, ok := strings.CutSuffix(name, p.weightSuffix)
if !ok {
@@ -319,7 +324,7 @@ func matchPrequant(name string, inv Inventory) (BlobSpec, []string, bool) {
}
}
return BlobSpec{Name: outWeight, Tensors: tensors, Metadata: prequantMetadata(inv, p)}, consumed, true
return BlobSpec{Name: outWeight, Tensors: tensors, Metadata: prequantMetadata(inv, p.forceQuantType, p.defaultGroupSize)}, consumed, true
}
return BlobSpec{}, nil, false
}
@@ -348,17 +353,17 @@ func matchesDtype(dtype string, allowed []string) bool {
// prequantMetadata builds the fused blob's metadata: the source config's quant
// metadata, with the pattern's quant_type override and group_size default
// applied. Returns nil when there is nothing to record.
func prequantMetadata(inv Inventory, p prequantPattern) map[string]string {
func prequantMetadata(inv Inventory, quantType, defaultGroupSize string) map[string]string {
md := make(map[string]string)
for k, v := range inv.Config.QuantMetadata() {
md[k] = v
}
if p.forceQuantType != "" {
md["quant_type"] = p.forceQuantType
if quantType != "" {
md["quant_type"] = quantType
}
if p.defaultGroupSize != "" {
if defaultGroupSize != "" {
if _, ok := md["group_size"]; !ok {
md["group_size"] = p.defaultGroupSize
md["group_size"] = defaultGroupSize
}
}
if len(md) == 0 {
+41 -8
View File
@@ -17,10 +17,21 @@ import (
"github.com/ollama/ollama/envconfig"
)
// Inkling can spend most of a request's budget reasoning. Give its longer
// requests their own deadline so earlier cases cannot consume it.
func inklingBatchContext(t *testing.T, ctx context.Context, info *api.ShowResponse, timeout time.Duration) context.Context {
if info.Renderer != "inkling2" {
return ctx
}
ctx, cancel := context.WithTimeout(t.Context(), timeout)
t.Cleanup(cancel)
return ctx
}
// runMLXBatching adds cache reuse and slot lifecycle checks to the release
// concurrency group. Capacity one exercises the same requests serially.
func runMLXBatching(t *testing.T, modelName string) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Minute)
defer cancel()
client, _, cleanup := InitServerConnection(ctx, t)
defer cleanup()
@@ -47,6 +58,7 @@ func runMLXBatching(t *testing.T, modelName string) {
requests[i] = request("What is the capital of "+countries[i]+"? Answer with just the city name.", 128)
}
t.Run("isolation", func(t *testing.T) {
ctx := inklingBatchContext(t, ctx, info, 5*time.Minute)
type result struct {
text string
final api.GenerateResponse
@@ -82,6 +94,7 @@ func runMLXBatching(t *testing.T, modelName string) {
}
})
t.Run("reuse", func(t *testing.T) {
ctx := inklingBatchContext(t, ctx, info, 5*time.Minute)
// When every slot is free, a repeat can select its cached prefix. A
// concurrent repeat may instead land on another available slot.
for _, req := range requests {
@@ -108,17 +121,22 @@ func runMLXBatching(t *testing.T, modelName string) {
}
}
})
storyBudget := 256
if info.Renderer == "inkling2" {
storyBudget = 512
}
for _, tc := range []struct {
name string
cancel bool
}{{"cancel", true}, {"finish", false}} {
t.Run("join_and_leave/"+tc.name, func(t *testing.T) {
ctx := inklingBatchContext(t, ctx, info, 5*time.Minute)
longCtx, stop := context.WithCancel(ctx)
defer stop()
first := make(chan struct{}, 1)
finished := make(chan error, 1)
var final api.GenerateResponse
long := request("Write a detailed 2000-word story about a lighthouse keeper. Start the story immediately and keep writing.", 256)
long := request("Write a detailed 2000-word story about a lighthouse keeper. Start the story immediately and keep writing.", storyBudget)
go func() {
finished <- client.Generate(longCtx, &long, func(chunk api.GenerateResponse) error {
if chunk.Response != "" || chunk.Thinking != "" {
@@ -165,7 +183,7 @@ func runMLXBatching(t *testing.T, modelName string) {
if !errors.Is(err, context.Canceled) {
t.Fatalf("cancel: %v", err)
}
} else if err != nil || !final.Done || final.EvalCount != 256 {
} else if err != nil || !final.Done || final.EvalCount != storyBudget {
t.Fatalf("surviving request: %+v, %v", final, err)
}
text = ""
@@ -177,6 +195,7 @@ func runMLXBatching(t *testing.T, modelName string) {
}
t.Run("independent_grammar", func(t *testing.T) {
ctx := inklingBatchContext(t, ctx, info, 5*time.Minute)
errs := make(chan error, 2)
for _, city := range cities[:2] {
go func() {
@@ -204,7 +223,7 @@ func TestMLXBatchingVision(t *testing.T) {
if testModel == "" {
t.Skip("set OLLAMA_TEST_MODEL to a published MLX vision model")
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Minute)
defer cancel()
client, _, cleanup := InitServerConnection(ctx, t)
defer cleanup()
@@ -215,6 +234,10 @@ func TestMLXBatchingVision(t *testing.T) {
if !slices.Contains(info.Capabilities, model.CapabilityVision) {
t.Skip("model has no vision capability")
}
answerBudget := 128
if info.Renderer == "inkling2" {
answerBudget = 1024
}
road, desk, _ := decodeTestImages(t)
cases := []struct {
image api.ImageData
@@ -225,18 +248,19 @@ func TestMLXBatchingVision(t *testing.T) {
{nil, "What is the capital of Japan? Begin with the city name and then describe the city's history in detail.", "tokyo"},
}
for round := range 2 {
roundCtx := inklingBatchContext(t, ctx, info, 8*time.Minute)
start := make(chan struct{})
results := make(chan error, len(cases))
for _, tc := range cases {
go func() {
<-start
req := api.GenerateRequest{Model: testModel, Runner: "mlx", Prompt: tc.prompt, Think: &api.ThinkValue{Value: false}, KeepAlive: &api.Duration{Duration: time.Minute}, Options: map[string]any{"num_predict": 128, "num_ctx": 4096, "temperature": 0}}
req := api.GenerateRequest{Model: testModel, Runner: "mlx", Prompt: tc.prompt, Think: &api.ThinkValue{Value: false}, KeepAlive: &api.Duration{Duration: time.Minute}, Options: map[string]any{"num_predict": answerBudget, "num_ctx": 4096, "temperature": 0}}
if tc.image != nil {
req.Images = []api.ImageData{tc.image}
}
var text string
var final api.GenerateResponse
err := client.Generate(ctx, &req, func(chunk api.GenerateResponse) error {
err := client.Generate(roundCtx, &req, func(chunk api.GenerateResponse) error {
text += chunk.Response
if chunk.Done {
final = chunk
@@ -268,13 +292,22 @@ func TestMLXBatchingLongPrompts(t *testing.T) {
if testModel == "" {
t.Skip("set OLLAMA_TEST_MODEL to a published MLX model")
}
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Minute)
ctx, cancel := context.WithTimeout(t.Context(), 8*time.Minute)
defer cancel()
client, _, cleanup := InitServerConnection(ctx, t)
defer cleanup()
info, err := client.Show(ctx, &api.ShowRequest{Model: testModel})
if err != nil {
t.Fatal(err)
}
ctx = inklingBatchContext(t, ctx, info, 15*time.Minute)
start := make(chan struct{})
cities := []string{"Paris", "Tokyo", "Rome", "Madrid", "London", "Berlin", "Ottawa", "Cairo"}
countries := []string{"France", "Japan", "Italy", "Spain", "the United Kingdom", "Germany", "Canada", "Egypt"}
historyBudget := 512
if info.Renderer == "inkling2" {
historyBudget = 3072
}
rows := max(2, min(len(cities), int(envconfig.NumParallel())))
t.Logf("keeping %d requests active across unequal prompt lengths", rows)
results := make(chan error, rows)
@@ -285,7 +318,7 @@ func TestMLXBatchingLongPrompts(t *testing.T) {
repetitions = 180
}
prompt := strings.Repeat("The island has an old lighthouse, a harbor, and a village beside the sea. ", repetitions)
req := api.GenerateRequest{Model: testModel, Runner: "mlx", Prompt: prompt + "\nIgnore the preceding background. What is the capital of " + countries[i] + "? Begin with the city name, then write a detailed 1000-word history of the city.", Think: &api.ThinkValue{Value: false}, KeepAlive: &api.Duration{Duration: time.Minute}, Options: map[string]any{"num_predict": 512, "num_ctx": 8192, "temperature": 0}}
req := api.GenerateRequest{Model: testModel, Runner: "mlx", Prompt: prompt + "\nIgnore the preceding background. What is the capital of " + countries[i] + "? Begin with the city name, then write a detailed 1000-word history of the city.", Think: &api.ThinkValue{Value: false}, KeepAlive: &api.Duration{Duration: time.Minute}, Options: map[string]any{"num_predict": historyBudget, "num_ctx": 8192, "temperature": 0}}
<-start
var text, thinking string
var final api.GenerateResponse
+1 -1
View File
@@ -50,7 +50,7 @@ func runVisionOCRDocument(t *testing.T, model string) {
{
Role: "user",
Content: "Scan the entire document and read the unique FINAL AUDIT CODE field. " +
"Reply with only its value.",
"Reply with only its value. Use ASCII hyphens between fields.",
Images: []api.ImageData{document},
},
},
+4
View File
@@ -14,6 +14,7 @@ import (
"github.com/ollama/ollama/format"
"github.com/ollama/ollama/fs/gguf"
"github.com/ollama/ollama/ml"
"github.com/ollama/ollama/types/model"
)
var ErrLoadRequiredFull = errors.New("unable to load full model on GPU")
@@ -172,6 +173,8 @@ type MediaData struct {
Data []byte `json:"data"`
ID int `json:"id"`
Kind MediaKind
// TagOffsets are the byte offsets of this attachment's tags, in prompt order.
TagOffsets []int `json:"tag_offsets,omitempty"`
}
type Message struct {
@@ -216,6 +219,7 @@ type CompletionRequest struct {
// response begins with, which Format leaves free; none when the response
// starts in content.
ThinkingClose []string
FormatFrames *model.StructuredOutputFrames // MLX framed structured output, when the parser supplies it
// Logprobs specifies whether to include log probabilities in the response
Logprobs bool
+159
View File
@@ -0,0 +1,159 @@
package mlx
import "math"
// MatmulBF16Weight computes x [M,K] times weight [N,K] transposed. Short projections
// are bandwidth bound, so weights stay in BF16 storage while the result accumulates in FP32.
// It returns nil outside the qualified Metal path for up to two eight-row tiles.
func MatmulBF16Weight(x, weight *Array) *Array {
if x == nil || weight == nil || x.NumDims() != 2 || weight.NumDims() != 2 ||
(x.DType() != DTypeFloat32 && x.DType() != DTypeBFloat16) || weight.DType() != DTypeBFloat16 {
return nil
}
rows, width, columns := x.Dim(0), x.Dim(1), weight.Dim(0)
// At these dimensions native FP32 matmul may split K across workgroups,
// changing the accumulation order of a compact single-pass projection.
if width >= 128 && columns <= width {
return nil
}
if rows < 1 || rows > 16 || width < 1 || width != weight.Dim(1) || columns < 1 || !SupportsBF16WeightMatmul() {
return nil
}
if usesBF16TensorMatmul() {
return matmulBF16WeightTensor(x, weight, rows, width, columns)
}
const tile = 8
paddedRows := (rows + tile - 1) / tile * tile
paddedWidth := (width + tile - 1) / tile * tile
paddedColumns := (columns + tile - 1) / tile * tile
if paddedColumns > math.MaxInt32/4 || paddedWidth > math.MaxInt32 {
return nil
}
x = x.AsType(DTypeFloat32)
if rows != paddedRows || width != paddedWidth {
x = PadConstant(x, []int{0, 1}, []int{0, 0}, []int{paddedRows - rows, paddedWidth - width})
}
if weight.Size() < tile {
// MLX passes tiny arguments in Metal's constant address space, which
// SIMD matrix loads cannot use. Padding at most seven rows gives it
// a device buffer without changing the logical matrix.
weight = PadConstant(weight, []int{0}, []int{0}, []int{tile - columns})
}
result, ok := bf16WeightMatmul.applyMetal(gpuLaunch{
inputs: []*Array{x, weight},
ints: []gpuIntArg{{"Width", width}, {"Columns", columns}},
outputs: []gpuOutputSpec{{"matmul", []int32{int32(paddedRows), int32(paddedColumns)}, DTypeFloat32}},
grid: [3]int{paddedColumns / tile * 32, paddedRows / tile, 1}, threadGroup: [3]int{128, 1, 1},
})
if !ok {
return nil
}
if rows == paddedRows && columns == paddedColumns {
return result[0]
}
return result[0].Slice(Slice(0, rows), Slice(0, columns))
}
func matmulBF16WeightTensor(x, weight *Array, rows, width, columns int) *Array {
const tileRows, tileColumns, kAlignment = 16, 32, 16
// Contracting projections can use a split-K reduction in MLX. The
// vocabulary projection expands the hidden dimension and has one accumulator.
if columns < width || columns > math.MaxInt32-tileColumns || width > math.MaxInt32-kAlignment {
return nil
}
paddedColumns := (columns + tileColumns - 1) / tileColumns * tileColumns
paddedWidth := (width + kAlignment - 1) / kAlignment * kAlignment
if rows != tileRows || width != paddedWidth {
x = PadConstant(x, []int{0, 1}, []int{0, 0}, []int{tileRows - rows, paddedWidth - width})
}
if columns != paddedColumns || width != paddedWidth {
weight = PadConstant(weight, []int{0, 1}, []int{0, 0}, []int{paddedColumns - columns, paddedWidth - width})
}
result, ok := bf16TensorMatmul.applyMetal(gpuLaunch{
inputs: []*Array{x, weight},
dtypes: []gpuDTypeArg{{"Hidden", x.DType()}},
ints: []gpuIntArg{{"Width", paddedWidth}, {"Columns", paddedColumns}},
outputs: []gpuOutputSpec{{"matmul", []int32{tileRows, int32(paddedColumns)}, DTypeFloat32}},
grid: [3]int{paddedColumns / tileColumns * 32, 1, 1}, threadGroup: [3]int{32, 1, 1},
})
if !ok {
return nil
}
return result[0].Slice(Slice(0, rows), Slice(0, columns))
}
// On Metal 4, stock FP32 projections can use tensor operations with TF32 inputs.
// A mixed-type tile preserves their rounding while reading each BF16 weight once.
var bf16TensorMatmul = &gpuKernel{
name: "bf16_tensor_matmul",
inputs: []string{"hidden", "weight"},
outputs: []string{"scores"},
metal: gpuSource{
header: `
#include <metal_tensor>
#include <MetalPerformancePrimitives/MetalPerformancePrimitives.h>
using namespace metal;
`,
source: `
constexpr int rows = 16, channels = 32;
const uint channel = threadgroup_position_in_grid.x * channels;
using dims = dextents<int, 2>;
using strides = array<int, 2>;
tensor<device Hidden, dims, tensor_inline> input(
(device Hidden*)hidden, dims(Width, rows), strides{1, Width});
tensor<device bfloat, dims, tensor_inline> weights(
(device bfloat*)weight + size_t(channel) * Width, dims(Width, channels), strides{1, Width});
tensor<device float, dims, tensor_inline> output(
scores + channel, dims(channels, rows), strides{1, Columns});
constexpr mpp::tensor_ops::matmul2d_descriptor shape(rows, channels, int(dynamic_extent), false, true, true);
mpp::tensor_ops::matmul2d<shape, execution_simdgroup> product;
product.run(input, weights, output);
`,
},
}
// Stock FP32 matmul reads four bytes per weight. Widening BF16 tiles in registers
// halves the weight traffic while preserving FP32 multiplication and accumulation.
var bf16WeightMatmul = &gpuKernel{
name: "bf16_weight_matmul",
inputs: []string{"x", "weight"},
outputs: []string{"result"},
metal: gpuSource{
header: `
#include <metal_simdgroup_matrix>
using namespace metal;
`,
source: `
constexpr uint xStride = (Width + 7u) / 8u * 8u;
constexpr uint outStride = (Columns + 7u) / 8u * 8u;
uint row = 8 * thread_position_in_grid.y;
uint col = 8 * (thread_position_in_grid.x / 32);
simdgroup_float8x8 sum = make_filled_simdgroup_matrix<float, 8, 8>(0);
threadgroup bfloat edge[4][64];
for (uint k = 0; k < Width; k += 8) {
simdgroup_float8x8 lhs;
simdgroup_load(lhs, x + size_t(row) * xStride + k, xStride);
simdgroup_bfloat8x8 rhs;
if (Width % 8 == 0 && (Columns % 8 == 0 || col + 8 <= Columns)) {
simdgroup_load(rhs, weight + size_t(col) * Width + k, Width, ulong2(0), true);
} else {
// A partial or unaligned weight tile is zero-filled in its own SIMD group.
threadgroup bfloat* tile = edge[simdgroup_index_in_threadgroup];
for (uint i = thread_index_in_simdgroup; i < 64; i += 32) {
uint n = col + i / 8, d = k + i % 8;
tile[i] = n < Columns && d < Width ? weight[size_t(n) * Width + d] : bfloat(0);
}
simdgroup_barrier(mem_flags::mem_threadgroup);
simdgroup_load(rhs, tile, 8, ulong2(0), true);
simdgroup_barrier(mem_flags::mem_threadgroup);
}
simdgroup_float8x8 expanded;
expanded.thread_elements()[0] = float(rhs.thread_elements()[0]);
expanded.thread_elements()[1] = float(rhs.thread_elements()[1]);
simdgroup_multiply_accumulate(sum, lhs, expanded, sum);
}
simdgroup_store(sum, result + size_t(row) * outStride + col, outStride);
`,
},
}
+136
View File
@@ -0,0 +1,136 @@
package mlx
import (
"math"
"testing"
"github.com/ollama/ollama/mlx/mlxthread/mlxthreadtest"
)
func TestMatmulBF16Weight(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
if !SupportsBF16WeightMatmul() {
t.Skip("requires a qualified BF16 projection")
}
// At this output width stock MLX selects its FP32 matrix reduction.
// Fractional inputs distinguish it from a lower-precision accumulation.
const width, columns = 2304, 4090
weights := make([]float32, columns*width)
for i := range weights {
weights[i] = float32(math.Cos(float64(i) * 0.0237))
}
w := FromValues(weights, columns, width).AsType(DTypeBFloat16)
stock := w.AsType(DTypeFloat32).Transpose(1, 0)
for _, rows := range []int{1, 7, 8, 14, 16} {
values := make([]float32, rows*(width+4))
for i := range values {
values[i] = float32(math.Sin(float64(i) * 0.15891))
}
x := FromValues(values, rows, width+4).Slice(Slice(), Slice(4, width+4))
got := MatmulBF16Weight(x, w)
if got == nil {
t.Fatalf("declined %d rows", rows)
}
// The SIMD matrix contracts eight rows, including the short final tile.
padded := x
if rows%8 != 0 {
padded = PadConstant(x, []int{0}, []int{0}, []int{8 - rows%8})
}
want := padded.Matmul(stock).Slice(Slice(0, rows), Slice())
checkBF16Matmul(t, got, want)
}
})
}
func TestMatmulBF16WeightEdges(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
if !SupportsBF16WeightMatmul() {
t.Skip("requires a qualified BF16 projection")
}
// All partial sums are exactly representable even if stock MLX picks a
// different reduction on smaller matrices. Both operands are strided.
for _, shape := range [][3]int{{1, 1, 1}, {5, 13, 8}, {5, 13, 19}, {11, 35, 13}, {11, 35, 41}, {9, 16, 17}, {16, 32, 64}} {
rows, width, columns := shape[0], shape[1], shape[2]
matrix := func(n, stride int, dtype DType) *Array {
values := make([]float32, n*stride)
for i := range values {
values[i] = float32(i%23-11) / 8
}
return FromValues(values, n, stride).AsType(dtype).Slice(Slice(), Slice(1, width+1))
}
w := matrix(columns, width+3, DTypeBFloat16)
stock := w.AsType(DTypeFloat32).Transpose(1, 0)
for _, dtype := range []DType{DTypeFloat32, DTypeBFloat16} {
x := matrix(rows, width+5, dtype)
got := MatmulBF16Weight(x, w)
if usesBF16TensorMatmul() && columns < width {
if got != nil {
t.Fatalf("tensor projection accepted contracting shape %v", shape)
}
continue
}
if got == nil {
t.Fatalf("declined %v, dtype %v", shape, dtype)
}
checkBF16Matmul(t, got, x.AsType(DTypeFloat32).Matmul(stock))
}
}
w := Zeros(DTypeBFloat16, 11, 9)
x := Zeros(DTypeFloat32, 2, 9)
for _, inputs := range [][2]*Array{
{nil, w},
{x, nil},
{Zeros(DTypeFloat32, 17, 9), w},
{Zeros(DTypeFloat32, 1, 1, 9), w},
{x, w.Reshape(1, 11, 9)},
{x, Zeros(DTypeBFloat16, 11, 8)},
{x, w.AsType(DTypeFloat32)},
{x.AsType(DTypeFloat16), w},
{x, Zeros(DTypeBFloat16, 0, 9)},
{Zeros(DTypeFloat32, 0, 9), w},
{Zeros(DTypeFloat32, 1, 0), Zeros(DTypeBFloat16, 2, 0)},
} {
if MatmulBF16Weight(inputs[0], inputs[1]) != nil {
t.Fatal("unexpected projection for an unsupported input")
}
}
})
}
func TestMatmulBF16WeightSplitK(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
if !SupportsBF16WeightMatmul() {
t.Skip("requires a qualified BF16 projection")
}
const rows, width = 8, 128
values := make([]float32, (width+1)*width)
for i := range values {
values[i] = float32(math.Sin(float64(i) * 0.15891))
}
x := FromValues(values[:rows*width], rows, width)
for _, columns := range []int{127, 128, 129} {
w := FromValues(values[:columns*width], columns, width).AsType(DTypeBFloat16)
got := MatmulBF16Weight(x, w)
if columns <= width {
if got != nil {
t.Fatalf("accepted possible split-K projection [%d,%d] x [%d,%d]", rows, width, columns, width)
}
continue
}
if got == nil {
t.Fatal("declined expanding projection")
}
checkBF16Matmul(t, got, x.Matmul(w.AsType(DTypeFloat32).Transpose(1, 0)))
}
})
}
func checkBF16Matmul(t *mlxthreadtest.T, got, want *Array) {
if got.NumDims() != 2 || got.Dim(0) != want.Dim(0) || got.Dim(1) != want.Dim(1) || got.DType() != DTypeFloat32 {
t.Fatalf("output %v %v, want %v FP32", got.Dims(), got.DType(), want.Dims())
}
matches := got.View(DTypeUint32).Equal(want.View(DTypeUint32)).AsType(DTypeInt32).Reshape(-1).SumAxis(0, false).Int()
if int(matches) != want.Size() {
t.Errorf("%v differs at %d FP32 elements", got.Dims(), want.Size()-int(matches))
}
}
+162
View File
@@ -0,0 +1,162 @@
package mlx
import (
"math"
"slices"
)
// BlockResidualMix normalizes each [batch, tokens, width] residual source and
// mixes the sources independently for each query. Fusing RMS and query scoring
// avoids the [batch, tokens, queries, sources, width] product. At width 2304
// this improved Inkling's cold prefill by 4–8% on M4 Pro and M5 Max.
// Other shapes, dtypes, epsilons and devices return nil for the caller's graph.
func BlockResidualMix(sources []*Array, query *Array, epsilon float32) *Array {
const width, maxSources = 2304, 5
if len(sources) < 2 || len(sources) > maxSources || epsilon != 1e-6 || !MetalIsAvailable() || !isAppleGPU() {
return nil
}
supported := func(x *Array) bool {
if x == nil {
return false
}
dtype := x.DType()
return dtype == DTypeBFloat16 || dtype == DTypeFloat32
}
if !supported(query) || !supported(sources[0]) {
return nil
}
shape := sources[0].Dims()
if len(shape) != 3 || shape[0] < 1 || shape[1] < 1 || shape[2] != width {
return nil
}
// M2 Ultra gained 3.8% on cold prefill, but fixed-work decode was 1.6% slower.
if name, _ := kernelDevice(); name == "Apple M2 Ultra" && shape[1] < 16 {
return nil
}
for _, source := range sources[1:] {
if !supported(source) || !slices.Equal(shape, source.Dims()) {
return nil
}
}
qshape := query.Dims()
queries := 1
switch len(qshape) {
case 1:
case 2:
queries = qshape[0]
default:
return nil
}
if queries < 1 || queries > 4 || qshape[len(qshape)-1] != width {
return nil
}
batch, tokens, count := shape[0], shape[1], len(sources)
if batch > math.MaxUint32/width/max(queries, count)/tokens {
return nil // Shader element offsets are unsigned 32-bit indices.
}
// The score kernel has a fixed signature for mixed BF16/FP32 sources.
// Extra bindings alias a live source and are never read.
var inputs [maxSources + 1]*Array
for i := range maxSources {
inputs[i] = sources[min(i, count-1)]
}
inputs[maxSources] = MulScalar(query, float32(1/math.Sqrt(width)))
args := []gpuIntArg{{"Width", width}, {"Sources", count}, {"Queries", queries}}
b, t, s, q := int32(batch), int32(tokens), int32(count), int32(queries)
out, ok := blockResidualScores.applyMetal(gpuLaunch{
inputs: inputs[:],
ints: args,
outputs: []gpuOutputSpec{
{"values", []int32{b, t, s, width}, DTypeFloat32},
{"scores", []int32{b, t, q, s}, DTypeFloat32},
},
grid: [3]int{width / 4, count, batch * tokens}, threadGroup: [3]int{width / 4, 1, 1},
})
if !ok {
return nil
}
outputShape := []int32{b, t, width}
if len(qshape) == 2 {
outputShape = []int32{b, t, q, width}
}
mixed, ok := blockResidualSum.applyMetal(gpuLaunch{
inputs: []*Array{out[0], SoftmaxAxis(out[1], -1, true)},
ints: args,
outputs: []gpuOutputSpec{{"mixed", outputShape, DTypeFloat32}},
grid: [3]int{width, queries, batch * tokens}, threadGroup: [3]int{128, 1, 1},
})
if !ok {
return nil
}
return mixed[0]
}
var blockResidualScores = &gpuKernel{
name: "block_residual_scores",
inputs: []string{"x0", "x1", "x2", "x3", "x4", "query"},
outputs: []string{"values", "scores"},
metal: gpuSource{header: `
// The pinned MLX width-2304 RMS and row sum both reduce four adjacent
// values per thread, then the 18 SIMD-group totals in a second SIMD sum.
inline float block_residual_sum(float x, threadgroup float* partials, uint lane, uint group) {
float subtotal = simd_sum(x);
if (lane == 0) partials[group] = subtotal;
threadgroup_barrier(mem_flags::mem_threadgroup);
if (group == 0) return simd_sum(lane < 18 ? partials[lane] : 0.0f);
return 0.0f;
}
`, source: `
uint tid = thread_position_in_threadgroup.x;
uint lane = thread_index_in_simdgroup, group = simdgroup_index_in_threadgroup;
uint source = threadgroup_position_in_grid.y, row = threadgroup_position_in_grid.z;
uint column = tid * 4, offset = row * Width + column;
threadgroup float partials[18];
threadgroup float invRMS;
float v[4], squares = 0.0f;
for (uint j = 0; j < 4; j++) {
switch (source) {
case 0: v[j] = float(x0[offset + j]); break;
case 1: v[j] = float(x1[offset + j]); break;
case 2: v[j] = float(x2[offset + j]); break;
case 3: v[j] = float(x3[offset + j]); break;
default: v[j] = float(x4[offset + j]); break;
}
squares += v[j] * v[j];
}
float total = block_residual_sum(squares, partials, lane, group);
if (tid == 0) invRMS = metal::precise::rsqrt(total / float(Width) + 1e-6f);
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint j = 0; j < 4; j++) {
v[j] *= invRMS;
values[(row * Sources + source) * Width + column + j] = v[j];
}
for (uint q = 0; q < Queries; q++) {
float dot = 0.0f;
for (uint j = 0; j < 4; j++) {
// Match a materialized FP32 product followed by MLX Sum.
volatile float product = v[j] * float(query[q * Width + column + j]);
dot += product;
}
float score = block_residual_sum(dot, partials, lane, group);
if (tid == 0) scores[(row * Queries + q) * Sources + source] = score;
threadgroup_barrier(mem_flags::mem_threadgroup);
}
`},
}
// Each query uses the same normalized sources. Accumulating the individually
// rounded products avoids a query-expanded tensor and preserves the stock sum.
var blockResidualSum = &gpuKernel{
name: "block_residual_weighted_sum",
inputs: []string{"values", "weights"},
outputs: []string{"mixed"},
metal: gpuSource{source: `
uint h = thread_position_in_grid.x, q = thread_position_in_grid.y, row = thread_position_in_grid.z;
float sum = 0.0f;
for (uint s = 0; s < Sources; s++) {
volatile float product = values[(row * Sources + s) * Width + h] * weights[(row * Queries + q) * Sources + s];
sum += product;
}
mixed[(row * Queries + q) * Width + h] = sum;
`},
}
+111
View File
@@ -0,0 +1,111 @@
package mlx
import (
"math"
"slices"
"testing"
"github.com/ollama/ollama/mlx/mlxthread/mlxthreadtest"
)
func TestBlockResidualMixMatchesGraph(t *testing.T) {
const width = 2304
for _, tc := range []struct {
name string
batch, tokens, sources, queries int
vector, strided bool
queryType DType
}{
{"decode", 1, 1, 2, 1, true, false, DTypeFloat32},
{"batched_single_query_matrix", 4, 1, 3, 1, false, false, DTypeBFloat16},
{"strided_verification", 2, 8, 4, 4, false, true, DTypeBFloat16},
{"short_prompt_tail", 1, 15, 5, 3, false, false, DTypeFloat32},
{"prefill_boundary", 1, 16, 5, 3, false, false, DTypeFloat32},
{"prefill", 1, 65, 5, 3, false, false, DTypeFloat32},
} {
t.Run(tc.name, func(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
shape := []int{tc.batch, tc.tokens, width}
sources := make([]*Array, tc.sources)
for i := range sources {
dtype := DTypeBFloat16
if i%2 == 1 {
dtype = DTypeFloat32
}
if tc.strided {
sources[i] = patternArray(dtype, []int{tc.batch, width, tc.tokens}, 0.05, 0.004, 13+2*i, 263).Transpose(0, 2, 1)
} else {
sources[i] = patternArray(dtype, shape, 0.05, 0.004, 13+2*i, 263)
}
}
query := patternArray(tc.queryType, []int{width, tc.queries}, -0.07, 0.013, 37, 271).Transpose(1, 0)
if tc.vector {
query = query.Squeeze(0)
}
got := BlockResidualMix(sources, query, 1e-6)
name, _ := kernelDevice()
if !isAppleGPU() || name == "Apple M2 Ultra" && tc.tokens < 16 {
if got != nil {
t.Fatalf("selected the Metal residual mixer on %s for %d tokens", name, tc.tokens)
}
return
}
if got == nil {
t.Fatal("eligible Metal inputs did not select the residual mixer")
}
// Reproduce the release graph, including scaling the query in its original
// dtype before FP32 multiplication and both native reduction orders.
keys := RMSNormFn(Stack(sources, -2).AsType(DTypeFloat32), nil, 1e-6)
scaled := MulScalar(query.Reshape(tc.queries, width), float32(1/math.Sqrt(width)))
scores := Sum(Mul(keys.ExpandDims(-3), scaled.ExpandDims(-2)), -1, false)
weights := SoftmaxAxis(scores, -1, true).ExpandDims(-1)
want := Sum(Mul(keys.ExpandDims(-3), weights), -2, false)
if tc.vector {
want = want.Squeeze(-2)
}
if got.DType() != DTypeFloat32 || !slices.Equal(got.Dims(), want.Dims()) {
t.Fatalf("got %v %v, want float32 %v", got.DType(), got.Dims(), want.Dims())
}
if err := requireExact(tc.name, got, want); err != nil {
t.Fatal(err)
}
})
})
}
}
func TestBlockResidualMixFallback(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
const width, tokens = 2304, 16
x := Zeros(DTypeBFloat16, 1, tokens, width)
q := Zeros(DTypeFloat32, width)
valid := []*Array{x, x}
for _, tc := range []struct {
name string
sources []*Array
query *Array
epsilon float32
}{
{"one_source", []*Array{x}, q, 1e-6},
{"too_many_sources", []*Array{x, x, x, x, x, x}, q, 1e-6},
{"missing_source", []*Array{x, nil}, q, 1e-6},
{"source_dimensions", []*Array{x, x.Reshape(tokens, width)}, q, 1e-6},
{"different_rows", []*Array{x, x.Reshape(tokens, 1, width)}, q, 1e-6},
{"source_dtype", []*Array{x, x.AsType(DTypeFloat16)}, q, 1e-6},
{"source_width", []*Array{x.Slice(Slice(), Slice(), Slice(0, 64)), x.Slice(Slice(), Slice(), Slice(0, 64))}, Zeros(DTypeFloat32, 64), 1e-6},
{"missing_query", valid, nil, 1e-6},
{"query_rank", valid, q.Reshape(1, 1, width), 1e-6},
{"query_width", valid, q.Reshape(2, width/2), 1e-6},
{"too_many_queries", valid, Zeros(DTypeFloat32, 5, width), 1e-6},
{"query_dtype", valid, q.AsType(DTypeFloat16), 1e-6},
{"zero_epsilon", valid, q, 0},
{"other_epsilon", valid, q, 1e-3},
{"nonfinite_epsilon", valid, q, float32(math.NaN())},
} {
if got := BlockResidualMix(tc.sources, tc.query, tc.epsilon); got != nil {
t.Errorf("%s selected the Metal residual mixer", tc.name)
}
}
})
}
+135
View File
@@ -0,0 +1,135 @@
package mlx
// #include "generated.h"
import "C"
import (
"strings"
"sync"
)
// MLX exposes the backend device name and architecture that select its
// native CUDA and Metal reductions.
var kernelDevice = sync.OnceValues(func() (string, string) {
info := C.mlx_device_info_new()
if mlxError(info) != nil {
return "", ""
}
defer freeDeviceInfo(info)
if mlxError(C.mlx_device_info_get(&info, DefaultDevice().ctx)) != nil {
return "", ""
}
name, err := deviceInfoString(info, "device_name")
if err != nil {
return "", ""
}
arch, err := deviceInfoString(info, "architecture")
if err != nil {
return "", ""
}
return name, arch
})
func isM5Pro(name, architecture string) bool {
return name == "Apple M5 Pro" && architecture == "applegpu_g17s"
}
func isM5MatrixDevice(name, architecture string) bool {
return (name == "Apple M5 Pro" || name == "Apple M5 Max") && architecture == "applegpu_g17s" ||
name == "Apple M5 Ultra" && architecture == "applegpu_g17d"
}
// MLX JITs custom shaders as Metal 4 on macOS 26 and later, with either
// bundled dylib. Earlier drivers cannot compile the TensorOps header.
var hasMetalTensorOps = sync.OnceValue(func() bool {
return macOSMajorVersion() >= 26 && isAppleGPU()
})
func isAppleGPU() bool {
_, arch := kernelDevice()
return strings.HasPrefix(arch, "applegpu_")
}
type metalMatmulMode uint8
const (
metalMatmulUnsupported metalMatmulMode = iota
metalMatmulScalar
metalMatmulTensor
)
// A stock grouped dot distinguishes the active reduction, including when TF32
// is disabled on Metal 4. Device names alone cannot distinguish the two modes.
var metalMatmul = sync.OnceValue(func() metalMatmulMode {
if !isAppleGPU() {
return metalMatmulUnsupported
}
mode := metalMatmulUnsupported
Scoped(func() {
// After the leading product, sixteen 1/16 terms round away in a
// scalar FP32 sum. Their tensor-core subtotal adds exactly one.
input := [32]float32{1536}
for i := 16; i < len(input); i++ {
input[i] = 0.125
}
x := BroadcastTo(FromValues(input[:], 1, 1, 1, 32), 16, 1, 1, 32)
w := FromValues([]uint32{7, 0, 0x11111111, 0x11111111}, 1, 1, 4)
s := FromValues([]uint8{0x7e, 0x38}, 1, 1, 2)
ids := Zeros(DTypeInt32, 16, 1)
y := GatherQMM(x, w, s, nil, nil, ids, true, 16, 4, "nvfp4", nil, true)
switch y.Flatten(0, -1).Slice(Slice(0, 1)).Float() {
case 4128768:
mode = metalMatmulScalar
case 4128769:
mode = metalMatmulTensor
}
})
return mode
})
// Dense and grouped products can select different reductions. In this dense
// dot, TF32 rounds the only nonzero input down to one. Full FP32 preserves it.
var usesBF16TensorMatmul = sync.OnceValue(func() bool {
if !hasMetalTensorOps() {
return false
}
match := false
Scoped(func() {
const rows, width, columns = 8, 16, 32
const fraction = 1 + 1.0/4096
input := [rows * width]float32{fraction}
weight := [columns * width]float32{1}
x := FromValues(input[:], rows, width)
w := FromValues(weight[:], columns, width)
tensor := matmulBF16WeightTensor(x, w.AsType(DTypeBFloat16), rows, width, columns)
if tensor == nil {
return
}
stock := x.Matmul(w.Transpose(1, 0))
cell := Slice(0, 1)
got, want := tensor.Slice(cell, cell), stock.Slice(cell, cell)
Eval(got, want)
native := want.Float()
match = (native == 1 || native == fraction) && got.Float() == native
})
return match
})
// UsesM5MatrixKernels identifies Metal devices qualified for the short projection kernels.
func UsesM5MatrixKernels() bool {
return isM5MatrixDevice(kernelDevice())
}
// SupportsPackedController reports where a combined gain/forget projection
// matches the two separate projections. M3 Ultra was verified on Metal 3.
func SupportsPackedController() bool {
name, arch := kernelDevice()
return isM5MatrixDevice(name, arch) ||
name == "Apple M3 Ultra" && arch == "applegpu_g15d" && !hasMetalTensorOps()
}
// SupportsBF16WeightMatmul lets the loader retain compact weights only for a known reduction.
func SupportsBF16WeightMatmul() bool {
return usesBF16TensorMatmul() || UsesM5MatrixKernels() && metalMatmul() == metalMatmulScalar
}
+48
View File
@@ -0,0 +1,48 @@
package mlx
import (
"testing"
"github.com/ollama/ollama/mlx/mlxthread/mlxthreadtest"
)
func TestMetalTensorOpsFallback(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
if hasMetalTensorOps() {
t.Skip("requires a backend without Metal tensor ops")
}
// These shapes qualify on a Metal 4 driver. An older driver must
// return to the native model path before constructing the shader.
q := Zeros(DTypeFloat32, 1, 1, 16, 128)
k := Zeros(DTypeBFloat16, 1, 1, 16, 128)
table := Zeros(DTypeBFloat16, 1, 1, 16, 16)
sink := Zeros(DTypeBFloat16, 1, 1, 16, 1)
if RelativePositionAttentionBF16Probabilities(q, k, k, table, sink, 0, 16, 0.125) != nil {
t.Fatal("selected MPP attention")
}
x := Zeros(DTypeBFloat16, 16, 1, 1, 32)
w := Zeros(DTypeUint32, 1, 64, 4)
s := Zeros(DTypeUint8, 1, 64, 2)
ids := Zeros(DTypeInt32, 16, 1)
if PrefersCompactNVFP4QMM() || GatherNVFP4QMM(x, w, s, ids) != nil {
t.Fatal("selected MPP grouped matmul")
}
})
}
func TestM5MatrixDevice(t *testing.T) {
for _, tc := range []struct {
name, architecture string
want bool
}{
{"Apple M5 Max", "applegpu_g17s", true},
{"Apple M5 Ultra", "applegpu_g17d", true},
{"Apple M5 Max", "applegpu_g17d", false},
{"Apple M5 Pro", "applegpu_g17s", true},
{"Apple M3 Ultra", "applegpu_g15d", false},
} {
if got := isM5MatrixDevice(tc.name, tc.architecture); got != tc.want {
t.Errorf("device %s/%s returns %t, want %t", tc.name, tc.architecture, got, tc.want)
}
}
}
+285
View File
@@ -0,0 +1,285 @@
package mlx
import (
"math"
"sync"
)
// MLX derives its NVFP4 scale from the block maximum divided by 6. The 4-over-6
// variant also tries a divisor of 4 and compares both reconstruction errors in one pass.
var nvfp4Activation = &gpuKernel{
name: "nvfp4_activation",
inputs: []string{"x"},
outputs: []string{"inner", "amax"},
cuda: nvfp4ActivationCUDA,
metal: gpuSource{
header: `
#include <metal_stdlib>
using namespace metal;
inline float round_e4m3(float x) {
// Nonnegative E4M3FN with round-to-nearest-even.
uint exponent = (as_type<uint>(x) >> 23) & 255u;
float spacing = as_type<float>((max(exponent, 121u) - 3u) << 23);
return rint(x / spacing) * spacing;
}
inline float round_e2m1(float x) {
float m = abs(x);
float q = m > 0.25f ? 0.5f : 0.0f;
if (m >= 0.75f) q = 1.0f;
if (m > 1.25f) q = 1.5f;
if (m >= 1.75f) q = 2.0f;
if (m > 2.5f) q = 3.0f;
if (m >= 3.5f) q = 4.0f;
if (m > 5.0f) q = 6.0f;
return x < 0.0f ? -q : q;
}
`,
source: `
#pragma clang fp contract(off) reassociate(off)
uint row = threadgroup_position_in_grid.y;
uint worker = thread_index_in_threadgroup;
uint lane = thread_index_in_simdgroup;
uint group = simdgroup_index_in_threadgroup;
uint start = row * W + worker * 16;
bool active = worker < W / 16;
float data[16];
float block_max = 0.0f;
for (uint i = 0; i < 16; ++i) {
data[i] = active ? float(x[start + i]) : 0.0f;
block_max = max(block_max, abs(data[i]));
}
threadgroup float partial[G / 32];
float simd_amax = simd_max(block_max);
if (lane == 0) partial[group] = simd_amax;
threadgroup_barrier(mem_flags::mem_threadgroup);
float row_max = simd_max(lane < G / 32 ? partial[lane] : 0.0f);
if (worker == 0) amax[row] = row_max;
if (!active) return;
float normalizer = min(float(MaxProduct) / row_max, FLT_MAX);
float decoder = 1.0f / normalizer;
float outer = row_max * (1.0f / float(MaxProduct));
float scale_a = round_e4m3(min(block_max * (normalizer * (1.0f / 6.0f)), 448.0f));
float scale_b = round_e4m3(min(block_max * (normalizer * 0.25f), 448.0f));
float inv_a = min(1.0f / (scale_a * decoder), FLT_MAX);
float inv_b = min(1.0f / (scale_b * decoder), FLT_MAX);
float candidate_a[16], candidate_b[16];
float error_a = 0.0f, error_b = 0.0f;
for (uint i = 0; i < 16; ++i) {
candidate_a[i] = round_e2m1(data[i] * inv_a) * scale_a;
candidate_b[i] = round_e2m1(data[i] * inv_b) * scale_b;
error_a += abs(data[i] - candidate_a[i] * outer);
error_b += abs(data[i] - candidate_b[i] * outer);
}
for (uint i = 0; i < 16; ++i) {
inner[start + i] = error_b < error_a ? candidate_b[i] : candidate_a[i];
}
`,
},
}
// QuantizeNVFP4Activation4Over6 returns FP32 reconstructions of the inner E2M1
// values times their E4M3 block scales, and one FP32 absolute maximum per row.
// Multiply the reconstructed values by maxima / maxProduct to restore the
// input scale. For each block of 16, the scale selected from the 4 and 6
// ranges minimizes total absolute error. Ties select the 6 range.
func QuantizeNVFP4Activation4Over6(x *Array, maxProduct int) (values, maxima *Array) {
if x == nil || x.NumDims() == 0 || x.Dim(-1) == 0 || x.Dim(-1)%16 != 0 {
panic("mlx: NVFP4 activations require rows of complete 16-value blocks")
}
if maxProduct < 1 || maxProduct > Nvfp4MaxProduct {
panic("mlx: NVFP4 activation normalization exceeds the FP4 × FP8 range")
}
if values, maxima := fastNVFP4Activation(x, maxProduct); values != nil {
return values, maxima
}
shape := x.Dims()
width := shape[len(shape)-1]
blocks := x.Reshape(x.Size()/width, width/16, 16)
denominator := FromValue(float32(maxProduct))
inverse := FromValue(1 / float32(maxProduct))
if MetalIsAvailable() {
result := compiledNVFP4Blocks(blocks, denominator, inverse)
values, maxima = result[0], result[1]
} else {
values, maxima = quantizeNVFP4Blocks(blocks, denominator, inverse)
}
values = values.Reshape(shape...)
shape[len(shape)-1] = 1
return values, maxima.Reshape(shape...)
}
// One SIMD lane handles 16 channels, with up to 256 lanes per threadgroup.
func fastNVFP4Activation(x *Array, maxProduct int) (values, maxima *Array) {
if x == nil || x.NumDims() == 0 || x.DType() != DTypeBFloat16 {
return nil, nil
}
width, size := x.Dim(-1), x.Size()
if width < 16 || width%16 != 0 || width > 16*256 || size == 0 || uint64(size) > math.MaxUint32 {
return nil, nil
}
useCUDA := !MetalIsAvailable()
if useCUDA && !nvfp4ActivationCUDAEnabled() {
return nil, nil
}
workers := (width/16 + 31) / 32 * 32
if useCUDA && size/width > math.MaxInt32/workers {
return nil, nil
}
shape := make([]int32, x.NumDims())
for i := range shape {
shape[i] = int32(x.Dim(i))
}
maxShape := append([]int32(nil), shape...)
maxShape[len(maxShape)-1] = 1
launch := gpuLaunch{
ints: []gpuIntArg{{"W", width}, {"G", workers}, {"MaxProduct", maxProduct}},
outputs: []gpuOutputSpec{{"NVFP4Values", shape, DTypeFloat32}, {"NVFP4Maxima", maxShape, DTypeFloat32}},
grid: [3]int{workers, size / width, 1}, threadGroup: [3]int{workers, 1, 1},
inputs: []*Array{x},
}
apply := nvfp4Activation.applyMetal
if useCUDA {
launch.grid = [3]int{workers * (size / width), 1, 1}
apply = nvfp4Activation.applyCUDA
}
output, ok := apply(launch)
if !ok {
return nil, nil
}
return output[0], output[1]
}
// The MLX graph materializes both 4-over-6 candidates. Compare their errors in
// registers using MLX's SM120 sum order so close decisions choose the same scale.
var nvfp4ActivationCUDA = gpuSource{
header: `
__device__ float nvfp4_round_e4m3(float input) {
unsigned exponent = __float_as_uint(input) >> 23;
int spacing_exponent = int(exponent > 121 ? exponent : 121) - 130;
float spacing = ldexpf(1.0f, spacing_exponent);
return nearbyintf(__fdiv_rn(input, spacing)) * spacing;
}
__device__ float nvfp4_round_e2m1(float input) {
float magnitude = fabsf(input);
float value = magnitude > 0.25f ? 0.5f : 0.0f;
if (magnitude >= 0.75f) value = 1.0f;
if (magnitude > 1.25f) value = 1.5f;
if (magnitude >= 1.75f) value = 2.0f;
if (magnitude > 2.5f) value = 3.0f;
if (magnitude >= 3.5f) value = 4.0f;
if (magnitude > 5.0f) value = 6.0f;
return input < 0.0f ? -value : value;
}
`,
source: `
unsigned token = blockIdx.x;
unsigned worker = threadIdx.x;
unsigned lane = worker % 32;
unsigned start = token * W + worker * 16;
bool active = worker < W / 16;
float data[16];
float block_max = 0.0f;
for (int i = 0; i < 16; ++i) {
data[i] = active ? float(x[start + i]) : 0.0f;
block_max = fmaxf(block_max, fabsf(data[i]));
}
__shared__ float warp_maxima[G / 32];
float token_max = block_max;
for (int stride = 16; stride; stride >>= 1) {
token_max = fmaxf(token_max, __shfl_down_sync(0xffffffff, token_max, stride));
}
if (lane == 0) warp_maxima[worker / 32] = token_max;
__syncthreads();
token_max = lane < G / 32 ? warp_maxima[lane] : 0.0f;
for (int stride = 16; stride; stride >>= 1) {
token_max = fmaxf(token_max, __shfl_down_sync(0xffffffff, token_max, stride));
}
token_max = __shfl_sync(0xffffffff, token_max, 0);
if (worker == 0) amax[token] = token_max;
if (!active) return;
float float_max = __uint_as_float(0x7f7fffff);
float normalizer = fminf(__fdiv_rn(float(MaxProduct), token_max), float_max);
float decoder = __fdiv_rn(1.0f, normalizer);
float outer = __fmul_rn(token_max, 1.0f / float(MaxProduct));
float values[2][16], errors[2];
for (int candidate = 0; candidate < 2; ++candidate) {
float reciprocal = candidate == 0 ? 1.0f / 6.0f : 0.25f;
float limit = __fmul_rn(block_max, __fmul_rn(normalizer, reciprocal));
float scale = nvfp4_round_e4m3(fminf(limit, 448.0f));
float inverse = fminf(__fdiv_rn(1.0f, __fmul_rn(scale, decoder)), float_max);
// The CUDA reduction sums adjacent sets of four, then the warp
// combines its partials. Preserve separate multiplies and subtraction.
float partial[4] = {};
for (int i = 0; i < 16; ++i) {
float quantized = nvfp4_round_e2m1(__fmul_rn(data[i], inverse));
values[candidate][i] = __fmul_rn(quantized, scale);
float restored = __fmul_rn(values[candidate][i], outer);
partial[i / 4] += fabsf(__fsub_rn(data[i], restored));
}
errors[candidate] = (partial[0] + partial[2]) + (partial[1] + partial[3]);
}
int selected = errors[1] < errors[0];
for (int i = 0; i < 16; ++i) inner[start + i] = values[selected][i];
`,
}
// The CUDA error reduction matches MLX's SM120 order.
var nvfp4ActivationCUDAEnabled = sync.OnceValue(func() bool {
if !CUDAIsAvailable() {
return false
}
_, arch := kernelDevice()
return arch == "sm_120"
})
var compiledNVFP4Blocks = Compile("NVFP4ActivationBlocks", func(inputs ...*Array) []*Array {
values, maxima := quantizeNVFP4Blocks(inputs[0], inputs[1], inputs[2])
return []*Array{values, maxima}
}, Shapeless())
func quantizeNVFP4Blocks(blocks, maxProduct, inverseMaxProduct *Array) (values, maxima *Array) {
blocks = blocks.AsType(DTypeFloat32)
blockMax := blocks.Abs().MaxAxis(-1, true)
maxima = blockMax.MaxAxis(-2, true)
one := FromValue(float32(1))
limit := FromValue(float32(math.MaxFloat32))
normalizer := Minimum(Div(maxProduct, maxima), limit)
decoder := Div(one, normalizer)
outer := Mul(maxima, inverseMaxProduct)
candidate := func(limitValue float32) (values, errorSum *Array) {
scale := Mul(blockMax, MulScalar(normalizer, 1/limitValue))
scale = Minimum(scale, FromValue(float32(448)))
scale = FromFP8(ToFP8(scale), DTypeFloat32)
inverse := Minimum(Div(one, Mul(scale, decoder)), limit)
values = Mul(roundE2M1(Mul(blocks, inverse)), scale)
errorSum = Sum(Sub(blocks, Mul(values, outer)).Abs(), -1, true)
return values, errorSum
}
full, fullError := candidate(6)
alternate, alternateError := candidate(4)
return Where(alternateError.Less(fullError), alternate, full), maxima
}
func roundE2M1(x *Array) *Array {
zero := FromValue(float32(0))
magnitude := x.Abs()
result := zero
levels := [...]float32{0, 0.5, 1, 1.5, 2, 3, 4, 6}
for index := 1; index < len(levels); index++ {
midpoint := FromValue((levels[index-1] + levels[index]) / 2)
selectLevel := magnitude.Greater(midpoint)
if index%2 == 0 {
selectLevel = midpoint.LessEqual(magnitude)
}
result = Where(selectLevel, FromValue(levels[index]), result)
}
return Where(x.Less(zero), Neg(result), result)
}
+154
View File
@@ -0,0 +1,154 @@
package mlx
import (
"fmt"
"math/rand/v2"
"slices"
"testing"
"github.com/ollama/ollama/mlx/mlxthread/mlxthreadtest"
)
func BenchmarkNVFP4BlocksEager(b *testing.B) {
benchmarkNVFP4Blocks(b, false, func(blocks *Array) (*Array, *Array) {
return quantizeNVFP4Blocks(blocks, FromValue(float32(1536)), FromValue(float32(1.0/1536)))
})
}
func BenchmarkNVFP4BlocksCompiled(b *testing.B) {
benchmarkNVFP4Blocks(b, true, func(blocks *Array) (*Array, *Array) {
result := compiledNVFP4Blocks(blocks, FromValue(float32(1536)), FromValue(float32(1.0/1536)))
return result[0], result[1]
})
}
func BenchmarkNVFP4BlocksKernel(b *testing.B) {
benchmarkNVFP4Blocks(b, false, func(blocks *Array) (*Array, *Array) {
values, maxima := fastNVFP4Activation(blocks.Reshape(blocks.Dim(0), -1), 1536)
if values == nil {
panic("NVFP4 activation unavailable")
}
return values, maxima
})
}
func benchmarkNVFP4Blocks(b *testing.B, metalOnly bool, quantize func(*Array) (*Array, *Array)) {
worker := mlxTestThread(b)
for _, rows := range []int{8, 512} {
b.Run(fmt.Sprintf("rows%d", rows), func(b *testing.B) {
var supported bool
if err := worker.Do(b.Context(), func() error {
metal := MetalIsAvailable()
supported = metal
if !metal && !metalOnly {
values, _ := fastNVFP4Activation(Zeros(DTypeBFloat16, 1, 2304), 1536)
supported = values != nil
}
if !supported {
return nil
}
if metal {
EnableCompile()
}
Scoped(func() {
const width = 2304
data := make([]float32, rows*width)
random := rand.New(rand.NewPCG(41, 723))
for i := range data {
data[i] = float32(random.NormFloat64())
}
blocks := FromValues(data, rows, width/16, 16).AsType(DTypeBFloat16)
Eval(blocks)
run := func() { Eval(quantize(blocks)) }
Scoped(run)
b.ResetTimer()
for range b.N {
Scoped(run)
}
b.StopTimer()
})
return nil
}); err != nil {
b.Fatal(err)
}
if !supported {
b.Skip("requires a qualified activation backend")
}
})
}
}
func requireNVFP4Activation(t *mlxthreadtest.T) {
t.Helper()
values, _ := fastNVFP4Activation(Zeros(DTypeBFloat16, 1, 2304), 1536)
if values == nil {
if MetalIsAvailable() {
t.Fatal("Metal declined an eligible NVFP4 activation")
}
t.Skip("requires a qualified NVFP4 activation device")
}
}
func TestNVFP4ActivationMatchesEagerAcrossShapes(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
requireNVFP4Activation(t)
for _, input := range []*Array{
Zeros(DTypeBFloat16, 1, 17),
Zeros(DTypeBFloat16, 1, 4112),
Zeros(DTypeFloat32, 1, 2304),
BroadcastTo(FromValue(float32(0)).AsType(DTypeBFloat16), 1<<22, 1152),
} {
if values, maxima := fastNVFP4Activation(input, 1536); values != nil || maxima != nil {
t.Fatalf("unexpected NVFP4 specialization for %v %v", input.Dims(), input.DType())
}
}
random := rand.New(rand.NewPCG(41, 723))
for _, tc := range [][4]int{{1, 1, 2304, 1536}, {8, 8, 1152, 1536}, {67, 1, 2304, 1536}, {13, 8, 1152, 1536}, {2, 1, 16, Nvfp4MaxProduct}, {3, 2, 528, Nvfp4MaxProduct}, {1, 2, 4096, 1536}} {
Scoped(func() {
rows, routes, width, maxProduct := tc[0], tc[1], tc[2], tc[3]
data := make([]float32, rows*routes*width)
for i := range data {
// Include empty blocks, equal magnitudes and random rounding decisions.
switch (i / 16) % 3 {
case 1:
data[i] = float32(i%7-3) * 0.5
case 2:
data[i] = float32(random.NormFloat64())
}
}
x := FromValues(data, rows, routes, 1, width).AsType(DTypeBFloat16)
want, wantMax := quantizeNVFP4Blocks(x.Reshape(-1, width/16, 16), FromValue(float32(maxProduct)), FromValue(1/float32(maxProduct)))
got, gotMax := fastNVFP4Activation(x, maxProduct)
if got == nil {
t.Fatalf("Metal activation unavailable for shape %v", tc)
}
if !slices.Equal(got.Dims(), x.Dims()) || !slices.Equal(gotMax.Dims(), []int{rows, routes, 1, 1}) ||
!slices.Equal(got.Floats(), want.Floats()) || !slices.Equal(gotMax.Floats(), wantMax.Floats()) {
t.Errorf("shape %v: Metal activation or row maxima differ from eager", tc)
}
})
}
})
}
func TestNVFP4ActivationFallback(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
// FP32 always takes the graph path, including on Metal.
x := Arange(-64, 64, 1, DTypeFloat32).Reshape(2, 64)
for _, maxProduct := range []int{1536, Nvfp4MaxProduct} {
got, gotMax := QuantizeNVFP4Activation4Over6(x, maxProduct)
want, wantMax := quantizeNVFP4Blocks(x.Reshape(2, 4, 16), FromValue(float32(maxProduct)), FromValue(1/float32(maxProduct)))
if !slices.Equal(got.Dims(), x.Dims()) || !slices.Equal(gotMax.Dims(), []int{2, 1}) ||
!slices.Equal(got.Floats(), want.Floats()) || !slices.Equal(gotMax.Floats(), wantMax.Floats()) {
t.Errorf("graph fallback differs for max product %d", maxProduct)
}
}
if CUDAIsAvailable() {
_, arch := kernelDevice()
values, maxima := fastNVFP4Activation(x.AsType(DTypeBFloat16), 1536)
if (values != nil) != (arch == "sm_120") || (maxima != nil) != (arch == "sm_120") {
t.Fatalf("unexpected activation dispatch for %s", arch)
}
}
})
}
+319
View File
@@ -0,0 +1,319 @@
package mlx
import "math"
// Accelerating stock GatherQMM on M5 requires matrix tiles confined to one expert.
// Build runs of up to 32 rows from sorted IDs on the GPU to avoid a host readback.
var nvfp4RouteRuns = &gpuKernel{
name: "nvfp4_route_runs",
inputs: []string{"indices"},
outputs: []string{"runs"},
metal: gpuSource{
source: `
uint rows = indices_shape[0];
uint capacity = (rows + 31) / 32 + Experts - 1;
constexpr uint tileRows = 32;
uint expert = thread_index_in_threadgroup;
uint low = 0, high = rows;
while (low < high) {
uint middle = (low + high) / 2;
if (uint(indices[middle]) < expert)
low = middle + 1;
else
high = middle;
}
uint start = low;
high = rows;
while (low < high) {
uint middle = (low + high) / 2;
if (uint(indices[middle]) <= expert)
low = middle + 1;
else
high = middle;
}
uint end = low, count = (end - start + tileRows - 1) / tileRows;
threadgroup uint prefix[Experts];
prefix[expert] = count;
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint stride = 1; stride < Experts; stride *= 2) {
uint left = expert >= stride ? prefix[expert - stride] : 0;
threadgroup_barrier(mem_flags::mem_threadgroup);
prefix[expert] += left;
threadgroup_barrier(mem_flags::mem_threadgroup);
}
// Prefix sums place each expert’s runs contiguously in the output.
uint begin = prefix[expert] - count;
for (uint i = 0; i < count; ++i) {
uint index = (begin + i) * 3, row = start + i * tileRows;
runs[index] = row;
runs[index + 1] = min(uint(tileRows), end - row);
runs[index + 2] = expert;
}
// Empty records pad the grid to its host-known upper bound.
for (uint i = prefix[Experts - 1] + expert; i < capacity; i += Experts) {
runs[i * 3] = 0;
runs[i * 3 + 1] = 0;
runs[i * 3 + 2] = 0;
}
`,
},
}
// A nonzero finite float is an integer multiple of 2^quantum.
const nvfp4QuantumMetal = `
inline int nvfp4_binary_quantum(float f) {
uint raw = as_type<uint>(abs(f));
if (raw == 0)
return 127;
return int(raw >> 23) - 150 + int(ctz((raw & 0x7fffffu) | 0x800000u));
}
// Bound exact accumulation by 0.999 * 2^(quantum + 24). Adjusting the
// exponent of 0.999 avoids ldexp in the tile loop. Zero forces native
// replay if an intermediate could be subnormal; exponents above 104
// put the bound beyond the largest finite FP32 value.
inline float nvfp4_exact_limit(int quantum) {
uint bits = as_type<uint>(0.999f) + (uint(quantum + 24) << 23);
return quantum < -126 ? 0.f : quantum > 104 ? INFINITY : as_type<float>(bits);
}
`
// Matrix accumulation can change FP32 rounding. Compute each input block's peak
// and binary quantum once so all output tiles can reuse the same exactness bound.
var nvfp4ActivationBounds = &gpuKernel{
name: "nvfp4_activation_bounds",
inputs: []string{"values"},
outputs: []string{"quantum", "maxima"},
metal: gpuSource{
header: nvfp4DecodeMetal + nvfp4QuantumMetal,
source: `
constexpr uint blockSize = 32;
uint block = thread_position_in_grid.x;
int exponent = 127;
float peak = 0;
for (uint i = 0; i < blockSize; ++i) {
float v = float(values[block * blockSize + i]);
exponent = min(exponent, nvfp4_binary_quantum(v));
peak = max(peak, abs(v));
}
quantum[block] = exponent;
maxima[block] = peak;
`,
},
}
// Stock FP32 GatherQMM is slower on long runs routed to one expert. Reuse decoded
// weights on M5 matrix tiles and replay ambiguous sums in native FP32 order.
var gatherNVFP4QMM = &gpuKernel{
name: "gather_nvfp4_qmm",
inputs: []string{"activation", "weights", "scales", "runs", "quantum", "maxima"},
outputs: []string{"result"},
metal: gpuSource{
header: nvfp4DecodeMetal + nvfp4QuantumMetal + `
#include <MetalPerformancePrimitives/MetalPerformancePrimitives.h>
#include <metal_simdgroup_matrix>
`,
source: `
constexpr uint BM = 32, BN = 64, BK = 32, Workers = 128;
uint worker = thread_index_in_threadgroup, lane = thread_index_in_simdgroup,
simd = simdgroup_index_in_threadgroup;
uint tile = threadgroup_position_in_grid.y, start = runs[tile * 3], rows = runs[tile * 3 + 1],
expert = runs[tile * 3 + 2];
if (rows == 0)
return;
uint col0 = threadgroup_position_in_grid.x * BN;
uint tileRow = (simd / (BN / 32)) * 16, tileColumn = (simd % (BN / 32)) * 32;
threadgroup bfloat decodedWeights[BN * BK];
threadgroup float final[BM * BN];
using Shape = metal::dextents<int32_t, 2>;
using Strides = metal::array<int32_t, 2>;
using ActivationTile = metal::tensor<device bfloat, Shape, metal::tensor_inline>;
using WeightTile = metal::tensor<threadgroup bfloat, Shape, metal::tensor_inline>;
using ResultTile = metal::tensor<threadgroup float, Shape, metal::tensor_inline>;
constexpr auto descriptor = mpp::tensor_ops::matmul2d_descriptor(
16, 32, BK, false, true, true, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate);
mpp::tensor_ops::matmul2d<descriptor, metal::execution_simdgroup> product;
auto accumulator =
product.template get_destination_cooperative_tensor<ActivationTile, WeightTile, float>();
for (uint i = 0; i < accumulator.get_capacity(); ++i)
accumulator[i] = 0;
// The minimum binary quantum of all products so far also divides every
// possible FP32 prefix, including prefixes rounded to a coarser power of two.
int smallest = 127;
for (uint offset = 0; offset < Width; offset += BK) {
for (uint i = worker; i < BN * (BK / 8); i += Workers) {
uint channel = col0 + i / (BK / 8), at = offset + (i % (BK / 8)) * 8;
uint wr = expert * Channels + channel;
uint word = 0;
float gain = 0;
if (Channels % BN == 0 || channel < Channels) {
word = weights[wr * (Width / 8) + at / 8];
gain = nvfp4_e4m3(scales[wr * (Width / 16) + at / 16]);
}
for (uint j = 0; j < 8; ++j)
decodedWeights[i * 8 + j] = bfloat(nvfp4_e2m1(word >> (4 * j)) * gain);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (tileRow < rows) {
int valid = int(min(16u, rows - tileRow));
uint block = (start + tileRow + min(lane, 15u)) * (Width / BK) + offset / BK;
float rowPeak = lane < valid ? maxima[block] : 0.f;
float inputPeak = simd_max(rowPeak);
int rowQuantum = lane < valid ? quantum[block] : 127;
int minInputQuantum = simd_min(rowQuantum);
int weightQuantum = 127;
float weightPeak = 0;
for (uint h = 0; h < BK / 16; ++h) {
uint channel = col0 + tileColumn + lane;
float gain = 0;
if (Channels % BN == 0 || channel < Channels)
gain = nvfp4_e4m3(scales[(expert * Channels + channel) * (Width / 16) + offset / 16 + h]);
weightQuantum = min(weightQuantum, nvfp4_binary_quantum(gain) - 1);
weightPeak = max(weightPeak, abs(gain) * 6.f);
}
smallest = min(smallest, minInputQuantum + simd_min(weightQuantum));
float columnPeak = weightPeak;
int columnQuantum = weightQuantum;
weightPeak = simd_max(weightPeak);
float partialPeak = 0;
for (uint i = 0; i < accumulator.get_capacity(); ++i)
partialPeak = max(partialPeak, abs(accumulator[i]));
partialPeak = simd_max(partialPeak);
// Every add is exact if every possible intermediate sum is an
// integer smaller than 2^24 in this binary quantum. The maximum
// absolute prefix plus the block L1 bound covers both reduction orders.
float upper = partialPeak + float(BK) * inputPeak * weightPeak;
// Native FP32 arithmetic flushes subnormal intermediates; the
// matrix unit can preserve them. Replay if a prefix can be subnormal.
bool safe = upper < nvfp4_exact_limit(smallest);
float before[16] = {};
uint replay = 0;
// A tile can fail the common bound while individual entries pass.
if (!safe) {
for (uint i = 0; i < accumulator.get_capacity(); ++i) {
auto loc = accumulator.get_multidimensional_index(i);
uint row = loc[1], column = loc[0];
float lhs = simd_shuffle(rowPeak, row), rhs = simd_shuffle(columnPeak, column);
int productQuantum =
simd_shuffle(rowQuantum, row) + simd_shuffle(columnQuantum, column);
float prev = accumulator[i];
before[i] = prev;
float bound = abs(prev) + float(BK) * lhs * rhs;
int quantum = min(nvfp4_binary_quantum(prev), productQuantum);
float limit = nvfp4_exact_limit(quantum);
if (row < uint(valid) && !(bound < limit))
replay |= 1u << i;
}
}
auto lhs = ActivationTile((device bfloat *)activation + (start + tileRow) * Width + offset,
Shape(BK, valid), Strides{1, Width});
auto rhs = WeightTile(decodedWeights + tileColumn * BK, Shape(BK, 32), Strides{1, BK});
product.run(lhs, rhs, accumulator);
// Reproduce the native FP32 reduction on the ambiguous outputs.
while (replay) {
uint i = ctz(replay);
replay &= replay - 1;
auto loc = accumulator.get_multidimensional_index(i);
uint row = loc[1], column = loc[0];
float value = before[i];
for (uint h = 0; h < BK; ++h) {
value = fma(float(activation[(start + tileRow + row) * Width + offset + h]),
float(decodedWeights[(tileColumn + column) * BK + h]), value);
}
accumulator[i] = value;
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
}
accumulator.store(ResultTile(final + tileRow * BN + tileColumn, Shape(32, 16), Strides{1, BN}));
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint i = worker; i < rows * BN; i += Workers) {
uint channel = col0 + i % BN;
if (Channels % BN == 0 || channel < Channels)
result[(start + i / BN) * Channels + channel] = final[i];
}
`,
},
}
// PrefersCompactNVFP4QMM reports when compact tiles beat native sorted FP32
// GatherQMM. On M5 the compatibility reduction benefits from compact tiles.
// Native grouped work is faster alongside MPP attention on the M4 Pro.
func PrefersCompactNVFP4QMM() bool {
return hasMetalTensorOps() && UsesM5MatrixKernels() && metalMatmul() == metalMatmulScalar
}
// GatherNVFP4QMM multiplies sorted BF16 vectors [R,1,1,K] by transposed
// NVFP4 matrices [E,N,K/8] with E4M3FN scales [E,N,K/16]. Its FP32 output
// [R,1,1,N] matches grouped GatherQMM on the FP32 reconstruction of the
// vectors. Reconstructed NVFP4 activations fit exactly in BF16.
// The caller supplies one valid, nondecreasing expert ID per row in [R,1].
// It returns nil for unsupported devices or shapes.
func GatherNVFP4QMM(values, weight, scales, indices *Array) *Array {
if !hasMetalTensorOps() || values == nil || values.NumDims() != 4 || values.DType() != DTypeBFloat16 ||
values.Dim(1) != 1 || values.Dim(2) != 1 || !validNVFP4RouteIndices(indices) {
return nil
}
rows, width := values.Dim(0), values.Dim(3)
if indices.Dim(0) != rows || indices.Dim(1) != 1 || width%32 != 0 ||
!validNVFP4Bank(width, weight, scales) {
return nil
}
experts, channels := weight.Dim(0), weight.Dim(1)
// The prefix scan uses one hardware thread per expert. Native GatherQMM
// uses the sorted matrix reduction for at least 16 routes and 4 per expert.
if experts > 1024 || rows < 16 || rows/experts < 4 ||
uint64(rows)*uint64(width) > math.MaxUint32 || uint64(rows)*uint64(channels) > math.MaxUint32 {
return nil
}
columnTiles := 1 + (channels-1)/64
if columnTiles > math.MaxInt32/128 {
return nil
}
switch metalMatmul() {
case metalMatmulUnsupported:
return nil
case metalMatmulTensor:
return GatherQMM(values.AsType(DTypeFloat32), weight, scales, nil, nil, indices, true, 16, 4, "nvfp4", nil, true)
}
// Each expert after the first contributes at most one extra partial run.
capacity := (rows+31)/32 + experts - 1
runs, ok := nvfp4RouteRuns.applyMetal(gpuLaunch{
ints: []gpuIntArg{{"Experts", experts}},
inputs: []*Array{indices},
outputs: []gpuOutputSpec{{"NVFP4RouteRuns", []int32{int32(capacity), 3}, DTypeUint32}},
grid: [3]int{experts, 1, 1},
threadGroup: [3]int{experts, 1, 1},
})
if !ok {
return nil
}
metaShape := []int32{int32(rows), int32(width / 32)}
bounds, ok := nvfp4ActivationBounds.applyMetal(gpuLaunch{
inputs: []*Array{values},
outputs: []gpuOutputSpec{
{"NVFP4Quantum", metaShape, DTypeInt32},
{"NVFP4Maxima", metaShape, DTypeFloat32},
},
grid: [3]int{rows * (width / 32), 1, 1},
threadGroup: [3]int{128, 1, 1},
})
if !ok {
return nil
}
output, ok := gatherNVFP4QMM.applyMetal(gpuLaunch{
ints: []gpuIntArg{{"Width", width}, {"Channels", channels}},
inputs: []*Array{values, weight, scales, runs[0], bounds[0], bounds[1]},
outputs: []gpuOutputSpec{{"GatherNVFP4QMM", []int32{int32(rows), 1, 1, int32(channels)}, DTypeFloat32}},
grid: [3]int{columnTiles * 128, capacity, 1},
threadGroup: [3]int{128, 1, 1},
})
if !ok {
return nil
}
return output[0]
}
+179
View File
@@ -0,0 +1,179 @@
package mlx
import (
"math"
"testing"
"github.com/ollama/ollama/mlx/mlxthread/mlxthreadtest"
)
func TestGatherNVFP4QMM(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
if !hasMetalTensorOps() || metalMatmul() == metalMatmulUnsupported {
t.Skip("requires Metal tensor ops and a known grouped reduction")
}
for _, shape := range []struct{ rows, experts, width, channels int }{
{515, 128, 2304, 2304},
{77, 7, 96, 67}, // partial output tile and partially occupied runs
{583, 129, 64, 37}, // prefix scan spans more than 128 experts
{4096, 1024, 32, 9}, // largest supported prefix scan
} {
Scoped(func() {
rows, expertCount, width, channels := shape.rows, shape.experts, shape.width, shape.channels
activation := make([]float32, rows*width)
experts := make([]uint32, rows)
for row := range rows {
// Include empty experts, multiple full tiles and a partial tail.
if row >= 65 {
experts[row] = uint32(2 + 2*((row-65)*((expertCount-1)/2)/(rows-65)))
}
for col := range width {
activation[row*width+col] = float32((row*61+col*109)%997-498) * .25
}
}
// The leading product is 4,128,768. The following 1/16 terms are
// below half an FP32 ULP individually, while their block sum is
// large enough to change the result if the reduction is reordered.
activation[0] = 1536
for col := 1; col < 16; col++ {
activation[col] = 0
}
for col := 16; col < width; col++ {
activation[col] = .125
}
packed := make([]uint32, expertCount*width/8)
scales := make([]uint8, expertCount*width/16)
for i := range packed {
packed[i] = uint32(i) * 2654435761
}
for i := range width / 8 {
packed[i] = 0x11111111
}
packed[0] = 0x11111117
for i := range scales {
scales[i] = uint8(i % 127)
if i%3 == 0 {
scales[i] |= 128
}
}
for i := range width / 16 {
scales[i] = 0x38
}
scales[0] = 0x7e
// Reconstructed NVFP4 input values have a BF16-exact significand.
values := FromValues(activation, rows, 1, 1, width).AsType(DTypeBFloat16)
ids := FromValues(experts, rows, 1)
w := Add(FromValues(packed, expertCount, 1, width/8), Arange(0, float64(channels), 1, DTypeUint32).Reshape(1, channels, 1))
s := BroadcastTo(FromValues(scales, expertCount, 1, width/16), int32(expertCount), int32(channels), int32(width/16))
result := GatherNVFP4QMM(values, w, s, ids)
if result == nil {
t.Fatal("qualified grouped routes did not dispatch")
}
ref := GatherQMM(values.AsType(DTypeFloat32), w, s, nil, nil, ids, true, 16, 4, "nvfp4", nil, true)
actual, want := result.Flatten(0, -1).Floats(), ref.Flatten(0, -1).Floats()
control := float32(4128768)
if metalMatmul() == metalMatmulTensor {
// The accelerator adds each 16-product subtotal as a group.
control += float32(width/16 - 1)
}
if want[0] != control {
t.Fatalf("native rounding control = %v, want %v", want[0], control)
}
for i, v := range actual {
if math.Float32bits(v) != math.Float32bits(want[i]) {
t.Fatalf("shape %+v, route %d, channel %d: got %08x, want %08x", shape, i/channels, i%channels, math.Float32bits(v), math.Float32bits(want[i]))
}
}
if GatherNVFP4QMM(values, w, s, ids.Reshape(1, -1)) != nil {
t.Fatal("ungrouped route shape dispatched")
}
if GatherNVFP4QMM(values.AsType(DTypeFloat32), w, s, ids) != nil {
t.Fatal("FP32 activations were silently rounded to BF16")
}
few := values.Slice(Slice(0, 4), Slice(), Slice(), Slice())
if GatherNVFP4QMM(few, w, s, ids.Slice(Slice(0, 4), Slice())) != nil {
t.Fatal("short route list selected the sorted matrix reduction")
}
})
}
})
}
func TestGatherNVFP4QMMExtremes(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
if !hasMetalTensorOps() || metalMatmul() == metalMatmulUnsupported {
t.Skip("requires Metal tensor ops and a known grouped reduction")
}
Scoped(func() {
const rows, width, channels = 16, 64, 9
// Include the smallest normal BF16 input of either sign. Paired
// with a small scale, its dot can underflow to signed zero.
patterns := []uint32{
0, 0x00010000, 0x80800000, 0x7f7f0000, 0x00800000,
0x7fc00000, 0x7f800000, 0xff800000, 0x35b00000, 0xb5100000,
}
data := make([]float32, rows*width)
for i := range data {
data[i] = math.Float32frombits(patterns[(i/width)%len(patterns)])
}
encodings := []uint8{0x7e, 0x38, 0x01, 0x37, 0x7f, 0xff, 0, 1, 0x80}
blocks := make([]uint8, channels*width/16)
for i := range blocks {
blocks[i] = encodings[i/(width/16)]
}
w := BroadcastTo(FromValues([]uint32{0x7f129817}, 1, 1, 1), 1, channels, width/8)
s := FromValues(blocks, 1, channels, width/16)
ids := Zeros(DTypeInt32, rows, 1)
x := FromValues(data, rows, 1, 1, width).AsType(DTypeBFloat16)
y := GatherNVFP4QMM(x, w, s, ids)
if y == nil {
t.Fatal("valid grouped matmul did not dispatch")
}
ref := GatherQMM(x.AsType(DTypeFloat32), w, s, nil, nil, ids, true, 16, 4, "nvfp4", nil, true)
actual, want := y.Flatten(0, -1).Floats(), ref.Flatten(0, -1).Floats()
for i, v := range actual {
if math.Float32bits(v) != math.Float32bits(want[i]) {
t.Fatalf("row %d, channel %d: got %08x, want %08x", i/channels, i%channels, math.Float32bits(v), math.Float32bits(want[i]))
}
}
})
})
}
// Cancellation in a later tile can produce a subnormal even when every
// product in that tile is normal. Only the scalar reduction flushes that result.
func TestGatherNVFP4QMMCancellation(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
if !hasMetalTensorOps() || metalMatmul() == metalMatmulUnsupported {
t.Skip("requires Metal tensor ops and a known grouped reduction")
}
Scoped(func() {
const rows, width = 16, 64
data := make([]float32, width)
data[0], data[1], data[32] = 0x1p-126, 0x1p-126, -0x1p-116
x := BroadcastTo(FromValues(data, 1, 1, 1, width).AsType(DTypeBFloat16), rows, 1, 1, width)
// The first tile adds 1.5 * 2^-126. The second subtracts 2^-126.
words := []uint32{0x12, 0, 0, 0, 1, 0, 0, 0}
w := FromValues(words, 1, 1, width/8)
s := FromValues([]uint8{0x38, 0, 1, 0}, 1, 1, width/16)
ids := Zeros(DTypeInt32, rows, 1)
got := GatherNVFP4QMM(x, w, s, ids)
want := GatherQMM(x.AsType(DTypeFloat32), w, s, nil, nil, ids, true, 16, 4, "nvfp4", nil, true)
if got == nil {
t.Fatal("valid grouped matmul did not dispatch")
}
expected := float32(0)
if metalMatmul() == metalMatmulTensor {
expected = 0x1p-127
}
for i, v := range want.Flatten(0, -1).Floats() {
if v != expected {
t.Fatalf("native cancellation row %d: got %g, want %g", i, v, expected)
}
}
if got.View(DTypeUint32).Equal(want.View(DTypeUint32)).AsType(DTypeInt32).Reshape(-1).SumAxis(0, false).Int() != rows {
t.Fatal("grouped cancellation differs from native FP32")
}
})
})
}
+180
View File
@@ -0,0 +1,180 @@
package mlx
import "math"
// Stock short GatherQMM decodes the same weights for each route to an expert.
// A verification batch can share those reads across tokens that select the same expert.
const nvfp4DecodeMetal = `
#include <metal_stdlib>
using namespace metal;
// Shift E2M1 into the low exponent range of binary16. The half-to-float
// conversion handles its zero and subnormal values before rescaling.
inline float nvfp4_e2m1(uint bits) {
ushort fp16 = ushort(((bits & 8u) << 12) | ((bits & 7u) << 9));
return float(as_type<half>(fp16)) * 16384.0f;
}
inline float nvfp4_e4m3(uchar bits) {
uint magnitude = bits & 127u;
ushort sign = ushort(bits & 128u) << 8;
if (magnitude == 127u) return float(as_type<half>(ushort(sign | 0x7f80u)));
return float(as_type<half>(ushort(sign | (magnitude << 7)))) * 256.0f;
}
`
// Keep GatherQMM's eight-element FP32 partial sums when accumulating the shared tile.
var gatherNVFP4QMV = &gpuKernel{
name: "gather_nvfp4_qmv",
inputs: []string{"activation", "packed", "scales", "experts"},
outputs: []string{"result"},
metal: gpuSource{
header: nvfp4DecodeMetal + `template<uint Tokens, uint Width, uint Channels, uint Outputs, uint RowStep>
inline void nvfp4_gather_dot(
const device float* activation, const device uint* packed,
const device uchar* scales, device float* result,
thread const uint* routes, uint expert, uint first, uint lane) {
float sums[Outputs][Tokens] = {};
for (uint col = lane * 8; col < Width; col += 256) {
float4 left[Tokens], right[Tokens];
for (uint j = 0; j < Tokens; ++j) {
uint row = routes[j] / RowStep;
const device float4* x = (const device float4*)(activation + row * Width + col);
left[j] = x[0];
right[j] = x[1];
}
for (uint out = 0; out < Outputs; ++out) {
if (Channels % Outputs && first + out >= Channels) break;
uint row = expert * Channels + first + out;
uint word = packed[row * (Width / 8) + col / 8];
float scale = nvfp4_e4m3(scales[row * (Width / 16) + col / 16]);
float4 low, high;
for (uint k = 0; k < 4; ++k) {
low[k] = nvfp4_e2m1(word >> (4 * k));
high[k] = nvfp4_e2m1(word >> (4 * k + 16));
}
for (uint j = 0; j < Tokens; ++j) {
float4 x = left[j], y = right[j];
float a = x.x * low.x + x.y * low.y + x.z * low.z + x.w * low.w;
float b = y.x * high.x + y.y * high.y + y.z * high.z + y.w * high.w;
sums[out][j] += (a + b) * scale;
}
}
}
for (uint out = 0; out < Outputs; ++out) {
if (Channels % Outputs && first + out >= Channels) break;
for (uint j = 0; j < Tokens; ++j) {
float value = simd_sum(sums[out][j]);
if (lane == 0) result[routes[j] * Channels + first + out] = value;
}
}
}
`,
source: `
uint route = threadgroup_position_in_grid.y;
uint lane = thread_index_in_simdgroup;
uint first = (threadgroup_position_in_grid.x * (Workers / 32) + simdgroup_index_in_threadgroup) * Outputs;
if (Channels % ((Workers / 32) * Outputs) && first >= Channels) return;
uint expert = experts[route];
if (expert >= Experts) {
if (lane == 0) {
for (uint out = 0; out < Outputs && first + out < Channels; ++out)
result[route * Channels + first + out] = NAN;
}
return;
}
// The current route always contributes a bit, including on partial SIMDs.
uint matching = simd_or(lane < Routes && uint(experts[lane]) == expert ? (1u << lane) : 0u);
uint routes[4] = {route, 0, 0, 0};
uint count = 1;
// The register tile fits up to four routes. Larger runs compute one dot per route.
if (popcount(matching) <= 4) {
if (ctz(matching) != route) return;
matching &= matching - 1;
while (matching) {
routes[count++] = ctz(matching);
matching &= matching - 1;
}
}
switch (count) {
case 1: nvfp4_gather_dot<1, Width, Channels, Outputs, RowStep>(activation, packed, scales, result, routes, expert, first, lane); break;
case 2: nvfp4_gather_dot<2, Width, Channels, Outputs, RowStep>(activation, packed, scales, result, routes, expert, first, lane); break;
case 3: nvfp4_gather_dot<3, Width, Channels, Outputs, RowStep>(activation, packed, scales, result, routes, expert, first, lane); break;
case 4: nvfp4_gather_dot<4, Width, Channels, Outputs, RowStep>(activation, packed, scales, result, routes, expert, first, lane); break;
}
`,
},
}
// GatherNVFP4QMV multiplies FP32 vectors by selected transposed NVFP4
// matrices. For indices [B,T], x may be [B,1,1,K] (one vector per row) or
// [B,T,1,K] (one per route). Weights are [E,N,K/8] packed E2M1, with one
// E4M3FN scale per 16 elements. The FP32 output has shape [B,T,1,N].
// Up to 32 routes fit in one SIMD ballot. Out-of-range IDs produce NaNs.
// It returns nil when the device, layout, or native reduction is unsupported.
func GatherNVFP4QMV(x, weight, scales, indices *Array) *Array {
if x == nil || x.NumDims() != 4 || x.DType() != DTypeFloat32 || x.Dim(2) != 1 ||
!validNVFP4RouteIndices(indices) || indices.Dim(0) != x.Dim(0) {
return nil
}
rows, topK, width := indices.Dim(0), indices.Dim(1), x.Dim(3)
if rows < 1 || topK < 1 || rows > 32/topK ||
(x.Dim(1) != 1 && x.Dim(1) != topK) || !validNVFP4Bank(width, weight, scales) {
return nil
}
routes, experts, channels := rows*topK, weight.Dim(0), weight.Dim(1)
// GatherQMM's aligned QMV kernel reduces 16 elements per lane. This
// kernel matches the eight-element reduction of the other QMV shapes.
if (width%512 == 0 && channels%8 == 0) ||
uint64(x.Size()) > math.MaxUint32 || uint64(routes)*uint64(channels) > math.MaxUint32 {
return nil
}
routesPerVector, outputs, workers := topK, 2, 64
if x.Dim(1) != 1 {
routesPerVector, outputs, workers = 1, 4, 128
}
tile := outputs * (workers / 32)
groups := 1 + (channels-1)/tile
if groups > math.MaxInt32/workers || !UsesM5MatrixKernels() {
return nil
}
result, ok := gatherNVFP4QMV.applyMetal(gpuLaunch{
ints: []gpuIntArg{
{"Width", width},
{"Channels", channels},
{"Experts", experts},
{"Routes", routes},
{"RowStep", routesPerVector},
{"Outputs", outputs},
{"Workers", workers},
},
inputs: []*Array{x, weight, scales, indices},
outputs: []gpuOutputSpec{{"GatherNVFP4QMV", []int32{int32(rows), int32(topK), 1, int32(channels)}, DTypeFloat32}},
grid: [3]int{groups * workers, routes, 1},
threadGroup: [3]int{workers, 1, 1},
})
if !ok {
return nil
}
return result[0]
}
func validNVFP4RouteIndices(indices *Array) bool {
return indices != nil && indices.NumDims() == 2 &&
(indices.DType() == DTypeInt32 || indices.DType() == DTypeUint32)
}
func validNVFP4Bank(width int, weight, scales *Array) bool {
if width <= 0 || width%16 != 0 || weight == nil || scales == nil ||
weight.NumDims() != 3 || weight.DType() != DTypeUint32 ||
scales.NumDims() != 3 || scales.DType() != DTypeUint8 {
return false
}
experts, channels := weight.Dim(0), weight.Dim(1)
// The shaders address both packed arrays with 32-bit element offsets.
return experts > 0 && channels > 0 && weight.Dim(2) == width/8 &&
scales.Dim(0) == experts && scales.Dim(1) == channels && scales.Dim(2) == width/16 &&
uint64(experts)*uint64(channels) <= math.MaxUint32/uint64(width/8)
}
+110
View File
@@ -0,0 +1,110 @@
package mlx
import (
"math"
"testing"
"github.com/ollama/ollama/mlx/mlxthread/mlxthreadtest"
)
func TestGatherNVFP4QMV(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
if !isM5MatrixDevice(kernelDevice()) {
t.Skip("requires qualified Metal NVFP4 matvec")
}
for _, width := range []int{2304, 1152} {
Scoped(func() {
// Across rows, experts appear once, twice, three times, or four times.
ids := FromValues([]uint32{0, 1, 2, 3, 4, 5, 6, 7, 1, 8, 9, 0, 2, 10, 11, 12, 13, 14, 0, 2, 15, 16, 17, 18, 19, 20, 21, 22, 0, 23, 24, 25}, 4, 8)
n := 1
if width == 1152 {
n = 8
}
data := make([]float32, 4*n*width)
for i := range data {
data[i] = float32((i*337)%1981-990) * 0.25
}
x := FromValues(data, 4, n, 1, width)
words := make([]uint32, 128*width/8)
for i := range words {
words[i] = uint32(i) * 2654435761
}
w := Add(FromValues(words, 128, 1, width/8), Arange(0, 2304, 1, DTypeUint32).Reshape(1, 2304, 1))
// Each output row uses a single E4M3FN encoding across its K
// blocks. All 256 encodings reach the output independently.
blocks := make([]uint8, 128*2304)
for i := range blocks {
blocks[i] = uint8(i)
}
s := BroadcastTo(FromValues(blocks, 128, 2304, 1), 128, 2304, int32(width/16))
for _, routes := range []*Array{ids, Zeros(DTypeUint32, 4, 8)} {
y := GatherNVFP4QMV(x, w, s, routes)
if y == nil {
t.Fatalf("width %d did not dispatch", width)
}
reference := GatherQMM(x, w, s, nil, nil, routes, true, 16, 4, "nvfp4", nil, false)
actual, expected := y.Flatten(0, -1).Floats(), reference.Flatten(0, -1).Floats()
for i, v := range actual {
if math.Float32bits(v) != math.Float32bits(expected[i]) {
t.Fatalf("width %d, output %d (scale %#02x): got %08x, expected %08x", width, i, uint8(i%2304), math.Float32bits(v), math.Float32bits(expected[i]))
}
}
}
invalid := Add(ids, FromValue(128).AsType(DTypeUint32))
for i, v := range GatherNVFP4QMV(x, w, s, invalid).Flatten(0, -1).Floats() {
if !math.IsNaN(float64(v)) {
t.Fatalf("invalid route output %d = %g", i, v)
}
}
if GatherNVFP4QMV(x.Slice(Slice(0, 1), Slice(), Slice(), Slice()), w, s, ids) != nil {
t.Fatal("mismatched route-row count dispatched")
}
})
}
})
}
func TestGatherNVFP4QMVRectangular(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
if !isM5MatrixDevice(kernelDevice()) {
t.Skip("requires qualified Metal NVFP4 matvec")
}
Scoped(func() {
const rows, topK, experts, width, channels = 3, 4, 7, 96, 67
ids := FromValues([]int32{0, 1, 4, 6, 1, 1, 2, 0, 1, 1, 2, 4}, rows, topK)
words := make([]uint32, experts*channels*width/8)
blocks := make([]uint8, experts*channels*width/16)
for i := range words {
words[i] = uint32(i) * 2654435761
}
for i := range blocks {
blocks[i] = uint8((i * 19) % 127)
}
w := FromValues(words, experts, channels, width/8)
s := FromValues(blocks, experts, channels, width/16)
for _, inputRoutes := range []int{1, topK} {
data := make([]float32, rows*inputRoutes*width)
for i := range data {
data[i] = float32((i*17)%57-21) / float32(1+i%23)
}
x := FromValues(data, rows, inputRoutes, 1, width)
got := GatherNVFP4QMV(x, w, s, ids)
if got == nil {
t.Fatalf("input routes %d did not dispatch", inputRoutes)
}
ref := GatherQMM(x, w, s, nil, nil, ids, true, 16, 4, "nvfp4", nil, false)
actual, expected := got.Flatten(0, -1).Floats(), ref.Flatten(0, -1).Floats()
for i, y := range actual {
if math.Float32bits(y) != math.Float32bits(expected[i]) {
t.Fatalf("input routes %d, row %d, channel %d: got %08x, want %08x", inputRoutes, i/channels, i%channels, math.Float32bits(y), math.Float32bits(expected[i]))
}
}
}
// Native GatherQMM uses a different reduction at this alignment.
if GatherNVFP4QMV(Zeros(DTypeFloat32, 1, 1, 1, 512), Zeros(DTypeUint32, 1, 8, 64),
Zeros(DTypeUint8, 1, 8, 32), Zeros(DTypeUint32, 1, 1)) != nil {
t.Fatal("aligned native QMV dispatched")
}
})
})
}
+7
View File
@@ -49,6 +49,13 @@ func (t *Array) AsType(dtype DType) *Array {
return out
}
// View reinterprets the array's storage as dtype without converting the values.
func (t *Array) View(dtype DType) *Array {
out := New("VIEW")
mlxCheck(C.mlx_view(&out.ctx, t.ctx, C.mlx_dtype(dtype), DefaultStream().ctx))
return out
}
func (t *Array) BitwiseXor(other *Array) *Array {
out := New("BITWISE_XOR")
mlxCheck(C.mlx_bitwise_xor(&out.ctx, t.ctx, other.ctx, DefaultStream().ctx))
+204
View File
@@ -0,0 +1,204 @@
package mlx
import (
"math"
"os"
"sync"
)
// MLX selects split vector attention for a single query with 1024 or more visible
// keys on these devices. The fused bias path must match its number of partial sums.
var relativeAttentionParts = sync.OnceValue(func() int {
if !MetalIsAvailable() || os.Getenv("MLX_SDPA_BLOCKS") != "" {
return 0
}
return relativeAttentionSplitParts(kernelDevice())
})
func relativeAttentionSplitParts(name, arch string) int {
switch {
case name == "Apple M2 Ultra" && arch == "applegpu_g14d",
name == "Apple M3 Ultra" && arch == "applegpu_g15d",
name == "Apple M5 Ultra" && arch == "applegpu_g17d":
return 128
case name == "Apple M4 Pro" && arch == "applegpu_g16s",
isM5Pro(name, arch), name == "Apple M5 Max" && arch == "applegpu_g17s":
return 64
default:
return 0
}
}
// RelativePositionAttention applies causal attention to one ordered sequence of
// BF16 keys and values. Q has shape [1, heads, queries, width], and K and V
// have shape [1, kvHeads, keys, width]. The queries cover the final positions
// of K. Each group of heads/kvHeads query heads shares one KV head.
//
// For a query and key separated by d positions, table[0, head, query, d]
// adds a score bias. Distances past the end of the table contribute zero.
// Each query also has a learned sink of shape [1, heads, queries, 1] with
// zero value. The query dtype (BF16 or FP32) controls the shifted bias, partial
// numerators and output. K, V, the bias table and sink stay in BF16.
// A positive window limits history to that many keys including the query's
// own position. Zero allows its entire history. Unsupported inputs return nil.
func RelativePositionAttention(q, k, v, table, sink *Array, window int, scale float32) *Array {
for i, a := range []*Array{q, k, v, table, sink} {
if a == nil || a.NumDims() != 4 || a.Dim(0) != 1 {
return nil
}
if dtype := a.DType(); dtype != DTypeBFloat16 && !(i == 0 && dtype == DTypeFloat32) {
return nil
}
if size := a.Size(); size == 0 || uint64(size) > math.MaxUint32 {
return nil
}
}
heads, queries, width := q.Dim(1), q.Dim(2), q.Dim(3)
kvHeads, keys := k.Dim(1), k.Dim(2)
if keys < queries || heads%kvHeads != 0 || window < 0 || window > math.MaxInt32 ||
k.Dim(3) != width || v.Dim(1) != kvHeads || v.Dim(2) != keys || v.Dim(3) != width ||
table.Dim(1) != heads || table.Dim(2) != queries || sink.Dim(1) != heads || sink.Dim(2) != queries || sink.Dim(3) != 1 {
return nil
}
if queries > 8 {
return relativeAttentionPrefill(q, k, v, table, sink, window, scale)
}
// Match single-query native SDPA on long visible histories.
if keys-queries+1 < 1024 || (window > 0 && window < 1024) {
return nil
}
parts := relativeAttentionParts()
if parts == 0 {
return nil
}
sharing := heads / kvHeads
maxVisible := keys
if window > 0 {
maxVisible = min(keys, window)
}
// The Metal shader assigns four channels to each SIMD lane. Larger
// groups, and small groups with long histories on Ultra, can select a
// different native partition count and change the rounding of each part.
if width != 128 || sharing > 4 || (parts == 128 && sharing <= 2 && maxVisible > 8192) {
return nil
}
rows := heads * queries
if uint64(rows) > math.MaxUint32/uint64(parts*width) {
return nil
}
partials, ok := relativeAttentionPart.applyMetal(gpuLaunch{
inputs: []*Array{q, k, v, table, sink, FromValue(keys), FromValue(window), FromValue(scale)},
dtypes: []gpuDTypeArg{{"T", q.DType()}},
ints: []gpuIntArg{{"Queries", queries}, {"Distances", table.Dim(3)}, {"Sharing", heads / k.Dim(1)}, {"Parts", parts}},
outputs: []gpuOutputSpec{
{"relative_numerators", []int32{int32(rows), int32(parts), 128}, q.DType()},
{"relative_statistics", []int32{int32(rows), int32(parts), 2}, DTypeFloat32},
},
grid: [3]int{32 * parts, rows, 1}, threadGroup: [3]int{128, 1, 1},
})
if !ok {
return nil
}
output, ok := relativeAttentionMerge.applyMetal(gpuLaunch{
inputs: partials,
dtypes: []gpuDTypeArg{{"T", q.DType()}},
ints: []gpuIntArg{{"Parts", parts}},
outputs: []gpuOutputSpec{{"relative_result", []int32{1, int32(heads), int32(queries), 128}, q.DType()}},
grid: [3]int{1024, rows, 1}, threadGroup: [3]int{128, 1, 1},
})
if !ok {
return nil
}
return output[0]
}
// Stock vector SDPA takes a dense mask for learned distances and per-query sinks.
// Apply the bias while reading each key and round the partial numerator as MLX does.
var relativeAttentionPart = &gpuKernel{
name: "relative_attention_part",
inputs: []string{"query", "keys", "values", "relative", "sink", "extent", "window", "scale"},
outputs: []string{"numerators", "statistics"},
metal: gpuSource{source: `
uint row = thread_position_in_grid.y;
uint lane = thread_index_in_simdgroup;
uint shard = thread_position_in_grid.x / 32;
uint proposal = row % Queries;
uint head = row / Queries;
uint end = uint(extent) - Queries + proposal + 1;
uint visible = window ? min(end, uint(window)) : end;
uint offset = (head / Sharing) * uint(extent) * 128;
uint component = lane * 4;
float4 q;
for (uint j = 0; j < 4; j++) {
q[j] = float(query[row * 128 + component + j]) * scale;
}
bool with_sink = shard == 0;
float peak = with_sink ? 0.0f : -INFINITY;
float weight = with_sink ? 1.0f : 0.0f;
float4 value(0.0f);
for (uint i = shard; i < visible; i += Parts) {
uint base = offset + (i + end - visible) * 128 + component;
float dot = 0.0f;
for (uint j = 0; j < 4; j++) {
dot = fma(q[j], float(keys[base + j]), dot);
}
uint distance = visible - i - 1;
float bias = distance < Distances ? float(relative[row * Distances + distance]) : 0.0f;
bias = float(T(bias - float(sink[row])));
float score = simd_sum(dot) + bias;
float next = max(peak, score);
float prior = fast::exp(peak - next);
float prob = fast::exp(score - next);
for (uint j = 0; j < 4; j++) {
value[j] = fma(value[j], prior, prob * float(values[base + j]));
}
weight = fma(weight, prior, prob);
peak = next;
}
uint idx = row * Parts + shard;
if (lane == 0) {
statistics[2 * idx] = peak;
statistics[2 * idx + 1] = weight;
}
for (uint j = 0; j < 4; j++) {
numerators[idx * 128 + component + j] = T(value[j]);
}
`},
}
// MLX exposes only the final SDPA output. Merge the partial softmax sums and
// numerators in its native reduction order to reproduce the same output rounding.
var relativeAttentionMerge = &gpuKernel{
name: "relative_attention_merge",
inputs: []string{"numerators", "statistics"},
outputs: []string{"output"},
metal: gpuSource{source: `
uint row = thread_position_in_grid.y;
uint lane = thread_index_in_simdgroup;
uint component = (thread_position_in_grid.x / 32) * 4;
uint first = row * Parts;
float peak = -INFINITY;
for (uint p = lane; p < Parts; p += 32) {
peak = max(peak, statistics[2 * (first + p)]);
}
peak = simd_max(peak);
float z = 0.0f;
float4 value(0.0f);
for (uint p = lane; p < Parts; p += 32) {
uint idx = first + p;
float factor = fast::exp(statistics[2 * idx] - peak);
z = fma(statistics[2 * idx + 1], factor, z);
for (uint j = 0; j < 4; j++) {
value[j] = fma(float(numerators[idx * 128 + component + j]), factor, value[j]);
}
}
z = simd_sum(z);
for (uint j = 0; j < 4; j++) {
float answer = simd_sum(value[j]) / z;
if (lane == 0) {
uint idx = row * 128 + component + j;
output[idx] = T(answer);
}
}
`},
}
+273
View File
@@ -0,0 +1,273 @@
package mlx
import (
"math"
"slices"
)
func supportsRelativeAttentionPrefill(name, arch string) bool {
return isM5MatrixDevice(name, arch) ||
name == "Apple M2 Pro" && arch == "applegpu_g14s" ||
name == "Apple M2 Ultra" && arch == "applegpu_g14d" ||
name == "Apple M3 Ultra" && arch == "applegpu_g15d" ||
name == "Apple M4 Pro" && arch == "applegpu_g16s"
}
// Stock SDPA takes a dense bias for learned relative positions. Tiling the queries
// limits both the bias allocation and the attention work to the keys each tile can see.
func relativeAttentionPrefill(q, k, v, table, sink *Array, window int, scale float32) *Array {
// Native matrix attention uses the same key-tile alignment for these widths.
width := q.Dim(3)
if (width != 64 && width != 128) || !MetalIsAvailable() || !supportsRelativeAttentionPrefill(kernelDevice()) {
return nil
}
heads, queries, keys := q.Dim(1), q.Dim(2), k.Dim(2)
const tile = 256
cut := func(x *Array, start, end int) *Array { return x.Slice(Slice(), Slice(), Slice(start, end), Slice()) }
sinks := Zeros(q.DType(), heads)
var pieces []*Array
for begin := 0; begin < queries; {
end := min(queries, begin+tile)
// Preserve the native matrix attention path on the final partial tile.
if queries-end < 64 {
end = queries
}
lastKey := keys - queries + end
firstKey := 0
if window > 0 {
// Keep the first retained key on the original reduction boundary.
firstKey = max(0, keys-queries+begin+1-window) / 64 * 64
}
n, span := end-begin, lastKey-firstKey
if uint64(heads)*uint64(n)*uint64(span) > math.MaxUint32 {
return nil
}
// Pass query-major tables so the mask kernel reads adjacent heads per query.
bias, ok := relativeAttentionMask.applyMetal(gpuLaunch{
inputs: []*Array{cut(table, begin, end).Transpose(0, 2, 1, 3), cut(sink, begin, end).Transpose(0, 2, 1, 3), FromValue(n), FromValue(span), FromValue(window)},
dtypes: []gpuDTypeArg{{"T", q.DType()}},
ints: []gpuIntArg{{"Heads", heads}, {"Distances", table.Dim(3)}},
outputs: []gpuOutputSpec{{"relative_bias", []int32{1, int32(heads), int32(n), int32(span)}, q.DType()}},
grid: [3]int{span, n, heads}, threadGroup: [3]int{256, 1, 1},
})
if !ok {
return nil
}
out := FastScaledDotProductAttentionWithSinks(cut(q, begin, end), cut(k, firstKey, lastKey), cut(v, firstKey, lastKey), scale, FastSDPANoWindow, "", bias[0], sinks)
if begin == 0 && end == queries {
return out
}
pieces = append(pieces, out)
begin = end
}
return Concatenate(pieces, 2)
}
// RelativePositionDecodeBias reuses the prefill mask shader for a single final query.
// All keys are causal for this row; the caller applies any sliding-window mask.
func RelativePositionDecodeBias(table, sink *Array, keys int) *Array {
if table == nil || sink == nil || keys < 1 || keys > math.MaxInt32 ||
!MetalIsAvailable() || !supportsRelativeAttentionPrefill(kernelDevice()) {
return nil
}
if table.NumDims() != 4 || table.Dim(0) != 1 || table.Dim(2) != 1 ||
table.DType() != DTypeBFloat16 || sink.DType() != DTypeBFloat16 {
return nil
}
heads, distances := table.Dim(1), table.Dim(3)
if heads == 0 || distances == 0 || uint64(heads)*uint64(max(keys, distances)) > math.MaxUint32 ||
sink.NumDims() != 4 || sink.Dim(0) != 1 || sink.Dim(1) != heads || sink.Dim(2) != 1 || sink.Dim(3) != 1 {
return nil
}
result, ok := relativeAttentionMask.applyMetal(gpuLaunch{
inputs: []*Array{table, sink, FromValue(1), FromValue(keys), FromValue(0)},
dtypes: []gpuDTypeArg{{"T", DTypeFloat32}},
ints: []gpuIntArg{{"Heads", heads}, {"Distances", distances}},
outputs: []gpuOutputSpec{{"relative_bias", []int32{1, int32(heads), 1, int32(keys)}, DTypeFloat32}},
grid: [3]int{keys, 1, heads}, threadGroup: [3]int{256, 1, 1},
})
if !ok {
return nil
}
return result[0]
}
// The stock graph gathers distances, shifts by the sink and applies masks separately.
// Write the final bias for a visible query/key tile in one pass.
var relativeAttentionMask = &gpuKernel{
name: "relative_attention_mask",
inputs: []string{"table", "sinks", "queries", "keys", "window"},
outputs: []string{"bias"},
metal: gpuSource{source: `
uint3 pos = thread_position_in_grid;
int distance = int(keys) - int(queries) + int(pos.y) - int(pos.x);
uint row = pos.y * Heads + pos.z;
float relative = (distance >= 0 && distance < Distances) ? float(table[row * Distances + distance]) : 0.0f;
float shifted = relative - float(sinks[row]);
bool masked = distance < 0 || (window > 0 && distance >= window);
bias[(pos.z * queries + pos.y) * keys + pos.x] = T(masked ? -INFINITY : shifted);
`},
}
// RelativePositionAttentionBF16Probabilities computes causal attention in reverse 128-key
// blocks. It expects BF16 query values widened to FP32. The tensor operations accumulate
// in FP32 and round the unnormalized probabilities to BF16 for the value product.
// firstKey is the absolute token position of the first retained key, including after eviction.
func RelativePositionAttentionBF16Probabilities(q, k, v, table, sink *Array, firstKey, window int, scale float32) *Array {
if firstKey < 0 || window < 1 || window > math.MaxInt32 {
return nil
}
for i, a := range []*Array{q, k, v, table, sink} {
if a == nil || a.NumDims() != 4 || a.Dim(0) != 1 || a.Size() < 1 || a.Size() > math.MaxInt32 {
return nil
}
if (i == 0 && a.DType() != DTypeFloat32) || (i != 0 && a.DType() != DTypeBFloat16) {
return nil
}
}
const width, tileRows, groups = 128, 16, 4
heads, queries, kvHeads, keys := q.Dim(1), q.Dim(2), k.Dim(1), k.Dim(2)
if queries <= 8 || queries > keys || heads%kvHeads != 0 || q.Dim(3) != width || k.Dim(3) != width ||
!slices.Equal(k.Dims(), v.Dims()) || !slices.Equal(table.Dims()[:3], q.Dims()[:3]) ||
!slices.Equal(sink.Dims()[:3], q.Dims()[:3]) || sink.Dim(3) != 1 {
return nil
}
if !hasMetalTensorOps() {
return nil
}
leading := firstKey % width
paddedKeys := (leading + keys + width - 1) / width * width
paddedQueries := (queries + tileRows - 1) / tileRows * tileRows
if paddedKeys > math.MaxInt32/kvHeads/width || paddedQueries > math.MaxInt32/heads/width {
return nil
}
// Align physical key blocks to their original token positions, including the
// first partial block of a sliding window. The shader masks both padded borders.
if leading != 0 || paddedKeys != keys {
trailing := paddedKeys - leading - keys
k = PadConstant(k, []int{2}, []int{leading}, []int{trailing})
v = PadConstant(v, []int{2}, []int{leading}, []int{trailing})
}
if paddedQueries != queries {
q = PadConstant(q, []int{2}, []int{0}, []int{paddedQueries - queries})
}
shape := FromValues([]int32{int32(queries), int32(keys), int32(table.Dim(3)), int32(window), int32(leading), int32(heads / kvHeads), int32(paddedQueries), int32(paddedKeys)}, 8)
result, ok := relativeAttentionBF16Probabilities.applyMetal(gpuLaunch{
inputs: []*Array{q, k, v, table, sink, FromValue(scale), shape},
ints: []gpuIntArg{{"Groups", groups}},
outputs: []gpuOutputSpec{{"attention", []int32{1, int32(heads), int32(queries), width}, DTypeFloat32}},
grid: [3]int{paddedQueries / tileRows * groups * 32, heads, 1}, threadGroup: [3]int{groups * 32, 1, 1},
})
if !ok {
return nil
}
return result[0]
}
// Stock FP32 SDPA retains FP32 probabilities in the value product. Round each
// reverse tile's unnormalized probabilities to BF16 while preserving FP32 normalization.
var relativeAttentionBF16Probabilities = &gpuKernel{
name: "relative_attention_bf16_probabilities",
inputs: []string{"query", "key", "value", "table", "sink", "scale", "shape"},
outputs: []string{"out"},
metal: gpuSource{header: `
#include <metal_tensor>
#include <MetalPerformancePrimitives/MetalPerformancePrimitives.h>
using namespace metal;
`, source: `
using namespace mpp::tensor_ops;
using dims = dextents<int, 2>;
using strides = array<int, 2>;
constexpr int rows = 16, width = 128, channels = width / Groups;
constexpr matmul2d_descriptor dotShape(rows, channels, width, false, true, true);
constexpr matmul2d_descriptor valueShape(rows, channels, width, false, false, true);
matmul2d<dotShape, execution_simdgroup> dot;
matmul2d<valueShape, execution_simdgroup> weightedValue;
const int Queries=shape[0], Keys=shape[1], Distances=shape[2], Window=shape[3];
const int Leading=shape[4], Sharing=shape[5], QPad=shape[6], KPad=shape[7];
const int head = threadgroup_position_in_grid.y;
const int rowStart = threadgroup_position_in_grid.x * rows;
const int group = simdgroup_index_in_threadgroup, lane = thread_index_in_simdgroup;
const int columnStart = group * channels;
const int queryStart = Leading + Keys - Queries + rowStart;
const int newest = (queryStart + min(rows, Queries - rowStart) - 1) / width;
const int oldest = max(Leading, queryStart + 1 - Window) / width;
threadgroup float tile[rows * width], scalePrior[rows], denominator[rows], sinkWeight[rows];
threadgroup bfloat probabilities[rows * width];
float accumulator[rows][channels / 32] = {};
float peaks[rows / Groups], denominators[rows / Groups] = {};
for (int i = 0; i < rows / Groups; ++i) peaks[i] = -INFINITY;
tensor<device float, dims, tensor_inline> queries((device float*)query + (head * QPad + rowStart) * width,
dims(width, rows), strides{1, width});
tensor<threadgroup float, dims, tensor_inline> output(tile + columnStart, dims(channels, rows), strides{1, width});
tensor<threadgroup bfloat, dims, tensor_inline> p(probabilities, dims(width, rows), strides{1, width});
for (int block = newest; block >= oldest; --block) {
const int base = ((head / Sharing) * KPad + block * width) * width;
tensor<device bfloat, dims, tensor_inline> keys((device bfloat*)key + base + columnStart * width,
dims(width, channels), strides{1, width});
dot.run(queries, keys, output);
threadgroup_barrier(mem_flags::mem_threadgroup);
// Each SIMD group normalizes complete rows using the running 128-key maximum.
for (int r = group; r < rows; r += Groups) {
const int queryRow = rowStart + r, row = head * Queries + queryRow;
float score[4], localMax = -INFINITY;
for (int j = 0; j < 4; ++j) {
const int col = lane + j * 32, keyIndex = block * width + col;
const int distance = queryStart + r - keyIndex;
score[j] = -INFINITY;
if (queryRow < Queries && keyIndex >= Leading && distance >= 0 && distance < Window) {
const float relative = distance < Distances ? float(table[row * Distances + distance]) : 0;
score[j] = fma(tile[r * width + col], float(scale), relative);
}
localMax = max(localMax, score[j]);
}
const int i = r / Groups;
const float peak = max(peaks[i], simd_max(localMax));
const float previous = isfinite(peaks[i]) ? fast::exp(peaks[i] - peak) : 0;
float localSum = 0;
for (int j = 0; j < 4; ++j) {
const float weight = isfinite(score[j]) ? fast::exp(score[j] - peak) : 0;
probabilities[r * width + lane + j * 32] = bfloat(weight);
localSum += weight;
}
denominators[i] = fma(denominators[i], previous, simd_sum(localSum));
peaks[i] = peak;
if (lane == 0) {
scalePrior[r] = previous;
if (block == oldest && queryRow < Queries) {
// Include the sink in the softmax denominator with a single reciprocal.
const float gap = float(sink[row]) - peak;
const float inverse = 1 / (denominators[i] + fast::exp(gap));
denominator[r] = 1;
sinkWeight[r] = inverse;
if (inverse < FLT_MIN) {
// A large sink can flush the reciprocal even when the gated
// mean is normal. Normalize V before applying the sink there.
denominator[r] = denominators[i];
sinkWeight[r] = 1 / (1 + fast::exp(gap - fast::log(denominators[i])));
}
}
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
tensor<device bfloat, dims, tensor_inline> values((device bfloat*)value + base + columnStart,
dims(channels, width), strides{1, width});
weightedValue.run(p, values, output);
threadgroup_barrier(mem_flags::mem_threadgroup);
for (int r = 0; r < rows; ++r) {
for (int j = 0; j < channels / 32; ++j) {
accumulator[r][j] = fma(accumulator[r][j], scalePrior[r], tile[r * width + columnStart + lane + j*32]);
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
}
for (int r = 0; r < min(rows, Queries - rowStart); ++r) {
const int offset = (head * Queries + rowStart + r) * width + columnStart + lane;
for (int j = 0; j < channels / 32; ++j) out[offset + j * 32] = (accumulator[r][j] / denominator[r]) * sinkWeight[r];
}
`},
}
+83
View File
@@ -0,0 +1,83 @@
package mlx
import (
"math"
"testing"
"github.com/ollama/ollama/mlx/mlxthread/mlxthreadtest"
)
func TestRelativeAttentionPrefill(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
if !MetalIsAvailable() {
t.Skip("requires Metal")
}
if !supportsRelativeAttentionPrefill(kernelDevice()) {
t.Skip("requires a Metal device with qualified tiled prefill")
}
check := func(queries, keys, heads, kvHeads, width, distances, window int) {
scale := float32(1 / math.Sqrt(float64(width)))
Scoped(func() {
q, k, v, table, sink := relativeAttentionInputs(queries+3, keys, heads, kvHeads, width, distances)
// Crop a tail from strided views to test offsets in all five operands.
crop := func(x *Array) *Array { return x.Slice(Slice(), Slice(), Slice(3, queries+3), Slice()) }
q, table, sink = crop(q), crop(table), crop(sink)
pos := Arange(float64(keys-queries), float64(keys), 1, DTypeInt32).Reshape(1, 1, queries, 1)
distance := pos.Subtract(Arange(0, float64(keys), 1, DTypeInt32))
index := Clip(distance, FromValue(0), FromValue(distances-1))
relative := Where(distance.Equal(index), table.TakeAlongAxis(index, -1).AsType(DTypeFloat32), FromValue(float32(0)))
bias := relative.Subtract(sink.AsType(DTypeFloat32))
inf := FromValue(float32(math.Inf(-1)))
bias = Where(distance.Less(FromValue(0)), inf, bias)
if window > 0 {
bias = Where(FromValue(window-1).Less(distance), inf, bias)
}
for _, dtype := range []DType{DTypeBFloat16, DTypeFloat32} {
query := q.AsType(dtype)
got := RelativePositionAttention(query, k, v, table, sink, window, scale)
if got == nil || got.DType() != dtype {
t.Fatalf("prefill did not return dtype %v", dtype)
}
want := FastScaledDotProductAttentionWithSinks(query, k.AsType(dtype), v.AsType(dtype), scale, FastSDPANoWindow, "", bias.AsType(dtype), Zeros(dtype, heads))
if err := requireExact("tiled prefill", Contiguous(got, false), Contiguous(want, false)); err != nil {
t.Fatalf("prefill %d/%d window %d dtype %v: %v", queries, keys, window, dtype, err)
}
}
})
}
for _, tc := range []struct{ queries, keys, window int }{
{9, 9, 0},
{63, 84, 1024},
{64, 1031, 1024},
{65, 68, 0},
{257, 257, 1024},
{319, 1542, 0},
{320, 1543, 0},
{400, 1400, 1024},
{400, 1423, 1024},
{1023, 1120, 1024},
{1024, 1120, 1024},
{1089, 2110, 1024},
} {
check(tc.queries, tc.keys, 24, 8, 128, 1024, tc.window)
}
// Vary the table and the window independently, including a single
// learned distance, and exercise MHA and GQA with different head widths.
check(75, 135, 4, 4, 64, 1, 31)
check(319, 517, 8, 2, 64, 29, 133)
check(327, 934, 6, 2, 128, 77, 0)
check(21, 27, 1, 1, 128, 51, 1)
const scale = 0.125
q, k, v, table, sink := relativeAttentionInputs(9, 32, 24, 8, 128, 1024)
if RelativePositionAttention(q, k, v, table, sink, -1, scale) != nil ||
RelativePositionAttention(q.AsType(DTypeFloat16), k, v, table, sink, 0, scale) != nil ||
RelativePositionAttention(q, k.Slice(Slice(), Slice(), Slice(0, 8), Slice()), v, table, sink, 0, scale) != nil ||
RelativePositionAttention(q, nil, v, table, sink, 0, scale) != nil {
t.Fatal("unsupported input selected prefill")
}
q, k, v, table, sink = relativeAttentionInputs(8, 32, 24, 8, 128, 1024)
if RelativePositionAttention(q, k, v, table, sink, 0, scale) != nil {
t.Fatal("verification width selected prefill")
}
})
}
@@ -0,0 +1,110 @@
package mlx
import (
"math"
"slices"
"testing"
"github.com/ollama/ollama/mlx/mlxthread/mlxthreadtest"
)
func TestRelativePositionAttentionBF16Probabilities(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
if !hasMetalTensorOps() {
t.Skip("requires Metal tensor ops")
}
const queries, keys, width, window = 17, 273, 128, 176
const scale = 0.25
// Each output channel samples one key's individual contribution. The
// peaks straddle absolute block boundaries and change along the window.
positions := []int{84, 93, 124, 127, 130, 190, 199, 240, 250, 255, 256, 265, 271}
keyScore := make([]float32, keys)
keyScore[124], keyScore[130], keyScore[190] = 5.5, 1.1875, 4
keyScore[240], keyScore[265] = 2.5, 1.25
qData := make([]float32, queries*width)
kData := make([]float32, keys*width)
vData := make([]float32, keys*width)
sinkData := make([]float32, queries)
for i := range queries {
qData[i*width] = 1
sinkData[i] = float32(i%3) + 3.5
}
for key, score := range keyScore {
kData[key*width] = score / scale
}
for channel, key := range positions {
vData[key*width+channel] = 64
}
relative := []float32{0.25, 0, 0, -0.5, 0, 0, 0, 0, 0.75}
q := FromValues(qData, 1, 1, queries, width)
k := FromValues(kData, 1, 1, keys, width).AsType(DTypeBFloat16)
v := FromValues(vData, 1, 1, keys, width).AsType(DTypeBFloat16)
table := BroadcastTo(FromValues(relative, 1, 1, 1, len(relative)).AsType(DTypeBFloat16), 1, 1, queries, int32(len(relative)))
sink := FromValues(sinkData, 1, 1, queries, 1).AsType(DTypeBFloat16)
for _, firstKey := range []int{0, 61} {
out := RelativePositionAttentionBF16Probabilities(q, k, v, table, sink, firstKey, window, scale)
if out == nil || out.DType() != DTypeFloat32 {
t.Fatal("expected the FP32 attention result")
}
actual := Contiguous(out, false).Floats()
for row := range queries {
end := keys - queries + row + 1
start := max(0, end-window)
scores := make([]float64, end)
denominator := math.Exp(float64(sinkData[row]))
for key := start; key < end; key++ {
score := float64(keyScore[key])
if dist := end - 1 - key; dist < len(relative) {
score += float64(relative[dist])
}
scores[key] = score
denominator += math.Exp(score)
}
for channel, key := range positions {
want := 0.0
if start <= key && key < end {
// At this key's multiply, the running maximum covers
// its absolute 128-key block and all more recent blocks.
blockStart := (firstKey+key)/128*128 - firstKey
peak := slices.Max(scores[max(start, blockStart):])
p := float32(math.Exp(scores[key] - peak))
// Round just the unnormalized numerator weight to nearest
// even BF16. The denominator above retains full precision.
bits := math.Float32bits(p)
p = math.Float32frombits((bits + 0x7fff + ((bits >> 16) & 1)) & 0xffff0000)
want = 64 * float64(p) * math.Exp(peak) / denominator
}
got := float64(actual[row*width+channel])
if math.IsNaN(got) || math.Abs(got-want) > 2e-6*max(1.0, math.Abs(want)) {
t.Fatalf("first key %d, query %d, value key %d: got %.9g, want %.9g", firstKey, row, key, got, want)
}
}
}
}
})
}
func TestRelativePositionAttentionBF16ProbabilitySink(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
if !hasMetalTensorOps() {
t.Skip("requires Metal tensor ops")
}
const queries, keys, width = 16, 1024, 128
q := Zeros(DTypeFloat32, 1, 1, queries, width)
k := Zeros(DTypeBFloat16, 1, 1, keys, width)
v := BroadcastTo(FromValue(float32(1)).AsType(DTypeBFloat16), 1, 1, keys, width)
table := Zeros(DTypeBFloat16, 1, 1, queries, 1)
sink := BroadcastTo(FromValue(float32(92)).AsType(DTypeBFloat16), 1, 1, queries, 1)
out := RelativePositionAttentionBF16Probabilities(q, k, v, table, sink, 0, keys, 0.125)
if out == nil {
t.Fatal("expected the BF16 probability kernel")
}
// Every visible value is one. exp(92) overflows FP32, even though
// the sink-gated mean for 1024 visible keys is a normal FP32 value.
want := 1 / (1 + math.Exp(92-math.Log(keys)))
raw := Contiguous(out, false).Floats()
if got := float64(raw[len(raw)-1]); math.IsNaN(got) || math.Abs(got/want-1) > 2e-5 {
t.Fatalf("last query with large sink: got %.9g, want %.9g", got, want)
}
})
}
+253
View File
@@ -0,0 +1,253 @@
package mlx
import (
"fmt"
"math"
"testing"
"github.com/ollama/ollama/mlx/mlxthread/mlxthreadtest"
)
func TestRelativeAttentionMetalDevices(t *testing.T) {
for _, tc := range []struct {
name, arch string
parts int
prefill bool
}{
{"Apple M2 Pro", "applegpu_g14s", 0, true},
{"Apple M2 Ultra", "applegpu_g14d", 128, true},
{"Apple M3 Ultra", "applegpu_g15d", 128, true},
{"Apple M4 Pro", "applegpu_g16s", 64, true},
{"Apple M5 Pro", "applegpu_g17s", 64, true},
{"Apple M5 Pro", "applegpu_g17d", 0, false},
{"Apple M5 Max", "applegpu_g17s", 64, true},
{"Apple M5 Ultra", "applegpu_g17d", 128, true},
{"Apple M5 Ultra", "applegpu_g15d", 0, false},
{"Apple M1 Ultra", "applegpu_g13d", 0, false},
{"Apple M3 Max", "applegpu_g15s", 0, false},
{"Apple M5 Max", "unqualified_arch_s", 0, false},
} {
if got := relativeAttentionSplitParts(tc.name, tc.arch); got != tc.parts {
t.Errorf("%s/%s: split parts %d, want %d", tc.name, tc.arch, got, tc.parts)
}
if got := supportsRelativeAttentionPrefill(tc.name, tc.arch); got != tc.prefill {
t.Errorf("%s/%s: tiled prefill %t, want %t", tc.name, tc.arch, got, tc.prefill)
}
}
}
func TestRelativeAttentionCUDAFallback(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
if !CUDAIsAvailable() {
t.Skip("requires CUDA")
}
for _, width := range []int{1, 4, 8, 9, 64} {
q, k, v, table, sink := relativeAttentionInputs(width, 1041, 8, 2, 128, 1024)
for _, dtype := range []DType{DTypeFloat32, DTypeBFloat16} {
if out := RelativePositionAttention(q.AsType(dtype), k, v, table, sink, 1024, 0.125); out != nil {
t.Fatalf("CUDA attention with %d queries of dtype %v must use native SDPA", width, dtype)
}
}
}
})
}
func TestRelativeAttentionOrderedViews(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
if relativeAttentionParts() == 0 {
t.Skip("requires a qualified relative-attention device")
}
scale := float32(1 / math.Sqrt(128))
for _, width := range []int{1, 8} {
q, k, v, table, sink := relativeAttentionInputs(width, 1041, 24, 8, 128, 1024)
for _, window := range []int{0, 1024} {
got := RelativePositionAttention(q, k, v, table, sink, window, scale)
if got == nil {
t.Fatal("eligible route declined")
}
want := stockRelativeAttention(q, k, v, table, sink, window, scale)
if err := requireClose(fmt.Sprintf("width %d window %d", width, window), got, want, 0); err != nil {
t.Fatal(err)
}
query := q.AsType(DTypeFloat32)
got = RelativePositionAttention(query, k, v, table, sink, window, scale)
if got == nil || got.DType() != DTypeFloat32 {
t.Fatal("FP32 query requires an FP32 result")
}
want = stockRelativeAttention(query, k.AsType(DTypeFloat32), v.AsType(DTypeFloat32), table, sink, window, scale)
if err := requireExact("FP32 per-query attention", Contiguous(got, false), Contiguous(want, false)); err != nil {
t.Fatal(err)
}
}
if RelativePositionAttention(q, k, v, table.AsType(DTypeFloat32), sink, 0, scale) != nil {
t.Fatal("unexpected dispatch for FP32 bias")
}
if RelativePositionAttention(q, k, v, table, sink, 32, scale) != nil {
t.Fatal("unexpected dispatch with short local window")
}
short := func(x *Array) *Array { return x.Slice(Slice(), Slice(), Slice(0, 1023), Slice()) }
if RelativePositionAttention(q, short(k), short(v), table, sink, 0, scale) != nil {
t.Fatal("unexpected dispatch under split threshold")
}
if width == 1 {
// Verify that a rejected launch returns control to the model's
// stock attention path, including after the first pass succeeded.
for _, stage := range []**gpuKernel{&relativeAttentionPart, &relativeAttentionMerge} {
original := *stage
*stage = &gpuKernel{metalDisabled: true, cudaDisabled: true}
got := RelativePositionAttention(q, k, v, table, sink, 0, scale)
*stage = original
if got != nil {
t.Fatal("disabled GPU kernel produced output")
}
}
}
}
})
}
func TestRelativeAttentionHeadGroups(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
if relativeAttentionParts() == 0 {
t.Skip("requires a qualified GPU")
}
for _, tc := range []struct{ queries, heads, kvHeads, distances, window int }{
{1, 4, 4, 1, 0},
{3, 8, 2, 73, 1061},
{8, 6, 2, 1600, 1200},
} {
Scoped(func() {
q, k, v, table, sink := relativeAttentionInputs(tc.queries, 1243, tc.heads, tc.kvHeads, 128, tc.distances)
scale := float32(1 / math.Sqrt(128))
got := RelativePositionAttention(q, k, v, table, sink, tc.window, scale)
if got == nil {
t.Fatal("eligible head group declined")
}
want := stockRelativeAttention(q, k, v, table, sink, tc.window, scale)
same := got.View(DTypeUint16).Equal(want.View(DTypeUint16)).AsType(DTypeInt32).Reshape(-1).SumAxis(0, false).Int()
if int(same) != got.Size() {
t.Fatalf("heads %d/%d, queries %d, distances %d, window %d: %d differing BF16 elements", tc.heads, tc.kvHeads, tc.queries, tc.distances, tc.window, got.Size()-int(same))
}
})
}
})
}
func TestRelativeAttentionRejectsIncompatibleShapes(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
q, k, v, table, sink := relativeAttentionInputs(3, 1027, 6, 2, 128, 31)
shortHeads := func(x *Array, heads int) *Array { return x.Slice(Slice(), Slice(0, heads), Slice(), Slice()) }
emptyDistances := table.Slice(Slice(), Slice(), Slice(), Slice(0, 0))
for _, tc := range []struct {
name string
q, k, v, table, sink *Array
window int
}{
{"ungrouped heads", shortHeads(q, 5), k, v, shortHeads(table, 5), shortHeads(sink, 5), 0},
{"wrong value heads", q, k, shortHeads(v, 1), table, sink, 0},
{"wrong table heads", q, k, v, shortHeads(table, 3), sink, 0},
{"missing distances", q, k, v, emptyDistances, sink, 0},
{"negative window", q, k, v, table, sink, -1},
} {
if RelativePositionAttention(tc.q, tc.k, tc.v, tc.table, tc.sink, tc.window, 0.125) != nil {
t.Fatalf("%s unexpectedly launched", tc.name)
}
}
})
}
func stockRelativeAttention(q, k, v, table, sink *Array, window int, scale float32) *Array {
keys, rows := k.Dim(2), q.Dim(2)
rowSlice := func(x *Array, row int) *Array {
return x.Slice(Slice(), Slice(), Slice(row, row+1), Slice())
}
var out []*Array
for row := range rows {
end := keys - rows + row + 1
begin := 0
if window > 0 {
begin = max(0, end-window)
}
distance := Arange(float64(end-begin-1), -1, -1, DTypeInt32)
positions := Clip(distance, FromValue(0), FromValue(table.Dim(3)-1))
bias := rowSlice(table, row).TakeAlongAxis(positions.Reshape(1, 1, 1, end-begin), -1).AsType(DTypeFloat32)
bias = Where(positions.Equal(distance), bias, FromValue(float32(0)))
mask := bias.Subtract(rowSlice(sink, row).AsType(DTypeFloat32)).AsType(q.DType())
rowK := k.Slice(Slice(), Slice(), Slice(begin, end), Slice())
rowV := v.Slice(Slice(), Slice(), Slice(begin, end), Slice())
out = append(out, FastScaledDotProductAttentionWithSinks(rowSlice(q, row), rowK, rowV, scale,
FastSDPANoWindow, "", mask, Zeros(q.DType(), q.Dim(1))))
}
return Concatenate(out, 2)
}
func relativeAttentionInputs(queries, keys, heads, kvHeads, width, distances int) (q, k, v, table, sink *Array) {
// Leave unused capacity on both sides of each head's visible cache. The
// logical sequence length differs from the physical head stride.
history := func(stride, modulus int) *Array {
raw := patternArray(DTypeBFloat16, []int{1, kvHeads, keys + 19, width}, 0, 0.015625, stride, modulus)
return raw.Slice(Slice(), Slice(), Slice(5, 5+keys), Slice())
}
q = patternArray(DTypeBFloat16, []int{1, heads, queries, width}, 0, 0.03125, 7, 71)
table = patternArray(DTypeBFloat16, []int{1, heads, queries, distances}, 0, 0.0078125, 9, 127)
sink = patternArray(DTypeBFloat16, []int{1, heads, queries, 1}, 0, 0.1, 13, 67)
return q, history(17, 79), history(31, 113), table, sink
}
func BenchmarkRelativePositionAttentionEager(b *testing.B) {
benchmarkRelativeAttention(b, stockRelativeAttention)
}
func BenchmarkRelativePositionAttentionKernel(b *testing.B) {
benchmarkRelativeAttention(b, RelativePositionAttention)
}
func benchmarkRelativeAttention(b *testing.B, attend func(q, k, v, table, sink *Array, window int, scale float32) *Array) {
thread := mlxTestThread(b)
var supported bool
if err := thread.Do(b.Context(), func() error {
supported = relativeAttentionParts() != 0
return nil
}); err != nil {
b.Fatal(err)
}
if !supported {
b.Skip("requires a qualified relative-attention device")
}
// The eager arm evaluates native vector SDPA separately for each query.
// The checkpoint's full serving route is measured by the model benchmark.
for _, width := range []int{1, 8} {
for _, tc := range []struct {
name string
keys, window int
}{
{"local", 1024 + width - 1, 1024}, {"global", 3484, 0},
} {
b.Run(fmt.Sprintf("%s/width%d", tc.name, width), func(b *testing.B) {
err := thread.Do(b.Context(), func() error {
var launchErr error
Scoped(func() {
q, k, v, table, sink := relativeAttentionInputs(width, tc.keys, 24, 8, 128, 1024)
Eval(q, k, v, table, sink)
run := func() *Array { return attend(q, k, v, table, sink, tc.window, float32(1/math.Sqrt(128))) }
warm := run()
if warm == nil {
launchErr = fmt.Errorf("attention declined the %s inputs", tc.name)
return
}
Eval(warm)
b.ResetTimer()
for range b.N {
Scoped(func() { Eval(run()) })
}
b.StopTimer()
})
return launchErr
})
if err != nil {
b.Fatal(err)
}
})
}
}
}
+28 -10
View File
@@ -18,6 +18,7 @@ type RotatingKVCache struct {
step int
maxSize int
idx int
ordered bool
snapshots pendingSnapshots
@@ -33,26 +34,36 @@ func NewRotatingKVCache(maxSize int) *RotatingKVCache {
return &RotatingKVCache{maxSize: maxSize, step: 256, scope: mlx.NewScope()}
}
// NewOrderedWindowKVCache keeps the keys in sequence order for both single
// queries and blocks, so changing query width does not reorder the attention
// reduction over the window.
func NewOrderedWindowKVCache(maxSize int) *RotatingKVCache {
c := NewRotatingKVCache(maxSize)
c.ordered = true
return c
}
// Assumes B = 1; heterogeneous batches are not supported.
func (c *RotatingKVCache) Update(b *batch.Batch, keys, values *mlx.Array) *nn.KVHistory {
start := c.offset
c.captureStartBoundary(start)
batched := keys.Dim(2) > 1
linearized := keys.Dim(2) > 1 || c.ordered
var newK, newV *mlx.Array
if batched {
if linearized {
newK, newV = c.concat(keys, values)
} else {
newK, newV = c.update(keys, values)
}
c.captureLazySnapshots(start, c.offset, batched)
c.captureLazySnapshots(start, c.offset, linearized)
return nn.NewKVHistory(newK, newV, rotatingApplier{
b: b,
K: newK.Dim(2),
L: keys.Dim(2),
window: c.maxSize,
ringIdx: c.idx,
ordered: c.ordered,
dtype: keys.DType(),
})
}
@@ -180,6 +191,7 @@ func (c *RotatingKVCache) View(b *batch.Batch) *nn.KVHistory {
L: 1,
window: c.maxSize,
ringIdx: ringIdx,
ordered: c.ordered,
dtype: k.DType(),
})
}
@@ -229,12 +241,11 @@ func (c *RotatingKVCache) captureStartBoundary(start int) {
}
// captureLazySnapshots records a snapshot for each scheduled offset the write
// reached after the start boundary. A batched write (concat) linearizes the
// buffer into logical order, so each window is a contiguous slot slice captured
// lazily (lazyRotatingSnapshot). A single-token write (update) leaves the buffer
// ring-ordered or grown, breaking that slot math, so capture a clone (Snapshot)
// instead; update only ever reaches the end boundary (o == c.offset).
func (c *RotatingKVCache) captureLazySnapshots(start, end int, batched bool) {
// reached after the start boundary. A concat write leaves each window as a
// contiguous slice in logical order, so it can be captured lazily. A ring
// write can change that order and reaches only the end boundary, where it
// captures a clone instead.
func (c *RotatingKVCache) captureLazySnapshots(start, end int, linearized bool) {
if len(c.snapshots.offsets) == 0 {
return
}
@@ -243,7 +254,7 @@ func (c *RotatingKVCache) captureLazySnapshots(start, end int, batched bool) {
continue // captured pre-write by captureStartBoundary
}
c.snapshots.captureReached(o, func(int) Snapshot {
if batched {
if linearized {
return c.lazyRotatingSnapshot(o)
}
return c.Snapshot(o - min(o, c.maxSize))
@@ -495,6 +506,7 @@ type rotatingApplier struct {
L int
window int
ringIdx int
ordered bool
dtype mlx.DType
}
@@ -520,6 +532,12 @@ func (r rotatingApplier) ApplyMask(logical nn.AttentionMask) nn.AttentionMask {
return nn.AttentionMask{}
}
// Chronological keys already use the logical mask's column order.
// Leave its precision to the attention operation.
if r.ordered {
return logical
}
// Tensor-backed mask: materialize in logical order, then gather K cols
// into ring-slot order to align with the cache output.
arr := logical.AsArray(r.b, r.K, r.dtype)
+35
View File
@@ -1,10 +1,12 @@
package cache
import (
"math"
"testing"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
"github.com/ollama/ollama/mlxrunner/nn"
)
// singleTokenKV and multiTokenKV fabricate [B=1, H=1, L, D=2] key/value
@@ -337,3 +339,36 @@ func TestRotatingKVCacheOffsetTracking(t *testing.T) {
}
})
}
func TestRotatingCacheSingleQueryMaskPrecision(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
const bias = 1 + 1.0/256 // rounds to 1 at BF16
for _, tc := range []struct {
name string
newCache func(int) *RotatingKVCache
maskBias float64
}{
{"ring", NewRotatingKVCache, 1},
{"ordered", NewOrderedWindowKVCache, bias},
} {
mlx.Scoped(func() {
c := tc.newCache(8)
defer c.Free()
zero := mlx.Zeros(mlx.DTypeBFloat16, 1, 1, 1, 8)
one := mlx.AddScalar(zero, 1)
c.Update(newKVBatch(0, 1), zero, zero)
b := newKVBatch(1, 1)
updated := c.Update(b, zero, one)
mask := nn.ArrayMask(mlx.FromValues([]float32{0, bias}, 1, 1, 1, 2))
q := zero.AsType(mlx.DTypeFloat32)
want := 1 / (1 + math.Exp(-tc.maskBias))
for _, history := range []*nn.KVHistory{updated, c.View(b)} {
out := nn.ScaledDotProductAttention(b, q, 1, nn.WithKVHistory(history.AsType(mlx.DTypeFloat32)), nn.WithMask(mask))
if got := out.Floats()[0]; math.Abs(float64(got)-want) > 1e-5 {
t.Fatalf("%s cache: attention to second value = %g, want %g", tc.name, got, want)
}
}
})
}
})
}
+27 -2
View File
@@ -169,7 +169,24 @@ func requestGrammar(req llm.CompletionRequest) json.RawMessage {
schema = json.RawMessage(`{"type":"object"}`)
}
format := `{"type":"json_schema","json_schema":` + string(schema) + `}`
if len(req.ThinkingClose) > 0 {
if frames := req.FormatFrames; frames != nil {
var elements []string
if frames.ThinkingClose != "" {
excludes := make([]string, len(frames.ThinkingExcludes))
for i, marker := range frames.ThinkingExcludes {
excludes[i] = jsonString(marker)
}
body := `{"type":"any_text","excludes":[` + strings.Join(excludes, ",") + `]}`
close := grammarLiteral(frames.ThinkingClose)
if frames.ThinkingOpen == "" {
elements = append(elements, body, close)
} else {
thought := grammarSequence(grammarLiteral(frames.ThinkingOpen), body, close)
elements = append(elements, `{"type":"optional","content":`+thought+`}`)
}
}
format = grammarSequence(append(elements, grammarLiteral(frames.ContentOpen), format)...)
} else if len(req.ThinkingClose) > 0 {
excludes := make([]string, len(req.ThinkingClose))
closings := make([]string, len(req.ThinkingClose))
for i, closing := range req.ThinkingClose {
@@ -187,6 +204,14 @@ func requestGrammar(req llm.CompletionRequest) json.RawMessage {
return json.RawMessage(`{"type":"structural_tag","format":` + format + `}`)
}
func grammarLiteral(text string) string {
return `{"type":"const_string","value":` + jsonString(text) + `}`
}
func grammarSequence(elements ...string) string {
return `{"type":"sequence","elements":[` + strings.Join(elements, ",") + `]}`
}
// jsonString quotes s without escaping the HTML characters tags carry.
func jsonString(s string) string {
var b strings.Builder
@@ -436,7 +461,7 @@ func (c *Client) Load(ctx context.Context, systemInfo ml.SystemInfo, gpus []ml.D
}
// Spawn subprocess: ollama runner --model <name> --port <port>
cmd := exec.Command(exe, "runner", "--model", c.modelName, "--port", strconv.Itoa(port))
cmd := exec.Command(exe, "runner", "--model", c.modelName, "--port", strconv.Itoa(port), "--ctx-size", strconv.Itoa(c.softContextLength))
cmd.Env = os.Environ()
loadedLibraryPath, err := mlx.LoadedLibraryPath()
if err != nil {
+79
View File
@@ -2,9 +2,17 @@ package mlxrunner
import (
"encoding/json"
"errors"
"io/fs"
"path/filepath"
"testing"
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/llm"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/xgrammar"
"github.com/ollama/ollama/model/parsers"
"github.com/ollama/ollama/types/model"
)
func TestRequestGrammar(t *testing.T) {
@@ -47,3 +55,74 @@ func TestRequestGrammar(t *testing.T) {
})
}
}
func TestInkling2StructuredGrammarFrames(t *testing.T) {
const (
thoughtOpen int32 = iota
thoughtClose
contentOpen
plain
jsonBody
eos
)
pieces := []string{"<|message_model|><|content_thinking|>", "<|end_message|>", "<|message_model|><|content_text|>", "plain text", `{"x":"<|end_message|>"}`, "<eos>"}
path, err := mlx.LoadedLibraryPath()
if err != nil {
t.Skipf("native MLX payload is unavailable: %v", err)
}
compiler, err := xgrammar.New(filepath.Dir(path), pieces, len(pieces), []int32{eos}, 1, 0)
if errors.Is(err, fs.ErrNotExist) {
t.Skipf("native xgrammar payload is unavailable: %v", err)
}
if err != nil {
t.Fatal(err)
}
defer compiler.Close()
for _, tc := range []struct {
name string
prompt string
suppress bool
accepted []int32
rejected int32
}{
{prompt: pieces[thoughtClose], name: "plain text before a frame", rejected: plain},
{prompt: pieces[thoughtClose], name: "plain text after thinking", accepted: []int32{thoughtOpen, plain, thoughtClose}, rejected: plain},
{prompt: pieces[thoughtClose], name: "stop before an answer", accepted: []int32{thoughtOpen, plain, thoughtClose}, rejected: eos},
{prompt: pieces[thoughtClose], name: "plain text inside the answer frame", accepted: []int32{contentOpen}, rejected: plain},
{prompt: pieces[thoughtClose], name: "answer after thinking", accepted: []int32{thoughtOpen, plain, thoughtClose, contentOpen, jsonBody, eos}, rejected: -1},
{prompt: pieces[thoughtClose], name: "answer without thinking", accepted: []int32{contentOpen, jsonBody, eos}, rejected: -1},
{name: "continue prefilled thought", prompt: pieces[thoughtOpen], accepted: []int32{plain, thoughtClose, contentOpen, jsonBody, eos}, rejected: -1},
{name: "close prefilled thought even when hidden", prompt: pieces[thoughtOpen], suppress: true, accepted: []int32{plain, thoughtClose, contentOpen, jsonBody, eos}, rejected: -1},
{name: "early stop in prefilled thought", prompt: pieces[thoughtOpen], accepted: []int32{plain}, rejected: eos},
{name: "prefilled answer", prompt: pieces[contentOpen], accepted: []int32{jsonBody, eos}, rejected: -1},
{name: "disabled thought", prompt: pieces[thoughtClose], suppress: true, rejected: thoughtOpen},
{name: "unframed answer with thinking disabled", prompt: pieces[thoughtClose], suppress: true, rejected: jsonBody},
{name: "framed answer with thinking disabled", prompt: pieces[thoughtClose], suppress: true, accepted: []int32{contentOpen, jsonBody, eos}, rejected: -1},
} {
p := parsers.ParserForName("inkling2")
p.Init(nil, nil, &api.ThinkValue{Value: !tc.suppress})
framed := p.(interface {
StructuredOutputFrames(string) *model.StructuredOutputFrames
})
frames := framed.StructuredOutputFrames(tc.prompt)
format := requestGrammar(llm.CompletionRequest{Format: json.RawMessage(`"json"`), FormatFrames: frames, ThinkingClose: p.ThinkingClose()})
matcher, err := compiler.Compile(string(format))
if err != nil {
t.Fatal(err)
}
for _, token := range tc.accepted {
if err := matcher.Accept(token); err != nil {
t.Errorf("%s rejected token %q: %v", tc.name, pieces[token], err)
break
}
}
if tc.rejected >= 0 {
if err := matcher.Accept(tc.rejected); err == nil {
t.Errorf("%s accepted token %q", tc.name, pieces[tc.rejected])
}
} else if !matcher.Terminated() {
t.Errorf("%s did not reach the stop token", tc.name)
}
matcher.Close()
}
}
+20 -11
View File
@@ -13,8 +13,7 @@ import (
// dflashPendingFlushTokens bounds the held feature rows between flushes.
const dflashPendingFlushTokens = 256
// dflash2Depth is a DFlash2 session's fixed draft length. The depth controller's
// shallower picks lose more accepted tokens than they save in verify time.
// DFlash2's learned selector uses seven proposals per round.
const dflash2Depth = 7
// dflashDrafter drafts with a block-diffusion draft model (DFlash): one
@@ -160,12 +159,15 @@ func (d *dflashDraftSession) propose(current *mlx.Array, maxTokens int) *draftCa
}
d.commitBlock()
// Draft only the requested rows, not the full trained block: exact for
// causal layers, while a bidirectional draft's proposal distribution
// changes; verification uses the actual proposal probabilities.
// Changing the mask count changes a bidirectional draft's predictions.
// An adaptive selector consumes a prefix after the full draft forward.
rows := n
if spec.depth.block {
rows = blockSize - 1
}
var candidates *draftCandidates
mlx.ScopedArrays(func() []*mlx.Array {
masks := make([]int32, n)
masks := make([]int32, rows)
for i := range masks {
masks[i] = d.drafter.maskToken
}
@@ -180,30 +182,37 @@ func (d *dflashDraftSession) propose(current *mlx.Array, maxTokens int) *draftCa
hidden, _ := spec.draft.Forward(&batch.Batch{
InputIDs: block,
SeqOffsets: []int32{int32(offset)},
SeqQueryLens: []int32{int32(n + 1)},
SeqQueryLens: []int32{int32(rows + 1)},
Hidden: features,
Layout: d.layout,
}, cache.Layers(spec.targets), cache.Layers(spec.draftKV))
candidates = d.selectBlock(hidden, current, n)
candidates = d.selectBlock(hidden, current, rows, n)
return candidates.Arrays()
})
return candidates
}
// selectBlock samples the proposal from a draft forward's block rows.
func (d *dflashDraftSession) selectBlock(hidden, current *mlx.Array, n int) *draftCandidates {
func (d *dflashDraftSession) selectBlock(hidden, current *mlx.Array, rows, n int) *draftCandidates {
spec := d.drafter.spec
r := spec.r
// Row i predicts the token at its own position; the anchor row is unused.
hidden = hidden.Slice(mlx.Slice(), mlx.Slice(1, n+1), mlx.Slice())
hidden = hidden.Slice(mlx.Slice(), mlx.Slice(1, rows+1), mlx.Slice())
logits := spec.draft.Unembed(hidden)
if selector, ok := spec.draft.(model.BlockSelector); ok {
if n < rows {
hidden = hidden.Slice(mlx.Slice(), mlx.Slice(0, n), mlx.Slice())
logits = logits.Slice(mlx.Slice(), mlx.Slice(0, n), mlx.Slice())
}
tokens, ids, probs := selector.Select(hidden, logits, current, func(ids, scores *mlx.Array) (*mlx.Array, *mlx.Array) {
tokens, dist := r.Sampler.SampleCandidates(spec.slotID, ids, scores)
return tokens, dist.Probs
})
return &draftCandidates{tokens: tokens, dist: sample.Distribution{IDs: ids.Squeeze(0), Probs: probs.Squeeze(0)}}
if ids != nil {
ids = ids.Squeeze(0)
}
return &draftCandidates{tokens: tokens, dist: sample.Distribution{IDs: ids, Probs: probs.Squeeze(0)}}
}
// Independent DFlash rows see the committed history, without the other
// rows of the block contributing to penalties.
+139 -26
View File
@@ -372,6 +372,120 @@ func (d *selectedBlockDraft) Select(_ *mlx.Array, logits *mlx.Array, _ *mlx.Arra
return tokens.Reshape(1, n), ids.Reshape(1, n, 2), probs.Reshape(1, n, 2)
}
type vocabularyBlockSelector struct{ *selectedBlockDraft }
func (*vocabularyBlockSelector) Select(_ *mlx.Array, logits *mlx.Array, _ *mlx.Array, choose func(*mlx.Array, *mlx.Array) (*mlx.Array, *mlx.Array)) (tokens, ids, probs *mlx.Array) {
rows, vocab := logits.Dim(1), logits.Dim(2)
ids = mlx.BroadcastTo(mlx.Arange(0, float64(vocab), 1, mlx.DTypeInt32), int32(rows), int32(vocab))
tokens, probs = choose(ids, logits.Squeeze(0))
return tokens.ExpandDims(0), nil, probs.ExpandDims(0)
}
func TestBlockSelectorVocabularyOrderWithTopKTarget(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
r, draft, session, _ := newBlockTestSession(t, nil, 3)
defer session.close()
r.spec.draft = &vocabularyBlockSelector{&selectedBlockDraft{draft}}
r.Sampler.Remove(pipelineSlot)
r.Sampler.Add(pipelineSlot, sampler.Options{Temperature: 1, TopK: 2, UseSeed: true, Seed: 42}, nil)
// After the unused anchor row, the first proposal is uniform and the
// second assigns more than half its mass to token 3.
logits := mlx.FromValues([]float32{
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 2,
}, 1, 3, 4)
q := session.selectBlock(logits, mlx.FromValues([]int32{0}, 1), 2, 2).dist
if q.IDs != nil || !slices.Equal(q.Probs.Dims(), []int{2, 4}) {
t.Fatalf("proposal IDs %v, shape %v, want dense [2 4]", q.IDs, q.Probs.Dims())
}
// Target row 0 splits its mass equally between tokens 0 and 2.
// Row 1 splits between 1 and 3, so only token 1 has residual mass.
p := r.Sampler.Distribution(pipelineSlot, mlx.FromValues([]float32{1, 0, 1, 0, 0, 1, 0, 1}, 2, 4), nil)
residual := p.ResidualAgainst(q)
query := mlx.FromValues([]int32{2, 0, 1, 1, 3, 2}, 2, 3)
if got, want := residual.ProbsForIDs(query).Floats(), []float32{.5, .5, 0, 1, 0, 0}; !slices.Equal(got, want) {
t.Fatalf("residual probabilities = %v, want %v", got, want)
}
})
}
type observeProposalRows struct {
*selectedBlockDraft
unembed, hidden, logits int
}
func (d *observeProposalRows) Unembed(h *mlx.Array) *mlx.Array {
d.unembed = h.Dim(1)
return d.selectedBlockDraft.Unembed(h)
}
func (d *observeProposalRows) Select(hidden, logits, anchor *mlx.Array, choose func(*mlx.Array, *mlx.Array) (*mlx.Array, *mlx.Array)) (*mlx.Array, *mlx.Array, *mlx.Array) {
d.hidden = hidden.Dim(1)
d.logits = logits.Dim(1)
return d.selectedBlockDraft.Select(hidden, logits, anchor, choose)
}
type adaptiveBlockSelector struct{ *observeProposalRows }
func (*adaptiveBlockSelector) AdaptiveDraftDepth() bool { return true }
func TestBlockProposalIgnoresPaddedHidden(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
r, draft, session, _ := newBlockTestSession(t, nil, 8)
defer session.close()
hidden := oneHotLogits([]int32{1, 2, 3, 4, 5})
current := mlx.FromValues([]int32{1}, 1)
if got := session.selectBlock(hidden, current, 2, 2).tokens.Ints(); !slices.Equal(got, []int32{2, 3}) {
t.Fatalf("padded block proposed %v, want [2 3]", got)
}
selector := &observeProposalRows{selectedBlockDraft: &selectedBlockDraft{draft}}
r.spec.draft = selector
got := session.selectBlock(hidden, current, 2, 2)
if got.tokens.Dim(1) != 2 || selector.unembed != 2 {
t.Fatalf("padded selector projected %d rows and proposed %d, want 2 each", selector.unembed, got.tokens.Dim(1))
}
})
}
func TestProposalPrefixAfterFullVocabularyProjection(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
for _, adaptive := range []bool{false, true} {
for n := range 8 {
mlx.Scoped(func() {
r, fake, _, caches := newBlockTestSession(t, map[int32]int32{0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 1}, 8)
observer := &observeProposalRows{selectedBlockDraft: &selectedBlockDraft{fake}}
var selector model.BlockSelector = observer
rows := n
if adaptive {
selector = &adaptiveBlockSelector{observer}
rows = 7
}
r.spec = newSpeculation(r, pipelineSlot, selector, caches[:1], caches[1:])
session := r.spec.drafter.open(nil)
defer session.close()
session.committed(mlx.FromValues([]int32{1}, 1, 1), oneHotLogits([]int32{1}), 0, nil)
got := session.propose(mlx.FromValues([]int32{1}, 1), n)
if n == 0 {
if got != nil || len(fake.calls) != 0 {
t.Fatalf("zero budget produced a proposal or a forward")
}
return
}
mlx.Eval(got.Arrays()...)
if len(fake.calls) != 1 || len(fake.calls[0].block) != rows+1 || observer.unembed != rows {
t.Fatalf("adaptive=%v, %d proposals: draft calls %v, projected %d rows, want %d", adaptive, n, fake.calls, observer.unembed, rows)
}
if observer.hidden != n || observer.logits != n || !slices.Equal(got.tokens.Dims(), []int{1, n}) || got.dist.Probs.Dim(0) != n || got.dist.IDs.Dim(0) != n {
t.Fatalf("%d proposals: selector rows %d/%d, tokens %v, probabilities %v, IDs %v", n, observer.hidden, observer.logits, got.tokens.Dims(), got.dist.Probs.Dims(), got.dist.IDs.Dims())
}
})
}
}
})
}
func TestBlockSelectorProposalAndRejection(t *testing.T) {
for _, tc := range []struct {
slot int
@@ -436,33 +550,32 @@ func TestBlockSelectorProposalAndRejection(t *testing.T) {
// round accepts, without training the depth controller; a plain block draft
// still takes the controller's depth.
func TestSelectorDraftKeepsFixedDepth(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
r, draft, session, _ := newBlockTestSession(t, map[int32]int32{1: 2}, 8)
session.close()
req := request{Tokens: []int32{1, 2, 3}}
draft := &fakeBlockDraft{blockSize: 8}
r := &Runner{}
r.spec = newSpeculation(r, pipelineSlot, draft, nil, nil)
req := request{Tokens: []int32{1, 2, 3}}
plain := r.spec.open(req, nil)
if plain.fixedDepth || plain.limit != r.spec.depth.scheduled {
t.Fatalf("block draft: fixedDepth %v limit %d, want the controller's %d", plain.fixedDepth, plain.limit, r.spec.depth.scheduled)
}
plain.close()
plain := r.spec.open(req, nil)
if plain.fixedDepth || plain.limit != r.spec.depth.scheduled {
t.Fatalf("block draft: fixedDepth %v limit %d, want the controller's %d", plain.fixedDepth, plain.limit, r.spec.depth.scheduled)
}
plain.close()
r.spec.draft = &selectedBlockDraft{draft}
s := r.spec.open(req, nil)
defer s.close()
if !s.fixedDepth || s.limit != dflash2Depth {
t.Fatalf("selector draft: fixedDepth %v limit %d, want %d", s.fixedDepth, s.limit, dflash2Depth)
r.spec.draft = &selectedBlockDraft{draft}
s := r.spec.open(req, nil)
defer s.close()
if !s.fixedDepth || s.limit != dflash2Depth {
t.Fatalf("selector draft: fixedDepth %v limit %d, want %d", s.fixedDepth, s.limit, dflash2Depth)
}
scheduled := r.spec.depth.scheduled
for _, accepted := range []int{0, 3, dflash2Depth} {
s.beginRound()
s.endRound(dflash2Depth, accepted, dflash2Depth)
if s.limit != dflash2Depth {
t.Fatalf("limit %d after accepting %d, want %d", s.limit, accepted, dflash2Depth)
}
scheduled := r.spec.depth.scheduled
for _, accepted := range []int{0, 3, dflash2Depth} {
s.beginRound()
s.endRound(dflash2Depth, accepted, dflash2Depth)
if s.limit != dflash2Depth {
t.Fatalf("limit %d after accepting %d, want %d", s.limit, accepted, dflash2Depth)
}
}
if slices.ContainsFunc(r.spec.depth.acc.seen, func(n int) bool { return n != 0 }) || r.spec.depth.scheduled != scheduled {
t.Fatalf("fixed-depth rounds trained the depth controller: seen %v, scheduled %d -> %d", r.spec.depth.acc.seen, scheduled, r.spec.depth.scheduled)
}
})
}
if slices.ContainsFunc(r.spec.depth.acc.seen, func(n int) bool { return n != 0 }) || r.spec.depth.scheduled != scheduled {
t.Fatalf("fixed-depth rounds trained the depth controller: seen %v, scheduled %d -> %d", r.spec.depth.acc.seen, scheduled, r.spec.depth.scheduled)
}
}
+36 -26
View File
@@ -7,6 +7,7 @@ import (
"hash/fnv"
"log/slog"
"regexp"
"slices"
"strconv"
"github.com/ollama/ollama/llm"
@@ -99,9 +100,13 @@ func (m *requestMedia) extendChunk(pos, n, limit int) int {
if m == nil {
return n
}
return extendMediaChunk(m.items, pos, n, limit)
}
func extendMediaChunk(items []mediaItem, pos, n, limit int) int {
end := pos + n
for i := range m.items {
item := &m.items[i]
for i := range items {
item := &items[i]
if !item.atomic() {
continue
}
@@ -175,35 +180,40 @@ func (m *requestMedia) close() {
// them in a single PrepareMedia call, and validates the authored items
// before keying cache identity on them.
func (r *Runner) expandMedia(mm model.MediaModel, prompt string, media []llm.MediaData) (*model.PreparedRequest, []mediaItem, error) {
matches := imgTagPattern.FindAllStringSubmatch(prompt, -1)
parts := imgTagPattern.Split(prompt, -1)
referenced := make([]bool, len(media))
// A renderer can identify the genuine attachments even when text contains
// identical tags. Raw prompts use every indexed tag as before.
positioned := slices.ContainsFunc(media, func(m llm.MediaData) bool { return len(m.TagOffsets) > 0 })
references := make([]int, len(media))
var segments []model.Segment
for i, part := range parts {
segments = append(segments, model.Segment{Tokens: r.Tokenizer.Encode(part, i == 0 && r.Tokenizer.AddBOS())})
if i >= len(matches) {
continue
}
id, _ := strconv.Atoi(matches[i][1])
idx := -1
for j := range media {
if media[j].ID == id {
idx = j
break
start := 0
for _, match := range imgTagPattern.FindAllStringSubmatchIndex(prompt, -1) {
id, _ := strconv.Atoi(prompt[match[2]:match[3]])
idx := slices.IndexFunc(media, func(m llm.MediaData) bool { return m.ID == id })
if positioned {
if idx < 0 {
continue
}
}
if idx < 0 {
if _, ok := slices.BinarySearch(media[idx].TagOffsets, match[0]); !ok {
continue
}
} else if idx < 0 {
return nil, nil, fmt.Errorf("invalid image index: %d", id)
}
referenced[idx] = true
segments = append(segments, model.Segment{Kind: string(media[idx].Kind), Data: media[idx].Data})
}
for j := range media {
if !referenced[j] {
slog.Warn("media not referenced by prompt", "id", media[j].ID)
tokens := r.Tokenizer.Encode(prompt[start:match[0]], len(segments) == 0 && r.Tokenizer.AddBOS())
segments = append(segments, model.Segment{Tokens: tokens}, model.Segment{Kind: string(media[idx].Kind), Data: media[idx].Data})
references[idx]++
start = match[1]
}
tokens := r.Tokenizer.Encode(prompt[start:], len(segments) == 0 && r.Tokenizer.AddBOS())
segments = append(segments, model.Segment{Tokens: tokens})
for j, m := range media {
if positioned && references[j] != len(m.TagOffsets) {
return nil, nil, fmt.Errorf("invalid prompt offsets for image %d", m.ID)
}
if references[j] == 0 {
slog.Warn("media not referenced by prompt", "id", m.ID)
}
}
@@ -12,6 +12,7 @@ import (
_ "github.com/ollama/ollama/mlxrunner/model/gemma4embedding"
_ "github.com/ollama/ollama/mlxrunner/model/glimmer"
_ "github.com/ollama/ollama/mlxrunner/model/glm4_moe_lite"
_ "github.com/ollama/ollama/mlxrunner/model/inkling2"
_ "github.com/ollama/ollama/mlxrunner/model/kev"
_ "github.com/ollama/ollama/mlxrunner/model/laguna"
_ "github.com/ollama/ollama/mlxrunner/model/laya"
+210
View File
@@ -0,0 +1,210 @@
package inkling2
import (
"math"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/nn"
)
type selfAttention struct {
Query, Key, Value, Output *nn.Linear
Relative, Gate, Sink *nn.Linear
PositionProjection *mlx.Array
QueryScale, RelativeScale *mlx.Array
KeyConv, ValueConv shortConv
headDim, heads, kvHeads int
window int
rmsEpsilon float32
qkClip, relativeClip float32
logFloor, logAlpha float32
}
func (a selfAttention) forward(qInput, kInput, vInput *mlx.Array, b *batch.Batch, kvCache, keyCache, valueCache cache.Layer) *mlx.Array {
rows, tokens := qInput.Dim(0), qInput.Dim(1)
q := projectTarget(a.Query, qInput).Reshape(rows, tokens, a.heads, a.headDim)
k := a.KeyConv.forward(projectTarget(a.Key, kInput), kInput, b, keyCache).Reshape(rows, tokens, a.kvHeads, a.headDim)
v := a.ValueConv.forward(projectTarget(a.Value, vInput), vInput, b, valueCache).Reshape(rows, tokens, a.kvHeads, a.headDim)
r := projectTarget(a.Relative, qInput).Reshape(rows, tokens, a.heads, a.PositionProjection.Dim(0))
var tau *mlx.Array
if a.window == 0 && a.logFloor > 0 && a.logAlpha != 0 {
offsets := mlx.FromValues(b.SeqOffsets, rows, 1)
indices := mlx.Arange(1, float64(tokens+1), 1, mlx.DTypeInt32)
length := offsets.Add(indices).AsType(mlx.DTypeFloat32)
ratio := mlx.Maximum(mlx.DivScalar(length, a.logFloor), mlx.FromValue(float32(1)))
tau = mlx.AddScalar(mlx.MulScalar(mlx.Log(ratio), a.logAlpha), 1).Reshape(rows, tokens, 1, 1)
}
q = clipL2(q, a.QueryScale, tau, a.qkClip).Transpose(0, 2, 1, 3)
k = clipL2(k, nil, nil, a.qkClip).Transpose(0, 2, 1, 3)
v = mlx.RMSNormFn(v, nil, a.rmsEpsilon).Transpose(0, 2, 1, 3)
r = clipL2(r, a.RelativeScale, tau, a.relativeClip)
table := r.Matmul(a.PositionProjection).Transpose(0, 2, 1, 3)
sink := projectTarget(a.Sink, qInput).Transpose(0, 2, 1).ExpandDims(-1)
var history *nn.KVHistory
if kvCache != nil {
history = kvCache.(cache.Attention).Update(b, k, v)
}
scale := float32(1 / math.Sqrt(float64(a.headDim)))
attended := relativeSDPA(b, q, k, v, table, sink, history, a.window, scale)
attended = attended.Transpose(0, 2, 1, 3).Reshape(rows, tokens, a.heads*a.headDim)
gate := projectTarget(a.Gate, qInput)
if mlx.MetalIsAvailable() && gate.DType() == qInput.DType() {
return projectTarget(a.Output, compiledAttentionGate(attended, gate))
}
return projectTarget(a.Output, gateAttention(attended, gate, qInput.DType()))
}
func gateAttention(value, gate *mlx.Array, dtype mlx.DType) *mlx.Array {
return mlx.Mul(value.AsType(mlx.DTypeFloat32), gate.AsType(mlx.DTypeFloat32).Sigmoid()).AsType(dtype)
}
var compiledAttentionGate = mlx.Compile2("InklingAttentionGate", func(value, gate *mlx.Array) *mlx.Array {
return gateAttention(value, gate, gate.DType())
}, mlx.Shapeless())
func clipL2(x, weight, temperature *mlx.Array, threshold float32) *mlx.Array {
inputs := []*mlx.Array{x, mlx.FromValue(threshold)}
if weight != nil {
inputs = append(inputs, weight)
}
if temperature != nil {
if weight == nil {
inputs = append(inputs, mlx.FromValue(float32(1)))
}
inputs = append(inputs, temperature)
}
if mlx.MetalIsAvailable() {
return compiledClipL2(inputs...)[0]
}
return clipL2Tensors(inputs...)[0]
}
var compiledClipL2 = mlx.Compile("InklingClipL2", clipL2Tensors, mlx.Shapeless())
func clipL2Tensors(inputs ...*mlx.Array) []*mlx.Array {
x, threshold := inputs[0], inputs[1]
values := x.AsType(mlx.DTypeFloat32)
if len(inputs) > 2 {
values = mlx.Mul(values, inputs[2].AsType(mlx.DTypeFloat32))
}
norm := mlx.Sum(mlx.Mul(values, values), -1, true).Sqrt()
factor := mlx.Div(threshold, mlx.AddScalar(norm, residualEpsilon))
values = mlx.Mul(values, mlx.Minimum(factor, mlx.FromValue(float32(1))))
if len(inputs) > 3 {
values = mlx.Mul(values, inputs[3])
}
return []*mlx.Array{values.AsType(x.DType())}
}
func relativeSDPA(b *batch.Batch, q, k, v, table, sink *mlx.Array, history *nn.KVHistory, window int, scale float32) *mlx.Array {
if history != nil && history.Rows() != nil {
output := make([]*mlx.Array, q.Dim(0))
for i, row := range history.Rows() {
selectRow := func(x *mlx.Array) *mlx.Array {
return x.Slice(mlx.Slice(i, i+1), mlx.Slice(), mlx.Slice(), mlx.Slice())
}
output[i] = relativeSDPA(b.Row(i), selectRow(q), nil, nil, selectRow(table), selectRow(sink), row, window, scale)
}
return mlx.Concatenate(output, 0)
}
// Attention stays in FP32 through its output gate. Preserve the stored
// BF16 keys and values, and widen only the views used by this forward.
q = q.AsType(mlx.DTypeFloat32)
if history == nil {
k, v = k.AsType(mlx.DTypeFloat32), v.AsType(mlx.DTypeFloat32)
return relativeWindowSDPA(b, q, table, sink, k.Dim(2), window, scale, nn.WithKV(k, v, b.SeqQueryLens))
}
queries, keys := q.Dim(2), history.K().Dim(2)
if len(b.SeqQueryLens) == 1 && window > 0 && int(b.SeqOffsets[0])+queries >= keys {
// Ordered cache writes include the physical query width. Remove matching
// Q and K tails so live rows use the same positions and kernel as serial.
if live := int(b.SeqQueryLens[0]); live > 0 && live < queries {
pad := queries - live
trim := func(x *mlx.Array) *mlx.Array {
return x.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(0, x.Dim(2)-pad), mlx.Slice())
}
row := &batch.Batch{InputIDs: b.InputIDs.Slice(mlx.Slice(), mlx.Slice(0, live)), SeqOffsets: b.SeqOffsets, SeqQueryLens: b.SeqQueryLens}
h := nn.NewKVHistory(trim(history.K()), trim(history.V()), nil)
out := relativeCachedSDPA(row, trim(q), trim(table), trim(sink), h, window, window, scale)
return mlx.PadConstant(out, []int{2}, []int{0}, []int{pad})
}
}
return relativeCachedSDPA(b, q, table, sink, history, window, 0, scale)
}
// A cache history normally supplies its own sliding mask. A trimmed chronological
// view has no storage applier, so its fallback must use the model's window.
func relativeCachedSDPA(b *batch.Batch, q, table, sink *mlx.Array, history *nn.KVHistory, window, maskWindow int, scale float32) *mlx.Array {
queries, keys := q.Dim(2), history.K().Dim(2)
// An ordered prefill history can contain padding beyond its last query.
if len(b.SeqQueryLens) == 1 && b.SeqQueryLens[0] == int32(queries) &&
(queries <= shortTargetRows || int(b.SeqOffsets[0])+queries >= keys) {
// The local attention variant rounds the unnormalized probabilities before P times V.
if queries > shortTargetRows && window == 1024 && table.Dim(3) == 1024 && q.Dim(1) == 24 && history.K().Dim(1) == 8 {
firstKey := int(b.SeqOffsets[0]) + queries - keys
if out := mlx.RelativePositionAttentionBF16Probabilities(q, history.K(), history.V(), table, sink, firstKey, window, scale); out != nil {
return out
}
}
if out := mlx.RelativePositionAttention(q, history.K(), history.V(), table, sink, window, scale); out != nil {
return out
}
}
history = history.AsType(mlx.DTypeFloat32)
if queries == 1 || queries > shortTargetRows {
return relativeWindowSDPA(b, q, table, sink, keys, maskWindow, scale, nn.WithKVHistory(history))
}
// Short blocks share their projections and cache write. Give each query
// the same ordered window and kernel extent it sees in single-token decode.
output := make([]*mlx.Array, queries)
for i := range queries {
row := &batch.Batch{
InputIDs: b.InputIDs.Slice(mlx.Slice(), mlx.Slice(i, i+1)),
SeqOffsets: []int32{b.SeqOffsets[0] + int32(i)},
SeqQueryLens: []int32{min(max(b.SeqQueryLens[0]-int32(i), 0), 1)},
}
selectQuery := func(x *mlx.Array) *mlx.Array {
return x.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(i, i+1), mlx.Slice())
}
end := keys - queries + i + 1
start := 0
if window > 0 {
start = max(0, end-window)
}
k := history.K().Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(start, end), mlx.Slice())
v := history.V().Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(start, end), mlx.Slice())
output[i] = relativeWindowSDPA(row, selectQuery(q), selectQuery(table), selectQuery(sink),
end-start, 0, scale, nn.WithKV(k, v, nil))
}
return mlx.Concatenate(output, 2)
}
func relativeWindowSDPA(b *batch.Batch, q, table, sink *mlx.Array, keys, window int, scale float32, kv nn.SDPAOption) *mlx.Array {
shifted := mlx.RelativePositionDecodeBias(table, sink, keys)
if shifted == nil {
shifted = relativeBiasGraph(table, sink, keys)
}
mask := nn.DeviceCausalMask().Intersect(nn.ArrayMask(shifted))
if window > 0 {
mask = mask.Intersect(nn.SlidingWindowMaskDevice(b, keys, window, q.DType()))
}
return nn.ScaledDotProductAttention(b, q, scale, kv, nn.WithMask(mask), nn.WithSinks(mlx.Zeros(q.DType(), q.Dim(1))))
}
func relativeBiasGraph(table, sink *mlx.Array, keys int) *mlx.Array {
queries := table.Dim(2)
shiftedQueries := mlx.Arange(float64(keys-queries), float64(keys), 1, mlx.DTypeInt32).Reshape(1, 1, queries, 1)
keyPositions := mlx.Arange(0, float64(keys), 1, mlx.DTypeInt32)
distance := shiftedQueries.Subtract(keyPositions)
index := mlx.Clip(distance, mlx.FromValue(0), mlx.FromValue(table.Dim(-1)-1))
// The relative bias is already in the same score domain as the sink.
bias := table.TakeAlongAxis(index, -1).AsType(mlx.DTypeFloat32)
bias = mlx.Where(index.Equal(distance), bias, mlx.FromValue(float32(0)))
// Shifting the real logits by the token's sink value lets the kernel use
// a single zero-logit sink per head with the same softmax denominator.
return bias.Subtract(sink.AsType(mlx.DTypeFloat32))
}
+245
View File
@@ -0,0 +1,245 @@
package inkling2
import (
"math"
"math/rand/v2"
"slices"
"testing"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/nn"
)
func TestAttentionRoundsAfterGate(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
mlx.Scoped(func() {
bf16 := func(n float32) *mlx.Array {
return mlx.FromValues([]float32{n}, 1, 1, 1, 1).AsType(mlx.DTypeBFloat16)
}
const width = 128
q := mlx.Zeros(mlx.DTypeBFloat16, 1, 1, 1, width)
for _, keys := range []int{1, 1024} {
b := &batch.Batch{
InputIDs: mlx.Zeros(mlx.DTypeInt32, 1, 1), SeqOffsets: []int32{int32(keys - 1)}, SeqQueryLens: []int32{1},
}
k := mlx.Zeros(mlx.DTypeBFloat16, 1, 1, keys, width)
values := make([]float32, keys*width)
for i := (keys - 1) * width; i < len(values); i++ {
values[i] = 8
}
v := mlx.FromValues(values, 1, 1, keys, width).AsType(mlx.DTypeBFloat16)
store := cache.NewKVCache()
histories := []*nn.KVHistory{store.Update(b, k, v)}
if keys == 1 {
histories = append(histories, nil)
}
for _, tc := range []struct {
name string
bias, gate, want float32
}{
{"attention output", 0, 2, 6.21875},
{"relative bias and sink", 1.0 / 128, 0, 3.53125},
} {
// Only the last key contributes at BF16 output precision, giving
// 8 * sigmoid(bias + 2) * sigmoid(gate), rounded after the gate.
bias := make([]float32, keys)
bias[0] = tc.bias
for i := 1; i < keys; i++ {
bias[i] = -96
}
table := mlx.FromValues(bias, 1, 1, 1, keys).AsType(mlx.DTypeBFloat16)
for _, history := range histories {
attended := relativeSDPA(b, q, k, v, table, bf16(-2), history, 0, 1)
out := gateAttention(attended, bf16(tc.gate), mlx.DTypeBFloat16)
if got := out.AsType(mlx.DTypeFloat32).Floats()[0]; got != tc.want {
t.Errorf("%s (%d keys, cached %t): gated output = %v, want %v", tc.name, keys, history != nil, got, tc.want)
}
}
}
store.Free()
}
})
})
}
func TestRelativeAttentionWithTokenDependentSinks(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
mlx.Scoped(func() {
b := &batch.Batch{
InputIDs: mlx.Zeros(mlx.DTypeInt32, 1, 2),
SeqOffsets: []int32{0},
SeqQueryLens: []int32{2},
}
qk := mlx.Zeros(mlx.DTypeFloat32, 1, 1, 2, 1)
values := mlx.FromValues([]float32{4, 10}, 1, 1, 2, 1)
relative := mlx.FromValues([]float32{math.Ln2, math.Ln2}, 1, 1, 2, 1)
sink := mlx.FromValues([]float32{0, float32(math.Log(3))}, 1, 1, 2, 1)
// The dot product scale does not affect the relative bias or sinks.
got := relativeSDPA(b, qk, qk, values, relative, sink, nil, 0, 0.5).Floats()
want := []float64{8.0 / 3, 4}
if len(got) != len(want) {
t.Fatalf("attention produced %d values, want %d", len(got), len(want))
}
for i := range want {
if !(math.Abs(float64(got[i])-want[i]) <= 1e-5) {
t.Errorf("query %d: attention = %g, want %g", i, got[i], want[i])
}
}
})
})
}
func TestRelativeAttentionMatchesSerialAfterCacheRestore(t *testing.T) {
for _, tc := range []struct {
name string
window int
}{{"full", 0}, {"sliding", 1024}} {
t.Run(tc.name, func(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
mlx.Scoped(func() {
const (
prefix = 1037
block = 8
accepted = 3
)
rng := rand.New(rand.NewPCG(5, 19))
values := func(heads, tokens, width int) *mlx.Array {
data := make([]float32, heads*tokens*width)
for i := range data {
data[i] = float32(rng.NormFloat64())
}
return mlx.FromValues(data, 1, heads, tokens, width).AsType(mlx.DTypeBFloat16)
}
q := values(8, block, 64)
k, v := values(2, prefix+block, 64), values(2, prefix+block, 64)
relative, sink := values(8, block, 16), values(8, block, 1)
querySlice := func(x *mlx.Array, start, end int) *mlx.Array {
return x.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(start, end), mlx.Slice())
}
batchOf := func(start, length int) *batch.Batch {
return &batch.Batch{
InputIDs: mlx.Zeros(mlx.DTypeInt32, 1, length), SeqOffsets: []int32{int32(start)}, SeqQueryLens: []int32{int32(length)},
}
}
prefill := func() cache.Cache {
var c cache.Cache
if tc.window > 0 {
c = cache.NewOrderedWindowKVCache(tc.window)
} else {
c = cache.NewKVCache()
}
c.(cache.Attention).Update(batchOf(0, prefix), querySlice(k, 0, prefix), querySlice(v, 0, prefix))
return c
}
decode := func(c cache.Cache, start, end int) *mlx.Array {
b := batchOf(prefix+start, end-start)
history := c.(cache.Attention).Update(b, querySlice(k, prefix+start, prefix+end), querySlice(v, prefix+start, prefix+end))
return relativeSDPA(b, querySlice(q, start, end), nil, nil, querySlice(relative, start, end), querySlice(sink, start, end), history, tc.window, 0.125)
}
serial := prefill()
defer serial.Free()
want := make([]*mlx.Array, block)
for i := range block {
want[i] = decode(serial, i, i+1)
}
blockCache := prefill()
defer blockCache.Free()
blockCache.PrepareSnapshots([]int{prefix + accepted})
logicalValues := func(x *mlx.Array) []float32 {
return mlx.Contiguous(x.AsType(mlx.DTypeFloat32), false).Floats()
}
got := logicalValues(decode(blockCache, 0, block))
if !slices.Equal(got, logicalValues(mlx.Concatenate(want, 2))) {
t.Error("block attention differs from serial decode")
}
snapshots := blockCache.TakeSnapshots()
if len(snapshots) != 1 || snapshots[0] == nil {
t.Fatal("speculative block did not capture its rollback boundary")
}
defer snapshots[0].Close()
if !blockCache.Restore(snapshots[0], prefix+accepted) {
t.Fatal("cache could not restore the accepted prefix")
}
got = logicalValues(decode(blockCache, accepted, block))
if !slices.Equal(got, logicalValues(mlx.Concatenate(want[accepted:], 2))) {
t.Error("attention after rollback differs from serial decode")
}
})
})
})
}
}
func TestRelativeAttentionKeepsDistancesAfterWindowRestore(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
mlx.Scoped(func() {
const window = 4
run := func(c *cache.RotatingKVCache, start, length int) []float32 {
b := &batch.Batch{
InputIDs: mlx.Zeros(mlx.DTypeInt32, 1, length),
SeqOffsets: []int32{int32(start)},
SeqQueryLens: []int32{int32(length)},
}
q := mlx.Zeros(mlx.DTypeFloat32, 1, 1, length, 1)
values := mlx.Arange(float64(start+1), float64(start+length+1), 1, mlx.DTypeFloat32).
Reshape(1, 1, length, 1)
row := mlx.FromValues([]float32{0, -0.3, -0.8, -1.7}, 1, 1, 1, window)
table := mlx.BroadcastTo(row, 1, 1, int32(length), window)
sinks := mlx.Zeros(mlx.DTypeFloat32, 1, 1, length, 1)
history := c.Update(b, q, values)
return relativeSDPA(b, q, nil, nil, table, sinks, history, window, 1).Floats()
}
cold := cache.NewRotatingKVCache(window)
defer cold.Free()
cold.PrepareSnapshots([]int{6})
prefill := run(cold, 0, 8)
snapshots := cold.TakeSnapshots()
if len(snapshots) != 1 || snapshots[0] == nil {
t.Fatal("expected a snapshot in the oversize prefill")
}
defer snapshots[0].Close()
want := append(prefill[6:], run(cold, 8, 1)...)
warm := cache.NewRotatingKVCache(window)
defer warm.Free()
if !warm.Restore(snapshots[0], 6) {
t.Fatal("failed to restore the prefill snapshot")
}
got := append(run(warm, 6, 2), run(warm, 8, 1)...)
if len(want) != 3 || len(got) != len(want) {
t.Fatalf("expected three attention values, got %d restored and %d cold", len(got), len(want))
}
for i := range want {
if !(math.Abs(float64(got[i]-want[i])) <= 1e-5) {
t.Errorf("position %d: restored attention = %g, cold attention = %g", 6+i, got[i], want[i])
}
}
})
})
}
func TestRelativePositionDecodeBias(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
mlx.Scoped(func() {
for _, extent := range []int{16, 128, 1024} {
// Select one query from a query-major table, as in speculative verification.
table := mlx.Arange(0, float64(3*24*extent), 1, mlx.DTypeFloat32).AsType(mlx.DTypeBFloat16).Reshape(1, 3, 24, extent).Transpose(0, 2, 1, 3).Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(1, 2), mlx.Slice())
sink := mlx.Arange(0, 3*24, 1, mlx.DTypeFloat32).AsType(mlx.DTypeBFloat16).Reshape(1, 3, 24, 1).Transpose(0, 2, 1, 3).Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(1, 2), mlx.Slice())
for _, keys := range []int{1, 17, 127, 1023} {
got := mlx.RelativePositionDecodeBias(table, sink, keys)
if got == nil {
t.Skip("requires a qualified relative-attention Metal device")
}
want := relativeBiasGraph(table, sink, keys)
if !slices.Equal(got.Floats(), want.Floats()) {
t.Fatalf("extent=%d keys=%d: decode shader differs from graph", extent, keys)
}
}
}
})
})
}
+134
View File
@@ -0,0 +1,134 @@
package inkling2
import "fmt"
// Bound allocations driven by checkpoint metadata before weights are loaded.
const maxLayerCount = 1024
type textConfig struct {
NumLayers int `json:"num_hidden_layers"`
LocalLayers []int `json:"local_layer_ids"`
ResidualBlockSize int `json:"n_layers_per_attn_res_block"`
NormalizeResidualValues bool `json:"attn_res_normalize_values"`
Loop *loopConfig `json:"loop_config"`
HiddenSize int `json:"hidden_size"`
VocabSize int `json:"vocab_size"`
UnpaddedVocab int `json:"unpadded_vocab_size"`
Context int `json:"model_max_length"`
HeadDim int `json:"head_dim"`
Heads int `json:"num_attention_heads"`
KVHeads int `json:"num_key_value_heads"`
LocalHeadDim int `json:"swa_head_dim"`
LocalHeads int `json:"swa_num_attention_heads"`
LocalKVHeads int `json:"swa_num_key_value_heads"`
RelativeDim int `json:"d_rel"`
RelativeRange int `json:"rel_extent"`
Window int `json:"sliding_window_size"`
ConvTaps int `json:"sconv_kernel_size"`
Experts int `json:"n_routed_experts"`
SharedExperts int `json:"n_shared_experts"`
TopK int `json:"num_experts_per_tok"`
ExpertWidth int `json:"intermediate_size"`
NormEps float32 `json:"rms_norm_eps"`
QKClip float32 `json:"qk_l2_clip_threshold"`
RelativeClip float32 `json:"rel_l2_clip_threshold"`
LogFloor float32 `json:"log_scaling_n_floor"`
LogAlpha float32 `json:"log_scaling_alpha"`
RouteScale float32 `json:"route_scale"`
GateCap float32 `json:"mlp_gate_softcap"`
UpCap float32 `json:"mlp_up_softcap"`
LogitCap float32 `json:"final_logit_softcapping"`
GateBias bool `json:"use_gate_bias"`
ValueNorm bool `json:"use_value_norm_no_gamma"`
QueryBias bool `json:"q_bias"`
OutputBias bool `json:"o_bias"`
}
func (c textConfig) validate() error {
if c.HiddenSize <= 0 || c.UnpaddedVocab <= 0 || c.UnpaddedVocab > c.VocabSize || c.Context <= 0 {
return fmt.Errorf("invalid Inkling2 hidden size, vocabulary or context")
}
if c.HeadDim <= 0 || c.KVHeads <= 0 || c.Heads <= 0 || c.Heads%c.KVHeads != 0 ||
c.LocalHeadDim <= 0 || c.LocalKVHeads <= 0 || c.LocalHeads <= 0 || c.LocalHeads%c.LocalKVHeads != 0 {
return fmt.Errorf("invalid Inkling2 attention dimensions")
}
if c.ConvTaps <= 0 || c.RelativeDim <= 0 || c.RelativeRange <= 0 || c.Window <= 0 || c.NormEps <= 0 || c.QKClip <= 0 || c.RelativeClip <= 0 {
return fmt.Errorf("invalid Inkling2 convolution, attention or normalization settings")
}
if c.TopK <= 0 || c.TopK > c.Experts || c.ExpertWidth <= 0 || c.RouteScale <= 0 || c.GateCap < 0 || c.UpCap < 0 || c.LogitCap < 0 {
return fmt.Errorf("invalid Inkling2 expert routing or softcap settings")
}
if c.SharedExperts != 0 || c.QueryBias || c.OutputBias || !c.ValueNorm {
return fmt.Errorf("unsupported Inkling2 expert, attention bias or value normalization configuration")
}
return nil
}
type loopConfig struct {
Variable bool `json:"is_varloop"`
Start int `json:"core_start"`
End int `json:"core_end"`
Passes int `json:"num_passes"`
GateRank int `json:"gate_rank"`
}
// A layer visit owns its own attention and convolution cache slots. Several
// visits can use the same physical layer's weights.
type layerVisit struct {
layer int
pass int
local bool
}
// executionPlan orders visits as the decoder executes them. Indices in the
// plan also identify the target activations consumed by the draft model.
func (c textConfig) executionPlan() ([]layerVisit, error) {
if c.NumLayers <= 0 || c.NumLayers > maxLayerCount || c.ResidualBlockSize <= 0 || c.ResidualBlockSize > c.NumLayers {
return nil, fmt.Errorf("invalid Inkling2 decoder depth %d or residual block size %d", c.NumLayers, c.ResidualBlockSize)
}
end := c.NumLayers
visits := c.NumLayers
if loop := c.Loop; loop != nil {
if loop.Variable {
return nil, fmt.Errorf("variable Inkling2 loops are unsupported")
}
if loop.Start < 0 || loop.End > c.NumLayers || loop.Start >= loop.End || loop.Passes < 2 || loop.GateRank <= 0 {
return nil, fmt.Errorf("invalid Inkling2 loop: layers [%d,%d), passes %d, gate rank %d", loop.Start, loop.End, loop.Passes, loop.GateRank)
}
if loop.Start%c.ResidualBlockSize != 0 || loop.End%c.ResidualBlockSize != 0 || !c.NormalizeResidualValues {
return nil, fmt.Errorf("Inkling2 looping requires aligned residual blocks and normalized residual values")
}
width := loop.End - loop.Start
if loop.Passes-1 > (maxLayerCount-c.NumLayers)/width {
return nil, fmt.Errorf("Inkling2 loop with %d passes exceeds the %d-visit limit", loop.Passes, maxLayerCount)
}
visits += (loop.Passes - 1) * width
end = loop.End
}
local := make([]bool, c.NumLayers)
for _, layer := range c.LocalLayers {
if layer < 0 || layer >= c.NumLayers || local[layer] {
return nil, fmt.Errorf("invalid or duplicate Inkling2 local attention layer %d", layer)
}
local[layer] = true
}
plan := make([]layerVisit, 0, visits)
for layer := range end {
plan = append(plan, layerVisit{layer: layer, local: local[layer]})
}
if loop := c.Loop; loop != nil {
for pass := 1; pass < loop.Passes; pass++ {
for layer := loop.Start; layer < loop.End; layer++ {
plan = append(plan, layerVisit{layer: layer, pass: pass, local: local[layer]})
}
}
}
for layer := end; layer < c.NumLayers; layer++ {
plan = append(plan, layerVisit{layer: layer, local: local[layer]})
}
return plan, nil
}
+83
View File
@@ -0,0 +1,83 @@
package inkling2
import "testing"
func TestLoopedExecutionPlan(t *testing.T) {
config := textConfig{
NumLayers: 24,
ResidualBlockSize: 6,
NormalizeResidualValues: true,
Loop: &loopConfig{Start: 6, End: 18, Passes: 3, GateRank: 64},
}
for i := range config.NumLayers {
if i%6 != 5 {
config.LocalLayers = append(config.LocalLayers, i)
}
}
plan, err := config.executionPlan()
if err != nil {
t.Fatal(err)
}
if len(plan) != 48 {
t.Fatalf("decoder visits = %d, want 48", len(plan))
}
for _, span := range []struct{ firstVisit, firstLayer, length, pass int }{
{0, 0, 18, 0},
{18, 6, 12, 1},
{30, 6, 12, 2},
{42, 18, 6, 0},
} {
for offset := range span.length {
index := span.firstVisit + offset
layer := span.firstLayer + offset
want := layerVisit{layer: layer, pass: span.pass, local: layer%6 != 5}
if got := plan[index]; got != want {
t.Errorf("decoder visit %d = %+v, want %+v", index, got, want)
}
}
}
}
func TestExecutionPlanRejectsLoopInsideResidualBlock(t *testing.T) {
config := textConfig{
NumLayers: 24,
ResidualBlockSize: 6,
NormalizeResidualValues: true,
Loop: &loopConfig{Start: 7, End: 18, Passes: 3, GateRank: 64},
}
if _, err := config.executionPlan(); err == nil {
t.Fatal("expected an error for a loop starting inside a residual block")
}
}
func TestExecutionPlanRejectsVariableLoop(t *testing.T) {
cfg := textConfig{
NumLayers: 4, ResidualBlockSize: 2, NormalizeResidualValues: true,
Loop: &loopConfig{Start: 0, End: 2, Passes: 3, GateRank: 1, Variable: true},
}
if _, err := cfg.executionPlan(); err == nil {
t.Fatal("accepted variable looping with a fixed execution plan")
}
}
func TestExecutionPlanBoundsExpandedDepth(t *testing.T) {
config := textConfig{
NumLayers: 2,
ResidualBlockSize: 1,
NormalizeResidualValues: true,
Loop: &loopConfig{Start: 0, End: 2, Passes: maxLayerCount / 2, GateRank: 1},
}
plan, err := config.executionPlan()
if err != nil || len(plan) != maxLayerCount {
t.Fatalf("plan at visit limit: %d visits, error %v", len(plan), err)
}
config.Loop.Passes++
if _, err := config.executionPlan(); err == nil {
t.Fatal("accepted a loop exceeding the visit limit")
}
config.Loop = nil
config.NumLayers = maxLayerCount + 1
if _, err := config.executionPlan(); err == nil {
t.Fatal("accepted a decoder exceeding the layer limit")
}
}
@@ -0,0 +1,43 @@
package inkling2
import (
"testing"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
"github.com/ollama/ollama/mlxrunner/nn"
)
func TestMetalLoopControllerMatchesSeparateProjections(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
if !mlx.SupportsPackedController() {
t.Skip("requires qualified Metal controller")
}
mlx.Scoped(func() {
const width, rank = 2304, 64
values := func(x, y int, scale float32, dtype mlx.DType) *mlx.Array {
a := mlx.Arange(0, float64(x*y), 1, mlx.DTypeFloat32)
return mlx.MulScalar(mlx.Sin(mlx.MulScalar(a, scale)), .07).AsType(dtype).Reshape(x, y)
}
down := nn.NewLinear(values(rank, 2*width, .018, mlx.DTypeBFloat16), nil)
gain := nn.NewLinear(values(width, rank, .021, mlx.DTypeFloat32), nil)
forget := nn.NewLinear(values(width, rank, -.029, mlx.DTypeFloat32), nil)
ordinary := messageGate{Down: down, Gain: gain, Forget: forget}
packed := messageGate{Down: down, GainForget: nn.NewLinear(mlx.Concatenate([]*mlx.Array{gain.Weight, forget.Weight}, 0), nil)}
for _, sh := range [][2]int{{1, 4}, {2, 8}, {4, 8}, {1, 257}} {
mlx.Scoped(func() {
b, n := sh[0], sh[1]
x := values(b*n, width, .0111, mlx.DTypeFloat32).Reshape(b, n, width)
m := values(b*n, width, .0379, mlx.DTypeFloat32).Reshape(b, n, width)
want := ordinary.apply(x, m)
got := packed.apply(x, m)
equal := got.View(mlx.DTypeUint32).Equal(want.View(mlx.DTypeUint32)).AsType(mlx.DTypeInt32).Reshape(-1).SumAxis(0, false).Int()
t.Logf("B=%d T=%d exact=%d/%d", b, n, equal, got.Size())
if int(equal) != got.Size() {
t.Fatalf("B=%d T=%d: %d differing FP32 values", b, n, got.Size()-int(equal))
}
})
}
})
})
}
+87
View File
@@ -0,0 +1,87 @@
package inkling2
import (
"math"
"slices"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/nn"
)
type shortConv struct {
Weight *mlx.Array // [taps, channels]
Dynamic *nn.Linear
heads int
}
func (s shortConv) forward(x, conditioning *mlx.Array, b *batch.Batch, layerCache cache.Layer) *mlx.Array {
rows, tokens, channels := x.Dim(0), x.Dim(1), x.Dim(2)
taps := s.Weight.Dim(0)
tail := taps - 1
var history *nn.RecurrentHistory
var options []nn.RecurrentOption
if layerCache == nil {
options = append(options, nn.WithRecurrentState(mlx.Zeros(x.DType(), rows, tail, channels), nil))
} else {
recurrent := layerCache.(cache.Recurrent)
history = recurrent.Get(b, x.DType())
options = append(options, nn.WithRecurrentHistory(history), nn.WithSnapshotSplits(recurrent.SnapshotSplits(tokens)))
}
window, states := nn.CausalConvWindow(b, x, tail, options...)
if history != nil {
delta := slices.Repeat([]*mlx.Array{history.DeltaState()}, len(states))
layerCache.(cache.Recurrent).Put(b, states, delta)
}
inputs := []*mlx.Array{window, x, s.Weight}
if s.Dynamic != nil {
perToken := projectTarget(s.Dynamic, conditioning).AsType(mlx.DTypeFloat32).Reshape(rows, tokens, s.heads, taps)
inputs = append(inputs, perToken)
}
if mlx.MetalIsAvailable() {
return compiledConvTaps(inputs...)[0]
}
return convTaps(inputs...)[0]
}
// DepthwiseConvSiLU uses fixed taps and a SiLU output. Inkling can add per-token
// tap weights and needs a scaled residual, so fuse those operations in one graph.
var compiledConvTaps = mlx.Compile("InklingConvTaps", convTaps)
func convTaps(inputs ...*mlx.Array) []*mlx.Array {
window, x, weight := inputs[0], inputs[1], inputs[2]
rows, tokens, channels := x.Dim(0), x.Dim(1), x.Dim(2)
taps := weight.Dim(0)
tail, terms := taps-1, taps+1
var perToken *mlx.Array
var heads int
if len(inputs) == 4 {
perToken = inputs[3]
heads = perToken.Dim(2)
terms += taps
}
var sum *mlx.Array
for tap := range taps {
start := tap
coef := weight.Slice(mlx.Slice(tap, tap+1), mlx.Slice()).AsType(mlx.DTypeFloat32)
if perToken != nil {
// Projected convolutions index weights by lag. The fixed
// convolutions store their weights in chronological order.
start = tail - tap
shift := perToken.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(), mlx.Slice(tap, tap+1))
coef = mlx.Add(coef.Reshape(1, 1, heads, channels/heads), shift).Reshape(rows, tokens, channels)
}
lagged := window.Slice(mlx.Slice(), mlx.Slice(start, start+tokens), mlx.Slice()).AsType(mlx.DTypeFloat32)
product := mlx.Mul(lagged, coef)
if sum == nil {
sum = product
} else {
sum = mlx.Add(sum, product)
}
}
sum = mlx.Add(sum, x.AsType(mlx.DTypeFloat32))
return []*mlx.Array{mlx.MulScalar(sum, float32(1/math.Sqrt(float64(terms)))).AsType(x.DType())}
}
+83
View File
@@ -0,0 +1,83 @@
package inkling2
import (
"math"
"math/rand/v2"
"slices"
"testing"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/nn"
)
func TestDynamicShortConvolutionRetainsHistoryAcrossDecode(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
mlx.Scoped(func() {
convolution := shortConv{
Weight: mlx.FromValues([]float32{1, 2}, 2, 1),
Dynamic: nn.NewLinear(mlx.FromValues([]float32{0, 1}, 2, 1), nil),
heads: 1,
}
state := cache.NewRecurrentCache(1, 1, 1, 1, 1)
defer state.Free()
input := mlx.FromValues([]float32{1, 2, 3}, 1, 3, 1)
prefill := &batch.Batch{InputIDs: mlx.Zeros(mlx.DTypeInt32, 1, 3), SeqQueryLens: []int32{3}}
full := convolution.forward(input, input, prefill, nil).Floats()
for index, want := range []float64{2, 8, 16} {
chunk := &batch.Batch{InputIDs: mlx.Zeros(mlx.DTypeInt32, 1, 1), SeqOffsets: []int32{int32(index)}, SeqQueryLens: []int32{1}}
token := input.Slice(mlx.Slice(), mlx.Slice(index, index+1), mlx.Slice())
got := convolution.forward(token, token, chunk, state).Floats()[0]
if math.Abs(float64(got)-want/math.Sqrt(5)) > 1e-6 || got != full[index] {
t.Errorf("token %d: decoded %g, prefill %g, want %g", index, got, full[index], want/math.Sqrt(5))
}
}
})
})
}
func TestMetalConvTapsMatchEager(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
if !mlx.MetalIsAvailable() {
t.Skip("requires Metal")
}
mlx.EnableCompile()
random := rand.New(rand.NewPCG(71, 219))
makeValues := func(shape ...int) *mlx.Array {
count := 1
for _, size := range shape {
count *= size
}
values := make([]float32, count)
for i := range values {
values[i] = float32(random.NormFloat64())
}
return mlx.FromValues(values, shape...).AsType(mlx.DTypeBFloat16)
}
const rows, channels, taps, heads = 2, 128, 4, 8
for _, length := range []int{1, 8, 17, 64} {
mlx.Scoped(func() {
x := makeValues(rows, length, channels)
previous := makeValues(rows, taps-1, channels)
window := mlx.Concatenate([]*mlx.Array{previous, x}, 1)
for _, dynamic := range []bool{false, true} {
var inputs []*mlx.Array
if dynamic {
weight := makeValues(taps, channels)
shift := makeValues(rows, length, heads, taps).AsType(mlx.DTypeFloat32)
inputs = []*mlx.Array{window, x, weight, shift}
} else {
inputs = []*mlx.Array{window, x, makeValues(channels, taps).Transpose(1, 0)}
}
eager := convTaps(inputs...)[0].AsType(mlx.DTypeFloat32).Floats()
compiled := compiledConvTaps(inputs...)[0].AsType(mlx.DTypeFloat32).Floats()
if !slices.Equal(compiled, eager) {
t.Errorf("length %d dynamic %t: compiled convolution changed the BF16 result", length, dynamic)
}
}
})
}
})
}
+322
View File
@@ -0,0 +1,322 @@
package inkling2
import (
"fmt"
"math"
"slices"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
"github.com/ollama/ollama/mlxrunner/nn"
)
const draftArchitecture = "Inkling2ForConditionalGenerationMTP"
func init() { model.RegisterDraft(draftArchitecture, newDraft) }
type draftConfig struct {
Width int `json:"hidden_size"`
NumLayers int `json:"num_hidden_layers"`
Heads int `json:"num_attention_heads"`
KVHeads int `json:"num_key_value_heads"`
HeadDim int `json:"head_dim"`
FFWidth int `json:"intermediate_size"`
LocalLayers []int `json:"local_layer_ids"`
Window int `json:"sliding_window_size"`
RopeTheta float32 `json:"rope_theta"`
Epsilon float32 `json:"rms_norm_eps"`
Block int `json:"block_size"`
StateWidth int `json:"markov_rank"`
HeadType string `json:"markov_head_type"`
Taps []int `json:"target_layer_ids"`
QueryBias bool `json:"q_bias"`
OutputBias bool `json:"o_bias"`
}
type draft struct {
config draftConfig
target *targetModel
prefix string
Layers []draftLayer
Fuse *mlx.Array
Mask *mlx.Array
Norm *mlx.Array
RecurrentNorm *mlx.Array
Previous *nn.Embedding
Recurrent *nn.Linear
Folded *nn.Linear
}
type draftLayer struct {
local bool
InputNorm *mlx.Array
FfNorm *mlx.Array
ContextNorm *mlx.Array
QueryNorm *mlx.Array
KeyNorm *mlx.Array
ContextKeyNorm *mlx.Array
Query *nn.Linear
Key, Value *nn.Linear
ContextKey *nn.Linear
ContextValue *nn.Linear
AttentionOutput *nn.Linear
Gate, Up, Down *nn.Linear
}
var _ model.BlockSelector = (*draft)(nil)
func newDraft(root *model.Root, target model.Model) (model.DraftModel, error) {
m, ok := target.(*targetModel)
if !ok {
return nil, fmt.Errorf("Inkling2 MTP requires an Inkling2 target, got %T", target)
}
path := root.Draft.Config
if path == "" {
path = "draft/config.json"
}
var cfg draftConfig
if err := root.Manifest.ReadConfigJSON(path, &cfg); err != nil {
return nil, fmt.Errorf("load Inkling2 MTP config: %w", err)
}
const maxDraftBlockSize = 1024
if cfg.NumLayers > maxLayerCount || cfg.Block > maxDraftBlockSize {
return nil, fmt.Errorf("Inkling2 MTP layer count %d or block size %d exceeds its limit", cfg.NumLayers, cfg.Block)
}
if cfg.Width != m.config.HiddenSize || cfg.NumLayers <= 0 || cfg.Heads <= 0 || cfg.KVHeads <= 0 ||
cfg.Heads%cfg.KVHeads != 0 || cfg.HeadDim <= 0 || cfg.HeadDim%2 != 0 || cfg.FFWidth <= 0 ||
cfg.Window <= 0 || cfg.RopeTheta <= 0 || cfg.Epsilon <= 0 || cfg.Block < 2 ||
cfg.StateWidth <= 0 || cfg.HeadType != "rnn_hidden" || cfg.QueryBias || cfg.OutputBias {
return nil, fmt.Errorf("unsupported Inkling2 MTP configuration")
}
if len(cfg.Taps) == 0 || !slices.IsSorted(cfg.Taps) || cfg.Taps[0] < 0 ||
cfg.Taps[len(cfg.Taps)-1] != len(m.plan) || len(slices.Compact(slices.Clone(cfg.Taps))) != len(cfg.Taps) {
return nil, fmt.Errorf("invalid Inkling2 MTP target visits %v", cfg.Taps)
}
for _, layer := range cfg.LocalLayers {
if layer < 0 || layer >= cfg.NumLayers {
return nil, fmt.Errorf("invalid Inkling2 MTP local layer %d", layer)
}
}
prefix := root.Draft.TensorPrefix
if prefix == "" {
prefix = "draft."
}
return &draft{config: cfg, target: m, prefix: prefix}, nil
}
func (d *draft) LoadWeights(tensors map[string]*mlx.Array) error {
c := d.config
r := weightReader{tensors: tensors}
d.Fuse = r.tensor(d.prefix+"fuse_weight", c.NumLayers+1, len(c.Taps))
d.Mask = r.tensor(d.prefix+"mask_embed", c.Width)
d.Norm = r.tensor(d.prefix+"norm.weight", c.Width)
p := d.prefix + "markov_head."
d.RecurrentNorm = r.tensor(p+"dflare_norm.weight", c.Width)
d.Previous = nn.NewEmbedding(r.tensor(p+"markov_w1.weight", d.target.config.VocabSize, c.StateWidth))
d.Recurrent = r.projection(p+"rnn_proj", 3*c.StateWidth, 2*(c.StateWidth+c.Width), true)
latent := r.projection(p+"hidden_out", c.Width, c.StateWidth, true)
d.Layers = make([]draftLayer, c.NumLayers)
for i := range d.Layers {
layer := fmt.Sprintf("%slayers.%d.", d.prefix, i)
a := layer + "self_attn."
kvWidth := c.KVHeads * c.HeadDim
d.Layers[i] = draftLayer{
local: slices.Contains(c.LocalLayers, i),
InputNorm: r.tensor(layer+"input_layernorm.weight", c.Width),
FfNorm: r.tensor(layer+"post_attention_layernorm.weight", c.Width),
ContextNorm: r.tensor(layer+"dflare_norm.weight", c.Width),
QueryNorm: r.tensor(a+"q_norm.weight", c.HeadDim),
KeyNorm: r.tensor(a+"k_norm.weight", c.HeadDim),
ContextKeyNorm: r.tensor(a+"k_norm_ctx.weight", c.HeadDim),
Query: r.linear(a+"q_proj.weight", c.Heads*c.HeadDim, c.Width),
Key: r.linear(a+"k_proj.weight", kvWidth, c.Width),
Value: r.linear(a+"v_proj.weight", kvWidth, c.Width),
ContextKey: r.linear(a+"k_proj_ctx.weight", kvWidth, c.Width),
ContextValue: r.linear(a+"v_proj_ctx.weight", kvWidth, c.Width),
AttentionOutput: r.linear(a+"o_proj.weight", c.Width, c.Heads*c.HeadDim),
Gate: r.linear(layer+"mlp.gate_proj.weight", c.FFWidth, c.Width),
Up: r.linear(layer+"mlp.up_proj.weight", c.FFWidth, c.Width),
Down: r.linear(layer+"mlp.down_proj.weight", c.Width, c.FFWidth),
}
}
if r.err != nil {
return r.err
}
d.Fuse = mlx.SoftmaxAxis(d.Fuse.AsType(mlx.DTypeFloat32), -1, true).AsType(mlx.DTypeBFloat16)
// Fold the latent projection into the shared target head once. Both source
// matrices retain their original BF16 values, with FP32 accumulation.
output := d.target.Output.Weight.AsType(mlx.DTypeFloat32)
foldWeight := output.Matmul(latent.Weight.AsType(mlx.DTypeFloat32)).AsType(mlx.DTypeBFloat16)
foldBias := output.Matmul(latent.Bias.AsType(mlx.DTypeFloat32)).AsType(mlx.DTypeBFloat16)
d.Folded = nn.NewLinear(foldWeight, foldBias)
d.target.draftTaps = slices.Clone(c.Taps)
return nil
}
func (d *draft) BlockParams() (int, int32) {
// The learned mask embeddings do not use a token ID from the vocabulary.
return d.config.Block, 0
}
func (d *draft) AdaptiveDraftDepth() bool {
// The published head was trained with an anchor and seven masks.
return d.config.Block == 8
}
func (d *draft) NewCaches() []cache.Cache {
states := make([]cache.Cache, 0, len(d.Layers)+1)
for _, layer := range d.Layers {
if layer.local {
// The rotating cache reserves one slot for the incoming block.
// Keep the whole preceding window available to its first row.
states = append(states, cache.NewRotatingKVCache(d.config.Window+1))
} else {
states = append(states, cache.NewKVCache())
}
}
// The proposal head conditions on the most recent committed target row.
return append(states, cache.NewRotatingKVCache(1))
}
func (d *draft) mix(features *mlx.Array, row int, norm *mlx.Array) *mlx.Array {
taps := len(d.config.Taps)
weights := d.Fuse.Slice(mlx.Slice(row, row+1), mlx.Slice()).Reshape(1, 1, taps, 1).AsType(mlx.DTypeFloat32)
x := features.Reshape(features.Dim(0), features.Dim(1), taps, d.config.Width).AsType(mlx.DTypeFloat32)
return modelRMS(mlx.Sum(mlx.Mul(x, weights), 2, false), norm, d.config.Epsilon)
}
func (d *draft) Forward(b *batch.Batch, _, states []cache.Layer) (hidden, auxHidden *mlx.Array) {
c := d.config
featureCache := states[len(d.Layers)].(cache.Attention)
var contextLength int
if b.Hidden != nil {
contextLength = b.Hidden.Dim(1)
f := d.mix(b.Hidden, len(d.Layers), d.RecurrentNorm).ExpandDims(1)
featureCache.Update(b, f, f)
}
var x *mlx.Array
var block *batch.Batch
contextStart := mlx.FromValues(b.SeqOffsets, len(b.SeqOffsets))
if b.InputIDs != nil {
batchSize, length := b.InputIDs.Dim(0), b.InputIDs.Dim(1)
anchor := d.target.embedTokens(b.InputIDs.Slice(mlx.Slice(), mlx.Slice(0, 1)))
masks := mlx.BroadcastTo(d.Mask, int32(batchSize), int32(length-1), int32(c.Width))
x = anchor.Concatenate(1, masks)
offsets := make([]int32, len(b.SeqOffsets))
for i, pos := range b.SeqOffsets {
offsets[i] = pos + int32(contextLength)
}
block = &batch.Batch{InputIDs: b.InputIDs, SeqOffsets: offsets, SeqQueryLens: b.SeqQueryLens}
}
for i, layer := range d.Layers {
var k, v *mlx.Array
if b.Hidden != nil {
ctx := d.mix(b.Hidden, i, layer.ContextNorm)
k, v = layer.kv(ctx, layer.ContextKey, layer.ContextValue, layer.ContextKeyNorm, contextStart, c)
}
store := states[i].(cache.Attention)
if x == nil {
if k != nil {
store.Update(b, k, v)
}
continue
}
x = layer.forward(x, k, v, block, store, c)
}
if x == nil {
return nil, nil
}
x = modelRMS(x, d.Norm, c.Epsilon)
f := featureCache.View(block).V().Squeeze(1)
f = mlx.BroadcastTo(f, int32(x.Dim(0)), int32(x.Dim(1)), int32(c.Width))
// Keep the committed conditioning with each row so proposal selection can
// run without storing mutable request state on the model.
return x.Concatenate(-1, f), nil
}
func (l draftLayer) kv(x *mlx.Array, key, value *nn.Linear, keyNorm, offsets *mlx.Array, c draftConfig) (k, v *mlx.Array) {
b, n := x.Dim(0), x.Dim(1)
k = modelRMS(key.Forward(x).Reshape(b, n, c.KVHeads, c.HeadDim), keyNorm, c.Epsilon).Transpose(0, 2, 1, 3)
v = value.Forward(x).Reshape(b, n, c.KVHeads, c.HeadDim).Transpose(0, 2, 1, 3)
return mlx.RoPEWithBase(k, c.HeadDim, false, c.RopeTheta, 1, offsets), v
}
func (l draftLayer) forward(x, contextKey, contextValue *mlx.Array, b *batch.Batch, store cache.Attention, c draftConfig) *mlx.Array {
rows, n := x.Dim(0), x.Dim(1)
offsets := mlx.FromValues(b.SeqOffsets, rows)
xNorm := modelRMS(x, l.InputNorm, c.Epsilon)
q := modelRMS(l.Query.Forward(xNorm).Reshape(rows, n, c.Heads, c.HeadDim), l.QueryNorm, c.Epsilon).Transpose(0, 2, 1, 3)
q = mlx.RoPEWithBase(q, c.HeadDim, false, c.RopeTheta, 1, offsets)
k, v := l.kv(xNorm, l.Key, l.Value, l.KeyNorm, offsets, c)
if contextKey != nil {
k = contextKey.Concatenate(2, k)
v = contextValue.Concatenate(2, v)
}
history := store.Update(b, k, v)
k, v = history.K(), history.V()
if l.local {
// The local draft window is measured from the first block position.
// The whole proposed block attends bidirectionally inside that window.
end := k.Dim(2)
start := max(0, end-n-c.Window)
k = k.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(start, end), mlx.Slice())
v = v.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(start, end), mlx.Slice())
}
scale := float32(1 / math.Sqrt(float64(c.HeadDim)))
out := nn.ScaledDotProductAttention(b, q, scale, nn.WithKV(k, v, nil))
attention := l.AttentionOutput.Forward(out.Transpose(0, 2, 1, 3).Reshape(rows, n, c.Heads*c.HeadDim))
residual := draftResidualSum(x, attention)
ff := modelRMS(residual, l.FfNorm, c.Epsilon)
return draftResidualSum(residual, l.Down.Forward(mlx.SwiGLU(l.Gate.Forward(ff), l.Up.Forward(ff))))
}
// SGLang's draft normalizes the FP32 sum and stores a BF16 residual for
// the next addition. Keep the sum for normalization and round it on reuse.
func draftResidualSum(residual, update *mlx.Array) *mlx.Array {
return residual.AsType(mlx.DTypeBFloat16).AsType(mlx.DTypeFloat32).Add(update.AsType(mlx.DTypeFloat32))
}
func (d *draft) Unembed(h *mlx.Array) *mlx.Array {
hidden := h.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(0, d.config.Width))
if hidden.Dim(1) == 7 {
if logits := d.target.shortVocabularyProjection(hidden); logits != nil {
return logits.AsType(mlx.DTypeBFloat16)
}
}
return hidden.AsType(mlx.DTypeFloat32).Matmul(d.target.Output.Weight.AsType(mlx.DTypeFloat32).Transpose(1, 0)).AsType(mlx.DTypeBFloat16)
}
func (d *draft) Select(h, logits, anchor *mlx.Array, choose func(ids, scores *mlx.Array) (tokens, probs *mlx.Array)) (tokens, ids, probs *mlx.Array) {
c := d.config
b, length, vocab := logits.Dim(0), logits.Dim(1), logits.Dim(2)
candidates := mlx.BroadcastTo(mlx.Arange(0, float64(vocab), 1, mlx.DTypeInt32), int32(b), int32(vocab))
state := mlx.Zeros(mlx.DTypeBFloat16, b, c.StateWidth)
last := anchor
feature := h.Slice(mlx.Slice(), mlx.Slice(0, 1), mlx.Slice(c.Width, 2*c.Width)).Squeeze(1)
sequence := make([]*mlx.Array, length)
dist := make([]*mlx.Array, length)
for i := range length {
prev := d.Previous.Forward(last)
hidden := h.Slice(mlx.Slice(), mlx.Slice(i, i+1), mlx.Slice(0, c.Width)).Squeeze(1)
gates := d.Recurrent.Forward(mlx.Concatenate([]*mlx.Array{state, prev, hidden, feature}, -1))
width := c.StateWidth
keep := gates.Slice(mlx.Slice(), mlx.Slice(0, width)).Sigmoid()
update := gates.Slice(mlx.Slice(), mlx.Slice(width, 2*width)).Tanh()
latent := gates.Slice(mlx.Slice(), mlx.Slice(2*width, 3*width)).Tanh()
state = mlx.Add(mlx.Mul(keep, state), mlx.Mul(mlx.AddScalar(mlx.MulScalar(keep, -1), 1), update))
base := logits.Slice(mlx.Slice(), mlx.Slice(i, i+1), mlx.Slice()).Squeeze(1)
// The BF16 head rounds the sum before softcapping, then writes the
// capped scores back to BF16 before the sampler sees them.
corrected := base.Add(d.Folded.Forward(latent))
scores := softcap(corrected.AsType(mlx.DTypeFloat32), d.target.config.LogitCap).AsType(corrected.DType())
last, dist[i] = choose(candidates, scores)
sequence[i] = last
}
return mlx.Stack(sequence, 1), nil, mlx.Stack(dist, 1)
}
+147
View File
@@ -0,0 +1,147 @@
package inkling2
import (
"slices"
"testing"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/nn"
)
func TestDraftEmbedsAnchorWithTargetNorm(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
mlx.Scoped(func() {
const eps = 1e-6
ones := mlx.FromValues([]float32{1, 1}, 2).AsType(mlx.DTypeBFloat16)
d := &draft{
target: &targetModel{
config: textConfig{NormEps: eps},
Embed: nn.NewEmbedding(ones.Reshape(1, 2)),
EmbedNorm: mlx.FromValues([]float32{0, 2}, 2),
},
config: draftConfig{Width: 2, Taps: []int{0}, Epsilon: eps},
Mask: ones,
Norm: ones,
RecurrentNorm: ones,
Fuse: mlx.FromValues([]float32{1}, 1, 1),
}
states := d.NewCaches()
defer states[0].Free()
b := &batch.Batch{
InputIDs: mlx.FromValues([]int32{0, 0}, 1, 2), Hidden: ones.Reshape(1, 1, 2),
SeqOffsets: []int32{0}, SeqQueryLens: []int32{2},
}
hidden, _ := d.Forward(b, nil, cache.Layers(states))
got := hidden.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(0, 2)).AsType(mlx.DTypeFloat32).Floats()
// The target norm maps the anchor to [0, 2]. The final draft norm
// gives [0, sqrt(2)] rounded to BF16 and leaves the unit mask at [1, 1].
if want := []float32{0, 1.4140625, 1, 1}; !slices.Equal(got, want) {
t.Errorf("draft anchor and mask = %v, want %v", got, want)
}
})
})
}
func TestDraftBlockKeepsFullPrecedingWindow(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
mlx.Scoped(func() {
const bf16 = mlx.DTypeBFloat16
zero := nn.NewLinear(mlx.Zeros(bf16, 2, 2), nil)
identity := nn.NewLinear(mlx.FromValues([]float32{1, 0, 0, 1}, 2, 2).AsType(bf16), nil)
norm := mlx.FromValues([]float32{1, 1}, 2).AsType(bf16)
d := &draft{
config: draftConfig{Window: 2, Heads: 1, KVHeads: 1, HeadDim: 2, RopeTheta: 10000, Epsilon: 1e-6},
Layers: []draftLayer{{
local: true, InputNorm: norm, FfNorm: norm, QueryNorm: norm, KeyNorm: norm,
Query: zero, Key: zero, Value: zero, AttentionOutput: identity, Gate: zero, Up: zero, Down: zero,
}},
}
states := d.NewCaches()
defer func() {
for _, state := range states {
state.Free()
}
}()
history := states[0].(cache.Attention)
keys := mlx.Zeros(bf16, 1, 1, 3, 2)
values := mlx.FromValues([]float32{64, 0, 16, 0, 0, 0}, 1, 1, 3, 2).AsType(bf16)
history.Update(&batch.Batch{SeqOffsets: []int32{0}, SeqQueryLens: []int32{3}}, keys, values)
block := &batch.Batch{
InputIDs: mlx.Zeros(mlx.DTypeInt32, 1, 2), SeqOffsets: []int32{3}, SeqQueryLens: []int32{2},
}
out := d.Layers[0].forward(mlx.Zeros(bf16, 1, 2, 2), nil, nil, block, history, d.config)
// All queries see two preceding rows plus both block rows. The
// first of those four values contributes 16/4 to each output.
if got := out.AsType(mlx.DTypeFloat32).Floats(); !slices.Equal(got, []float32{4, 0, 4, 0}) {
t.Errorf("block attention = %v, want [4 0 4 0]", got)
}
})
})
}
func TestDraftNormalizesUnroundedResidualSum(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
mlx.Scoped(func() {
residual := mlx.FromValues([]float32{1, 1}, 1, 2).AsType(mlx.DTypeBFloat16)
update := mlx.FromValues([]float32{1.0 / 256, -1.0 / 128}, 1, 2).AsType(mlx.DTypeBFloat16)
weight := mlx.FromValues([]float32{1, 1}, 2)
sum := draftResidualSum(residual, update)
if got := modelRMS(sum, weight, 1e-6).AsType(mlx.DTypeFloat32).Floats(); !slices.Equal(got, []float32{1.0078125, 0.9921875}) {
t.Errorf("normalized sum = %v, want [1.0078125 0.9921875]", got)
}
if got := draftResidualSum(sum, update).Floats(); !slices.Equal(got, []float32{1.00390625, 0.984375}) {
t.Errorf("next sum = %v, want [1.00390625 0.984375]", got)
}
})
})
}
func TestDraftRoundsCorrectedScoresToBF16(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
mlx.Scoped(func() {
const bf16 = mlx.DTypeBFloat16
d := &draft{
config: draftConfig{Width: 1, StateWidth: 1},
target: &targetModel{config: textConfig{LogitCap: 30}},
Previous: nn.NewEmbedding(mlx.Zeros(bf16, 2, 1)),
Recurrent: nn.NewLinear(mlx.Zeros(bf16, 3, 4), nil),
Folded: nn.NewLinear(mlx.Zeros(bf16, 2, 1), mlx.FromValues([]float32{0, 1.0 / 256}, 2).AsType(bf16)),
}
hidden := mlx.Zeros(bf16, 1, 1, 2)
base := mlx.FromValues([]float32{2, 2}, 1, 1, 2).AsType(bf16)
anchor := mlx.FromValues([]int32{0}, 1)
// Both values round to 2 in the publisher head. A float32 sum
// keeps the small bias and incorrectly breaks the tie.
tokens, ids, scores := d.Select(hidden, base, anchor, func(candidates, scores *mlx.Array) (*mlx.Array, *mlx.Array) {
if got := candidates.Ints(); !slices.Equal(got, []int32{0, 1}) {
t.Fatalf("candidate order = %v, want [0 1]", got)
}
return scores.Argmax(-1, false).AsType(mlx.DTypeInt32), scores.AsType(mlx.DTypeFloat32)
})
if ids != nil {
t.Fatalf("vocabulary-ordered scores returned explicit IDs %v", ids)
}
if got := scores.Floats(); !slices.Equal(got, []float32{2, 2}) {
t.Errorf("corrected scores = %v, want [2 2]", got)
}
if got := tokens.Ints(); !slices.Equal(got, []int32{0}) {
t.Errorf("greedy token = %v, want [0]", got)
}
})
})
}
func TestDraftVerificationDepth(t *testing.T) {
for _, tc := range []struct {
block int
adaptive bool
}{{4, false}, {8, true}, {1024, false}} {
d := &draft{config: draftConfig{Block: tc.block}}
if got := d.AdaptiveDraftDepth(); got != tc.adaptive {
t.Errorf("block %d: got adaptive depth %v, want %v", tc.block, got, tc.adaptive)
}
}
}
+152
View File
@@ -0,0 +1,152 @@
package inkling2
import (
"fmt"
"math"
"slices"
"testing"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
)
type gateUpInputs struct {
inner, xmax, wmax, denominator, ids, scores *mlx.Array
}
func gateUpInputsFor(rows, topK int) gateUpInputs {
inner := make([]float32, rows*topK*2304)
for i := range inner {
inner[i] = float32((i*397)%15011-7505) / 19
}
ids := make([]uint32, rows*topK)
scores := make([]float32, len(ids))
for i := range ids {
ids[i] = uint32((i * 17) % 128)
scores[i] = float32((i*31)%123+1) / 31
}
xmax := make([]float32, rows)
wmax := make([]float32, 128)
for i := range xmax {
xmax[i] = float32(i + 1)
}
for i := range wmax {
wmax[i] = float32(i + 1)
}
if rows >= 2 {
// Two captured routes put the final weighted FP32 product exactly
// halfway between adjacent BF16 values on Metal.
inner[0], inner[1] = 1809456, -2859888
inner[topK*2304], inner[topK*2304+1] = 888816, 1665824
xmax[0], xmax[1] = 1.640625, 1.7734375
wmax[ids[0]], wmax[ids[topK]] = 0.14305396, 0.11680993
scores[0], scores[topK] = 0.53709847, 0.4751412
}
return gateUpInputs{
inner: mlx.FromValues(inner, rows, topK, 1, 2304),
xmax: mlx.FromValues(xmax, rows, 1, 1, 1),
wmax: mlx.FromValues(wmax, 128),
denominator: mlx.FromValue(float32(2688)),
ids: mlx.FromValues(ids, rows, topK),
scores: mlx.FromValues(scores, rows, topK),
}
}
func (in gateUpInputs) eager() *mlx.Array {
outer := mlx.Div(mlx.Mul(in.xmax, mlx.Take(in.wmax, in.ids, 0).ExpandDims(-1).ExpandDims(-1)), mlx.MulScalar(in.denominator, 1536))
y := mlx.Mul(in.inner, outer).AsType(mlx.DTypeBFloat16).AsType(mlx.DTypeFloat32)
gate := y.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(), mlx.Slice(0, 2304, 2))
up := y.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(), mlx.Slice(1, 2304, 2))
gateFactor := mlx.MulScalar(mlx.DivScalar(gate, 4).Tanh(), 4)
upFactor := mlx.MulScalar(mlx.DivScalar(up, 25).Tanh(), 25)
return mlx.Mul(mlx.Mul(mlx.Mul(gateFactor, gate.Sigmoid()), upFactor), in.scores.ExpandDims(-1).ExpandDims(-1)).AsType(mlx.DTypeBFloat16)
}
func (in gateUpInputs) compiled() *mlx.Array {
gate, up := splitGateUp(in.inner)
return compiledGateUpEpilogue(gate, up, in.xmax, in.wmax, in.denominator, in.ids, in.scores)[0]
}
func TestNVFP4GateUpEpilogue(t *testing.T) {
for _, tc := range []struct{ rows, topK int }{{2, 8}, {16, 1}} {
t.Run(fmt.Sprintf("rows%d/top%d", tc.rows, tc.topK), func(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
mlx.Scoped(func() {
if !mlx.MetalIsAvailable() {
t.Skip("Metal epilogue required")
}
mlx.EnableCompile()
in := gateUpInputsFor(tc.rows, tc.topK)
want := in.eager().AsType(mlx.DTypeFloat32).Floats()
got := in.compiled().AsType(mlx.DTypeFloat32).Floats()
if !slices.Equal(got, want) {
t.Error("compiled gate/up result differs from the eager graph")
}
for i, bits := range []uint32{0xbb9a0000, 0x3a6e0000} {
if actual := math.Float32bits(got[i*tc.topK*1152]); actual != bits {
t.Errorf("route %d rounded to %08x, want %08x", i, actual, bits)
}
}
})
})
})
}
}
func TestGateUpFloatBank(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
mlx.Scoped(func() {
weight := mlx.Arange(0, 2*32*64, 1, mlx.DTypeFloat32).Reshape(2, 32, 64)
e := routedExperts{GateUp: expertBank{Weight: weight}, topK: 1, gateCap: 2, upCap: 7}
flat := mlx.AddScalar(mlx.Zeros(mlx.DTypeFloat32, 2, 64), 1)
ids := mlx.FromValues([]uint32{1, 0}, 2, 1)
scores := mlx.FromValues([]float32{0.25, 0.75}, 2, 1)
got := e.gateUpInput(flat, ids, nil, scores, false)
pair := mlx.GatherMM(flat.Reshape(2, 1, 1, 64), weight.Transpose(0, 2, 1), nil, ids, false)
gate, up := splitGateUp(pair)
want := weightedSwiGLU(gate, up, scores, 2, 7, mlx.DTypeFloat32)
if !slices.Equal(got.Floats(), want.Floats()) {
t.Error("float bank changed on the existing GatherMM route")
}
})
})
}
func BenchmarkInklingGateUpEpilogue(b *testing.B) {
worker := mlxtest.Worker(b)
var metal bool
if err := worker.Do(b.Context(), func() error { metal = mlx.MetalIsAvailable(); return nil }); err != nil {
b.Fatal(err)
}
if !metal {
b.Skip("Metal epilogue required")
}
for _, tc := range []struct{ rows, topK int }{{1, 8}, {8, 8}, {512, 1}} {
for _, mode := range []string{"eager", "compiled"} {
b.Run(fmt.Sprintf("rows%d/top%d/%s", tc.rows, tc.topK, mode), func(b *testing.B) {
err := worker.Do(b.Context(), func() error {
mlx.Scoped(func() {
mlx.EnableCompile()
in := gateUpInputsFor(tc.rows, tc.topK)
mlx.Eval(in.inner, in.xmax, in.wmax, in.denominator, in.ids, in.scores)
op := in.eager
if mode == "compiled" {
op = in.compiled
}
eval := func() { mlx.Eval(op()) }
mlx.Scoped(eval)
b.ResetTimer()
for range b.N {
mlx.Scoped(eval)
}
b.StopTimer()
})
return nil
})
if err != nil {
b.Fatal(err)
}
})
}
}
}
+186
View File
@@ -0,0 +1,186 @@
package inkling2
import (
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/nn"
)
// Inkling's SGLang reference sets the outer scale to the row maximum magnitude
// divided by 1536. Each block uses the 4- or 6-range scale with the smaller L1 error.
const nvfp4ActivationDenominator = 1536
type expertBank struct {
Weight *mlx.Array
BlockScales *mlx.Array
Maxima *mlx.Array
Denominator *mlx.Array
}
// inputRows gathers the gate/up activations after quantization, so each
// token's activation is quantized once even when several experts use it.
func (e expertBank) project(x, indices, inputRows *mlx.Array, grouped bool) *mlx.Array {
if e.BlockScales == nil {
return mlx.GatherMM(x, e.Weight.Transpose(0, 2, 1), nil, indices, false)
}
if e.Maxima == nil {
values := mxfp8ExpertInput(x)
result := mlx.GatherQMM(values, e.Weight, e.BlockScales, nil, nil, indices, true, 32, 8, "mxfp8", nil, false)
return result.AsType(x.DType())
}
result, activationMax := e.nvfp4Inner(x, indices, inputRows, grouped)
outerScale := nvfp4OuterScale(activationMax, e.Maxima, e.Denominator, indices)
return mlx.Mul(result, outerScale).AsType(x.DType())
}
func (e expertBank) nvfp4Inner(x, indices, inputRows *mlx.Array, grouped bool) (*mlx.Array, *mlx.Array) {
values, activationMax := mlx.QuantizeNVFP4Activation4Over6(x, nvfp4ActivationDenominator)
if inputRows != nil {
values = mlx.Take(values, inputRows, 0)
activationMax = mlx.Take(activationMax, inputRows, 0)
}
if !grouped && inputRows == nil && indices.Dim(0) == 4 {
if result := mlx.GatherNVFP4QMV(values, e.Weight, e.BlockScales, indices); result != nil {
return result, activationMax
}
}
if grouped && inputRows != nil && indices.Dim(0) >= 512 && mlx.PrefersCompactNVFP4QMM() {
// Each reconstructed E2M1 value times its E4M3 block scale fits exactly in BF16.
if result := mlx.GatherNVFP4QMM(values.AsType(mlx.DTypeBFloat16), e.Weight, e.BlockScales, indices); result != nil {
return result, activationMax
}
}
result := mlx.GatherQMM(values, e.Weight, e.BlockScales, nil, nil, indices, true, 16, 4, "nvfp4", nil, grouped)
return result, activationMax
}
func nvfp4OuterScale(activationMax, expertMaxima, denominator, indices *mlx.Array) *mlx.Array {
weightMax := mlx.Take(expertMaxima, indices, 0).ExpandDims(-1).ExpandDims(-1)
return mlx.Div(mlx.Mul(activationMax, weightMax), mlx.MulScalar(denominator, nvfp4ActivationDenominator))
}
func mxfp8ExpertInput(x *mlx.Array) *mlx.Array {
shape := x.Dims()
width := shape[len(shape)-1]
blocks := x.AsType(mlx.DTypeFloat32).Reshape(-1, width/32, 32)
rawScale := mlx.MulScalar(blocks.Abs().MaxAxis(-1, true), 1.0/448)
// MX scales are powers of two. Round the exponent up when the
// FP32 significand has a fractional part.
bits := rawScale.View(mlx.DTypeInt32)
exponent := bits.RightShift(mlx.FromValue(23))
fraction := bits.BitwiseAnd(mlx.FromValue((1 << 23) - 1))
exponent = exponent.Add(fraction.Greater(mlx.FromValue(0)).AsType(mlx.DTypeInt32))
exponent = mlx.Minimum(exponent, mlx.FromValue(254))
minimum := mlx.FromValue(float32(0x1p-127))
exponent = mlx.Where(rawScale.Greater(minimum), exponent, mlx.FromValue(0))
encoded := exponent.Multiply(mlx.FromValue(1 << 23)).View(mlx.DTypeFloat32)
scale := mlx.Maximum(encoded, minimum)
inverse := mlx.Where(exponent.Equal(mlx.FromValue(0)), mlx.FromValue(float32(0x1p127)), mlx.Div(mlx.FromValue(float32(1)), scale))
scaled := mlx.Clip(mlx.Mul(blocks, inverse), mlx.FromValue(float32(-448)), mlx.FromValue(float32(448)))
return mlx.Mul(mlx.FromFP8(mlx.ToFP8(scaled), mlx.DTypeFloat32), scale).Reshape(shape...)
}
func routeExperts(logits, bias *mlx.Array, topK int, scale float32) (indices, weights *mlx.Array) {
selection := logits.Sigmoid()
if bias != nil {
selection = selection.Add(bias)
}
indices = mlx.Argpartition(mlx.Neg(selection), topK-1, -1).Slice(mlx.Slice(), mlx.Slice(0, topK))
chosen := logits.TakeAlongAxis(indices, -1)
logWeights := mlx.Neg(mlx.Softplus(mlx.Neg(chosen)))
return indices, mlx.MulScalar(mlx.SoftmaxAxis(logWeights, -1, true), scale)
}
type routedExperts struct {
Router *mlx.Array
Bias *mlx.Array
GateUp expertBank
Down expertBank
topK int
routeScale float32
gateCap float32
upCap float32
}
func (e routedExperts) forward(x *mlx.Array) *mlx.Array {
batch, tokens, width := x.Dim(0), x.Dim(1), x.Dim(2)
flat := x.Reshape(batch*tokens, width)
router := nn.Linear{Weight: e.Router.AsType(mlx.DTypeFloat32)}
routerInput := flat.AsType(mlx.DTypeFloat32)
if tokens <= shortTargetRows {
routerInput = routerInput.Reshape(batch, tokens, width)
}
logits := projectTarget(&router, routerInput).Reshape(batch*tokens, e.Router.Dim(0))
indices, weights := routeExperts(logits, e.Bias, e.topK, e.routeScale)
// The Metal grouped gather reuses each expert when there are at least
// four routes per expert on average. Keep short target verification rows
// on the width-stable path even if multiple requests share a batch.
grouped := e.GateUp.Maxima != nil && e.Down.Maxima != nil &&
tokens >= 64 && batch*tokens*e.topK/e.Router.Dim(0) >= 4 && mlx.MetalIsAvailable()
return e.combine(flat, indices, weights, grouped).Reshape(batch, tokens, width)
}
// combine evaluates the selected experts and restores their routing order
// before accumulating the result for each token.
func (e routedExperts) combine(flat, indices, weights *mlx.Array, grouped bool) *mlx.Array {
rows, width := flat.Dim(0), flat.Dim(1)
var inputRows, inverse *mlx.Array
if grouped {
flatIndices := indices.Reshape(-1)
order := mlx.Argsort(flatIndices, 0)
inverse = mlx.Argsort(order, 0)
inputRows = mlx.FloorDivideScalar(order, int32(e.topK))
indices = mlx.Take(flatIndices, order, 0).Reshape(-1, 1)
weights = mlx.Take(weights.Reshape(-1), order, 0).Reshape(-1, 1)
}
weighted := e.gateUpInput(flat, indices, inputRows, weights, grouped)
down := e.Down.project(weighted, indices, nil, grouped).Squeeze(2).AsType(mlx.DTypeFloat32)
if grouped {
down = mlx.Take(down.Reshape(-1, width), inverse, 0).Reshape(rows, e.topK, width)
}
return mlx.Sum(down, 1, false).AsType(flat.DType())
}
// Fuse the checkpoint's NVFP4 outer scale, projection rounding and SwiGLU
// pointwise operations after the Metal gather.
func (e routedExperts) gateUpInput(flat, indices, inputRows, scores *mlx.Array, grouped bool) *mlx.Array {
x := flat.ExpandDims(1).ExpandDims(1)
if mlx.MetalIsAvailable() && flat.DType() == mlx.DTypeBFloat16 && flat.Dim(1) == 2304 &&
e.GateUp.BlockScales != nil && e.GateUp.Maxima != nil && e.GateUp.Weight.Dim(0) == 128 && e.GateUp.Weight.Dim(1) == 2304 &&
e.topK == 8 && e.gateCap == 4 && e.upCap == 25 {
inner, xmax := e.GateUp.nvfp4Inner(x, indices, inputRows, grouped)
gate, up := splitGateUp(inner)
return compiledGateUpEpilogue(gate, up, xmax, e.GateUp.Maxima, e.GateUp.Denominator, indices, scores)[0]
}
paired := e.GateUp.project(x, indices, inputRows, grouped).AsType(mlx.DTypeFloat32)
gate, up := splitGateUp(paired)
return weightedSwiGLU(gate, up, scores, e.gateCap, e.upCap, flat.DType())
}
func splitGateUp(paired *mlx.Array) (gate, up *mlx.Array) {
end := paired.Dim(-1)
return paired.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(), mlx.Slice(0, end, 2)),
paired.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(), mlx.Slice(1, end, 2))
}
// Routing weights apply before the down projection and its quantizer.
func weightedSwiGLU(gate, up, scores *mlx.Array, gateCap, upCap float32, dtype mlx.DType) *mlx.Array {
activated := mlx.Mul(mlx.Mul(softcap(gate, gateCap), gate.Sigmoid()), softcap(up, upCap))
return mlx.Mul(activated, scores.ExpandDims(-1).ExpandDims(-1)).AsType(dtype)
}
var compiledGateUpEpilogue = mlx.Compile("InklingGateUpEpilogue", func(inputs ...*mlx.Array) []*mlx.Array {
gate, up := inputs[0], inputs[1]
xmax, wmax, denom, ids, scores := inputs[2], inputs[3], inputs[4], inputs[5], inputs[6]
outer := nvfp4OuterScale(xmax, wmax, denom, ids)
// Each projection rounds to BF16 before either nonlinearity.
gate = mlx.Mul(gate, outer).AsType(mlx.DTypeBFloat16).AsType(mlx.DTypeFloat32)
up = mlx.Mul(up, outer).AsType(mlx.DTypeBFloat16).AsType(mlx.DTypeFloat32)
return []*mlx.Array{weightedSwiGLU(gate, up, scores, 4, 25, mlx.DTypeBFloat16)}
}, mlx.Shapeless())
func softcap(x *mlx.Array, cap float32) *mlx.Array {
if cap <= 0 {
return x
}
return mlx.MulScalar(mlx.DivScalar(x, cap).Tanh(), cap)
}
+122
View File
@@ -0,0 +1,122 @@
package inkling2
import (
"math/rand/v2"
"slices"
"testing"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
)
func TestNVFP4ExpertAppliesActivationAndWeightScales(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
mlx.Scoped(func() {
const width, outputs = 64, 8
// E2M1 value 1 in every nibble, with E4M3 block scales of 1.
bank := expertBank{
Weight: mlx.FromValues(slices.Repeat([]uint32{0x22222222}, 2*outputs*width/8), 2, outputs, width/8),
BlockScales: mlx.FromValues(slices.Repeat([]uint8{0x38}, 2*outputs*width/16), 2, outputs, width/16),
Maxima: mlx.FromValues([]float32{2, 3}, 2),
Denominator: mlx.FromValues([]float32{4}, 1),
}
input := mlx.FromValues(slices.Repeat([]float32{2}, width), 1, 1, 1, width).AsType(mlx.DTypeBFloat16)
selected := mlx.FromValues([]int32{1, 0}, 1, 2)
got := bank.project(input, selected, nil, false).AsType(mlx.DTypeFloat32).Floats()
want := append(slices.Repeat([]float32{96}, outputs), slices.Repeat([]float32{64}, outputs)...)
if !slices.Equal(got, want) {
t.Errorf("expert outputs = %v, want %v", got, want)
}
})
})
}
func TestNVFP4ActivationRounding(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
// The first block of the publisher CUDA capture contains its row maximum.
// Tiling preserves both normalization and the per-block scale decisions.
block := []float32{
2.4375, -0.66015625, 0.126953125, 2.25, 0.66796875, -0.96484375, -0.61328125, 0.400390625,
-0.26953125, 0.77734375, -0.3359375, -0.28515625, 1, -1.421875, 0.2578125, 0.05078125,
}
quantized := []float32{1536, -384, 0, 1536, 384, -576, -384, 192, -192, 576, -192, -192, 576, -768, 192, 0}
for _, width := range []int{1152, 2304} {
input := make([]float32, 3*width)
want := make([]float32, len(input))
// Row 0 is all zero. Row 1 has outer scale one. Both candidates
// tie at ±1.25, rounding to ±1 with scale one or ±1.5 with scale 1.5.
input[width], want[width] = 1536, 1536
for i := 16; i < width; i += 16 {
copy(input[width+i:], []float32{6, 1.25, -1.25})
copy(want[width+i:], []float32{6, 1, -1})
}
for i := 2 * width; i < len(input); i += 16 {
copy(input[i:], block)
copy(want[i:], quantized)
}
values, maxima := mlx.QuantizeNVFP4Activation4Over6(mlx.FromValues(input, 3, width).AsType(mlx.DTypeBFloat16), nvfp4ActivationDenominator)
if values == nil {
t.Fatalf("Metal activation unavailable for width %d", width)
}
if got := maxima.Floats(); !slices.Equal(got, []float32{0, 1536, 2.4375}) {
t.Errorf("width %d maxima = %v", width, got)
}
for i, v := range values.Floats() {
if v != want[i] {
t.Fatalf("width %d row %d element %d = %g, want %g", width, i/width, i%width, v, want[i])
}
}
}
})
}
func TestGroupedNVFP4ExpertsPreserveRouting(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
if !mlx.MetalIsAvailable() {
t.Skip("Metal grouped gather")
}
mlx.Scoped(func() {
// At 512 routes, the scalar Metal backend selects the compact gate/up matmul.
const rows, experts, topK, width = 128, 8, 4, 128
random := rand.New(rand.NewPCG(19, 31))
bank := func(outputs int) expertBank {
packed := make([]uint32, experts*outputs*width/8)
for i := range packed {
packed[i] = random.Uint32()
}
scales := make([]uint8, experts*outputs*width/16)
for i := range scales {
scales[i] = uint8(32 + random.IntN(32))
}
return expertBank{
Weight: mlx.FromValues(packed, experts, outputs, width/8),
BlockScales: mlx.FromValues(scales, experts, outputs, width/16),
Maxima: mlx.Arange(1, experts+1, 1, mlx.DTypeFloat32),
Denominator: mlx.FromValue(float32(8)),
}
}
e := routedExperts{GateUp: bank(2 * width), Down: bank(width), topK: topK, gateCap: 5, upCap: 4}
input := make([]float32, rows*width)
indices := make([]int32, rows*topK)
weights := make([]float32, rows*topK)
for i := range input {
input[i] = float32(random.NormFloat64())
}
for row := range rows {
order := random.Perm(experts)
for j := range topK {
indices[row*topK+j] = int32(order[j])
weights[row*topK+j] = float32(random.Float64())
}
}
x := mlx.FromValues(input, rows, width).AsType(mlx.DTypeBFloat16)
ids := mlx.FromValues(indices, rows, topK)
gains := mlx.FromValues(weights, rows, topK)
want := e.combine(x, ids, gains, false).AsType(mlx.DTypeFloat32).Floats()
got := e.combine(x, ids, gains, true).AsType(mlx.DTypeFloat32).Floats()
if !slices.Equal(got, want) {
t.Fatal("grouping changed the routed expert result")
}
})
})
}
+259
View File
@@ -0,0 +1,259 @@
package inkling2
import (
"encoding/json"
"fmt"
"slices"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
"github.com/ollama/ollama/mlxrunner/nn"
"github.com/ollama/ollama/mlxrunner/tokenizer"
)
func init() {
model.Register("Inkling2LoopForConditionalGeneration", newModel)
}
type targetModel struct {
config textConfig
plan []layerVisit
tok *tokenizer.Tokenizer
Vision *visionEncoder
draftTaps []int
Embed *nn.Embedding
EmbedNorm *mlx.Array
OutputNorm *mlx.Array
OutputQuery *mlx.Array
Output *nn.Linear
CompactOutput *mlx.Array
fp32Output bool
Layers []decoderLayer
}
type decoderLayer struct {
Attention selfAttention
AttentionNorm []*mlx.Array
AttentionQuery *mlx.Array
AttentionOutput shortConv
FeedForward routedExperts
FeedForwardNorm *mlx.Array
FeedForwardQuery *mlx.Array
FeedForwardOutput shortConv
MessageProjections []messageGate
MessageQueries *mlx.Array
}
const numVisitCaches = 5
func newModel(root *model.Root) (model.Model, error) {
raw, err := root.Manifest.ReadConfig("config.json")
if err != nil {
return nil, err
}
var cfg struct {
Text textConfig `json:"text_config"`
Vision *visionConfig `json:"vision_config"`
}
if err := json.Unmarshal(raw, &cfg); err != nil {
return nil, fmt.Errorf("parse Inkling2 config: %w", err)
}
if err := cfg.Text.validate(); err != nil {
return nil, err
}
plan, err := cfg.Text.executionPlan()
if err != nil {
return nil, err
}
tokData, err := root.Manifest.ReadConfig("tokenizer.json")
if err != nil {
return nil, err
}
tokConfig, err := root.Manifest.ReadConfig("tokenizer_config.json")
if err != nil {
return nil, err
}
var generation []byte
if _, exists := root.Manifest.ConfigLayer("generation_config.json"); exists {
generation, err = root.Manifest.ReadConfig("generation_config.json")
if err != nil {
return nil, err
}
}
tok, err := tokenizer.LoadFromBytesWithConfig(tokData, &tokenizer.TokenizerConfig{
ConfigJSON: raw, GenerationConfigJSON: generation, TokenizerConfigJSON: tokConfig,
})
if err != nil {
return nil, fmt.Errorf("parse Inkling2 tokenizer: %w", err)
}
m := &targetModel{config: cfg.Text, plan: plan, tok: tok}
if cfg.Vision != nil {
if err := cfg.Vision.validate(); err != nil {
return nil, err
}
var processor struct {
ImageToken string `json:"image_token"`
}
if err := root.Manifest.ReadConfigJSON("processor_config.json", &processor); err != nil {
return nil, fmt.Errorf("load Inkling2 image processor: %w", err)
}
id, ok := tok.GetSpecialToken(processor.ImageToken)
if !ok {
return nil, fmt.Errorf("Inkling2 image token %q is missing from the tokenizer", processor.ImageToken)
}
m.Vision = &visionEncoder{config: *cfg.Vision, imageToken: id}
}
if _, exists := root.Manifest.ConfigLayer("hf_quant_config.json"); exists {
var quant struct {
Model struct {
Groups []struct {
Tensors []string `json:"tensors"`
Output string `json:"fwd_output_dtype"`
} `json:"parameter_groups"`
} `json:"model"`
}
if err := root.Manifest.ReadConfigJSON("hf_quant_config.json", &quant); err != nil {
return nil, fmt.Errorf("parse Inkling2 precision config: %w", err)
}
for _, group := range quant.Model.Groups {
if slices.Contains(group.Tensors, "model.llm.unembed.weight") {
m.fp32Output = group.Output == "float32"
}
}
}
return m, nil
}
func (m *targetModel) MaxContextLength() int { return m.config.Context }
func (m *targetModel) Tokenizer() *tokenizer.Tokenizer { return m.tok }
// Routed low-precision experts can make different choices when the same rows
// are processed in a different size of token batch.
func (*targetModel) AlignPrefillToSnapshots() {}
func (m *targetModel) NewCaches() []cache.Cache {
states := make([]cache.Cache, 0, numVisitCaches*len(m.plan))
for _, visit := range m.plan {
a := m.Layers[visit.layer].Attention
if a.window > 0 {
states = append(states, cache.NewOrderedWindowKVCache(a.window))
} else {
states = append(states, cache.NewKVCache())
}
for _, width := range []int{a.kvHeads * a.headDim, a.kvHeads * a.headDim, m.config.HiddenSize, m.config.HiddenSize} {
states = append(states, cache.NewRecurrentCache(int32(m.config.ConvTaps-1), int32(width), 1, 1, 1))
}
}
return states
}
func (m *targetModel) embedTokens(ids *mlx.Array) *mlx.Array {
return modelRMS(m.Embed.Forward(ids), m.EmbedNorm, m.config.NormEps)
}
func (m *targetModel) Forward(b *batch.Batch, caches []cache.Layer) (hidden, auxHidden *mlx.Array) {
embeddings := m.embedTokens(b.InputIDs)
state := residualStream{partial: m.imageEmbeddings(b, embeddings)}
var prelude residualStream
var previous []*mlx.Array
features := make([]*mlx.Array, 0, len(m.draftTaps))
for i, visit := range m.plan {
if loop := m.config.Loop; loop != nil && visit.layer == loop.Start {
if visit.pass == 0 {
prelude = state
} else {
blocks := state.blocks[len(prelude.blocks)+1:]
previous = append(slices.Clone(blocks), state.partial)
state = prelude
}
}
if len(features) < len(m.draftTaps) && i == m.draftTaps[len(features)] {
features = append(features, state.partial)
}
var layerCaches [numVisitCaches]cache.Layer
if caches != nil {
copy(layerCaches[:], caches[i*numVisitCaches:(i+1)*numVisitCaches])
}
var messages *mlx.Array
layer := m.Layers[visit.layer]
if visit.pass > 0 {
messages = mixResiduals(previous, layer.MessageQueries, true)
}
state = layer.forward(state, messages, b, layerCaches, visit.layer%m.config.ResidualBlockSize == 0, m.config)
}
hidden = modelRMS(state.mix(m.OutputQuery, m.config.NormalizeResidualValues), m.OutputNorm, m.config.NormEps)
if len(features) != 0 {
features = append(features, hidden)
return hidden, mlx.Concatenate(features, -1)
}
return hidden, hidden
}
func (m *targetModel) shortVocabularyProjection(hidden *mlx.Array) *mlx.Array {
if m.CompactOutput == nil || hidden.NumDims() != 3 {
return nil
}
b, t, width := hidden.Dim(0), hidden.Dim(1), hidden.Dim(2)
if b < 1 || b > 2 || t < 1 || t > shortTargetRows {
return nil
}
scores := mlx.MatmulBF16Weight(hidden.Reshape(b*t, width), m.CompactOutput)
if scores == nil {
return nil
}
vocab := m.config.UnpaddedVocab
return scores.Slice(mlx.Slice(), mlx.Slice(0, vocab)).Reshape(b, t, vocab)
}
func (m *targetModel) Unembed(hidden *mlx.Array) *mlx.Array {
if logits := m.shortVocabularyProjection(hidden); logits != nil {
return softcap(logits, m.config.LogitCap)
}
if m.fp32Output {
hidden = hidden.AsType(mlx.DTypeFloat32)
}
return softcap(projectTarget(m.Output, hidden).AsType(mlx.DTypeFloat32), m.config.LogitCap)
}
func modelRMS(x, weight *mlx.Array, epsilon float32) *mlx.Array {
return mlx.RMSNormFn(x.AsType(mlx.DTypeFloat32), weight.AsType(mlx.DTypeFloat32), epsilon).AsType(mlx.DTypeBFloat16)
}
func (l decoderLayer) forward(state residualStream, messages *mlx.Array, b *batch.Batch, caches [numVisitCaches]cache.Layer, boundary bool, cfg textConfig) residualStream {
inputs := [3]*mlx.Array{state.partial, state.partial, state.partial}
if len(state.blocks) != 0 && l.AttentionQuery != nil {
mixed := state.mix(l.AttentionQuery, cfg.NormalizeResidualValues)
if l.AttentionQuery.NumDims() == 1 {
inputs = [3]*mlx.Array{mixed, mixed, mixed}
} else {
for index := range inputs {
inputs[index] = selectMessage(mixed, index)
}
}
}
for index, input := range inputs {
if messages != nil {
input = l.MessageProjections[index].apply(input, selectMessage(messages, index))
}
inputs[index] = modelRMS(input, l.AttentionNorm[index], cfg.NormEps)
}
attention := l.Attention.forward(inputs[0], inputs[1], inputs[2], b, caches[0], caches[1], caches[2])
attention = l.AttentionOutput.forward(attention, nil, b, caches[3])
subtotal := state.afterAttention(attention, boundary)
ffnInput := subtotal.mix(l.FeedForwardQuery, cfg.NormalizeResidualValues)
if messages != nil {
ffnInput = l.MessageProjections[3].apply(ffnInput, selectMessage(messages, 3))
}
ffn := l.FeedForward.forward(modelRMS(ffnInput, l.FeedForwardNorm, cfg.NormEps))
ffn = l.FeedForwardOutput.forward(ffn, nil, b, caches[4])
subtotal.partial = mlx.Add(subtotal.partial.AsType(mlx.DTypeFloat32), ffn.AsType(mlx.DTypeFloat32)).AsType(state.partial.DType())
return subtotal
}
func selectMessage(inputs *mlx.Array, index int) *mlx.Array {
return inputs.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(index, index+1), mlx.Slice()).Squeeze(2)
}
@@ -0,0 +1,58 @@
package inkling2
import (
"math"
"math/rand/v2"
"slices"
"testing"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
)
func TestMetalAttentionRounding(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
if !mlx.MetalIsAvailable() {
t.Skip("requires Metal")
}
mlx.EnableCompile()
random := rand.New(rand.NewPCG(131, 49))
values := func(shape ...int) *mlx.Array {
n := 1
for _, size := range shape {
n *= size
}
data := make([]float32, n)
for i := range data {
data[i] = float32(random.NormFloat64())
}
return mlx.FromValues(data, shape...).AsType(mlx.DTypeBFloat16)
}
equal := func(name string, got, want *mlx.Array) {
t.Helper()
if got.DType() != want.DType() || !slices.Equal(got.Dims(), want.Dims()) {
t.Fatalf("%s got %s %v, want %s %v", name, got.DType(), got.Dims(), want.DType(), want.Dims())
}
a := got.AsType(mlx.DTypeFloat32).Floats()
b := want.AsType(mlx.DTypeFloat32).Floats()
for i := range a {
if math.Float32bits(a[i]) != math.Float32bits(b[i]) {
t.Fatalf("%s value %d: got %g, want %g", name, i, a[i], b[i])
}
}
}
for _, tokens := range []int{1, 8, 129} {
mlx.Scoped(func() {
x := values(2, tokens, 8, 128)
weight := values(8, 128)
temperature := values(2, tokens, 1, 1).AsType(mlx.DTypeFloat32)
for _, scales := range [][]*mlx.Array{{}, {weight}, {weight, temperature}} {
inputs := append([]*mlx.Array{x, mlx.FromValue(float32(8))}, scales...)
equal("L2 clip", compiledClipL2(inputs...)[0], clipL2Tensors(inputs...)[0])
}
gate := values(2, tokens, 8, 128)
equal("attention gate", compiledAttentionGate(x, gate), gateAttention(x, gate, x.DType()))
})
}
})
}
@@ -0,0 +1,94 @@
package inkling2
import (
"math"
"testing"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/nn"
)
func TestRelativePrefillMixedHistories(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
if !mlx.MetalIsAvailable() {
t.Skip("requires Metal")
}
const width = 320
for _, tc := range []struct{ window, prefix, paddedLive int }{
{0, 155, 197},
{1024, 155, 0},
{1024, 155, 1},
{1024, 1211, 8},
{1024, 155, 9},
{1024, 155, 197},
{1024, 1211, 197},
} {
window := tc.window
mlx.Scoped(func() {
b := &batch.Batch{InputIDs: mlx.Zeros(mlx.DTypeInt32, 2, width), SeqOffsets: []int32{1211, int32(tc.prefix)}, SeqQueryLens: []int32{width, int32(tc.paddedLive)}}
values := func(rows, heads, steps, channels int, factor float32) *mlx.Array {
data := mlx.Arange(0, float64(rows*heads*steps*channels), 1, mlx.DTypeFloat32)
return mlx.Sin(mlx.MulScalar(data, factor)).AsType(mlx.DTypeBFloat16).Reshape(rows, steps, heads, channels).Transpose(0, 2, 1, 3)
}
q, table, sink := values(2, 24, width, 128, .017), values(2, 24, width, 1024, -.009), values(2, 24, width, 1, .005)
histories := make([]*nn.KVHistory, 2)
expected := make([]*mlx.Array, 2)
scale := float32(1 / math.Sqrt(128))
for i := range histories {
var store interface {
cache.Attention
Free()
} = cache.NewKVCache()
if window != 0 {
store = cache.NewOrderedWindowKVCache(window)
}
defer store.Free()
prefix := int(b.SeqOffsets[i])
row := b.Row(i)
first := &batch.Batch{InputIDs: mlx.Zeros(mlx.DTypeInt32, 1, prefix), SeqOffsets: []int32{0}, SeqQueryLens: []int32{int32(prefix)}}
prefixK, prefixV := values(1, 8, prefix, 128, .014), values(1, 8, prefix, 128, .023)
newK, newV := values(1, 8, width, 128, -.008), values(1, 8, width, 128, .031)
store.Update(first, prefixK, prefixV)
h := store.Update(row, newK, newV)
histories[i] = h
pick := func(x *mlx.Array) *mlx.Array {
return x.Slice(mlx.Slice(i, i+1), mlx.Slice(), mlx.Slice(), mlx.Slice())
}
if window == 0 {
expected[i] = relativeWindowSDPA(row, pick(q).AsType(mlx.DTypeFloat32), pick(table), pick(sink), h.K().Dim(2), 0, scale, nn.WithKVHistory(h.AsType(mlx.DTypeFloat32)))
continue
}
// Build a separate history from only the live tokens. This checks both
// the absolute key positions after eviction and zeroed padding.
live := int(row.SeqQueryLens[0])
if live == 0 {
expected[i] = mlx.Zeros(mlx.DTypeFloat32, 1, 24, width, 128)
continue
}
trim := func(x *mlx.Array) *mlx.Array {
return x.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(0, live), mlx.Slice())
}
single := &batch.Batch{InputIDs: mlx.Zeros(mlx.DTypeInt32, 1, live), SeqOffsets: []int32{int32(prefix)}, SeqQueryLens: []int32{int32(live)}}
serial := cache.NewOrderedWindowKVCache(window)
defer serial.Free()
serial.Update(first, prefixK, prefixV)
h = serial.Update(single, trim(newK), trim(newV))
out := relativeSDPA(single, trim(pick(q)), nil, nil, trim(pick(table)), trim(pick(sink)), h, window, scale)
expected[i] = mlx.PadConstant(out, []int{2}, []int{0}, []int{width - live})
}
got := relativeSDPA(b, q, nil, nil, table, sink, nn.NewRowKVHistory(histories), window, scale)
want := mlx.Concatenate(expected, 0)
if got.DType() != mlx.DTypeFloat32 || want.DType() != mlx.DTypeFloat32 {
t.Fatal("relative attention must preserve FP32 until the output gate")
}
same := got.View(mlx.DTypeUint32).Equal(want.View(mlx.DTypeUint32)).AsType(mlx.DTypeInt32).Reshape(-1).SumAxis(0, false).Int()
if int(same) != want.Size() {
t.Fatalf("window %d with %d live tokens: %d of %d mixed-row FP32 entries differ", window, tc.paddedLive, want.Size()-int(same), want.Size())
}
})
}
})
}
+45
View File
@@ -0,0 +1,45 @@
package inkling2
import (
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/nn"
)
// Short target forwards cover the anchor and up to seven draft proposals.
const shortTargetRows = 8
// projectTarget keeps the same matrix shape for short prefill, ordinary
// decode, and draft verification. Different MLX kernels round BF16 results
// differently, and the routed experts can amplify that difference. Flatten
// requests before partitioning the rows so joining a batch cannot change the
// kernel either. Larger prefill forwards keep the usual projection path.
func projectTarget(projection *nn.Linear, x *mlx.Array) *mlx.Array {
if x.NumDims() != 3 || x.Dim(1) > shortTargetRows {
return projection.Forward(x)
}
rows, tokens, hidden := x.Dim(0), x.Dim(1), x.Dim(2)
total := rows * tokens
if total == 0 {
return projection.Forward(x)
}
x = x.Reshape(total, hidden)
var results []*mlx.Array
for begin := 0; begin < total; begin += shortTargetRows {
end := min(total, begin+shortTargetRows)
n := end - begin
tile := x.Slice(mlx.Slice(begin, end), mlx.Slice())
if n < shortTargetRows {
tile = mlx.PadConstant(tile, []int{0}, []int{0}, []int{shortTargetRows - n})
}
result := projection.Forward(tile)
if n < shortTargetRows {
result = result.Slice(mlx.Slice(0, n), mlx.Slice())
}
results = append(results, result)
}
out := results[0]
if len(results) > 1 {
out = mlx.Concatenate(results, 0)
}
return out.Reshape(rows, tokens, out.Dim(1))
}
@@ -0,0 +1,55 @@
package inkling2
import (
"math/rand/v2"
"slices"
"testing"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
"github.com/ollama/ollama/mlxrunner/nn"
)
func TestTargetProjectionUsesConsistentRows(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
mlx.Scoped(func() {
const hidden, output = 2304, 128
rng := rand.New(rand.NewPCG(448, 1536))
values := func(n int) []float32 {
data := make([]float32, n)
for i := range data {
data[i] = rng.Float32() - 0.5
}
return data
}
input := mlx.FromValues(values(2*shortTargetRows*hidden), 2*shortTargetRows, hidden).AsType(mlx.DTypeBFloat16)
weight := mlx.FromValues(values(output*hidden), output, hidden).AsType(mlx.DTypeBFloat16)
bias := mlx.FromValues(values(output), output).AsType(mlx.DTypeBFloat16)
linear := nn.NewLinear(weight, bias)
var want []float32
for i := range 2 {
row := input.Slice(mlx.Slice(i*shortTargetRows, (i+1)*shortTargetRows), mlx.Slice())
want = append(want, linear.Forward(row).AsType(mlx.DTypeFloat32).Flatten(0, -1).Floats()...)
}
batched := projectTarget(linear, input.Reshape(2, shortTargetRows, hidden))
if got := batched.AsType(mlx.DTypeFloat32).Flatten(0, -1).Floats(); !slices.Equal(got, want) {
t.Fatal("joining two verification blocks changed their projection")
}
for tokens := 1; tokens <= shortTargetRows; tokens++ {
ids := input.Slice(mlx.Slice(0, tokens), mlx.Slice()).Reshape(1, tokens, hidden)
got := projectTarget(linear, ids).AsType(mlx.DTypeFloat32).Flatten(0, -1).Floats()
if !slices.Equal(got, want[:tokens*output]) {
t.Errorf("projection at width %d differs from width %d", tokens, shortTargetRows)
}
}
prefill := input.Reshape(1, 2*shortTargetRows, hidden)
got := projectTarget(linear, prefill).AsType(mlx.DTypeFloat32).Flatten(0, -1).Floats()
ordinary := linear.Forward(prefill).AsType(mlx.DTypeFloat32).Flatten(0, -1).Floats()
if !slices.Equal(got, ordinary) {
t.Error("larger prefill changed from the ordinary projection path")
}
})
})
}
+99
View File
@@ -0,0 +1,99 @@
package inkling2
import (
"math"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/nn"
)
const residualEpsilon = 1e-6
// mixResiduals attends across residual blocks independently at each token.
// A matrix of queries returns a separate mixture for each input projection.
func mixResiduals(sources []*mlx.Array, query *mlx.Array, normalizeValues bool) *mlx.Array {
if normalizeValues {
if mixed := mlx.BlockResidualMix(sources, query, residualEpsilon); mixed != nil {
return mixed
}
}
values := mlx.Stack(sources, -2).AsType(mlx.DTypeFloat32)
keys := mlx.RMSNormFn(values, nil, residualEpsilon)
if normalizeValues {
values = keys
}
single := query.NumDims() == 1
if len(sources) == 1 && single {
return values.Squeeze(-2)
}
if single {
query = query.ExpandDims(0)
}
query = mlx.MulScalar(query, float32(1/math.Sqrt(float64(keys.Dim(-1)))))
scores := mlx.Sum(mlx.Mul(keys.ExpandDims(-3), query.ExpandDims(-2)), -1, false)
weights := mlx.SoftmaxAxis(scores, -1, true).ExpandDims(-1)
mixed := mlx.Sum(mlx.Mul(values.ExpandDims(-3), weights), -2, false)
if single {
return mixed.Squeeze(-2)
}
return mixed
}
type residualStream struct {
blocks []*mlx.Array
partial *mlx.Array
}
func (s residualStream) mix(query *mlx.Array, normalizeValues bool) *mlx.Array {
return mixResiduals(append(s.blocks[:len(s.blocks):len(s.blocks)], s.partial), query, normalizeValues)
}
// The feed-forward input sees the attention update before the residual stream
// advances. Within a block that sum is normalized in FP32 without an intervening
// rounding to the activation dtype.
func (s residualStream) afterAttention(attention *mlx.Array, boundary bool) residualStream {
if boundary {
return residualStream{
blocks: append(s.blocks[:len(s.blocks):len(s.blocks)], s.partial),
partial: attention,
}
}
s.partial = mlx.Add(s.partial.AsType(mlx.DTypeFloat32), attention.AsType(mlx.DTypeFloat32))
return s
}
type messageGate struct {
Down *nn.Linear
Gain *nn.Linear
Forget *nn.Linear
GainForget *nn.Linear
}
func (g messageGate) apply(input, message *mlx.Array) *mlx.Array {
normalized := func(x *mlx.Array) *mlx.Array {
return mlx.RMSNormFn(x.AsType(mlx.DTypeFloat32), nil, residualEpsilon).AsType(mlx.DTypeBFloat16)
}
if g.GainForget != nil {
paired := normalized(mlx.Stack([]*mlx.Array{input, message}, -2)).Flatten(-2, -1)
compressed := projectTarget(g.Down, paired).AsType(mlx.DTypeFloat32)
expansion := projectTarget(g.GainForget, compressed)
width := input.Dim(-1)
gain := expansion.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(0, width))
forget := expansion.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(width, 2*width))
return compiledControllerMix(input, message, gain, forget)[0]
}
compressed := projectTarget(g.Down, mlx.Concatenate([]*mlx.Array{normalized(input), normalized(message)}, -1))
// The two expansion projections produce FP32 before applying tanh.
compressed = compressed.AsType(mlx.DTypeFloat32)
gain := projectTarget(g.Gain, compressed).Tanh()
forget := projectTarget(g.Forget, compressed).Tanh()
keep := mlx.AddScalar(mlx.MulScalar(forget, -1), 1)
return mlx.Add(mlx.Mul(input, keep), mlx.Mul(message, gain))
}
// Both output gates are FP32 up to the following layer's input normalization.
var compiledControllerMix = mlx.Compile("InklingLoopController", func(args ...*mlx.Array) []*mlx.Array {
input, message, gain, forget := args[0], args[1], args[2], args[3]
keep := mlx.AddScalar(mlx.MulScalar(forget.Tanh(), -1), 1)
return []*mlx.Array{mlx.Add(mlx.Mul(input, keep), mlx.Mul(message, gain.Tanh()))}
}, mlx.Shapeless())
+55
View File
@@ -0,0 +1,55 @@
package inkling2
import (
"math"
"slices"
"testing"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
)
func TestResidualMixPreservesIndependentQueries(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
mlx.Scoped(func() {
sources := []*mlx.Array{
mlx.FromValues([]float32{3, 0, 0, 5}, 1, 2, 2),
mlx.FromValues([]float32{0, 4, 7, 0}, 1, 2, 2),
}
queries := mlx.FromValues([]float32{1, 0, 0, 1}, 2, 2)
got := mixResiduals(sources, queries, true)
if !slices.Equal(got.Dims(), []int{1, 2, 2, 2}) {
t.Fatalf("residual mixture shape = %v, want [1 2 2 2]", got.Dims())
}
high := math.Sqrt2 / (1 + math.Exp(-1))
low := math.Sqrt2 - high
want := []float64{high, low, low, high, high, low, low, high}
values := got.Floats()
if len(values) != len(want) {
t.Fatalf("residual mixture produced %d values, want %d", len(values), len(want))
}
for i, value := range values {
if !(math.Abs(float64(value)-want[i]) <= 1e-5) {
t.Errorf("residual mixture element %d = %g, want %g", i, value, want[i])
}
}
})
})
}
func TestResidualMixUnnormalizedValues(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
mlx.Scoped(func() {
const width = 2304
zero := mlx.Zeros(mlx.DTypeBFloat16, 1, 2, width)
sources := []*mlx.Array{mlx.AddScalar(zero, 2), mlx.AddScalar(zero, 8)}
// Equal scores average the original values in this configuration.
got := mixResiduals(sources, mlx.Zeros(mlx.DTypeFloat32, width), false)
for i, value := range got.Floats() {
if value != 5 {
t.Fatalf("unnormalized residual[%d] = %g, want 5", i, value)
}
}
})
})
}
+254
View File
@@ -0,0 +1,254 @@
package inkling2
import (
"bytes"
"fmt"
"image"
"image/color"
"math"
"slices"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/model"
"github.com/ollama/ollama/mlxrunner/nn"
)
type visionConfig struct {
Patch int `json:"native_patch_size"`
Merge int `json:"adapter_merge_size"`
Temporal int `json:"temporal_patch_size"`
Projector int `json:"projection_hidden_dim"`
Width int `json:"hidden_size"`
Layers int `json:"num_hidden_layers"`
Heads int `json:"num_attention_heads"`
MLPRatio float64 `json:"mlp_ratio"`
Grid int `json:"posemb_grid_size"`
Epsilon float32 `json:"layer_norm_eps"`
ProjBias bool `json:"projector_bias"`
}
func (c visionConfig) validate() error {
if c.Patch <= 0 || c.Merge <= 0 || c.Temporal <= 0 || c.Projector <= 0 || c.Width <= 0 || c.Layers <= 0 ||
c.Heads <= 0 || c.Width%c.Heads != 0 || (c.Width/c.Heads)%4 != 0 || c.MLPRatio <= 0 || c.Grid <= 0 || c.Epsilon <= 0 {
return fmt.Errorf("invalid Inkling2 vision dimensions")
}
if c.Layers > maxLayerCount || c.Patch > math.MaxInt32/c.Merge {
return fmt.Errorf("Inkling2 vision layer count %d or patch dimensions %d × %d exceed their limit", c.Layers, c.Patch, c.Merge)
}
return nil
}
type imageGrid struct{ rows, cols int }
type visionEncoder struct {
config visionConfig
imageToken int32
Patch *nn.Linear
Class *mlx.Array
ClassOffset *mlx.Array
Positions *mlx.Array
PreNorm *nn.LayerNorm
Layers []visionLayer
Project *nn.Linear
Out *nn.Linear
}
type visionLayer struct {
Norm, FfNorm *nn.LayerNorm
Q, K, V, O *nn.Linear
Up, Down *nn.Linear
AttnScale *mlx.Array
FfScale *mlx.Array
}
// Inkling uses CLIP normalization before rounding the pixels to the vision
// tower's input dtype. The patch encoder converts these back to [-1,1].
var (
imageMean = []float32{0.48145466, 0.4578275, 0.40821073}
imageStd = []float32{0.26862954, 0.26130258, 0.27577711}
)
func (m *targetModel) PrepareMedia(segments []model.Segment) (*model.PreparedRequest, error) {
if m.Vision == nil {
return nil, fmt.Errorf("Inkling2 checkpoint does not have a vision encoder")
}
side := m.Vision.config.Patch * m.Vision.config.Merge
remaining := m.config.Context - 1 // leave a token for generation
for _, segment := range segments {
remaining -= len(segment.Tokens)
}
var prepared model.PreparedRequest
for i, segment := range segments {
if segment.Data == nil {
prepared.Tokens = append(prepared.Tokens, segment.Tokens...)
continue
}
if segment.Kind != "image" {
if segment.Kind == "" {
return nil, fmt.Errorf("unrecognized Inkling2 media at input segment %d", i)
}
return nil, fmt.Errorf("Inkling2 does not support %s inputs", segment.Kind)
}
info, _, err := image.DecodeConfig(bytes.NewReader(segment.Data))
if err != nil {
return nil, fmt.Errorf("read Inkling2 image dimensions: %w", err)
}
if info.Width <= 0 || info.Height <= 0 {
return nil, fmt.Errorf("invalid Inkling2 image dimensions %d × %d", info.Width, info.Height)
}
grid := imageGrid{rows: (info.Height-1)/side + 1, cols: (info.Width-1)/side + 1}
if grid.rows > remaining/grid.cols {
return nil, fmt.Errorf("Inkling2 image %d × %d exceeds the remaining context", info.Width, info.Height)
}
if grid.rows > math.MaxInt32/side || grid.cols > math.MaxInt32/side ||
grid.rows > math.MaxInt/3/side/side/grid.cols {
return nil, fmt.Errorf("Inkling2 image %d × %d exceeds representable dimensions", info.Width, info.Height)
}
tokens := grid.rows * grid.cols
remaining -= tokens
img, _, err := image.Decode(bytes.NewReader(segment.Data))
if err != nil {
return nil, fmt.Errorf("decode Inkling2 image: %w", err)
}
if bounds := img.Bounds(); bounds.Dx() != info.Width || bounds.Dy() != info.Height {
return nil, fmt.Errorf("Inkling2 image dimensions changed during decoding")
}
pixels := imagePixels(img, side, grid)
start := len(prepared.Tokens)
prepared.Tokens = append(prepared.Tokens, slices.Repeat([]int32{m.Vision.imageToken}, tokens)...)
prepared.Items = append(prepared.Items, model.PreparedItem{
Range: [2]int{start, len(prepared.Tokens)}, Source: i, Causal: true,
MediaData: pixels, Dims: []int{grid.rows * side, grid.cols * side, 3}, Opaque: grid,
})
}
return &prepared, nil
}
func imagePixels(img image.Image, tile int, grid imageGrid) []float32 {
b := img.Bounds()
height, width := grid.rows*tile, grid.cols*tile
pixels := make([]float32, height*width*3)
for y := range height {
for x := range width {
rgb := [3]int{-1, -1, -1}
if x < b.Dx() && y < b.Dy() {
p := color.NRGBAModel.Convert(img.At(b.Min.X+x, b.Min.Y+y)).(color.NRGBA)
bg := 204
if ((x/8)+(y/8))%2 == 1 {
bg = 153
}
alpha := int(p.A)
for channel, value := range [3]uint8{p.R, p.G, p.B} {
rgb[channel] = (int(value)*alpha + bg*(255-alpha) + 127) / 255
}
}
for channel, value := range rgb {
pixels[3*(y*width+x)+channel] = (float32(value)/255 - imageMean[channel]) / imageStd[channel]
}
}
}
return pixels
}
func (m *targetModel) EncodeMedia(item *model.PreparedItem, data *mlx.Array) *mlx.Array {
return m.Vision.encode(data, item.Opaque.(imageGrid))
}
func (m *targetModel) imageEmbeddings(b *batch.Batch, embeddings *mlx.Array) *mlx.Array {
for _, item := range b.Media {
if item.Features == nil {
continue
}
offset := int(b.SeqOffsets[item.Seq])
start := max(item.Pos, offset)
end := min(item.Pos+item.Features.Dim(0), offset+int(b.SeqQueryLens[item.Seq]))
if start >= end {
continue
}
feature := item.Features.Slice(mlx.Slice(start-item.Pos, end-item.Pos), mlx.Slice()).ExpandDims(0)
embeddings = embeddings.SliceUpdate(feature, mlx.Slice(item.Seq, item.Seq+1), mlx.Slice(start-offset, end-offset), mlx.Slice())
}
return embeddings
}
func (v *visionEncoder) encode(data *mlx.Array, grid imageGrid) *mlx.Array {
c := v.config
patchRows, patchCols := grid.rows*c.Merge, grid.cols*c.Merge
data = data.AsType(mlx.DTypeBFloat16)
mean := mlx.FromValues(imageMean, 3).AsType(mlx.DTypeBFloat16)
std := mlx.FromValues(imageStd, 3).AsType(mlx.DTypeBFloat16)
data = mlx.AddScalar(mlx.MulScalar(mlx.Add(mlx.Mul(data, std), mean), 2), -1)
// A still image has identical temporal frames, so their mean is the
// single preprocessed frame.
patches := data.Reshape(patchRows, c.Patch, patchCols, c.Patch, 3).Transpose(0, 2, 1, 3, 4)
h := v.Patch.Forward(patches.Reshape(patchRows*patchCols, c.Patch*c.Patch*3))
h = mlx.Add(h, interpolatePositions(v.Positions, c.Grid, patchRows, patchCols))
h = mlx.Concatenate([]*mlx.Array{mlx.Add(v.Class, v.ClassOffset).ExpandDims(0), h}, 0)
h = v.PreNorm.Forward(h)
cos, sin := imagePhases(patchRows, patchCols, c.Width/c.Heads)
for _, layer := range v.Layers {
h = layer.forward(h, cos, sin, c.Heads)
}
patchOutput := h.Slice(mlx.Slice(1, h.Dim(0)), mlx.Slice())
patchOutput = patchOutput.Reshape(grid.rows, c.Merge, grid.cols, c.Merge, c.Width).Transpose(0, 2, 1, 3, 4)
patchOutput = patchOutput.Reshape(grid.rows*grid.cols, c.Merge*c.Merge*c.Width)
return v.Out.Forward(mlx.GELU(v.Project.Forward(patchOutput)))
}
func interpolatePositions(table *mlx.Array, size, rows, cols int) *mlx.Array {
indices := make([]int32, 0, 4*rows*cols)
weights := make([]float32, 0, 4*rows*cols)
for row := range rows {
for col := range cols {
y := min(float64(size-1), max(0, (float64(row)+0.5)*float64(size)/float64(rows)-0.5))
x := min(float64(size-1), max(0, (float64(col)+0.5)*float64(size)/float64(cols)-0.5))
y0, x0 := int(y), int(x)
y1, x1 := min(y0+1, size-1), min(x0+1, size-1)
dy, dx := float32(y-float64(y0)), float32(x-float64(x0))
indices = append(indices, int32(y0*size+x0), int32(y0*size+x1), int32(y1*size+x0), int32(y1*size+x1))
weights = append(weights, (1-dy)*(1-dx), (1-dy)*dx, dy*(1-dx), dy*dx)
}
}
selected := table.TakeAxis(mlx.FromValues(indices, rows*cols, 4), 0).AsType(mlx.DTypeFloat32)
return mlx.Sum(mlx.Mul(selected, mlx.FromValues(weights, rows*cols, 4, 1)), 1, false).AsType(table.DType())
}
func imagePhases(rows, cols, headDim int) (cos, sin *mlx.Array) {
count := rows*cols + 1
x, y := make([]float32, count), make([]float32, count)
for i := range count - 1 {
x[i+1], y[i+1] = float32(i%cols+1), float32(i/cols+1)
}
frequencies := make([]float32, headDim/4)
for i := range frequencies {
frequencies[i] = float32(math.Pow(10000, -4*float64(i)/float64(headDim)))
}
freq := mlx.FromValues(frequencies, 1, len(frequencies))
angles := mlx.Concatenate([]*mlx.Array{mlx.Mul(mlx.FromValues(x, count, 1), freq), mlx.Mul(mlx.FromValues(y, count, 1), freq)}, -1)
return mlx.Cos(angles).ExpandDims(1), mlx.Sin(angles).ExpandDims(1)
}
func applyImageRotary(x, cos, sin *mlx.Array) *mlx.Array {
count, heads, dim := x.Dim(0), x.Dim(1), x.Dim(2)
values := x.AsType(mlx.DTypeFloat32)
even := values.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(0, dim, 2))
odd := values.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(1, dim, 2))
real := mlx.Sub(mlx.Mul(even, cos), mlx.Mul(odd, sin))
imag := mlx.Add(mlx.Mul(even, sin), mlx.Mul(odd, cos))
return mlx.Stack([]*mlx.Array{real, imag}, -1).Reshape(count, heads, dim).AsType(x.DType())
}
func (l visionLayer) forward(h, cos, sin *mlx.Array, heads int) *mlx.Array {
count, width := h.Dim(0), h.Dim(1)
dim := width / heads
n := l.Norm.Forward(h)
q := applyImageRotary(l.Q.Forward(n).Reshape(count, heads, dim), cos, sin).Transpose(1, 0, 2).ExpandDims(0)
k := applyImageRotary(l.K.Forward(n).Reshape(count, heads, dim), cos, sin).Transpose(1, 0, 2).ExpandDims(0)
v := l.V.Forward(n).Reshape(count, heads, dim).Transpose(1, 0, 2).ExpandDims(0)
a := mlx.FastScaledDotProductAttention(q, k, v, float32(1/math.Sqrt(float64(dim))), mlx.FastSDPANoWindow, "", nil)
a = a.Squeeze(0).Transpose(1, 0, 2).Reshape(count, width)
h = mlx.Add(h, mlx.Mul(l.O.Forward(a), l.AttnScale))
f := l.Down.Forward(mlx.GELU(l.Up.Forward(l.FfNorm.Forward(h))))
return mlx.Add(h, mlx.Mul(f, l.FfScale))
}
+43
View File
@@ -0,0 +1,43 @@
package inkling2
import (
"bytes"
"image"
"image/png"
"slices"
"strings"
"testing"
"github.com/ollama/ollama/mlxrunner/model"
)
func TestPrepareMediaChecksContextBeforeDecodingPixels(t *testing.T) {
var img bytes.Buffer
if err := png.Encode(&img, image.NewRGBA(image.Rect(0, 0, 21, 11))); err != nil {
t.Fatal(err)
}
m := targetModel{
config: textConfig{Context: 5},
Vision: &visionEncoder{config: visionConfig{Patch: 10, Merge: 2}, imageToken: 9},
}
segments := []model.Segment{
{Tokens: []int32{1}},
{Kind: "image", Data: img.Bytes()},
{Tokens: []int32{2}},
}
prepared, err := m.PrepareMedia(segments)
if err != nil {
t.Fatal(err)
}
if !slices.Equal(prepared.Tokens, []int32{1, 9, 9, 2}) || len(prepared.Items) != 1 ||
!slices.Equal(prepared.Items[0].Dims, []int{20, 40, 3}) {
t.Fatalf("unexpected padded image expansion: tokens %v, items %d", prepared.Tokens, len(prepared.Items))
}
// A PNG header is sufficient to reject the image when there is no room
// for its two tiles. The missing pixel data would otherwise fail decoding.
m.config.Context--
segments[1].Data = img.Bytes()[:33]
if _, err := m.PrepareMedia(segments); err == nil || !strings.Contains(err.Error(), "exceeds the remaining context") {
t.Fatalf("expected context error before pixel decoding, got %v", err)
}
}
+261
View File
@@ -0,0 +1,261 @@
package inkling2
import (
"fmt"
"slices"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/nn"
)
const textPrefix = "model.llm."
func (m *targetModel) LoadWeights(tensors map[string]*mlx.Array) error {
reader := weightReader{tensors: tensors}
c := m.config
embedding := reader.tensor(textPrefix+"embed.weight", c.VocabSize, c.HiddenSize)
output := reader.tensor(textPrefix+"unembed.weight", c.VocabSize, c.HiddenSize)
m.EmbedNorm = reader.tensor(textPrefix+"embed_norm.weight", c.HiddenSize)
m.OutputNorm = reader.tensor(textPrefix+"norm.weight", c.HiddenSize)
m.OutputQuery = reader.tensor(textPrefix+"attn_res.output_query", c.HiddenSize)
if reader.err != nil {
return reader.err
}
m.Embed = nn.NewEmbedding(embedding)
// Retain complete BF16 tiles beside the FP32 fallback for short projections.
const compactVocab = 200058
const paddedVocab = (compactVocab + 7) / 8 * 8
if m.fp32Output && c.UnpaddedVocab == compactVocab && c.HiddenSize == 2304 &&
output.DType() == mlx.DTypeBFloat16 && output.Dim(0) >= paddedVocab && mlx.SupportsBF16WeightMatmul() {
m.CompactOutput = output.Slice(mlx.Slice(0, paddedVocab), mlx.Slice())
}
output = output.Slice(mlx.Slice(0, c.UnpaddedVocab), mlx.Slice())
if m.fp32Output {
output = output.AsType(mlx.DTypeFloat32)
}
m.Output = nn.NewLinear(output, nil)
var queries, kvQueries *mlx.Array
if c.Loop != nil {
rows := 2 * (c.Loop.End - c.Loop.Start)
queries = reader.tensor(textPrefix+"middle_cycle_cross_pass_queries", rows, c.HiddenSize)
kvQueries = reader.tensor(textPrefix+"middle_cycle_cross_pass_kv_queries", rows, c.HiddenSize)
if reader.err != nil {
return reader.err
}
}
m.Layers = make([]decoderLayer, c.NumLayers)
for _, visit := range m.plan {
// One set of weights is shared by all visits of a physical layer.
if visit.pass == 0 {
m.Layers[visit.layer] = reader.layer(c, visit.layer, visit.local, queries, kvQueries)
}
}
if m.Vision != nil && reader.err == nil {
reader.vision(m.Vision, c.HiddenSize)
}
return reader.err
}
type weightReader struct {
tensors map[string]*mlx.Array
err error
}
func (r *weightReader) tensor(name string, shape ...int) *mlx.Array {
tensor := r.tensors[name]
if r.err == nil {
switch {
case tensor == nil:
r.err = fmt.Errorf("Inkling2 tensor %q is missing", name)
case !slices.Equal(tensor.Dims(), shape):
r.err = fmt.Errorf("Inkling2 tensor %q has shape %v, want %v", name, tensor.Dims(), shape)
}
}
return tensor
}
func (r *weightReader) linear(name string, out, in int) *nn.Linear {
return nn.NewLinear(r.tensor(name, out, in), nil)
}
func (r *weightReader) layer(c textConfig, index int, local bool, queries, kvQueries *mlx.Array) decoderLayer {
prefix := fmt.Sprintf("%slayers.%d.", textPrefix, index)
attention := r.attention(c, prefix+"attn.", local)
layer := decoderLayer{
Attention: attention,
AttentionOutput: r.shortConv(prefix+"attn_sconv", c.ConvTaps, c.HiddenSize, 0, 0),
FeedForwardNorm: r.tensor(prefix+"mlp_norm.weight", c.HiddenSize),
FeedForwardQuery: r.tensor(fmt.Sprintf("%sattn_res.mlp_queries.%d", textPrefix, index), c.HiddenSize),
FeedForwardOutput: r.shortConv(prefix+"mlp_sconv", c.ConvTaps, c.HiddenSize, 0, 0),
FeedForward: routedExperts{
Router: r.tensor(prefix+"mlp.gate.weight", c.Experts, c.HiddenSize),
GateUp: r.expertBank(prefix+"mlp.experts.w13_weight", c.Experts, 2*c.ExpertWidth, c.HiddenSize),
Down: r.expertBank(prefix+"mlp.experts.w2_weight", c.Experts, c.HiddenSize, c.ExpertWidth),
topK: c.TopK,
routeScale: c.RouteScale,
gateCap: c.GateCap,
upCap: c.UpCap,
},
}
if c.GateBias {
layer.FeedForward.Bias = r.tensor(prefix+"mlp.gate.bias", c.Experts)
}
if local {
norm := r.tensor(prefix+"attn_norm.weight", c.HiddenSize)
layer.AttentionNorm = []*mlx.Array{norm, norm, norm}
} else {
layer.AttentionNorm = make([]*mlx.Array, 3)
for i, projection := range []string{"q", "k", "v"} {
layer.AttentionNorm[i] = r.tensor(prefix+projection+"_input_norm.weight", c.HiddenSize)
}
}
if index > 0 {
shape := []int{3, c.HiddenSize}
if local {
shape = []int{c.HiddenSize}
}
layer.AttentionQuery = r.tensor(fmt.Sprintf("%sattn_res.attn_queries.%d", textPrefix, index-1), shape...)
}
if c.Loop != nil && index >= c.Loop.Start && index < c.Loop.End {
layer.MessageProjections = make([]messageGate, 4)
row := 2 * (index - c.Loop.Start)
q := queries.Slice(mlx.Slice(row, row+1), mlx.Slice())
kv := kvQueries.Slice(mlx.Slice(row, row+2), mlx.Slice())
ffn := queries.Slice(mlx.Slice(row+1, row+2), mlx.Slice())
layer.MessageQueries = mlx.Concatenate([]*mlx.Array{q, kv, ffn}, 0)
for i, name := range []string{"attn", "k", "v", "mlp"} {
stem := prefix + "controllers." + name + "."
gate := messageGate{
Down: r.linear(stem+"down_weight", c.Loop.GateRank, 2*c.HiddenSize),
Gain: r.linear(stem+"gain_weight", c.HiddenSize, c.Loop.GateRank),
Forget: r.linear(stem+"forget_weight", c.HiddenSize, c.Loop.GateRank),
}
if r.err == nil {
gate.Gain.Weight = gate.Gain.Weight.AsType(mlx.DTypeFloat32)
gate.Forget.Weight = gate.Forget.Weight.AsType(mlx.DTypeFloat32)
if mlx.SupportsPackedController() && c.Loop.GateRank == 64 && c.HiddenSize == 2304 {
gate.GainForget = nn.NewLinear(mlx.Concatenate([]*mlx.Array{gate.Gain.Weight, gate.Forget.Weight}, 0), nil)
gate.Gain, gate.Forget = nil, nil
}
}
layer.MessageProjections[i] = gate
}
}
return layer
}
func (r *weightReader) attention(c textConfig, prefix string, local bool) selfAttention {
dim, heads, kvHeads := c.HeadDim, c.Heads, c.KVHeads
relativeRange, window, dynamicHeads := c.RelativeRange, 0, kvHeads
if local {
dim, heads, kvHeads = c.LocalHeadDim, c.LocalHeads, c.LocalKVHeads
relativeRange, window, dynamicHeads = c.Window, c.Window, 0
}
width, kvWidth := dim*heads, dim*kvHeads
return selfAttention{
Query: r.linear(prefix+"wq_du.weight", width, c.HiddenSize),
Key: r.linear(prefix+"wk_dv.weight", kvWidth, c.HiddenSize),
Value: r.linear(prefix+"wv_dv.weight", kvWidth, c.HiddenSize),
Output: r.linear(prefix+"wo_ud.weight", c.HiddenSize, width),
Relative: r.linear(prefix+"wr_du.weight", heads*c.RelativeDim, c.HiddenSize),
Gate: r.linear(prefix+"gate_attn.weight", width, c.HiddenSize),
Sink: r.linear(prefix+"attn_sink_proj.weight", heads, c.HiddenSize),
PositionProjection: r.tensor(prefix+"rel_logits_proj.proj", c.RelativeDim, relativeRange),
// The manifest loader maps the publisher's .scale suffix to _scale.
QueryScale: r.tensor(prefix+"q_l2_clip_scale", heads, dim),
RelativeScale: r.tensor(prefix+"rel_l2_clip_scale", heads, c.RelativeDim),
KeyConv: r.shortConv(prefix+"k_sconv", c.ConvTaps, kvWidth, dynamicHeads, c.HiddenSize),
ValueConv: r.shortConv(prefix+"v_sconv", c.ConvTaps, kvWidth, dynamicHeads, c.HiddenSize),
headDim: dim, heads: heads, kvHeads: kvHeads, window: window,
rmsEpsilon: c.NormEps, qkClip: c.QKClip, relativeClip: c.RelativeClip,
logFloor: c.LogFloor, logAlpha: c.LogAlpha,
}
}
func (r *weightReader) shortConv(prefix string, taps, channels, heads, inputWidth int) shortConv {
if heads > 0 {
return shortConv{
Weight: r.tensor(prefix+".static_w", taps, channels),
Dynamic: r.linear(prefix+".weight_proj", heads*taps, inputWidth),
heads: heads,
}
}
weight := r.tensor(prefix+".weight", channels, 1, taps)
if r.err != nil {
return shortConv{}
}
return shortConv{Weight: weight.Squeeze(1).Transpose(1, 0)}
}
func (r *weightReader) expertBank(name string, experts, rows, cols int) expertBank {
weight := r.tensors[name]
if weight == nil || weight.DType() != mlx.DTypeUint32 {
return expertBank{Weight: r.tensor(name, experts, rows, cols)}
}
result := expertBank{}
// The publisher's NVFP4 banks store packed E2M1 weights with an E4M3 scale per 16 columns in each row.
// Each expert's outer weight scale is its amax divided by the bank-wide denominator.
// MXFP8 banks have block scales and omit the per-expert maxima.
if r.tensors[name+"_amax"] != nil {
result.Weight = r.tensor(name, experts, rows, cols/8)
result.BlockScales = r.tensor(name+"_scale", experts, rows, cols/16)
result.Maxima = r.tensor(name+"_amax", experts)
result.Denominator = r.tensor(name+"_outer_scale_denominator", 1)
} else {
result.Weight = r.tensor(name, experts, rows, cols/4)
result.BlockScales = r.tensor(name+"_scale", experts, rows, cols/32)
}
return result
}
func (r *weightReader) vision(v *visionEncoder, textWidth int) {
const prefix = "model.visual."
c := v.config
embedding := prefix + "backbone.embeddings."
v.Patch = r.linear(embedding+"patch_embedding.weight", c.Width, c.Patch*c.Patch*3)
v.Class = r.tensor(embedding+"class_embedding", c.Width)
v.ClassOffset = r.tensor(embedding+"cls_position_embedding", c.Width)
v.Positions = r.tensor(embedding+"position_embedding", c.Grid*c.Grid, c.Width)
v.PreNorm = r.visionNorm(prefix+"backbone.ln_pre", c)
v.Project = r.projection(prefix+"proj_in", c.Projector, c.Merge*c.Merge*c.Width, c.ProjBias)
v.Out = r.projection(prefix+"proj_out", textWidth, c.Projector, c.ProjBias)
v.Layers = make([]visionLayer, c.Layers)
intermediate := int(float64(c.Width) * c.MLPRatio)
for i := range v.Layers {
layer := fmt.Sprintf("%sbackbone.layers.%d.", prefix, i)
attn := layer + "self_attn."
v.Layers[i] = visionLayer{
Norm: r.visionNorm(layer+"ln_1", c),
FfNorm: r.visionNorm(layer+"ln_2", c),
Q: r.projection(attn+"q_proj", c.Width, c.Width, true),
K: r.projection(attn+"k_proj", c.Width, c.Width, true),
V: r.projection(attn+"v_proj", c.Width, c.Width, true),
O: r.projection(attn+"out_proj", c.Width, c.Width, true),
Up: r.projection(layer+"mlp.c_fc", intermediate, c.Width, true),
Down: r.projection(layer+"mlp.c_proj", c.Width, intermediate, true),
AttnScale: r.tensor(layer+"ls_1.gamma", c.Width),
FfScale: r.tensor(layer+"ls_2.gamma", c.Width),
}
}
}
func (r *weightReader) visionNorm(prefix string, config visionConfig) *nn.LayerNorm {
return &nn.LayerNorm{
Weight: r.tensor(prefix+".weight", config.Width),
Bias: r.tensor(prefix+".bias", config.Width),
Eps: config.Epsilon,
}
}
func (r *weightReader) projection(prefix string, out, in int, withBias bool) *nn.Linear {
weight := r.tensor(prefix+".weight", out, in)
var bias *mlx.Array
if withBias {
bias = r.tensor(prefix+".bias", out)
}
if r.err != nil {
return nil
}
return nn.NewLinear(weight, bias)
}
+2 -1
View File
@@ -87,7 +87,8 @@ type BlockSelector interface {
// samples one of each row's unique candidate IDs, taking IDs and scores
// [N,K] and returning tokens [N] and probabilities [N,K]. Select returns
// tokens [B,L] and each position's candidate IDs and probabilities [B,L,K],
// which verification uses to correct the proposal.
// which verification uses to correct the proposal. For probabilities in
// full vocabulary order [B,L,V], Select may return nil IDs.
Select(hidden, logits, anchor *mlx.Array, choose func(ids, scores *mlx.Array) (tokens, probs *mlx.Array)) (tokens, ids, probs *mlx.Array)
}
+54
View File
@@ -848,6 +848,60 @@ func TestDecodeKVDraft(t *testing.T) {
})
}
func TestDecodeKVDraftFailedRound(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
predict := map[int32]int32{1: 2, 2: 3, 3: 4, 4: 5, 5: 6}
r := mtpTestRunner(t, predict, []int32{7}, sampler.Options{})
target := &schedulingModel{fakeMTPModel: fakeMTPModel{tok: r.Tokenizer, predict: predict}}
draft := &schedulingDraft{fakeMTPDraft: fakeMTPDraft{predict: predict}}
targetKV, draftKV := target.NewCaches(), draft.NewCaches()
r.Model, r.cache = target, newPrefixCache(append(targetKV, draftKV...))
defer r.cache.close()
r.spec = newSpeculation(r, pipelineSlot, draft, targetKV, draftKV)
req := request{
Tokens: []int32{1, 2, 3, 4},
Responses: make(chan CompletionResponse, 1),
CompletionRequest: CompletionRequest{Options: api.Options{NumPredict: 8}},
}
session := r.cache.begin(req.Tokens, nil)
spec := r.spec.open(req, nil)
pinDraftLimit(spec, 3)
p := r.newPrefill(session, spec, r.openMedia(req))
if ready, err := p.step(context.Background()); err != nil || !ready {
t.Fatalf("prefill: ready %t, err %v", ready, err)
}
engine, grammar := testDigitGrammar(t, `{"type":"string"}`)
r.grammarEngine = engine
d := spec.decoder(p.seed(), p.position, grammar)
if err := driveTestDecoder(context.Background(), r, req, session, d, 0); err == nil || !strings.Contains(err.Error(), "token mask rejects every vocabulary token") {
t.Fatalf("expected the digit-only tokenizer to reject the string grammar, got %v", err)
}
if !spec.failedVerification || r.cache.root == nil || targetKV[0].Offset() != 0 || draftKV[0].Offset() != 0 {
t.Fatalf("failed speculation remained available for reuse")
}
session = r.cache.begin(req.Tokens, nil)
if !slices.Equal(session.remaining, req.Tokens) {
t.Fatal("retry used failed state")
}
spec = r.spec.open(req, nil)
pinDraftLimit(spec, 3)
p = r.newPrefill(session, spec, r.openMedia(req))
if ready, err := p.step(context.Background()); err != nil || !ready {
t.Fatalf("retry prefill %t %v", ready, err)
}
r.Sampler.Add(pipelineSlot, sampler.Options{}, nil)
d = spec.decoder(p.seed(), p.position, nil)
req.Responses = make(chan CompletionResponse, 20)
if err := driveTestDecoder(context.Background(), r, req, session, d, 0); err != nil {
t.Fatalf("retry: %v", err)
}
if len(session.outputs) < 2 || !slices.Equal(session.outputs[:2], []int32{5, 6}) {
t.Fatalf("retry produced %v", session.outputs)
}
})
}
func TestDecodeKVDraftRejectionRebuildsFromTarget(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
// The draft mispredicts mid-chain: it proposes 6 where the target's own
+31 -14
View File
@@ -136,6 +136,31 @@ func resolveRecurrentConfig(opts []RecurrentOption) recurrentConfig {
// unsegmented conv.
func CausalConv1D(b *batch.Batch, input *mlx.Array, conv *Conv1d, convTail int, opts ...RecurrentOption) (out *mlx.Array, states []*mlx.Array) {
cfg := resolveRecurrentConfig(opts)
L := int32(input.Dim(1))
window := causalConvInput(b, input, cfg, L)
if cfg.convSiLU {
if w := depthwiseConvWeight(conv); w != nil {
out = mlx.DepthwiseConvSiLU(window, w, conv.Bias, int(L))
} else {
out = mlx.SiLU(conv.Forward(window))
}
} else {
out = conv.Forward(window)
}
return out, causalConvTails(b, window, convTail, cfg.splits, L)
}
// CausalConvWindow returns a window prefixed with the cached history and the
// input tails to save at snapshot boundaries. Use it for convolutions whose
// coefficients depend on the current token.
func CausalConvWindow(b *batch.Batch, input *mlx.Array, convTail int, opts ...RecurrentOption) (window *mlx.Array, states []*mlx.Array) {
cfg := resolveRecurrentConfig(opts)
L := int32(input.Dim(1))
window = causalConvInput(b, input, cfg, L)
return window, causalConvTails(b, window, convTail, cfg.splits, L)
}
func causalConvInput(b *batch.Batch, input *mlx.Array, cfg recurrentConfig, L int32) *mlx.Array {
var prior *mlx.Array
if cfg.history != nil {
prior = cfg.history.ConvState()
@@ -145,28 +170,20 @@ func CausalConv1D(b *batch.Batch, input *mlx.Array, conv *Conv1d, convTail int,
// concat is [prior(convTail); input]; each boundary tail is sliced from it
// below.
L := int32(input.Dim(1))
if mask := paddingMask(b, L); mask != nil {
zero := mlx.FromValue(float32(0)).AsType(input.DType())
input = mlx.Where(mlx.ExpandDims(mask, 2), input, zero)
}
concat := mlx.Concatenate([]*mlx.Array{prior, input}, 1)
if cfg.convSiLU {
if w := depthwiseConvWeight(conv); w != nil {
out = mlx.DepthwiseConvSiLU(concat, w, conv.Bias, int(L))
} else {
out = mlx.SiLU(conv.Forward(concat))
}
} else {
out = conv.Forward(concat)
}
return mlx.Concatenate([]*mlx.Array{prior, input}, 1)
}
func causalConvTails(b *batch.Batch, concat *mlx.Array, convTail int, splits []int, L int32) []*mlx.Array {
// Snapshot the conv tail at each segment boundary: interior splits in
// ascending order, then the forward end at L. Each boundary at offset O
// captures input positions [O-convTail, O) — the trailing convTail rows of
// the window through token O.
segs := segmentRanges(cfg.splits, L)
states = make([]*mlx.Array, 0, len(segs))
segs := segmentRanges(splits, L)
states := make([]*mlx.Array, 0, len(segs))
for _, s := range segs {
st := convStateAt(concat, b.SeqQueryLens, convTail, s.end)
if L > 1 {
@@ -175,7 +192,7 @@ func CausalConv1D(b *batch.Batch, input *mlx.Array, conv *Conv1d, convTail int,
}
states = append(states, st)
}
return out, states
return states
}
// depthwiseConvWeight returns the [C, K] weight view the fused conv kernel
+6
View File
@@ -311,6 +311,12 @@ func NewRowKVHistory(rows []*KVHistory) *KVHistory {
return &KVHistory{rows: rows}
}
// AsType returns a single sequence's keys and values in dtype for an attention
// operation. It preserves the cache mask and leaves its backing storage intact.
func (h *KVHistory) AsType(dtype mlx.DType) *KVHistory {
return NewKVHistory(h.K().AsType(dtype), h.V().AsType(dtype), h.applier)
}
// Rows returns the borrowed single-request histories, or nil for a shared
// rectangular history. Custom attention paths must dispatch these separately;
// the histories may have different lengths. Callers must not modify the slice.
+10
View File
@@ -12,6 +12,15 @@ import (
// additional temporary prefill storage on the older, smaller Mac.
const parallelWorkspace = 4 << 30
// num_ctx is a sizing hint. Requests can still use the full trained context.
func parallelContextLength(trained, requested int) int {
length := min(trained, 256*1024)
if requested > 0 {
length = min(length, requested)
}
return length
}
func defaultParallelism(fullContextBytes, headroom int64) int {
if fullContextBytes <= 0 || headroom <= parallelWorkspace {
return 1
@@ -50,5 +59,6 @@ func (r *Runner) configureParallelism() {
headroom := min(int64(limit)-int64(mlx.ActiveMemory()), memory.AvailableRAM)
r.parallel = defaultParallelism(r.fullContextBytes, headroom)
slog.Info("MLX automatic parallelism", "parallel", r.parallel, "context_length", r.contextLength,
"projected_context_length", parallelContextLength(r.contextLength, r.parallelContext),
"full_context_bytes", r.fullContextBytes, "workspace", parallelWorkspace, "headroom", headroom)
}
+20
View File
@@ -6,6 +6,26 @@ import (
"github.com/ollama/ollama/mlx/mlxtest"
)
func TestParallelContextLength(t *testing.T) {
for _, tc := range []struct {
name string
trained, requested, want int
}{
{"unknown model size", 0, 4096, 0},
{"short model", 8192, 0, 8192},
{"short requested window", 1 << 20, 4096, 4096},
{"request exceeds model", 8192, 32768, 8192},
{"large model default", 1 << 20, 0, 256 << 10},
{"large requested window", 1 << 20, 512 << 10, 256 << 10},
} {
t.Run(tc.name, func(t *testing.T) {
if got := parallelContextLength(tc.trained, tc.requested); got != tc.want {
t.Fatalf("projected context = %d, want %d", got, tc.want)
}
})
}
}
func TestDefaultParallelism(t *testing.T) {
const gib = 1 << 30
for _, tc := range []struct {
+85 -10
View File
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"log/slog"
"slices"
"sort"
"time"
@@ -23,6 +24,78 @@ func prefillChunkSize() int {
return 2 << 10
}
// prefillPlan holds the absolute batch ends for models that are sensitive to
// prefill width. Compute it from the prompt before looking at cached state.
type prefillPlan []int
func planPrefill(length int, items []mediaItem) prefillPlan {
end := length - 1 // leave the decode seed
offsets := prefillSnapshotOffsets(length)
for i, offset := range offsets {
offsets[i] = prefillSnapshotOffset(items, offset, 0)
}
slices.Sort(offsets)
var plan prefillPlan
for pos := 0; pos < end; {
n := min(prefillChunkSize(), end-pos)
for len(offsets) > 0 && offsets[0] <= pos {
offsets = offsets[1:]
}
if len(offsets) > 0 {
n = min(n, offsets[0]-pos)
}
pos += extendMediaChunk(items, pos, n, end)
plan = append(plan, pos)
}
return plan
}
// restoreOffset rounds down to a completed batch. An empty plan lets models
// with width-independent prefill reuse arbitrary prefix lengths.
func (p prefillPlan) restoreOffset(offset int) int {
if len(p) == 0 {
return offset
}
i, exact := slices.BinarySearch(p, offset)
if exact {
return offset
}
if i == 0 {
return 0
}
return p[i-1]
}
func prefillSnapshotOffsets(length int) []int {
var offsets []int
for offset := prefillSnapshotInterval; offset < length; offset += prefillSnapshotInterval {
offsets = append(offsets, offset)
}
const preThinking = 4
if end := length - preThinking; end > 0 {
offsets = append(offsets, end)
}
return offsets
}
// A longer prompt can reuse states at unchanged prefill widths. Keep the
// last full batch in addition to the usual periodic and terminal captures.
func (s *cacheSession) scheduleGenerationSnapshots() {
offsets := prefillSnapshotOffsets(len(s.inputs))
for i := len(s.prefill) - 1; i >= 0; i-- {
start := 0
if i > 0 {
start = s.prefill[i-1]
}
if end := s.prefill[i]; end-start == prefillChunkSize() {
offsets = append(offsets, end)
break
}
}
s.schedulePrefillSnapshots(offsets)
}
// Prepare tokenizes the prompt and validates it against the model's
// context length. It is safe to call from any goroutine. On success it
// populates request.Tokens and adjusts request.Options.NumPredict.
@@ -118,15 +191,7 @@ func (r *Runner) newPrefill(session *cacheSession, spec *speculationSession, med
// Request periodic snapshots during prefill and near the end of the
// prompt so that long prompts can be partially restored and
// thinking/generation can be retried without full reprocessing.
var snapshotOffsets []int
for offset := prefillSnapshotInterval; offset < len(session.inputs); offset += prefillSnapshotInterval {
snapshotOffsets = append(snapshotOffsets, offset)
}
const preThinking = 4
if end := len(session.inputs) - preThinking; end > 0 {
snapshotOffsets = append(snapshotOffsets, end)
}
session.schedulePrefillSnapshots(snapshotOffsets)
session.scheduleGenerationSnapshots()
// Free restored items' buffers now: on a full cache hit the loop never runs.
media.free(p.position)
return p
@@ -144,7 +209,17 @@ func (p *prefillCursor) step(ctx context.Context) (bool, error) {
if len(tokens)-p.processed <= 1 {
return true, nil
}
n := p.media.extendChunk(p.position, min(prefillChunkSize(), len(tokens)-p.processed-1), len(p.session.inputs)-1)
var n int
if plan := p.session.prefill; len(plan) > 0 {
i, atEnd := slices.BinarySearch(plan, p.position)
if atEnd {
i++
}
n = plan[i] - p.position
} else {
chunk := min(prefillChunkSize(), len(tokens)-p.processed-1)
n = p.media.extendChunk(p.position, chunk, len(p.session.inputs)-1)
}
mlx.Scoped(func() {
chunkIDs := mlx.FromValues(tokens[p.processed:p.processed+n], 1, n)
chunkMedia := p.media.batchMedia(p.position, n)
+76
View File
@@ -93,6 +93,82 @@ func mediaTestRunner(t *testing.T) *Runner {
}
}
func TestPrepareMediaTagTransport(t *testing.T) {
r := mediaTestRunner(t)
tok, err := tokenizer.LoadFromBytes([]byte(`{
"model":{"type":"BPE","vocab":{"a":0,"Ā":1,"[":2,"i":3,"m":4,"g":5,"-":6,"9":7,"]":8,"b":9},"merges":[]}
}`))
if err != nil {
t.Fatal(err)
}
r.Tokenizer = tok
attachment := []llm.MediaData{{ID: 0, Kind: llm.MediaKindImage, Data: []byte("img")}}
literal := "a\x00\x00[\x00img-9][img-9]"
literalIDs := []int32{0, 1, 1, 2, 1, 3, 4, 5, 6, 7, 8, 2, 3, 4, 5, 6, 7, 8}
rawPrefix := "a\x00\x00[\x00img-9]"
for _, tc := range []struct {
name string
req CompletionRequest
want []int32
}{
{
name: "raw text",
req: CompletionRequest{Prompt: literal},
want: literalIDs,
},
{
name: "raw with attachment",
req: CompletionRequest{Prompt: rawPrefix + "[img-0]b", Media: attachment},
want: append(slices.Clone(literalIDs[:11]), 70, 500, 500, 71, 9),
},
{
name: "rendered with attachment",
req: CompletionRequest{Prompt: literal + "[img-9]b", Media: []llm.MediaData{{ID: 9, Kind: llm.MediaKindImage, Data: []byte("img"), TagOffsets: []int{len(literal)}}}},
want: append(slices.Clone(literalIDs), 70, 500, 500, 71, 9),
},
} {
t.Run(tc.name, func(t *testing.T) {
req := &request{CompletionRequest: tc.req}
if err := r.Prepare(req); err != nil {
t.Fatal(err)
}
if !slices.Equal(req.Tokens, tc.want) {
t.Errorf("got tokens %v, want %v", req.Tokens, tc.want)
}
if len(req.MediaItems) != len(tc.req.Media) {
t.Errorf("got %d media items, want %d", len(req.MediaItems), len(tc.req.Media))
}
})
}
}
func TestPreparePositionedMediaOrder(t *testing.T) {
r := mediaTestRunner(t)
const prefix = "0[img-0]"
const tag0, tag1 = "[img-0]", "[img-1]"
prompt := prefix + tag1 + tag0 + tag1
media := []llm.MediaData{
{ID: 0, Kind: llm.MediaKindImage, Data: []byte{1}, TagOffsets: []int{len(prefix + tag1)}},
{ID: 1, Kind: llm.MediaKindImage, Data: []byte{2, 3}, TagOffsets: []int{len(prefix), len(prefix + tag1 + tag0)}},
}
req := &request{CompletionRequest: CompletionRequest{Prompt: prompt, Media: media}}
if err := r.Prepare(req); err != nil {
t.Fatal(err)
}
var sizes []int
for _, item := range req.MediaItems {
sizes = append(sizes, item.item.Opaque.(int))
}
if !slices.Equal(sizes, []int{2, 1, 2}) {
t.Fatalf("media payload sizes in prompt order = %v, want [2 1 2]", sizes)
}
req.Media[0].TagOffsets[0]++
if err := r.Prepare(req); err == nil {
t.Fatal("accepted an offset pointing inside a tag")
}
}
func TestPrepareExpandsMediaTags(t *testing.T) {
r := mediaTestRunner(t)
req := &request{
+152
View File
@@ -0,0 +1,152 @@
package mlxrunner
import (
"slices"
"testing"
"github.com/ollama/ollama/mlxrunner/model"
)
func TestPrefillPlan(t *testing.T) {
atomic := &model.PreparedItem{}
causal := &model.PreparedItem{Causal: true}
for _, tc := range []struct {
name string
length int
items []mediaItem
ends []int
}{
{"decode seed only", 1, nil, nil},
{"short prompt", 3, nil, []int{2}},
{"final snapshot", 2048, nil, []int{2044, 2047}},
{"periodic snapshot", 8200, nil, []int{2048, 4096, 6144, 8192, 8196, 8199}},
{"atomic media crosses batch", 4097, []mediaItem{{pos: 2000, length: 800, item: atomic}}, []int{2000, 4048, 4093, 4096}},
{"atomic media crosses snapshot", 11200, []mediaItem{{pos: 8000, length: 3000, item: atomic}}, []int{2048, 4096, 6144, 8000, 11000, 11196, 11199}},
{"atomic media crosses final snapshot", 2048, []mediaItem{{pos: 2038, length: 8, item: atomic}}, []int{2046, 2047}},
{"causal media can span batches", 4100, []mediaItem{{pos: 2040, length: 20, item: causal}}, []int{2048, 4096, 4099}},
} {
t.Run(tc.name, func(t *testing.T) {
if got := planPrefill(tc.length, tc.items); !slices.Equal(got, tc.ends) {
t.Fatalf("batch ends = %v, want %v", got, tc.ends)
}
})
}
}
func TestPrefixCacheAlignedPrefill(t *testing.T) {
const length = 2048
pc := newRecurrentEnv().pc
pc.alignPrefill = true
t.Cleanup(pc.close)
for _, tc := range []struct {
token int32
want int
}{{2, 0}, {3, 0}, {4, 0}, {3, length - 4}} {
prompt := slices.Repeat([]int32{tc.token}, length)
for i := range prompt[:30] {
prompt[i] = 1
}
s := pc.begin(prompt, nil)
if got := length - len(s.remaining); got != tc.want {
t.Fatalf("prompt %d reused %d tokens, want %d", tc.token, got, tc.want)
}
if tc.want == 0 && len(s.pendingSnapshots) != 0 {
t.Fatalf("prompt %d scheduled an interior capture: %v", tc.token, s.pendingSnapshots)
}
finishAlignedPrefill(s)
}
}
func TestPrefixCacheAlignedPrefillReusesCompatibleWidths(t *testing.T) {
for _, peer := range []bool{false, true} {
name := "local"
if peer {
name = "peer"
}
t.Run(name, func(t *testing.T) {
pc := newRecurrentEnv().pc
pc.alignPrefill = true
t.Cleanup(pc.close)
prompt := slices.Repeat([]int32{1}, prefillSnapshotInterval+8)
finishAlignedPrefill(pc.begin(prompt, nil))
// The shared periodic batch keeps its width. The first short
// terminal batch changes width with the longer prompt.
longer := append(prompt, slices.Repeat([]int32{2}, 25)...)
dest := pc
var peers []*prefixCache
if peer {
dest = newRecurrentEnv().pc
dest.alignPrefill = true
t.Cleanup(dest.close)
peers = append(peers, pc)
}
s := dest.begin(longer, nil, peers...)
if got := len(longer) - len(s.remaining); got != prefillSnapshotInterval {
t.Fatalf("longer prompt reused %d tokens, want %d", got, prefillSnapshotInterval)
}
finishAlignedPrefill(s)
})
}
}
func finishAlignedPrefill(s *cacheSession) {
s.scheduleGenerationSnapshots()
pos := len(s.inputs) - len(s.remaining)
for _, end := range s.prefill {
if end > pos {
feedAll(s.caches, s.inputs[pos:end])
pos = end
}
}
s.attachPrefillSnapshots()
feedAll(s.caches, s.inputs[pos:]) // decode consumes the final prompt token
s.close()
}
// An extension that changes the terminal batch still has the same completed
// full batches, including ones shifted by an indivisible media span.
func TestPrefixCacheRestoresLastFullPrefillBatch(t *testing.T) {
for _, tc := range []struct {
name string
media []mediaItem
want int
}{
{"raw", nil, 4096},
{"atomic media", []mediaItem{{pos: 1900, length: 400, fold: 42, item: &model.PreparedItem{}}}, 3948},
} {
for _, peer := range []bool{false, true} {
name := "local"
if peer {
name = "peer"
}
t.Run(tc.name+"/"+name, func(t *testing.T) {
src := newRecurrentEnv().pc
t.Cleanup(src.close)
src.alignPrefill = true
original := slices.Repeat([]int32{1}, 4400)
finishAlignedPrefill(src.begin(original, tc.media))
dst := src
var peers []*prefixCache
if peer {
dst = newRecurrentEnv().pc
t.Cleanup(dst.close)
dst.alignPrefill = true
peers = []*prefixCache{src}
}
longer := append(slices.Clone(original), 2, 3, 4)
s := dst.begin(longer, tc.media, peers...)
if got := len(longer) - len(s.remaining); got != tc.want {
t.Fatalf("extended prompt restored %d tokens, want %d", got, tc.want)
}
finishAlignedPrefill(s)
retry := dst.begin(longer, tc.media)
if got := len(longer) - len(retry.remaining); got != len(longer)-4 {
t.Fatalf("identical prompt restored %d tokens, want terminal snapshot at %d", got, len(longer)-4)
}
finishAlignedPrefill(retry)
})
}
}
}
+55 -14
View File
@@ -54,6 +54,7 @@ type prefixCache struct {
// draftLookahead is how far the draft caches' entries reference past
// their own slot; trie keys pack each token with its look-ahead (see key).
draftLookahead int
alignPrefill bool
}
// pendingSnapshot is a snapshot scheduled to be taken during prefill.
@@ -71,6 +72,7 @@ type cacheSession struct {
effInputs []uint32 // inputs' key alphabet, media folds applied
items []mediaItem
outputs []int32
prefill prefillPlan
caches []cache.Cache
remaining []int32
@@ -111,17 +113,19 @@ func (c *prefixCache) beginAt(inputs []int32, items []mediaItem, maxReuse int, p
c.ensureRoot()
effInputs := effectiveKeyTokens(inputs, items)
keys := c.key(effInputs)
plan := c.prefillPlan(len(inputs), items)
keys := plan.tag(c.key(effInputs))
matchPath, matched := findBestMatch(c.root, keys)
originalMatched := matched
// Generation leaves a decode seed; scoring can reuse the full row.
if matched > maxReuse {
matchPath, matched = findBestMatch(c.root, keys[:maxReuse])
}
reuse := min(matched, maxReuse)
// A match ending inside a non-causal media item resumes before it.
if item := insideAtomicItem(items, matched); item != nil {
matchPath, matched = findBestMatch(c.root, keys[:item.pos])
if item := insideAtomicItem(items, reuse); item != nil {
reuse = item.pos
}
if reuse = plan.restoreOffset(reuse); reuse < matched {
matchPath, matched = findBestMatch(c.root, keys[:reuse])
}
// Switch to the matched path, paging in/out as needed.
@@ -129,10 +133,15 @@ func (c *prefixCache) beginAt(inputs []int32, items []mediaItem, maxReuse int, p
// switchToPath aligns caches to a common offset
prefix := c.minCacheOffset()
if plan.restoreOffset(prefix) != prefix {
// A partial restore can stop at a split edge inside a batch.
c.switchToPath([]*trieNode{c.root}, 0)
prefix = 0
}
var source *prefixCache
var shared []*trieNode
for _, peer := range peers {
path, end := peer.sharedPrefix(keys, min(maxReuse, len(keys)), items)
path, end := peer.sharedPrefix(keys, min(maxReuse, len(keys)), items, plan)
if end > prefix {
source, shared, prefix = peer, path, end
}
@@ -141,6 +150,10 @@ func (c *prefixCache) beginAt(inputs []int32, items []mediaItem, maxReuse int, p
c.rewind(0)
c.restoreSnapshots(shared, prefix, 0)
prefix = c.alignCaches()
if plan.restoreOffset(prefix) != prefix {
c.freeAll()
prefix = 0
}
// The destination owns its trie and mutable state. Never install the
// source's nodes or snapshots in a second store.
c.activePath = []*trieNode{c.root}
@@ -160,6 +173,7 @@ func (c *prefixCache) beginAt(inputs []int32, items []mediaItem, maxReuse int, p
inputs: inputs,
effInputs: effInputs,
items: items,
prefill: plan,
caches: c.caches,
remaining: remaining,
}
@@ -207,6 +221,28 @@ func effectiveKeyTokens(tokens []int32, items []mediaItem) []uint32 {
return eff
}
func (c *prefixCache) prefillPlan(length int, items []mediaItem) prefillPlan {
if !c.alignPrefill {
return nil
}
if c.draftLookahead != 0 {
panic("prefill alignment requires a draft without look-ahead")
}
return planPrefill(length, items)
}
// tag encodes each prefill batch width in the first key of that batch. The
// upper 32 bits are available when caches have no draft look-ahead. Decode
// keys stay untagged, so they cannot match the start of a prefill batch.
func (p prefillPlan) tag(keys []trieKey) []trieKey {
start := 0
for _, end := range p {
keys[start] |= trieKey(end-start) << 32
start = end
}
return keys
}
// key packs (token i, token i+1) per restorable offset: draft caches
// pair each slot with the next token, so matching k keys verifies k+1
// tokens and every match is a valid restore point.
@@ -238,7 +274,7 @@ func (s *cacheSession) storedKeys() []trieKey {
eff = append(eff, uint32(t))
}
}
return s.cache.key(eff)
return s.prefill.tag(s.cache.key(eff))
}
// switchToPath transitions from the current active path to a new path,
@@ -299,7 +335,7 @@ func (c *prefixCache) switchToPath(newPath []*trieNode, matched int) {
// sharedPrefix returns complete saved edges that another slot can restore.
// Live state and partial edges are not borrowed: recurrent and wrapped sliding
// caches can only resume at a saved boundary. Missing edges break KV continuity.
func (c *prefixCache) sharedPrefix(keys []trieKey, maxReuse int, items []mediaItem) ([]*trieNode, int) {
func (c *prefixCache) sharedPrefix(keys []trieKey, maxReuse int, items []mediaItem, plan prefillPlan) ([]*trieNode, int) {
path, matched := findBestMatch(c.root, keys[:maxReuse])
end, count := 0, 1
for i := 1; i < len(path); i++ {
@@ -307,7 +343,7 @@ func (c *prefixCache) sharedPrefix(keys []trieKey, maxReuse int, items []mediaIt
if node.endOffset > matched || !hasAllSnapshots(node, c.caches) {
break
}
if insideAtomicItem(items, node.endOffset) == nil {
if plan.restoreOffset(node.endOffset) == node.endOffset && insideAtomicItem(items, node.endOffset) == nil {
end, count = node.endOffset, i+1
}
}
@@ -386,10 +422,7 @@ func (s *cacheSession) schedulePrefillSnapshots(offsets []int) {
c := s.cache
base := c.minCacheOffset()
for _, offset := range offsets {
offset -= c.draftLookahead
if item := insideAtomicItem(s.items, offset); item != nil {
offset = item.pos + item.length
}
offset = prefillSnapshotOffset(s.items, offset, c.draftLookahead)
if offset <= base || offset > len(s.inputs) {
continue
}
@@ -425,6 +458,14 @@ func (s *cacheSession) schedulePrefillSnapshots(offsets []int) {
}
}
func prefillSnapshotOffset(items []mediaItem, offset, lookahead int) int {
offset -= lookahead
if item := insideAtomicItem(items, offset); item != nil {
return item.pos + item.length
}
return offset
}
// attachPrefillSnapshots collects the snapshots captured during prefill and
// attaches them to the trie, materializing a node at each requested offset.
// Pending offsets are ascending and were scheduled in the same order, so the
+9 -4
View File
@@ -115,16 +115,21 @@ func (s *batchScheduler) matchingHistory(incoming queuedRequest, destination int
if c == nil || c.root == nil {
continue
}
cacheKeys := c.key(keys)
plan := c.prefillPlan(len(tokens), items)
cacheKeys := plan.tag(c.key(keys))
var path []*trieNode
var matched int
if i == destination {
path, matched = findBestMatch(c.root, cacheKeys[:min(maxReuse, len(cacheKeys))])
if item := insideAtomicItem(items, matched); item != nil {
path, matched = findBestMatch(c.root, cacheKeys[:item.pos])
reuse := matched
if item := insideAtomicItem(items, reuse); item != nil {
reuse = item.pos
}
if reuse = plan.restoreOffset(reuse); reuse < matched {
path, matched = findBestMatch(c.root, cacheKeys[:reuse])
}
} else {
path, matched = c.sharedPrefix(cacheKeys, min(maxReuse, len(cacheKeys)), items)
path, matched = c.sharedPrefix(cacheKeys, min(maxReuse, len(cacheKeys)), items, plan)
}
for _, n := range path {
preferred[n] = matched
+49
View File
@@ -787,3 +787,52 @@ func TestCompressionPreservesIdleFrontier(t *testing.T) {
}
})
}
func TestAdmissionPrefersRestorablePrefillWidth(t *testing.T) {
const firstBatch, common = 2048, 2100
for _, tc := range []struct {
name string
aligned bool
want int
}{
{"ordinary", false, common},
{"aligned", true, firstBatch},
} {
for _, peer := range []bool{false, true} {
t.Run(fmt.Sprintf("%s/peer=%v", tc.name, peer), func(t *testing.T) {
src, dst := newRecurrentEnv().pc, newRecurrentEnv().pc
t.Cleanup(src.close)
t.Cleanup(dst.close)
src.alignPrefill, dst.alignPrefill = tc.aligned, tc.aligned
tokens := slices.Repeat([]int32{1}, 4400)
// A complete snapshot inside the second prefill batch is usable only
// when the model's restoration contract accepts arbitrary widths.
simulateRequest(t, src, tokens, nil, firstBatch, common, 4096)
tokens[common] = 2
req := request{Tokens: tokens}
s := &batchScheduler{slots: []*batchSlot{{cache: dst}, {cache: src}}}
wantSlot := 1
if peer {
s.slots[1].request = &batchRequest{finished: true}
wantSlot = 0
}
dest := s.selectSlot(req)
if dest != wantSlot {
t.Fatalf("selected slot %d, want %d", dest, wantSlot)
}
longest := 0
for _, n := range s.matchingHistory(req, dest) {
longest = max(longest, n)
}
if longest != tc.want {
t.Fatalf("preferred %d tokens under pressure, want %d", longest, tc.want)
}
session := s.slots[dest].cache.begin(tokens, nil, s.slots[1-dest].cache)
defer session.close()
if got := len(tokens) - len(session.remaining); got != longest {
t.Fatalf("restored %d tokens, preferred %d", got, longest)
}
})
}
}
}
+4 -3
View File
@@ -104,7 +104,8 @@ type queuedRequest interface {
type Runner struct {
parallel int
fullContextBytes int64 // Estimated per-client storage at the model context limit.
parallelContext int
fullContextBytes int64 // Estimated per-client storage at the projected context size.
Model model.Model
weights *mlx.Scope
Tokenizer *tokenizer.Tokenizer
@@ -227,7 +228,7 @@ func (r *Runner) loadModel(modelName string) (weights []*mlx.Array, err error) {
r.spec = newSpeculation(r, pipelineSlot, draftModel, caches, draftCaches)
var capacity int
if r.parallel <= 0 && mlx.MetalIsAvailable() {
capacity = r.contextLength
capacity = parallelContextLength(r.contextLength, r.parallelContext)
}
width, fullContextBytes := modelShapes(m, draftModel, capacity)
r.fullContextBytes = fullContextBytes
@@ -259,7 +260,7 @@ func newDraftCaches(draft model.DraftModel) []cache.Cache {
// modelShapes inspects the existing one-token load graph without evaluating it.
// Cache dimensions come from the same forward used for inference, including the
// drafter. Budget the actual model limit: num_ctx is only a soft limit in MLX.
// drafter, at the projected context size.
func modelShapes(m model.Model, draft model.DraftModel, tokens int) (width int, fullContextBytes int64) {
mlx.Scoped(func() {
caches := m.NewCaches()
+72 -12
View File
@@ -14,6 +14,11 @@ import (
"github.com/ollama/ollama/mlxrunner/sample"
)
// snapshotAlignedPrefill keeps prefill batch widths consistent across restores.
type snapshotAlignedPrefill interface {
AlignPrefillToSnapshots()
}
type batchSlot struct {
id int
cache *prefixCache
@@ -86,12 +91,19 @@ type batchDrafting struct {
func (b *batchDrafting) reset() {
b.requests = nil
b.interrupt()
}
// Interleaved work invalidates the timing sample. The same ready requests
// can still finish their scheduled probe on the next complete decode round.
func (b *batchDrafting) interrupt() {
b.started = time.Time{}
}
func (b *batchDrafting) begin(slots []*batchSlot) *depthController {
requests := make([]*batchRequest, len(slots))
size := draftBatchSize{rows: len(slots)}
block := false
for i, slot := range slots {
req := slot.request
if req.spec == nil || req.spec.fixedDepth {
@@ -101,6 +113,7 @@ func (b *batchDrafting) begin(slots []*batchSlot) *depthController {
requests[i] = req
if req.spec.enabled {
size.drafting++
block = req.spec.depth.block
}
}
if size.drafting == 0 {
@@ -117,8 +130,15 @@ func (b *batchDrafting) begin(slots []*batchSlot) *depthController {
c.drafterLimit = slots[0].speculation.drafter.draftLimit()
b.depths[size] = c
}
same := slices.Equal(requests, b.requests)
if block && !same {
// The batch shape keeps its measured costs. A different group starts
// a fresh probe schedule and brings its own per-request acceptance.
c = c.forBlock()
b.depths[size] = c
}
now := time.Now()
if !b.started.IsZero() && slices.Equal(requests, b.requests) {
if !b.started.IsZero() && same {
if b.drafts == b.previousDrafts {
c.cost.observe(b.drafts, now.Sub(b.started))
}
@@ -133,6 +153,33 @@ func (b *batchDrafting) begin(slots []*batchSlot) *depthController {
return c
}
// A block verifier uses one width for all drafting rows. Its throughput is the
// sum of their expected committed tokens plus one for each plain row, divided
// by the measured cost of the whole batch at that width.
func (b *batchDrafting) next(c *depthController) {
if !c.block {
c.next()
return
}
frontier := 0
for _, req := range b.requests {
if req.spec.enabled {
frontier = max(frontier, req.spec.depth.frontier())
}
}
c.nextFor(min(frontier+1, c.drafterLimit), func(n int) float64 {
var tokens float64
for _, req := range b.requests {
if req.spec.enabled {
tokens += req.spec.depth.acc.expectedCommitted(n)
} else {
tokens++
}
}
return tokens
})
}
func (r *Runner) onMLX(ctx context.Context, f func() error) error {
if r.mlxThread != nil {
return r.mlxThread.Do(ctx, f)
@@ -317,7 +364,8 @@ func (s *batchScheduler) admit(pending queuedRequest) bool {
// available slot. A completed response still draining to its reader is busy.
func (s *batchScheduler) selectSlot(pending queuedRequest) int {
var keys []uint32
if req, ok := pending.(request); ok {
req, generation := pending.(request)
if generation {
keys = effectiveKeyTokens(req.Tokens, req.MediaItems)
}
best, bestMatch := -1, -1
@@ -327,7 +375,9 @@ func (s *batchScheduler) selectSlot(pending queuedRequest) int {
}
matched := 0
if len(keys) > 0 && slot != nil && slot.cache != nil && slot.cache.root != nil {
_, matched = findBestMatch(slot.cache.root, slot.cache.key(keys))
plan := slot.cache.prefillPlan(len(req.Tokens), req.MediaItems)
_, matched = findBestMatch(slot.cache.root, plan.tag(slot.cache.key(keys)))
matched = plan.restoreOffset(matched)
}
if matched > bestMatch {
best, bestMatch = i, matched
@@ -355,6 +405,7 @@ func (s *batchScheduler) admitGeneration(request request, best int) {
}
slot.targets = targets
slot.cache = newPrefixCache(slices.Concat(targets, draft))
_, slot.cache.alignPrefill = s.r.Model.(snapshotAlignedPrefill)
slot.cache.limitBytes = s.r.snapshotLimit()
if s.r.spec != nil {
slot.speculation = newSpeculation(s.r, slot.id, s.r.spec.draft, targets, draft)
@@ -395,7 +446,12 @@ func (s *batchScheduler) finish(slot *batchSlot, err error) {
s.r.Sampler.Remove(slot.id)
}
req.spec.close()
req.session.close()
if req.spec != nil && req.spec.failedVerification {
// Discard uncommitted writes. Previously saved prefixes remain available on retry.
slot.cache.switchToPath([]*trieNode{slot.cache.root}, 0)
} else {
req.session.close()
}
if slog.Default().Enabled(req.request.Ctx, logutil.LevelTrace) {
slot.cache.dumpTree()
}
@@ -452,7 +508,7 @@ func (s *batchScheduler) step() bool {
slot := s.slots[i]
if slot != nil && slot.evaluation != nil {
s.nextPrefill = (i + 1) % len(s.slots)
s.drafting.reset()
s.drafting.interrupt()
s.stepEvaluation(slot)
progressed = true
break
@@ -461,7 +517,7 @@ func (s *batchScheduler) step() bool {
continue
}
req := slot.request
s.drafting.reset()
s.drafting.interrupt()
before := req.prefill.processed
ready, err := req.prefill.step(req.request.Ctx)
progressed = progressed || req.prefill.processed != before
@@ -508,7 +564,7 @@ func (s *batchScheduler) step() bool {
break
}
if s.decodeSpeech() {
s.drafting.reset()
s.drafting.interrupt()
progressed = true
}
var ready []*batchSlot
@@ -596,7 +652,7 @@ func (s *batchScheduler) decode(ready []*batchSlot, active int) error {
d.s.lastRoundStart = time.Time{}
d.s.prevDrafts, d.s.roundDrafts = -1, -1
if d.inner != nil {
s.drafting.reset()
s.drafting.interrupt()
results, err := d.resume()
if err == nil {
d.advance(results[len(results)-1])
@@ -607,14 +663,14 @@ func (s *batchScheduler) decode(ready []*batchSlot, active int) error {
remaining := req.output.limit - req.output.generated
candidates := d.s.drafter.propose(d.current.Token, min(limit, remaining-1))
if candidates == nil {
s.drafting.reset()
s.drafting.interrupt()
plain = append(plain, slot)
continue
}
mlx.AsyncEval(candidates.Arrays()...)
n := candidates.tokens.Dim(1)
if n != limit {
s.drafting.reset()
s.drafting.interrupt()
}
i := slices.IndexFunc(groups, func(g group) bool { return g.rounds[0].candidates.tokens.Dim(1) == n })
if i < 0 {
@@ -631,7 +687,11 @@ func (s *batchScheduler) decode(ready []*batchSlot, active int) error {
if out.err == nil {
d.s.recordRound(g.rounds[i].candidates.tokens.Dim(1), out.accepted)
if controller != nil {
controller.acc.observe(out.observed, out.accepted)
evidence := controller.acc
if controller.block {
evidence = d.s.depth.acc
}
evidence.observe(out.observed, out.accepted)
}
d.advance(out.results[len(out.results)-1])
}
@@ -645,7 +705,7 @@ func (s *batchScheduler) decode(ready []*batchSlot, active int) error {
if controller != nil && !s.drafting.started.IsZero() {
// Draining a parked pipeline does not execute the scheduled probe.
// Hold its depth until a complete round consumes it.
controller.next()
s.drafting.next(controller)
}
return err
}
+136
View File
@@ -845,6 +845,142 @@ func TestBatchSchedulerLearnsDraftDepth(t *testing.T) {
}
}
func TestBatchBlockDepthChoosesForCurrentRequests(t *testing.T) {
const width = 7
draft := &dflashDrafter{blockSize: width + 1}
row := func(enabled bool, accepted int) *batchSlot {
spec := &speculation{drafter: draft, depth: newDepthController()}
spec.depth.drafterLimit = width
session := &speculationSession{spec: spec, depth: spec.depth, enabled: enabled}
if enabled {
session.depth = spec.depth.forBlock()
for range acceptanceMinSamples {
session.depth.acc.observe(width, accepted)
}
}
return &batchSlot{speculation: spec, request: &batchRequest{spec: session}}
}
// One row accepts the entire block. The other rejects its first draft.
deep, shallow, plain := row(true, width), row(true, 0), row(false, 0)
var batch batchDrafting
choose := func(slots ...*batchSlot) *depthController {
c := batch.begin(slots)
if c == nil || !c.block {
t.Fatal("responsive block controller missing from the batch")
}
c.cost.observe(0, 10*time.Millisecond)
for n := 1; n < width; n++ {
c.cost.observe(n, 60*time.Millisecond)
}
c.cost.observe(width, 36*time.Millisecond)
batch.next(c)
return c
}
// For two drafting rows, full depth produces 9 tokens in 36 ms, against
// 2 in 10 ms when parked. Adding a plain peer reverses the decision.
if got := choose(deep, shallow).scheduled; got != width {
t.Fatalf("two drafting rows chose depth %d, want %d", got, width)
}
c := choose(plain, deep, shallow)
if c.scheduled != 0 {
t.Fatalf("batch with a plain row chose depth %d, want 0", c.scheduled)
}
// The same set retains its pending probe when resuming a parked pipeline.
c.scheduled = 3
batch.interrupt()
if got := batch.begin([]*batchSlot{plain, deep, shallow}); got != c || got.scheduled != 3 {
t.Fatal("incomplete round lost the pending probe for the same requests")
}
// Same number of rows and drafters, different request in the third slot.
replacement := row(true, width)
next := batch.begin([]*batchSlot{plain, deep, replacement})
if next == c || next.cost != c.cost || next.scheduled != width {
t.Fatal("new cohort must reuse the cost curve and start with a fresh block probe")
}
batch.next(next)
if next.scheduled != width {
t.Fatalf("two full-acceptance rows and a plain peer chose depth %d, want %d", next.scheduled, width)
}
}
func TestBatchSchedulerBlockAcceptanceFollowsEachRow(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
// The test selector always chooses token zero. Each target row repeats
// its own token, so one request always accepts and one always rejects.
predict := map[int32]int32{0: 0, 1: 1, 2: 2}
tok := newTestTokenizer(t, []int32{7})
m := &schedulingModel{fakeMTPModel: fakeMTPModel{tok: tok, predict: predict}}
r := &Runner{Model: m, Tokenizer: tok, Sampler: sample.New(4096), parallel: 3}
r.cache = newPrefixCache(m.NewCaches())
selector := &selectedBlockDraft{&fakeBlockDraft{predict: predict, blockSize: 8, maskToken: 7}}
draft := &adaptiveBlockSelector{&observeProposalRows{selectedBlockDraft: selector}}
r.spec = newSpeculation(r, pipelineSlot, draft, r.cache.caches, nil)
s := &batchScheduler{r: r, slots: make([]*batchSlot, 3)}
defer func() {
for _, slot := range s.slots {
if slot.request != nil {
s.finish(slot, context.Canceled)
}
slot.cache.close()
}
r.cache.close()
r.Sampler.Free()
}()
mlx.Scoped(func() {
for id := range 3 {
s.admit(request{
Ctx: context.Background(), Tokens: []int32{int32(id), int32(id)}, Responses: make(chan CompletionResponse, 256),
CompletionRequest: CompletionRequest{Options: api.Options{NumPredict: 256}},
SamplerOpts: sample.Options{Temperature: 0, Logprobs: id == 2},
})
}
})
for range 16 {
mlx.Scoped(func() { s.step() })
}
for i, slot := range s.slots {
session := slot.request.spec
if i == 2 {
if session.stats.drafted != 0 || len(session.depth.acc.seen) != 1 {
t.Fatal("logprobs row drafted or learned acceptance")
}
continue
}
a := session.depth.acc
wantRate := 0.0
if i == 0 {
wantRate = 1
}
if len(a.seen) < 2 || a.seen[1] == 0 || a.rate[1] != wantRate {
t.Fatalf("row %d acceptance rates %v, seen %v", i, a.rate, a.seen)
}
}
// Block the rejecting row's output, then let it rejoin. Its evidence
// stays with the request while the other rows run with their own costs.
blocked := s.slots[1].request
responses := blocked.request.Responses
blocked.request.Responses = make(chan CompletionResponse)
oldCosts := s.drafting.depths[draftBatchSize{rows: 3, drafting: 2}].cost
for range 3 {
mlx.Scoped(func() { s.step() })
}
if len(s.drafting.requests) != 2 || slices.Contains(s.drafting.requests, blocked) {
t.Fatal("blocked request retained by the ready batch")
}
seen := blocked.spec.depth.acc.seen[1]
mlx.Scoped(func() { s.step() })
if blocked.spec.depth.acc.seen[1] != seen {
t.Fatal("blocked request learned from another row's verification")
}
blocked.request.Responses = responses
mlx.Scoped(func() { s.step() })
if !slices.Contains(s.drafting.requests, blocked) || s.drafting.depths[draftBatchSize{rows: 3, drafting: 2}].cost != oldCosts {
t.Fatal("returning request failed to rejoin the previous batch shape")
}
})
}
func TestGenerationReusesBusyPeer(t *testing.T) {
ctx := t.Context()
mlxtest.Run(t, func(t *mlxtest.T) {
+8 -5
View File
@@ -26,13 +26,15 @@ func Execute(args []string) error {
slog.SetDefault(logutil.NewLogger(os.Stderr, envconfig.LogLevel()))
var (
modelName string
port int
modelName string
port int
contextHint int
)
flagSet := flag.NewFlagSet("mlxrunner", flag.ExitOnError)
flagSet.StringVar(&modelName, "model", "", "Model name")
flagSet.IntVar(&port, "port", 0, "Port to listen on")
flagSet.IntVar(&contextHint, "ctx-size", 0, "Context size for automatic parallelism estimation")
_ = flagSet.Bool("verbose", false, "Enable debug logging")
flagSet.Parse(args)
@@ -63,9 +65,10 @@ func Execute(args []string) error {
defer cancelRunner()
runner := Runner{
parallel: int(envconfig.NumParallel()),
Requests: make(chan queuedRequest),
mlxThread: worker,
parallelContext: contextHint,
parallel: int(envconfig.NumParallel()),
Requests: make(chan queuedRequest),
mlxThread: worker,
}
if err := worker.Do(context.Background(), func() error {
+21 -10
View File
@@ -83,6 +83,12 @@ func newSpeculation(r *Runner, slotID int, draft model.DraftModel, targets, draf
s := &speculation{r: r, slotID: slotID, draft: draft, targets: targets, draftKV: draftKV, depth: newDepthController()}
if bd, ok := draft.(model.BlockDraft); ok {
s.drafter = newDFlashDrafter(s, bd)
if selector, ok := bd.(interface {
model.BlockSelector
AdaptiveDraftDepth() bool
}); ok {
s.depth.block = selector.AdaptiveDraftDepth()
}
} else {
s.drafter = newMTPDrafter(s)
}
@@ -100,9 +106,11 @@ type speculationSession struct {
limit int // current draft length
layout []any // the request's per-row layout state, stamped on every target forward
stats specStats
depth *depthController
// fixedDepth holds limit for the whole request, bypassing the depth controller.
fixedDepth bool
fixedDepth bool
failedVerification bool
// Cost sampling: each round's wall time (start to next start, spanning the
// next emit's sync) is attributed to its draft depth only when the depth
@@ -125,12 +133,15 @@ func (s *speculation) open(request request, layout []any) *speculationSession {
opts := request.SamplerOpts
enabled := !opts.Logprobs && opts.TopLogprobs == 0
spec := &speculationSession{spec: s, drafter: d, layout: layout, enabled: enabled, prevDrafts: -1, roundDrafts: -1}
spec := &speculationSession{spec: s, drafter: d, layout: layout, enabled: enabled, depth: s.depth, prevDrafts: -1, roundDrafts: -1}
if enabled {
spec.limit = s.depth.scheduled
if _, ok := s.draft.(model.BlockSelector); ok {
if s.depth.block {
spec.depth = s.depth.forBlock()
} else if _, ok := s.draft.(model.BlockSelector); ok {
spec.limit, spec.fixedDepth = dflash2Depth, true
return spec
}
spec.limit = spec.depth.scheduled
}
return spec
}
@@ -146,7 +157,7 @@ func (s *speculationSession) beginRound() {
now := time.Now()
if !s.lastRoundStart.IsZero() && s.roundDrafts >= 0 {
if s.roundDrafts == s.prevDrafts {
s.spec.depth.cost.observe(s.roundDrafts, now.Sub(s.lastRoundStart))
s.depth.cost.observe(s.roundDrafts, now.Sub(s.lastRoundStart))
}
s.prevDrafts = s.roundDrafts
}
@@ -167,9 +178,9 @@ func (s *speculationSession) endRound(drafted, accepted, observed int) {
return
}
if observed > 0 {
s.spec.depth.acc.observe(observed, accepted)
s.depth.acc.observe(observed, accepted)
}
s.limit = s.spec.depth.next()
s.limit = s.depth.next()
}
func (s *speculationSession) recordRound(drafted, accepted int) {
@@ -219,9 +230,8 @@ type speculativeDecoder struct {
scope *mlx.Scope // holds current across rounds
}
// decoder returns the decoder for this engine's session. A speculationSession that
// cannot draft (logprobs) has no depth controller and permanently parks,
// running the inner pipelined decoder whose reports keep the draft KV level.
// A logprobs session keeps its draft cache current using the pipelined decoder.
// Only sessions that can draft observe acceptance or train the depth controller.
func (s *speculationSession) decoder(seed *mlx.Array, position int, grammar *grammar) *speculativeDecoder {
current := sampler.Result{Token: seed}
scope := mlx.NewScope()
@@ -482,6 +492,7 @@ func (r *Runner) acceptDrafts(rounds []draftRound) []draftOutcome {
defer func() {
for i, round := range rounds {
if !committed[i] {
round.s.failedVerification = true
commitSpeculation(round.s.spec.targets, 0, draftCount, int(offsets[i])+1)
}
}
+44 -9
View File
@@ -1,6 +1,7 @@
package mlxrunner
import (
"context"
"slices"
"testing"
@@ -105,9 +106,21 @@ func TestAcceptDraftBatchGrammarFailureIsolated(t *testing.T) {
r.grammarEngine = engine
rounds := make([]draftRound, 2)
positions := []int{0, 0}
var owners [2]*prefixCache
var sessions [2]*cacheSession
for i := range rounds {
cs := m.NewCaches()
defer cs[0].Free()
owners[i] = newPrefixCache(cs)
if i == 0 {
// A failed continuation must preserve an unrelated saved turn in this slot.
previous := owners[i].begin([]int32{6, 6, 6, 6}, nil)
kv := cs[0].(*cache.KVCache)
data := mlx.FromValues([]float32{6, 6, 6}, 1, 1, 3, 1)
kv.Update(nil, data, data)
previous.close()
}
sessions[i] = owners[i].begin([]int32{1}, nil)
defer owners[i].close()
r.Sampler.Add(i, sample.Options{Temperature: 0}, nil)
drafts := []int32{2, 3}
rounds[i] = draftRound{
@@ -118,22 +131,44 @@ func TestAcceptDraftBatchGrammarFailureIsolated(t *testing.T) {
}
rounds[0].grammar = g
out := r.acceptDrafts(rounds)
if out[0].err == nil || len(out[0].results) != 0 || positions[0] != 0 || rounds[0].s.spec.targets[0].Offset() != 1 {
if out[0].err == nil || len(out[0].results) != 0 || positions[0] != 0 {
t.Fatalf("failed row: %+v position %d cache offset %d", out[0], positions[0], rounds[0].s.spec.targets[0].Offset())
}
if out[1].err != nil || !slices.Equal(resultIDs(out[1].results), []int32{2, 3, 4}) || positions[1] != 3 {
t.Fatalf("healthy row: %+v position %d", out[1], positions[1])
}
scheduler := &batchScheduler{r: r}
for i, round := range rounds {
if snapshots := round.s.spec.targets[0].TakeSnapshots(); len(snapshots) != 0 {
for _, snapshot := range snapshots {
if snapshot != nil {
snapshot.Close()
}
}
t.Errorf("row %d left %d snapshot slots", i, len(snapshots))
req := request{Ctx: context.Background(), Tokens: []int32{1}}
sessions[i].outputs = resultIDs(out[i].results)
active := &batchRequest{request: req, session: sessions[i], spec: round.s, output: newGenerationOutput(r, req, sessions[i], 0)}
scheduler.finish(&batchSlot{id: i, request: active, cache: owners[i]}, out[i].err)
if snapshots := owners[i].caches[0].TakeSnapshots(); len(snapshots) != 0 {
t.Fatalf("row %d left %d pending snapshots", i, len(snapshots))
}
}
if got := owners[0].minCacheOffset(); got != 0 {
t.Fatalf("failed slot kept %d rows", got)
}
failed := owners[0].begin([]int32{1, 2, 3, 4}, nil)
if len(failed.remaining) != 4 {
t.Fatal("failed continuation entered the prefix cache")
}
warm := owners[0].begin([]int32{6, 6, 6, 6}, nil)
if !slices.Equal(warm.remaining, []int32{6}) || !slices.Equal(owners[0].caches[0].State()[0].Floats(), []float32{6, 6, 6}) {
t.Fatal("older saved turn failed to restore")
}
retry := owners[0].begin([]int32{1, 2, 3, 4}, nil, owners[1])
if !slices.Equal(retry.remaining, []int32{4}) {
t.Fatalf("peer reuse left %v", retry.remaining)
}
got := owners[0].caches[0].State()[0].Floats()
if !slices.Equal(got, []float32{1, 2, 3}) {
t.Fatalf("peer restored %v", got)
}
if owners[1].minCacheOffset() != 3 {
t.Fatal("peer restore altered healthy slot")
}
})
}
+61 -40
View File
@@ -18,20 +18,16 @@ const depthProbeInterval = 4
const depthProbeIntervalMax = 512
// depthController drafts argmax_N EV(N) where EV(N) = committed(N) / cost(N), over
// depths from 0 (plain decode) up to one past the frontier, or the drafter's limit
// where that is shallower. The depth-0 floor lets it stop speculating when no draft
// pays; the frontier ceiling keeps it from scoring a depth on the optimistic
// inherited rate, so it climbs outward one position at a time as acceptance is
// measured rather than leaping deep.
// depths from plain decode up to one past the measured acceptance frontier,
// bounded by the drafter's capacity. A probe can observe a complete block.
//
// It holds the depth-selection state learned across requests — the target forward's
// per-depth cost curve, the drafts' per-position acceptance rates, the probe cadence,
// and the depth scheduled for the next round — persisted on the speculation so a fresh
// request starts at the proven-out depth instead of re-ramping from shallow.
// Sequential drafters carry the learned state across requests. Adaptive block
// selectors reuse the cost curve and observe acceptance in the current request.
type depthController struct {
cost *costModel
acc *acceptanceModel
probed bool // the previous round drafted a probe
block bool // sample a complete draft block when resuming from plain decode
// plainTokens is the number of plain-row tokens per drafting row in a
// mixed batch. Include them when comparing whole-batch throughput.
@@ -54,13 +50,25 @@ type depthController struct {
}
func newDepthController() *depthController {
return &depthController{cost: newCostModel(), acc: newAcceptanceModel(), probeInterval: depthProbeInterval}
return &depthController{cost: newCostModel(), acc: newAcceptanceModel(acceptanceMinSamples), probeInterval: depthProbeInterval}
}
// A block's hardware costs carry across requests. A full first probe can give
// acceptance evidence for every position in the new text in a single round.
func (c *depthController) forBlock() *depthController {
return &depthController{
cost: c.cost,
acc: newAcceptanceModel(1),
block: true,
drafterLimit: c.drafterLimit,
scheduled: c.drafterLimit,
probeInterval: depthProbeInterval,
}
}
func (c *depthController) frontier() int { return c.acc.frontier() }
// limit is the deepest depth the search considers: one past the frontier, held
// to what the drafter can produce.
// limit bounds the search at one beyond the measured acceptance frontier.
func (c *depthController) limit() int {
limit := c.frontier() + 1
if c.drafterLimit > 0 {
@@ -69,28 +77,44 @@ func (c *depthController) limit() int {
return limit
}
// next returns the draft depth for the upcoming step: the EV-optimal depth (held
// to the search limit), except periodically it probes one past the selection to
// refresh the next position up. The probe stays within that limit. The cadence
// doubles toward its cap while probes change nothing and resets on any selection
// change, giving the new selection a full interval to settle. The chosen depth is
// recorded in c.scheduled for the next request's open to consume.
func (c *depthController) next() (depth int) {
// next selects the best measured throughput and periodically probes a deeper
// draft. A parked block selector can probe all positions with one draft forward.
func (c *depthController) next() int {
return c.nextFor(c.limit(), c.expectedCommitted)
}
func (c *depthController) expectedCommitted(n int) float64 {
return c.acc.expectedCommitted(n) + c.plainTokens
}
// nextFor also serves a batch, where the expected output sums the contribution
// of each conversation and the measured cost covers the whole forward.
func (c *depthController) nextFor(limit int, expected func(int) float64) (depth int) {
defer func() { c.scheduled = depth }()
sel := c.selected()
sel := c.selected(limit, expected)
if sel != c.lastSelected {
c.probeInterval = depthProbeInterval
c.probeSince = 0
c.lastSelected = sel
} else if c.probed {
c.probeInterval = min(c.probeInterval*2, depthProbeIntervalMax)
maxInterval := depthProbeIntervalMax
if c.block {
// A transition from reasoning to predictable code can make a
// whole block profitable before the first position has been relearnt.
maxInterval = 2 * depthProbeInterval
}
c.probeInterval = min(c.probeInterval*2, maxInterval)
}
c.probed = false
c.probeSince++
if c.probeSince >= c.probeInterval {
c.probeSince = 0
if probe := min(sel+1, c.limit()); probe != sel {
probe := min(sel+1, limit)
if c.block && sel == 0 {
probe = c.drafterLimit
}
if probe != sel {
c.probed = true
return probe
}
@@ -101,7 +125,7 @@ func (c *depthController) next() (depth int) {
// at has no clean sample; draft the shallowest such depth to dwell there. Without
// this the controller stays at the one depth it can sit at without a transition
// (depth 0) and never learns that drafting pays on a deep-optimum model.
if seed := c.costSeedDepth(); seed >= 0 {
if seed := c.costSeedDepth(limit); seed >= 0 {
return seed
}
return sel
@@ -110,8 +134,7 @@ func (c *depthController) next() (depth int) {
// costSeedDepth is the shallowest depth within the search limit with no clean
// cost sample, or -1 if all are sampled; the bound keeps cost-seeding from
// outrunning the acceptance frontier or the drafter.
func (c *depthController) costSeedDepth() int {
limit := c.limit()
func (c *depthController) costSeedDepth(limit int) int {
for n := 0; n <= limit; n++ {
if !c.cost.sampled(n) {
return n
@@ -124,14 +147,13 @@ func (c *depthController) costSeedDepth() int {
// argmax within the search limit. The frontier bound keeps the inherited optimistic
// rate from making ever-deeper depths look best; the depth-0 floor lets it stop
// speculating. Returns 0 until the cost model can compare depths.
func (c *depthController) selected() int {
func (c *depthController) selected(limit int, expected func(int) float64) int {
if !c.cost.ready() {
return 0
}
limit := c.limit()
best, bestEV := 0, (c.acc.expectedCommitted(0)+c.plainTokens)/c.cost.cost(0)
best, bestEV := 0, expected(0)/c.cost.cost(0)
for n := 1; n <= limit; n++ {
if ev := (c.acc.expectedCommitted(n) + c.plainTokens) / c.cost.cost(n); ev > bestEV {
if ev := expected(n) / c.cost.cost(n); ev > bestEV {
best, bestEV = n, ev
}
}
@@ -234,17 +256,16 @@ const acceptanceEWMAAlpha = 0.1
// the ramp, since each depth is re-measured as it is drafted.
const acceptanceMinSamples = 10
// acceptanceModel learns the per-position conditional acceptance rate — the chance
// position i is accepted given every draft before it already was — as an EWMA, shared
// across requests so a fresh request keeps the proven-out frontier. Drift is handled
// by the EWMA forgetting, not by discarding the estimate.
// acceptanceModel estimates the chance that position i is accepted given that
// every preceding draft was accepted. Its EWMA follows changes in the text.
type acceptanceModel struct {
rate []float64 // EWMA acceptance rate given the prefix survived; index i is position i
seen []int // times position i was reached (warmup gate for rate)
minSamples int
rate []float64 // EWMA acceptance rate given the prefix survived; index i is position i
seen []int // times position i was reached (warmup gate for rate)
}
func newAcceptanceModel() *acceptanceModel {
return &acceptanceModel{rate: []float64{0}, seen: []int{0}}
func newAcceptanceModel(minSamples int) *acceptanceModel {
return &acceptanceModel{minSamples: minSamples, rate: []float64{0}, seen: []int{0}}
}
func (a *acceptanceModel) grow(i int) {
@@ -281,12 +302,12 @@ func (a *acceptanceModel) observe(drafted, accepted int) {
// position inherits the deepest trusted rate rather than zero, so the controller
// keeps exploring deeper instead of locking shallow on noise.
func (a *acceptanceModel) acceptance(i int) float64 {
if i >= 1 && i < len(a.seen) && a.seen[i] >= acceptanceMinSamples {
if i >= 1 && i < len(a.seen) && a.seen[i] >= a.minSamples {
return a.rate[i]
}
// Inherit the deepest trusted rate; fall back to optimistic 1 if none yet.
for j := i - 1; j >= 1; j-- {
if j < len(a.seen) && a.seen[j] >= acceptanceMinSamples {
if j < len(a.seen) && a.seen[j] >= a.minSamples {
return a.rate[j]
}
}
@@ -312,7 +333,7 @@ func (a *acceptanceModel) expectedCommitted(n int) float64 {
func (a *acceptanceModel) frontier() int {
f := 0
for i := 1; i < len(a.seen); i++ {
if a.seen[i] >= acceptanceMinSamples {
if a.seen[i] >= a.minSamples {
f = i
} else {
break
+39 -8
View File
@@ -5,6 +5,37 @@ import (
"time"
)
func TestAdaptiveBlockFollowsCurrentAcceptance(t *testing.T) {
slot := newDepthController()
slot.drafterLimit = 7
for n := 0; n <= slot.drafterLimit; n++ {
slot.cost.observe(n, time.Duration(40+10*n)*time.Millisecond)
}
c := slot.forBlock()
for _, phase := range []struct {
accept bool
want int
}{{false, 0}, {true, 7}, {false, 0}} {
for range 128 {
n := c.scheduled
accepted := 0
if phase.accept {
accepted = n
}
c.acc.observe(n, accepted)
c.next()
}
if got := c.selected(c.limit(), c.expectedCommitted); got != phase.want {
t.Fatalf("accept=%v: selected %d, want %d", phase.accept, got, phase.want)
}
}
next := slot.forBlock()
if next.cost != c.cost || next.acc == c.acc || next.frontier() != 0 || next.scheduled != 7 {
t.Fatalf("new request: depth %d, frontier %d, shared costs %v", next.scheduled, next.frontier(), next.cost == c.cost)
}
}
// driveDepthController runs the controller for n steps against a regime mirroring
// the real loop: next() picks a draft depth D; the regime reports the forward time
// at fused width D+1, fed to the cost model keyed by draft depth D, and how many of
@@ -26,7 +57,7 @@ func driveDepthController(c *depthController, n int, fwdMS func(width int) float
}
c.acc.observe(d, accepted)
}
return c.selected()
return c.selected(c.limit(), c.expectedCommitted)
}
// deterministicDraw turns a per-position acceptance rate into a reproducible,
@@ -201,7 +232,7 @@ func TestDepthControllerStaysParkedThroughHostStall(t *testing.T) {
// parked baseline remains credible and the controller does not start
// drafting against a phantom plain-decode cost.
cost.observe(0, 49*time.Millisecond)
if selected := c.selected(); selected != 0 {
if selected := c.selected(c.limit(), c.expectedCommitted); selected != 0 {
t.Errorf("a single stall-inflated depth-0 sample un-parked the controller: selected %d with cost(0)=%.1fms", selected, cost.cost(0))
}
}
@@ -238,8 +269,8 @@ func TestDepthControllerProbeBackoff(t *testing.T) {
steep := func(width int) float64 { return 16.0 + 15.0*float64(width-1) }
mediocre := deterministicDraw(func(int) float64 { return 0.6 })
driveDepthController(c, 600, steep, mediocre)
if c.selected() != 0 {
t.Fatalf("expected the controller to park at depth 0, got %d", c.selected())
if c.selected(c.limit(), c.expectedCommitted) != 0 {
t.Fatalf("expected the controller to park at depth 0, got %d", c.selected(c.limit(), c.expectedCommitted))
}
probes := driveCountingProbes(c, 4096, steep, mediocre)
if c.probeInterval != depthProbeIntervalMax {
@@ -283,7 +314,7 @@ func TestDepthControllerTracksAcceptanceDrift(t *testing.T) {
}
deepFavoring := func(int) float64 { return 0.95 } // deep readily accepted
driveDepthController(c, 400, bandwidthBoundCost, deterministicDraw(shallowFavoring))
shallow := c.selected()
shallow := c.selected(c.limit(), c.expectedCommitted)
if shallow > 4 {
t.Fatalf("expected shallow selection while deep acceptance is poor, got %d", shallow)
}
@@ -291,7 +322,7 @@ func TestDepthControllerTracksAcceptanceDrift(t *testing.T) {
// recovery runs at backed-off probe spacing until the first selection
// change snaps it back — the drive must span several backed-off intervals.
driveDepthController(c, 4096, bandwidthBoundCost, deterministicDraw(deepFavoring))
deep := c.selected()
deep := c.selected(c.limit(), c.expectedCommitted)
if deep <= shallow {
t.Errorf("expected selection to deepen after acceptance rose (was %d, now %d)", shallow, deep)
}
@@ -305,13 +336,13 @@ func TestDepthControllerIncludesPlainPeers(t *testing.T) {
for range acceptanceMinSamples {
c.acc.observe(1, 1)
}
if got := c.selected(); got != 1 {
if got := c.selected(c.limit(), c.expectedCommitted); got != 1 {
t.Fatalf("draft-only selection = %d, want 1", got)
}
// Three plain peers produce one token each in every round. Doubling
// the drafting row's output no longer pays for a 50% longer batch.
c.plainTokens = 3
if got := c.selected(); got != 0 {
if got := c.selected(c.limit(), c.expectedCommitted); got != 0 {
t.Fatalf("mixed selection = %d, want 0", got)
}
}
+1 -1
View File
@@ -68,7 +68,7 @@ func (s *speculationSession) logStats() {
// Log learned acceptance over the trusted positions [1, frontier] and
// expected throughput over the searched window [0, limit]; deeper
// depths have no data of their own.
d := s.spec.depth
d := s.depth
frontier := d.frontier()
rates := make([]string, 0, frontier)
for n := 1; n <= frontier; n++ {
+223
View File
@@ -0,0 +1,223 @@
package parsers
import (
"bytes"
"encoding/json"
"fmt"
"math"
"strings"
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/types/model"
)
const (
inklingModel = "<|message_model|>"
inklingText = "<|content_text|>"
inklingThought = "<|content_thinking|>"
inklingTool = "<|content_invoke_tool_json|>"
inklingToolText = "<|content_invoke_tool_text|>"
inklingToolError = "<|content_tool_error|>"
inklingEnd = "<|end_message|>"
inklingEndSample = "<|content_model_end_sampling|>"
inklingUnframed = "unframed"
)
type inkling2ToolArguments struct{ api.ToolCallFunctionArguments }
func (a *inkling2ToolArguments) UnmarshalJSON(data []byte) error {
if err := json.Unmarshal(data, &a.ToolCallFunctionArguments); err != nil {
return err
}
// The native argument decoder stores numbers as float64. Keep exact IDs
// in generated tool calls, including IDs in nested objects and arrays.
dec := json.NewDecoder(bytes.NewReader(data))
dec.UseNumber()
var fields map[string]any
if err := dec.Decode(&fields); err != nil {
return err
}
for key := range a.All() {
a.Set(key, inkling2ToolValue(fields[key]))
}
return nil
}
func inkling2ToolValue(value any) any {
switch v := value.(type) {
case json.Number:
f, _ := v.Float64() // the native decoder already validated the number
if math.Abs(f) >= 1<<53 && !strings.ContainsAny(v.String(), ".eE") {
return v
}
return f
case []any:
for i, item := range v {
v[i] = inkling2ToolValue(item)
}
case map[string]any:
for key, item := range v {
v[key] = inkling2ToolValue(item)
}
}
return value
}
type inkling2Parser struct {
buffer string
mode string
name string
callIndex int
suppressThinking bool
structured bool
}
func init() {
Register("inkling2", func() Parser { return &inkling2Parser{} })
}
func (p *inkling2Parser) Init(tools []api.Tool, _ *api.Message, think *api.ThinkValue) []api.Tool {
*p = inkling2Parser{}
p.suppressThinking = think != nil && (think.Value == false || think.Value == "none")
return tools
}
func (*inkling2Parser) HasToolSupport() bool { return true }
func (*inkling2Parser) HasThinkingSupport() bool { return true }
func (p *inkling2Parser) ThinkingClose() []string {
if p.mode == inklingText || (p.suppressThinking && p.mode != inklingThought) {
return nil
}
// A thought frame ends before the model opens the visible text frame.
// Structured output starts inside that text frame.
return []string{inklingModel + inklingText}
}
// StructuredOutputFrames aligns the stream parser and the grammar with the
// last frame in the rendered prompt. A custom template can open either frame.
func (p *inkling2Parser) StructuredOutputFrames(prompt string) *model.StructuredOutputFrames {
p.structured = true
const answer, thought = inklingModel + inklingText, inklingModel + inklingThought
prompt = strings.TrimRight(prompt, " \t\r\n")
frames := &model.StructuredOutputFrames{ContentOpen: answer}
switch {
case strings.HasSuffix(prompt, answer):
p.mode = inklingText
return nil
case strings.HasSuffix(prompt, thought):
p.mode = inklingThought
case strings.HasSuffix(prompt, inklingEnd), strings.HasSuffix(prompt, inklingEndSample):
// The publisher template ends at a message boundary.
if p.suppressThinking {
return frames
}
frames.ThinkingOpen = thought
default:
// An unframed custom prompt uses the ordinary format grammar.
if p.suppressThinking {
p.mode = inklingText
}
return nil
}
frames.ThinkingClose = inklingEnd
frames.ThinkingExcludes = p.PreservedTokens()
return frames
}
func (*inkling2Parser) PreservedTokens() []string {
return []string{inklingModel, inklingText, inklingThought, inklingTool, inklingToolText, inklingToolError, inklingEnd, inklingEndSample}
}
func (p *inkling2Parser) Add(s string, done bool) (string, string, []api.ToolCall, error) {
p.buffer += s
var content, thinking strings.Builder
var calls []api.ToolCall
for len(p.buffer) > 0 {
if p.structured && p.mode == inklingText {
// The grammar owns the JSON boundary. Marker spellings inside
// string values are part of the visible JSON.
content.WriteString(p.buffer)
p.buffer = ""
break
}
tokens := p.PreservedTokens()
atBoundary := p.mode == "" || p.mode == inklingEnd || p.mode == inklingEndSample
searchFrom := 0
if p.mode == inklingTool {
// The template allows literal control tokens in JSON strings.
// Only search for a terminator after the tool call object.
tokens = []string{inklingEnd, inklingEndSample}
searchFrom = findJSONEnd(p.buffer) + 1
if searchFrom == 0 && !done {
break
}
}
marker, index := "", len(p.buffer)
var keep int
for _, token := range tokens {
// A raw tool-text or error opener may follow a named header or
// start a frame by itself. Its spelling inside a body is text.
if (token == inklingToolText || token == inklingToolError) && p.mode != inklingModel {
if !atBoundary || !(strings.HasPrefix(p.buffer, token) || strings.HasPrefix(token, p.buffer)) {
continue
}
}
if i := strings.Index(p.buffer[searchFrom:], token); i >= 0 && searchFrom+i < index {
marker, index = token, searchFrom+i
}
keep = max(keep, overlap(p.buffer, token))
}
if marker == "" && !done {
if p.mode == inklingTool || p.mode == inklingModel {
break
}
index -= keep
}
body := p.buffer[:index]
p.buffer = p.buffer[index+len(marker):]
switch p.mode {
case inklingModel:
p.name = body
case inklingThought:
if !p.suppressThinking {
thinking.WriteString(body)
}
case inklingToolError:
// The model's tool-error frame is suppressed in Ollama responses.
case inklingTool:
var invocation struct {
Name *string `json:"name"`
Args inkling2ToolArguments `json:"args"`
}
if err := json.Unmarshal([]byte(body), &invocation); err != nil {
return content.String(), thinking.String(), calls, fmt.Errorf("invalid Inkling2 tool call: %w", err)
}
if invocation.Name == nil {
return content.String(), thinking.String(), calls, fmt.Errorf("missing Inkling2 tool name for header %q", p.name)
}
if p.name != "" && p.name != *invocation.Name {
return content.String(), thinking.String(), calls, fmt.Errorf("invalid Inkling2 tool name %q for header %q", *invocation.Name, p.name)
}
calls = append(calls, api.ToolCall{Function: api.ToolCallFunction{
Index: p.callIndex,
Name: *invocation.Name,
Arguments: invocation.Args.ToolCallFunctionArguments,
}})
p.callIndex++
default:
content.WriteString(body)
}
if marker == "" {
if atBoundary && body != "" {
p.mode = inklingUnframed
}
break
}
if marker != inklingTool {
p.name = ""
}
p.mode = marker
}
return content.String(), thinking.String(), calls, nil
}
+222
View File
@@ -0,0 +1,222 @@
package parsers
import (
"encoding/json"
"reflect"
"slices"
"testing"
"github.com/ollama/ollama/api"
)
func TestInkling2ThinkingClose(t *testing.T) {
for _, tc := range []struct {
name string
think *api.ThinkValue
want []string
}{
{name: "default", want: []string{inklingModel + inklingText}},
{name: "low", think: &api.ThinkValue{Value: "low"}, want: []string{inklingModel + inklingText}},
{name: "false", think: &api.ThinkValue{Value: false}},
{name: "none", think: &api.ThinkValue{Value: "none"}},
} {
t.Run(tc.name, func(t *testing.T) {
p := ParserForName("inkling2")
p.Init(nil, nil, tc.think)
if got := p.ThinkingClose(); !slices.Equal(got, tc.want) {
t.Fatalf("ThinkingClose() = %q, want %q", got, tc.want)
}
})
}
}
func TestInkling2FramedJSONPreservesMarkerText(t *testing.T) {
const answer = `{"text":"<|end_message|><|content_thinking|>"}`
response := inklingModel + inklingThought + "checking" + inklingEnd + inklingModel + inklingText + answer
for split := range len(response) + 1 {
p := inkling2Parser{}
p.StructuredOutputFrames(inklingEnd)
first, firstThought, firstCalls, err := p.Add(response[:split], false)
if err != nil || len(firstCalls) != 0 {
t.Fatalf("split %d first chunk: %v, %v", split, err, firstCalls)
}
last, lastThought, lastCalls, err := p.Add(response[split:], true)
if err != nil || len(lastCalls) != 0 || first+last != answer || firstThought+lastThought != "checking" {
t.Fatalf("split %d: content %q, thinking %q, calls %v, err %v", split, first+last, firstThought+lastThought, lastCalls, err)
}
}
}
func TestInkling2ToolIntegerPrecision(t *testing.T) {
for _, tc := range []struct {
raw string
want any
}{
{"9007199254740991", float64(1<<53 - 1)},
{"-9007199254740991", -float64(1<<53 - 1)},
{"9007199254740992", json.Number("9007199254740992")},
{"-9007199254740992", json.Number("-9007199254740992")},
{"9007199254740993", json.Number("9007199254740993")},
{"-9007199254740993", json.Number("-9007199254740993")},
{"1e20", float64(1e20)},
} {
var args inkling2ToolArguments
if err := json.Unmarshal([]byte(`{"id":`+tc.raw+`}`), &args); err != nil {
t.Fatal(err)
}
if got, _ := args.Get("id"); got != tc.want {
t.Errorf("%s decoded as %v (%T), want %v (%T)", tc.raw, got, got, tc.want, tc.want)
}
}
}
func TestInkling2ParserChunkBoundaries(t *testing.T) {
response := inklingModel + inklingThought + "check the source 🦉" + inklingEnd +
inklingModel + "lookup" + inklingTool + `{"name":"lookup","args":{"id":17,"parts":[true,null,"café",{"account":9007199254740993,"group":18446744073709551615}]}}` + inklingEnd +
inklingModel + "save" + inklingTool + `{"name":"save","args":{}}` + inklingEnd +
inklingModel + inklingText + "The answer is 17." + inklingEnd + inklingEndSample
for split := range len(response) + 1 {
p := ParserForName("inkling2")
p.Init(nil, nil, nil)
first, firstThought, firstCalls, err := p.Add(response[:split], false)
if err != nil {
t.Fatalf("split %d: %v", split, err)
}
last, lastThought, lastCalls, err := p.Add(response[split:], true)
if err != nil {
t.Fatalf("split %d: %v", split, err)
}
if first+last != "The answer is 17." || firstThought+lastThought != "check the source 🦉" {
t.Errorf("split %d: content %q, thinking %q", split, first+last, firstThought+lastThought)
}
calls := append(firstCalls, lastCalls...)
want := map[string]any{"id": float64(17), "parts": []any{true, nil, "café", map[string]any{"account": json.Number("9007199254740993"), "group": json.Number("18446744073709551615")}}}
if len(calls) != 2 || calls[0].Function.Name != "lookup" || !reflect.DeepEqual(calls[0].Function.Arguments.ToMap(), want) ||
calls[1].Function.Name != "save" || calls[1].Function.Arguments.Len() != 0 {
t.Errorf("split %d: tool calls %v", split, calls)
}
}
}
func TestInkling2ParserJinjaToolCalls(t *testing.T) {
// The Jinja template leaves literal control spellings in JSON strings and
// accepts an empty string as a function name.
const value = `before \"quoted\" <|end_message|> <|content_model_end_sampling|> after`
response := inklingModel + "lookup" + inklingTool + `{"name":"lookup","args":{"text":"` + value + `"}}` + inklingEnd +
inklingModel + inklingTool + `{"name":"","args":{}}` + inklingEnd +
inklingModel + inklingText + "Done." + inklingEnd + inklingEndSample
for split := range len(response) + 1 {
p := inkling2Parser{}
var content string
var calls []api.ToolCall
for i, chunk := range []string{response[:split], response[split:]} {
text, thinking, parsed, err := p.Add(chunk, i == 1)
if err != nil || thinking != "" {
t.Fatalf("split %d chunk %d: thinking %q, error %v", split, i, thinking, err)
}
content += text
calls = append(calls, parsed...)
}
if content != "Done." || len(calls) != 2 {
t.Fatalf("split %d: content %q, tool calls %v", split, content, calls)
}
text, ok := calls[0].Function.Arguments.Get("text")
if !ok || text != `before "quoted" <|end_message|> <|content_model_end_sampling|> after` ||
calls[0].Function.Name != "lookup" || calls[1].Function.Name != "" || calls[1].Function.Arguments.Len() != 0 {
t.Fatalf("split %d: tool calls %v", split, calls)
}
}
}
func TestInkling2SuppressesThinkingWhenDisabled(t *testing.T) {
response := inklingModel + inklingThought + "checking" + inklingEnd +
inklingModel + "lookup" + inklingTool + `{"name":"lookup","args":{}}` + inklingEnd +
inklingModel + inklingText + "Tokyo" + inklingEnd + inklingEndSample
for _, level := range []any{false, "none"} {
for split := range len(response) + 1 {
p := inkling2Parser{}
p.Init(nil, nil, &api.ThinkValue{Value: level})
first, firstThought, firstCalls, err := p.Add(response[:split], false)
if err != nil {
t.Fatalf("think %v split %d: %v", level, split, err)
}
last, lastThought, lastCalls, err := p.Add(response[split:], true)
if err != nil || first+last != "Tokyo" || firstThought != "" || lastThought != "" {
t.Fatalf("think %v split %d: content %q, thinking %q, error %v", level, split, first+last, firstThought+lastThought, err)
}
calls := append(firstCalls, lastCalls...)
if len(calls) != 1 || calls[0].Function.Name != "lookup" {
t.Fatalf("think %v split %d: tool calls %v", level, split, calls)
}
}
}
}
func TestInkling2ToolTextAndErrorFrames(t *testing.T) {
const literal = "quote " + inklingToolError + " and " + inklingToolText + " here"
for _, tc := range []struct{ name, input, want string }{
{"headerless", inklingToolText + "lookup x=1" + inklingEnd, "lookup x=1"},
{"named", inklingModel + "lookup" + inklingToolText + "lookup x=1" + inklingEnd, "lookup x=1"},
{"error", inklingModel + inklingToolError + "failed" + inklingEnd + inklingToolText + "retry", "retry"},
{"thought", inklingModel + inklingThought + literal + inklingEnd + inklingModel + inklingText + "answer", "answer"},
{"leading whitespace", "\n" + inklingModel + inklingThought + literal + inklingEnd + inklingToolText + "answer", "\nanswer"},
{"unframed", literal, literal},
{"text", inklingModel + inklingText + literal + inklingEnd, literal},
{"tool text", inklingToolText + literal + inklingEnd, literal},
} {
t.Run(tc.name, func(t *testing.T) {
for _, tools := range [][]api.Tool{nil, {{Type: "function", Function: api.ToolFunction{Name: "lookup"}}}} {
for split := range len(tc.input) + 1 {
p := ParserForName("inkling2")
p.Init(tools, nil, &api.ThinkValue{Value: false})
var text string
for i, chunk := range []string{tc.input[:split], tc.input[split:]} {
body, thinking, calls, err := p.Add(chunk, i == 1)
if err != nil || thinking != "" || len(calls) != 0 {
t.Fatalf("split %d chunk %d: thinking %q, calls %v, error %v", split, i, thinking, calls, err)
}
text += body
}
if text != tc.want {
t.Fatalf("split %d: content %q, want %q", split, text, tc.want)
}
}
}
})
}
}
func FuzzInkling2Parser(f *testing.F) {
f.Add(inklingModel+inklingThought+"checking"+inklingEnd+inklingModel+inklingText+"Tokyo"+inklingEnd, uint16(7), false)
f.Add(inklingModel+"lookup"+inklingTool+`{"name":"lookup","args":{"x":"<|end_message|>"}}`+inklingEnd, uint16(23), false)
f.Add(inklingModel+inklingTool+`{"name":`, uint16(9), false)
f.Add(inklingModel+inklingText+`{"text":"<|end_message|>"}`, uint16(37), true)
f.Add("0"+inklingEnd, uint16(3), true)
f.Fuzz(func(t *testing.T, input string, offset uint16, structured bool) {
if len(input) > 4096 {
t.Skip("input exceeds the fuzz case budget")
}
newParser := func() *inkling2Parser {
p := &inkling2Parser{}
if structured {
p.StructuredOutputFrames(inklingEnd)
}
return p
}
wantContent, wantThinking, wantCalls, wantErr := newParser().Add(input, true)
p := newParser()
split := int(offset) % (len(input) + 1)
content, thinking, calls, err := p.Add(input[:split], false)
if err == nil {
var tail, tailThinking string
var tailCalls []api.ToolCall
tail, tailThinking, tailCalls, err = p.Add(input[split:], true)
content += tail
thinking += tailThinking
calls = append(calls, tailCalls...)
}
if (err == nil) != (wantErr == nil) || content != wantContent || thinking != wantThinking || !reflect.DeepEqual(calls, wantCalls) {
t.Fatalf("split at %d changed parse: content %q, thinking %q, calls %v, error %v; want %q, %q, %v, %v", split, content, thinking, calls, err, wantContent, wantThinking, wantCalls, wantErr)
}
})
}
+269
View File
@@ -0,0 +1,269 @@
package renderers
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"regexp"
"strconv"
"strings"
"unicode"
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/types/model"
)
type inkling2Renderer struct {
useImgTags bool
imageOffsets map[int][]int
}
func (*inkling2Renderer) LeadingBOS() string { return "" }
// Native messages carry attachment bytes without a MIME type. MP3 can start
// directly with a frame sync when it has no ID3 tag for the MIME sniffer.
func inkling2Audio(data []byte) bool {
switch http.DetectContentType(data) {
case "audio/wave", "audio/mpeg":
return true
}
return len(data) >= 2 && data[0] == 0xff && data[1]&0xe0 == 0xe0
}
func (*inkling2Renderer) Thinking() *model.Thinking {
return &model.Thinking{
Values: []any{false, true, "none", "minimal", "low", "medium", "high", "xhigh", "max"},
Default: "high",
}
}
func inkling2Effort(think *api.ThinkValue) (string, error) {
if think == nil || think.Value == nil {
return "0.9", nil
}
value := think.Value
if name, ok := value.(string); ok {
// Python str.strip also removes the four ASCII information separators.
value = strings.TrimFunc(name, func(r rune) bool {
return unicode.IsSpace(r) || r >= 0x1c && r <= 0x1f
})
}
switch value {
case false, "none":
return "0", nil
case "minimal":
return "0.1", nil
case "low":
return "0.2", nil
case "medium":
return "0.7", nil
case true, "high":
return "0.9", nil
case "xhigh", "max":
return "0.99", nil
default:
return "", fmt.Errorf("Unknown reasoning_effort: %v", think.Value)
}
}
func inkling2Tools(tools []api.Tool) (string, error) {
specs := make([]map[string]any, 0, len(tools))
for _, tool := range tools {
raw, err := json.Marshal(tool.Function.Parameters)
if err != nil {
return "", err
}
// Jinja sorts keys recursively for tool declarations. UseNumber
// retains JSON number types when canonicalizing schema fields.
var parameters map[string]any
decoder := json.NewDecoder(bytes.NewReader(raw))
decoder.UseNumber()
if err := decoder.Decode(&parameters); err != nil {
return "", err
}
if tool.Function.Parameters.Type == "" {
delete(parameters, "type")
}
if parameters["properties"] == nil {
delete(parameters, "properties")
}
kind := tool.Type
if kind == "" {
kind = "function"
}
specs = append(specs, map[string]any{
"description": tool.Function.Description,
"name": tool.Function.Name,
"parameters": parameters,
"type": kind,
})
}
return PythonJSONCompact(specs)
}
var inkling2ImageMarker = regexp.MustCompile(`\[img-[0-9]+\]`)
// RenderInkling2WithImages records each attachment tag's byte offset in the
// prompt. Text may contain identical tags, including an entire image frame.
func RenderInkling2WithImages(messages []api.Message, tools []api.Tool, think *api.ThinkValue) (string, map[int][]int, error) {
r := inkling2Renderer{useImgTags: true, imageOffsets: make(map[int][]int)}
prompt, err := r.Render(messages, tools, think)
return prompt, r.imageOffsets, err
}
func (r *inkling2Renderer) writeContent(out *strings.Builder, role string, message api.Message, imageOffset int) error {
writeText := func(text string) {
out.WriteString(role + "<|content_text|>" + text + "<|end_message|>")
}
if len(message.Images) == 0 {
writeText(message.Content)
return nil
}
content := message.Content
var prefix strings.Builder
tags := make(map[string]int, len(message.Images))
for i := range message.Images {
tag := "[img-" + strconv.Itoa(imageOffset+i) + "]"
if !strings.Contains(content, tag) {
if before, after, ok := strings.Cut(content, "[img]"); ok {
content = before + tag + after
} else {
prefix.WriteString(tag)
}
}
tags[tag] = i
}
content = prefix.String() + content
previous := 0
for _, span := range inkling2ImageMarker.FindAllStringIndex(content, -1) {
marker := content[span[0]:span[1]]
i, ok := tags[marker]
if !ok {
continue
}
if inkling2Audio(message.Images[i]) {
return errors.New("Inkling 2 does not accept audio input")
}
if message.Role != "user" && message.Role != "tool" {
return errors.New("Image content is only supported for user and tool messages")
}
if span[0] > previous {
writeText(content[previous:span[0]])
}
out.WriteString(role + "<|content_image|>")
if r.imageOffsets != nil {
id := imageOffset + i
r.imageOffsets[id] = append(r.imageOffsets[id], out.Len())
}
if !r.useImgTags {
marker = "<|unused_200054|>"
}
out.WriteString(marker + "<|end_message|>")
previous = span[1]
}
if previous < len(content) {
writeText(content[previous:])
}
return nil
}
func (r *inkling2Renderer) Render(messages []api.Message, tools []api.Tool, think *api.ThinkValue) (string, error) {
var out strings.Builder
if len(tools) > 0 {
declaration, err := inkling2Tools(tools)
if err != nil {
return "", err
}
out.WriteString("<|message_system|>tool_declare<|content_xml|>" + declaration + "<|end_message|>")
}
writeEffort := func() error {
effort, err := inkling2Effort(think)
if err != nil {
return err
}
out.WriteString("<|message_system|><|content_text|>Thinking effort level: " + effort + "<|end_message|>")
return nil
}
effortEmitted := false
imageOffset := 0
toolCallNames := make(map[string]string)
for _, message := range messages {
if message.Role != "assistant" {
continue
}
for _, call := range message.ToolCalls {
if call.ID != "" {
toolCallNames[call.ID] += call.Function.Name
}
}
}
for _, message := range messages {
var role string
switch message.Role {
case "user":
role = "<|message_user|>"
case "assistant":
role = "<|message_model|>" + message.ToolName
case "system":
role = "<|message_system|>"
case "tool":
name := message.ToolName
if name == "" {
name = toolCallNames[message.ToolCallID]
}
role = "<|message_tool|>" + name
default:
return "", fmt.Errorf("Unknown message role: %s", message.Role)
}
if !effortEmitted && message.Role != "system" {
if err := writeEffort(); err != nil {
return "", err
}
effortEmitted = true
}
if message.Role == "assistant" && message.Thinking != "" {
out.WriteString(role + "<|content_thinking|>" + message.Thinking + "<|end_message|>")
}
if len(message.Images) > 0 || message.Content != "" || !(message.Role == "assistant" && (len(message.ToolCalls) > 0 || message.Thinking != "")) {
if err := r.writeContent(&out, role, message, imageOffset); err != nil {
return "", err
}
imageOffset += len(message.Images)
}
if message.Role == "assistant" {
for _, call := range message.ToolCalls {
if message.ToolName != "" && message.ToolName != call.Function.Name {
return "", fmt.Errorf("assistant name %s does not match its tool call %s", message.ToolName, call.Function.Name)
}
// The template sorts argument names; values retain the object
// order present in their JSON representation.
arguments := call.Function.Arguments.ToMap()
if arguments == nil {
arguments = map[string]any{}
}
args, err := PythonJSONCompact(arguments)
if err != nil {
return "", fmt.Errorf("Inkling 2 tool call %s: %w", call.Function.Name, err)
}
name, err := pythonScalar(call.Function.Name)
if err != nil {
return "", err
}
body := "{\"name\":" + name + ",\"args\":" + args + "}"
out.WriteString("<|message_model|>" + call.Function.Name + "<|content_invoke_tool_json|>" + body + "<|end_message|>")
}
out.WriteString("<|content_model_end_sampling|>")
}
}
if !effortEmitted {
if err := writeEffort(); err != nil {
return "", err
}
}
return out.String(), nil
}
+738
View File
@@ -0,0 +1,738 @@
package renderers
import (
"bytes"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"slices"
"testing"
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/mlxrunner/tokenizer"
"github.com/ollama/ollama/model/parsers"
)
type inkling2JinjaMessage struct {
Role string `json:"role"`
Content any `json:"content"`
Reasoning string `json:"reasoning_content,omitempty"`
Name string `json:"name,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"`
ToolCalls []api.ToolCall `json:"tool_calls,omitempty"`
}
type inkling2JinjaInput struct {
Messages any `json:"messages"`
Tools any `json:"tools,omitempty"`
Effort any `json:"reasoning_effort,omitempty"`
AddGenerationPrompt bool `json:"add_generation_prompt"`
}
type inkling2JinjaResult struct {
Prompt string
Error string
TokenIDs []int32
}
type inkling2ParityCase struct {
name string
messages []api.Message
tools []api.Tool
think *api.ThinkValue
// Literal reference input where native attachments and Jinja content parts
// differ in shape, or where the API decodes omitted tool schema fields.
parts map[int][]any
rawTools json.RawMessage
}
func (c inkling2ParityCase) referenceInput() inkling2JinjaInput {
messages := make([]inkling2JinjaMessage, 0, len(c.messages))
for i, m := range c.messages {
j := inkling2JinjaMessage{
Role: m.Role, Content: m.Content, Reasoning: m.Thinking, Name: m.ToolName,
ToolCallID: m.ToolCallID, ToolCalls: m.ToolCalls,
}
if parts, ok := c.parts[i]; ok {
j.Content = parts
}
messages = append(messages, j)
}
input := inkling2JinjaInput{Messages: messages, Tools: c.tools, AddGenerationPrompt: true}
if c.rawTools != nil {
input.Tools = c.rawTools
}
if c.think != nil {
input.Effort = c.think.Value
if b, ok := c.think.Value.(bool); ok {
// Ollama booleans select named levels. Jinja's numeric boolean
// conversion is exercised separately with raw publisher input.
input.Effort = map[bool]string{false: "none", true: "high"}[b]
}
}
return input
}
// TestInkling2RendererMatchesJinja2Reference keeps the exact prompts and
// errors runnable in ordinary Go tests. Set VERIFY_JINJA2=1 and point
// INKLING2_JINJA_PYTHON at Python with Transformers 5.x to verify the
// expectations against the publisher template.
func TestInkling2RendererMatchesJinja2Reference(t *testing.T) {
const end = "<|end_message|>"
const stop = "<|content_model_end_sampling|>"
const effort = "<|message_system|><|content_text|>Thinking effort level: "
const system = "<|message_system|><|content_text|>"
const user = "<|message_user|><|content_text|>"
const assistant = "<|message_model|>"
const tool = "<|message_tool|>"
const lookupThinking = assistant + "lookup<|content_thinking|>Find it" + end
const lookupText = assistant + "lookup<|content_text|>Looking" + end
const lookupCall = assistant + `lookup<|content_invoke_tool_json|>{"name":"lookup","args":{"A":{"z":1.0,"a":null},"z":"café"}}` + end
const saveCall = assistant + `save<|content_invoke_tool_json|>{"name":"save","args":{}}` + end
const registry = `<|message_system|>tool_declare<|content_xml|>[{"description":"","name":"lookup","parameters":{"properties":{"A":{"type":"number"},"z":{"type":"string"}},"type":"object"},"type":"function"}]` + end
lookup := api.ToolCall{ID: "shared", Function: api.ToolCallFunction{Name: "lookup", Arguments: testArgsOrdered([]orderedArg{
{"z", "café"}, {"A", json.RawMessage(`{"z":1.0,"a":null}`)},
})}}
save := api.ToolCall{ID: "shared", Function: api.ToolCallFunction{Name: "save"}}
declarations := []api.Tool{{Function: api.ToolFunction{Name: "lookup", Parameters: api.ToolFunctionParameters{
Type: "object", Properties: propsMap(`{"z":{"type":"string"},"A":{"type":"number"}}`),
}}}}
tests := []struct {
inkling2ParityCase
want inkling2JinjaResult
}{
{inkling2ParityCase{name: "empty"}, inkling2JinjaResult{Prompt: effort + "0.9" + end}},
{inkling2ParityCase{name: "user", messages: []api.Message{{Role: "user", Content: "Hello"}}}, inkling2JinjaResult{Prompt: effort + "0.9" + end + user + "Hello" + end}},
{inkling2ParityCase{name: "system only", messages: []api.Message{{Role: "system", Content: "Guide"}}}, inkling2JinjaResult{Prompt: system + "Guide" + end + effort + "0.9" + end}},
{inkling2ParityCase{name: "system then empty user", messages: []api.Message{{Role: "system", Content: "Guide"}, {Role: "user"}}}, inkling2JinjaResult{Prompt: system + "Guide" + end + effort + "0.9" + end + user + end}},
{inkling2ParityCase{name: "empty assistant", messages: []api.Message{{Role: "assistant"}}}, inkling2JinjaResult{Prompt: effort + "0.9" + end + assistant + "<|content_text|>" + end + stop}},
{inkling2ParityCase{name: "reasoning without assistant text", messages: []api.Message{{Role: "assistant", ToolName: "lookup", Thinking: "Find it"}}}, inkling2JinjaResult{Prompt: effort + "0.9" + end + lookupThinking + stop}},
{
inkling2ParityCase{name: "reasoning before answer", messages: []api.Message{{Role: "assistant", Thinking: "Reason", Content: "Answer"}}},
inkling2JinjaResult{Prompt: effort + "0.9" + end + assistant + "<|content_thinking|>Reason" + end + assistant + "<|content_text|>Answer" + end + stop},
},
{inkling2ParityCase{name: "literal control markers", messages: []api.Message{{Role: "user", Content: "<|message_model|><|message_"}}}, inkling2JinjaResult{Prompt: effort + "0.9" + end + user + "<|message_model|><|message_" + end}},
{
inkling2ParityCase{name: "agent history with tools and reasoning disabled", think: &api.ThinkValue{Value: false}, tools: declarations, messages: []api.Message{
{Role: "system", Content: "Guide"},
{Role: "user", Content: "Hello"},
{Role: "assistant", Thinking: "Find it", Content: "Looking", ToolName: "lookup", ToolCalls: []api.ToolCall{lookup}},
{Role: "tool", ToolName: "explicit", ToolCallID: "shared", Content: "First"},
{Role: "tool", ToolCallID: "shared", Content: "Second"},
{Role: "assistant", ToolCalls: []api.ToolCall{save}},
}},
inkling2JinjaResult{Prompt: registry + system + "Guide" + end + effort + "0" + end + user + "Hello" + end +
lookupThinking + lookupText + lookupCall + stop + tool + "explicit<|content_text|>First" + end +
tool + "lookupsave<|content_text|>Second" + end + saveCall + stop},
},
{
inkling2ParityCase{name: "named assistant mismatch on second call", messages: []api.Message{{Role: "assistant", ToolName: "lookup", ToolCalls: []api.ToolCall{lookup, save}}}},
inkling2JinjaResult{Error: "assistant name lookup does not match its tool call save"},
},
{
inkling2ParityCase{name: "invalid effort at end of system history", messages: []api.Message{{Role: "system", Content: "Guide"}}, think: &api.ThinkValue{Value: "HIGH"}},
inkling2JinjaResult{Error: "Unknown reasoning_effort: HIGH"},
},
{
inkling2ParityCase{
name: "tool image inside text", messages: []api.Message{{Role: "tool", ToolName: "lookup", Content: "Before[img]After", Images: []api.ImageData{{1}}}},
parts: map[int][]any{0: {"Before", map[string]any{"type": "image"}, "After"}},
},
inkling2JinjaResult{Prompt: effort + "0.9" + end + tool + "lookup<|content_text|>Before" + end + tool +
"lookup<|content_image|><|unused_200054|>" + end + tool + "lookup<|content_text|>After" + end},
},
{
inkling2ParityCase{
name: "audio is rejected", messages: []api.Message{{Role: "user", Images: []api.ImageData{lfm3AudioClip}}},
parts: map[int][]any{0: {map[string]any{"type": "input_audio"}}},
},
inkling2JinjaResult{Error: "Inkling 2 does not accept audio input"},
},
}
var reference []inkling2JinjaResult
if os.Getenv("VERIFY_JINJA2") != "" {
inputs := make([]inkling2JinjaInput, len(tests))
for i, tc := range tests {
inputs[i] = tc.referenceInput()
}
reference = inkling2RenderJinjaBatch(t, inputs)
}
for i, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, err := RenderWithRenderer("inkling2", tc.messages, tc.tools, tc.think)
var gotError string
if err != nil {
gotError = err.Error()
}
if got != tc.want.Prompt || gotError != tc.want.Error {
t.Errorf("Go prompt = %q, error = %q\nwant = %q, error = %q", got, gotError, tc.want.Prompt, tc.want.Error)
}
if reference != nil && (reference[i].Prompt != tc.want.Prompt || reference[i].Error != tc.want.Error) {
t.Errorf("Jinja prompt = %q, error = %q\nwant = %q, error = %q", reference[i].Prompt, reference[i].Error, tc.want.Prompt, tc.want.Error)
}
})
}
}
// TestInkling2RendererJinjaParity compares the Go renderer with the pinned
// fixture using the actual Transformers Jinja engine. The same inputs test
// history framing as well as the prompt suffix at each terminal role.
func TestInkling2RendererJinjaParity(t *testing.T) {
user := api.Message{Role: "user", Content: "What is 7 + 5? Answer with just the number."}
system := api.Message{Role: "system", Content: " Use examples.\n"}
tool := api.Tool{Type: "function", Function: api.ToolFunction{
Name: "lookup", Description: "Search café 🌍 <&>'",
Parameters: api.ToolFunctionParameters{
Type: "object",
Properties: testPropsOrdered([]orderedProp{
{"z", api.ToolProperty{Type: api.PropertyType{"array"}, Items: map[string]any{"type": []string{"number", "null"}, "maximum": json.Number("1e16"), "default": nil}}},
{"A", api.ToolProperty{AnyOf: []api.ToolProperty{{Type: api.PropertyType{"null"}}, {Type: api.PropertyType{"string"}}}}},
}),
Required: []string{"A", "z"},
Extra: map[string]any{"additionalProperties": false},
Defs: json.RawMessage(`{"z":{"type":"string","default":0.00001},"A":{"type":"number","minimum":-1e-7}}`),
},
}}
save := api.Tool{Type: "custom", Function: api.ToolFunction{Name: "save", Parameters: api.ToolFunctionParameters{
Type: "object", Properties: api.NewToolPropertiesMap(),
}}}
rawRegistry := json.RawMessage(`[{"function":{"name":"lookup"}},{"type":"","function":{"name":"save","description":"","parameters":{"type":"object"}}}]`)
zeroSchema := []api.Tool{
{Function: api.ToolFunction{Name: "lookup"}},
{Function: api.ToolFunction{Name: "save", Parameters: api.ToolFunctionParameters{Type: "object"}}},
}
mixed := testArgsOrdered([]orderedArg{
{"z", []any{true, false, nil, "", []any{}, map[string]any{}, "café 🌦️\u2028\u2029", "\x00\b\f\n\r\t\"\\<>&'"}},
{"Ω", json.RawMessage(`{"z":9,"A":{"y":[{"c":null,"b":true}],"a":0}}`)},
{"a", []any{json.Number("1.0"), json.Number("-0.0"), json.Number("-0"), json.Number("1e16"), json.Number("1e-5"), json.Number("3e-6"), json.Number("0.0001"), json.Number("5e-324"), json.Number("1.7976931348623157e308"), json.Number("18446744073709551616")}},
{"A", "case sensitive"},
{"", "empty key"},
})
lookup := api.ToolCall{ID: "shared", Function: api.ToolCallFunction{Name: "lookup", Arguments: mixed}}
secondLookup := api.ToolCall{ID: "shared", Function: api.ToolCallFunction{Name: "lookup"}}
saveCall := api.ToolCall{ID: "shared", Function: api.ToolCallFunction{Name: "save", Arguments: api.NewToolCallFunctionArguments()}}
unnamedID := api.ToolCall{Function: api.ToolCallFunction{Name: "noid", Arguments: testArgs(map[string]any{"one": 1})}}
literal := "<<|message_model|><|content_thinking|><|end_message|><|message_\x00| < |message_tool|> [img] [img-5]"
tests := []inkling2ParityCase{
{name: "empty"},
{name: "system-only", messages: []api.Message{system, {Role: "system"}}},
{name: "ordered-systems", messages: []api.Message{system, {Role: "system"}, user, {Role: "system", Content: "Late"}}, tools: []api.Tool{save, tool}},
{name: "empty-user", messages: []api.Message{{Role: "user"}}},
{name: "plain-transcript", messages: []api.Message{user, {Role: "assistant", Content: "12"}, user}},
{name: "empty-tools", messages: []api.Message{user}, tools: []api.Tool{}},
{name: "registry-only", tools: []api.Tool{save, tool}},
{name: "registry-default-fields", messages: []api.Message{user}, tools: zeroSchema, rawTools: rawRegistry},
{name: "registry-empty-function-name", tools: []api.Tool{{Function: api.ToolFunction{}}}, rawTools: json.RawMessage(`[{"function":{"name":""}}]`)},
{name: "registry-schema-with-internal-nulls", tools: []api.Tool{tool}, think: &api.ThinkValue{Value: "max"}},
{name: "named-assistant-thinking-and-text", messages: []api.Message{{Role: "assistant", ToolName: "lookup", Thinking: "First", Content: "Explain"}}},
{name: "named-assistant-matching-all-calls", messages: []api.Message{{Role: "assistant", ToolName: "lookup", Thinking: "Reason", Content: "Looking", ToolCalls: []api.ToolCall{lookup, secondLookup}}}},
{name: "named-assistant-matches-first-call-only", messages: []api.Message{{Role: "assistant", ToolName: "lookup", ToolCalls: []api.ToolCall{lookup, saveCall}}}},
{name: "named-assistant-mismatch", messages: []api.Message{{Role: "assistant", ToolName: "other", ToolCalls: []api.ToolCall{lookup}}}},
{name: "empty-call-name-is-a-string", messages: []api.Message{{Role: "assistant", ToolCalls: []api.ToolCall{{}}}}},
{name: "tool-result-explicit-name-precedence", messages: []api.Message{{Role: "assistant", ToolCalls: []api.ToolCall{lookup}}, {Role: "tool", ToolName: "explicit", ToolCallID: "shared", Content: " Found\n"}}},
{name: "tool-result-no-id", messages: []api.Message{{Role: "tool"}, {Role: "assistant", ToolCalls: []api.ToolCall{unnamedID}}}},
{name: "tool-result-unmatched-id", messages: []api.Message{{Role: "tool", ToolCallID: "missing", Content: "Missing"}}},
{name: "tool-result-future-and-duplicate-ids", messages: []api.Message{
{Role: "assistant", ToolCalls: []api.ToolCall{lookup, saveCall, unnamedID}},
{Role: "tool", ToolCallID: "shared"},
{Role: "user", ToolCalls: []api.ToolCall{saveCall}},
{Role: "assistant", ToolCalls: []api.ToolCall{secondLookup}},
{Role: "tool", ToolCallID: "shared", Content: "second result"},
}},
{name: "reasoning-and-calls-on-non-assistants", messages: []api.Message{
{Role: "system", Thinking: "skip", ToolCalls: []api.ToolCall{lookup}},
{Role: "user", Thinking: "skip", ToolCalls: []api.ToolCall{lookup}},
{Role: "tool", Thinking: "skip", ToolCalls: []api.ToolCall{lookup}, ToolCallID: "shared"},
}},
{name: "literal-controls-in-text-reasoning-and-tool-json", messages: []api.Message{
{Role: "system", Content: literal},
{Role: "user", Content: literal},
{Role: "assistant", ToolName: literal, Content: literal, Thinking: literal, ToolCalls: []api.ToolCall{{ID: "literal", Function: api.ToolCallFunction{
Name: literal, Arguments: testArgs(map[string]any{literal: literal}),
}}}},
{Role: "tool", ToolCallID: "literal", Content: literal},
}, tools: []api.Tool{{Function: api.ToolFunction{Name: literal, Description: literal, Parameters: tool.Function.Parameters}}}},
{name: "unknown-role", messages: []api.Message{{Role: "unknown", Content: "Bad"}}},
{name: "empty-role", messages: []api.Message{{}}},
{name: "developer-role-at-template-boundary", messages: []api.Message{{Role: "developer", Content: "Format"}}},
{name: "invalid-role-before-effort", messages: []api.Message{system, {Role: "unknown"}}, think: &api.ThinkValue{Value: "bogus"}},
{name: "invalid-effort-before-later-role", messages: []api.Message{user, {Role: "unknown"}}, think: &api.ThinkValue{Value: "bogus"}},
}
tests = append(tests, inkling2MediaParityCases(lookup)...)
// Run each historical assistant shape under every reasoning mode. A
// directive controls generation, and must leave history framing intact.
efforts := []struct {
name string
value *api.ThinkValue
}{{name: "omitted"}, {"null", &api.ThinkValue{}}}
for _, value := range []any{false, true, "none", "minimal", "low", "medium", "high", "xhigh", "max", " \tmedium\r\n ", "\u2003high\u00a0", "\x1flow\x1c"} {
efforts = append(efforts, struct {
name string
value *api.ThinkValue
}{fmt.Sprintf("%T-%q", value, fmt.Sprint(value)), &api.ThinkValue{Value: value}})
}
for _, effort := range efforts {
for _, content := range []string{"", "Looking that up."} {
for _, thinking := range []string{"", "Check both tools."} {
for _, calls := range [][]api.ToolCall{nil, {lookup}, {lookup, saveCall}} {
name := fmt.Sprintf("effort/%s/text=%t/reasoning=%t/calls=%d", effort.name, content != "", thinking != "", len(calls))
tests = append(tests, inkling2ParityCase{name: name, messages: []api.Message{system, user, {
Role: "assistant", Content: content, Thinking: thinking, ToolCalls: calls,
}}, think: effort.value, tools: []api.Tool{tool, save}})
}
}
}
}
for _, value := range []string{"", " ", "none!", "HIGH", "0.125", "ultra"} {
tests = append(tests, inkling2ParityCase{name: fmt.Sprintf("invalid-effort-%q", value), messages: []api.Message{user}, think: &api.ThinkValue{Value: value}})
}
pipeline := []api.Message{
user,
{Role: "assistant", Thinking: "Look it up.", ToolCalls: []api.ToolCall{lookup}},
{Role: "tool", ToolCallID: "shared", Content: "12"},
{Role: "assistant", Content: "Found it.", Thinking: "Save that.", ToolCalls: []api.ToolCall{saveCall}},
{Role: "tool", ToolName: "save", ToolCallID: "shared"},
{Role: "assistant", Content: "The result is 12."},
user,
}
for _, effort := range efforts {
tests = append(tests, inkling2ParityCase{
name: "arithmetic/" + effort.name, messages: []api.Message{user}, think: effort.value,
})
for end := 1; end <= len(pipeline); end++ {
tests = append(tests, inkling2ParityCase{
name: fmt.Sprintf("agent-transcript/%s/%d-%s", effort.name, end, pipeline[end-1].Role),
messages: pipeline[:end], tools: []api.Tool{tool, save}, think: effort.value,
})
}
}
inputs := make([]inkling2JinjaInput, len(tests))
for i, tc := range tests {
inputs[i] = tc.referenceInput()
}
results := inkling2RenderJinjaBatch(t, inputs)
tok := inkling2ReferenceTokenizer(t)
for i, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, err := RenderWithRenderer("inkling2", tc.messages, tc.tools, tc.think)
want := results[i]
if want.Error != "" || err != nil {
if err == nil || err.Error() != want.Error || got != "" {
t.Fatalf("Go error = %v, prompt = %q\nJinja error = %q, prompt = %q", err, got, want.Error, want.Prompt)
}
return
}
if got != want.Prompt {
t.Fatalf("Go %q\nJinja %q", got, want.Prompt)
}
if tok != nil {
ids := tok.Encode(got, tok.AddBOS())
if !slices.Equal(ids, want.TokenIDs) {
t.Errorf("Go IDs %v\nJinja IDs %v", ids, want.TokenIDs)
}
}
})
}
}
func TestInkling2ParserRendererToolLoopRoundTrip(t *testing.T) {
const effort = "<|message_system|><|content_text|>Thinking effort level: 0.7<|end_message|>"
const end = "<|end_message|>"
const stop = "<|content_model_end_sampling|>"
const model = "<|message_model|>"
const lookupArgs = `{"id":17,"query":"check <|end_message|> café","tags":[true,null,{"account":9007199254740993}]}`
const lookupBody = model + `lookup<|content_invoke_tool_json|>{"name":"lookup","args":` + lookupArgs + `}` + end
const saveBody = model + `save<|content_invoke_tool_json|>{"name":"save","args":{}}` + end
const registry = `<|message_system|>tool_declare<|content_xml|>[{"description":"","name":"lookup","parameters":{},"type":"function"},{"description":"","name":"save","parameters":{},"type":"function"}]` + end
tools := []api.Tool{
{Type: "function", Function: api.ToolFunction{Name: "lookup"}},
{Type: "function", Function: api.ToolFunction{Name: "save"}},
}
refTools := json.RawMessage(`[{"type":"function","function":{"name":"lookup"}},{"type":"function","function":{"name":"save"}}]`)
think := &api.ThinkValue{Value: "medium"}
lookup := args(lookupArgs)
lookup.Set("tags", json.RawMessage(`[true,null,{"account":9007199254740993}]`))
turns := []struct {
message api.Message
raw string
results []api.Message
rawResults string
}{
{
message: api.Message{Role: "assistant", Content: "I’ll check and save that.", Thinking: "Use both tools.", ToolCalls: []api.ToolCall{
{ID: "call_lookup", Function: api.ToolCallFunction{Name: "lookup", Arguments: lookup}},
{ID: "call_save", Function: api.ToolCallFunction{Name: "save", Index: 1}},
}},
raw: model + "<|content_thinking|>Use both tools." + end + model + "<|content_text|>I’ll check and save that." + end + lookupBody + saveBody + stop,
results: []api.Message{
{Role: "tool", ToolCallID: "call_lookup", Content: "Found 17."},
{Role: "tool", ToolCallID: "call_save", ToolName: "save", Content: "Saved."},
},
rawResults: "<|message_tool|>lookup<|content_text|>Found 17." + end + "<|message_tool|>save<|content_text|>Saved." + end,
},
{
message: api.Message{Role: "assistant", Thinking: "Verify the save.", ToolCalls: []api.ToolCall{
{ID: "call_verify", Function: api.ToolCallFunction{Name: "lookup", Arguments: lookup}},
}},
raw: model + "<|content_thinking|>Verify the save." + end + lookupBody + stop,
results: []api.Message{{Role: "tool", ToolCallID: "call_verify", Content: "Verified."}},
rawResults: "<|message_tool|>lookup<|content_text|>Verified." + end,
},
{
message: api.Message{Role: "assistant", Thinking: "Both results agree.", Content: "The saved result is 17."},
raw: model + "<|content_thinking|>Both results agree." + end + model + "<|content_text|>The saved result is 17." + end + stop,
},
}
const question = "Look up the result and save it."
initial := api.Message{Role: "user", Content: question}
var reference []inkling2JinjaResult
if os.Getenv("VERIFY_JINJA2") != "" {
expectedHistory := []api.Message{initial}
var inputs []inkling2JinjaInput
for _, turn := range turns {
assistant := inkling2ParityCase{messages: []api.Message{turn.message}, think: think}
inputs = append(inputs, assistant.referenceInput())
expectedHistory = append(expectedHistory, turn.message)
expectedHistory = append(expectedHistory, turn.results...)
next := inkling2ParityCase{messages: expectedHistory, rawTools: refTools, think: think}
inputs = append(inputs, next.referenceInput())
}
reference = inkling2RenderJinjaBatch(t, inputs)
}
history := []api.Message{initial}
wantHistory := registry + effort + "<|message_user|><|content_text|>" + question + end
parser := parsers.ParserForName("inkling2")
for i, turn := range turns {
raw := turn.raw
if reference != nil {
ref := reference[2*i]
if ref.Error != "" || ref.Prompt != effort+raw {
t.Fatalf("turn %d: Jinja assistant turn = %q, error = %q\nwant %q", i+1, ref.Prompt, ref.Error, effort+raw)
}
raw = ref.Prompt[len(effort):]
}
var message api.Message
for split := range len(raw) + 1 {
parser.Init(tools, nil, think)
message = api.Message{Role: "assistant"}
for j, chunk := range []string{raw[:split], raw[split:]} {
content, thinking, calls, err := parser.Add(chunk, j == 1)
if err != nil {
t.Fatalf("turn %d split %d: parse: %v", i+1, split, err)
}
message.Content += content
message.Thinking += thinking
message.ToolCalls = append(message.ToolCalls, calls...)
}
if message.Content != turn.message.Content || message.Thinking != turn.message.Thinking || len(message.ToolCalls) != len(turn.message.ToolCalls) {
t.Fatalf("turn %d split %d: content = %q, thinking = %q, tool calls = %v", i+1, split, message.Content, message.Thinking, message.ToolCalls)
}
for j, call := range message.ToolCalls {
want := turn.message.ToolCalls[j]
if call.Function.Index != want.Function.Index || call.Function.Name != want.Function.Name ||
call.Function.Arguments.String() != want.Function.Arguments.String() {
t.Fatalf("turn %d split %d: tool call %d (%q, index %d, args %s), want (%q, index %d, args %s)",
i+1, split, j, call.Function.Name, call.Function.Index, call.Function.Arguments.String(),
want.Function.Name, want.Function.Index, want.Function.Arguments.String())
}
// The server supplies the call IDs before clients append their results.
message.ToolCalls[j].ID = want.ID
}
}
history = append(history, message)
history = append(history, turn.results...)
wantHistory += turn.raw + turn.rawResults
got, err := RenderWithRenderer("inkling2", history, tools, think)
if err != nil || got != wantHistory {
t.Fatalf("turn %d: Go history = %q, error = %v\nwant %q", i+1, got, err, wantHistory)
}
if reference != nil {
if ref := reference[2*i+1]; ref.Error != "" || ref.Prompt != wantHistory {
t.Fatalf("turn %d: Jinja history = %q, error = %q\nwant %q", i+1, ref.Prompt, ref.Error, wantHistory)
}
}
}
}
// INKLING2_TOKENIZER_DIR optionally enables the production-tokenizer check
// against the publisher's tokenizer.json for the same exact rendered prompts.
func inkling2ReferenceTokenizer(t *testing.T) *tokenizer.Tokenizer {
t.Helper()
dir := os.Getenv("INKLING2_TOKENIZER_DIR")
if dir == "" {
return nil
}
read := func(name string) []byte {
t.Helper()
data, err := os.ReadFile(filepath.Join(dir, name))
if err != nil {
t.Fatal(err)
}
return data
}
tok, err := tokenizer.LoadFromBytesWithConfig(read("tokenizer.json"), &tokenizer.TokenizerConfig{
ConfigJSON: read("config.json"),
TokenizerConfigJSON: read("tokenizer_config.json"),
})
if err != nil {
t.Fatal(err)
}
return tok
}
func inkling2MediaParityCases(call api.ToolCall) []inkling2ParityCase {
image := map[string]any{"type": "image"}
imageURL := map[string]any{"type": "image_url"}
inputImage := map[string]any{"type": "input_image"}
text := func(s string) map[string]any { return map[string]any{"type": "text", "text": s} }
one := []api.ImageData{{1}}
three := []api.ImageData{{1}, {2}, {3}}
wav := lfm3AudioClip
mp3 := api.ImageData{0xff, 0xfb, 0x90, 0x64}
inputAudio := map[string]any{"type": "input_audio"}
audio := map[string]any{"type": "audio"}
return []inkling2ParityCase{
{name: "user-image-only", messages: []api.Message{{Role: "user", Images: one}}, parts: map[int][]any{0: {image}}},
{name: "user-image-plus-text", messages: []api.Message{{Role: "user", Content: "Read", Images: one}}, parts: map[int][]any{0: {imageURL, text("Read")}}},
{name: "image-order-and-tool-result", messages: []api.Message{
{Role: "user", Content: "[img]Compare[img] with the last [img]", Images: three},
{Role: "assistant", ToolCalls: []api.ToolCall{call}},
{Role: "tool", ToolCallID: call.ID, Content: "Before[img]After", Images: one},
{Role: "tool", ToolName: "other", Images: one},
}, parts: map[int][]any{
0: {image, text("Compare"), inputImage, text(" with the last "), imageURL},
2: {text("Before"), image, text("After")},
3: {inputImage},
}},
{name: "indexed-images-and-unplaced-images", messages: []api.Message{
{Role: "user", Content: "See [img-0]", Images: three},
{Role: "tool", Content: "Result [img-3]", Images: one},
}, parts: map[int][]any{0: {image, image, text("See "), image}, 1: {text("Result "), imageURL}}},
{name: "mixed-indexed-and-anonymous-images", messages: []api.Message{
{Role: "user", Content: "[img-0] [?] [img] then [img-999] or [img-]", Images: three},
}, parts: map[int][]any{0: {image, image, text(" [?] "), image, text(" then [img-999] or [img-]")}}},
{
name: "assistant-image-error-after-effort-error", messages: []api.Message{{Role: "assistant", Images: one}},
parts: map[int][]any{0: {image}}, think: &api.ThinkValue{Value: "bogus"},
},
{name: "leading-system-with-image", messages: []api.Message{{Role: "system", Images: one}}, parts: map[int][]any{0: {image}}},
{
name: "leading-system-image-error-before-effort-error", messages: []api.Message{{Role: "system", Images: one}, {Role: "user", Content: "Read"}},
parts: map[int][]any{0: {image}}, think: &api.ThinkValue{Value: "bogus"},
},
{name: "assistant-with-image", messages: []api.Message{{Role: "assistant", Images: one}}, parts: map[int][]any{0: {image}}},
{
name: "assistant-image-error-before-mismatched-tool-name", messages: []api.Message{{
Role: "assistant", ToolName: "other", Thinking: "Read this", Content: "First[img]", Images: one, ToolCalls: []api.ToolCall{call},
}}, parts: map[int][]any{0: {text("First"), image}},
},
{
name: "late-system-with-image", messages: []api.Message{{Role: "user", Content: "Hello"}, {Role: "system", Images: one}},
parts: map[int][]any{1: {image}},
},
{name: "user-with-wav", messages: []api.Message{{Role: "user", Images: []api.ImageData{wav}}}, parts: map[int][]any{0: {inputAudio}}},
{name: "user-with-id3", messages: []api.Message{{Role: "user", Images: []api.ImageData{[]byte("ID3")}}}, parts: map[int][]any{0: {inputAudio}}},
{
name: "tool-with-image-then-mp3", messages: []api.Message{{Role: "tool", ToolCallID: call.ID, Content: "Look[img] then hear[img]", Images: []api.ImageData{one[0], mp3}}},
parts: map[int][]any{0: {text("Look"), image, text(" then hear"), audio}},
},
{
name: "assistant-with-audio-before-image", messages: []api.Message{{Role: "assistant", Thinking: "Seen", Images: []api.ImageData{wav, one[0]}}},
parts: map[int][]any{0: {audio, image}},
},
{
name: "system-with-image-before-audio", messages: []api.Message{{Role: "system", Images: []api.ImageData{one[0], wav}}},
parts: map[int][]any{0: {image, audio}},
},
{
name: "system-with-reordered-audio-before-image", messages: []api.Message{{Role: "system", Content: "[img-1][img-0]", Images: []api.ImageData{one[0], wav}}},
parts: map[int][]any{0: {audio, image}},
},
}
}
func inkling2RenderJinjaBatch(t *testing.T, inputs []inkling2JinjaInput) []inkling2JinjaResult {
t.Helper()
if os.Getenv("VERIFY_JINJA2") == "" {
t.Skip("set VERIFY_JINJA2=1 to run publisher Jinja comparison")
}
verifyLFM3TemplateFixture(t, inkling2Template, inkling2TemplateSHA256)
python := os.Getenv("INKLING2_JINJA_PYTHON")
if python == "" {
python = "python3"
}
input, err := json.Marshal(inputs)
if err != nil {
t.Fatal(err)
}
const script = `
import json
import sys
from pathlib import Path
from jinja2 import TemplateError
from tokenizers import Tokenizer
from transformers.utils.chat_template_utils import _compile_jinja_template
template = _compile_jinja_template(Path(sys.argv[1]).read_text(encoding="utf-8"))
tokenizer = Tokenizer.from_file(str(Path(sys.argv[2]) / "tokenizer.json")) if sys.argv[2] else None
results = []
for kwargs in json.load(sys.stdin):
try:
prompt = template.render(**kwargs)
result = {"prompt": prompt}
if tokenizer is not None:
result["tokenids"] = tokenizer.encode(prompt, add_special_tokens=False).ids
results.append(result)
except TemplateError as error:
results.append({"error": str(error)})
print(json.dumps(results, ensure_ascii=True))
`
cmd := exec.CommandContext(t.Context(), python, "-c", script, inkling2Template, os.Getenv("INKLING2_TOKENIZER_DIR"))
cmd.Stdin = bytes.NewReader(input)
output, err := cmd.Output()
if err != nil {
if exit, ok := err.(*exec.ExitError); ok {
t.Fatalf("Jinja: %v\n%s", err, exit.Stderr)
}
t.Fatal(err)
}
var results []inkling2JinjaResult
if err := json.Unmarshal(output, &results); err != nil {
t.Fatal(err)
}
if len(results) != len(inputs) {
t.Fatalf("received %d Jinja results for %d cases", len(results), len(inputs))
}
return results
}
// These cases exercise Jinja input shapes that api.Message, api.Tool, or
// api.ThinkValue flatten or reject before the renderer is called.
func TestInkling2PublisherOnlyJinjaBranches(t *testing.T) {
const effortStart = "<|message_system|><|content_text|>Thinking effort level: "
const end = "<|end_message|>"
const userText = "<|message_user|><|content_text|>"
const userImage = "<|message_user|><|content_image|><|unused_200054|>" + end
const assistantHeader = "<|message_model|>"
const stop = "<|content_model_end_sampling|>"
const toolDeclaration = "<|message_system|>tool_declare<|content_xml|>"
const lookup = assistantHeader + "lookup<|content_invoke_tool_json|>" + `{"name":"lookup","args":{}}` + end + stop
const defaultEffort = effortStart + "0.9" + end
type rawCase struct {
name, messages, tools, effort string
want inkling2JinjaResult
}
tests := []rawCase{
{name: "explicit-null-effort", effort: "null", want: inkling2JinjaResult{Prompt: defaultEffort}},
{name: "zero-numeric-effort", effort: "0", want: inkling2JinjaResult{Prompt: effortStart + "0" + end}},
{name: "negative-zero-effort", effort: "-0.0", want: inkling2JinjaResult{Prompt: effortStart + "0" + end}},
{name: "max-numeric-effort", effort: "0.99", want: inkling2JinjaResult{Prompt: effortStart + "0.99" + end}},
{name: "nonpreset-numeric-effort", effort: "0.125", want: inkling2JinjaResult{Prompt: effortStart + "0.125" + end}},
{name: "numeric-effort-below-range", effort: "-0.001", want: inkling2JinjaResult{Error: "reasoning_effort must be in [0.0, 0.99]"}},
{name: "numeric-effort-above-range", effort: "0.991", want: inkling2JinjaResult{Error: "reasoning_effort must be in [0.0, 0.99]"}},
{name: "raw-boolean-false-effort", effort: "false", want: inkling2JinjaResult{Prompt: effortStart + "0" + end}},
{name: "raw-boolean-true-effort", effort: "true", want: inkling2JinjaResult{Error: "reasoning_effort must be in [0.0, 0.99]"}},
{name: "tools-null", tools: "null", want: inkling2JinjaResult{Prompt: defaultEffort}},
{name: "tools-empty", tools: "[]", want: inkling2JinjaResult{Prompt: defaultEffort}},
{
name: "bare-and-wrapped-declarations", tools: `[{"name":"a"},{"type":null,"function":{"name":"b","description":null,"parameters":null}},{"type":"other","function":{"name":"c","description":" ","parameters":{}}}]`,
want: inkling2JinjaResult{Prompt: toolDeclaration + `[{"description":"","name":"a","parameters":{},"type":"function"},{"description":"","name":"b","parameters":{},"type":"function"},{"description":" ","name":"c","parameters":{},"type":"other"}]` + end + defaultEffort},
},
{name: "missing-user-content", messages: `[{"role":"user"}]`, want: inkling2JinjaResult{Prompt: defaultEffort}},
{name: "null-user-content", messages: `[{"role":"user","content":null}]`, want: inkling2JinjaResult{Prompt: defaultEffort}},
{name: "empty-user-parts", messages: `[{"role":"user","content":[]}]`, want: inkling2JinjaResult{Prompt: defaultEffort}},
{name: "missing-assistant-content", messages: `[{"role":"assistant"}]`, want: inkling2JinjaResult{Prompt: defaultEffort + stop}},
{name: "null-thinking-and-empty-calls", messages: `[{"role":"assistant","content":"","reasoning_content":null,"tool_calls":[]}]`, want: inkling2JinjaResult{Prompt: defaultEffort + assistantHeader + "<|content_text|>" + end + stop}},
{
name: "explicit-empty-names-use-call-id",
messages: `[{"role":"assistant","name":"","content":"","tool_calls":[{"id":"call_1","function":{"name":"lookup"}}]},` +
`{"role":"tool","name":"","tool_call_id":"call_1","content":"Found it"}]`,
want: inkling2JinjaResult{Prompt: defaultEffort + lookup + "<|message_tool|>lookup<|content_text|>Found it" + end},
},
{
name: "explicit-empty-call-id",
messages: `[{"role":"tool","tool_call_id":"","content":"No match"}]`,
want: inkling2JinjaResult{Prompt: defaultEffort + "<|message_tool|><|content_text|>No match" + end},
},
{
name: "bare-and-typed-text-parts", messages: `[{"role":"user","content":["", "bare", {"text":"untyped"}, {"type":"text","text":"typed"}, {"type":"input_text","text":"input"}, {"type":"input_text","text":8}, {"type":"text","text":null}, {"type":"text"}, {}]}]`,
want: inkling2JinjaResult{Prompt: defaultEffort + userText + end + userText + "bare" + end + userText + "untyped" + end + userText + "typed" + end + userText + "input" + end + userText + end + userText + end + userText + end + userText + end},
},
{
name: "assistant-text-parts-between-reasoning-and-calls", messages: `[{"role":"assistant","name":"lookup","content":[{"type":"text","text":"one"},"two"],"reasoning_content":"think","tool_calls":[{"function":{"name":"lookup"}}]}]`,
want: inkling2JinjaResult{Prompt: defaultEffort + assistantHeader + "lookup<|content_thinking|>think" + end + assistantHeader + "lookup<|content_text|>one" + end + assistantHeader + "lookup<|content_text|>two" + end + lookup},
},
{name: "image-aliases", messages: `[{"role":"user","content":[{"type":"input_image"},{"type":"image"},{"type":"image_url"}]}]`, want: inkling2JinjaResult{Prompt: defaultEffort + userImage + userImage + userImage}},
{name: "system-image", messages: `[{"role":"system","content":[{"type":"input_image"}]}]`, want: inkling2JinjaResult{Error: "Image content is only supported for user and tool messages"}},
{name: "unsupported-video", messages: `[{"role":"user","content":[{"type":"video"}]}]`, want: inkling2JinjaResult{Error: "Unsupported content part type: video"}},
{name: "unsupported-unknown-part", messages: `[{"role":"tool","content":[{"type":"blob"}]}]`, want: inkling2JinjaResult{Error: "Unsupported content part type: blob"}},
{name: "nonstring-call-name", messages: `[{"role":"assistant","tool_calls":[{"function":{"name":12}}]}]`, want: inkling2JinjaResult{Error: "tool call function name must be a string"}},
{name: "null-call-name", messages: `[{"role":"assistant","tool_calls":[{"function":{"name":null}}]}]`, want: inkling2JinjaResult{Error: "tool call function name must be a string"}},
{name: "absent-name-at-tool-lookup", messages: `[{"role":"tool","tool_call_id":"id","content":"result"},{"role":"assistant","tool_calls":[{"id":"id","function":{}}]}]`, want: inkling2JinjaResult{Error: "tool call function name must be a string"}},
{name: "stringified-call-arguments", messages: `[{"role":"assistant","tool_calls":[{"function":{"name":"lookup","arguments":"{}"}}]}]`, want: inkling2JinjaResult{Error: "tool call arguments must be a parsed object, not a JSON string; canonicalize upstream"}},
}
for _, alias := range []string{"audio", "input_audio", "audio_url"} {
tests = append(tests, rawCase{
name: "unsupported-" + alias, messages: fmt.Sprintf(`[{"role":"tool","content":[{"type":%q}]}]`, alias),
want: inkling2JinjaResult{Error: "Inkling 2 does not accept audio input"},
})
}
for _, arguments := range []string{"null", "false", "0", `""`, "[]", "{}", "[1]", "true", "2"} {
want := inkling2JinjaResult{Prompt: defaultEffort + lookup}
if arguments == "[1]" || arguments == "true" || arguments == "2" {
want = inkling2JinjaResult{Error: "tool call arguments must be an object"}
}
tests = append(tests, rawCase{
name: "arguments-" + arguments, messages: fmt.Sprintf(`[{"role":"assistant","tool_calls":[{"function":{"name":"lookup","arguments":%s}}]}]`, arguments), want: want,
})
}
inputs := make([]inkling2JinjaInput, len(tests))
for i, tc := range tests {
inputs[i] = inkling2JinjaInput{Messages: json.RawMessage("[]"), AddGenerationPrompt: true}
if tc.messages != "" {
inputs[i].Messages = json.RawMessage(tc.messages)
}
if tc.tools != "" {
inputs[i].Tools = json.RawMessage(tc.tools)
}
if tc.effort != "" {
inputs[i].Effort = json.RawMessage(tc.effort)
}
}
results := inkling2RenderJinjaBatch(t, inputs)
for i, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if got := results[i]; got.Prompt != tc.want.Prompt || got.Error != tc.want.Error {
t.Fatalf("Jinja got %+q, want %+q", got, tc.want)
}
})
}
}
func TestInkling2JinjaHasNoGenerationOpener(t *testing.T) {
messages := []json.RawMessage{
json.RawMessage(`[]`),
json.RawMessage(`[{"role":"system","content":"guide"}]`),
json.RawMessage(`[{"role":"user","content":"question"}]`),
json.RawMessage(`[{"role":"assistant","content":"partial answer"}]`),
json.RawMessage(`[{"role":"assistant","reasoning_content":"consider","tool_calls":[{"function":{"name":"lookup"}}]}]`),
json.RawMessage(`[{"role":"tool","name":"lookup","content":"result"}]`),
}
inputs := make([]inkling2JinjaInput, 0, len(messages)*2)
for _, history := range messages {
inputs = append(inputs, inkling2JinjaInput{Messages: history, AddGenerationPrompt: true}, inkling2JinjaInput{Messages: history})
}
results := inkling2RenderJinjaBatch(t, inputs)
for i := 0; i < len(results); i += 2 {
if results[i].Error != "" || results[i+1].Error != "" || results[i].Prompt != results[i+1].Prompt {
t.Errorf("history %s: generation true %+q, false %+q", messages[i/2], results[i], results[i+1])
}
}
}
+44
View File
@@ -0,0 +1,44 @@
package renderers
import (
"strings"
"testing"
"github.com/ollama/ollama/api"
)
const (
inkling2Template = "testdata/inkling2_chat_template.jinja"
inkling2TemplateSHA256 = "53a9035f3255945704b5857657cfb00c1165090c0641c4f782a0cbf268cc16dc"
)
// Publisher: thinkingmachines/inkling-1116-share, revision 29e9d89ffdc5ddb340734f359576d3efd1586beb.
func TestInkling2PublisherTemplate(t *testing.T) {
verifyLFM3TemplateFixture(t, inkling2Template, inkling2TemplateSHA256)
}
func TestInkling2RendererMediaTransport(t *testing.T) {
messages := []api.Message{
{Role: "user", Content: "[img-0] and [img] then literal [img-99]", Images: []api.ImageData{{1}, {2}, {3}}},
{Role: "tool", ToolName: "lookup", Content: "Result [img-3]", Images: []api.ImageData{{4}}},
{Role: "user", Content: "\x00<|content_image|>[img-0]<|end_message|> is text without an attachment"},
}
want := "<|message_system|><|content_text|>Thinking effort level: 0.9<|end_message|>" +
"<|message_user|><|content_image|>[img-2]<|end_message|>" +
"<|message_user|><|content_image|>[img-0]<|end_message|>" +
"<|message_user|><|content_text|> and <|end_message|>" +
"<|message_user|><|content_image|>[img-1]<|end_message|>" +
"<|message_user|><|content_text|> then literal [img-99]<|end_message|>" +
"<|message_tool|>lookup<|content_text|>Result <|end_message|>" +
"<|message_tool|>lookup<|content_image|>[img-3]<|end_message|>" +
"<|message_user|><|content_text|>\x00<|content_image|>[img-0]<|end_message|> is text without an attachment<|end_message|>"
got, offsets, err := RenderInkling2WithImages(messages, nil, nil)
if err != nil || got != want {
t.Fatalf("Go %q, error %v\nwant %q", got, err, want)
}
for id, marker := range []string{"[img-0]", "[img-1]", "[img-2]", "[img-3]"} {
if len(offsets[id]) != 1 || offsets[id][0] != strings.Index(want, marker) {
t.Errorf("tag %s offsets = %v, want its first occurrence", marker, offsets[id])
}
}
}
+2
View File
@@ -59,6 +59,8 @@ func rendererForName(name string) Renderer {
return constructor()
}
switch name {
case "inkling2":
return &inkling2Renderer{useImgTags: RenderImgTags}
case "ripple":
return &RippleRenderer{}
case "qwen3-coder":
+137
View File
@@ -0,0 +1,137 @@
{%- set effort_map = {"none": 0.0, "minimal": 0.1, "low": 0.2, "medium": 0.7, "high": 0.9, "xhigh": 0.99, "max": 0.99} -%}
{%- set role_token = {"user": "<|message_user|>", "assistant": "<|message_model|>", "system": "<|message_system|>", "tool": "<|message_tool|>"} -%}
{%- macro emit_thinking_effort() -%}
{%- set eff = reasoning_effort if reasoning_effort is defined and reasoning_effort is not none else 0.9 -%}
{%- if eff is string -%}
{%- set key = eff | trim -%}
{%- if key not in effort_map -%}
{{- raise_exception("Unknown reasoning_effort: " ~ eff) -}}
{%- endif -%}
{%- set num = effort_map[key] -%}
{%- else -%}
{%- set num = eff | float -%}
{%- endif -%}
{%- if num < 0.0 or num > 0.99 -%}
{{- raise_exception("reasoning_effort must be in [0.0, 0.99]") -}}
{%- endif -%}
{{- "<|message_system|><|content_text|>Thinking effort level: " -}}
{%- if num == 0.0 -%}0{%- else -%}{{ num }}{%- endif -%}
{{- "<|end_message|>" -}}
{%- endmacro -%}
{%- if tools -%}
{%- set tool_state = namespace(specs=[]) -%}
{%- for tool in tools -%}
{%- set fn = tool.function if tool.function is defined else tool -%}
{%- set spec = {
"description": (fn.description if fn.description is defined and fn.description else ""),
"name": fn.name,
"parameters": (fn.parameters if fn.parameters is defined and fn.parameters else {}),
"type": (tool.type if tool.type is defined and tool.type else "function"),
} -%}
{%- set tool_state.specs = tool_state.specs + [spec] -%}
{%- endfor -%}
{{- "<|message_system|>tool_declare<|content_xml|>" -}}
{{- tool_state.specs | tojson(sort_keys=true, separators=(",", ":")) -}}
{{- "<|end_message|>" -}}
{%- endif -%}
{%- set state = namespace(effort_emitted=false) -%}
{%- for message in messages -%}
{%- if message.role not in role_token -%}
{{- raise_exception("Unknown message role: " ~ message.role) -}}
{%- endif -%}
{%- if not state.effort_emitted and message.role != "system" -%}
{{- emit_thinking_effort() -}}
{%- set state.effort_emitted = true -%}
{%- endif -%}
{%- set header = namespace(text=role_token[message.role]) -%}
{%- if message.role == "tool" -%}
{%- if message.name is defined and message.name -%}
{%- set header.text = header.text ~ message.name -%}
{%- elif message.tool_call_id is defined and message.tool_call_id -%}
{%- for prev in messages -%}
{%- if prev.role == "assistant" and prev.tool_calls -%}
{%- for tc in prev.tool_calls -%}
{%- if tc.id is defined and tc.id == message.tool_call_id and tc.function.name is defined -%}
{%- set header.text = header.text ~ tc.function.name -%}
{%- endif -%}
{%- endfor -%}
{%- endif -%}
{%- endfor -%}
{%- endif -%}
{%- elif message.role == "assistant" and message.name is defined and message.name -%}
{%- set header.text = header.text ~ message.name -%}
{%- endif -%}
{%- set rtok = header.text -%}
{%- set rendered -%}
{%- if message.role == "assistant" and message.reasoning_content is defined and message.reasoning_content -%}
{{- rtok ~ "<|content_thinking|>" ~ message.reasoning_content ~ "<|end_message|>" -}}
{%- endif -%}
{%- if message.content is string and (message.content or not (message.role == "assistant" and (message.tool_calls or message.reasoning_content))) -%}
{{- rtok ~ "<|content_text|>" ~ message.content ~ "<|end_message|>" -}}
{%- elif message.content -%}
{%- for part in message.content -%}
{%- if part is string -%}
{{- rtok ~ "<|content_text|>" ~ part ~ "<|end_message|>" -}}
{%- elif part.type is not defined or part.type in ("text", "input_text") -%}
{%- set text_part = (part.text if part.text is defined and part.text is string else "") -%}
{{- rtok ~ "<|content_text|>" ~ text_part ~ "<|end_message|>" -}}
{%- elif part.type in ("image", "input_image", "image_url") -%}
{%- if message.role not in ("user", "tool") -%}
{{- raise_exception("Image content is only supported for user and tool messages") -}}
{%- endif -%}
{{- rtok ~ "<|content_image|><|unused_200054|><|end_message|>" -}}
{%- elif part.type in ("audio", "input_audio", "audio_url") -%}
{{- raise_exception("Inkling 2 does not accept audio input") -}}
{%- else -%}
{{- raise_exception("Unsupported content part type: " ~ part.type) -}}
{%- endif -%}
{%- endfor -%}
{%- endif -%}
{%- if message.role == "assistant" and message.tool_calls -%}
{%- for tc in message.tool_calls -%}
{%- set fn = tc.function -%}
{%- if fn.name is not defined or fn.name is not string -%}
{{- raise_exception("tool call function name must be a string") -}}
{%- endif -%}
{%- if message.name is defined and message.name and message.name != fn.name -%}
{{- raise_exception("assistant name " ~ message.name ~ " does not match its tool call " ~ fn.name) -}}
{%- endif -%}
{%- set args = fn.arguments if fn.arguments is defined and fn.arguments else {} -%}
{%- if args is string -%}
{{- raise_exception("tool call arguments must be a parsed object, not a JSON string; canonicalize upstream") -}}
{%- endif -%}
{%- if args is not mapping -%}
{{- raise_exception("tool call arguments must be an object") -}}
{%- endif -%}
{{- "<|message_model|>" ~ fn.name ~ "<|content_invoke_tool_json|>" -}}
{{- '{"name":' ~ (fn.name | tojson(sort_keys=true, separators=(",", ":"))) ~ ',"args":' -}}
{{- "{" -}}
{%- for key, value in args | dictsort(case_sensitive=true) -%}
{{- (key | tojson) ~ ":" ~ (value | tojson(separators=(",", ":"))) -}}
{%- if not loop.last -%},{%- endif -%}
{%- endfor -%}
{{- "}}<|end_message|>" -}}
{%- endfor -%}
{%- endif -%}
{%- if message.role == "assistant" -%}
{{- "<|content_model_end_sampling|>" -}}
{%- endif -%}
{%- endset -%}
{%- if message.role == "assistant" -%}
{%- generation -%}{{- rendered -}}{%- endgeneration -%}
{%- else -%}
{{- rendered -}}
{%- endif -%}
{%- endfor -%}
{%- if not state.effort_emitted -%}
{{- emit_thinking_effort() -}}
{%- endif -%}
+13 -2
View File
@@ -82,8 +82,19 @@ func chatPrompt(ctx context.Context, m *Model, tokenize tokenizeFunc, opts *api.
return "", nil, err
}
// truncate any messages that do not fit into the context window
p, err := renderPrompt(m, append(system, renderMsgs[currMsgIdx:]...), tools, think)
renderMsgs = append(system, renderMsgs[currMsgIdx:]...)
if len(media) > 0 && m.IsMLX() && m.Config.Renderer == "inkling2" {
prompt, offsets, err := renderers.RenderInkling2WithImages(renderMsgs, tools, think)
if err != nil {
return "", nil, err
}
for i := range media {
media[i].TagOffsets = offsets[media[i].ID]
}
return prompt, media, nil
}
p, err := renderPrompt(m, renderMsgs, tools, think)
if err != nil {
return "", nil, err
}
+31
View File
@@ -3,6 +3,7 @@ package server
import (
"bytes"
"context"
"slices"
"strings"
"testing"
@@ -474,6 +475,12 @@ func TestChatPromptRendererAddsToolImageTags(t *testing.T) {
wantUserTag: "<|im_start|>user\n[img-0]look at this file<|im_end|>\n",
wantToolContent: "<tool_response>\n[img-1]\nattached image\n</tool_response>",
},
{
name: "inkling2",
renderer: "inkling2",
wantUserTag: "<|message_user|><|content_image|>[img-0]<|end_message|><|message_user|><|content_text|>look at this file<|end_message|>",
wantToolContent: "<|message_tool|>Read<|content_image|>[img-1]<|end_message|><|message_tool|>Read<|content_text|>attached image<|end_message|>",
},
}
for _, tt := range tests {
@@ -576,6 +583,30 @@ func TestChatPromptRendererPreservesExplicitImagePlaceholders(t *testing.T) {
}
}
func TestChatPromptInklingImageOffsetsAfterTruncation(t *testing.T) {
const literal = "\x00<|content_image|>[img-0]<|end_message|>"
messages := []api.Message{
{Role: "system", Content: literal},
{Role: "user", Content: strings.Repeat("old ", 100), Images: []api.ImageData{{1}}},
{Role: "user", Content: "[img-1][img-0][img-1]", Images: []api.ImageData{{2}, {3}}},
}
m := Model{Config: model.ConfigV2{ModelFormat: "safetensors", Renderer: "inkling2"}}
opts := api.Options{Runner: api.Runner{NumCtx: 30}}
prompt, media, err := chatPrompt(t.Context(), &m, mockRunner{}.Tokenize, &opts, messages, nil, nil, true)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(prompt, literal) || strings.Contains(prompt, "old") || len(media) != 2 {
t.Fatalf("trimmed prompt %q, media %v", prompt, media)
}
want := [][]int{{strings.LastIndex(prompt, "[img-0]")}, {strings.Index(prompt, "[img-1]"), strings.LastIndex(prompt, "[img-1]")}}
for i, m := range media {
if len(m.Data) != 1 || m.Data[0] != byte(i+2) || !slices.Equal(m.TagOffsets, want[i]) {
t.Errorf("attachment %d = %+v, want data %d at offsets %v", i, m, i+2, want[i])
}
}
}
func TestChatPromptLFM3PreservesIndexedImagePlaceholders(t *testing.T) {
msgs := []api.Message{{
Role: "user",
+37 -4
View File
@@ -691,6 +691,11 @@ func (s *Server) GenerateHandler(c *gin.Context) {
}
// TEMP(drifkin): req.Context will be removed very soon, but we're temporarily supporting it in this flow here
if req.Context != nil {
for i := range media {
for j := range media[i].TagOffsets {
media[i].TagOffsets[j] += b.Len()
}
}
b.WriteString(prompt)
prompt = b.String()
}
@@ -747,8 +752,9 @@ func (s *Server) GenerateHandler(c *gin.Context) {
// A raw prompt gives no way to tell where the response starts, so the
// format applies from its first token.
var thinkingClose []string
var formatFrames *model.StructuredOutputFrames
if !req.Raw {
thinkingClose = thinkingCloseForCompletion(builtinParser, thinkTagParser)
thinkingClose, formatFrames = prepareStructuredOutput(builtinParser, thinkTagParser, req.Format, prompt)
}
if err := r.Completion(ctx, llm.CompletionRequest{
@@ -763,6 +769,7 @@ func (s *Server) GenerateHandler(c *gin.Context) {
PreservedTokens: preservedTokensForCompletion(builtinParser),
LeadingBOS: leadingBOS,
ThinkingClose: thinkingClose,
FormatFrames: formatFrames,
}, func(cr llm.CompletionResponse) {
res := api.GenerateResponse{
Model: req.Model,
@@ -2049,7 +2056,7 @@ func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
}
// Populate tensor info if verbose
if req.Verbose {
if tensors, err := getSafetensorsTensorInfoForRunner(name, req.Runner); err == nil {
if tensors, err := getTensorInfoFromManifest(mf, modelDetails.Family); err == nil {
resp.Tensors = tensors
}
}
@@ -2905,6 +2912,22 @@ func thinkingCloseForCompletion(builtinParser parsers.Parser, thinkTagParser *th
return nil
}
// The sampler needs the response framing before it generates tokens. Let the
// parser recognize any opener already in the prompt before asking where thinking ends.
func prepareStructuredOutput(parser parsers.Parser, tagParser *thinkingparser.Parser, format json.RawMessage, prompt string) ([]string, *model.StructuredOutputFrames) {
var frames *model.StructuredOutputFrames
switch string(format) {
case "", `null`, `""`:
default:
if p, ok := parser.(interface {
StructuredOutputFrames(string) *model.StructuredOutputFrames
}); ok {
frames = p.StructuredOutputFrames(prompt)
}
}
return thinkingCloseForCompletion(parser, tagParser), frames
}
func leadingBOSForModel(m *Model) string {
if m == nil || m.Config.Renderer == "" {
return ""
@@ -3345,6 +3368,7 @@ func (s *Server) ChatHandler(c *gin.Context) {
var parserErr error
thinkingClose, formatFrames := prepareStructuredOutput(builtinParser, thinkTagParser, req.Format, prompt)
err := r.Completion(ctx, llm.CompletionRequest{
Prompt: prompt,
Media: media,
@@ -3357,7 +3381,8 @@ func (s *Server) ChatHandler(c *gin.Context) {
PreservedTokens: preservedTokensForCompletion(builtinParser),
ToolCallTag: toolCallTagForCompletion(toolParser),
LeadingBOS: leadingBOSForModel(m),
ThinkingClose: thinkingCloseForCompletion(builtinParser, thinkTagParser),
ThinkingClose: thinkingClose,
FormatFrames: formatFrames,
}, func(r llm.CompletionResponse) {
res := api.ChatResponse{
Model: req.Model,
@@ -3659,7 +3684,15 @@ func chatMessagesForRequest(m *Model, requestMessages []api.Message) []api.Messa
// Loaded runners retain m, so request messages must not share its backing slice.
msgs := append(slices.Clone(m.Messages), requestMessages...)
if requestMessages[0].Role != "system" && m.System != "" {
if m.Config.Renderer == "inkling2" {
// Inkling2's serving protocol maps developer instructions to system messages.
for i := range msgs {
if msgs[i].Role == "developer" {
msgs[i].Role = "system"
}
}
}
if msgs[len(m.Messages)].Role != "system" && m.System != "" {
msgs = append([]api.Message{{Role: "system", Content: m.System}}, msgs...)
}
return filterThinkTags(msgs, m)
+25
View File
@@ -798,6 +798,31 @@ func TestGenerateHandlerChatTemplateRoute(t *testing.T) {
})
}
func TestGenerateInklingImageAfterContext(t *testing.T) {
t.Setenv("OLLAMA_MODELS", t.TempDir())
const name = "inkling-generate"
const prefix = "prior 🖼\x00<|content_image|>[img-0]<|end_message|>"
mock := mockRunner{
DetokenizeFn: func(context.Context, []int) (string, error) { return prefix, nil },
CompletionResponse: llm.CompletionResponse{Done: true, DoneReason: llm.DoneReasonStop},
}
s := newServerWithMockRunner(t, &mock)
createSafetensorsTestModel(t, name, model.ConfigV2{
ModelFormat: "safetensors", Renderer: "inkling2", Capabilities: []string{"completion", "vision"},
}, nil)
w := createRequest(t, s.GenerateHandler, api.GenerateRequest{
Model: name, Prompt: "look[img]", Images: []api.ImageData{{1}}, Context: []int{1}, Stream: new(false),
})
if w.Code != http.StatusOK {
t.Fatalf("generate status %d: %s", w.Code, w.Body)
}
got := mock.CompletionRequest
want := strings.LastIndex(got.Prompt, "[img-0]")
if !strings.HasPrefix(got.Prompt, prefix) || want < len(prefix) || len(got.Media) != 1 || !slices.Equal(got.Media[0].TagOffsets, []int{want}) {
t.Fatalf("generate prompt %q, media %+v; want attachment only at %d", got.Prompt, got.Media, want)
}
}
func TestGenerateChatRemote(t *testing.T) {
gin.SetMode(gin.TestMode)
+73
View File
@@ -30,6 +30,7 @@ import (
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/fs/gguf"
gguftest "github.com/ollama/ollama/internal/testutil/gguf"
"github.com/ollama/ollama/llm"
"github.com/ollama/ollama/manifest"
"github.com/ollama/ollama/model/renderers"
"github.com/ollama/ollama/openai"
@@ -258,6 +259,29 @@ func TestLoadedModelLookupDoesNotWaitForUnrelatedRunner(t *testing.T) {
}
}
func TestInkling2ChatMapsDeveloperInstructions(t *testing.T) {
m := &Model{System: "model default"}
m.Config.Renderer = "inkling2"
request := []api.Message{
{Role: "developer", Content: "follow the tool instructions"},
{Role: "user", Content: "find the weather"},
{Role: "developer", Content: "return a tool call"},
}
want := slices.Clone(request)
want[0].Role = "system"
want[2].Role = "system"
if got := chatMessagesForRequest(m, request); !reflect.DeepEqual(got, want) {
t.Fatalf("messages = %+v, want %+v", got, want)
}
if request[0].Role != "developer" || request[2].Role != "developer" {
t.Fatal("request messages were modified")
}
m.Config.Renderer = "flint"
if got := chatMessagesForRequest(m, request); len(got) != 4 || got[1].Role != "developer" || got[3].Role != "developer" {
t.Fatalf("explicit developer roles were changed for another renderer: %+v", got)
}
}
func TestChatMessagesForRequestIsolation(t *testing.T) {
defaults := make([]api.Message, 1, 4)
defaults[0] = api.Message{Role: "assistant", Content: "<think>saved reasoning</think>saved reply"}
@@ -2496,3 +2520,52 @@ func TestShowRendererParserAndTemplateSource(t *testing.T) {
t.Errorf("template source = %q, want none", resp.TemplateSource)
}
}
func TestGenerateInklingStructuredFormat(t *testing.T) {
t.Setenv("OLLAMA_MODELS", t.TempDir())
const name = "inkling-structured"
mock := mockRunner{CompletionResponse: llm.CompletionResponse{Done: true, DoneReason: llm.DoneReasonStop}}
s := newServerWithMockRunner(t, &mock)
createSafetensorsTestModel(t, name, model.ConfigV2{
ModelFormat: "safetensors", Renderer: "inkling2", Parser: "inkling2", Capabilities: []string{"completion", "thinking"},
}, nil)
const answer = `{"text":"<|end_message|><|content_thinking|>"}`
const thought, text, end = "<|message_model|><|content_thinking|>", "<|message_model|><|content_text|>", "<|end_message|>"
for _, tc := range []struct {
name, template string
think bool
generation string
wantThinking string
wantFrames bool
}{
{"publisher", "", true, thought + "check" + end + text + answer, "check", true},
{"publisher no thought", "", false, text + answer, "", true},
{"custom", "{{ .Prompt }}", true, thought + "check" + end + text + answer, "check", false},
{"custom plain", "{{ .Prompt }}", false, answer, "", false},
{"open thought", "{{ .Prompt }}" + thought + "\n", true, "check" + end + text + answer, "check", true},
{"open hidden thought", "{{ .Prompt }}" + thought, false, "check" + end + text + answer, "", true},
{"open answer", "{{ .Prompt }}" + text + " ", true, answer, "", false},
{"open answer no thought", "{{ .Prompt }}" + text, false, answer, "", false},
} {
t.Run(tc.name, func(t *testing.T) {
mock.CompletionResponse.Content = tc.generation
w := createRequest(t, s.GenerateHandler, api.GenerateRequest{
Model: name, Prompt: "hello", Template: tc.template, Format: json.RawMessage(`"json"`),
Think: &api.ThinkValue{Value: tc.think}, Stream: new(false),
})
if w.Code != http.StatusOK {
t.Fatalf("generate status %d: %s", w.Code, w.Body)
}
var response api.GenerateResponse
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
if response.Response != answer || response.Thinking != tc.wantThinking {
t.Fatalf("content %q, thinking %q", response.Response, response.Thinking)
}
if frames := mock.CompletionRequest.FormatFrames; (frames != nil) != tc.wantFrames {
t.Errorf("grammar frames = %+v, want frames %v", frames, tc.wantFrames)
}
})
}
}
+32 -10
View File
@@ -17,6 +17,8 @@ import (
"github.com/ollama/ollama/types/model"
)
const inkling2ModelType = "inkling2_loop"
func canonicalQuantType(quantType string) string {
return strings.ToLower(strings.TrimSpace(quantType))
}
@@ -70,7 +72,7 @@ func getSafetensorsLLMInfoForRunner(name model.Name, runner string) (map[string]
// For quantized models, byte-based estimation can significantly undercount
// parameters. Prefer exact counting from tensor shapes in safetensors headers.
if paramCount, err := getParameterCountFromManifest(mf); err == nil && paramCount > 0 {
if paramCount, err := getParameterCountFromManifest(mf, config.ModelType); err == nil && paramCount > 0 {
info["general.parameter_count"] = paramCount
}
@@ -174,14 +176,18 @@ func buildModelInfo(config modelConfig, totalTensorBytes, tensorCount int64) map
// getParameterCountFromManifest counts model parameters from tensor shapes.
// This accounts for quantized tensors by using unpacked shapes from
// getTensorInfoFromManifest.
func getParameterCountFromManifest(mf *manifest.Manifest) (int64, error) {
tensors, err := getTensorInfoFromManifest(mf)
func getParameterCountFromManifest(mf *manifest.Manifest, modelType string) (int64, error) {
tensors, err := getTensorInfoFromManifest(mf, modelType)
if err != nil {
return 0, err
}
var total int64
for _, tensor := range tensors {
// Inkling packages its separate DSpark draft in the same manifest.
if modelType == inkling2ModelType && strings.HasPrefix(tensor.Name, "draft.") {
continue
}
if len(tensor.Shape) == 0 {
continue
}
@@ -225,14 +231,14 @@ func getSafetensorsTensorInfoForRunner(name model.Name, runner string) ([]api.Te
return nil, fmt.Errorf("failed to load manifest: %w", err)
}
return getTensorInfoFromManifest(mf)
return getTensorInfoFromManifest(mf, "")
}
// getTensorInfoFromManifest extracts tensor info from a manifest.
// This is separated for testability.
// For quantized tensors, reads quant_type from blob __metadata__.
// For packed blobs (multiple tensors per blob), enumerates all tensors in the blob.
func getTensorInfoFromManifest(mf *manifest.Manifest) ([]api.Tensor, error) {
func getTensorInfoFromManifest(mf *manifest.Manifest, modelType string) ([]api.Tensor, error) {
var tensors []api.Tensor
for _, layer := range mf.Layers {
@@ -251,7 +257,7 @@ func getTensorInfoFromManifest(mf *manifest.Manifest) ([]api.Tensor, error) {
continue
}
allInfos, err := parseSafetensorsAllHeaders(f)
allInfos, err := parseSafetensorsAllHeaders(f, modelType)
f.Close()
if err != nil {
continue
@@ -267,7 +273,8 @@ func getTensorInfoFromManifest(mf *manifest.Manifest) ([]api.Tensor, error) {
tensorName = info.Name
}
if info.QuantType != "" {
// Inkling's dense tensors retain their own dtype in a quantized blob.
if info.QuantType != "" && (modelType != inkling2ModelType || info.Dtype == "U32") {
quantType := canonicalQuantType(info.QuantType)
shape := make([]uint64, len(info.Shape))
@@ -335,7 +342,7 @@ func getSafetensorsDtypeForRunner(name model.Name, runner string) (string, error
if err != nil {
continue
}
infos, err := parseSafetensorsAllHeaders(f)
infos, err := parseSafetensorsAllHeaders(f, "")
_ = f.Close()
if err != nil {
continue
@@ -392,7 +399,7 @@ type safetensorsTensorInfo struct {
// For packed blobs this returns multiple entries; for single-tensor blobs, one entry.
// Each tensor's quant type is inferred from its shape and the presence of .scale/.bias entries
// when no global __metadata__ quant_type is present.
func parseSafetensorsAllHeaders(r io.Reader) ([]safetensorsTensorInfo, error) {
func parseSafetensorsAllHeaders(r io.Reader, modelType string) ([]safetensorsTensorInfo, error) {
var headerSize uint64
if err := binary.Read(r, binary.LittleEndian, &headerSize); err != nil {
return nil, fmt.Errorf("failed to read header size: %w", err)
@@ -431,7 +438,11 @@ func parseSafetensorsAllHeaders(r io.Reader) ([]safetensorsTensorInfo, error) {
// Collect all main tensor entries (sorted for deterministic output)
var mainNames []string
for name := range header {
if isSafetensorsCompanionTensor(name) {
if modelType == inkling2ModelType {
if isInkling2CompanionTensor(name, headerKeys) {
continue
}
} else if isSafetensorsCompanionTensor(name) {
continue
}
mainNames = append(mainNames, name)
@@ -472,6 +483,17 @@ func isSafetensorsCompanionTensor(name string) bool {
strings.HasSuffix(name, ".global_scale")
}
func isInkling2CompanionTensor(name string, keys map[string]bool) bool {
// Inkling has learned biases and clipping scales. A quantization companion
// shares the header with its parent weight.
if isSafetensorsCompanionTensor(name) {
dot := strings.LastIndexByte(name, '.')
return dot < 0 || keys[name[:dot]]
}
return strings.HasSuffix(name, "_weight_scale") && keys[strings.TrimSuffix(name, "_scale")] ||
strings.HasSuffix(name, "_weight_amax") || strings.HasSuffix(name, "_weight_outer_scale_denominator")
}
// inferQuantType infers the quantization type for a tensor from its shape and scale shape.
// Returns "int4", "int8", etc. or "" if not quantized.
func inferQuantType(header map[string]json.RawMessage, name string) string {
+103 -29
View File
@@ -9,6 +9,9 @@ import (
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/manifest"
"github.com/ollama/ollama/types/model"
)
@@ -388,7 +391,7 @@ func TestParseSafetensorsAllHeaders_Errors(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := parseSafetensorsAllHeaders(bytes.NewReader(tt.data))
_, err := parseSafetensorsAllHeaders(bytes.NewReader(tt.data), "")
if err == nil {
t.Error("expected error, got nil")
return
@@ -484,7 +487,7 @@ func TestGetTensorInfoFromManifest(t *testing.T) {
Layers: layers,
}
result, err := getTensorInfoFromManifest(mf)
result, err := getTensorInfoFromManifest(mf, "")
if err != nil {
t.Fatalf("getTensorInfoFromManifest() error = %v", err)
}
@@ -570,7 +573,7 @@ func TestGetTensorInfoFromManifest_Quantized(t *testing.T) {
},
}
result, err := getTensorInfoFromManifest(mf)
result, err := getTensorInfoFromManifest(mf, "")
if err != nil {
t.Fatalf("getTensorInfoFromManifest() error = %v", err)
}
@@ -772,7 +775,7 @@ func TestGetParameterCountFromManifest(t *testing.T) {
},
}
paramCount, err := getParameterCountFromManifest(mf)
paramCount, err := getParameterCountFromManifest(mf, "")
if err != nil {
t.Fatalf("getParameterCountFromManifest() error = %v", err)
}
@@ -855,7 +858,7 @@ func TestGetParameterCountFromManifest_MixedQuantizedPacked(t *testing.T) {
},
}
paramCount, err := getParameterCountFromManifest(mf)
paramCount, err := getParameterCountFromManifest(mf, "")
if err != nil {
t.Fatalf("getParameterCountFromManifest() error = %v", err)
}
@@ -1044,7 +1047,7 @@ func TestParseSafetensorsAllHeaders(t *testing.T) {
}
buf.Write(headerJSON)
results, err := parseSafetensorsAllHeaders(&buf)
results, err := parseSafetensorsAllHeaders(&buf, "")
if (err != nil) != tt.wantErr {
t.Errorf("parseSafetensorsAllHeaders() error = %v, wantErr %v", err, tt.wantErr)
return
@@ -1166,7 +1169,7 @@ func TestGetTensorInfoFromManifest_Packed(t *testing.T) {
},
}
result, err := getTensorInfoFromManifest(mf)
result, err := getTensorInfoFromManifest(mf, "")
if err != nil {
t.Fatalf("getTensorInfoFromManifest() error = %v", err)
}
@@ -1208,31 +1211,31 @@ func TestGetTensorInfoFromManifest_Packed(t *testing.T) {
}
}
func writeSafetensorsLayer(t *testing.T, header map[string]any, name string) manifest.Layer {
t.Helper()
headerJSON, err := json.Marshal(header)
if err != nil {
t.Fatalf("failed to marshal header: %v", err)
}
var buf bytes.Buffer
if err := binary.Write(&buf, binary.LittleEndian, uint64(len(headerJSON))); err != nil {
t.Fatalf("failed to write header size: %v", err)
}
buf.Write(headerJSON)
layer, err := manifest.NewLayer(&buf, manifest.MediaTypeImageTensor)
if err != nil {
t.Fatalf("failed to create tensor layer: %v", err)
}
layer.Name = name
return layer
}
func TestGetSafetensorsDtypeChoosesLowestPrecisionQuantizedBlob(t *testing.T) {
t.Setenv("OLLAMA_MODELS", t.TempDir())
writeSafetensorsLayer := func(t *testing.T, header map[string]any, name string) manifest.Layer {
t.Helper()
headerJSON, err := json.Marshal(header)
if err != nil {
t.Fatalf("failed to marshal header: %v", err)
}
var buf bytes.Buffer
if err := binary.Write(&buf, binary.LittleEndian, uint64(len(headerJSON))); err != nil {
t.Fatalf("failed to write header size: %v", err)
}
buf.Write(headerJSON)
layer, err := manifest.NewLayer(&buf, manifest.MediaTypeImageTensor)
if err != nil {
t.Fatalf("failed to create tensor layer: %v", err)
}
layer.Name = name
return layer
}
configData, err := json.Marshal(map[string]any{
"model_format": "safetensors",
})
@@ -1331,3 +1334,74 @@ func TestGetSafetensorsDtypeChoosesLowestPrecisionQuantizedBlob(t *testing.T) {
t.Fatalf("getSafetensorsDtypeForRunner() = %q, want target bfloat16", got)
}
}
func TestShowInkling2Tensors(t *testing.T) {
t.Setenv("OLLAMA_MODELS", t.TempDir())
const nv = "model.llm.layers.0.mlp.experts.w13_weight"
const mx = "model.llm.layers.1.mlp.experts.w2_weight"
const clip = "model.llm.layers.0.attn.q_l2_clip.scale"
const bias = "model.visual.backbone.layers.0.ln_1.bias"
const draft = "draft.markov_head.hidden_out.bias"
// The importer stores a packed U32 weight and its U8 block scales in one
// blob, and keeps the NVFP4 outer-scale parameters in separate blobs.
bank := func(name, mode string, weight, scales []int) map[string]any {
return map[string]any{
"__metadata__": map[string]string{"quant_type": mode},
name: map[string]any{"dtype": "U32", "shape": weight},
name + "_scale": map[string]any{"dtype": "U8", "shape": scales},
}
}
hfConfig, err := manifest.NewLayer(strings.NewReader(`{"model_type":"inkling2_loop"}`), manifest.MediaTypeImageJSON)
if err != nil {
t.Fatal(err)
}
hfConfig.Name = "config.json"
config, err := createConfigLayer(model.ConfigV2{ModelFormat: manifest.FormatSafetensors, Capabilities: []string{"completion"}})
if err != nil {
t.Fatal(err)
}
name := model.ParseName("show-inkling")
// Packed headers may name several primaries. The learned clipping scale
// and bias retain their own dtype and shape alongside a quantized bank.
packed := bank(mx, "mxfp8", []int{2, 4, 8}, []int{2, 4, 1})
packed[clip] = map[string]any{"dtype": "F32", "shape": []int{2, 3}}
packed[bias] = map[string]any{"dtype": "F32", "shape": []int{3}}
layers := []manifest.Layer{
hfConfig,
writeSafetensorsLayer(t, bank(nv, "nvfp4", []int{2, 3, 4}, []int{2, 3, 2}), nv),
writeSafetensorsLayer(t, packed, "model.packed"),
createShowSafetensorsLayer(t, nv+"_amax", []int64{2}),
createShowSafetensorsLayer(t, nv+"_outer_scale_denominator", []int64{1}),
createShowSafetensorsLayer(t, draft, []int64{5}),
}
if err := manifest.WriteManifestWithMetadata(name, *config, layers, manifest.RunnerMLX, manifest.FormatSafetensors); err != nil {
t.Fatal(err)
}
for _, verbose := range []bool{false, true} {
resp, err := GetModelInfo(api.ShowRequest{Model: name.String(), Verbose: verbose})
if err != nil {
t.Fatal(err)
}
if got := resp.ModelInfo["general.parameter_count"]; got != int64(457) {
t.Fatalf("parameter count = %v, want 457", got)
}
if got := resp.Details.ParameterSize; got != "457" {
t.Fatalf("parameter size = %q, want 457", got)
}
var want []api.Tensor
if verbose {
want = []api.Tensor{
{Name: draft, Type: "F32", Shape: []uint64{5}},
{Name: clip, Type: "F32", Shape: []uint64{2, 3}},
{Name: nv, Type: "nvfp4", Shape: []uint64{2, 3, 32}},
{Name: mx, Type: "mxfp8", Shape: []uint64{2, 4, 32}},
{Name: bias, Type: "F32", Shape: []uint64{3}},
}
}
if diff := cmp.Diff(want, resp.Tensors); diff != "" {
t.Fatalf("verbose=%t tensor inventory (-want +got):\n%s", verbose, diff)
}
}
}
+11
View File
@@ -0,0 +1,11 @@
package model
// StructuredOutputFrames describes the markers a model can emit before a
// structured answer. A thinking close without an open continues a thought
// the template already opened.
type StructuredOutputFrames struct {
ThinkingOpen string
ThinkingClose string
ThinkingExcludes []string
ContentOpen string
}