Skip to content

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

mlxrunner, cmd, server: fold three small packages into their users

Jesse Gross04b450a81b19
diff --git a/cmd/cmd.go b/cmd/cmd.go
index baba019c1..7eb645afb 100644
--- a/cmd/cmd.go
+++ b/cmd/cmd.go
@@ -43,7 +43,6 @@ import (
"github.com/ollama/ollama/cmd/launch"
"github.com/ollama/ollama/cmd/tui"
"github.com/ollama/ollama/create"
- createclient "github.com/ollama/ollama/create/client"
"github.com/ollama/ollama/discover"
"github.com/ollama/ollama/envconfig"
"github.com/ollama/ollama/format"
@@ -241,28 +240,28 @@ func readCreateModelfile(cmd *cobra.Command) (*parser.Modelfile, string, error)
return modelfile, filename, nil
}
-func safetensorsCreateOptions(modelfile *parser.Modelfile, filename, modelName string) (createclient.CreateOptions, bool, error) {
- modelDir, mfConfig, err := createclient.ConfigFromModelfile(modelfile)
+func safetensorsCreateOptions(modelfile *parser.Modelfile, filename, modelName string) (createOptions, bool, error) {
+ modelDir, mfConfig, err := configFromModelfile(modelfile)
if err != nil {
- return createclient.CreateOptions{}, false, err
+ return createOptions{}, false, err
}
modelDir = resolveCreateLocalModelDir(modelDir, filename)
isSafetensors := create.IsSafetensorsModelDir(modelDir)
isBaseModelWithDraft := mfConfig.Draft != "" && !isSafetensors && create.IsSafetensorsLLMModel(modelDir)
if !isSafetensors && !isBaseModelWithDraft {
- return createclient.CreateOptions{}, false, nil
+ return createOptions{}, false, nil
}
if mfConfig.Draft != "" {
draftDir, err := resolveCreateDraftDir(mfConfig.Draft, filename)
if err != nil {
if isSafetensors {
- return createclient.CreateOptions{}, false, err
+ return createOptions{}, false, err
}
// Existing safetensors models may still use a GGUF DRAFT layer;
// leave that combination on the standard create path.
- return createclient.CreateOptions{}, false, nil
+ return createOptions{}, false, nil
}
mfConfig.Draft = draftDir
}
@@ -277,13 +276,13 @@ func safetensorsCreateOptions(modelfile *parser.Modelfile, filename, modelName s
}
}
if modelCount != 1 {
- return createclient.CreateOptions{}, false, errors.New("safetensors imports require exactly one FROM source")
+ return createOptions{}, false, errors.New("safetensors imports require exactly one FROM source")
}
if draftCount > 1 {
- return createclient.CreateOptions{}, false, errors.New("safetensors imports support at most one DRAFT source")
+ return createOptions{}, false, errors.New("safetensors imports support at most one DRAFT source")
}
- return createclient.CreateOptions{
+ return createOptions{
ModelName: modelName,
ModelDir: modelDir,
Modelfile: mfConfig,
@@ -298,9 +297,9 @@ var (
// createSafetensorsModel imports in-process when the server is local and
// otherwise uploads the source files for the server to import.
-func createSafetensorsModel(cmd *cobra.Command, args []string, opts createclient.CreateOptions, p *progress.Progress) error {
+func createSafetensorsModel(cmd *cobra.Command, args []string, opts createOptions, p *progress.Progress) error {
if !envconfig.CreateRemote() && isLocalhost() {
- return createclient.CreateModel(cmd.Context(), opts, p)
+ return createModel(cmd.Context(), opts, p)
}
if opts.Force {
return errForceLocalOnly
@@ -312,7 +311,7 @@ func createSafetensorsModel(cmd *cobra.Command, args []string, opts createclient
if err != nil {
return err
}
- return createclient.CreateModelRemote(cmd.Context(), client, opts, p)
+ return createModelRemote(cmd.Context(), client, opts, p)
}
func CreateHandler(cmd *cobra.Command, args []string) error {
diff --git a/create/client/create.go b/cmd/create_safetensors.go
similarity index 91%
rename from create/client/create.go
rename to cmd/create_safetensors.go
index 80986ce13..e9b276590 100644
--- a/create/client/create.go
+++ b/cmd/create_safetensors.go
@@ -1,11 +1,8 @@
-// Package client provides local and server-backed model creation for
-// safetensors-based models.
-package client
+package cmd
import (
"context"
"encoding/json"
- "errors"
"fmt"
"os"
"slices"
@@ -22,10 +19,8 @@ import (
"github.com/ollama/ollama/types/model"
)
-var errAdaptersUnsupported = errors.New("LoRA adapters are no longer supported")
-
-// ModelfileConfig holds configuration extracted from a Modelfile.
-type ModelfileConfig struct {
+// modelfileConfig holds configuration extracted from a Modelfile.
+type modelfileConfig struct {
Template string
System string
Licenses []string
@@ -49,11 +44,11 @@ var ignoredModelfileParameters = []string{
"mirostat_eta",
}
-// ConfigFromModelfile extracts the model directory and create-specific
+// configFromModelfile extracts the model directory and create-specific
// Modelfile configuration from a parsed Modelfile.
-func ConfigFromModelfile(modelfile *parser.Modelfile) (string, *ModelfileConfig, error) {
+func configFromModelfile(modelfile *parser.Modelfile) (string, *modelfileConfig, error) {
var modelDir string
- mfConfig := &ModelfileConfig{}
+ mfConfig := &modelfileConfig{}
for _, cmd := range modelfile.Commands {
switch cmd.Name {
@@ -118,20 +113,20 @@ func ConfigFromModelfile(modelfile *parser.Modelfile) (string, *ModelfileConfig,
return modelDir, mfConfig, nil
}
-// CreateOptions holds all options for model creation.
-type CreateOptions struct {
+// createOptions holds all options for model creation.
+type createOptions struct {
ModelName string
ModelDir string
Quantize string // "int4", "int8", "nvfp4", "mxfp4", or "mxfp8" for quantization
DraftQuantize string // optional quantization level for draft model tensors
Force bool // create even when MLX validation fails
- Modelfile *ModelfileConfig // template/system/license/parser/renderer/parameters from Modelfile
+ Modelfile *modelfileConfig // template/system/license/parser/renderer/parameters from Modelfile
}
-// CreateModel imports a model from a local directory.
+// createModel imports a model from a local directory.
// This creates blobs and manifest directly on disk, bypassing the HTTP API.
// Automatically detects safetensors source imports and existing safetensors base models.
-func CreateModel(ctx context.Context, opts CreateOptions, p *progress.Progress) error {
+func createModel(ctx context.Context, opts createOptions, p *progress.Progress) error {
// Detect model type
isSafetensors := create.IsSafetensorsModelDir(opts.ModelDir)
hasDraft := opts.Modelfile != nil && opts.Modelfile.Draft != ""
@@ -236,7 +231,7 @@ func CreateModel(ctx context.Context, opts CreateOptions, p *progress.Progress)
return nil
}
-func validateSafetensorsQuantization(opts CreateOptions) error {
+func validateSafetensorsQuantization(opts createOptions) error {
hasDraft := opts.Modelfile != nil && opts.Modelfile.Draft != ""
if opts.DraftQuantize != "" && !hasDraft {
return fmt.Errorf("--draft-quantize requires a DRAFT model")
@@ -250,7 +245,7 @@ func validateSafetensorsQuantization(opts CreateOptions) error {
return nil
}
-func createModelFromBaseWithDraft(ctx context.Context, opts CreateOptions, draftLayers []create.LayerInfo, progressFn func(string)) error {
+func createModelFromBaseWithDraft(ctx context.Context, opts createOptions, draftLayers []create.LayerInfo, progressFn func(string)) error {
if err := ctx.Err(); err != nil {
return err
}
@@ -344,7 +339,7 @@ func readConfigV2(m *manifest.Manifest) (*model.ConfigV2, error) {
return &cfg, nil
}
-func validateDistinctSafetensorsSources(modelDir string, modelfile *ModelfileConfig) error {
+func validateDistinctSafetensorsSources(modelDir string, modelfile *modelfileConfig) error {
if modelfile == nil || modelfile.Draft == "" {
return nil
}
@@ -364,7 +359,7 @@ func validateDistinctSafetensorsSources(modelDir string, modelfile *ModelfileCon
}
// newManifestWriter returns a ManifestWriter callback for writing the model manifest.
-func newManifestWriter(opts CreateOptions) create.ManifestWriter {
+func newManifestWriter(opts createOptions) create.ManifestWriter {
var template, system, draftDir string
var license any
var parameters map[string]any
diff --git a/create/client/remote.go b/cmd/create_safetensors_remote.go
similarity index 96%
rename from create/client/remote.go
rename to cmd/create_safetensors_remote.go
index 515e6484e..2db47bf36 100644
--- a/create/client/remote.go
+++ b/cmd/create_safetensors_remote.go
@@ -1,4 +1,4 @@
-package client
+package cmd
import (
"context"
@@ -26,10 +26,10 @@ import (
// Six attempts produce at most 31 seconds of exponential backoff per blob.
const maxUploadRetries = 6
-// CreateModelRemote uploads raw safetensors source files and asks the server to
+// createModelRemote uploads raw safetensors source files and asks the server to
// run the create import pipeline. The server performs planning, transforms,
// and MLX quantization against its own hardware.
-func CreateModelRemote(ctx context.Context, client *api.Client, opts CreateOptions, p *progress.Progress) error {
+func createModelRemote(ctx context.Context, client *api.Client, opts createOptions, p *progress.Progress) error {
if opts.Force {
return errors.New("--force is only supported for local MLX safetensors imports")
}
@@ -262,7 +262,7 @@ func (pr *progressReader) Read(p []byte) (int, error) {
return n, err
}
-func newRemoteCreateRequest(opts CreateOptions, files []remoteSourceFile) *api.CreateRequest {
+func newRemoteCreateRequest(opts createOptions, files []remoteSourceFile) *api.CreateRequest {
req := &api.CreateRequest{
Model: opts.ModelName,
Files: make(map[string]string),
diff --git a/create/client/remote_test.go b/cmd/create_safetensors_remote_test.go
similarity index 97%
rename from create/client/remote_test.go
rename to cmd/create_safetensors_remote_test.go
index d687fafa4..72bfdae7e 100644
--- a/create/client/remote_test.go
+++ b/cmd/create_safetensors_remote_test.go
@@ -1,4 +1,4 @@
-package client
+package cmd
import (
"context"
@@ -122,11 +122,11 @@ func TestPrepareRemoteSourceFilesCanceled(t *testing.T) {
}
func TestNewRemoteCreateRequest(t *testing.T) {
- req := newRemoteCreateRequest(CreateOptions{
+ req := newRemoteCreateRequest(createOptions{
ModelName: "example",
Quantize: "nvfp4",
DraftQuantize: "mxfp8",
- Modelfile: &ModelfileConfig{
+ Modelfile: &modelfileConfig{
Template: "{{ .Prompt }}",
System: "system",
Licenses: []string{"MIT", "Apache-2.0"},
@@ -170,9 +170,9 @@ func TestNewRemoteCreateRequest(t *testing.T) {
}
func TestCreateModelRemoteRejectsForceBeforeReadingSource(t *testing.T) {
- err := CreateModelRemote(t.Context(), nil, CreateOptions{Force: true, ModelDir: "missing"}, nil)
+ err := createModelRemote(t.Context(), nil, createOptions{Force: true, ModelDir: "missing"}, nil)
if err == nil || !strings.Contains(err.Error(), "only supported for local") {
- t.Fatalf("CreateModelRemote() error = %v, want local-only force error", err)
+ t.Fatalf("createModelRemote() error = %v, want local-only force error", err)
}
}
diff --git a/create/client/create_test.go b/cmd/create_safetensors_test.go
similarity index 92%
rename from create/client/create_test.go
rename to cmd/create_safetensors_test.go
index f5e67f9bc..78a587510 100644
--- a/create/client/create_test.go
+++ b/cmd/create_safetensors_test.go
@@ -1,4 +1,4 @@
-package client
+package cmd
import (
"context"
@@ -20,8 +20,8 @@ import (
)
func TestModelfileConfig(t *testing.T) {
- // Test that ModelfileConfig struct works as expected
- config := &ModelfileConfig{
+ // Test that modelfileConfig struct works as expected
+ config := &modelfileConfig{
Template: "{{ .Prompt }}",
System: "You are a helpful assistant.",
Licenses: []string{"MIT"},
@@ -63,7 +63,7 @@ PARAMETER stop ASSISTANT:
t.Fatal(err)
}
- modelDir, mfConfig, err := ConfigFromModelfile(modelfile)
+ modelDir, mfConfig, err := configFromModelfile(modelfile)
if err != nil {
t.Fatal(err)
}
@@ -118,7 +118,7 @@ PARAMETER stop ASSISTANT:
t.Fatal(err)
}
- modelDir, got, err := ConfigFromModelfile(modelfile)
+ modelDir, got, err := configFromModelfile(modelfile)
if err != nil {
t.Fatal(err)
}
@@ -130,7 +130,7 @@ PARAMETER stop ASSISTANT:
if !ok {
t.Fatalf("CreateRequest license = %#v, want []string", req.License)
}
- want := &ModelfileConfig{
+ want := &modelfileConfig{
Template: req.Template,
System: req.System,
Licenses: licenses,
@@ -157,7 +157,7 @@ REQUIRES 0.14.0
t.Fatal(err)
}
- _, config, err := ConfigFromModelfile(modelfile)
+ _, config, err := configFromModelfile(modelfile)
if err != nil {
t.Fatal(err)
}
@@ -175,7 +175,7 @@ REQUIRES not-a-version
t.Fatal(err)
}
- _, _, err = ConfigFromModelfile(modelfile)
+ _, _, err = configFromModelfile(modelfile)
if err == nil {
t.Fatal("expected error for invalid semver, got nil")
}
@@ -185,7 +185,7 @@ REQUIRES not-a-version
}
func TestModelfileConfig_Empty(t *testing.T) {
- config := &ModelfileConfig{}
+ config := &modelfileConfig{}
if config.Template != "" {
t.Errorf("Template should be empty, got %q", config.Template)
@@ -206,7 +206,7 @@ func TestModelfileConfig_Empty(t *testing.T) {
func TestModelfileConfig_PartialFields(t *testing.T) {
// Test config with only some fields set
- config := &ModelfileConfig{
+ config := &modelfileConfig{
Template: "{{ .Prompt }}",
// System and License intentionally empty
}
@@ -239,8 +239,8 @@ func TestMinOllamaVersion(t *testing.T) {
}
func TestCreateModel_InvalidDir(t *testing.T) {
- // Test that CreateModel returns error for invalid directory
- err := CreateModel(context.Background(), CreateOptions{
+ // Test that createModel returns error for invalid directory
+ err := createModel(context.Background(), createOptions{
ModelName: "test-model",
ModelDir: "/nonexistent/path",
}, nil)
@@ -250,10 +250,10 @@ func TestCreateModel_InvalidDir(t *testing.T) {
}
func TestCreateModel_NotSafetensorsDir(t *testing.T) {
- // Test that CreateModel returns error for directory without safetensors
+ // Test that createModel returns error for directory without safetensors
dir := t.TempDir()
- err := CreateModel(context.Background(), CreateOptions{
+ err := createModel(context.Background(), createOptions{
ModelName: "test-model",
ModelDir: dir,
}, nil)
@@ -267,8 +267,8 @@ func TestConfigFromModelfileRejectsAdapters(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if _, _, err := ConfigFromModelfile(modelfile); !errors.Is(err, errAdaptersUnsupported) {
- t.Fatalf("ConfigFromModelfile() error = %v, want %v", err, errAdaptersUnsupported)
+ if _, _, err := configFromModelfile(modelfile); !errors.Is(err, errAdaptersUnsupported) {
+ t.Fatalf("configFromModelfile() error = %v, want %v", err, errAdaptersUnsupported)
}
}
@@ -293,9 +293,9 @@ func TestCreateRejectsSameSafetensorsModelAndDraftSource(t *testing.T) {
}
for _, source := range draftSources {
t.Run(source.name, func(t *testing.T) {
- opts := CreateOptions{
+ opts := createOptions{
ModelDir: dir,
- Modelfile: &ModelfileConfig{
+ Modelfile: &modelfileConfig{
Draft: source.path,
},
}
@@ -303,8 +303,8 @@ func TestCreateRejectsSameSafetensorsModelAndDraftSource(t *testing.T) {
name string
create func() error
}{
- {name: "local", create: func() error { return CreateModel(t.Context(), opts, nil) }},
- {name: "remote", create: func() error { return CreateModelRemote(t.Context(), nil, opts, nil) }},
+ {name: "local", create: func() error { return createModel(t.Context(), opts, nil) }},
+ {name: "remote", create: func() error { return createModelRemote(t.Context(), nil, opts, nil) }},
} {
t.Run(tt.name, func(t *testing.T) {
err := tt.create()
@@ -318,7 +318,7 @@ func TestCreateRejectsSameSafetensorsModelAndDraftSource(t *testing.T) {
}
func TestCreateModel_DraftQuantizeRequiresDraft(t *testing.T) {
- err := CreateModel(context.Background(), CreateOptions{
+ err := createModel(context.Background(), createOptions{
ModelName: "test-model",
ModelDir: t.TempDir(),
DraftQuantize: "mxfp8",
@@ -339,22 +339,22 @@ func TestCreateModelCanceledContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
- err := CreateModel(ctx, CreateOptions{
+ err := createModel(ctx, createOptions{
ModelName: "test-model",
ModelDir: dir,
}, nil)
if err != context.Canceled {
- t.Fatalf("CreateModel() error = %v, want context.Canceled", err)
+ t.Fatalf("createModel() error = %v, want context.Canceled", err)
}
}
func TestCreateOptions(t *testing.T) {
- opts := CreateOptions{
+ opts := createOptions{
ModelName: "my-model",
ModelDir: "/path/to/model",
Quantize: "fp8",
DraftQuantize: "mxfp8",
- Modelfile: &ModelfileConfig{
+ Modelfile: &modelfileConfig{
Template: "test",
System: "system",
Licenses: []string{"MIT"},
@@ -396,7 +396,7 @@ func TestCreateOptions(t *testing.T) {
}
func TestCreateOptions_Defaults(t *testing.T) {
- opts := CreateOptions{
+ opts := createOptions{
ModelName: "test",
ModelDir: "/tmp",
}
@@ -418,7 +418,7 @@ func TestCreateOptions_Defaults(t *testing.T) {
func TestNewManifestWriter_PopulatesFileTypeFromEffectiveQuantize(t *testing.T) {
t.Setenv("OLLAMA_MODELS", t.TempDir())
- opts := CreateOptions{
+ opts := createOptions{
ModelName: "test-quantized",
ModelDir: t.TempDir(),
}
@@ -460,10 +460,10 @@ func TestNewManifestWriter_PopulatesFileTypeFromEffectiveQuantize(t *testing.T)
func TestNewManifestWriterPreservesMultipleLicenses(t *testing.T) {
t.Setenv("OLLAMA_MODELS", t.TempDir())
- opts := CreateOptions{
+ opts := createOptions{
ModelName: "test-licenses",
ModelDir: t.TempDir(),
- Modelfile: &ModelfileConfig{
+ Modelfile: &modelfileConfig{
Licenses: []string{"MIT", "Apache-2.0"},
},
}
@@ -508,10 +508,10 @@ func TestNewManifestWriter_PopulatesDraftMetadata(t *testing.T) {
t.Fatalf("WriteFile() error = %v", err)
}
- opts := CreateOptions{
+ opts := createOptions{
ModelName: "test-draft",
ModelDir: t.TempDir(),
- Modelfile: &ModelfileConfig{Draft: draftDir},
+ Modelfile: &modelfileConfig{Draft: draftDir},
}
writer := newManifestWriter(opts)
@@ -588,10 +588,10 @@ func TestCreateModelFromBaseReplacesDraftLayers(t *testing.T) {
draftLayers := []create.LayerInfo{{
Digest: newDraft.Digest, Size: newDraft.Size, MediaType: newDraft.MediaType, Name: newDraft.Name,
}}
- opts := CreateOptions{
+ opts := createOptions{
ModelName: "base-with-replaced-draft:latest",
ModelDir: baseName.String(),
- Modelfile: &ModelfileConfig{Draft: draftDir},
+ Modelfile: &modelfileConfig{Draft: draftDir},
}
if err := createModelFromBaseWithDraft(t.Context(), opts, draftLayers, func(string) {}); err != nil {
t.Fatal(err)
diff --git a/mlxrunner/dflash.go b/mlxrunner/dflash.go
index b4b383e44..fd3bd9542 100644
--- a/mlxrunner/dflash.go
+++ b/mlxrunner/dflash.go
@@ -5,7 +5,7 @@ import (
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
- "github.com/ollama/ollama/mlxrunner/model/base"
+ "github.com/ollama/ollama/mlxrunner/model"
)
// dflashPendingFlushTokens bounds the held feature rows between flushes.
@@ -20,7 +20,7 @@ type dflashDrafter struct {
maskToken int32
}
-func newDFlashDrafter(s *speculation, draft base.BlockDraft) *dflashDrafter {
+func newDFlashDrafter(s *speculation, draft model.BlockDraft) *dflashDrafter {
blockSize, maskToken := draft.BlockParams()
return &dflashDrafter{spec: s, blockSize: blockSize, maskToken: maskToken}
}
diff --git a/mlxrunner/dflash_test.go b/mlxrunner/dflash_test.go
index bdcc4e090..660e63d5b 100644
--- a/mlxrunner/dflash_test.go
+++ b/mlxrunner/dflash_test.go
@@ -10,7 +10,7 @@ import (
"github.com/ollama/ollama/mlx/mlxtest"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
- "github.com/ollama/ollama/mlxrunner/model/base"
+ "github.com/ollama/ollama/mlxrunner/model"
sampler "github.com/ollama/ollama/mlxrunner/sample"
)
@@ -88,7 +88,7 @@ func (d *fakeBlockDraft) Forward(b *batch.Batch, _, draftCaches []cache.Cache) (
// Unembed is the identity: the fake's hidden already is its one-hot logits.
func (d *fakeBlockDraft) Unembed(x *mlx.Array) *mlx.Array { return x }
-var _ base.BlockDraft = (*fakeBlockDraft)(nil)
+var _ model.BlockDraft = (*fakeBlockDraft)(nil)
// newBlockTestSession wires a runner around a fakeBlockDraft and opens one
// request's drafting session, returning the concrete session for
diff --git a/mlxrunner/media.go b/mlxrunner/media.go
index a48b3216a..21ab61271 100644
--- a/mlxrunner/media.go
+++ b/mlxrunner/media.go
@@ -12,7 +12,7 @@ import (
"github.com/ollama/ollama/llm"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
- "github.com/ollama/ollama/mlxrunner/model/base"
+ "github.com/ollama/ollama/mlxrunner/model"
)
var imgTagPattern = regexp.MustCompile(`\[img-(\d+)\]`)
@@ -24,7 +24,7 @@ type mediaItem struct {
pos int
length int
fold uint32
- item *base.PreparedItem
+ item *model.PreparedItem
}
// foldValue derives the trie-key substitute for a media item: a hash of the
@@ -46,7 +46,7 @@ func foldValue(data []byte, dims []int) uint32 {
// use, released when the expansion is fully evaluated. A nil
// *requestMedia is a text-only request; every method is nil-safe.
type requestMedia struct {
- model base.MediaModel
+ model model.MediaModel
items []mediaItem
inputLen int
@@ -66,7 +66,7 @@ func (r *Runner) openMedia(request Request) *requestMedia {
return nil
}
m := &requestMedia{
- model: r.Model.(base.MediaModel),
+ model: r.Model.(model.MediaModel),
items: request.MediaItems,
inputLen: len(request.Tokens),
manifest: make([]batch.MediaItem, len(request.MediaItems)),
@@ -174,14 +174,14 @@ func (m *requestMedia) close() {
// expandMedia tokenizes the [img-N]-tagged prompt into segments, expands
// them in a single PrepareMedia call, and validates the authored items
// before keying cache identity on them.
-func (r *Runner) expandMedia(mm base.MediaModel, prompt string, media []llm.MediaData) (*base.PreparedRequest, []mediaItem, error) {
+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))
- var segments []base.Segment
+ var segments []model.Segment
for i, part := range parts {
- segments = append(segments, base.Segment{Tokens: r.Tokenizer.Encode(part, i == 0 && r.Tokenizer.AddBOS())})
+ segments = append(segments, model.Segment{Tokens: r.Tokenizer.Encode(part, i == 0 && r.Tokenizer.AddBOS())})
if i >= len(matches) {
continue
}
@@ -198,7 +198,7 @@ func (r *Runner) expandMedia(mm base.MediaModel, prompt string, media []llm.Medi
return nil, nil, fmt.Errorf("invalid image index: %d", id)
}
referenced[idx] = true
- segments = append(segments, base.Segment{Kind: string(media[idx].Kind), Data: media[idx].Data})
+ segments = append(segments, model.Segment{Kind: string(media[idx].Kind), Data: media[idx].Data})
}
for j := range media {
@@ -220,7 +220,7 @@ func (r *Runner) expandMedia(mm base.MediaModel, prompt string, media []llm.Medi
// bindItems validates the authored ranges before cache identity is keyed
// on them and binds each item to its source segment's bytes.
-func bindItems(prepared *base.PreparedRequest, segments []base.Segment) ([]mediaItem, error) {
+func bindItems(prepared *model.PreparedRequest, segments []model.Segment) ([]mediaItem, error) {
covered := make([]bool, len(segments))
items := make([]mediaItem, 0, len(prepared.Items))
end := 0
diff --git a/mlxrunner/media_test.go b/mlxrunner/media_test.go
index f84023cb4..ebddbc33a 100644
--- a/mlxrunner/media_test.go
+++ b/mlxrunner/media_test.go
@@ -6,7 +6,7 @@ import (
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
- "github.com/ollama/ollama/mlxrunner/model/base"
+ "github.com/ollama/ollama/mlxrunner/model"
)
func TestEffectiveKeyTokens(t *testing.T) {
@@ -30,9 +30,9 @@ func TestEffectiveKeyTokens(t *testing.T) {
func TestExtendChunk(t *testing.T) {
m := &requestMedia{
items: []mediaItem{
- {pos: 10, length: 4, item: &base.PreparedItem{}},
- {pos: 40, length: 8, item: &base.PreparedItem{Causal: true}},
- {pos: 96, length: 4, item: &base.PreparedItem{}},
+ {pos: 10, length: 4, item: &model.PreparedItem{}},
+ {pos: 40, length: 8, item: &model.PreparedItem{Causal: true}},
+ {pos: 96, length: 4, item: &model.PreparedItem{}},
},
inputLen: 100,
}
@@ -67,7 +67,7 @@ type encodeCountingModel struct {
calls *int
}
-func (m encodeCountingModel) EncodeMedia(item *base.PreparedItem, data *mlx.Array) *mlx.Array {
+func (m encodeCountingModel) EncodeMedia(item *model.PreparedItem, data *mlx.Array) *mlx.Array {
*m.calls++
return mlx.Zeros(mlx.DTypeFloat32, item.Range[1]-item.Range[0], 4)
}
@@ -75,7 +75,7 @@ func (m encodeCountingModel) EncodeMedia(item *base.PreparedItem, data *mlx.Arra
func TestBatchMediaLifecycle(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
calls := 0
- prepared := &base.PreparedItem{
+ prepared := &model.PreparedItem{
Range: [2]int{2, 6},
MediaData: []float32{1, 2},
Dims: []int{2},
diff --git a/mlxrunner/model/base/base.go b/mlxrunner/model/base.go
similarity index 91%
rename from mlxrunner/model/base/base.go
rename to mlxrunner/model/base.go
index 468a46e02..d0353d335 100644
--- a/mlxrunner/model/base/base.go
+++ b/mlxrunner/model/base.go
@@ -1,4 +1,4 @@
-package base
+package model
import (
"encoding/json"
@@ -9,7 +9,6 @@ import (
"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/tokenizer"
)
@@ -71,13 +70,13 @@ type SelfDraft interface {
var (
mu sync.Mutex
- registry = make(map[string]func(root *model.Root) (Model, error))
- draftRegistry = make(map[string]func(root *model.Root, target Model) (DraftModel, error))
+ registry = make(map[string]func(root *Root) (Model, error))
+ draftRegistry = make(map[string]func(root *Root, target Model) (DraftModel, error))
)
// Register registers a model constructor by architecture name.
// Called from init() in model packages. Panics on duplicate registration.
-func Register(arch string, fn func(root *model.Root) (Model, error)) {
+func Register(arch string, fn func(root *Root) (Model, error)) {
mu.Lock()
defer mu.Unlock()
@@ -88,7 +87,7 @@ func Register(arch string, fn func(root *model.Root) (Model, error)) {
}
// RegisterDraft registers a draft model constructor by architecture name.
-func RegisterDraft(arch string, fn func(root *model.Root, target Model) (DraftModel, error)) {
+func RegisterDraft(arch string, fn func(root *Root, target Model) (DraftModel, error)) {
mu.Lock()
defer mu.Unlock()
@@ -117,7 +116,7 @@ func SupportsDraftArchitecture(arch string) bool {
// New reads config.json from the manifest, detects the architecture, looks up
// the registered constructor, and calls it to create the model (with config
// parsed and struct created, but weights not yet loaded).
-func New(root *model.Root) (Model, error) {
+func New(root *Root) (Model, error) {
configData, err := root.Manifest.ReadConfig("config.json")
if err != nil {
return nil, fmt.Errorf("failed to read config.json: %w", err)
@@ -149,7 +148,7 @@ func New(root *model.Root) (Model, error) {
}
// NewDraft constructs the draft model described by the manifest config, if any.
-func NewDraft(root *model.Root, target Model) (DraftModel, error) {
+func NewDraft(root *Root, target Model) (DraftModel, error) {
if root == nil || root.Draft == nil {
return nil, nil
}
diff --git a/mlxrunner/model/cohere2_moe/cohere2_moe.go b/mlxrunner/model/cohere2_moe/cohere2_moe.go
index 37fd67f07..2d714f024 100644
--- a/mlxrunner/model/cohere2_moe/cohere2_moe.go
+++ b/mlxrunner/model/cohere2_moe/cohere2_moe.go
@@ -23,13 +23,12 @@ import (
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
- "github.com/ollama/ollama/mlxrunner/model/base"
"github.com/ollama/ollama/mlxrunner/nn"
"github.com/ollama/ollama/mlxrunner/tokenizer"
)
func init() {
- base.Register("Cohere2MoeForCausalLM", NewModel)
+ model.Register("Cohere2MoeForCausalLM", NewModel)
}
// Config holds the Cohere2 MoE configuration (HuggingFace config.json).
@@ -329,7 +328,7 @@ func (cfg *Config) tieEmbeddings() bool {
}
// NewModel creates a Cohere2 MoE model from a manifest root.
-func NewModel(root *model.Root) (base.Model, error) {
+func NewModel(root *model.Root) (model.Model, error) {
configData, err := root.Manifest.ReadConfig("config.json")
if err != nil {
return nil, fmt.Errorf("load config: %w", err)
diff --git a/mlxrunner/model/dflash/dflash.go b/mlxrunner/model/dflash/dflash.go
index a3aa7ab54..44e9055ff 100644
--- a/mlxrunner/model/dflash/dflash.go
+++ b/mlxrunner/model/dflash/dflash.go
@@ -12,23 +12,22 @@ import (
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
- "github.com/ollama/ollama/mlxrunner/model/base"
"github.com/ollama/ollama/mlxrunner/nn"
)
func init() {
- base.RegisterDraft("DFlashDraftModel", func(root *model.Root, target base.Model) (base.DraftModel, error) {
+ model.RegisterDraft("DFlashDraftModel", func(root *model.Root, target model.Model) (model.DraftModel, error) {
return newModel(root, target, false)
})
- base.RegisterDraft("DFlashLagunaForCausalLM", func(root *model.Root, target base.Model) (base.DraftModel, error) {
+ model.RegisterDraft("DFlashLagunaForCausalLM", func(root *model.Root, target model.Model) (model.DraftModel, error) {
return newModel(root, target, true)
})
- base.RegisterDraft("MuseGlimmerAssistantModel", func(root *model.Root, target base.Model) (base.DraftModel, error) {
+ model.RegisterDraft("MuseGlimmerAssistantModel", func(root *model.Root, target model.Model) (model.DraftModel, error) {
return newModel(root, target, false)
})
}
-var _ base.BlockDraft = (*Model)(nil)
+var _ model.BlockDraft = (*Model)(nil)
type Config struct {
HiddenSize int32
@@ -59,9 +58,9 @@ type Config struct {
Causal *bool
}
-// draftTarget is what dflash requires of its target beyond base.Model.
+// draftTarget is what dflash requires of its target beyond model.Model.
type draftTarget interface {
- base.Model
+ model.Model
// TokenEmbeddings is the raw table lookup; the draft has no table of
// its own.
@@ -232,7 +231,7 @@ func parseConfig(data []byte) (*Config, error) {
return cfg, nil
}
-func newModel(root *model.Root, targetModel base.Model, ctxLayerNorm bool) (base.DraftModel, error) {
+func newModel(root *model.Root, targetModel model.Model, ctxLayerNorm bool) (model.DraftModel, error) {
if root == nil || root.Draft == nil {
return nil, fmt.Errorf("draft metadata missing")
}
diff --git a/mlxrunner/model/gemma4/assistant.go b/mlxrunner/model/gemma4/assistant.go
index 3ef69b46b..477d81ee5 100644
--- a/mlxrunner/model/gemma4/assistant.go
+++ b/mlxrunner/model/gemma4/assistant.go
@@ -8,11 +8,10 @@ import (
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
- "github.com/ollama/ollama/mlxrunner/model/base"
"github.com/ollama/ollama/mlxrunner/nn"
)
-var _ base.DraftModel = (*AssistantModel)(nil)
+var _ model.DraftModel = (*AssistantModel)(nil)
type AssistantConfig struct {
TextConfig TextConfig `json:"text_config"`
@@ -108,7 +107,7 @@ func parseAssistantConfig(configData []byte) (AssistantConfig, error) {
}, nil
}
-func newAssistantModel(root *model.Root, target base.Model) (base.DraftModel, error) {
+func newAssistantModel(root *model.Root, target model.Model) (model.DraftModel, error) {
if root == nil || root.Draft == nil {
return nil, fmt.Errorf("draft metadata missing")
}
diff --git a/mlxrunner/model/gemma4/audio_test.go b/mlxrunner/model/gemma4/audio_test.go
index 80028f67f..a6eb71af4 100644
--- a/mlxrunner/model/gemma4/audio_test.go
+++ b/mlxrunner/model/gemma4/audio_test.go
@@ -7,7 +7,7 @@ import (
"github.com/ollama/ollama/mlx/mlxtest"
"github.com/ollama/ollama/mlx"
- "github.com/ollama/ollama/mlxrunner/model/base"
+ "github.com/ollama/ollama/mlxrunner/model"
)
func newAudioTestModel() *Model {
@@ -28,7 +28,7 @@ func newAudioTestModel() *Model {
func TestPrepareAudioMedia(t *testing.T) {
m := newAudioTestModel()
- prepared, err := m.PrepareMedia([]base.Segment{
+ prepared, err := m.PrepareMedia([]model.Segment{
{Tokens: []int32{2, 5}},
{Kind: "audio", Data: wavPCM16(16000)},
{Tokens: []int32{7}},
@@ -70,7 +70,7 @@ func TestPrepareAudioMediaChunks(t *testing.T) {
// 61 s: three chunks of at most 30 s, one soft-token run each, back to
// back inside one boa/eoa pair.
- prepared, err := m.PrepareMedia([]base.Segment{{Kind: "audio", Data: wavPCM16(976000)}})
+ prepared, err := m.PrepareMedia([]model.Segment{{Kind: "audio", Data: wavPCM16(976000)}})
if err != nil {
t.Fatal(err)
}
@@ -99,18 +99,18 @@ func TestPrepareAudioMediaChunks(t *testing.T) {
func TestPrepareAudioMediaRejections(t *testing.T) {
m := newAudioTestModel()
- _, err := m.PrepareMedia([]base.Segment{{Kind: "audio", Data: []byte("ID3\x04\x00junk")}})
+ _, err := m.PrepareMedia([]model.Segment{{Kind: "audio", Data: []byte("ID3\x04\x00junk")}})
if err == nil || !strings.Contains(err.Error(), "unrecognized audio format") {
t.Fatalf("mp3 error = %v", err)
}
- _, err = m.PrepareMedia([]base.Segment{{Kind: "video", Data: []byte{1}}})
+ _, err = m.PrepareMedia([]model.Segment{{Kind: "video", Data: []byte{1}}})
if err == nil || !strings.Contains(err.Error(), "does not support video input") {
t.Fatalf("video error = %v", err)
}
noAudio := &Model{MM: multimodalConfig{ImageTokenID: 258880}}
- _, err = noAudio.PrepareMedia([]base.Segment{{Kind: "audio", Data: wavPCM16(16000)}})
+ _, err = noAudio.PrepareMedia([]model.Segment{{Kind: "audio", Data: wavPCM16(16000)}})
if err == nil || !strings.Contains(err.Error(), "does not support audio input") {
t.Fatalf("no-audio error = %v", err)
}
@@ -123,7 +123,7 @@ func TestPrepareUnifiedAudioMedia(t *testing.T) {
// 31 s stays one item on the unified path: no chunking, one token per
// 640-sample frame, the final partial frame zero-padded.
- prepared, err := m.PrepareMedia([]base.Segment{{Kind: "audio", Data: wavPCM16(496001)}})
+ prepared, err := m.PrepareMedia([]model.Segment{{Kind: "audio", Data: wavPCM16(496001)}})
if err != nil {
t.Fatal(err)
}
diff --git a/mlxrunner/model/gemma4/gemma4.go b/mlxrunner/model/gemma4/gemma4.go
index e61addc16..8349ab4b1 100644
--- a/mlxrunner/model/gemma4/gemma4.go
+++ b/mlxrunner/model/gemma4/gemma4.go
@@ -11,25 +11,24 @@ import (
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
- "github.com/ollama/ollama/mlxrunner/model/base"
"github.com/ollama/ollama/mlxrunner/nn"
"github.com/ollama/ollama/mlxrunner/tokenizer"
)
func init() {
- base.Register("Gemma4ForCausalLM", newModel)
- base.Register("Gemma4ForConditionalGeneration", newModel)
- base.Register("Gemma4UnifiedForCausalLM", newModel)
- base.Register("Gemma4UnifiedForConditionalGeneration", newModel)
- base.Register("gemma4_unified", newModel)
- base.RegisterDraft("Gemma4AssistantForCausalLM", newAssistantModel)
- base.RegisterDraft("Gemma4UnifiedAssistantForCausalLM", newAssistantModel)
- base.RegisterDraft("gemma4_assistant", newAssistantModel)
- base.RegisterDraft("gemma4_unified_assistant", newAssistantModel)
+ model.Register("Gemma4ForCausalLM", newModel)
+ model.Register("Gemma4ForConditionalGeneration", newModel)
+ model.Register("Gemma4UnifiedForCausalLM", newModel)
+ model.Register("Gemma4UnifiedForConditionalGeneration", newModel)
+ model.Register("gemma4_unified", newModel)
+ model.RegisterDraft("Gemma4AssistantForCausalLM", newAssistantModel)
+ model.RegisterDraft("Gemma4UnifiedAssistantForCausalLM", newAssistantModel)
+ model.RegisterDraft("gemma4_assistant", newAssistantModel)
+ model.RegisterDraft("gemma4_unified_assistant", newAssistantModel)
}
// Compile-time interface checks.
-var _ base.Model = (*Model)(nil)
+var _ model.Model = (*Model)(nil)
// RopeParams holds per-layer-type RoPE settings.
type RopeParams struct {
@@ -702,7 +701,7 @@ func precomputeGemmaScaledWeights(m *Model) {
}
}
-func newModel(root *model.Root) (base.Model, error) {
+func newModel(root *model.Root) (model.Model, error) {
configData, err := root.Manifest.ReadConfig("config.json")
if err != nil {
return nil, fmt.Errorf("load config: %w", err)
diff --git a/mlxrunner/model/gemma4/media.go b/mlxrunner/model/gemma4/media.go
index 40103101d..6b1af4cae 100644
--- a/mlxrunner/model/gemma4/media.go
+++ b/mlxrunner/model/gemma4/media.go
@@ -8,7 +8,6 @@ import (
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/model"
- "github.com/ollama/ollama/mlxrunner/model/base"
"github.com/ollama/ollama/mlxrunner/nn"
)
@@ -143,13 +142,13 @@ func makeClippableLinear(linears model.LinearFactory, tensors map[string]*mlx.Ar
return c, nil
}
-// PrepareMedia implements base.MediaModel: splice each media segment's
+// PrepareMedia implements model.MediaModel: splice each media segment's
// placeholder expansion — the begin token, the soft-token run(s), the end
// token — into the stream, with all preprocessing on the CPU. An audio
// segment yields one item per chunk, all inside one boa/eoa pair; the runs
// attend causally, so chunked prefill may split them.
-func (m *Model) PrepareMedia(segments []base.Segment) (*base.PreparedRequest, error) {
- prepared := &base.PreparedRequest{}
+func (m *Model) PrepareMedia(segments []model.Segment) (*model.PreparedRequest, error) {
+ prepared := &model.PreparedRequest{}
for s, seg := range segments {
switch seg.Kind {
case "":
@@ -172,7 +171,7 @@ func (m *Model) PrepareMedia(segments []base.Segment) (*base.PreparedRequest, er
prepared.Tokens = append(prepared.Tokens, m.MM.EOITokenID)
n := int(geom.PatchesH * geom.PatchesW)
- prepared.Items = append(prepared.Items, base.PreparedItem{
+ prepared.Items = append(prepared.Items, model.PreparedItem{
Range: [2]int{start, len(prepared.Tokens)},
Source: s,
MediaData: pixels,
@@ -207,7 +206,7 @@ func (m *Model) PrepareMedia(segments []base.Segment) (*base.PreparedRequest, er
for range chunk.numTokens {
prepared.Tokens = append(prepared.Tokens, m.MM.AudioTokenID)
}
- prepared.Items = append(prepared.Items, base.PreparedItem{
+ prepared.Items = append(prepared.Items, model.PreparedItem{
Range: [2]int{start, len(prepared.Tokens)},
Source: s,
MediaData: chunk.data,
@@ -224,9 +223,9 @@ func (m *Model) PrepareMedia(segments []base.Segment) (*base.PreparedRequest, er
return prepared, nil
}
-// EncodeMedia implements base.MediaModel: run the matching encoder over one
+// EncodeMedia implements model.MediaModel: run the matching encoder over one
// whole item, returning the lazy [soft tokens, hidden] features.
-func (m *Model) EncodeMedia(item *base.PreparedItem, data *mlx.Array) *mlx.Array {
+func (m *Model) EncodeMedia(item *model.PreparedItem, data *mlx.Array) *mlx.Array {
switch p := item.Opaque.(type) {
case preparedAudio:
if m.AudioTower != nil {
diff --git a/mlxrunner/model/gemma4/media_test.go b/mlxrunner/model/gemma4/media_test.go
index 2b41e5e1a..cafd8c76a 100644
--- a/mlxrunner/model/gemma4/media_test.go
+++ b/mlxrunner/model/gemma4/media_test.go
@@ -10,7 +10,7 @@ import (
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
- "github.com/ollama/ollama/mlxrunner/model/base"
+ "github.com/ollama/ollama/mlxrunner/model"
)
func TestParseMultimodalConfig(t *testing.T) {
@@ -216,7 +216,7 @@ func TestPrepareMediaExpansion(t *testing.T) {
t.Fatal(err)
}
- prepared, err := m.PrepareMedia([]base.Segment{
+ prepared, err := m.PrepareMedia([]model.Segment{
{Tokens: []int32{9}},
{Kind: "image", Data: buf.Bytes()},
})
@@ -257,14 +257,14 @@ func TestPrepareMediaExpansion(t *testing.T) {
t.Fatalf("geometry = %+v, positions = %d", p.geom, len(p.positions))
}
- if _, err := m.PrepareMedia([]base.Segment{{Kind: "audio", Data: []byte{1}}}); err == nil {
+ if _, err := m.PrepareMedia([]model.Segment{{Kind: "audio", Data: []byte{1}}}); err == nil {
t.Fatal("audio accepted")
}
- if _, err := m.PrepareMedia([]base.Segment{{Kind: "image"}}); err == nil {
+ if _, err := m.PrepareMedia([]model.Segment{{Kind: "image"}}); err == nil {
t.Fatal("image with no data accepted")
}
m.VisionTower = nil
- if _, err := m.PrepareMedia([]base.Segment{{Kind: "image", Data: buf.Bytes()}}); err == nil {
+ if _, err := m.PrepareMedia([]model.Segment{{Kind: "image", Data: buf.Bytes()}}); err == nil {
t.Fatal("towerless model accepted an image")
}
}
diff --git a/mlxrunner/model/glimmer/glimmer.go b/mlxrunner/model/glimmer/glimmer.go
index 557f304fc..4771ffbf2 100644
--- a/mlxrunner/model/glimmer/glimmer.go
+++ b/mlxrunner/model/glimmer/glimmer.go
@@ -11,16 +11,15 @@ import (
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
- "github.com/ollama/ollama/mlxrunner/model/base"
"github.com/ollama/ollama/mlxrunner/nn"
"github.com/ollama/ollama/mlxrunner/tokenizer"
)
func init() {
- base.Register("MuseGlimmerForConditionalGeneration", newModel)
+ model.Register("MuseGlimmerForConditionalGeneration", newModel)
}
-var _ base.Model = (*Model)(nil)
+var _ model.Model = (*Model)(nil)
// Config holds the decoder and vision fields from an Glimmer configuration.
type Config struct {
@@ -364,7 +363,7 @@ func parseConfig(data []byte) (Config, error) {
return cfg, nil
}
-func newModel(root *model.Root) (base.Model, error) {
+func newModel(root *model.Root) (model.Model, error) {
configData, err := root.Manifest.ReadConfig("config.json")
if err != nil {
return nil, fmt.Errorf("load config: %w", err)
diff --git a/mlxrunner/model/glimmer/media.go b/mlxrunner/model/glimmer/media.go
index 803c3d85d..0c2425008 100644
--- a/mlxrunner/model/glimmer/media.go
+++ b/mlxrunner/model/glimmer/media.go
@@ -13,14 +13,14 @@ import (
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
- "github.com/ollama/ollama/mlxrunner/model/base"
+ "github.com/ollama/ollama/mlxrunner/model"
)
// The reference processor uses the full 4096-token budget for still images.
// Reducing it here discards source detail and disproportionately hurts OCR.
const maxImageTokens = 4096
-var _ base.MediaModel = (*Model)(nil)
+var _ model.MediaModel = (*Model)(nil)
// preparedImage is glimmer's model-private media state: the patch grid the
// encoder consumes and the soft-token count of its pixel-shuffled output.
@@ -30,11 +30,11 @@ type preparedImage struct {
outputTokens int
}
-// PrepareMedia implements base.MediaModel: splice each image segment's
+// PrepareMedia implements model.MediaModel: splice each image segment's
// placeholder expansion — image_start, the patch-token run, image_end — into
// the stream, decoding, resizing, and patchifying the image on the CPU.
-func (m *Model) PrepareMedia(segments []base.Segment) (*base.PreparedRequest, error) {
- prepared := &base.PreparedRequest{}
+func (m *Model) PrepareMedia(segments []model.Segment) (*model.PreparedRequest, error) {
+ prepared := &model.PreparedRequest{}
for s, seg := range segments {
if seg.Data == nil {
prepared.Tokens = append(prepared.Tokens, seg.Tokens...)
@@ -60,7 +60,7 @@ func (m *Model) PrepareMedia(segments []base.Segment) (*base.PreparedRequest, er
prepared.Tokens = append(prepared.Tokens, m.ImageEndTokenID)
n := geom.gridH * geom.gridW
- prepared.Items = append(prepared.Items, base.PreparedItem{
+ prepared.Items = append(prepared.Items, model.PreparedItem{
Range: [2]int{start, len(prepared.Tokens)},
Source: s,
MediaData: patches,
@@ -74,9 +74,9 @@ func (m *Model) PrepareMedia(segments []base.Segment) (*base.PreparedRequest, er
return prepared, nil
}
-// EncodeMedia implements base.MediaModel: run the vision tower over one
+// EncodeMedia implements model.MediaModel: run the vision tower over one
// prepared image, returning the lazy [outputTokens, hidden] features.
-func (m *Model) EncodeMedia(item *base.PreparedItem, data *mlx.Array) *mlx.Array {
+func (m *Model) EncodeMedia(item *model.PreparedItem, data *mlx.Array) *mlx.Array {
geom := item.Opaque.(preparedImage)
return m.encodeVision(data, geom.gridH, geom.gridW)
}
diff --git a/mlxrunner/model/glimmer/media_test.go b/mlxrunner/model/glimmer/media_test.go
index 0c027db7f..7faf4a8f9 100644
--- a/mlxrunner/model/glimmer/media_test.go
+++ b/mlxrunner/model/glimmer/media_test.go
@@ -6,7 +6,7 @@ import (
"image/png"
"testing"
- "github.com/ollama/ollama/mlxrunner/model/base"
+ "github.com/ollama/ollama/mlxrunner/model"
)
func testVisionModel() *Model {
@@ -35,7 +35,7 @@ func testPNG(t *testing.T, w, h int) []byte {
func TestPrepareMediaSplicesExpansion(t *testing.T) {
m := testVisionModel()
- prepared, err := m.PrepareMedia([]base.Segment{
+ prepared, err := m.PrepareMedia([]model.Segment{
{Tokens: []int32{1, 2}},
{Kind: "image", Data: testPNG(t, 56, 56)},
{Tokens: []int32{3}},
@@ -85,13 +85,13 @@ func TestPrepareMediaSplicesExpansion(t *testing.T) {
func TestPrepareMediaRejectsUnsupportedKind(t *testing.T) {
m := testVisionModel()
- _, err := m.PrepareMedia([]base.Segment{{Kind: "audio", Data: []byte{1}}})
+ _, err := m.PrepareMedia([]model.Segment{{Kind: "audio", Data: []byte{1}}})
if err == nil {
t.Fatal("expected error for audio input")
}
text := &Model{Config: &Config{}}
- _, err = text.PrepareMedia([]base.Segment{{Kind: "image", Data: []byte{1}}})
+ _, err = text.PrepareMedia([]model.Segment{{Kind: "image", Data: []byte{1}}})
if err == nil {
t.Fatal("expected error for text-only model")
}
diff --git a/mlxrunner/model/glm4_moe_lite/glm4_moe_lite.go b/mlxrunner/model/glm4_moe_lite/glm4_moe_lite.go
index de6efdf84..8fbbe607e 100644
--- a/mlxrunner/model/glm4_moe_lite/glm4_moe_lite.go
+++ b/mlxrunner/model/glm4_moe_lite/glm4_moe_lite.go
@@ -11,14 +11,13 @@ import (
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
- "github.com/ollama/ollama/mlxrunner/model/base"
"github.com/ollama/ollama/mlxrunner/nn"
"github.com/ollama/ollama/mlxrunner/tokenizer"
)
func init() {
- base.Register("Glm4MoeLiteForCausalLM", newModel)
- base.Register("GLM4MoeLite", newModel)
+ model.Register("Glm4MoeLiteForCausalLM", newModel)
+ model.Register("GLM4MoeLite", newModel)
}
// RopeScaling holds RoPE scaling configuration
@@ -622,8 +621,8 @@ func sanitizeMLAWeights(tensors map[string]*mlx.Array, prefix string, cfg *Confi
}
// newModel creates a new GLM4-MoE-Lite model from a Root (config + tokenizer,
-// no weights loaded yet). Called by the registry via base.New().
-func newModel(root *model.Root) (base.Model, error) {
+// no weights loaded yet). Called by the registry via model.New().
+func newModel(root *model.Root) (model.Model, error) {
configData, err := root.Manifest.ReadConfig("config.json")
if err != nil {
return nil, fmt.Errorf("load config: %w", err)
diff --git a/mlxrunner/model/laguna/laguna.go b/mlxrunner/model/laguna/laguna.go
index e1e353cf9..62f579e76 100644
--- a/mlxrunner/model/laguna/laguna.go
+++ b/mlxrunner/model/laguna/laguna.go
@@ -12,16 +12,15 @@ import (
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
- "github.com/ollama/ollama/mlxrunner/model/base"
"github.com/ollama/ollama/mlxrunner/nn"
"github.com/ollama/ollama/mlxrunner/tokenizer"
)
func init() {
- base.Register("LagunaForCausalLM", NewModel)
+ model.Register("LagunaForCausalLM", NewModel)
}
-var _ base.Model = (*Model)(nil)
+var _ model.Model = (*Model)(nil)
type gatingMode string
@@ -473,7 +472,7 @@ func clampRopeDim(v, maxDim int) int {
return v
}
-func NewModel(root *model.Root) (base.Model, error) {
+func NewModel(root *model.Root) (model.Model, error) {
configData, err := root.Manifest.ReadConfig("config.json")
if err != nil {
return nil, fmt.Errorf("load config: %w", err)
diff --git a/mlxrunner/model/llama/llama.go b/mlxrunner/model/llama/llama.go
index 8b2d62374..e209c7eee 100644
--- a/mlxrunner/model/llama/llama.go
+++ b/mlxrunner/model/llama/llama.go
@@ -10,13 +10,12 @@ import (
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
- "github.com/ollama/ollama/mlxrunner/model/base"
"github.com/ollama/ollama/mlxrunner/nn"
"github.com/ollama/ollama/mlxrunner/tokenizer"
)
func init() {
- base.Register("LlamaForCausalLM", newModel)
+ model.Register("LlamaForCausalLM", newModel)
}
// Config holds Llama model configuration.
@@ -85,7 +84,7 @@ func resolveWeightPrefix(tensors map[string]*mlx.Array) string {
return ""
}
-func newModel(root *model.Root) (base.Model, error) {
+func newModel(root *model.Root) (model.Model, error) {
configData, err := root.Manifest.ReadConfig("config.json")
if err != nil {
return nil, fmt.Errorf("load config: %w", err)
diff --git a/mlxrunner/model/base/media.go b/mlxrunner/model/media.go
similarity index 99%
rename from mlxrunner/model/base/media.go
rename to mlxrunner/model/media.go
index b14318504..e479993ae 100644
--- a/mlxrunner/model/base/media.go
+++ b/mlxrunner/model/media.go
@@ -1,4 +1,4 @@
-package base
+package model
import (
// Every model's PrepareMedia decodes through image.Decode; the decoder
diff --git a/mlxrunner/model/nemotron_h/nemotron_h.go b/mlxrunner/model/nemotron_h/nemotron_h.go
index ce7e27af3..221a7d9bf 100644
--- a/mlxrunner/model/nemotron_h/nemotron_h.go
+++ b/mlxrunner/model/nemotron_h/nemotron_h.go
@@ -13,21 +13,20 @@ import (
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
- "github.com/ollama/ollama/mlxrunner/model/base"
"github.com/ollama/ollama/mlxrunner/nn"
"github.com/ollama/ollama/mlxrunner/tokenizer"
)
func init() {
- base.Register("NemotronH_Nano_VL_V2", newModel)
- base.Register("NemotronH_Nano_Omni_Reasoning_V3", newModel)
- base.Register("NemotronHForCausalLM", newModel)
+ model.Register("NemotronH_Nano_VL_V2", newModel)
+ model.Register("NemotronH_Nano_Omni_Reasoning_V3", newModel)
+ model.Register("NemotronHForCausalLM", newModel)
}
var (
- _ base.Model = (*Model)(nil)
- _ base.SelfDraft = (*Model)(nil)
- _ base.DraftModel = (*mtpDraft)(nil)
+ _ model.Model = (*Model)(nil)
+ _ model.SelfDraft = (*Model)(nil)
+ _ model.DraftModel = (*mtpDraft)(nil)
)
type Config struct {
@@ -285,7 +284,7 @@ func parseConfig(data []byte) (Config, error) {
return cfg, nil
}
-func newModel(root *model.Root) (base.Model, error) {
+func newModel(root *model.Root) (model.Model, error) {
configData, err := root.Manifest.ReadConfig("config.json")
if err != nil {
return nil, fmt.Errorf("load config: %w", err)
@@ -1475,7 +1474,7 @@ type mtpDraft Model
// SelfDraft returns the model's drafting view, or nil when no MTP head was
// loaded. The methods exist either way, so this is what decides availability.
-func (m *Model) SelfDraft() base.DraftModel {
+func (m *Model) SelfDraft() model.DraftModel {
if m.MTP == nil {
return nil
}
diff --git a/mlxrunner/model/qwen3/qwen3.go b/mlxrunner/model/qwen3/qwen3.go
index f87b4ff17..36f1a5973 100644
--- a/mlxrunner/model/qwen3/qwen3.go
+++ b/mlxrunner/model/qwen3/qwen3.go
@@ -10,13 +10,12 @@ import (
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
- "github.com/ollama/ollama/mlxrunner/model/base"
"github.com/ollama/ollama/mlxrunner/nn"
"github.com/ollama/ollama/mlxrunner/tokenizer"
)
func init() {
- base.Register("Qwen3ForCausalLM", newModel)
+ model.Register("Qwen3ForCausalLM", newModel)
}
// Config holds Qwen3 model configuration.
@@ -91,7 +90,7 @@ func resolveWeightPrefix(tensors map[string]*mlx.Array) string {
return ""
}
-func newModel(root *model.Root) (base.Model, error) {
+func newModel(root *model.Root) (model.Model, error) {
configData, err := root.Manifest.ReadConfig("config.json")
if err != nil {
return nil, fmt.Errorf("load config: %w", err)
diff --git a/mlxrunner/model/qwen3_5/qwen3_5.go b/mlxrunner/model/qwen3_5/qwen3_5.go
index ecf06f3a7..81dc7a35c 100644
--- a/mlxrunner/model/qwen3_5/qwen3_5.go
+++ b/mlxrunner/model/qwen3_5/qwen3_5.go
@@ -12,23 +12,22 @@ import (
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
- "github.com/ollama/ollama/mlxrunner/model/base"
"github.com/ollama/ollama/mlxrunner/nn"
"github.com/ollama/ollama/mlxrunner/tokenizer"
)
func init() {
- base.Register("Qwen3_5ForCausalLM", NewModel)
- base.Register("Qwen3_5ForConditionalGeneration", NewModel)
- base.Register("Qwen3NextForCausalLM", NewModel)
- base.Register("Qwen3NextForConditionalGeneration", NewModel)
+ model.Register("Qwen3_5ForCausalLM", NewModel)
+ model.Register("Qwen3_5ForConditionalGeneration", NewModel)
+ model.Register("Qwen3NextForCausalLM", NewModel)
+ model.Register("Qwen3NextForConditionalGeneration", NewModel)
}
var (
- _ base.Model = (*Model)(nil)
- _ base.SelfDraft = (*Model)(nil)
- _ base.DraftModel = (*mtpDraft)(nil)
- _ base.MediaModel = (*Model)(nil)
+ _ model.Model = (*Model)(nil)
+ _ model.SelfDraft = (*Model)(nil)
+ _ model.DraftModel = (*mtpDraft)(nil)
+ _ model.MediaModel = (*Model)(nil)
)
// RopeParameters carries optional rope metadata embedded under rope_parameters.
@@ -391,7 +390,7 @@ func layerUsesMoE(cfg *Config, layer int32) bool {
}
// NewModel creates a Qwen 3.5 model from a manifest root.
-func NewModel(root *model.Root) (base.Model, error) {
+func NewModel(root *model.Root) (model.Model, error) {
configData, err := root.Manifest.ReadConfig("config.json")
if err != nil {
return nil, fmt.Errorf("load config: %w", err)
@@ -1359,7 +1358,7 @@ func (m *mtpDraft) Unembed(x *mlx.Array) *mlx.Array { return (*Model)(m).Unembed
// SelfDraft returns the model's drafting view, or nil when no MTP head was
// loaded. The methods exist either way, so this is what decides availability.
-func (m *Model) SelfDraft() base.DraftModel {
+func (m *Model) SelfDraft() model.DraftModel {
if m.MTP == nil {
return nil
}
diff --git a/mlxrunner/model/qwen3_5/vision.go b/mlxrunner/model/qwen3_5/vision.go
index 1c41591e4..419e97d34 100644
--- a/mlxrunner/model/qwen3_5/vision.go
+++ b/mlxrunner/model/qwen3_5/vision.go
@@ -8,7 +8,6 @@ import (
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/model"
- "github.com/ollama/ollama/mlxrunner/model/base"
"github.com/ollama/ollama/mlxrunner/nn"
)
@@ -140,11 +139,11 @@ func NewVisionAdapter(configData []byte, tensors map[string]*mlx.Array, cfg Visi
return &VisionAdapter{Model: m}, nil
}
-func (a *VisionAdapter) PrepareMedia(segments []base.Segment) (*base.PreparedRequest, error) {
+func (a *VisionAdapter) PrepareMedia(segments []model.Segment) (*model.PreparedRequest, error) {
return a.Model.PrepareMedia(segments)
}
-func (a *VisionAdapter) EncodeMedia(item *base.PreparedItem, data *mlx.Array) *mlx.Array {
+func (a *VisionAdapter) EncodeMedia(item *model.PreparedItem, data *mlx.Array) *mlx.Array {
return a.Model.EncodeMedia(item, data)
}
@@ -265,11 +264,11 @@ func (m *Model) loadVisionWeights(tensors map[string]*mlx.Array, linears model.L
func (m *Model) visionLoaded() bool { return m.VisionTower != nil }
-// PrepareMedia implements base.MediaModel: preprocess each image segment,
+// PrepareMedia implements model.MediaModel: preprocess each image segment,
// splice its vision_start + pads + vision_end expansion, and precompute the
// request's 3-channel rope positions.
-func (m *Model) PrepareMedia(segments []base.Segment) (*base.PreparedRequest, error) {
- prepared := &base.PreparedRequest{}
+func (m *Model) PrepareMedia(segments []model.Segment) (*model.PreparedRequest, error) {
+ prepared := &model.PreparedRequest{}
// pos walks the reference's multimodal position rule: text advances one
// per token on all channels; an image spans a merged grid anchored at
@@ -320,7 +319,7 @@ func (m *Model) PrepareMedia(segments []base.Segment) (*base.PreparedRequest, er
text(1)
n := int(prep.numPatches())
- prepared.Items = append(prepared.Items, base.PreparedItem{
+ prepared.Items = append(prepared.Items, model.PreparedItem{
Range: [2]int{start, len(prepared.Tokens)},
Source: s,
MediaData: pixels,
@@ -345,9 +344,9 @@ func (m *Model) PrepareMedia(segments []base.Segment) (*base.PreparedRequest, er
return prepared, nil
}
-// EncodeMedia implements base.MediaModel: run the tower over one whole
+// EncodeMedia implements model.MediaModel: run the tower over one whole
// image, returning the lazy [numTokens, hidden] features.
-func (m *Model) EncodeMedia(item *base.PreparedItem, data *mlx.Array) *mlx.Array {
+func (m *Model) EncodeMedia(item *model.PreparedItem, data *mlx.Array) *mlx.Array {
prep := item.Opaque.(preparedImage)
v := m.Vision
t := m.VisionTower
diff --git a/mlxrunner/model/qwen3_5/vision_test.go b/mlxrunner/model/qwen3_5/vision_test.go
index 9668df77b..a50afc31d 100644
--- a/mlxrunner/model/qwen3_5/vision_test.go
+++ b/mlxrunner/model/qwen3_5/vision_test.go
@@ -9,7 +9,7 @@ import (
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
- "github.com/ollama/ollama/mlxrunner/model/base"
+ "github.com/ollama/ollama/mlxrunner/model"
)
func TestVisionAdapterWeightsAreCollectable(t *testing.T) {
@@ -85,7 +85,7 @@ func TestMRopePositionRule(t *testing.T) {
},
}
- prepared, err := m.PrepareMedia([]base.Segment{{Tokens: []int32{1, 2, 3}}})
+ prepared, err := m.PrepareMedia([]model.Segment{{Tokens: []int32{1, 2, 3}}})
if err != nil {
t.Fatal(err)
}
@@ -99,7 +99,7 @@ func TestMRopePositionRule(t *testing.T) {
if err := png.Encode(&buf, image.NewRGBA(image.Rect(0, 0, 64, 64))); err != nil {
t.Fatal(err)
}
- prepared, err = m.PrepareMedia([]base.Segment{
+ prepared, err = m.PrepareMedia([]model.Segment{
{Tokens: []int32{1, 2, 3}},
{Kind: "image", Data: buf.Bytes()},
})
diff --git a/mlxrunner/model/qwen3_5_moe/qwen3_5_moe.go b/mlxrunner/model/qwen3_5_moe/qwen3_5_moe.go
index 8975b2ad8..928922714 100644
--- a/mlxrunner/model/qwen3_5_moe/qwen3_5_moe.go
+++ b/mlxrunner/model/qwen3_5_moe/qwen3_5_moe.go
@@ -2,13 +2,13 @@
package qwen3_5_moe
import (
- "github.com/ollama/ollama/mlxrunner/model/base"
+ "github.com/ollama/ollama/mlxrunner/model"
"github.com/ollama/ollama/mlxrunner/model/qwen3_5"
)
func init() {
- base.Register("Qwen3_5MoeForConditionalGeneration", qwen3_5.NewModel)
- base.Register("Qwen3_5MoeForCausalLM", qwen3_5.NewModel)
- base.Register("Qwen3NextMoeForConditionalGeneration", qwen3_5.NewModel)
- base.Register("Qwen3NextMoeForCausalLM", qwen3_5.NewModel)
+ model.Register("Qwen3_5MoeForConditionalGeneration", qwen3_5.NewModel)
+ model.Register("Qwen3_5MoeForCausalLM", qwen3_5.NewModel)
+ model.Register("Qwen3NextMoeForConditionalGeneration", qwen3_5.NewModel)
+ model.Register("Qwen3NextMoeForCausalLM", qwen3_5.NewModel)
}
diff --git a/mlxrunner/model/qwen4_exp/qwen4_exp.go b/mlxrunner/model/qwen4_exp/qwen4_exp.go
index 88df62a15..5b5935bc6 100644
--- a/mlxrunner/model/qwen4_exp/qwen4_exp.go
+++ b/mlxrunner/model/qwen4_exp/qwen4_exp.go
@@ -8,21 +8,20 @@ import (
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
- "github.com/ollama/ollama/mlxrunner/model/base"
"github.com/ollama/ollama/mlxrunner/model/qwen3_5"
"github.com/ollama/ollama/mlxrunner/nn"
"github.com/ollama/ollama/mlxrunner/tokenizer"
)
func init() {
- base.Register("Qwen4ExpForConditionalGeneration", NewModel)
+ model.Register("Qwen4ExpForConditionalGeneration", NewModel)
}
var (
- _ base.Model = (*Model)(nil)
- _ base.SelfDraft = (*Model)(nil)
- _ base.DraftModel = (*mtpDraft)(nil)
- _ base.MediaModel = (*Model)(nil)
+ _ model.Model = (*Model)(nil)
+ _ model.SelfDraft = (*Model)(nil)
+ _ model.DraftModel = (*mtpDraft)(nil)
+ _ model.MediaModel = (*Model)(nil)
)
// Model carries the validated architecture and tokenizer.
@@ -44,7 +43,7 @@ type Model struct {
}
// NewModel validates the publisher config before constructing runtime state.
-func NewModel(root *model.Root) (base.Model, error) {
+func NewModel(root *model.Root) (model.Model, error) {
configData, err := root.Manifest.ReadConfig("config.json")
if err != nil {
return nil, fmt.Errorf("load config: %w", err)
@@ -175,14 +174,14 @@ func (m *Model) Unembed(hidden *mlx.Array) *mlx.Array {
func (m *Model) Tokenizer() *tokenizer.Tokenizer { return m.tok }
-func (m *Model) PrepareMedia(segments []base.Segment) (*base.PreparedRequest, error) {
+func (m *Model) PrepareMedia(segments []model.Segment) (*model.PreparedRequest, error) {
if m.Vision == nil {
return nil, fmt.Errorf("this model does not support media input")
}
return m.Vision.PrepareMedia(segments)
}
-func (m *Model) EncodeMedia(item *base.PreparedItem, data *mlx.Array) *mlx.Array {
+func (m *Model) EncodeMedia(item *model.PreparedItem, data *mlx.Array) *mlx.Array {
return m.Vision.EncodeMedia(item, data)
}
@@ -193,7 +192,7 @@ func (m *Model) MaxContextLength() int {
// mtpDraft views the checkpoint's inline predictor through DraftModel.
type mtpDraft Model
-func (m *Model) SelfDraft() base.DraftModel {
+func (m *Model) SelfDraft() model.DraftModel {
if m.MTP == nil {
return nil
}
diff --git a/mlxrunner/mtp_test.go b/mlxrunner/mtp_test.go
index 45404c27f..5e4d12624 100644
--- a/mlxrunner/mtp_test.go
+++ b/mlxrunner/mtp_test.go
@@ -16,7 +16,7 @@ import (
"github.com/ollama/ollama/mlx/mlxtest"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
- "github.com/ollama/ollama/mlxrunner/model/base"
+ "github.com/ollama/ollama/mlxrunner/model"
sampler "github.com/ollama/ollama/mlxrunner/sample"
"github.com/ollama/ollama/mlxrunner/tokenizer"
)
@@ -84,7 +84,7 @@ func (m *fakeMTPModel) LoadWeights(map[string]*mlx.Array) error {
return nil
}
-var _ base.Model = (*fakeMTPModel)(nil)
+var _ model.Model = (*fakeMTPModel)(nil)
// fakeMTPDraft is a cacheless draft that extends b.InputIDs through predict;
// a map (not a step counter) keeps drafting consistent regardless of batching.
@@ -117,7 +117,7 @@ func (d *fakeMTPDraft) Forward(b *batch.Batch, _, _ []cache.Cache) (hidden, auxH
// Unembed is the identity: the fake's hidden already is its one-hot logits.
func (d *fakeMTPDraft) Unembed(x *mlx.Array) *mlx.Array { return x }
-var _ base.DraftModel = (*fakeMTPDraft)(nil)
+var _ model.DraftModel = (*fakeMTPDraft)(nil)
// fakeKVDraft is a draft head that declares a KV cache: it writes its
// input ids there on every Draft call (advancing the
@@ -181,7 +181,7 @@ func (d *fakeKVDraft) Forward(b *batch.Batch, _, draftCaches []cache.Cache) (hid
// Unembed is the identity: the fake's hidden already is its one-hot logits.
func (d *fakeKVDraft) Unembed(x *mlx.Array) *mlx.Array { return x }
-var _ base.DraftModel = (*fakeKVDraft)(nil)
+var _ model.DraftModel = (*fakeKVDraft)(nil)
type fatalTester interface {
Helper()
diff --git a/mlxrunner/pipeline.go b/mlxrunner/pipeline.go
index 05a5d6039..eabe2e0d4 100644
--- a/mlxrunner/pipeline.go
+++ b/mlxrunner/pipeline.go
@@ -14,7 +14,7 @@ import (
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
- "github.com/ollama/ollama/mlxrunner/model/base"
+ "github.com/ollama/ollama/mlxrunner/model"
sampler "github.com/ollama/ollama/mlxrunner/sample"
"github.com/ollama/ollama/mlxrunner/tokenizer"
)
@@ -50,7 +50,7 @@ func (r *Runner) Prepare(request *Request) (err error) {
if len(request.Media) == 0 {
tokens = r.Tokenizer.Encode(request.Prompt, r.Tokenizer.AddBOS())
} else {
- mm, ok := r.Model.(base.MediaModel)
+ mm, ok := r.Model.(model.MediaModel)
if !ok {
kind := string(request.Media[0].Kind)
if kind == "" {
diff --git a/mlxrunner/pipeline_test.go b/mlxrunner/pipeline_test.go
index 5d0bcf787..827ce687d 100644
--- a/mlxrunner/pipeline_test.go
+++ b/mlxrunner/pipeline_test.go
@@ -10,11 +10,11 @@ import (
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
- "github.com/ollama/ollama/mlxrunner/model/base"
+ "github.com/ollama/ollama/mlxrunner/model"
"github.com/ollama/ollama/mlxrunner/tokenizer"
)
-// textOnlyModel satisfies base.Model but not base.MediaModel.
+// textOnlyModel satisfies model.Model but not model.MediaModel.
type textOnlyModel struct{}
func (textOnlyModel) LoadWeights(map[string]*mlx.Array) error { return nil }
@@ -53,8 +53,8 @@ type stubMediaModel struct {
layout any
}
-func (m stubMediaModel) PrepareMedia(segments []base.Segment) (*base.PreparedRequest, error) {
- prepared := &base.PreparedRequest{Layout: m.layout}
+func (m stubMediaModel) PrepareMedia(segments []model.Segment) (*model.PreparedRequest, error) {
+ prepared := &model.PreparedRequest{Layout: m.layout}
for s, seg := range segments {
if seg.Data == nil {
prepared.Tokens = append(prepared.Tokens, seg.Tokens...)
@@ -68,7 +68,7 @@ func (m stubMediaModel) PrepareMedia(segments []base.Segment) (*base.PreparedReq
}
start := len(prepared.Tokens)
prepared.Tokens = append(prepared.Tokens, m.expansion...)
- prepared.Items = append(prepared.Items, base.PreparedItem{
+ prepared.Items = append(prepared.Items, model.PreparedItem{
Range: [2]int{start, len(prepared.Tokens)},
Source: s,
MediaData: []float32{float32(len(seg.Data))},
@@ -79,7 +79,7 @@ func (m stubMediaModel) PrepareMedia(segments []base.Segment) (*base.PreparedReq
return prepared, nil
}
-func (stubMediaModel) EncodeMedia(*base.PreparedItem, *mlx.Array) *mlx.Array { return nil }
+func (stubMediaModel) EncodeMedia(*model.PreparedItem, *mlx.Array) *mlx.Array { return nil }
func mediaTestRunner(t *testing.T) *Runner {
t.Helper()
@@ -128,35 +128,35 @@ func TestPrepareExpandsMediaTags(t *testing.T) {
// runner's validation of model-authored items.
type rawMediaModel struct {
textOnlyModel
- prepared base.PreparedRequest
+ prepared model.PreparedRequest
}
-func (m rawMediaModel) PrepareMedia([]base.Segment) (*base.PreparedRequest, error) {
+func (m rawMediaModel) PrepareMedia([]model.Segment) (*model.PreparedRequest, error) {
p := m.prepared
return &p, nil
}
-func (rawMediaModel) EncodeMedia(*base.PreparedItem, *mlx.Array) *mlx.Array { return nil }
+func (rawMediaModel) EncodeMedia(*model.PreparedItem, *mlx.Array) *mlx.Array { return nil }
func TestPrepareValidatesAuthoredItems(t *testing.T) {
media := []llm.MediaData{{ID: 0, Kind: llm.MediaKindImage, Data: []byte("img")}}
- item := func(lo, hi, src int) base.PreparedItem {
- return base.PreparedItem{Range: [2]int{lo, hi}, Source: src, Dims: []int{1}}
+ item := func(lo, hi, src int) model.PreparedItem {
+ return model.PreparedItem{Range: [2]int{lo, hi}, Source: src, Dims: []int{1}}
}
// Prompt "0[img-0]1" produces segments 0=text, 1=media, 2=text.
cases := []struct {
name string
- items []base.PreparedItem
+ items []model.PreparedItem
want string // "" means the items must be accepted
}{
- {"per-tile items", []base.PreparedItem{item(1, 3, 1), item(3, 4, 1)}, ""},
- {"overlap", []base.PreparedItem{item(1, 3, 1), item(2, 4, 1)}, "invalid range"},
- {"out of bounds", []base.PreparedItem{item(2, 9, 1)}, "invalid range"},
- {"empty range", []base.PreparedItem{item(2, 2, 1)}, "invalid range"},
- {"text source", []base.PreparedItem{item(1, 3, 0)}, "non-media segment"},
+ {"per-tile items", []model.PreparedItem{item(1, 3, 1), item(3, 4, 1)}, ""},
+ {"overlap", []model.PreparedItem{item(1, 3, 1), item(2, 4, 1)}, "invalid range"},
+ {"out of bounds", []model.PreparedItem{item(2, 9, 1)}, "invalid range"},
+ {"empty range", []model.PreparedItem{item(2, 2, 1)}, "invalid range"},
+ {"text source", []model.PreparedItem{item(1, 3, 0)}, "non-media segment"},
}
for _, c := range cases {
r := mediaTestRunner(t)
- r.Model = rawMediaModel{prepared: base.PreparedRequest{Tokens: []int32{0, 5, 5, 5, 1}, Items: c.items}}
+ r.Model = rawMediaModel{prepared: model.PreparedRequest{Tokens: []int32{0, 5, 5, 5, 1}, Items: c.items}}
err := r.Prepare(&Request{CompletionRequest: CompletionRequest{Prompt: "0[img-0]1", Media: media}})
if c.want == "" {
if err != nil {
diff --git a/mlxrunner/prefix_cache_test.go b/mlxrunner/prefix_cache_test.go
index 4beff3151..ba71764b5 100644
--- a/mlxrunner/prefix_cache_test.go
+++ b/mlxrunner/prefix_cache_test.go
@@ -7,7 +7,7 @@ import (
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/cache"
- "github.com/ollama/ollama/mlxrunner/model/base"
+ "github.com/ollama/ollama/mlxrunner/model"
)
// snapshotTracker records every fakeSnapshot created and every Close() call
@@ -1038,7 +1038,7 @@ func TestAtomicMediaBoundaries(t *testing.T) {
pc := env.pc
inputs := []int32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
const itemPos, itemLen = 3, 6
- items := []mediaItem{{pos: itemPos, length: itemLen, fold: 1 << 31, item: &base.PreparedItem{}}}
+ items := []mediaItem{{pos: itemPos, length: itemLen, fold: 1 << 31, item: &model.PreparedItem{}}}
session := pc.begin(inputs, items)
session.schedulePrefillSnapshots([]int{itemPos + itemLen/2})
@@ -1059,7 +1059,7 @@ func TestAtomicMediaBoundaries(t *testing.T) {
// A prompt ending inside the item matches the stored path through its
// last token, which would put the resume point inside the item.
short := inputs[:itemPos+itemLen-2]
- shortItems := []mediaItem{{pos: itemPos, length: len(short) - itemPos, fold: 1 << 31, item: &base.PreparedItem{}}}
+ shortItems := []mediaItem{{pos: itemPos, length: len(short) - itemPos, fold: 1 << 31, item: &model.PreparedItem{}}}
session = pc.begin(short, shortItems)
if resumed := len(short) - len(session.remaining); resumed > itemPos {
t.Errorf("resumed at %d, inside the item's tokens starting at %d", resumed, itemPos)
diff --git a/mlxrunner/runner.go b/mlxrunner/runner.go
index a8eeb9303..1cbd57679 100644
--- a/mlxrunner/runner.go
+++ b/mlxrunner/runner.go
@@ -19,7 +19,6 @@ import (
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
_ "github.com/ollama/ollama/mlxrunner/model/architectures"
- "github.com/ollama/ollama/mlxrunner/model/base"
"github.com/ollama/ollama/mlxrunner/sample"
"github.com/ollama/ollama/mlxrunner/tokenizer"
)
@@ -42,7 +41,7 @@ type Request struct {
}
type Runner struct {
- Model base.Model
+ Model model.Model
weights *mlx.Scope
Tokenizer *tokenizer.Tokenizer
Requests chan Request
@@ -80,7 +79,7 @@ func (r *Runner) loadModel(modelName string) (weights []*mlx.Array, err error) {
}
defer root.Close()
- m, e := base.New(root)
+ m, e := model.New(root)
if e != nil {
err = e
return nil
@@ -107,8 +106,8 @@ func (r *Runner) loadModel(modelName string) (weights []*mlx.Array, err error) {
return nil
}
- var draftModel base.DraftModel
- draft, e := base.NewDraft(root, m)
+ var draftModel model.DraftModel
+ draft, e := model.NewDraft(root, m)
if e != nil {
err = e
return nil
@@ -118,7 +117,7 @@ func (r *Runner) loadModel(modelName string) (weights []*mlx.Array, err error) {
return nil
}
draftModel = draft
- } else if sd, ok := m.(base.SelfDraft); ok {
+ } else if sd, ok := m.(model.SelfDraft); ok {
// Inline draft head: already loaded with the target; nil if none shipped.
draftModel = sd.SelfDraft()
}
@@ -161,7 +160,7 @@ func (r *Runner) Close() {
}
// newDraftCaches returns nil when the model ships no draft.
-func newDraftCaches(draft base.DraftModel) []cache.Cache {
+func newDraftCaches(draft model.DraftModel) []cache.Cache {
if draft == nil {
return nil
}
@@ -171,7 +170,7 @@ func newDraftCaches(draft base.DraftModel) []cache.Cache {
// logitsWidth reads a model's logits width off a one-token forward's static
// shape — the same Forward and Unembed path decode logits take. Nothing is
// evaluated.
-func logitsWidth(m base.Model) (width int) {
+func logitsWidth(m model.Model) (width int) {
mlx.Scoped(func() {
caches := m.NewCaches()
hidden, _ := m.Forward(&batch.Batch{
diff --git a/mlxrunner/speculate.go b/mlxrunner/speculate.go
index 0f75aa6fe..0f85ef907 100644
--- a/mlxrunner/speculate.go
+++ b/mlxrunner/speculate.go
@@ -8,7 +8,7 @@ import (
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
- "github.com/ollama/ollama/mlxrunner/model/base"
+ "github.com/ollama/ollama/mlxrunner/model"
sampler "github.com/ollama/ollama/mlxrunner/sample"
)
@@ -45,7 +45,7 @@ type draftSession interface {
// decodes plainly.
type speculation struct {
r *Runner
- draft base.DraftModel
+ draft model.DraftModel
// targets are the model's cache slots, which speculation snapshots and
// rolls back; draftKV are the drafter's. Both are built at load and
@@ -75,12 +75,12 @@ type drafter interface {
// newSpeculation builds the speculative-decoding subsystem for a loaded model,
// or nil when the checkpoint ships no draft head.
-func newSpeculation(r *Runner, draft base.DraftModel, targets, draftKV []cache.Cache) *speculation {
+func newSpeculation(r *Runner, draft model.DraftModel, targets, draftKV []cache.Cache) *speculation {
if draft == nil {
return nil
}
s := &speculation{r: r, draft: draft, targets: targets, draftKV: draftKV, depth: newDepthController()}
- if bd, ok := draft.(base.BlockDraft); ok {
+ if bd, ok := draft.(model.BlockDraft); ok {
s.drafter = newDFlashDrafter(s, bd)
} else {
s.drafter = newMTPDrafter(s)
diff --git a/mlxrunner/verify.go b/mlxrunner/verify.go
index 85bd44331..20fe65d4e 100644
--- a/mlxrunner/verify.go
+++ b/mlxrunner/verify.go
@@ -1,15 +1,15 @@
package mlxrunner
import (
- "github.com/ollama/ollama/mlxrunner/model/base"
+ "github.com/ollama/ollama/mlxrunner/model"
)
// SupportsArchitecture reports whether the MLX runner has a constructor for arch.
func SupportsArchitecture(arch string) bool {
- return base.SupportsArchitecture(arch)
+ return model.SupportsArchitecture(arch)
}
// SupportsDraftArchitecture reports whether the MLX runner has a draft constructor for arch.
func SupportsDraftArchitecture(arch string) bool {
- return base.SupportsDraftArchitecture(arch)
+ return model.SupportsDraftArchitecture(arch)
}
diff --git a/server/routes.go b/server/routes.go
index 8661aab4d..0b1d668a0 100644
--- a/server/routes.go
+++ b/server/routes.go
@@ -51,7 +51,6 @@ import (
"github.com/ollama/ollama/types/errtypes"
"github.com/ollama/ollama/types/model"
"github.com/ollama/ollama/version"
- xserver "github.com/ollama/ollama/x/server"
)
const signinURLStr = "https://ollama.com/connect?name=%s&key=%s"
@@ -1430,7 +1429,7 @@ func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
// For safetensors LLM models, populate details from config.json.
if m.Config.ModelFormat == "safetensors" && slices.Contains(m.Config.Capabilities, "completion") {
- if info, err := xserver.GetSafetensorsLLMInfo(name); err == nil {
+ if info, err := getSafetensorsLLMInfo(name); err == nil {
if arch, ok := info["general.architecture"].(string); ok && arch != "" {
modelDetails.Family = arch
}
@@ -1440,7 +1439,7 @@ func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
}
// Older manifests may not have file_type populated for safetensors models.
if modelDetails.QuantizationLevel == "" {
- if dtype, err := xserver.GetSafetensorsDtype(name); err == nil && dtype != "" {
+ if dtype, err := getSafetensorsDtype(name); err == nil && dtype != "" {
modelDetails.QuantizationLevel = dtype
}
}
@@ -1541,12 +1540,12 @@ func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
// For safetensors LLM models, populate ModelInfo from config.json.
if m.Config.ModelFormat == "safetensors" && slices.Contains(m.Config.Capabilities, "completion") {
- if info, err := xserver.GetSafetensorsLLMInfo(name); err == nil {
+ if info, err := getSafetensorsLLMInfo(name); err == nil {
resp.ModelInfo = info
}
// Populate tensor info if verbose
if req.Verbose {
- if tensors, err := xserver.GetSafetensorsTensorInfo(name); err == nil {
+ if tensors, err := getSafetensorsTensorInfo(name); err == nil {
resp.Tensors = tensors
}
}
@@ -1559,7 +1558,7 @@ func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
if slices.Contains(m.Capabilities(), model.CapabilityImage) {
// Populate tensor info if verbose
if req.Verbose {
- if tensors, err := xserver.GetSafetensorsTensorInfo(name); err == nil {
+ if tensors, err := getSafetensorsTensorInfo(name); err == nil {
resp.Tensors = tensors
}
}
diff --git a/x/server/show.go b/server/show_safetensors.go
similarity index 97%
rename from x/server/show.go
rename to server/show_safetensors.go
index 4576b2ffb..3591d49c9 100644
--- a/x/server/show.go
+++ b/server/show_safetensors.go
@@ -41,9 +41,9 @@ type modelConfig struct {
} `json:"text_config"`
}
-// GetSafetensorsLLMInfo extracts model information from safetensors LLM models.
+// getSafetensorsLLMInfo extracts model information from safetensors LLM models.
// It reads the config.json layer and returns a map compatible with GGML's KV format.
-func GetSafetensorsLLMInfo(name model.Name) (map[string]any, error) {
+func getSafetensorsLLMInfo(name model.Name) (map[string]any, error) {
mf, err := manifest.ParseNamedManifest(name)
if err != nil {
return nil, fmt.Errorf("failed to load manifest: %w", err)
@@ -210,9 +210,9 @@ func getParameterCountFromManifest(mf *manifest.Manifest) (int64, error) {
return total, nil
}
-// GetSafetensorsTensorInfo extracts tensor information from safetensors model layers.
+// getSafetensorsTensorInfo extracts tensor information from safetensors model layers.
// Each tensor is stored as a minimal safetensors file with an 88-byte header containing metadata.
-func GetSafetensorsTensorInfo(name model.Name) ([]api.Tensor, error) {
+func getSafetensorsTensorInfo(name model.Name) ([]api.Tensor, error) {
mf, err := manifest.ParseNamedManifest(name)
if err != nil {
return nil, fmt.Errorf("failed to load manifest: %w", err)
@@ -303,10 +303,10 @@ func getTensorInfoFromManifest(mf *manifest.Manifest) ([]api.Tensor, error) {
return tensors, nil
}
-// GetSafetensorsDtype returns the quantization type for a safetensors model.
+// getSafetensorsDtype returns the quantization type for a safetensors model.
// Reads tensor headers and reports the lowest-precision quantized weight type.
// Falls back to torch_dtype from config.json if no quant metadata exists.
-func GetSafetensorsDtype(name model.Name) (string, error) {
+func getSafetensorsDtype(name model.Name) (string, error) {
mf, err := manifest.ParseNamedManifest(name)
if err != nil {
return "", fmt.Errorf("failed to load manifest: %w", err)
diff --git a/x/server/show_test.go b/server/show_safetensors_test.go
similarity index 99%
rename from x/server/show_test.go
rename to server/show_safetensors_test.go
index 88c253b8f..faddd6da2 100644
--- a/x/server/show_test.go
+++ b/server/show_safetensors_test.go
@@ -1160,11 +1160,11 @@ func TestGetSafetensorsDtypeChoosesLowestPrecisionQuantizedBlob(t *testing.T) {
t.Fatalf("failed to write manifest: %v", err)
}
- got, err := GetSafetensorsDtype(name)
+ got, err := getSafetensorsDtype(name)
if err != nil {
- t.Fatalf("GetSafetensorsDtype() error = %v", err)
+ t.Fatalf("getSafetensorsDtype() error = %v", err)
}
if got != "nvfp4" {
- t.Fatalf("GetSafetensorsDtype() = %q, want nvfp4", got)
+ t.Fatalf("getSafetensorsDtype() = %q, want nvfp4", got)
}
}