Skip to content

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

llama-server: prepare to remove compatibility patch

Daniel Hiltgen75b952780f90
diff --git a/api/client.go b/api/client.go
index 10913308a..7decf3d0f 100644
--- a/api/client.go
+++ b/api/client.go
@@ -392,12 +392,14 @@ func (c *Client) ListRunning(ctx context.Context) (*ProcessResponse, error) {
}
// Copy copies a model - creating a model with another name from an existing
-// model.
-func (c *Client) Copy(ctx context.Context, req *CopyRequest) error {
- if err := c.do(ctx, http.MethodPost, "/api/copy", req, nil); err != nil {
- return err
+// model. Status carries a warning when the copy drops manifest list children
+// that are not held locally.
+func (c *Client) Copy(ctx context.Context, req *CopyRequest) (*ProgressResponse, error) {
+ var resp ProgressResponse
+ if err := c.do(ctx, http.MethodPost, "/api/copy", req, &resp); err != nil {
+ return nil, err
}
- return nil
+ return &resp, nil
}
// Delete deletes a model and its data.
@@ -417,6 +419,21 @@ func (c *Client) Show(ctx context.Context, req *ShowRequest) (*ShowResponse, err
return &resp, nil
}
+// ShowManifests obtains model information for all manifests in a manifest list.
+func (c *Client) ShowManifests(ctx context.Context, req *ShowRequest) (*ShowManifestsResponse, error) {
+ showReq := &ShowRequest{AllManifests: true}
+ if req != nil {
+ *showReq = *req
+ showReq.AllManifests = true
+ }
+
+ var resp ShowManifestsResponse
+ if err := c.do(ctx, http.MethodPost, "/api/show", showReq, &resp); err != nil {
+ return nil, err
+ }
+ return &resp, nil
+}
+
// Heartbeat checks if the server has started and is responsive; if yes, it
// returns nil, otherwise an error.
func (c *Client) Heartbeat(ctx context.Context) error {
diff --git a/api/types.go b/api/types.go
index 30a5990b3..d7a2a0f6e 100644
--- a/api/types.go
+++ b/api/types.go
@@ -64,6 +64,9 @@ type GenerateRequest struct {
// the library at https://ollama.com/library
Model string `json:"model"`
+ // Runner selects a runner variant from a manifest list.
+ Runner string `json:"runner,omitempty"`
+
// Prompt is the textual prompt to send to the model.
Prompt string `json:"prompt"`
@@ -134,6 +137,9 @@ type ChatRequest struct {
// Model is the model name, as in [GenerateRequest].
Model string `json:"model"`
+ // Runner selects a runner variant from a manifest list.
+ Runner string `json:"runner,omitempty"`
+
// Messages is the messages of the chat - can be used to keep a chat memory.
Messages []Message `json:"messages"`
@@ -600,6 +606,9 @@ type EmbedRequest struct {
// Model is the model name.
Model string `json:"model"`
+ // Runner selects a runner variant from a manifest list.
+ Runner string `json:"runner,omitempty"`
+
// Input is the input to embed.
Input any `json:"input"`
@@ -632,6 +641,9 @@ type EmbeddingRequest struct {
// Model is the model name.
Model string `json:"model"`
+ // Runner selects a runner variant from a manifest list.
+ Runner string `json:"runner,omitempty"`
+
// Prompt is the textual prompt to embed.
Prompt string `json:"prompt"`
@@ -665,6 +677,9 @@ type CreateRequest struct {
// From is the name of the model or file to use as the source.
From string `json:"from,omitempty"`
+ // List is the list of local model tags to include in a manifest list.
+ List []string `json:"list,omitempty"`
+
// RemoteHost is the URL of the upstream ollama API for the model (if any).
RemoteHost string `json:"remote_host,omitempty"`
@@ -722,8 +737,10 @@ type DeleteRequest struct {
// ShowRequest is the request passed to [Client.Show].
type ShowRequest struct {
- Model string `json:"model"`
- System string `json:"system"`
+ Model string `json:"model"`
+ Runner string `json:"runner,omitempty"`
+ AllManifests bool `json:"all_manifests,omitempty"`
+ System string `json:"system"`
// Template is deprecated
Template string `json:"template"`
@@ -753,10 +770,31 @@ type ShowResponse struct {
ProjectorInfo map[string]any `json:"projector_info,omitempty"`
Tensors []Tensor `json:"tensors,omitempty"`
Capabilities []model.Capability `json:"capabilities,omitempty"`
+ Manifests []ManifestSummary `json:"manifests,omitempty"`
ModifiedAt time.Time `json:"modified_at,omitempty"`
Requires string `json:"requires,omitempty"`
}
+// ManifestSummary describes one child manifest available through a model tag.
+type ManifestSummary struct {
+ Digest string `json:"digest,omitempty"`
+ Runner string `json:"runner,omitempty"`
+ Format string `json:"format,omitempty"`
+ Selected bool `json:"selected,omitempty"`
+}
+
+// ShowManifest is a single manifest summary returned from [Client.ShowManifests].
+type ShowManifest struct {
+ Runner string `json:"runner,omitempty"`
+ ShowResponse
+}
+
+// ShowManifestsResponse is the response returned from [Client.ShowManifests].
+type ShowManifestsResponse struct {
+ Manifests []ShowManifest `json:"manifests"`
+ License string `json:"license,omitempty"`
+}
+
// CopyRequest is the request passed to [Client.Copy].
type CopyRequest struct {
Source string `json:"source"`
@@ -766,6 +804,7 @@ type CopyRequest struct {
// PullRequest is the request passed to [Client.Pull].
type PullRequest struct {
Model string `json:"model"`
+ Runner string `json:"runner,omitempty"`
Insecure bool `json:"insecure,omitempty"` // Deprecated: ignored
Username string `json:"username"` // Deprecated: ignored
Password string `json:"password"` // Deprecated: ignored
@@ -860,6 +899,7 @@ type ProcessModelResponse struct {
ExpiresAt time.Time `json:"expires_at"`
SizeVRAM int64 `json:"size_vram"`
ContextLength int `json:"context_length"`
+ Runner string `json:"runner,omitempty"`
}
type TokenResponse struct {
@@ -958,6 +998,10 @@ type ModelDetails struct {
QuantizationLevel string `json:"quantization_level"`
ContextLength int `json:"context_length,omitempty"`
EmbeddingLength int `json:"embedding_length,omitempty"`
+
+ // Runner identifies which runner serves this model. Manifest-list models
+ // list one row per child manifest; Runner is what distinguishes them.
+ Runner string `json:"runner,omitempty"`
}
// UserResponse provides information about a user.
diff --git a/app/ui/ui.go b/app/ui/ui.go
index 1f7287545..a88c5fb2f 100644
--- a/app/ui/ui.go
+++ b/app/ui/ui.go
@@ -561,6 +561,9 @@ func (s *Server) checkModelUpstream(ctx context.Context, modelName string, timeo
if err != nil {
return "", 0, err
}
+ // Opt into manifest lists so the registry reports the digest of what
+ // pullModelManifest stores locally rather than a legacy fallback child.
+ req.Header.Set("Accept", strings.Join([]string{manifest.MediaTypeManifestList, manifest.MediaTypeManifest}, ", "))
httpClient := s.httpClient()
httpClient.Timeout = timeout
diff --git a/cmd/cloud_suggest.go b/cmd/cloud_suggest.go
index 91fb242ba..e9c1e7cf2 100644
--- a/cmd/cloud_suggest.go
+++ b/cmd/cloud_suggest.go
@@ -80,14 +80,14 @@ func cloudSuggestionName(name string, insecure bool) (string, bool) {
// a confirmation prompt, or by augmenting the returned error when not at a
// terminal. It returns the name that was actually pulled. `verb` is the
// user-facing command ("run" or "pull") used in the hint text.
-func pullWithCloudSuggestion(ctx context.Context, client *api.Client, name string, insecure bool, verb string) (string, error) {
+func pullWithCloudSuggestion(ctx context.Context, client *api.Client, name, runner string, insecure bool, verb string) (string, error) {
// If a suggestion prompt may follow a failed pull, erase the failed
// attempt's progress display instead of leaving its "pulling manifest"
// line to stack up against the accepted pull's identical one.
_, eligible := cloudSuggestionName(name, insecure)
clearNotFound := eligible && isInteractiveTerminal()
- pullErr := pullModelWithProgress(ctx, client, name, insecure, clearNotFound)
+ pullErr := pullModelWithProgress(ctx, client, name, runner, insecure, clearNotFound)
if pullErr == nil {
return name, nil
}
@@ -100,7 +100,7 @@ func pullWithCloudSuggestion(ctx context.Context, client *api.Client, name strin
// Showing a ":cloud" model is proxied to ollama.com and mirrors its status,
// so this reliably answers "does a cloud version exist?". Any error (no
// cloud tag, cloud disabled, older server, offline) means no suggestion.
- if _, err := client.Show(ctx, &api.ShowRequest{Model: cloudName}); err != nil {
+ if _, err := client.Show(ctx, &api.ShowRequest{Model: cloudName, Runner: runner}); err != nil {
return "", pullErr
}
@@ -114,7 +114,7 @@ func pullWithCloudSuggestion(ctx context.Context, client *api.Client, name strin
return "", pullErr
}
- if err := pullModelWithProgress(ctx, client, cloudName, insecure, false); err != nil {
+ if err := pullModelWithProgress(ctx, client, cloudName, runner, insecure, false); err != nil {
return "", err
}
return cloudName, nil
diff --git a/cmd/cmd.go b/cmd/cmd.go
index af7427d39..f316a430d 100644
--- a/cmd/cmd.go
+++ b/cmd/cmd.go
@@ -139,11 +139,11 @@ func convertSelectionItemUpdates(updates <-chan []launch.SelectionItem) <-chan [
const ConnectInstructions = "If your browser did not open, navigate to:\n %s\n\n"
// ensureThinkingSupport emits a warning if the model does not advertise thinking support
-func ensureThinkingSupport(ctx context.Context, client *api.Client, name string) {
+func ensureThinkingSupport(ctx context.Context, client *api.Client, name, runner string) {
if name == "" {
return
}
- resp, err := client.Show(ctx, &api.ShowRequest{Model: name})
+ resp, err := client.Show(ctx, &api.ShowRequest{Model: name, Runner: runner})
if err != nil {
return
}
@@ -325,6 +325,42 @@ func CreateHandler(cmd *cobra.Command, args []string) error {
return fmt.Errorf("invalid model name: %s", modelName)
}
+ list, _ := cmd.Flags().GetStringSlice("combine")
+ if len(list) > 0 {
+ if quantize, _ := cmd.Flags().GetString("quantize"); quantize != "" {
+ return errors.New("--combine cannot be used with --quantize")
+ }
+ if cmd.Flags().Changed("file") {
+ return errors.New("--combine cannot be used with --file")
+ }
+
+ client, err := api.ClientFromEnvironment()
+ if err != nil {
+ return err
+ }
+
+ req := &api.CreateRequest{
+ Model: modelName,
+ List: list,
+ }
+
+ status := "creating manifest list"
+ spinner := progress.NewSpinner(status)
+ p.Add(status, spinner)
+
+ fn := func(resp api.ProgressResponse) error {
+ if status != resp.Status {
+ spinner.Stop()
+ status = resp.Status
+ spinner = progress.NewSpinner(status)
+ p.Add(status, spinner)
+ }
+ return nil
+ }
+
+ return client.Create(cmd.Context(), req, fn)
+ }
+
draftQuantize, _ := cmd.Flags().GetString("draft-quantize")
quantize, _ := cmd.Flags().GetString("quantize")
force, _ := cmd.Flags().GetBool("force")
@@ -632,7 +668,7 @@ func loadOrUnloadModel(cmd *cobra.Command, opts *runOptions) error {
requestedCloud := modelref.HasExplicitCloudSource(opts.Model)
- if info, err := client.Show(cmd.Context(), &api.ShowRequest{Model: opts.Model}); err != nil {
+ if info, err := client.Show(cmd.Context(), &api.ShowRequest{Model: opts.Model, Runner: opts.Runner}); err != nil {
return err
} else if info.RemoteHost != "" || requestedCloud {
// Cloud model, no need to load/unload
@@ -664,6 +700,7 @@ func loadOrUnloadModel(cmd *cobra.Command, opts *runOptions) error {
req := &api.GenerateRequest{
Model: opts.Model,
+ Runner: opts.Runner,
KeepAlive: opts.KeepAlive,
// pass Think here so we fail before getting to the chat prompt if the model doesn't support it
@@ -791,8 +828,8 @@ func hasListedModelName(models []api.ListModelResponse, name string) bool {
// pullWithCloudSuggestion), in which case the returned name is the cloud
// name the caller should continue with. verb is the user-facing command
// ("run" or "pull") used in hint text.
-func showOrPullModel(cmd *cobra.Command, client *api.Client, name string, insecure bool, verb string) (*api.ShowResponse, string, error) {
- info, err := client.Show(cmd.Context(), &api.ShowRequest{Model: name})
+func showOrPullModel(cmd *cobra.Command, client *api.Client, name, runner string, insecure bool, verb string) (*api.ShowResponse, string, error) {
+ info, err := client.Show(cmd.Context(), &api.ShowRequest{Model: name, Runner: runner})
if err == nil {
return info, name, nil
}
@@ -802,12 +839,12 @@ func showOrPullModel(cmd *cobra.Command, client *api.Client, name string, insecu
return nil, name, err
}
- resolved, err := pullWithCloudSuggestion(cmd.Context(), client, name, insecure, verb)
+ resolved, err := pullWithCloudSuggestion(cmd.Context(), client, name, runner, insecure, verb)
if err != nil {
return nil, name, err
}
- info, err = client.Show(cmd.Context(), &api.ShowRequest{Model: resolved})
+ info, err = client.Show(cmd.Context(), &api.ShowRequest{Model: resolved, Runner: runner})
return info, resolved, err
}
@@ -821,6 +858,14 @@ func RunHandler(cmd *cobra.Command, args []string) error {
ShowConnect: true,
}
+ if flag := cmd.Flags().Lookup("runner"); flag != nil {
+ runner, err := cmd.Flags().GetString("runner")
+ if err != nil {
+ return err
+ }
+ opts.Runner = runner
+ }
+
format, err := cmd.Flags().GetString("format")
if err != nil {
return err
@@ -909,7 +954,7 @@ func RunHandler(cmd *cobra.Command, args []string) error {
return err
}
- info, name, err := showOrPullModel(cmd, client, args[0], insecure, "run")
+ info, name, err := showOrPullModel(cmd, client, args[0], opts.Runner, insecure, "run")
if err != nil {
if handleCloudAuthorizationError(err) {
return nil
@@ -1234,12 +1279,12 @@ func ListRunningHandler(cmd *cobra.Command, args []string) error {
until = format.HumanTime(m.ExpiresAt, "Never")
}
ctxStr := strconv.Itoa(m.ContextLength)
- data = append(data, []string{m.Name, m.Digest[:12], format.HumanBytes(m.Size), procStr, ctxStr, until})
+ data = append(data, []string{m.Name, m.Digest[:12], format.HumanBytes(m.Size), procStr, ctxStr, m.Runner, until})
}
}
table := tablewriter.NewWriter(os.Stdout)
- table.SetHeader([]string{"NAME", "ID", "SIZE", "PROCESSOR", "CONTEXT", "UNTIL"})
+ table.SetHeader([]string{"NAME", "ID", "SIZE", "PROCESSOR", "CONTEXT", "RUNNER", "UNTIL"})
table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetHeaderLine(false)
@@ -1420,6 +1465,14 @@ func showInfo(resp *api.ShowResponse, verbose bool, w io.Writer) error {
if resp.Requires != "" {
rows = append(rows, []string{"", "requires", resp.Requires})
}
+ if len(resp.Manifests) > 0 {
+ if runner, ok := showSelectedRunner(resp.Manifests); ok {
+ rows = append(rows, []string{"", "runner", runner})
+ }
+ if runners := showAvailableRunners(resp.Manifests); runners != "" {
+ rows = append(rows, []string{"", "available runners", runners})
+ }
+ }
return
})
@@ -1584,6 +1637,62 @@ func showInfo(resp *api.ShowResponse, verbose bool, w io.Writer) error {
return nil
}
+func showSelectedRunner(manifests []api.ManifestSummary) (string, bool) {
+ for _, m := range manifests {
+ if m.Selected {
+ return showRunnerName(m), true
+ }
+ }
+ if len(manifests) == 1 {
+ return showRunnerName(manifests[0]), true
+ }
+ return "", false
+}
+
+func showAvailableRunners(manifests []api.ManifestSummary) string {
+ parts := make([]string, 0, len(manifests))
+ for _, m := range manifests {
+ if m.Selected {
+ parts = append(parts, showRunnerSummary(m))
+ }
+ }
+ for _, m := range manifests {
+ if m.Selected {
+ continue
+ }
+ parts = append(parts, showRunnerSummary(m))
+ }
+ return strings.Join(parts, ", ")
+}
+
+func showRunnerName(m api.ManifestSummary) string {
+ if m.Runner != "" {
+ return m.Runner
+ }
+ return "runner"
+}
+
+func showRunnerSummary(m api.ManifestSummary) string {
+ label := showRunnerName(m)
+ digest := showDigestSummary(m.Digest)
+ if digest != "" {
+ label += ":" + digest
+ }
+ return label
+}
+
+func showDigestSummary(digest string) string {
+ digest = strings.ToLower(strings.Replace(digest, "-", ":", 1))
+ algo, value, ok := strings.Cut(digest, ":")
+ if !ok || algo == "" || value == "" {
+ return ""
+ }
+ if len(value) > 12 {
+ value = value[:12]
+ }
+ return algo + ":" + value
+}
+
func CopyHandler(cmd *cobra.Command, args []string) error {
client, err := api.ClientFromEnvironment()
if err != nil {
@@ -1591,10 +1700,12 @@ func CopyHandler(cmd *cobra.Command, args []string) error {
}
req := api.CopyRequest{Source: args[0], Destination: args[1]}
- if err := client.Copy(cmd.Context(), &req); err != nil {
+ resp, err := client.Copy(cmd.Context(), &req)
+ if err != nil {
return err
}
fmt.Printf("copied '%s' to '%s'\n", args[0], args[1])
+ fmt.Fprintln(os.Stderr, resp.Status)
return nil
}
@@ -1603,13 +1714,20 @@ func PullHandler(cmd *cobra.Command, args []string) error {
if err != nil {
return err
}
+ runner := ""
+ if flag := cmd.Flags().Lookup("runner"); flag != nil {
+ runner, err = cmd.Flags().GetString("runner")
+ if err != nil {
+ return err
+ }
+ }
client, err := api.ClientFromEnvironment()
if err != nil {
return err
}
- _, err = pullWithCloudSuggestion(cmd.Context(), client, args[0], insecure, "pull")
+ _, err = pullWithCloudSuggestion(cmd.Context(), client, args[0], runner, insecure, "pull")
return err
}
@@ -1617,7 +1735,7 @@ func PullHandler(cmd *cobra.Command, args []string) error {
// clearNotFound is set and the pull fails because the model doesn't exist,
// the progress display is erased rather than left behind; callers set it
// when a ":cloud" suggestion prompt may immediately follow the failure.
-func pullModelWithProgress(ctx context.Context, client *api.Client, name string, insecure, clearNotFound bool) error {
+func pullModelWithProgress(ctx context.Context, client *api.Client, name, runner string, insecure, clearNotFound bool) error {
p := progress.NewProgress(os.Stderr)
defer p.Stop()
@@ -1678,7 +1796,7 @@ func pullModelWithProgress(ctx context.Context, client *api.Client, name string,
return nil
}
- request := api.PullRequest{Name: name, Insecure: insecure}
+ request := api.PullRequest{Name: name, Runner: runner, Insecure: insecure}
err := client.Pull(ctx, &request, fn)
if clearNotFound && isPullNotFoundErr(err) {
// The deferred Stop becomes a no-op after this.
@@ -1691,6 +1809,7 @@ type generateContextKey string
type runOptions struct {
Model string
+ Runner string
ParentModel string
LoadedMessages []api.Message
Prompt string
@@ -1742,6 +1861,7 @@ func (r runOptions) Copy() runOptions {
return runOptions{
Model: r.Model,
+ Runner: r.Runner,
ParentModel: r.ParentModel,
LoadedMessages: loadedMessages,
Prompt: r.Prompt,
@@ -1925,6 +2045,7 @@ func chat(cmd *cobra.Command, opts runOptions) (*api.Message, error) {
req := &api.ChatRequest{
Model: opts.Model,
+ Runner: opts.Runner,
Messages: opts.Messages,
Format: json.RawMessage(opts.Format),
Options: opts.Options,
@@ -2057,6 +2178,7 @@ func generate(cmd *cobra.Command, opts runOptions) error {
request := api.GenerateRequest{
Model: opts.Model,
+ Runner: opts.Runner,
Prompt: opts.Prompt,
Context: generateContext,
Images: opts.Images,
@@ -2226,7 +2348,7 @@ func launchInteractiveModel(cmd *cobra.Command, modelName string) error {
return err
}
- info, resolvedModel, err := showOrPullModel(cmd, client, modelName, false, "run")
+ info, resolvedModel, err := showOrPullModel(cmd, client, modelName, "", false, "run")
if err != nil {
if handleCloudAuthorizationError(err) {
return nil
@@ -2427,6 +2549,7 @@ func NewCLI() *cobra.Command {
createCmd.Flags().StringP("file", "f", "", "Name of the Modelfile (default \"Modelfile\")")
createCmd.Flags().StringP("quantize", "q", "", "Quantize safetensors model to this level (e.g. nvfp4)")
+ createCmd.Flags().StringSlice("combine", nil, "Create a manifest list from comma-separated local models")
createCmd.Flags().String("draft-quantize", "", "Quantize safetensors draft model to this level")
createCmd.Flags().Bool("force", false, "Continue local creation when MLX validation fails")
createCmd.Flags().Bool("experimental", false, "Deprecated no-op")
@@ -2460,6 +2583,8 @@ func NewCLI() *cobra.Command {
runCmd.Flags().Bool("insecure", false, "Use an insecure registry")
runCmd.Flags().Bool("nowordwrap", false, "Don't wrap words to the next line automatically")
runCmd.Flags().String("format", "", "Response format (e.g. json)")
+ runCmd.Flags().String("runner", "", "Runner to use for manifest list selection (mlx, ggml, llamacpp)")
+ runCmd.Flags().MarkHidden("runner")
runCmd.Flags().String("think", "", "Enable thinking mode: true/false or high/medium/low for supported models")
runCmd.Flags().Lookup("think").NoOptDefVal = "true"
runCmd.Flags().Bool("hidethinking", false, "Hide thinking output (if provided)")
@@ -2491,6 +2616,8 @@ func NewCLI() *cobra.Command {
}
pullCmd.Flags().Bool("insecure", false, "Use an insecure registry")
+ pullCmd.Flags().String("runner", "", "Runner to use for manifest list selection (mlx, ggml, llamacpp)")
+ pullCmd.Flags().MarkHidden("runner")
pushCmd := &cobra.Command{
Use: "push MODEL",
diff --git a/cmd/cmd_test.go b/cmd/cmd_test.go
index 08e975cec..463ea1f1f 100644
--- a/cmd/cmd_test.go
+++ b/cmd/cmd_test.go
@@ -75,6 +75,44 @@ func TestRunThinkingNamesReachServer(t *testing.T) {
}
}
+// captureOutput redirects *target (os.Stdout or os.Stderr) to a pipe while fn
+// runs and returns everything written to it. The original file is restored
+// before captureOutput returns.
+func captureOutput(t *testing.T, target **os.File, fn func()) string {
+ t.Helper()
+
+ old := *target
+ r, w, err := os.Pipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ *target = w
+ defer func() {
+ *target = old
+ }()
+
+ done := make(chan string)
+ go func() {
+ var buf bytes.Buffer
+ _, _ = io.Copy(&buf, r)
+ done <- buf.String()
+ }()
+
+ fn()
+ w.Close()
+ return <-done
+}
+
+func captureStdout(t *testing.T, fn func()) string {
+ t.Helper()
+ return captureOutput(t, &os.Stdout, fn)
+}
+
+func captureStderr(t *testing.T, fn func()) string {
+ t.Helper()
+ return captureOutput(t, &os.Stderr, fn)
+}
+
func TestShowInfo(t *testing.T) {
t.Run("bare details", func(t *testing.T) {
var b bytes.Buffer
@@ -380,6 +418,63 @@ Weigh anchor!
})
}
+func TestShowInfoRendersRunnerAlternates(t *testing.T) {
+ var b bytes.Buffer
+ if err := showInfo(&api.ShowResponse{
+ ModelInfo: map[string]any{
+ "general.architecture": "gemma3",
+ },
+ Details: api.ModelDetails{
+ ParameterSize: "4.3B",
+ QuantizationLevel: "nvfp4",
+ },
+ Manifests: []api.ManifestSummary{
+ {Digest: "sha256:aaaaaaaaaaaabbbbbbbbbbbbccccccccccccddddddddddddeeeeeeeeeeeeffffffff", Runner: "mlx", Format: "safetensors", Selected: true},
+ {Digest: "sha256:1111111111112222222222223333333333334444444444445555555555556666", Runner: "llamacpp", Format: "gguf"},
+ },
+ }, false, &b); err != nil {
+ t.Fatal(err)
+ }
+
+ expect := ` Model
+ architecture gemma3
+ parameters 4.3B
+ quantization nvfp4
+ runner mlx
+ available runners mlx:sha256:aaaaaaaaaaaa,
+ llamacpp:sha256:111111111111
+
+`
+ trimLinePadding := func(s string) string {
+ lines := strings.Split(s, "\n")
+ for i, line := range lines {
+ lines[i] = strings.TrimRight(line, " \t\r")
+ }
+ return strings.Join(lines, "\n")
+ }
+ if diff := cmp.Diff(trimLinePadding(expect), trimLinePadding(b.String())); diff != "" {
+ t.Errorf("unexpected output (-want +got):\n%s", diff)
+ }
+}
+
+func TestShowRunnerSummaries(t *testing.T) {
+ selected, ok := showSelectedRunner([]api.ManifestSummary{
+ {Digest: "sha256:aaaaaaaaaaaabbbbbbbbbbbbccccccccccccddddddddddddeeeeeeeeeeeeffffffff", Runner: "mlx", Format: "safetensors", Selected: true},
+ {Digest: "sha256:1111111111112222222222223333333333334444444444445555555555556666", Runner: "llamacpp", Format: "gguf"},
+ })
+ if !ok || selected != "mlx" {
+ t.Fatalf("selected = %q, %t", selected, ok)
+ }
+
+ available := showAvailableRunners([]api.ManifestSummary{
+ {Digest: "sha256:aaaaaaaaaaaabbbbbbbbbbbbccccccccccccddddddddddddeeeeeeeeeeeeffffffff", Runner: "mlx", Format: "safetensors", Selected: true},
+ {Digest: "sha256:1111111111112222222222223333333333334444444444445555555555556666", Runner: "llamacpp", Format: "gguf"},
+ })
+ if available != "mlx:sha256:aaaaaaaaaaaa, llamacpp:sha256:111111111111" {
+ t.Fatalf("available = %q", available)
+ }
+}
+
func TestDeleteHandler(t *testing.T) {
stopped := false
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -488,26 +583,15 @@ func TestRunEmbeddingModel(t *testing.T) {
cmd.Flags().String("think", "", "")
cmd.Flags().Bool("hidethinking", false, "")
- oldStdout := os.Stdout
- r, w, _ := os.Pipe()
- os.Stdout = w
-
- errCh := make(chan error, 1)
- go func() {
- errCh <- RunHandler(cmd, []string{"test-embedding-model", "hello", "world"})
- }()
-
- err := <-errCh
- w.Close()
- os.Stdout = oldStdout
+ var err error
+ out := captureStdout(t, func() {
+ err = RunHandler(cmd, []string{"test-embedding-model", "hello", "world"})
+ })
if err != nil {
t.Fatalf("RunHandler returned error: %v", err)
}
- var out bytes.Buffer
- io.Copy(&out, r)
-
select {
case req := <-reqCh:
inputText, _ := req.Input.(string)
@@ -528,11 +612,136 @@ func TestRunEmbeddingModel(t *testing.T) {
}
expectOutput := "[0.1,0.2,0.3]\n"
- if diff := cmp.Diff(expectOutput, out.String()); diff != "" {
+ if diff := cmp.Diff(expectOutput, out); diff != "" {
t.Errorf("unexpected output (-want +got):\n%s", diff)
}
}
+func TestListRunningHandlerShowsRunner(t *testing.T) {
+ mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/ps" || r.Method != http.MethodGet {
+ http.NotFound(w, r)
+ return
+ }
+
+ if err := json.NewEncoder(w).Encode(api.ProcessResponse{
+ Models: []api.ProcessModelResponse{
+ {
+ Name: "test-model:latest",
+ Model: "test-model:latest",
+ Digest: "abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890",
+ Size: 1024,
+ SizeVRAM: 1024,
+ ContextLength: 4096,
+ Runner: "mlx",
+ ExpiresAt: time.Now().Add(time.Hour),
+ },
+ },
+ }); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ }
+ }))
+ t.Setenv("OLLAMA_HOST", mockServer.URL)
+ t.Cleanup(mockServer.Close)
+
+ cmd := &cobra.Command{}
+ cmd.SetContext(t.Context())
+
+ var err error
+ got := captureStdout(t, func() {
+ err = ListRunningHandler(cmd, nil)
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ for _, want := range []string{"CONTEXT", "RUNNER", "abcdef123456", "mlx"} {
+ if !strings.Contains(got, want) {
+ t.Fatalf("output missing %q:\n%s", want, got)
+ }
+ }
+}
+
+func TestRunHandlerRunnerFlag(t *testing.T) {
+ showReqCh := make(chan api.ShowRequest, 1)
+ generateReqCh := make(chan api.GenerateRequest, 1)
+ mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.URL.Path == "/api/show" && r.Method == http.MethodPost:
+ var req api.ShowRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ showReqCh <- req
+ w.Header().Set("Content-Type", "application/json")
+ if err := json.NewEncoder(w).Encode(api.ShowResponse{
+ Capabilities: []model.Capability{model.CapabilityCompletion},
+ ModelInfo: map[string]any{},
+ }); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ }
+ case r.URL.Path == "/api/generate" && r.Method == http.MethodPost:
+ var req api.GenerateRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ generateReqCh <- req
+ w.Header().Set("Content-Type", "application/x-ndjson")
+ if err := json.NewEncoder(w).Encode(api.GenerateResponse{
+ Model: "test-model",
+ Done: true,
+ }); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ }
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ t.Setenv("OLLAMA_HOST", mockServer.URL)
+ t.Cleanup(mockServer.Close)
+
+ cmd := &cobra.Command{}
+ cmd.SetContext(t.Context())
+ cmd.Flags().String("keepalive", "", "")
+ cmd.Flags().Bool("verbose", false, "")
+ cmd.Flags().Bool("insecure", false, "")
+ cmd.Flags().Bool("nowordwrap", false, "")
+ cmd.Flags().String("format", "", "")
+ cmd.Flags().String("runner", "", "")
+ cmd.Flags().String("think", "", "")
+ cmd.Flags().Bool("hidethinking", false, "")
+ if err := cmd.Flags().Set("runner", "llamacpp"); err != nil {
+ t.Fatal(err)
+ }
+
+ var err error
+ captureStdout(t, func() {
+ err = RunHandler(cmd, []string{"test-model", "hello"})
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ select {
+ case req := <-showReqCh:
+ if req.Runner != "llamacpp" {
+ t.Fatalf("show runner = %q, want %q", req.Runner, "llamacpp")
+ }
+ default:
+ t.Fatal("server did not receive show request")
+ }
+ select {
+ case req := <-generateReqCh:
+ if req.Runner != "llamacpp" {
+ t.Fatalf("generate runner = %q, want %q", req.Runner, "llamacpp")
+ }
+ default:
+ t.Fatal("server did not receive generate request")
+ }
+}
+
func TestRunEmbeddingModelWithFlags(t *testing.T) {
reqCh := make(chan api.EmbedRequest, 1)
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -590,26 +799,15 @@ func TestRunEmbeddingModelWithFlags(t *testing.T) {
t.Fatalf("failed to set keepalive flag: %v", err)
}
- oldStdout := os.Stdout
- r, w, _ := os.Pipe()
- os.Stdout = w
-
- errCh := make(chan error, 1)
- go func() {
- errCh <- RunHandler(cmd, []string{"test-embedding-model", "test", "input"})
- }()
-
- err := <-errCh
- w.Close()
- os.Stdout = oldStdout
+ var err error
+ out := captureStdout(t, func() {
+ err = RunHandler(cmd, []string{"test-embedding-model", "test", "input"})
+ })
if err != nil {
t.Fatalf("RunHandler returned error: %v", err)
}
- var out bytes.Buffer
- io.Copy(&out, r)
-
select {
case req := <-reqCh:
inputText, _ := req.Input.(string)
@@ -630,7 +828,7 @@ func TestRunEmbeddingModelWithFlags(t *testing.T) {
}
expectOutput := "[0.4,0.5]\n"
- if diff := cmp.Diff(expectOutput, out.String()); diff != "" {
+ if diff := cmp.Diff(expectOutput, out); diff != "" {
t.Errorf("unexpected output (-want +got):\n%s", diff)
}
}
@@ -688,28 +886,16 @@ func TestRunEmbeddingModelPipedInput(t *testing.T) {
stdinW.Write([]byte("piped text"))
stdinW.Close()
- // Capture stdout
- oldStdout := os.Stdout
- stdoutR, stdoutW, _ := os.Pipe()
- os.Stdout = stdoutW
-
- errCh := make(chan error, 1)
- go func() {
- errCh <- RunHandler(cmd, []string{"test-embedding-model", "additional", "args"})
- }()
-
- err := <-errCh
- stdoutW.Close()
- os.Stdout = oldStdout
+ var err error
+ out := captureStdout(t, func() {
+ err = RunHandler(cmd, []string{"test-embedding-model", "additional", "args"})
+ })
os.Stdin = oldStdin
if err != nil {
t.Fatalf("RunHandler returned error: %v", err)
}
- var out bytes.Buffer
- io.Copy(&out, stdoutR)
-
select {
case req := <-reqCh:
inputText, _ := req.Input.(string)
@@ -722,7 +908,7 @@ func TestRunEmbeddingModelPipedInput(t *testing.T) {
}
expectOutput := "[0.6,0.7]\n"
- if diff := cmp.Diff(expectOutput, out.String()); diff != "" {
+ if diff := cmp.Diff(expectOutput, out); diff != "" {
t.Errorf("unexpected output (-want +got):\n%s", diff)
}
}
@@ -807,16 +993,10 @@ func TestRunHandler_CloudAuthErrorOnShow_PrintsSigninMessage(t *testing.T) {
cmd.Flags().String("think", "", "")
cmd.Flags().Bool("hidethinking", false, "")
- oldStdout := os.Stdout
- readOut, writeOut, _ := os.Pipe()
- os.Stdout = writeOut
- t.Cleanup(func() { os.Stdout = oldStdout })
-
- err := RunHandler(cmd, []string{"gpt-oss:20b:cloud", "hi"})
-
- _ = writeOut.Close()
- var out bytes.Buffer
- _, _ = io.Copy(&out, readOut)
+ var err error
+ out := captureStdout(t, func() {
+ err = RunHandler(cmd, []string{"gpt-oss:20b:cloud", "hi"})
+ })
if err != nil {
t.Fatalf("RunHandler returned error: %v", err)
@@ -826,12 +1006,12 @@ func TestRunHandler_CloudAuthErrorOnShow_PrintsSigninMessage(t *testing.T) {
t.Fatal("expected run to stop before /api/generate after unauthorized /api/show")
}
- if !strings.Contains(out.String(), "You need to be signed in to Ollama to run Cloud models.") {
- t.Fatalf("expected sign-in guidance message, got %q", out.String())
+ if !strings.Contains(out, "You need to be signed in to Ollama to run Cloud models.") {
+ t.Fatalf("expected sign-in guidance message, got %q", out)
}
- if !strings.Contains(out.String(), "https://ollama.com/signin") {
- t.Fatalf("expected signin_url in output, got %q", out.String())
+ if !strings.Contains(out, "https://ollama.com/signin") {
+ t.Fatalf("expected signin_url in output, got %q", out)
}
}
@@ -875,27 +1055,21 @@ func TestRunHandler_CloudAuthErrorOnGenerate_PrintsSigninMessage(t *testing.T) {
cmd.Flags().String("think", "", "")
cmd.Flags().Bool("hidethinking", false, "")
- oldStdout := os.Stdout
- readOut, writeOut, _ := os.Pipe()
- os.Stdout = writeOut
- t.Cleanup(func() { os.Stdout = oldStdout })
-
- err := RunHandler(cmd, []string{"gpt-oss:20b:cloud", "hi"})
-
- _ = writeOut.Close()
- var out bytes.Buffer
- _, _ = io.Copy(&out, readOut)
+ var err error
+ out := captureStdout(t, func() {
+ err = RunHandler(cmd, []string{"gpt-oss:20b:cloud", "hi"})
+ })
if err != nil {
t.Fatalf("RunHandler returned error: %v", err)
}
- if !strings.Contains(out.String(), "You need to be signed in to Ollama to run Cloud models.") {
- t.Fatalf("expected sign-in guidance message, got %q", out.String())
+ if !strings.Contains(out, "You need to be signed in to Ollama to run Cloud models.") {
+ t.Fatalf("expected sign-in guidance message, got %q", out)
}
- if !strings.Contains(out.String(), "https://ollama.com/signin") {
- t.Fatalf("expected signin_url in output, got %q", out.String())
+ if !strings.Contains(out, "https://ollama.com/signin") {
+ t.Fatalf("expected signin_url in output, got %q", out)
}
}
@@ -1318,38 +1492,23 @@ func TestPushHandler(t *testing.T) {
cmd.Flags().Bool("insecure", false, "")
cmd.SetContext(t.Context())
- // Redirect stderr to capture progress output
- oldStderr := os.Stderr
- r, w, _ := os.Pipe()
- os.Stderr = w
-
- // Capture stdout for the "Model pushed" message
- oldStdout := os.Stdout
- outR, outW, _ := os.Pipe()
- os.Stdout = outW
-
- err := PushHandler(cmd, []string{tt.modelName})
-
- // Restore stderr
- w.Close()
- os.Stderr = oldStderr
- // drain the pipe
- if _, err := io.ReadAll(r); err != nil {
- t.Fatal(err)
- }
-
- // Restore stdout and get output
- outW.Close()
- os.Stdout = oldStdout
- stdout, _ := io.ReadAll(outR)
+ var err error
+ var stdout string
+ // Capture stderr for progress output and stdout for the "Model
+ // pushed" message.
+ captureStderr(t, func() {
+ stdout = captureStdout(t, func() {
+ err = PushHandler(cmd, []string{tt.modelName})
+ })
+ })
if tt.expectedError == "" {
if err != nil {
t.Errorf("expected no error, got %v", err)
}
if tt.expectedOutput != "" {
- if got := string(stdout); !strings.Contains(got, tt.expectedOutput) {
- t.Errorf("expected output %q, got %q", tt.expectedOutput, got)
+ if !strings.Contains(stdout, tt.expectedOutput) {
+ t.Errorf("expected output %q, got %q", tt.expectedOutput, stdout)
}
}
} else {
@@ -1373,22 +1532,22 @@ func TestListHandler(t *testing.T) {
name: "list all models",
args: []string{},
serverResponse: []api.ListModelResponse{
- {Name: "model1", Digest: "sha256:abc123", Size: 1024, ModifiedAt: time.Now().Add(-24 * time.Hour)},
- {Name: "model2", Digest: "sha256:def456", Size: 2048, ModifiedAt: time.Now().Add(-48 * time.Hour)},
+ {Name: "model1", Digest: "abc123abc123abc123", Size: 1024, ModifiedAt: time.Now().Add(-24 * time.Hour)},
+ {Name: "model2", Digest: "def456def456def456", Size: 2048, ModifiedAt: time.Now().Add(-48 * time.Hour)},
},
expectedOutput: "NAME ID SIZE MODIFIED \n" +
- "model1 sha256:abc12 1.0 KB 24 hours ago \n" +
- "model2 sha256:def45 2.0 KB 2 days ago \n",
+ "model1 abc123abc123 1.0 KB 24 hours ago \n" +
+ "model2 def456def456 2.0 KB 2 days ago \n",
},
{
name: "filter models by prefix",
args: []string{"model1"},
serverResponse: []api.ListModelResponse{
- {Name: "model1", Digest: "sha256:abc123", Size: 1024, ModifiedAt: time.Now().Add(-24 * time.Hour)},
- {Name: "model2", Digest: "sha256:def456", Size: 2048, ModifiedAt: time.Now().Add(-24 * time.Hour)},
+ {Name: "model1", Digest: "abc123abc123abc123", Size: 1024, ModifiedAt: time.Now().Add(-24 * time.Hour)},
+ {Name: "model2", Digest: "def456def456def456", Size: 2048, ModifiedAt: time.Now().Add(-24 * time.Hour)},
},
expectedOutput: "NAME ID SIZE MODIFIED \n" +
- "model1 sha256:abc12 1.0 KB 24 hours ago \n",
+ "model1 abc123abc123 1.0 KB 24 hours ago \n",
},
{
name: "server error",
@@ -1423,24 +1582,17 @@ func TestListHandler(t *testing.T) {
cmd := &cobra.Command{}
cmd.SetContext(t.Context())
- // Capture stdout
- oldStdout := os.Stdout
- r, w, _ := os.Pipe()
- os.Stdout = w
-
- err := ListHandler(cmd, tt.args)
-
- // Restore stdout and get output
- w.Close()
- os.Stdout = oldStdout
- output, _ := io.ReadAll(r)
+ var err error
+ output := captureStdout(t, func() {
+ err = ListHandler(cmd, tt.args)
+ })
if tt.expectedError == "" {
if err != nil {
t.Errorf("expected no error, got %v", err)
}
- if got := string(output); got != tt.expectedOutput {
- t.Errorf("expected output:\n%s\ngot:\n%s", tt.expectedOutput, got)
+ if output != tt.expectedOutput {
+ t.Errorf("expected output:\n%s\ngot:\n%s", tt.expectedOutput, output)
}
} else {
if err == nil || !strings.Contains(err.Error(), tt.expectedError) {
@@ -1541,30 +1693,14 @@ func TestCreateHandler(t *testing.T) {
cmd.Flags().Bool("insecure", false, "")
cmd.SetContext(t.Context())
- // Redirect stderr to capture progress output
- oldStderr := os.Stderr
- r, w, _ := os.Pipe()
- os.Stderr = w
-
- // Capture stdout for the "Model pushed" message
- oldStdout := os.Stdout
- outR, outW, _ := os.Pipe()
- os.Stdout = outW
-
- err = CreateHandler(cmd, []string{tt.modelName})
-
- // Restore stderr
- w.Close()
- os.Stderr = oldStderr
- // drain the pipe
- if _, err := io.ReadAll(r); err != nil {
- t.Fatal(err)
- }
-
- // Restore stdout and get output
- outW.Close()
- os.Stdout = oldStdout
- stdout, _ := io.ReadAll(outR)
+ var stdout string
+ // Capture stderr for progress output and stdout for the final
+ // status message.
+ captureStderr(t, func() {
+ stdout = captureStdout(t, func() {
+ err = CreateHandler(cmd, []string{tt.modelName})
+ })
+ })
if tt.expectedError == "" {
if err != nil {
@@ -1572,8 +1708,8 @@ func TestCreateHandler(t *testing.T) {
}
if tt.expectedOutput != "" {
- if got := string(stdout); got != tt.expectedOutput {
- t.Errorf("expected output %q, got %q", tt.expectedOutput, got)
+ if stdout != tt.expectedOutput {
+ t.Errorf("expected output %q, got %q", tt.expectedOutput, stdout)
}
}
}
@@ -1988,6 +2124,61 @@ func TestResolveCreateDraftDir(t *testing.T) {
}
}
+func TestCreateHandlerManifestList(t *testing.T) {
+ mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/create" {
+ t.Errorf("unexpected request to %s", r.URL.Path)
+ http.Error(w, "not found", http.StatusNotFound)
+ return
+ }
+ if r.Method != http.MethodPost {
+ t.Errorf("expected POST request, got %s", r.Method)
+ }
+
+ var req api.CreateRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ if req.Model != "parent" {
+ t.Errorf("model = %q, want %q", req.Model, "parent")
+ }
+ if !cmp.Equal(req.List, []string{"gguf", "safetensors"}) {
+ t.Errorf("list = %#v, want %#v", req.List, []string{"gguf", "safetensors"})
+ }
+ if req.From != "" || len(req.Files) > 0 {
+ t.Errorf("manifest list create sent normal create fields: from=%q files=%v", req.From, req.Files)
+ }
+
+ if err := json.NewEncoder(w).Encode(api.ProgressResponse{Status: "success"}); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ w.(http.Flusher).Flush()
+ }))
+ t.Setenv("OLLAMA_HOST", mockServer.URL)
+ t.Cleanup(mockServer.Close)
+
+ cmd := &cobra.Command{}
+ cmd.Flags().String("file", "", "")
+ cmd.Flags().String("quantize", "", "")
+ cmd.Flags().Bool("experimental", false, "")
+ cmd.Flags().StringSlice("combine", nil, "")
+ cmd.SetContext(t.Context())
+ if err := cmd.Flags().Set("combine", "gguf,safetensors"); err != nil {
+ t.Fatal(err)
+ }
+
+ var err error
+ captureStderr(t, func() {
+ err = CreateHandler(cmd, []string{"parent"})
+ })
+
+ if err != nil {
+ t.Fatal(err)
+ }
+}
+
func TestSafetensorsCreateOptionsDetectsLocalDir(t *testing.T) {
dir := t.TempDir()
modelDir := filepath.Join(dir, "model")
diff --git a/cmd/interactive.go b/cmd/interactive.go
index 5a2f28c33..ff7fffbb2 100644
--- a/cmd/interactive.go
+++ b/cmd/interactive.go
@@ -224,7 +224,7 @@ func generateInteractive(cmd *cobra.Command, opts runOptions) error {
opts.Messages = []api.Message{}
opts.LoadedMessages = nil
fmt.Printf("Loading model '%s'\n", opts.Model)
- info, err := client.Show(cmd.Context(), &api.ShowRequest{Model: opts.Model})
+ info, err := client.Show(cmd.Context(), &api.ShowRequest{Model: opts.Model, Runner: opts.Runner})
if err != nil {
if strings.Contains(err.Error(), "not found") {
fmt.Printf("Couldn't find model '%s'\n", opts.Model)
@@ -323,7 +323,7 @@ func generateInteractive(cmd *cobra.Command, opts runOptions) error {
opts.Think = &thinkValue
thinkExplicitlySet = true
if client, err := api.ClientFromEnvironment(); err == nil {
- ensureThinkingSupport(cmd.Context(), client, opts.Model)
+ ensureThinkingSupport(cmd.Context(), client, opts.Model, opts.Runner)
}
if maybeLevel != "" {
fmt.Printf("Set 'think' mode to '%s'.\n", maybeLevel)
@@ -334,7 +334,7 @@ func generateInteractive(cmd *cobra.Command, opts runOptions) error {
opts.Think = &api.ThinkValue{Value: false}
thinkExplicitlySet = true
if client, err := api.ClientFromEnvironment(); err == nil {
- ensureThinkingSupport(cmd.Context(), client, opts.Model)
+ ensureThinkingSupport(cmd.Context(), client, opts.Model, opts.Runner)
}
fmt.Println("Set 'nothink' mode.")
case "format":
@@ -414,6 +414,7 @@ func generateInteractive(cmd *cobra.Command, opts runOptions) error {
}
req := &api.ShowRequest{
Name: opts.Model,
+ Runner: opts.Runner,
System: opts.System,
Options: opts.Options,
}
diff --git a/cmd/warn_thinking_test.go b/cmd/warn_thinking_test.go
index 31dc4156b..4d5eb9b70 100644
--- a/cmd/warn_thinking_test.go
+++ b/cmd/warn_thinking_test.go
@@ -47,7 +47,7 @@ func TestWarnMissingThinking(t *testing.T) {
oldStderr := os.Stderr
r, w, _ := os.Pipe()
os.Stderr = w
- ensureThinkingSupport(t.Context(), client, "m")
+ ensureThinkingSupport(t.Context(), client, "m", "")
w.Close()
os.Stderr = oldStderr
out, _ := io.ReadAll(r)
diff --git a/compatmigrate/bakllava.go b/compatmigrate/bakllava.go
new file mode 100644
index 000000000..d1e30929c
--- /dev/null
+++ b/compatmigrate/bakllava.go
@@ -0,0 +1,75 @@
+package compatmigrate
+
+import (
+ "strings"
+)
+
+type bakllavaMigrator struct{}
+
+// Mirrors needs_default_llava_projector_type in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (bakllavaMigrator) NeedsMigration(src *SourceModel) bool {
+ return src.ProjectorGGUF != nil &&
+ src.ProjectorGGUF.KeyValue("general.architecture").String() == "clip" &&
+ src.ProjectorGGUF.KeyValue("has_vision_encoder").Bool() &&
+ !rawGGUFKeyExists(src.ProjectorGGUF, "clip.projector_type") &&
+ !rawGGUFKeyExists(src.ProjectorGGUF, "clip.vision.projector_type")
+}
+
+func (bakllavaMigrator) Migrate(src *SourceModel) (*Result, error) {
+ modelTensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+ projectorTensors, err := readAllProjectorTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ modelKV := outKV{}
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+ key := keyValue.Key
+ if strings.HasPrefix(key, "general.") || strings.HasPrefix(key, "tokenizer.") || strings.HasPrefix(key, "llama.") {
+ modelKV[key] = normalizeGGUFValue(keyValue.Any())
+ }
+ }
+ if llama3NeedsMetadataFix(src) {
+ applyLlama3MetadataFix(modelKV)
+ }
+
+ projectorKV := outKV{}
+ for _, keyValue := range src.ProjectorGGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+ key := keyValue.Key
+ if strings.HasPrefix(key, "general.") || strings.HasPrefix(key, "clip.") {
+ projectorKV[key] = normalizeGGUFValue(keyValue.Any())
+ }
+ }
+
+ // The public bakllava projector is already split and tensor-compatible, but
+ // it predates llama-server's required projector type metadata. Local
+ // migration patches only that missing KV so users with the old q4_0 library
+ // artifact can load it without a pull. An explicit pull still gets the
+ // cleaner recreated manifest-list artifact once registry support is live.
+ projectorKV["clip.projector_type"] = "mlp"
+
+ modelOut := make([]*outTensor, 0, len(modelTensors))
+ for _, tensor := range modelTensors {
+ modelOut = append(modelOut, copyTensor(tensor.name, tensor))
+ }
+ projectorOut := make([]*outTensor, 0, len(projectorTensors))
+ for _, tensor := range projectorTensors {
+ projectorOut = append(projectorOut, copyTensor(tensor.name, tensor))
+ }
+
+ return &Result{
+ ModelKV: modelKV,
+ ModelTensors: modelOut,
+ ProjectorKV: projectorKV,
+ ProjectorTensors: projectorOut,
+ }, nil
+}
diff --git a/compatmigrate/deepseek_ocr.go b/compatmigrate/deepseek_ocr.go
new file mode 100644
index 000000000..d3e92bf6c
--- /dev/null
+++ b/compatmigrate/deepseek_ocr.go
@@ -0,0 +1,201 @@
+package compatmigrate
+
+import (
+ "strings"
+)
+
+type deepseekOCRMigrator struct{}
+
+// Mirrors detect_ollama_deepseekocr in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (deepseekOCRMigrator) NeedsMigration(src *SourceModel) bool {
+ return src.GGUF.KeyValue("general.architecture").String() == "deepseekocr"
+}
+
+func (deepseekOCRMigrator) Migrate(src *SourceModel) (*Result, error) {
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ var modelTensors []*outTensor
+ var projectorTensors []*outTensor
+ for _, tensor := range tensors {
+ if deepseekOCRVisionTensor(tensor.name) {
+ projectorTensors = append(projectorTensors, copyTensor(deepseekOCRProjectorTensorName(tensor.name), tensor))
+ continue
+ }
+ modelTensors = append(modelTensors, copyTensor(tensor.name, tensor))
+ }
+
+ modelKV := deepseekOCRModelKV(src)
+ if _, ok := modelKV["deepseek2-ocr.expert_feed_forward_length"]; !ok {
+ if inferred := deepseekOCRExpertFeedForwardLength(tensors); inferred != 0 {
+ modelKV["deepseek2-ocr.expert_feed_forward_length"] = inferred
+ }
+ }
+ if _, ok := modelKV["deepseek2-ocr.expert_shared_count"]; !ok {
+ if inferred := deepseekOCRSharedExpertCount(tensors); inferred != 0 {
+ modelKV["deepseek2-ocr.expert_shared_count"] = inferred
+ }
+ }
+
+ return &Result{
+ ModelKV: modelKV,
+ ModelTensors: modelTensors,
+ ProjectorKV: deepseekOCRProjectorKV(src),
+ ProjectorTensors: projectorTensors,
+ }, nil
+}
+
+func deepseekOCRVisionTensor(name string) bool {
+ return strings.HasPrefix(name, "v.") || strings.HasPrefix(name, "mm.") || strings.HasPrefix(name, "s.")
+}
+
+func deepseekOCRModelKV(src *SourceModel) outKV {
+ modelKV := outKV{}
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+
+ key := keyValue.Key
+ switch {
+ case key == "general.architecture":
+ modelKV[key] = "deepseek2-ocr"
+ case strings.HasPrefix(key, "deepseekocr.vision."), strings.HasPrefix(key, "deepseek2-ocr.vision."):
+ continue
+ case strings.HasPrefix(key, "deepseekocr."):
+ modelKV[strings.Replace(key, "deepseekocr.", "deepseek2-ocr.", 1)] = normalizeGGUFValue(keyValue.Any())
+ case strings.HasPrefix(key, "deepseek2-ocr."):
+ modelKV[key] = normalizeGGUFValue(keyValue.Any())
+ case deepseekOCRTextKVKey(key):
+ modelKV["deepseek2-ocr."+key] = normalizeGGUFValue(keyValue.Any())
+ case strings.HasPrefix(key, "general."), strings.HasPrefix(key, "tokenizer."):
+ modelKV[key] = normalizeGGUFValue(keyValue.Any())
+ }
+ }
+ if _, ok := modelKV["deepseek2-ocr.attention.layer_norm_rms_epsilon"]; !ok {
+ modelKV["deepseek2-ocr.attention.layer_norm_rms_epsilon"] = float32(1e-6)
+ }
+ return modelKV
+}
+
+func deepseekOCRExpertFeedForwardLength(tensors []*sourceTensor) uint32 {
+ for _, tensor := range tensors {
+ if !strings.Contains(tensor.name, "ffn_down_exps.weight") || len(tensor.shape) == 0 {
+ continue
+ }
+ return uint32(tensor.shape[0])
+ }
+ for _, tensor := range tensors {
+ if !(strings.Contains(tensor.name, "ffn_gate_exps.weight") || strings.Contains(tensor.name, "ffn_up_exps.weight")) || len(tensor.shape) < 2 {
+ continue
+ }
+ return uint32(tensor.shape[1])
+ }
+ return 0
+}
+
+func deepseekOCRSharedExpertCount(tensors []*sourceTensor) uint32 {
+ expertFF := deepseekOCRExpertFeedForwardLength(tensors)
+ if expertFF == 0 {
+ return 0
+ }
+ for _, tensor := range tensors {
+ if !(strings.Contains(tensor.name, "ffn_gate_shexp.weight") || strings.Contains(tensor.name, "ffn_up_shexp.weight") || strings.Contains(tensor.name, "ffn_down_shexp.weight")) || len(tensor.shape) < 2 {
+ continue
+ }
+ sharedWidth := tensor.shape[0]
+ if tensor.shape[1] > sharedWidth {
+ sharedWidth = tensor.shape[1]
+ }
+ if sharedWidth%uint64(expertFF) == 0 {
+ return uint32(sharedWidth / uint64(expertFF))
+ }
+ }
+ return 0
+}
+
+func deepseekOCRTextKVKey(key string) bool {
+ switch key {
+ case "block_count",
+ "context_length",
+ "embedding_length",
+ "feed_forward_length",
+ "attention.head_count",
+ "attention.head_count_kv",
+ "attention.layer_norm_rms_epsilon",
+ "expert_count",
+ "expert_feed_forward_length",
+ "expert_used_count",
+ "leading_dense_block_count",
+ "expert_shared_count",
+ "expert_group_count",
+ "expert_group_used_count",
+ "rope.dimension_count",
+ "vocab_size":
+ return true
+ default:
+ return false
+ }
+}
+
+func deepseekOCRProjectorKV(src *SourceModel) outKV {
+ return outKV{
+ "general.architecture": "clip",
+ "clip.projector_type": "deepseekocr",
+ "clip.has_vision_encoder": true,
+ "clip.use_gelu": true,
+ "clip.vision.block_count": uint32(src.GGUF.KeyValue("vision.block_count").Uint()),
+ "clip.vision.embedding_length": uint32(src.GGUF.KeyValue("vision.embedding_length").Uint()),
+ "clip.vision.feed_forward_length": uint32(64),
+ "clip.vision.attention.head_count": deepseekOCRUint(src, "vision.attention.head_count", "vision.head_count"),
+ "clip.vision.attention.layer_norm_epsilon": float32(1e-6),
+ "clip.vision.image_size": uint32(src.GGUF.KeyValue("vision.image_size").Uint()),
+ "clip.vision.image_mean": []float32{0.5, 0.5, 0.5},
+ "clip.vision.image_std": []float32{0.5, 0.5, 0.5},
+ "clip.vision.patch_size": uint32(src.GGUF.KeyValue("vision.patch_size").Uint()),
+ "clip.vision.projection_dim": deepseekOCRUint(src, "vision.projection_dim", "embedding_length"),
+ "clip.vision.projector.scale_factor": uint32(1),
+ "clip.vision.window_size": uint32(14),
+ "clip.vision.sam.block_count": deepseekOCRUint(src, "vision.sam.block_count", "sam.block_count"),
+ "clip.vision.sam.embedding_length": deepseekOCRUint(src, "vision.sam.embedding_length", "sam.embedding_length"),
+ "clip.vision.sam.head_count": deepseekOCRUint(src, "vision.sam.head_count", "sam.head_count"),
+ }
+}
+
+func deepseekOCRUint(src *SourceModel, keys ...string) uint32 {
+ for _, key := range keys {
+ if value := src.GGUF.KeyValue(key); value.Valid() {
+ return uint32(value.Uint())
+ }
+ }
+ return 0
+}
+
+func deepseekOCRProjectorTensorName(name string) string {
+ replacer := strings.NewReplacer(
+ "self_attn.out_proj", "attn_out",
+ "self_attn.qkv_proj", "attn_qkv",
+ "layer_norm1", "ln1",
+ "layer_norm2", "ln2",
+ "mlp.fc1", "ffn_up",
+ "mlp.fc2", "ffn_down",
+ "pre_layrnorm", "pre_ln",
+ "s.blk.", "v.sam.blk.",
+ "s.patch_embd.", "v.sam.patch_embd.",
+ "s.position_embd", "v.sam.pos_embd.weight",
+ "s.neck.", "v.sam.neck.",
+ "s.net_", "v.sam.net_",
+ "attn.proj.", "attn.out.",
+ "attn.rel_pos_h", "attn.pos_h.weight",
+ "attn.rel_pos_w", "attn.pos_w.weight",
+ ".norm1.", ".pre_ln.",
+ ".norm2.", ".post_ln.",
+ "mm.layers.", "mm.model.fc.",
+ "mm.image_newline", "v.image_newline",
+ "mm.view_seperator", "v.view_seperator", //nolint:misspell // published DeepSeek OCR tensor spelling
+ "mm.view_separator", "v.view_separator",
+ )
+ return replacer.Replace(name)
+}
diff --git a/compatmigrate/disk_unix.go b/compatmigrate/disk_unix.go
new file mode 100644
index 000000000..592f46cdb
--- /dev/null
+++ b/compatmigrate/disk_unix.go
@@ -0,0 +1,14 @@
+//go:build !windows
+
+package compatmigrate
+
+import "golang.org/x/sys/unix"
+
+func availableSpace(path string) (uint64, error) {
+ var st unix.Statfs_t
+ if err := unix.Statfs(path, &st); err != nil {
+ return 0, err
+ }
+
+ return st.Bavail * uint64(st.Bsize), nil
+}
diff --git a/compatmigrate/disk_windows.go b/compatmigrate/disk_windows.go
new file mode 100644
index 000000000..3a5f806c2
--- /dev/null
+++ b/compatmigrate/disk_windows.go
@@ -0,0 +1,24 @@
+//go:build windows
+
+package compatmigrate
+
+import (
+ "path/filepath"
+
+ "golang.org/x/sys/windows"
+)
+
+func availableSpace(path string) (uint64, error) {
+ root := filepath.VolumeName(path) + `\`
+ p, err := windows.UTF16PtrFromString(root)
+ if err != nil {
+ return 0, err
+ }
+
+ var available uint64
+ if err := windows.GetDiskFreeSpaceEx(p, &available, nil, nil); err != nil {
+ return 0, err
+ }
+
+ return available, nil
+}
diff --git a/compatmigrate/embeddinggemma.go b/compatmigrate/embeddinggemma.go
new file mode 100644
index 000000000..48a9a0980
--- /dev/null
+++ b/compatmigrate/embeddinggemma.go
@@ -0,0 +1,69 @@
+package compatmigrate
+
+import (
+ "strings"
+)
+
+type embeddingGemmaMigrator struct{}
+
+// Mirrors detect_ollama_embeddinggemma in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (embeddingGemmaMigrator) NeedsMigration(src *SourceModel) bool {
+ return src.GGUF.KeyValue("general.architecture").String() == "gemma3" &&
+ sourceTensorExists(src, "dense.0.weight")
+}
+
+func (embeddingGemmaMigrator) Migrate(src *SourceModel) (*Result, error) {
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ var modelTensors []*outTensor
+ denseShapes := map[string][]uint64{}
+ for _, tensor := range tensors {
+ name := tensor.name
+ switch {
+ case strings.HasPrefix(name, "dense.0."):
+ name = strings.Replace(name, "dense.0.", "dense_2.", 1)
+ denseShapes["dense_2"] = tensor.shape
+ case strings.HasPrefix(name, "dense.1."):
+ name = strings.Replace(name, "dense.1.", "dense_3.", 1)
+ denseShapes["dense_3"] = tensor.shape
+ case name == "norm.weight":
+ name = "output_norm.weight"
+ }
+ modelTensors = append(modelTensors, copyTensor(name, tensor))
+ }
+
+ modelKV := outKV{}
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+
+ key := keyValue.Key
+ switch {
+ case key == "general.architecture":
+ modelKV[key] = "gemma-embedding"
+ case key == "gemma3.attention.causal", key == "gemma3.attention.sliding_window_pattern":
+ continue
+ case strings.HasPrefix(key, "gemma3."):
+ modelKV[strings.Replace(key, "gemma3.", "gemma-embedding.", 1)] = normalizeGGUFValue(keyValue.Any())
+ case strings.HasPrefix(key, "general."), strings.HasPrefix(key, "tokenizer."):
+ modelKV[key] = normalizeGGUFValue(keyValue.Any())
+ }
+ }
+
+ modelKV["gemma-embedding.rope.freq_base_swa"] = float32(10000)
+ for _, dense := range []string{"dense_2", "dense_3"} {
+ if shape := denseShapes[dense]; len(shape) >= 2 {
+ modelKV["gemma-embedding."+dense+"_feat_in"] = uint32(shape[0])
+ modelKV["gemma-embedding."+dense+"_feat_out"] = uint32(shape[1])
+ }
+ }
+
+ return &Result{
+ ModelKV: modelKV,
+ ModelTensors: modelTensors,
+ }, nil
+}
diff --git a/compatmigrate/gemma3.go b/compatmigrate/gemma3.go
new file mode 100644
index 000000000..491f2a001
--- /dev/null
+++ b/compatmigrate/gemma3.go
@@ -0,0 +1,212 @@
+package compatmigrate
+
+import (
+ "strings"
+)
+
+const gemma3ChatTemplate = `{{ bos_token }}{% if messages[0]['role'] == 'system' %}{{ raise_exception('System role not supported') }}{% endif %}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if (message['role'] == 'assistant') %}{% set role = 'model' %}{% else %}{% set role = message['role'] %}{% endif %}{{ '<start_of_turn>' + role + '\n' + message['content'] | trim + '<end_of_turn>\n' }}{% endfor %}{% if add_generation_prompt %}{{'<start_of_turn>model\n'}}{% endif %}`
+
+type gemma3Migrator struct{}
+
+// Mirrors detect_ollama_gemma3 in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (gemma3Migrator) NeedsMigration(src *SourceModel) bool {
+ if src.GGUF.KeyValue("general.architecture").String() != "gemma3" {
+ return false
+ }
+ return sourceTensorHasPrefix(src, "v.") ||
+ sourceTensorHasPrefix(src, "mm.") ||
+ src.GGUF.KeyValue("rope.global.freq_base").Valid() ||
+ src.GGUF.KeyValue("rope.local.freq_base").Valid() ||
+ !src.GGUF.KeyValue("attention.layer_norm_rms_epsilon").Valid()
+}
+
+func (gemma3Migrator) Migrate(src *SourceModel) (*Result, error) {
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ vocabSize := gemma3VocabSize(tensors)
+ var modelTensors []*outTensor
+ var projectorTensors []*outTensor
+ for _, tensor := range tensors {
+ if isGemma3ProjectorTensor(tensor.name) {
+ projectorTensors = append(projectorTensors, copyTensor(gemma3ProjectorTensorName(tensor.name), tensor))
+ continue
+ }
+
+ modelTensors = append(modelTensors, copyTensor(tensor.name, tensor))
+ }
+
+ modelKV := gemma3ModelKV(src, vocabSize)
+
+ result := &Result{
+ ModelKV: modelKV,
+ ModelTensors: modelTensors,
+ // Gemma 3 uses the standard template/image-tag path; there is no
+ // built-in gemma3 renderer or parser to select.
+ ClearRenderer: true,
+ ClearParser: true,
+ }
+
+ if len(projectorTensors) > 0 {
+ result.ProjectorKV = gemma3ProjectorKV(src)
+ result.ProjectorTensors = projectorTensors
+ }
+
+ return result, nil
+}
+
+func gemma3ModelKV(src *SourceModel, vocabSize int) outKV {
+ modelKV := outKV{}
+ var globalRope any
+ var localRope any
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+
+ key := keyValue.Key
+ value := normalizeGGUFValue(keyValue.Any())
+ switch {
+ case key == "gemma3.rope.global.freq_base":
+ globalRope = value
+ modelKV["gemma3.rope.freq_base"] = value
+ case key == "gemma3.rope.local.freq_base":
+ localRope = value
+ modelKV["gemma3.rope.freq_base_swa"] = value
+ case strings.HasPrefix(key, "gemma3.vision."), strings.HasPrefix(key, "gemma3.mm."):
+ continue
+ case key == "tokenizer.ggml.tokens", key == "tokenizer.ggml.scores", key == "tokenizer.ggml.token_type":
+ modelKV[key] = truncateGemma3TokenizerValue(value, vocabSize)
+ case strings.HasPrefix(key, "general."), strings.HasPrefix(key, "tokenizer."), strings.HasPrefix(key, "gemma3."):
+ modelKV[key] = value
+ }
+ }
+
+ if _, ok := modelKV["general.architecture"]; !ok {
+ modelKV["general.architecture"] = "gemma3"
+ }
+ // Fallback defaults below mirror the upstream google/gemma-3 configuration for legacy files that omitted them.
+ if _, ok := modelKV["gemma3.attention.layer_norm_rms_epsilon"]; !ok {
+ modelKV["gemma3.attention.layer_norm_rms_epsilon"] = float32(1e-6)
+ }
+ if _, ok := modelKV["gemma3.rope.freq_base"]; !ok {
+ if globalRope != nil {
+ modelKV["gemma3.rope.freq_base"] = globalRope
+ } else {
+ modelKV["gemma3.rope.freq_base"] = float32(1000000)
+ }
+ }
+ if _, ok := modelKV["gemma3.rope.freq_base_swa"]; !ok {
+ if localRope != nil {
+ modelKV["gemma3.rope.freq_base_swa"] = localRope
+ } else {
+ modelKV["gemma3.rope.freq_base_swa"] = float32(10000)
+ }
+ }
+ if _, ok := modelKV["tokenizer.chat_template"]; !ok {
+ modelKV["tokenizer.chat_template"] = gemma3ChatTemplate
+ }
+ if src.GGUF.KeyValue("context_length").Uint() >= 131072 {
+ if _, ok := modelKV["gemma3.rope.scaling.type"]; !ok {
+ modelKV["gemma3.rope.scaling.type"] = "linear"
+ }
+ if _, ok := modelKV["gemma3.rope.scaling.factor"]; !ok {
+ modelKV["gemma3.rope.scaling.factor"] = float32(8)
+ }
+ }
+ delete(modelKV, "tokenizer.ggml.add_padding_token")
+ delete(modelKV, "tokenizer.ggml.add_unknown_token")
+
+ return modelKV
+}
+
+func gemma3ProjectorKV(src *SourceModel) outKV {
+ // image_size 896, patch_size 14, and 0.5 mean/std are the SigLIP vision defaults for Gemma 3.
+ imageSize := uint32(src.GGUF.KeyValue("vision.image_size").Uint())
+ if imageSize == 0 {
+ imageSize = 896
+ }
+
+ patchSize := uint32(src.GGUF.KeyValue("vision.patch_size").Uint())
+ if patchSize == 0 {
+ patchSize = 14
+ }
+
+ eps := float32(src.GGUF.KeyValue("vision.attention.layer_norm_epsilon").Float())
+ if eps == 0 {
+ eps = 1e-6
+ }
+
+ return outKV{
+ "general.architecture": "clip",
+ "clip.projector_type": "gemma3",
+ "clip.has_vision_encoder": true,
+ "clip.has_text_encoder": false,
+ "clip.has_llava_projector": false,
+ "clip.use_gelu": true,
+ "clip.vision.block_count": uint32(src.GGUF.KeyValue("vision.block_count").Uint()),
+ "clip.vision.embedding_length": uint32(src.GGUF.KeyValue("vision.embedding_length").Uint()),
+ "clip.vision.feed_forward_length": uint32(src.GGUF.KeyValue("vision.feed_forward_length").Uint()),
+ "clip.vision.image_size": imageSize,
+ "clip.vision.patch_size": patchSize,
+ "clip.vision.attention.head_count": uint32(src.GGUF.KeyValue("vision.attention.head_count").Uint()),
+ "clip.vision.attention.layer_norm_epsilon": eps,
+ "clip.vision.image_mean": []float32{0.5, 0.5, 0.5},
+ "clip.vision.image_std": []float32{0.5, 0.5, 0.5},
+ "clip.vision.projection_dim": uint32(src.GGUF.KeyValue("embedding_length").Uint()),
+ }
+}
+
+// gemma3VocabSize infers the vocab size from the trailing dim of token_embd.weight
+// because legacy files' tokenizer arrays can be longer than the actual vocab.
+func gemma3VocabSize(tensors []*sourceTensor) int {
+ for _, tensor := range tensors {
+ if tensor.name == "token_embd.weight" && len(tensor.shape) > 0 {
+ return int(tensor.shape[len(tensor.shape)-1])
+ }
+ }
+ return 0
+}
+
+func truncateGemma3TokenizerValue(v any, vocabSize int) any {
+ if vocabSize <= 0 {
+ return v
+ }
+
+ switch values := v.(type) {
+ case []string:
+ if len(values) > vocabSize {
+ return append([]string(nil), values[:vocabSize]...)
+ }
+ case []float32:
+ if len(values) > vocabSize {
+ return append([]float32(nil), values[:vocabSize]...)
+ }
+ case []int32:
+ if len(values) > vocabSize {
+ return append([]int32(nil), values[:vocabSize]...)
+ }
+ }
+ return v
+}
+
+func isGemma3ProjectorTensor(name string) bool {
+ return strings.HasPrefix(name, "v.") || strings.HasPrefix(name, "mm.")
+}
+
+func gemma3ProjectorTensorName(name string) string {
+ name = strings.Replace(name, "mm.mm_input_projection", "mm.input_projection", 1)
+ name = strings.Replace(name, "mm.mm_soft_emb_norm", "mm.soft_emb_norm", 1)
+ name = strings.Replace(name, "v.patch_embedding", "v.patch_embd", 1)
+ name = strings.Replace(name, "v.position_embedding", "v.position_embd", 1)
+ name = strings.Replace(name, "v.post_layernorm", "v.post_ln", 1)
+ name = strings.Replace(name, "layer_norm1", "ln1", 1)
+ name = strings.Replace(name, "layer_norm2", "ln2", 1)
+ name = strings.Replace(name, "attn_output", "attn_out", 1)
+ // The fc1->ffn_down / fc2->ffn_up mapping looks reversed but intentionally mirrors llama.cpp's clip naming for the gemma3 projector.
+ name = strings.Replace(name, "mlp.fc1", "ffn_down", 1)
+ name = strings.Replace(name, "mlp.fc2", "ffn_up", 1)
+ return name
+}
diff --git a/compatmigrate/gemma3n.go b/compatmigrate/gemma3n.go
new file mode 100644
index 000000000..d5b8b39e3
--- /dev/null
+++ b/compatmigrate/gemma3n.go
@@ -0,0 +1,193 @@
+package compatmigrate
+
+import (
+ "slices"
+ "strings"
+)
+
+const gemma3nVocabSize = 262144
+
+type gemma3nMigrator struct{}
+
+// Mirrors detect_ollama_gemma3n in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (gemma3nMigrator) NeedsMigration(src *SourceModel) bool {
+ if src.GGUF.KeyValue("general.architecture").String() != "gemma3n" {
+ return false
+ }
+ token, tokenOK := sourceTensorShape(src, "token_embd.weight")
+ perLayer, perLayerOK := sourceTensorShape(src, "per_layer_token_embd.weight")
+ return tokenOK && perLayerOK && len(token) >= 2 && len(perLayer) >= 2 && token[1] != perLayer[1]
+}
+
+func (gemma3nMigrator) Migrate(src *SourceModel) (*Result, error) {
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ perLayerVocab := uint64(gemma3nVocabSize)
+ perLayerInput := src.GGUF.KeyValue("embedding_length_per_layer_input").Uint()
+ embedLength := src.GGUF.KeyValue("embedding_length").Uint()
+ for _, tensor := range tensors {
+ if tensor.name == "per_layer_token_embd.weight" && len(tensor.shape) >= 2 {
+ perLayerVocab = inferEmbeddingVocabDim(tensor.shape, perLayerInput, embedLength, perLayerVocab)
+ break
+ }
+ }
+
+ var modelTensors []*outTensor
+ for _, tensor := range tensors {
+ if gemma3nDroppedTensor(tensor.name) {
+ continue
+ }
+
+ if tensor.name == "token_embd.weight" && perLayerVocab > 0 && len(tensor.shape) >= 2 {
+ shape := slices.Clone(tensor.shape)
+ switch inferEmbeddingVocabAxis(tensor.shape, perLayerVocab, embedLength, perLayerInput) {
+ case 0:
+ if shape[0] > perLayerVocab {
+ shape[0] = perLayerVocab
+ modelTensors = append(modelTensors, copyTensorPrefix(tensor.name, tensor, shape))
+ continue
+ }
+ case 1:
+ if shape[1] > perLayerVocab {
+ shape[1] = perLayerVocab
+ modelTensors = append(modelTensors, copyTensorPrefix(tensor.name, tensor, shape))
+ continue
+ }
+ }
+ }
+
+ modelTensors = append(modelTensors, copyTensor(tensor.name, tensor))
+ }
+
+ modelKV := outKV{}
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+
+ value := normalizeGGUFValue(keyValue.Any())
+ switch keyValue.Key {
+ case "tokenizer.ggml.tokens", "tokenizer.ggml.scores", "tokenizer.ggml.token_type":
+ value = truncateGemma3nTokenizerValue(value, perLayerVocab)
+ }
+ modelKV[keyValue.Key] = value
+ }
+ modelKV["tokenizer.ggml.model"] = "llama"
+ normalizeGemma3nTokenTypes(modelKV)
+ ensureGemma3nEOS(modelKV)
+
+ return &Result{
+ ModelKV: modelKV,
+ ModelTensors: modelTensors,
+ }, nil
+}
+
+func gemma3nDroppedTensor(name string) bool {
+ return strings.Contains(name, "audio_tower") ||
+ strings.Contains(name, "embed_audio") ||
+ strings.Contains(name, "vision_tower") ||
+ strings.Contains(name, "embed_vision")
+}
+
+func truncateGemma3nTokenizerValue(v any, targetVocab uint64) any {
+ if targetVocab == 0 {
+ return v
+ }
+
+ switch values := v.(type) {
+ case []string:
+ if uint64(len(values)) > targetVocab {
+ return slices.Clone(values[:targetVocab])
+ }
+ case []float32:
+ if uint64(len(values)) > targetVocab {
+ return slices.Clone(values[:targetVocab])
+ }
+ case []int32:
+ if uint64(len(values)) > targetVocab {
+ return slices.Clone(values[:targetVocab])
+ }
+ }
+ return v
+}
+
+func normalizeGemma3nTokenTypes(kv outKV) {
+ tokens, tokensOK := kv["tokenizer.ggml.tokens"].([]string)
+ types, typesOK := kv["tokenizer.ggml.token_type"].([]int32)
+ if !tokensOK || !typesOK {
+ return
+ }
+
+ n := min(len(tokens), len(types))
+ normalized := slices.Clone(types)
+ for i := range n {
+ switch token := tokens[i]; {
+ case len(token) == 6 && strings.HasPrefix(token, "<0x") && strings.HasSuffix(token, ">"):
+ normalized[i] = 6
+ case strings.HasPrefix(token, "<unused"):
+ normalized[i] = 1
+ }
+ }
+ kv["tokenizer.ggml.token_type"] = normalized
+}
+
+func inferEmbeddingVocabDim(shape []uint64, innerDim uint64, outerDim uint64, fallback uint64) uint64 {
+ switch inferEmbeddingVocabAxis(shape, fallback, outerDim, innerDim) {
+ case 0:
+ return shape[0]
+ case 1:
+ return shape[1]
+ default:
+ return fallback
+ }
+}
+
+func inferEmbeddingVocabAxis(shape []uint64, vocabHint uint64, knownDims ...uint64) int {
+ if len(shape) < 2 {
+ return -1
+ }
+
+ if shape[0] == vocabHint && shape[1] != vocabHint {
+ return 0
+ }
+ if shape[1] == vocabHint && shape[0] != vocabHint {
+ return 1
+ }
+
+ for _, known := range knownDims {
+ if known == 0 {
+ continue
+ }
+ if shape[0] == known && shape[1] != known {
+ return 1
+ }
+ if shape[1] == known && shape[0] != known {
+ return 0
+ }
+ }
+
+ if shape[0] >= shape[1] {
+ return 0
+ }
+ return 1
+}
+
+func ensureGemma3nEOS(kv outKV) {
+ const turnToken = int32(106)
+
+ switch ids := kv["tokenizer.ggml.eos_token_ids"].(type) {
+ case []int32:
+ if !slices.Contains(ids, turnToken) {
+ kv["tokenizer.ggml.eos_token_ids"] = append(slices.Clone(ids), turnToken)
+ }
+ case []uint32:
+ if !slices.Contains(ids, uint32(turnToken)) {
+ kv["tokenizer.ggml.eos_token_ids"] = append(slices.Clone(ids), uint32(turnToken))
+ }
+ default:
+ kv["tokenizer.ggml.eos_token_ids"] = []int32{1, turnToken}
+ }
+}
diff --git a/compatmigrate/gemma4.go b/compatmigrate/gemma4.go
new file mode 100644
index 000000000..3ffb46ab0
--- /dev/null
+++ b/compatmigrate/gemma4.go
@@ -0,0 +1,226 @@
+package compatmigrate
+
+import (
+ "strconv"
+ "strings"
+)
+
+type gemma4Migrator struct{}
+
+// Mirrors detect_ollama_gemma4 in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (gemma4Migrator) NeedsMigration(src *SourceModel) bool {
+ if src.GGUF.KeyValue("general.architecture").String() != "gemma4" {
+ return false
+ }
+ return sourceTensorHasPrefix(src, "a.") ||
+ sourceTensorHasPrefix(src, "v.") ||
+ sourceTensorHasPrefix(src, "mm.") ||
+ sourceTensorHasPrefix(src, "model.vision_tower.") ||
+ src.GGUF.KeyValue("tokenizer.ggml.model").String() == "llama"
+}
+
+func (gemma4Migrator) Migrate(src *SourceModel) (*Result, error) {
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+ legacyAudioNames := hasLegacyGemma4AudioNames(tensors)
+
+ var modelTensors []*outTensor
+ var projectorTensors []*outTensor
+ pendingGate := map[string]*sourceTensor{}
+ pendingUp := map[string]*sourceTensor{}
+ for _, tensor := range tensors {
+ switch {
+ case isGemma4ProjectorTensor(tensor.name):
+ projectorTensors = append(projectorTensors, copyTensor(gemma4ProjectorTensorName(tensor.name, legacyAudioNames), tensor))
+ case gemma4CanFuseExpert(tensors, tensor.name):
+ gateUpName := gemma4GateUpExpertName(tensor.name)
+ if strings.Contains(tensor.name, ".ffn_gate_exps.") {
+ if up := pendingUp[gateUpName]; up != nil {
+ merged, err := concatSourceTensorsDim(1, gateUpName, tensor, up)
+ if err != nil {
+ return nil, err
+ }
+ modelTensors = append(modelTensors, merged)
+ delete(pendingUp, gateUpName)
+ continue
+ }
+ pendingGate[gateUpName] = tensor
+ continue
+ }
+ if gate := pendingGate[gateUpName]; gate != nil {
+ merged, err := concatSourceTensorsDim(1, gateUpName, gate, tensor)
+ if err != nil {
+ return nil, err
+ }
+ modelTensors = append(modelTensors, merged)
+ delete(pendingGate, gateUpName)
+ continue
+ }
+ pendingUp[gateUpName] = tensor
+ default:
+ modelTensors = append(modelTensors, copyTensor(gemma4ModelTensorName(tensor.name), tensor))
+ }
+ }
+ for _, tensor := range pendingGate {
+ modelTensors = append(modelTensors, copyTensor(gemma4ModelTensorName(tensor.name), tensor))
+ }
+ for _, tensor := range pendingUp {
+ modelTensors = append(modelTensors, copyTensor(gemma4ModelTensorName(tensor.name), tensor))
+ }
+
+ modelKV := outKV{}
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+
+ key := keyValue.Key
+ if key == "general.architecture" || strings.HasPrefix(key, "general.") || strings.HasPrefix(key, "tokenizer.") {
+ modelKV[key] = normalizeGGUFValue(keyValue.Any())
+ continue
+ }
+
+ if strings.HasPrefix(key, "gemma4.audio.") || strings.HasPrefix(key, "gemma4.vision.") {
+ continue
+ }
+ if strings.HasPrefix(key, "gemma4.") {
+ modelKV[key] = normalizeGGUFValue(keyValue.Any())
+ }
+ }
+ if tokenizerModel, _ := modelKV["tokenizer.ggml.model"].(string); tokenizerModel == "llama" {
+ modelKV["tokenizer.ggml.model"] = "gemma4"
+ }
+
+ projectorKV := outKV{
+ "general.architecture": "clip",
+ "clip.has_vision_encoder": true,
+ "clip.projector_type": "gemma4v",
+ "clip.vision.projector_type": "gemma4v",
+ "clip.vision.block_count": uint32(src.GGUF.KeyValue("vision.block_count").Uint()),
+ "clip.vision.embedding_length": uint32(src.GGUF.KeyValue("vision.embedding_length").Uint()),
+ "clip.vision.feed_forward_length": uint32(src.GGUF.KeyValue("vision.feed_forward_length").Uint()),
+ "clip.vision.attention.head_count": uint32(src.GGUF.KeyValue("vision.attention.head_count").Uint()),
+ "clip.vision.attention.layer_norm_epsilon": float32(src.GGUF.KeyValue("vision.attention.layer_norm_epsilon").Float()),
+ "clip.vision.patch_size": uint32(src.GGUF.KeyValue("vision.patch_size").Uint()),
+ "clip.vision.image_size": uint32(224),
+ "clip.vision.projection_dim": uint32(src.GGUF.KeyValue("embedding_length").Uint()),
+ "clip.vision.image_mean": []float32{0, 0, 0},
+ "clip.vision.image_std": []float32{1, 1, 1},
+ }
+ if scale := src.GGUF.KeyValue("vision.projector.scale_factor"); scale.Valid() {
+ projectorKV["clip.vision.projector.scale_factor"] = uint32(scale.Uint())
+ }
+ if blockCount := src.GGUF.KeyValue("audio.block_count"); blockCount.Valid() && blockCount.Uint() > 0 {
+ audioFeedForwardLength := uint32(src.GGUF.KeyValue("audio.feed_forward_length").Uint())
+ audioEmbeddingLength := uint32(src.GGUF.KeyValue("audio.embedding_length").Uint())
+ if audioFeedForwardLength == 0 {
+ audioFeedForwardLength = audioEmbeddingLength * 4
+ }
+ // llama.cpp treats clip.projector_type as authoritative when present.
+ // Mixed Gemma4 projectors must use modality-specific projector keys so
+ // audio selects gemma4a instead of falling through to gemma4v.
+ delete(projectorKV, "clip.projector_type")
+ projectorKV["clip.has_audio_encoder"] = true
+ projectorKV["clip.audio.projector_type"] = "gemma4a"
+ projectorKV["clip.audio.num_mel_bins"] = uint32(128)
+ projectorKV["clip.audio.projection_dim"] = uint32(src.GGUF.KeyValue("embedding_length").Uint())
+ projectorKV["clip.audio.embedding_length"] = audioEmbeddingLength
+ projectorKV["clip.audio.feed_forward_length"] = audioFeedForwardLength
+ projectorKV["clip.audio.block_count"] = uint32(blockCount.Uint())
+ projectorKV["clip.audio.attention.head_count"] = uint32(src.GGUF.KeyValue("audio.attention.head_count").Uint())
+ projectorKV["clip.audio.attention.layer_norm_epsilon"] = float32(1e-5)
+ }
+
+ return &Result{
+ ModelKV: modelKV,
+ ModelTensors: modelTensors,
+ ProjectorKV: projectorKV,
+ ProjectorTensors: projectorTensors,
+ Renderer: "gemma4",
+ Parser: "gemma4",
+ }, nil
+}
+
+func isGemma4AudioTensor(name string) bool {
+ return strings.HasPrefix(name, "a.") || strings.HasPrefix(name, "mm.a.")
+}
+
+func isGemma4ProjectorTensor(name string) bool {
+ return strings.HasPrefix(name, "v.") || strings.HasPrefix(name, "mm.") || isGemma4AudioTensor(name)
+}
+
+func gemma4ModelTensorName(name string) string {
+ return strings.Replace(name, ".ffn_gate_inp.per_expert_scale", ".ffn_down_exps.scale", 1)
+}
+
+func gemma4CanFuseExpert(tensors []*sourceTensor, name string) bool {
+ if !strings.Contains(name, ".ffn_gate_exps.weight") && !strings.Contains(name, ".ffn_up_exps.weight") {
+ return false
+ }
+ block, ok := tensorBlock(name)
+ if !ok || gemma4ExpertSidecarExists(tensors, block) {
+ return false
+ }
+ return !sourceTensorNameExists(tensors, gemma4GateUpExpertName(name))
+}
+
+func gemma4ExpertSidecarExists(tensors []*sourceTensor, block int) bool {
+ prefix := "blk." + strconv.Itoa(block) + "."
+ for _, name := range []string{
+ prefix + "ffn_gate_exps.scale",
+ prefix + "ffn_gate_exps.input_scale",
+ prefix + "ffn_up_exps.scale",
+ prefix + "ffn_up_exps.input_scale",
+ } {
+ if sourceTensorNameExists(tensors, name) {
+ return true
+ }
+ }
+ return false
+}
+
+func sourceTensorNameExists(tensors []*sourceTensor, name string) bool {
+ for _, tensor := range tensors {
+ if tensor.name == name {
+ return true
+ }
+ }
+ return false
+}
+
+func gemma4GateUpExpertName(name string) string {
+ name = strings.Replace(name, ".ffn_gate_exps.", ".ffn_gate_up_exps.", 1)
+ return strings.Replace(name, ".ffn_up_exps.", ".ffn_gate_up_exps.", 1)
+}
+
+func hasLegacyGemma4AudioNames(tensors []*sourceTensor) bool {
+ for _, tensor := range tensors {
+ name := tensor.name
+ if strings.Contains(name, ".linear_pos.") ||
+ strings.Contains(name, ".layer_pre_norm.") ||
+ strings.HasPrefix(name, "mm.a.fc.") {
+ return true
+ }
+ }
+ return false
+}
+
+func gemma4ProjectorTensorName(name string, legacyAudioNames bool) string {
+ if !legacyAudioNames || !isGemma4AudioTensor(name) {
+ return name
+ }
+
+ name = strings.Replace(name, ".linear_pos.", ".attn_k_rel.", 1)
+ name = strings.Replace(name, ".ln1.", ".attn_pre_norm.", 1)
+ name = strings.Replace(name, ".ln2.", ".attn_post_norm.", 1)
+ name = strings.Replace(name, ".layer_pre_norm.", ".ln2.", 1)
+ if strings.HasPrefix(name, "mm.a.fc.") {
+ name = "a.pre_encode.out." + strings.TrimPrefix(name, "mm.a.fc.")
+ } else if strings.HasPrefix(name, "a.pre_encode.out.") {
+ name = "a.input_projection." + strings.TrimPrefix(name, "a.pre_encode.out.")
+ }
+
+ return name
+}
diff --git a/compatmigrate/glm47_flash.go b/compatmigrate/glm47_flash.go
new file mode 100644
index 000000000..36cccc698
--- /dev/null
+++ b/compatmigrate/glm47_flash.go
@@ -0,0 +1,269 @@
+package compatmigrate
+
+import (
+ "fmt"
+ "strings"
+)
+
+type glm47FlashMigrator struct{}
+
+// Mirrors detect_ollama_glm4moelite in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (glm47FlashMigrator) NeedsMigration(src *SourceModel) bool {
+ return src.GGUF.KeyValue("general.architecture").String() == "glm4moelite"
+}
+
+type glm47FlashMLA struct {
+ numHeads int
+ qkNope int
+ qkRope int
+ kvLoraRank int
+ vHeadDim int
+}
+
+func (glm47FlashMigrator) Migrate(src *SourceModel) (*Result, error) {
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ mla := glm47FlashInferMLAFromTensors(glm47FlashMLAFromSource(src), tensors)
+ modelKV := glm47FlashModelKV(src, mla)
+
+ var modelTensors []*outTensor
+ for _, tensor := range tensors {
+ if strings.HasSuffix(tensor.name, ".attn_kv_b.weight") {
+ if mla.kvLoraRank == 0 || mla.qkNope == 0 || mla.vHeadDim == 0 {
+ return nil, fmt.Errorf("glm-4.7-flash migration cannot split %s without MLA dimensions", tensor.name)
+ }
+ split, err := glm47FlashSplitKVB(tensor, mla)
+ if err != nil {
+ return nil, err
+ }
+ modelTensors = append(modelTensors, split...)
+ continue
+ }
+
+ modelTensors = append(modelTensors, copyTensor(tensor.name, tensor))
+ }
+
+ return &Result{
+ ModelKV: modelKV,
+ ModelTensors: modelTensors,
+ // The tensor format is a deepseek2-compatible GGUF, but chat/tool prompt
+ // formatting still needs the GLM-4.7 renderer/parser. Without this config
+ // chat falls back to the plain default template and the model does not
+ // naturally terminate on short integration prompts.
+ Renderer: "glm-4.7",
+ Parser: "glm-4.7",
+ }, nil
+}
+
+func glm47FlashInferMLAFromTensors(mla glm47FlashMLA, tensors []*sourceTensor) glm47FlashMLA {
+ for _, tensor := range tensors {
+ switch {
+ case strings.HasSuffix(tensor.name, ".attn_k_b.weight") && len(tensor.shape) == 3:
+ if tensor.shape[0] > 0 {
+ mla.qkNope = int(tensor.shape[0])
+ }
+ if tensor.shape[1] > 0 {
+ mla.kvLoraRank = int(tensor.shape[1])
+ }
+ if tensor.shape[2] > 0 {
+ mla.numHeads = int(tensor.shape[2])
+ }
+ case strings.HasSuffix(tensor.name, ".attn_v_b.weight") && len(tensor.shape) == 3:
+ if tensor.shape[0] > 0 {
+ mla.kvLoraRank = int(tensor.shape[0])
+ }
+ if tensor.shape[1] > 0 {
+ mla.vHeadDim = int(tensor.shape[1])
+ }
+ if tensor.shape[2] > 0 {
+ mla.numHeads = int(tensor.shape[2])
+ }
+ case strings.HasSuffix(tensor.name, ".attn_q_b.weight") && len(tensor.shape) == 2:
+ if mla.numHeads == 0 {
+ continue
+ }
+ switch {
+ case int(tensor.shape[0]) > 0 && int(tensor.shape[1])%mla.numHeads == 0:
+ if perHead := int(tensor.shape[1]) / mla.numHeads; perHead > mla.qkRope {
+ mla.qkNope = perHead - mla.qkRope
+ }
+ case int(tensor.shape[1]) > 0 && int(tensor.shape[0])%mla.numHeads == 0:
+ if perHead := int(tensor.shape[0]) / mla.numHeads; perHead > mla.qkRope {
+ mla.qkNope = perHead - mla.qkRope
+ }
+ }
+ case strings.HasSuffix(tensor.name, ".attn_kv_b.weight") && len(tensor.shape) == 2:
+ if mla.kvLoraRank == 0 || mla.vHeadDim == 0 || mla.numHeads == 0 || mla.qkNope > 0 {
+ continue
+ }
+ switch {
+ case int(tensor.shape[0]) == mla.kvLoraRank && int(tensor.shape[1])%mla.numHeads == 0:
+ if perHead := int(tensor.shape[1]) / mla.numHeads; perHead > mla.vHeadDim {
+ mla.qkNope = perHead - mla.vHeadDim
+ }
+ case int(tensor.shape[1]) == mla.kvLoraRank && int(tensor.shape[0])%mla.numHeads == 0:
+ if perHead := int(tensor.shape[0]) / mla.numHeads; perHead > mla.vHeadDim {
+ mla.qkNope = perHead - mla.vHeadDim
+ }
+ }
+ }
+ }
+
+ return mla
+}
+
+func glm47FlashModelKV(src *SourceModel, mla glm47FlashMLA) outKV {
+ modelKV := outKV{}
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+
+ key := keyValue.Key
+ switch {
+ case key == "general.architecture":
+ modelKV[key] = "deepseek2"
+ case strings.HasPrefix(key, "glm4moelite."):
+ modelKV[strings.Replace(key, "glm4moelite.", "deepseek2.", 1)] = normalizeGGUFValue(keyValue.Any())
+ case strings.HasPrefix(key, "general."), strings.HasPrefix(key, "tokenizer."):
+ modelKV[key] = normalizeGGUFValue(keyValue.Any())
+ }
+ }
+
+ if mla.numHeads > 0 {
+ modelKV["deepseek2.attention.head_count"] = uint32(mla.numHeads)
+ }
+ modelKV["deepseek2.attention.head_count_kv"] = uint32(1)
+ if mla.kvLoraRank > 0 {
+ modelKV["deepseek2.attention.kv_lora_rank"] = uint32(mla.kvLoraRank)
+ modelKV["deepseek2.attention.value_length"] = uint32(mla.kvLoraRank)
+ }
+ if mla.qkRope > 0 {
+ modelKV["deepseek2.rope.dimension_count"] = uint32(mla.qkRope)
+ }
+ if mla.kvLoraRank > 0 && mla.qkRope > 0 {
+ modelKV["deepseek2.attention.key_length"] = uint32(mla.kvLoraRank + mla.qkRope)
+ }
+ if mla.qkNope > 0 && mla.qkRope > 0 {
+ modelKV["deepseek2.attention.key_length_mla"] = uint32(mla.qkNope + mla.qkRope)
+ }
+ if mla.vHeadDim > 0 {
+ modelKV["deepseek2.attention.value_length_mla"] = uint32(mla.vHeadDim)
+ }
+ modelKV["tokenizer.ggml.pre"] = "glm4"
+ glm47FlashSetExtraEOGFromEOSIDs(modelKV)
+
+ return modelKV
+}
+
+func glm47FlashSetExtraEOGFromEOSIDs(kv outKV) {
+ switch ids := kv["tokenizer.ggml.eos_token_ids"].(type) {
+ case []int32:
+ if len(ids) >= 2 && ids[1] >= 0 {
+ kv["tokenizer.ggml.eot_token_id"] = uint32(ids[1])
+ }
+ if len(ids) >= 3 && ids[2] >= 0 {
+ kv["tokenizer.ggml.eom_token_id"] = uint32(ids[2])
+ }
+ case []uint32:
+ if len(ids) >= 2 {
+ kv["tokenizer.ggml.eot_token_id"] = ids[1]
+ }
+ if len(ids) >= 3 {
+ kv["tokenizer.ggml.eom_token_id"] = ids[2]
+ }
+ }
+}
+
+func glm47FlashMLAFromSource(src *SourceModel) glm47FlashMLA {
+ mla := glm47FlashMLA{
+ numHeads: int(src.GGUF.KeyValue("attention.head_count").Uint()),
+ qkRope: int(src.GGUF.KeyValue("rope.dimension_count").Uint()),
+ kvLoraRank: int(src.GGUF.KeyValue("attention.kv_lora_rank").Uint()),
+ vHeadDim: int(src.GGUF.KeyValue("attention.value_length_mla").Uint()),
+ }
+ if mla.vHeadDim == 0 {
+ mla.vHeadDim = int(src.GGUF.KeyValue("attention.value_length").Uint())
+ }
+ if keyMLA := int(src.GGUF.KeyValue("attention.key_length_mla").Uint()); keyMLA > mla.qkRope {
+ mla.qkNope = keyMLA - mla.qkRope
+ } else if key := int(src.GGUF.KeyValue("attention.key_length").Uint()); key > mla.qkRope && key != mla.kvLoraRank+mla.qkRope {
+ mla.qkNope = key - mla.qkRope
+ }
+ return mla
+}
+
+func glm47FlashSplitKVB(t *sourceTensor, mla glm47FlashMLA) ([]*outTensor, error) {
+ if len(t.shape) != 2 {
+ return nil, fmt.Errorf("glm-4.7-flash migration expected %s to be 2D, got %v", t.name, t.shape)
+ }
+
+ kvPerHead := mla.qkNope + mla.vHeadDim
+ numHeads := mla.numHeads
+ var kvFirst bool
+ switch {
+ case int(t.shape[0]) == mla.kvLoraRank:
+ if kvPerHead > 0 && int(t.shape[1])%kvPerHead == 0 {
+ numHeads = int(t.shape[1]) / kvPerHead
+ }
+ kvFirst = true
+ case int(t.shape[1]) == mla.kvLoraRank:
+ if kvPerHead > 0 && int(t.shape[0])%kvPerHead == 0 {
+ numHeads = int(t.shape[0]) / kvPerHead
+ }
+ kvFirst = false
+ default:
+ return nil, fmt.Errorf("glm-4.7-flash migration cannot infer %s layout from shape %v", t.name, t.shape)
+ }
+
+ kTensor := t.Clone()
+ kTensor.SetRepacker(glm47FlashRepackKVB(mla, true, kvFirst, numHeads))
+ vTensor := t.Clone()
+ vTensor.SetRepacker(glm47FlashRepackKVB(mla, false, kvFirst, numHeads))
+
+ return []*outTensor{
+ {
+ Name: strings.Replace(t.name, "attn_kv_b", "attn_k_b", 1),
+ Kind: uint32(t.info.Type),
+ Shape: []uint64{uint64(mla.qkNope), uint64(mla.kvLoraRank), uint64(numHeads)},
+ WriterTo: kTensor,
+ },
+ {
+ Name: strings.Replace(t.name, "attn_kv_b", "attn_v_b", 1),
+ Kind: uint32(t.info.Type),
+ Shape: []uint64{uint64(mla.kvLoraRank), uint64(mla.vHeadDim), uint64(numHeads)},
+ WriterTo: vTensor,
+ },
+ }, nil
+}
+
+func glm47FlashRepackKVB(mla glm47FlashMLA, extractK bool, kvFirst bool, numHeads int) repacker {
+ return func(name string, data []float32, shape []uint64) ([]float32, error) {
+ if kvFirst {
+ var err error
+ if data, _, err = permuteTensor(data, tensorDims(shape), 1, 0); err != nil {
+ return nil, err
+ }
+ }
+
+ headDims := []int{numHeads, mla.qkNope + mla.vHeadDim, mla.kvLoraRank}
+ if err := checkTensorDims(data, headDims); err != nil {
+ return nil, fmt.Errorf("glm-4.7-flash migration cannot reshape %s from %v to %v: %w", name, shape, headDims, err)
+ }
+
+ if !extractK {
+ return sliceTensorDim(data, headDims, 1, mla.qkNope, mla.qkNope+mla.vHeadDim)
+ }
+
+ k, err := sliceTensorDim(data, headDims, 1, 0, mla.qkNope)
+ if err != nil {
+ return nil, err
+ }
+ headDims[1] = mla.qkNope
+ k, _, err = permuteTensor(k, headDims, 0, 2, 1)
+ return k, err
+ }
+}
diff --git a/compatmigrate/glm_ocr.go b/compatmigrate/glm_ocr.go
new file mode 100644
index 000000000..71a3eeb1f
--- /dev/null
+++ b/compatmigrate/glm_ocr.go
@@ -0,0 +1,308 @@
+package compatmigrate
+
+import (
+ "strconv"
+ "strings"
+
+ "github.com/ollama/ollama/fs/gguf"
+)
+
+type glmOCRMigrator struct{}
+
+// Mirrors detect_ollama_glmocr in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (glmOCRMigrator) NeedsMigration(src *SourceModel) bool {
+ return src.GGUF.KeyValue("general.architecture").String() == "glmocr"
+}
+
+func (glmOCRMigrator) Migrate(src *SourceModel) (*Result, error) {
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ numLayers := glmOCRTextLayerCount(src)
+ var modelTensors []*outTensor
+ var projectorTensors []*outTensor
+ pendingGate := map[string]*sourceTensor{}
+ pendingUp := map[string]*sourceTensor{}
+ for _, tensor := range tensors {
+ if glmOCRVisionTensor(tensor.name) {
+ name := glmOCRProjectorTensorName(tensor.name)
+ if strings.HasSuffix(name, "patch_embd.weight") && len(tensor.shape) == 5 && tensor.shape[2] == 2 {
+ split, err := splitSourceTensorDim(tensor, 2, "v.patch_embd.weight", "v.patch_embd.weight.1")
+ if err != nil {
+ return nil, err
+ }
+ for _, t := range split {
+ t.Shape = []uint64{tensor.shape[0], tensor.shape[1], tensor.shape[3], tensor.shape[4]}
+ projectorTensors = append(projectorTensors, t)
+ }
+ continue
+ }
+ projectorTensors = append(projectorTensors, copyTensor(name, tensor))
+ continue
+ }
+
+ name := glmOCRTextTensorName(tensor.name, numLayers)
+ name = strings.Replace(name, ".attn_out.", ".attn_output.", 1)
+ name = strings.Replace(name, ".post_attn_norm.", ".post_attention_norm.", 1)
+ name = strings.Replace(name, ".post_ffn_norm.", ".post_ffw_norm.", 1)
+ if strings.Contains(name, ".ffn_gate.") {
+ fusedName := strings.Replace(name, ".ffn_gate.", ".ffn_up.", 1)
+ if up := pendingUp[fusedName]; up != nil {
+ merged, err := concatSourceTensorsSlowDim(1, fusedName, tensor, up)
+ if err != nil {
+ return nil, err
+ }
+ modelTensors = append(modelTensors, merged)
+ delete(pendingUp, fusedName)
+ continue
+ }
+ pendingGate[fusedName] = tensor
+ continue
+ }
+ if strings.Contains(name, ".ffn_up.") {
+ if gate := pendingGate[name]; gate != nil {
+ merged, err := concatSourceTensorsSlowDim(1, name, gate, tensor)
+ if err != nil {
+ return nil, err
+ }
+ modelTensors = append(modelTensors, merged)
+ delete(pendingGate, name)
+ continue
+ }
+ pendingUp[name] = tensor
+ continue
+ }
+ modelTensors = append(modelTensors, copyTensor(name, tensor))
+ }
+ for name, tensor := range pendingUp {
+ modelTensors = append(modelTensors, copyTensor(name, tensor))
+ }
+ for _, tensor := range pendingGate {
+ modelTensors = append(modelTensors, copyTensor(tensor.name, tensor))
+ }
+
+ return &Result{
+ ModelKV: glmOCRModelKV(src),
+ ModelTensors: modelTensors,
+ ProjectorKV: glmOCRProjectorKV(src),
+ ProjectorTensors: projectorTensors,
+ }, nil
+}
+
+func glmOCRVisionTensor(name string) bool {
+ return strings.HasPrefix(name, "v.") || strings.HasPrefix(name, "mm.")
+}
+
+func glmOCRModelKV(src *SourceModel) outKV {
+ modelKV := outKV{}
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+
+ key := keyValue.Key
+ switch {
+ case key == "general.architecture":
+ modelKV[key] = "glm4"
+ case strings.HasPrefix(key, "glm4.vision."), strings.HasPrefix(key, "glmocr.vision."):
+ continue
+ case key == "glm4.rope.mrope_section":
+ modelKV["glm4.rope.dimension_sections"] = padInt32Sections(normalizeGGUFValue(keyValue.Any()))
+ case key == "glmocr.rope.mrope_section":
+ modelKV["glm4.rope.dimension_sections"] = padInt32Sections(normalizeGGUFValue(keyValue.Any()))
+ case strings.HasPrefix(key, "glm4."):
+ modelKV[key] = normalizeGGUFValue(keyValue.Any())
+ case strings.HasPrefix(key, "glmocr."):
+ modelKV[strings.Replace(key, "glmocr.", "glm4.", 1)] = normalizeGGUFValue(keyValue.Any())
+ case key == "rope.mrope_section":
+ modelKV["glm4.rope.dimension_sections"] = padInt32Sections(normalizeGGUFValue(keyValue.Any()))
+ case glmOCRTextKVKey(key):
+ modelKV["glm4."+key] = normalizeGGUFValue(keyValue.Any())
+ case strings.HasPrefix(key, "general."), strings.HasPrefix(key, "tokenizer."):
+ modelKV[key] = normalizeGGUFValue(keyValue.Any())
+ }
+ }
+ if src.GGUF.KeyValue("tokenizer.ggml.pre").Valid() {
+ modelKV["tokenizer.ggml.pre"] = "chatglm-bpe"
+ }
+ if _, ok := modelKV["glm4.rope.dimension_count"]; !ok {
+ if keyLength := src.GGUF.KeyValue("attention.key_length"); keyLength.Valid() {
+ modelKV["glm4.rope.dimension_count"] = uint32(keyLength.Uint())
+ }
+ }
+ if _, ok := modelKV["glm4.rope.dimension_sections"]; !ok {
+ if sections := src.GGUF.KeyValue("rope.dimension_sections"); sections.Valid() {
+ modelKV["glm4.rope.dimension_sections"] = padInt32Sections(normalizeGGUFValue(sections.Any()))
+ }
+ }
+ return modelKV
+}
+
+func glmOCRTextKVKey(key string) bool {
+ switch key {
+ case "block_count",
+ "nextn_predict_layers",
+ "embedding_length",
+ "attention.head_count",
+ "attention.head_count_kv",
+ "attention.key_length",
+ "attention.value_length",
+ "feed_forward_length",
+ "attention.layer_norm_rms_epsilon",
+ "context_length",
+ "rope.freq_base",
+ "rope.dimension_count":
+ return true
+ default:
+ return false
+ }
+}
+
+func glmOCRProjectorKV(src *SourceModel) outKV {
+ projectorKV := outKV{
+ "general.architecture": "clip",
+ "clip.projector_type": "glm4v",
+ "clip.use_silu": true,
+ "clip.has_vision_encoder": true,
+ "clip.vision.block_count": uint32(src.GGUF.KeyValue("vision.block_count").Uint()),
+ "clip.vision.embedding_length": uint32(src.GGUF.KeyValue("vision.embedding_length").Uint()),
+ "clip.vision.attention.head_count": uint32(src.GGUF.KeyValue("vision.attention.head_count").Uint()),
+ "clip.vision.image_size": uint32(src.GGUF.KeyValue("vision.image_size").Uint()),
+ "clip.vision.patch_size": uint32(src.GGUF.KeyValue("vision.patch_size").Uint()),
+ "clip.vision.spatial_merge_size": uint32(src.GGUF.KeyValue("vision.spatial_merge_size").Uint()),
+ "clip.vision.temporal_patch_size": uint32(src.GGUF.KeyValue("vision.temporal_patch_size").Uint()),
+ "clip.vision.out_hidden_size": uint32(src.GGUF.KeyValue("vision.out_hidden_size").Uint()),
+ "clip.vision.intermediate_size": uint32(src.GGUF.KeyValue("vision.intermediate_size").Uint()),
+ "clip.vision.feed_forward_length": uint32(src.GGUF.KeyValue("vision.intermediate_size").Uint()),
+ "clip.vision.projection_dim": uint32(src.GGUF.KeyValue("vision.out_hidden_size").Uint()),
+ "clip.vision.attention.layer_norm_epsilon": glmOCRFloat(src, "vision.attention.layer_norm_epsilon", "vision.attention.layer_norm_rms_epsilon"),
+ }
+ if mean := src.GGUF.KeyValue("vision.image_mean"); mean.Valid() {
+ projectorKV["clip.vision.image_mean"] = normalizeGGUFValue(mean.Any())
+ }
+ if std := src.GGUF.KeyValue("vision.image_std"); std.Valid() {
+ projectorKV["clip.vision.image_std"] = normalizeGGUFValue(std.Any())
+ }
+ if minPixels := glmOCRKeyValue(src, "vision.min_pixels", "vision.shortest_edge"); minPixels.Valid() {
+ projectorKV["clip.vision.min_pixels"] = uint32(minPixels.Uint())
+ }
+ if maxPixels := glmOCRKeyValue(src, "vision.max_pixels", "vision.longest_edge"); maxPixels.Valid() {
+ projectorKV["clip.vision.max_pixels"] = uint32(maxPixels.Uint())
+ }
+ for _, key := range []string{"image_token_id", "image_start_token_id", "image_end_token_id"} {
+ if value := src.GGUF.KeyValue(key); value.Valid() {
+ projectorKV["clip.vision."+key] = uint32(value.Uint())
+ }
+ }
+ return projectorKV
+}
+
+func glmOCRKeyValue(src *SourceModel, keys ...string) gguf.KeyValue {
+ for _, key := range keys {
+ if value := src.GGUF.KeyValue(key); value.Valid() {
+ return value
+ }
+ }
+ return gguf.KeyValue{}
+}
+
+func glmOCRFloat(src *SourceModel, keys ...string) float32 {
+ for _, key := range keys {
+ if value := src.GGUF.KeyValue(key); value.Valid() {
+ return float32(value.Float())
+ }
+ }
+ return 0
+}
+
+func glmOCRTextLayerCount(src *SourceModel) int {
+ blockCount := src.GGUF.KeyValue("block_count").Uint()
+ nextN := src.GGUF.KeyValue("nextn_predict_layers").Uint()
+ numLayers := blockCount
+ if nextN > 0 && nextN < blockCount {
+ numLayers = blockCount - nextN
+ }
+ return int(numLayers)
+}
+
+func glmOCRTextTensorName(name string, numLayers int) string {
+ blkNum, ok := tensorBlock(name)
+ if !ok || blkNum < numLayers {
+ return name
+ }
+
+ prefix := "blk." + strconv.Itoa(blkNum) + "."
+ suffix := strings.TrimPrefix(name, prefix)
+ switch {
+ case strings.HasPrefix(suffix, "eh_proj"):
+ return prefix + "nextn." + suffix
+ case strings.HasPrefix(suffix, "embed_tokens"):
+ return prefix + "nextn.embed_tokens" + strings.TrimPrefix(suffix, "embed_tokens")
+ case strings.HasPrefix(suffix, "enorm"):
+ return prefix + "nextn." + suffix
+ case strings.HasPrefix(suffix, "hnorm"):
+ return prefix + "nextn." + suffix
+ case strings.HasPrefix(suffix, "shared_head.head"):
+ return prefix + "nextn.shared_head_head" + strings.TrimPrefix(suffix, "shared_head.head")
+ case strings.HasPrefix(suffix, "shared_head.norm"):
+ return prefix + "nextn.shared_head_norm" + strings.TrimPrefix(suffix, "shared_head.norm")
+ default:
+ return name
+ }
+}
+
+func tensorBlock(name string) (int, bool) {
+ if !strings.HasPrefix(name, "blk.") {
+ return 0, false
+ }
+ rest := strings.TrimPrefix(name, "blk.")
+ idx := strings.IndexByte(rest, '.')
+ if idx < 0 {
+ return 0, false
+ }
+ n, err := strconv.Atoi(rest[:idx])
+ return n, err == nil
+}
+
+func glmOCRProjectorTensorName(name string) string {
+ switch name {
+ case "v.patch_embd_0.weight":
+ return "v.patch_embd.weight"
+ case "v.patch_embd_1.weight":
+ return "v.patch_embd.weight.1"
+ }
+
+ replacer := strings.NewReplacer(
+ "v.patch_embed.", "v.patch_embd.",
+ "v.norm_embd", "v.post_ln",
+ "attn.qkv", "attn_qkv",
+ "attn.proj", "attn_out",
+ "attn.q_norm", "attn_q_norm",
+ "attn.k_norm", "attn_k_norm",
+ "norm1", "ln1",
+ "norm2", "ln2",
+ "mlp.gate_proj", "ffn_gate",
+ "mlp.up_proj", "ffn_up",
+ "mlp.down_proj", "ffn_down",
+ "mm.patch_merger.proj", "mm.model.fc",
+ )
+ return replacer.Replace(name)
+}
+
+func padInt32Sections(v any) []int32 {
+ var sections []int32
+ switch values := v.(type) {
+ case []int32:
+ sections = append([]int32{}, values...)
+ case []uint32:
+ for _, value := range values {
+ sections = append(sections, int32(value))
+ }
+ }
+ for len(sections) < 4 {
+ sections = append(sections, 0)
+ }
+ return sections
+}
diff --git a/compatmigrate/gptoss.go b/compatmigrate/gptoss.go
new file mode 100644
index 000000000..08b21ad33
--- /dev/null
+++ b/compatmigrate/gptoss.go
@@ -0,0 +1,71 @@
+package compatmigrate
+
+import (
+ "strings"
+)
+
+type gptossMigrator struct{}
+
+// Mirrors detect_ollama_gptoss in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (gptossMigrator) NeedsMigration(src *SourceModel) bool {
+ return src.GGUF.KeyValue("general.architecture").String() == "gptoss"
+}
+
+func (gptossMigrator) Migrate(src *SourceModel) (*Result, error) {
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ modelTensors := make([]*outTensor, 0, len(tensors))
+ for _, tensor := range tensors {
+ name := strings.Replace(tensor.name, ".attn_out.", ".attn_output.", 1)
+ name = strings.Replace(name, ".ffn_norm.", ".post_attention_norm.", 1)
+ if strings.HasSuffix(name, ".attn_sinks") {
+ name += ".weight"
+ }
+ modelTensors = append(modelTensors, copyTensor(name, tensor))
+ }
+
+ modelKV := outKV{}
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+
+ key := keyValue.Key
+ switch {
+ case key == "general.architecture":
+ modelKV[key] = "gpt-oss"
+ case strings.HasPrefix(key, "gptoss."):
+ modelKV[strings.Replace(key, "gptoss.", "gpt-oss.", 1)] = normalizeGGUFValue(keyValue.Any())
+ case strings.HasPrefix(key, "general."), strings.HasPrefix(key, "tokenizer."):
+ modelKV[key] = normalizeGGUFValue(keyValue.Any())
+ }
+ }
+
+ if _, ok := modelKV["gpt-oss.expert_feed_forward_length"]; !ok {
+ if feedForwardLength := gptOSSExpertFeedForwardLength(tensors); feedForwardLength > 0 {
+ modelKV["gpt-oss.expert_feed_forward_length"] = feedForwardLength
+ }
+ }
+ if _, ok := modelKV["gpt-oss.rope.scaling.type"]; !ok {
+ modelKV["gpt-oss.rope.scaling.type"] = "yarn"
+ }
+
+ modelKV["tokenizer.ggml.pre"] = "gpt-4o"
+
+ return &Result{
+ ModelKV: modelKV,
+ ModelTensors: modelTensors,
+ }, nil
+}
+
+func gptOSSExpertFeedForwardLength(tensors []*sourceTensor) uint32 {
+ for _, tensor := range tensors {
+ if tensor.name == "blk.0.ffn_gate_exps.weight" && len(tensor.shape) >= 2 {
+ return uint32(tensor.shape[1])
+ }
+ }
+ return 0
+}
diff --git a/compatmigrate/laguna.go b/compatmigrate/laguna.go
new file mode 100644
index 000000000..6fb168d06
--- /dev/null
+++ b/compatmigrate/laguna.go
@@ -0,0 +1,62 @@
+package compatmigrate
+
+import (
+ "strings"
+)
+
+type lagunaMigrator struct{}
+
+// Mirrors detect_ollama_laguna in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (lagunaMigrator) NeedsMigration(src *SourceModel) bool {
+ if src.GGUF.KeyValue("general.architecture").String() != "laguna" {
+ return false
+ }
+ return rawGGUFKeyExists(src.GGUF, "laguna.rope.swa.dimension_count") ||
+ rawGGUFKeyExists(src.GGUF, "laguna.rope.swa.freq_base") ||
+ sourceTensorExists(src, "blk.0.attn_g.weight")
+}
+
+func (lagunaMigrator) Migrate(src *SourceModel) (*Result, error) {
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ modelTensors := make([]*outTensor, 0, len(tensors))
+ for _, tensor := range tensors {
+ modelTensors = append(modelTensors, copyTensor(lagunaTensorName(tensor.name), tensor))
+ }
+
+ modelKV := outKV{}
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+
+ key := keyValue.Key
+ value := normalizeGGUFValue(keyValue.Any())
+ switch {
+ case key == "laguna.rope.swa.dimension_count":
+ modelKV["laguna.rope.dimension_count_swa"] = value
+ case key == "laguna.rope.swa.freq_base":
+ modelKV["laguna.rope.freq_base_swa"] = value
+ case strings.HasPrefix(key, "general."), strings.HasPrefix(key, "tokenizer."), strings.HasPrefix(key, "laguna."):
+ modelKV[key] = value
+ }
+ }
+ if _, ok := modelKV["general.architecture"]; !ok {
+ modelKV["general.architecture"] = "laguna"
+ }
+
+ return &Result{
+ ModelKV: modelKV,
+ ModelTensors: modelTensors,
+ }, nil
+}
+
+func lagunaTensorName(name string) string {
+ if base, ok := strings.CutSuffix(name, ".attn_g.weight"); ok {
+ return base + ".attn_gate.weight"
+ }
+ return name
+}
diff --git a/compatmigrate/lfm25_thinking.go b/compatmigrate/lfm25_thinking.go
new file mode 100644
index 000000000..ee2a28213
--- /dev/null
+++ b/compatmigrate/lfm25_thinking.go
@@ -0,0 +1,103 @@
+package compatmigrate
+
+import (
+ "slices"
+ "strings"
+)
+
+type lfm25ThinkingMigrator struct{}
+
+// Mirrors detect_ollama_lfm2 in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (lfm25ThinkingMigrator) NeedsMigration(src *SourceModel) bool {
+ return src.GGUF.KeyValue("general.architecture").String() == "lfm2" &&
+ sourceTensorExists(src, "output_norm.weight") &&
+ !sourceTensorExists(src, "token_embd_norm.weight")
+}
+
+func (lfm25ThinkingMigrator) Migrate(src *SourceModel) (*Result, error) {
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ var hasEmbeddingNorm bool
+ embedLength := src.GGUF.KeyValue("embedding_length").Uint()
+ feedForwardLength := inferFeedForwardLength(tensors, embedLength)
+ modelTensors := make([]*outTensor, 0, len(tensors)+1)
+ for _, tensor := range tensors {
+ switch tensor.name {
+ case "token_embd_norm.weight":
+ hasEmbeddingNorm = true
+ case "output_norm.weight":
+ hasEmbeddingNorm = true
+ modelTensors = append(modelTensors, copyTensor("token_embd_norm.weight", tensor))
+ continue
+ }
+ modelTensors = append(modelTensors, copyTensor(tensor.name, tensor))
+ }
+
+ if !hasEmbeddingNorm {
+ nEmbd := src.GGUF.KeyValue("embedding_length").Uint()
+ if nEmbd == 0 {
+ return nil, errUnsupportedFamily
+ }
+
+ // The public LFM2.5-thinking GGUF is missing the embedding norm that
+ // llama-server requires. The original weights are not recoverable from
+ // the installed artifact, so local migration uses identity scale. A clean
+ // pull/re-create can still ship the real tensor if we publish one later.
+ ones := slices.Repeat([]float32{1}, int(nEmbd))
+ modelTensors = append(modelTensors, f32Tensor("token_embd_norm.weight", []uint64{nEmbd}, ones))
+ }
+
+ modelKV := outKV{}
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+
+ key := keyValue.Key
+ switch {
+ case key == "tokenizer.ggml.pre":
+ modelKV[key] = "lfm2"
+ case key == "general.architecture", strings.HasPrefix(key, "lfm2."), strings.HasPrefix(key, "general."), strings.HasPrefix(key, "tokenizer."):
+ modelKV[key] = normalizeGGUFValue(keyValue.Any())
+ }
+ }
+ if feedForwardLength > 0 {
+ modelKV["lfm2.feed_forward_length"] = uint32(feedForwardLength)
+ }
+
+ return &Result{
+ ModelKV: modelKV,
+ ModelTensors: modelTensors,
+ Renderer: "lfm2-thinking",
+ Parser: "lfm2-thinking",
+ }, nil
+}
+
+func inferFeedForwardLength(tensors []*sourceTensor, embedLength uint64) uint64 {
+ for _, tensor := range tensors {
+ if !strings.HasSuffix(tensor.name, ".ffn_gate.weight") && !strings.HasSuffix(tensor.name, ".ffn_up.weight") {
+ continue
+ }
+ if len(tensor.shape) < 2 {
+ continue
+ }
+ if embedLength > 0 {
+ switch {
+ case tensor.shape[0] == embedLength && tensor.shape[1] != 0:
+ return tensor.shape[1]
+ case tensor.shape[1] == embedLength && tensor.shape[0] != 0:
+ return tensor.shape[0]
+ }
+ }
+
+ if tensor.shape[0] >= tensor.shape[1] {
+ return tensor.shape[0]
+ }
+ return tensor.shape[1]
+ }
+
+ return 0
+}
diff --git a/compatmigrate/llama3.go b/compatmigrate/llama3.go
new file mode 100644
index 000000000..f5dbdb61a
--- /dev/null
+++ b/compatmigrate/llama3.go
@@ -0,0 +1,166 @@
+package compatmigrate
+
+import (
+ "strings"
+
+ "github.com/ollama/ollama/fs/gguf"
+ "github.com/ollama/ollama/manifest"
+)
+
+type llama3Migrator struct{}
+
+// Mirrors detect_ollama_llama3_metadata_gap in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (llama3Migrator) NeedsMigration(src *SourceModel) bool {
+ return llama3NeedsMetadataFix(src)
+}
+
+func (llama3Migrator) Migrate(src *SourceModel) (*Result, error) {
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ modelTensors := make([]*outTensor, 0, len(tensors))
+ for _, tensor := range tensors {
+ modelTensors = append(modelTensors, copyTensor(tensor.name, tensor))
+ }
+
+ modelKV := outKV{}
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+
+ key := keyValue.Key
+ if strings.HasPrefix(key, "general.") || strings.HasPrefix(key, "tokenizer.") || strings.HasPrefix(key, "llama.") {
+ modelKV[key] = normalizeGGUFValue(keyValue.Any())
+ }
+ }
+ if _, ok := modelKV["general.architecture"]; !ok {
+ modelKV["general.architecture"] = "llama"
+ }
+ if llama3NeedsMetadataFix(src) {
+ applyLlama3MetadataFix(modelKV)
+ }
+
+ result := &Result{
+ ModelKV: modelKV,
+ ModelTensors: modelTensors,
+ }
+ if src.ProjectorGGUF != nil {
+ result.PreserveProjector = true
+ }
+
+ return result, nil
+}
+
+// applyLlama3MetadataFix replaces the legacy default 128001 (<|end_of_text|>) with 128009 (<|eot_id|>).
+func applyLlama3MetadataFix(modelKV outKV) {
+ if llama3StringMissingOrDefault(modelKV["tokenizer.ggml.pre"]) {
+ modelKV["tokenizer.ggml.pre"] = "llama-bpe"
+ }
+ if llama3TokenizerIDMissingOrOld(modelKV["tokenizer.ggml.eos_token_id"]) {
+ modelKV["tokenizer.ggml.eos_token_id"] = uint32(128009)
+ }
+ if llama3TokenizerIDMissingOrOld(modelKV["tokenizer.ggml.eot_token_id"]) {
+ modelKV["tokenizer.ggml.eot_token_id"] = uint32(128009)
+ }
+ modelKV["tokenizer.ggml.eos_token_ids"] = []int32{128009}
+}
+
+// RewriteLlama3MetadataLayer rewrites a GGUF layer with the legacy Llama 3 tokenizer metadata gap.
+func RewriteLlama3MetadataLayer(layer manifest.Layer) (manifest.Layer, bool, error) {
+ path, err := manifest.BlobsPath(layer.Digest)
+ if err != nil {
+ return manifest.Layer{}, false, err
+ }
+
+ g, err := gguf.Open(path)
+ if err != nil {
+ return manifest.Layer{}, false, err
+ }
+ defer g.Close()
+
+ src := &SourceModel{
+ GGUFPath: path,
+ GGUF: g,
+ GGUFData: g.ReaderAt(),
+ GGUFDataOffset: g.TensorDataOffset(),
+ }
+ if !llama3NeedsMetadataFix(src) {
+ return layer, false, nil
+ }
+
+ result, err := (llama3Migrator{}).Migrate(src)
+ if err != nil {
+ return manifest.Layer{}, false, err
+ }
+
+ rewritten, err := writeGGUFLayer(result.ModelKV, result.ModelTensors, layer.MediaType)
+ if err != nil {
+ return manifest.Layer{}, false, err
+ }
+ rewritten.Name = layer.Name
+ return rewritten, true, nil
+}
+
+func llama3NeedsMetadataFix(src *SourceModel) bool {
+ if src.GGUF.KeyValue("general.architecture").String() != "llama" {
+ return false
+ }
+ if !llama3TokenAt(src, 128009, "<|eot_id|>") {
+ return false
+ }
+
+ hasMarkers := llama3TokenAt(src, 128006, "<|start_header_id|>") ||
+ strings.Contains(src.GGUF.KeyValue("tokenizer.chat_template").String(), "<|start_header_id|>") ||
+ strings.Contains(src.GGUF.KeyValue("tokenizer.chat_template").String(), "<|eot_id|>")
+
+ return hasMarkers &&
+ (llama3StringMissingOrDefault(src.GGUF.KeyValue("tokenizer.ggml.pre").String()) ||
+ llama3TokenizerIDOld(src.GGUF.KeyValue("tokenizer.ggml.eos_token_id").Any()))
+}
+
+func llama3TokenAt(src *SourceModel, index int, want string) bool {
+ tokens := src.GGUF.KeyValue("tokenizer.ggml.tokens").Strings()
+ return index >= 0 && index < len(tokens) && tokens[index] == want
+}
+
+func llama3StringMissingOrDefault(value any) bool {
+ s, ok := value.(string)
+ return !ok || s == "" || s == "default"
+}
+
+func llama3TokenizerIDMissingOrOld(value any) bool {
+ switch value := value.(type) {
+ case uint32:
+ return value == 0 || value == 128001
+ case uint64:
+ return value == 0 || value == 128001
+ case int32:
+ return value <= 0 || value == 128001
+ case int64:
+ return value <= 0 || value == 128001
+ case int:
+ return value <= 0 || value == 128001
+ default:
+ return true
+ }
+}
+
+func llama3TokenizerIDOld(value any) bool {
+ switch value := value.(type) {
+ case uint32:
+ return value == 128001
+ case uint64:
+ return value == 128001
+ case int32:
+ return value == 128001
+ case int64:
+ return value == 128001
+ case int:
+ return value == 128001
+ default:
+ return false
+ }
+}
diff --git a/compatmigrate/llama4.go b/compatmigrate/llama4.go
new file mode 100644
index 000000000..d8bf28ead
--- /dev/null
+++ b/compatmigrate/llama4.go
@@ -0,0 +1,121 @@
+package compatmigrate
+
+import (
+ "math"
+ "strings"
+)
+
+type llama4Migrator struct{}
+
+// Mirrors detect_ollama_llama4 in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (llama4Migrator) NeedsMigration(src *SourceModel) bool {
+ if src.GGUF.KeyValue("general.architecture").String() != "llama4" {
+ return false
+ }
+ return sourceTensorHasPrefix(src, "v.") || sourceTensorHasPrefix(src, "mm.")
+}
+
+func (llama4Migrator) Migrate(src *SourceModel) (*Result, error) {
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ var modelTensors []*outTensor
+ var projectorTensors []*outTensor
+ for _, tensor := range tensors {
+ if llama4ProjectorTensor(tensor.name) {
+ projectorTensors = append(projectorTensors, copyTensor(llama4ProjectorTensorName(tensor.name), tensor))
+ } else {
+ modelTensors = append(modelTensors, copyTensor(tensor.name, tensor))
+ }
+ }
+ if len(projectorTensors) == 0 {
+ return nil, errUnsupportedFamily
+ }
+
+ modelKV := outKV{}
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+
+ key := keyValue.Key
+ switch {
+ case strings.HasPrefix(key, "llama4.vision."):
+ continue
+ case key == "general.architecture", strings.HasPrefix(key, "llama4."), strings.HasPrefix(key, "general."), strings.HasPrefix(key, "tokenizer."):
+ modelKV[key] = normalizeGGUFValue(keyValue.Any())
+ }
+ }
+
+ projectorKV := outKV{
+ "general.architecture": "clip",
+ "clip.has_vision_encoder": true,
+ "clip.projector_type": "llama4",
+ "clip.vision.projector_type": "llama4",
+ "clip.vision.block_count": uint32(src.GGUF.KeyValue("vision.block_count").Uint()),
+ "clip.vision.embedding_length": uint32(src.GGUF.KeyValue("vision.embedding_length").Uint()),
+ "clip.vision.feed_forward_length": uint32(src.GGUF.KeyValue("vision.feed_forward_length").Uint()),
+ "clip.vision.attention.head_count": uint32(src.GGUF.KeyValue("vision.attention.head_count").Uint()),
+ "clip.vision.attention.layer_norm_epsilon": float32(src.GGUF.KeyValue("vision.layer_norm_epsilon").Float()),
+ "clip.vision.image_size": uint32(src.GGUF.KeyValue("vision.image_size").Uint()),
+ "clip.vision.patch_size": uint32(src.GGUF.KeyValue("vision.patch_size").Uint()),
+ "clip.vision.projection_dim": uint32(src.GGUF.KeyValue("embedding_length").Uint()),
+ "clip.vision.projector.scale_factor": llama4ProjectorScale(src),
+ "clip.vision.image_mean": []float32{0.5, 0.5, 0.5},
+ "clip.vision.image_std": []float32{0.5, 0.5, 0.5},
+ "clip.use_gelu": true,
+ }
+
+ return &Result{
+ ModelKV: modelKV,
+ ModelTensors: modelTensors,
+ ProjectorKV: projectorKV,
+ ProjectorTensors: projectorTensors,
+ }, nil
+}
+
+func llama4ProjectorTensor(name string) bool {
+ return strings.HasPrefix(name, "v.") || strings.HasPrefix(name, "mm.")
+}
+
+func llama4ProjectorTensorName(name string) string {
+ switch {
+ case name == "v.class_embedding":
+ return "v.class_embd"
+ case name == "v.positional_embedding_vlm":
+ return "v.position_embd.weight"
+ case strings.HasPrefix(name, "v.patch_embedding."):
+ return strings.Replace(name, "v.patch_embedding.", "v.patch_embd.", 1)
+ case strings.HasPrefix(name, "v.layernorm_pre."):
+ return strings.Replace(name, "v.layernorm_pre.", "v.pre_ln.", 1)
+ case strings.HasPrefix(name, "v.layernorm_post."):
+ return strings.Replace(name, "v.layernorm_post.", "v.post_ln.", 1)
+ case strings.HasPrefix(name, "v.vision_adapter.mlp.fc1."):
+ return strings.Replace(name, "v.vision_adapter.mlp.fc1.", "mm.model.mlp.1.", 1)
+ case strings.HasPrefix(name, "v.vision_adapter.mlp.fc2."):
+ return strings.Replace(name, "v.vision_adapter.mlp.fc2.", "mm.model.mlp.2.", 1)
+ case strings.HasPrefix(name, "mm.linear_1."):
+ return strings.Replace(name, "mm.linear_1.", "mm.model.fc.", 1)
+ }
+
+ name = strings.Replace(name, ".attn_output.", ".attn_out.", 1)
+ name = strings.Replace(name, ".attn_norm.", ".ln1.", 1)
+ name = strings.Replace(name, ".ffn_norm.", ".ln2.", 1)
+ name = strings.Replace(name, ".mlp.fc1.", ".ffn_up.", 1)
+ name = strings.Replace(name, ".mlp.fc2.", ".ffn_down.", 1)
+ return name
+}
+
+func llama4ProjectorScale(src *SourceModel) uint32 {
+ scale := uint32(2)
+ ratio := float32(src.GGUF.KeyValue("vision.pixel_shuffle_ratio").Float())
+ if ratio > 0 {
+ scale = uint32(math.Round(float64(1 / ratio)))
+ }
+ if scale == 0 {
+ return 2
+ }
+ return scale
+}
diff --git a/compatmigrate/manifest.go b/compatmigrate/manifest.go
new file mode 100644
index 000000000..4d793ecaa
--- /dev/null
+++ b/compatmigrate/manifest.go
@@ -0,0 +1,186 @@
+package compatmigrate
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "os"
+ "strings"
+
+ "github.com/ollama/ollama/manifest"
+ "github.com/ollama/ollama/types/model"
+)
+
+func writeCompatibilityManifestList(name model.Name, source *manifest.Manifest, manifests []manifest.Manifest) (bool, error) {
+ // Write the list first so the source anchor can reference its document blob.
+ parentDigest, err := manifest.WriteManifestListPreserveLegacy(name, manifests)
+ if err != nil {
+ return false, err
+ }
+
+ if source != nil {
+ // TODO: remove this downgrade anchor once rollback to pre-manifest-list
+ // Ollama versions is no longer supported.
+ manifestDigests := []string{parentDigest}
+ for _, child := range manifests {
+ digest, err := manifest.ChildManifestDigest(child)
+ if err != nil {
+ return false, err
+ }
+ manifestDigests = append(manifestDigests, digest)
+ }
+ if err := manifest.WriteLegacyAnchor(name, source, manifestDigests...); err != nil {
+ return false, err
+ }
+ }
+
+ return true, nil
+}
+
+func writeConvertedLegacyShadow(digest string, data []byte) error {
+ // TODO: remove this shadow tag once rollback to pre-manifest-list Ollama
+ // versions is no longer supported.
+ name, err := convertedLegacyShadowName(digest)
+ if err != nil {
+ return err
+ }
+ return manifest.WriteLegacyManifestData(name, data)
+}
+
+func convertedLegacyShadowName(digest string) (model.Name, error) {
+ hex := strings.TrimPrefix(strings.ToLower(strings.TrimSpace(digest)), "sha256:")
+ if hex == "" {
+ return model.Name{}, errors.New("converted manifest digest is empty")
+ }
+ name := model.ParseName(manifest.RunnerLlamaCPP + ":" + hex)
+ if !name.IsFullyQualified() {
+ return model.Name{}, fmt.Errorf("invalid converted manifest shadow name for digest %q", digest)
+ }
+ return name, nil
+}
+
+// removeConvertedChildBlobs removes the blobs written for a converted child
+// that will not be referenced by a manifest list: its config and layer blobs
+// plus, when already written, the child manifest blob itself. Blobs shared
+// with the source model remain referenced by the source manifest and are
+// skipped by RemoveUnreferencedBlobs.
+func removeConvertedChildBlobs(child *manifest.Manifest, manifestDigest string) {
+ if child == nil {
+ return
+ }
+
+ digests := make([]string, 0, len(child.Layers)+2)
+ if manifestDigest != "" {
+ digests = append(digests, manifestDigest)
+ }
+ if child.Config.Digest != "" {
+ digests = append(digests, child.Config.Digest)
+ }
+ for _, layer := range child.Layers {
+ digests = append(digests, layer.Digest)
+ }
+
+ if _, err := manifest.RemoveUnreferencedBlobs(digests...); err != nil {
+ slog.Warn("could not remove aborted migration blobs", "error", err)
+ }
+}
+
+// removeConvertedReference undoes a completed conversion whose manifest list
+// was never written: it drops the legacy shadow tag first (the shadow retains
+// the converted blobs) and then the blobs only the converted child references.
+func removeConvertedReference(ref manifest.Manifest) {
+ digest := ref.BlobDigest()
+ if digest == "" {
+ return
+ }
+
+ if shadow, err := convertedLegacyShadowName(digest); err == nil {
+ if _, err := manifest.RemoveNamed(shadow); err != nil && !errors.Is(err, os.ErrNotExist) {
+ slog.Warn("could not remove converted manifest shadow", "digest", digest, "error", err)
+ }
+ }
+
+ child := &manifest.Manifest{}
+ if path, err := manifest.BlobsPath(digest); err == nil {
+ if data, err := os.ReadFile(path); err == nil {
+ if err := json.Unmarshal(data, child); err != nil {
+ child = &manifest.Manifest{}
+ }
+ }
+ }
+ removeConvertedChildBlobs(child, digest)
+}
+
+func resolveChildManifest(child manifest.Manifest) (*manifest.Manifest, error) {
+ if child.MediaType == manifest.MediaTypeManifestList {
+ return nil, errors.New("nested manifest lists are not supported")
+ }
+
+ resolved, ok, err := manifest.ResolveManifestReference(child)
+ if err != nil {
+ return nil, err
+ }
+ if !ok {
+ return nil, os.ErrNotExist
+ }
+ if resolved.MediaType == manifest.MediaTypeManifestList {
+ return nil, errors.New("nested manifest lists are not supported")
+ }
+
+ if err := manifest.FillMetadata(resolved); err != nil {
+ return nil, err
+ }
+ return resolved, nil
+}
+
+func manifestReferenceForChild(child *manifest.Manifest) (manifest.Manifest, error) {
+ data, err := json.Marshal(child)
+ if err != nil {
+ return manifest.Manifest{}, err
+ }
+ digest, err := manifest.WriteManifestBlob(data)
+ if err != nil {
+ return manifest.Manifest{}, err
+ }
+ return manifest.NewManifestReference(digest, child.Runner, child.Format)
+}
+
+func manifestBlobsExist(m *manifest.Manifest) bool {
+ if m == nil {
+ return false
+ }
+ if m.Config.Digest != "" && !blobExists(m.Config.Digest) {
+ return false
+ }
+ hasModelLayer := false
+ for _, layer := range m.Layers {
+ if layer.Digest == "" {
+ return false
+ }
+ if !blobExists(layer.Digest) {
+ return false
+ }
+ if layer.MediaType == manifest.MediaTypeImageModel {
+ hasModelLayer = true
+ }
+ }
+ return hasModelLayer
+}
+
+func blobExists(digest string) bool {
+ path, err := manifest.BlobsPath(digest)
+ if err != nil {
+ return false
+ }
+ _, err = os.Stat(path)
+ return err == nil
+}
+
+func isRunnerFormat(m *manifest.Manifest, runner, format string) bool {
+ if m == nil {
+ return false
+ }
+ return strings.EqualFold(strings.TrimSpace(m.Runner), runner) &&
+ strings.EqualFold(strings.TrimSpace(m.Format), format)
+}
diff --git a/compatmigrate/migrate.go b/compatmigrate/migrate.go
new file mode 100644
index 000000000..d6a5ce939
--- /dev/null
+++ b/compatmigrate/migrate.go
@@ -0,0 +1,457 @@
+// Package compatmigrate converts older Ollama-format GGUF manifests already
+// present in a local model store into llama.cpp-compatible manifest-list
+// children.
+//
+// This exists to bridge the llama-server transition without forcing users to
+// re-pull large models they already have on disk. The first load can still use
+// the temporary llama.cpp compatibility patch, while a best-effort background
+// migration materializes a clean llamacpp child for later loads.
+//
+// Once manifest-list publishing has been live for enough releases and stale
+// legacy-only local stores are no longer a practical concern, this code should
+// be removed and users with unmigrated local artifacts should re-pull.
+package compatmigrate
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "io"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/ollama/ollama/fs/gguf"
+ "github.com/ollama/ollama/manifest"
+ "github.com/ollama/ollama/types/model"
+)
+
+var (
+ errUnsupportedFamily = errors.New("compat migration unsupported for family")
+ errInsufficientSpace = errors.New("insufficient disk space for local compat migration")
+)
+
+const (
+ // compatMigrationHeadroom (512 MiB) covers the converted projector,
+ // config, and manifest blobs plus temp-file slack during conversion.
+ compatMigrationHeadroom = 512 << 20
+
+ // compatMigrationMarginDenom pads the estimated converted-model size by
+ // 1/4 (25%) to allow for metadata growth and tensor dtype promotions.
+ compatMigrationMarginDenom = 4
+)
+
+type Migrator interface {
+ NeedsMigration(*SourceModel) bool
+ Migrate(*SourceModel) (*Result, error)
+}
+
+type SourceModel struct {
+ Source model.Name
+ Manifest *manifest.Manifest
+ Config model.ConfigV2
+ GGUFPath string
+ GGUF *gguf.File
+ GGUFData io.ReaderAt
+ GGUFDataOffset int64
+
+ ProjectorPath string
+ ProjectorGGUF *gguf.File
+ ProjectorData io.ReaderAt
+ ProjectorDataOffset int64
+}
+
+type Result struct {
+ ModelKV outKV
+ ModelTensors []*outTensor
+ ProjectorKV outKV
+ ProjectorTensors []*outTensor
+ PreserveProjector bool
+
+ Renderer string
+ Parser string
+ Requires string
+
+ ClearRenderer bool
+ ClearParser bool
+}
+
+var migratorsByArchitecture = map[string][]Migrator{
+ "gemma4": {gemma4Migrator{}},
+ "gemma3": {embeddingGemmaMigrator{}, gemma3Migrator{}},
+ "gemma3n": {gemma3nMigrator{}},
+ "bert": {snowflakeArcticEmbed2Migrator{}},
+ "deepseekocr": {deepseekOCRMigrator{}},
+ "glm4moelite": {glm47FlashMigrator{}},
+ "glmocr": {glmOCRMigrator{}},
+ "gptoss": {gptossMigrator{}},
+ "laguna": {lagunaMigrator{}},
+ "lfm2": {lfm25ThinkingMigrator{}},
+ "llama": {bakllavaMigrator{}, llama3Migrator{}},
+ "llama4": {llama4Migrator{}},
+ "mistral3": {mistralPixtralMigrator{}},
+ "nemotron_h_moe": {nemotronHMoeMigrator{}},
+ "nemotron_h_omni": {nemotron3Migrator{}},
+ "olmo3": {olmo3Migrator{}},
+ "qwen35": {qwen35Migrator{}},
+ "qwen35moe": {qwen35Migrator{}},
+ "qwen3next": {qwen3NextMigrator{}},
+ "qwen25vl": {qwen25VLMigrator{}},
+ "qwen3vl": {qwen3VLMigrator{}},
+ "qwen3vlmoe": {qwen3VLMigrator{}},
+}
+
+var (
+ availableSpaceForPath = availableSpace
+ migrationLocks sync.Map
+ migrationInFlight sync.Map
+)
+
+// SetMigratorsForTesting replaces the migration registry for tests.
+func SetMigratorsForTesting(migrators map[string][]Migrator) func() {
+ previous := migratorsByArchitecture
+ migratorsByArchitecture = migrators
+ return func() {
+ migratorsByArchitecture = previous
+ }
+}
+
+func StartLocalCompatibilityMigration(name model.Name) bool {
+ if !name.IsFullyQualified() {
+ return false
+ }
+ if !hasCompatibilityMigrators() {
+ return false
+ }
+
+ key := name.String()
+ if _, loaded := migrationInFlight.LoadOrStore(key, struct{}{}); loaded {
+ return false
+ }
+
+ go func() {
+ defer migrationInFlight.Delete(key)
+
+ migrated, err := EnsureLocalCompatibilityMigration(name)
+ switch {
+ case err != nil:
+ slog.Warn("local compatibility migration failed",
+ "model", name.DisplayShortest(),
+ "error", err,
+ )
+ case migrated:
+ slog.Debug("local compatibility migration completed",
+ "model", name.DisplayShortest(),
+ )
+ }
+ }()
+
+ return true
+}
+
+func hasCompatibilityMigrators() bool {
+ for _, migrators := range migratorsByArchitecture {
+ if len(migrators) > 0 {
+ return true
+ }
+ }
+ return false
+}
+
+func EnsureLocalCompatibilityMigration(name model.Name) (bool, error) {
+ if !name.IsFullyQualified() {
+ return false, model.Unqualified(name)
+ }
+
+ unlock := lockCompatibilityMigration(name)
+ defer unlock()
+
+ data, err := manifest.ReadManifestData(name)
+ if errors.Is(err, os.ErrNotExist) {
+ return false, nil
+ } else if err != nil {
+ return false, err
+ }
+
+ var parent manifest.Manifest
+ if err := json.Unmarshal(data, &parent); err != nil {
+ return false, err
+ }
+
+ source, refs, done, err := migrationSourceFromManifest(&parent)
+ if err != nil || done || source == nil {
+ return done, err
+ }
+
+ if mediaType, ok := unsupportedSourceLayer(source); ok {
+ // copyAncillaryLayers cannot carry these layers into the converted
+ // child, and the converted child is preferred at load time — migrating
+ // would silently change model behavior (e.g. run a LoRA model without
+ // its adapter).
+ slog.Info("skipping local compatibility migration for unsupported source layer",
+ "model", name.DisplayShortest(),
+ "media_type", mediaType,
+ )
+ return false, nil
+ }
+
+ src, err := loadSourceModelFromManifest(name, source)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return false, nil
+ }
+ return false, err
+ }
+ defer src.Close()
+
+ migrator := compatibilityMigratorForSource(src)
+ if migrator == nil {
+ return false, nil
+ }
+
+ convertedRef, err := migrateToManifestReference(migrator, src)
+ if err != nil {
+ if errors.Is(err, errUnsupportedFamily) || errors.Is(err, errInsufficientSpace) {
+ slog.Info("skipping local compatibility migration",
+ "model", name.DisplayShortest(),
+ "reason", err,
+ )
+ return false, nil
+ }
+ return false, err
+ }
+
+ // The conversion can take minutes on a large model. If the named manifest
+ // was removed or replaced while it ran (ollama rm / pull / create), writing
+ // now would resurrect or revert it. The per-name lock is held for this
+ // whole function, so re-checking the raw manifest data closes the race.
+ if current, readErr := manifest.ReadManifestData(name); readErr != nil || !bytes.Equal(current, data) {
+ slog.Info("discarding local compatibility migration; model changed during conversion",
+ "model", name.DisplayShortest(),
+ )
+ removeConvertedReference(convertedRef)
+ return false, nil
+ }
+
+ refs = append(refs, convertedRef)
+ return writeCompatibilityManifestList(name, source, refs)
+}
+
+// unsupportedSourceLayer reports a source layer type the conversion would
+// silently drop from the converted child (see copyAncillaryLayers).
+func unsupportedSourceLayer(source *manifest.Manifest) (string, bool) {
+ for _, layer := range source.Layers {
+ switch layer.MediaType {
+ case manifest.MediaTypeImageAdapter, manifest.MediaTypeImageEmbed:
+ return layer.MediaType, true
+ }
+ }
+ return "", false
+}
+
+func lockCompatibilityMigration(name model.Name) func() {
+ value, _ := migrationLocks.LoadOrStore(name.String(), &sync.Mutex{})
+ mu := value.(*sync.Mutex)
+ mu.Lock()
+ return mu.Unlock
+}
+
+func migrationSourceFromManifest(parent *manifest.Manifest) (*manifest.Manifest, []manifest.Manifest, bool, error) {
+ if parent.MediaType != manifest.MediaTypeManifestList {
+ child := *parent
+ if err := manifest.FillMetadata(&child); err != nil {
+ return nil, nil, false, err
+ }
+ if isRunnerFormat(&child, manifest.RunnerLlamaCPP, manifest.FormatGGUF) && manifestBlobsExist(&child) {
+ return nil, nil, true, nil
+ }
+ if !isRunnerFormat(&child, manifest.RunnerGGML, manifest.FormatGGUF) {
+ return nil, nil, false, nil
+ }
+ ref, err := manifestReferenceForChild(&child)
+ if err != nil {
+ return nil, nil, false, err
+ }
+ return &child, []manifest.Manifest{ref}, false, nil
+ }
+
+ refs := make([]manifest.Manifest, 0, len(parent.Manifests)+1)
+ var source *manifest.Manifest
+ for _, child := range parent.Manifests {
+ if child.MediaType == manifest.MediaTypeManifestList {
+ return nil, nil, false, errors.New("nested manifest lists are not supported")
+ }
+
+ resolved, err := resolveChildManifest(child)
+ if err != nil {
+ if isRunnerFormat(&child, manifest.RunnerLlamaCPP, manifest.FormatGGUF) {
+ if !errors.Is(err, os.ErrNotExist) {
+ return nil, nil, false, err
+ }
+ // Drop llamacpp children whose blobs are gone so the
+ // migration regenerates them.
+ continue
+ }
+ // Preserve foreign-runner children verbatim; their blobs may
+ // legitimately live elsewhere (e.g. not pulled for this platform).
+ slog.Warn("keeping unresolvable manifest child during migration scan",
+ "runner", child.Runner,
+ "digest", child.Digest,
+ "error", err,
+ )
+ refs = append(refs, child)
+ continue
+ }
+
+ if isRunnerFormat(resolved, manifest.RunnerLlamaCPP, manifest.FormatGGUF) && manifestBlobsExist(resolved) {
+ return nil, nil, true, nil
+ }
+ if isRunnerFormat(resolved, manifest.RunnerLlamaCPP, manifest.FormatGGUF) {
+ // Broken llamacpp child (manifest resolves but blobs are missing):
+ // drop it so this migration writes a fresh replacement.
+ continue
+ }
+
+ // The first GGML child with complete blobs is the conversion source.
+ if source == nil && isRunnerFormat(resolved, manifest.RunnerGGML, manifest.FormatGGUF) && manifestBlobsExist(resolved) {
+ sourceCopy := *resolved
+ source = &sourceCopy
+ }
+
+ ref, err := manifestReferenceForChild(resolved)
+ if err != nil {
+ return nil, nil, false, err
+ }
+ refs = append(refs, ref)
+ }
+ return source, refs, false, nil
+}
+
+// RunnerForManifest reports the runner a GGUF manifest should carry: ggml when
+// a compatibility detector fires, llamacpp otherwise. It reads GGUF headers
+// only, so it is cheap enough to run whenever a manifest is written.
+func RunnerForManifest(source model.Name, mf *manifest.Manifest) (string, error) {
+ src, err := loadSourceModelFromManifest(source, mf)
+ if err != nil {
+ return "", err
+ }
+ defer src.Close()
+
+ if compatibilityMigratorForSource(src) != nil {
+ return manifest.RunnerGGML, nil
+ }
+ return manifest.RunnerLlamaCPP, nil
+}
+
+func compatibilityMigratorForSource(src *SourceModel) Migrator {
+ arch := strings.ToLower(strings.TrimSpace(src.GGUF.KeyValue("general.architecture").String()))
+ if arch == "" {
+ return nil
+ }
+
+ for _, migrator := range migratorsByArchitecture[arch] {
+ if migrator.NeedsMigration(src) {
+ return migrator
+ }
+ }
+ return nil
+}
+
+func sourceTensorHasPrefix(src *SourceModel, prefix string) bool {
+ for _, tensor := range src.GGUF.TensorInfos() {
+ if strings.HasPrefix(tensor.Name, prefix) {
+ return true
+ }
+ }
+ return false
+}
+
+func sourceTensorExists(src *SourceModel, name string) bool {
+ return src.GGUF.TensorInfo(name).Valid()
+}
+
+func sourceTensorShape(src *SourceModel, name string) ([]uint64, bool) {
+ info := src.GGUF.TensorInfo(name)
+ return info.Shape, info.Valid()
+}
+
+func rawGGUFKeyExists(g *gguf.File, key string) bool {
+ return rawGGUFKeyValue(g, key).Valid()
+}
+
+func rawGGUFKeyValue(g *gguf.File, key string) gguf.KeyValue {
+ for _, keyValue := range g.KeyValues() {
+ if keyValue.Key == key && keyValue.Valid() {
+ return keyValue
+ }
+ }
+ return gguf.KeyValue{}
+}
+
+func migrateToManifestReference(migrator Migrator, src *SourceModel) (_ manifest.Manifest, err error) {
+ required := requiredBytesFromSource(src)
+ available, err := availableSpaceForPath(filepath.Dir(src.GGUFPath))
+ if err != nil {
+ return manifest.Manifest{}, err
+ }
+ if available < required {
+ slog.Info("skipping local compat migration due to disk headroom",
+ "model", src.Source.DisplayShortest(),
+ "available_bytes", available,
+ "required_bytes", required,
+ )
+ return manifest.Manifest{}, errInsufficientSpace
+ }
+
+ start := time.Now()
+ slog.Info("starting local compat GGUF migration",
+ "model", src.Source.DisplayShortest(),
+ "required_bytes", required,
+ )
+
+ result, err := migrator.Migrate(src)
+ if err != nil {
+ return manifest.Manifest{}, err
+ }
+
+ child, err := convertedManifest(src, result)
+ if err != nil {
+ return manifest.Manifest{}, err
+ }
+
+ // From here on the converted blobs exist in the store; clean them up on
+ // any failure so an aborted migration does not strand a multi-GB blob
+ // until the next startup prune.
+ var childDigest string
+ defer func() {
+ if err != nil {
+ removeConvertedChildBlobs(child, childDigest)
+ }
+ }()
+
+ data, err := json.Marshal(child)
+ if err != nil {
+ return manifest.Manifest{}, err
+ }
+ childDigest, err = manifest.WriteManifestBlob(data)
+ if err != nil {
+ return manifest.Manifest{}, err
+ }
+ ref, err := manifest.NewManifestReference(childDigest, manifest.RunnerLlamaCPP, manifest.FormatGGUF)
+ if err != nil {
+ return manifest.Manifest{}, err
+ }
+ if err = writeConvertedLegacyShadow(childDigest, data); err != nil {
+ return manifest.Manifest{}, err
+ }
+
+ slog.Info("completed local compat GGUF migration",
+ "model", src.Source.DisplayShortest(),
+ "duration", time.Since(start),
+ )
+
+ return ref, nil
+}
diff --git a/compatmigrate/migrate_test.go b/compatmigrate/migrate_test.go
new file mode 100644
index 000000000..520f5688d
--- /dev/null
+++ b/compatmigrate/migrate_test.go
@@ -0,0 +1,1447 @@
+package compatmigrate
+
+import (
+ "bytes"
+ "encoding/binary"
+ "encoding/json"
+ "errors"
+ "io"
+ "math"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/x448/float16"
+
+ "github.com/ollama/ollama/fs/gguf"
+ "github.com/ollama/ollama/manifest"
+ "github.com/ollama/ollama/types/model"
+)
+
+func TestEnsureLocalCompatibilityMigrationAppendsToExistingManifestList(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+ registerTestCompatMigrator(t)
+
+ source := model.ParseName("registry.ollama.ai/library/testcompat:latest")
+ writeSourceManifest(t, source, sourceManifestInput{
+ config: model.ConfigV2{
+ ModelFormat: "gguf",
+ ModelFamily: "testcompat",
+ ModelFamilies: []string{"testcompat"},
+ },
+ modelKV: outKV{
+ "general.architecture": "testcompat",
+ "tokenizer.ggml.tokens": []string{"x"},
+ },
+ modelTensors: []*outTensor{
+ fixtureTensor("token_embd.weight", gguf.TensorTypeF16, []uint64{1, 8}),
+ },
+ })
+ wrapSourceManifestAsList(t, source)
+
+ migrated, err := EnsureLocalCompatibilityMigration(source)
+ if err != nil {
+ t.Fatalf("EnsureLocalCompatibilityMigration() error = %v", err)
+ }
+ if !migrated {
+ t.Fatal("expected migration to append a llamacpp child")
+ }
+
+ raw, err := manifest.ReadManifestData(source)
+ if err != nil {
+ t.Fatalf("ReadManifestData(source) error = %v", err)
+ }
+ var parent manifest.Manifest
+ if err := json.Unmarshal(raw, &parent); err != nil {
+ t.Fatalf("unmarshal parent manifest: %v", err)
+ }
+ if parent.MediaType != manifest.MediaTypeManifestList {
+ t.Fatalf("expected manifest list, got %q", parent.MediaType)
+ }
+ if len(parent.Manifests) != 2 {
+ t.Fatalf("expected two child manifests, got %d", len(parent.Manifests))
+ }
+ if _, err := manifest.ParseNamedManifestForRunner(source, manifest.RunnerGGML); err != nil {
+ t.Fatalf("expected ggml child to resolve: %v", err)
+ }
+ if _, err := manifest.ParseNamedManifestForRunner(source, manifest.RunnerLlamaCPP); err != nil {
+ t.Fatalf("expected llamacpp child to resolve: %v", err)
+ }
+
+ migratedAgain, err := EnsureLocalCompatibilityMigration(source)
+ if err != nil {
+ t.Fatalf("EnsureLocalCompatibilityMigration(second) error = %v", err)
+ }
+ if !migratedAgain {
+ t.Fatal("expected existing llamacpp child to satisfy migration")
+ }
+ rawAgain, err := manifest.ReadManifestData(source)
+ if err != nil {
+ t.Fatalf("ReadManifestData(second) error = %v", err)
+ }
+ if !bytes.Equal(raw, rawAgain) {
+ t.Fatal("expected second migration attempt to leave manifest list unchanged")
+ }
+}
+
+func TestEnsureLocalCompatibilityMigrationUnsupportedFamilyNoop(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ source := model.ParseName("registry.ollama.ai/library/notcompat:latest")
+ writeSourceManifest(t, source, sourceManifestInput{
+ config: model.ConfigV2{
+ ModelFormat: "gguf",
+ ModelFamily: "notcompat",
+ },
+ modelKV: outKV{
+ "general.architecture": "notcompat",
+ "tokenizer.ggml.tokens": []string{"x"},
+ },
+ modelTensors: []*outTensor{
+ fixtureTensor("token_embd.weight", gguf.TensorTypeF16, []uint64{1, 8}),
+ },
+ })
+
+ migrated, err := EnsureLocalCompatibilityMigration(source)
+ if err != nil {
+ t.Fatalf("EnsureLocalCompatibilityMigration() error = %v", err)
+ }
+ if migrated {
+ t.Fatal("expected unsupported family to skip migration")
+ }
+
+ raw, err := manifest.ReadManifestData(source)
+ if err != nil {
+ t.Fatalf("ReadManifestData(source) error = %v", err)
+ }
+ var stored manifest.Manifest
+ if err := json.Unmarshal(raw, &stored); err != nil {
+ t.Fatalf("unmarshal stored manifest: %v", err)
+ }
+ if stored.MediaType == manifest.MediaTypeManifestList {
+ t.Fatal("expected unsupported source manifest to remain simple")
+ }
+}
+
+func TestEnsureLocalCompatibilityMigrationSkipsAdapterModels(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+ registerTestCompatMigrator(t)
+
+ source := model.ParseName("registry.ollama.ai/library/testcompat:adapter")
+ writeSourceManifest(t, source, sourceManifestInput{
+ config: model.ConfigV2{
+ ModelFormat: "gguf",
+ ModelFamily: "testcompat",
+ },
+ modelKV: outKV{
+ "general.architecture": "testcompat",
+ },
+ modelTensors: []*outTensor{
+ fixtureTensor("token_embd.weight", gguf.TensorTypeF32, []uint64{2, 2}),
+ },
+ adapter: "fake lora adapter payload",
+ })
+
+ migrated, err := EnsureLocalCompatibilityMigration(source)
+ if err != nil {
+ t.Fatalf("EnsureLocalCompatibilityMigration() error = %v", err)
+ }
+ if migrated {
+ t.Fatal("expected adapter-bearing source to skip migration; the converted child would drop the adapter")
+ }
+
+ raw, err := manifest.ReadManifestData(source)
+ if err != nil {
+ t.Fatalf("ReadManifestData(source) error = %v", err)
+ }
+ var stored manifest.Manifest
+ if err := json.Unmarshal(raw, &stored); err != nil {
+ t.Fatalf("unmarshal stored manifest: %v", err)
+ }
+ if stored.MediaType == manifest.MediaTypeManifestList {
+ t.Fatal("expected adapter-bearing source manifest to remain simple")
+ }
+}
+
+func TestEnsureLocalCompatibilityMigrationPreservesPromptMetadata(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+ registerTestCompatMigrator(t)
+
+ source := model.ParseName("registry.ollama.ai/library/testcompat:latest")
+ template := "TEMPLATE keep"
+ writeSourceManifest(t, source, sourceManifestInput{
+ config: model.ConfigV2{
+ ModelFormat: "gguf",
+ ModelFamily: "testcompat",
+ ModelFamilies: []string{"testcompat"},
+ Renderer: "keep-renderer",
+ Parser: "keep-parser",
+ },
+ modelKV: outKV{
+ "general.architecture": "testcompat",
+ },
+ modelTensors: []*outTensor{
+ fixtureTensor("token_embd.weight", gguf.TensorTypeF32, []uint64{2, 2}),
+ },
+ template: template,
+ })
+
+ migrated, err := EnsureLocalCompatibilityMigration(source)
+ if err != nil {
+ t.Fatalf("EnsureLocalCompatibilityMigration() error = %v", err)
+ }
+ if !migrated {
+ t.Fatal("expected migration to create target manifest")
+ }
+
+ mf, err := manifest.ParseNamedManifestForRunner(source, manifest.RunnerLlamaCPP)
+ if err != nil {
+ t.Fatalf("ParseNamedManifestForRunner(target, llamacpp) error = %v", err)
+ }
+ if len(mf.Layers) != 2 {
+ t.Fatalf("expected model + template layers, got %d", len(mf.Layers))
+ }
+
+ configPath, err := manifest.BlobsPath(mf.Config.Digest)
+ if err != nil {
+ t.Fatalf("BlobsPath(config) error = %v", err)
+ }
+ configFile, err := os.Open(configPath)
+ if err != nil {
+ t.Fatalf("Open(config) error = %v", err)
+ }
+ defer configFile.Close()
+ var config model.ConfigV2
+ if err := json.NewDecoder(configFile).Decode(&config); err != nil {
+ t.Fatalf("Decode(config) error = %v", err)
+ }
+ if config.Renderer != "keep-renderer" || config.Parser != "keep-parser" {
+ t.Fatalf("expected renderer/parser to be preserved, got %q/%q", config.Renderer, config.Parser)
+ }
+
+ templatePath, err := manifest.BlobsPath(mf.Layers[1].Digest)
+ if err != nil {
+ t.Fatalf("BlobsPath(template) error = %v", err)
+ }
+ if got, err := os.ReadFile(templatePath); err != nil {
+ t.Fatalf("ReadFile(template) error = %v", err)
+ } else if string(got) != template {
+ t.Fatalf("expected template layer to be preserved, got %q", got)
+ }
+}
+
+func TestEnsureLocalCompatibilityMigrationGemma4(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ source := model.ParseName("registry.ollama.ai/library/gemma4:e4b")
+ writeSourceManifest(t, source, sourceManifestInput{
+ config: model.ConfigV2{
+ ModelFormat: "gguf",
+ ModelFamily: "gemma4",
+ ModelFamilies: []string{"gemma4"},
+ ModelType: "4.3B",
+ FileType: "Q4_K_M",
+ },
+ modelKV: outKV{
+ "general.architecture": "gemma4",
+ "gemma4.block_count": uint32(2),
+ "gemma4.embedding_length": uint32(32),
+ "gemma4.attention.head_count": uint32(8),
+ "gemma4.attention.head_count_kv": uint32(2),
+ "gemma4.attention.key_length": uint32(64),
+ "gemma4.attention.value_length": uint32(64),
+ "gemma4.attention.key_length_swa": uint32(32),
+ "gemma4.attention.value_length_swa": uint32(32),
+ "gemma4.attention.layer_norm_rms_epsilon": float32(1e-6),
+ "gemma4.attention.sliding_window": uint32(512),
+ "gemma4.attention.sliding_window_pattern": []bool{true, false},
+ "gemma4.attention.shared_kv_layers": uint32(1),
+ "gemma4.embedding_length_per_layer_input": uint32(8),
+ "gemma4.rope.dimension_count": uint32(64),
+ "gemma4.rope.dimension_count_swa": uint32(32),
+ "gemma4.rope.freq_base": float32(1e6),
+ "gemma4.rope.freq_base_swa": float32(1e4),
+ "gemma4.vision.block_count": uint32(4),
+ "gemma4.vision.embedding_length": uint32(24),
+ "gemma4.vision.feed_forward_length": uint32(96),
+ "gemma4.vision.attention.head_count": uint32(6),
+ "gemma4.vision.attention.layer_norm_epsilon": float32(1e-6),
+ "gemma4.vision.patch_size": uint32(16),
+ "gemma4.vision.projector.scale_factor": uint32(3),
+ "gemma4.audio.block_count": uint32(3),
+ "gemma4.audio.embedding_length": uint32(16),
+ "gemma4.audio.attention.head_count": uint32(4),
+ "tokenizer.ggml.model": "llama",
+ "tokenizer.ggml.tokens": []string{"<bos>", "hello"},
+ },
+ modelTensors: []*outTensor{
+ fixtureTensor("token_embd.weight", gguf.TensorTypeF16, []uint64{2, 32}),
+ fixtureTensor("blk.0.attn_q.weight", gguf.TensorTypeF16, []uint64{32, 32}),
+ fixtureTensor("blk.0.ffn_gate_exps.weight", gguf.TensorTypeF16, []uint64{32, 16, 2}),
+ fixtureTensor("blk.0.ffn_up_exps.weight", gguf.TensorTypeF16, []uint64{32, 16, 2}),
+ fixtureTensor("blk.0.ffn_gate_inp.per_expert_scale", gguf.TensorTypeF32, []uint64{2}),
+ fixtureTensor("v.patch_embd.weight", gguf.TensorTypeF16, []uint64{16, 16, 3, 24}),
+ fixtureTensor("mm.input_projection.weight", gguf.TensorTypeF16, []uint64{24, 32}),
+ fixtureTensor("a.blk.0.attn_q.weight", gguf.TensorTypeBF16, []uint64{16, 16}),
+ fixtureTensor("a.blk.0.linear_pos.weight", gguf.TensorTypeBF16, []uint64{16, 16}),
+ fixtureTensor("a.blk.0.ln1.weight", gguf.TensorTypeF32, []uint64{16}),
+ fixtureTensor("a.blk.0.ln2.weight", gguf.TensorTypeF32, []uint64{16}),
+ fixtureTensor("a.blk.0.layer_pre_norm.weight", gguf.TensorTypeF32, []uint64{16}),
+ fixtureTensor("a.pre_encode.out.weight", gguf.TensorTypeF16, []uint64{16, 16}),
+ fixtureTensor("mm.a.input_projection.weight", gguf.TensorTypeF16, []uint64{16, 32}),
+ fixtureTensor("mm.a.fc.weight", gguf.TensorTypeF16, []uint64{16, 32}),
+ },
+ template: "TEMPLATE gemma4",
+ })
+
+ migrated, err := EnsureLocalCompatibilityMigration(source)
+ if err != nil {
+ t.Fatalf("EnsureLocalCompatibilityMigration() error = %v", err)
+ }
+ if !migrated {
+ t.Fatal("expected migration to create target manifest")
+ }
+
+ mf, err := manifest.ParseNamedManifestForRunner(source, manifest.RunnerLlamaCPP)
+ if err != nil {
+ t.Fatalf("ParseNamedManifestForRunner(target, llamacpp) error = %v", err)
+ }
+ if len(mf.Layers) != 3 {
+ var mediaTypes []string
+ for _, layer := range mf.Layers {
+ mediaTypes = append(mediaTypes, layer.MediaType)
+ }
+ t.Fatalf("expected model + projector + template layers, got %d: %v runner=%q format=%q", len(mf.Layers), mediaTypes, mf.Runner, mf.Format)
+ }
+
+ config := readConfigLayer(t, mf.Config.Digest)
+ if config.Renderer != "gemma4" || config.Parser != "gemma4" {
+ t.Fatalf("expected gemma4 renderer/parser, got %q/%q", config.Renderer, config.Parser)
+ }
+
+ modelGGUF := openGGUFLayer(t, mf.Layers[0].Digest)
+ defer modelGGUF.Close()
+ if got := modelGGUF.KeyValue("general.architecture").String(); got != "gemma4" {
+ t.Fatalf("expected model architecture gemma4, got %q", got)
+ }
+ if got := modelGGUF.KeyValue("tokenizer.ggml.model").String(); got != "gemma4" {
+ t.Fatalf("expected migrated tokenizer.ggml.model gemma4, got %q", got)
+ }
+ if got := modelGGUF.TensorInfo("a.blk.0.attn_q.weight"); got.Valid() {
+ t.Fatal("expected audio tensor to be moved out of migrated text model")
+ }
+ if got := modelGGUF.TensorInfo("v.patch_embd.weight"); got.Valid() {
+ t.Fatal("expected vision tensor to be moved out of migrated text model")
+ }
+ if got := modelGGUF.TensorInfo("blk.0.ffn_gate_up_exps.weight"); !got.Valid() || !slices.Equal(got.Shape, []uint64{32, 32, 2}) {
+ t.Fatalf("expected fused MoE gate/up tensor shape [32 32 2], got valid=%v shape=%v", got.Valid(), got.Shape)
+ }
+ if got := modelGGUF.TensorInfo("blk.0.ffn_up_exps.weight"); got.Valid() {
+ t.Fatal("expected split MoE up tensor to be fused")
+ }
+ if got := modelGGUF.TensorInfo("blk.0.ffn_down_exps.scale"); !got.Valid() {
+ t.Fatal("expected per-expert scale to move to ffn_down_exps.scale")
+ }
+
+ projectorGGUF := openGGUFLayer(t, mf.Layers[1].Digest)
+ defer projectorGGUF.Close()
+ if got := projectorGGUF.KeyValue("general.architecture").String(); got != "clip" {
+ t.Fatalf("expected projector architecture clip, got %q", got)
+ }
+ if got := projectorGGUF.KeyValue("projector_type"); got.Valid() {
+ t.Fatalf("mixed Gemma4 projector must not set generic projector type, got %q", got.String())
+ }
+ if got := projectorGGUF.KeyValue("vision.projector_type").String(); got != "gemma4v" {
+ t.Fatalf("expected vision projector type gemma4v, got %q", got)
+ }
+ if got := projectorGGUF.KeyValue("has_audio_encoder").Bool(); !got {
+ t.Fatal("expected projector to advertise audio encoder")
+ }
+ if got := projectorGGUF.KeyValue("audio.projector_type").String(); got != "gemma4a" {
+ t.Fatalf("expected audio projector type gemma4a, got %q", got)
+ }
+ for _, name := range []string{
+ "v.patch_embd.weight",
+ "mm.input_projection.weight",
+ "mm.a.input_projection.weight",
+ "a.input_projection.weight",
+ "a.pre_encode.out.weight",
+ "a.blk.0.attn_q.weight",
+ "a.blk.0.attn_k_rel.weight",
+ "a.blk.0.attn_pre_norm.weight",
+ "a.blk.0.attn_post_norm.weight",
+ "a.blk.0.ln2.weight",
+ } {
+ if got := projectorGGUF.TensorInfo(name); !got.Valid() {
+ t.Fatalf("expected migrated Gemma4 projector tensor %s", name)
+ }
+ }
+}
+
+func TestEnsureLocalCompatibilityMigrationGemma4CompatibleCopyNoop(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ source := model.ParseName("registry.ollama.ai/library/gemma4:e4b-llamacpp")
+ writeSourceManifest(t, source, sourceManifestInput{
+ config: model.ConfigV2{
+ ModelFormat: "gguf",
+ ModelFamily: "gemma4",
+ ModelFamilies: []string{"gemma4"},
+ },
+ modelKV: outKV{
+ "general.architecture": "gemma4",
+ "gemma4.block_count": uint32(1),
+ "tokenizer.ggml.model": "gemma4",
+ "tokenizer.ggml.tokens": []string{"<bos>", "hello"},
+ },
+ modelTensors: []*outTensor{
+ fixtureTensor("token_embd.weight", gguf.TensorTypeF16, []uint64{2, 32}),
+ fixtureTensor("blk.0.attn_q.weight", gguf.TensorTypeF16, []uint64{32, 32}),
+ },
+ })
+
+ migrated, err := EnsureLocalCompatibilityMigration(source)
+ if err != nil {
+ t.Fatalf("EnsureLocalCompatibilityMigration() error = %v", err)
+ }
+ if migrated {
+ t.Fatal("expected compatible copied Gemma4 model to skip migration")
+ }
+
+ raw, err := manifest.ReadManifestData(source)
+ if err != nil {
+ t.Fatalf("ReadManifestData(source) error = %v", err)
+ }
+ var stored manifest.Manifest
+ if err := json.Unmarshal(raw, &stored); err != nil {
+ t.Fatalf("unmarshal stored manifest: %v", err)
+ }
+ if stored.MediaType == manifest.MediaTypeManifestList {
+ t.Fatal("expected compatible source manifest to remain simple")
+ }
+}
+
+func TestGemma4ProjectorTensorName(t *testing.T) {
+ tests := map[string]string{
+ "a.blk.0.linear_pos.weight": "a.blk.0.attn_k_rel.weight",
+ "a.blk.0.ln1.weight": "a.blk.0.attn_pre_norm.weight",
+ "a.blk.0.ln2.weight": "a.blk.0.attn_post_norm.weight",
+ "a.blk.0.layer_pre_norm.weight": "a.blk.0.ln2.weight",
+ "mm.a.fc.weight": "a.pre_encode.out.weight",
+ "a.pre_encode.out.weight": "a.input_projection.weight",
+ "v.patch_embd.weight": "v.patch_embd.weight",
+ "mm.input_projection.weight": "mm.input_projection.weight",
+ }
+
+ for in, want := range tests {
+ if got := gemma4ProjectorTensorName(in, true); got != want {
+ t.Fatalf("gemma4ProjectorTensorName(%q) = %q, want %q", in, got, want)
+ }
+ }
+ if got := gemma4ProjectorTensorName("a.pre_encode.out.weight", false); got != "a.pre_encode.out.weight" {
+ t.Fatalf("expected non-legacy audio name to be preserved, got %q", got)
+ }
+}
+
+func TestDeepseekOCRProjectorTensorName(t *testing.T) {
+ const (
+ publishedViewSeparator = "mm.view_seperator" //nolint:misspell // published DeepSeek OCR tensor spelling
+ llamaCPPViewSeparator = "v.view_seperator" //nolint:misspell // published DeepSeek OCR tensor spelling
+ )
+ tests := map[string]string{
+ publishedViewSeparator: llamaCPPViewSeparator,
+ "mm.view_separator": "v.view_separator",
+ }
+
+ for in, want := range tests {
+ if got := deepseekOCRProjectorTensorName(in); got != want {
+ t.Fatalf("deepseekOCRProjectorTensorName(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
+
+func TestEnsureLocalCompatibilityMigrationLaguna(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ source := model.ParseName("registry.ollama.ai/library/laguna-xs.2:q4_K_M")
+ writeSourceManifest(t, source, sourceManifestInput{
+ config: model.ConfigV2{
+ ModelFormat: "gguf",
+ ModelFamily: "laguna",
+ ModelFamilies: []string{"laguna"},
+ Renderer: "laguna",
+ Parser: "laguna",
+ },
+ modelKV: outKV{
+ "general.architecture": "laguna",
+ "laguna.block_count": uint32(2),
+ "laguna.embedding_length": uint32(32),
+ "laguna.attention.head_count": uint32(8),
+ "laguna.attention.head_count_kv": uint32(2),
+ "laguna.attention.layer_norm_rms_epsilon": float32(1e-6),
+ "laguna.attention.sliding_window": uint32(512),
+ "laguna.attention.layer_types": []int32{1, 0},
+ "laguna.rope.dimension_count": uint32(64),
+ "laguna.rope.freq_base": float32(1e6),
+ "laguna.rope.swa.dimension_count": uint32(32),
+ "laguna.rope.swa.freq_base": float32(1e4),
+ "tokenizer.ggml.model": "gpt2",
+ "tokenizer.ggml.tokens": []string{"<bos>", "hello"},
+ },
+ modelTensors: []*outTensor{
+ fixtureTensor("token_embd.weight", gguf.TensorTypeF16, []uint64{2, 32}),
+ fixtureTensor("blk.0.attn_q.weight", gguf.TensorTypeF16, []uint64{32, 32}),
+ fixtureTensor("blk.0.attn_g.weight", gguf.TensorTypeF16, []uint64{32, 32}),
+ fixtureTensor("blk.1.attn_g.weight", gguf.TensorTypeF16, []uint64{32, 32}),
+ },
+ template: "TEMPLATE laguna",
+ })
+
+ migrated, err := EnsureLocalCompatibilityMigration(source)
+ if err != nil {
+ t.Fatalf("EnsureLocalCompatibilityMigration() error = %v", err)
+ }
+ if !migrated {
+ t.Fatal("expected migration to create target manifest")
+ }
+
+ mf, err := manifest.ParseNamedManifestForRunner(source, manifest.RunnerLlamaCPP)
+ if err != nil {
+ t.Fatalf("ParseNamedManifestForRunner(target, llamacpp) error = %v", err)
+ }
+ if len(mf.Layers) != 2 {
+ t.Fatalf("expected model + template layers, got %d", len(mf.Layers))
+ }
+
+ config := readConfigLayer(t, mf.Config.Digest)
+ if config.Renderer != "laguna" || config.Parser != "laguna" {
+ t.Fatalf("expected laguna renderer/parser, got %q/%q", config.Renderer, config.Parser)
+ }
+
+ modelGGUF := openGGUFLayer(t, mf.Layers[0].Digest)
+ defer modelGGUF.Close()
+ if got := modelGGUF.KeyValue("general.architecture").String(); got != "laguna" {
+ t.Fatalf("expected model architecture laguna, got %q", got)
+ }
+ if got := modelGGUF.KeyValue("rope.dimension_count_swa"); !got.Valid() || got.Uint() != 32 {
+ t.Fatalf("expected migrated rope.dimension_count_swa 32, got valid=%v value=%d", got.Valid(), got.Uint())
+ }
+ if got := modelGGUF.KeyValue("rope.freq_base_swa"); !got.Valid() || got.Float() != 1e4 {
+ t.Fatalf("expected migrated rope.freq_base_swa 1e4, got valid=%v value=%f", got.Valid(), got.Float())
+ }
+ if got := modelGGUF.KeyValue("rope.swa.dimension_count"); got.Valid() {
+ t.Fatal("expected legacy rope.swa.dimension_count to be dropped")
+ }
+ if got := modelGGUF.KeyValue("rope.swa.freq_base"); got.Valid() {
+ t.Fatal("expected legacy rope.swa.freq_base to be dropped")
+ }
+ for _, name := range []string{"blk.0.attn_gate.weight", "blk.1.attn_gate.weight", "blk.0.attn_q.weight", "token_embd.weight"} {
+ if got := modelGGUF.TensorInfo(name); !got.Valid() {
+ t.Fatalf("expected migrated laguna tensor %s", name)
+ }
+ }
+ for _, name := range []string{"blk.0.attn_g.weight", "blk.1.attn_g.weight"} {
+ if got := modelGGUF.TensorInfo(name); got.Valid() {
+ t.Fatalf("expected legacy laguna tensor %s to be renamed", name)
+ }
+ }
+}
+
+func TestEnsureLocalCompatibilityMigrationSerializesConcurrentCalls(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ source := model.ParseName("registry.ollama.ai/library/testcompat:latest")
+ writeSourceManifest(t, source, sourceManifestInput{
+ config: model.ConfigV2{
+ ModelFormat: "gguf",
+ ModelFamily: "testcompat",
+ ModelFamilies: []string{"testcompat"},
+ },
+ modelKV: outKV{
+ "general.architecture": "testcompat",
+ "tokenizer.ggml.tokens": []string{"x"},
+ },
+ modelTensors: []*outTensor{
+ fixtureTensor("token_embd.weight", gguf.TensorTypeF16, []uint64{1, 8}),
+ },
+ })
+
+ var calls atomic.Int32
+ registerCountingCompatMigrator(t, &calls)
+
+ const workers = 8
+ var wg sync.WaitGroup
+ errs := make(chan error, workers)
+ start := make(chan struct{})
+ for range workers {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ <-start
+ migrated, err := EnsureLocalCompatibilityMigration(source)
+ if err != nil {
+ errs <- err
+ return
+ }
+ if !migrated {
+ errs <- errors.New("expected migration to succeed")
+ return
+ }
+ }()
+ }
+ close(start)
+ wg.Wait()
+ close(errs)
+
+ for err := range errs {
+ if err != nil {
+ t.Fatalf("concurrent migration failed: %v", err)
+ }
+ }
+ if got := calls.Load(); got != 1 {
+ t.Fatalf("expected one migration under concurrent calls, got %d", got)
+ }
+}
+
+func TestEnsureLocalCompatibilityMigrationSkipsWhenDiskIsTooFull(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+ registerTestCompatMigrator(t)
+
+ source := model.ParseName("registry.ollama.ai/library/testcompat:latest")
+ writeSourceManifest(t, source, sourceManifestInput{
+ config: model.ConfigV2{
+ ModelFormat: "gguf",
+ ModelFamily: "testcompat",
+ },
+ modelKV: outKV{
+ "general.architecture": "testcompat",
+ "tokenizer.ggml.tokens": []string{"x"},
+ },
+ modelTensors: []*outTensor{
+ fixtureTensor("token_embd.weight", gguf.TensorTypeF16, []uint64{1, 8}),
+ },
+ })
+
+ overrideAvailableSpace(t, func(string) (uint64, error) { return 0, nil })
+
+ migrated, err := EnsureLocalCompatibilityMigration(source)
+ if err != nil {
+ t.Fatalf("EnsureLocalCompatibilityMigration() error = %v", err)
+ }
+ if migrated {
+ t.Fatal("expected migration to skip when disk headroom is insufficient")
+ }
+ data, err := manifest.ReadManifestData(source)
+ if err != nil {
+ t.Fatalf("ReadManifestData(source) error = %v", err)
+ }
+ var stored manifest.Manifest
+ if err := json.Unmarshal(data, &stored); err != nil {
+ t.Fatalf("unmarshal stored manifest: %v", err)
+ }
+ if stored.MediaType == manifest.MediaTypeManifestList {
+ t.Fatal("expected source manifest to remain simple when disk headroom is insufficient")
+ }
+}
+
+func TestQwen3VLSplitLegacyPatchTensorOrder(t *testing.T) {
+ shape := []uint64{2, 2, 2, 6}
+ raw := make([]byte, tensorBytes(gguf.TensorTypeF16, shape))
+ for i := range len(raw) / 2 {
+ putF16(raw[i*2:], float32(i))
+ }
+
+ source := &sourceTensor{
+ readerAt: bytes.NewReader(raw),
+ info: gguf.TensorInfo{
+ Name: "v.patch_embed.weight",
+ Shape: shape,
+ Type: gguf.TensorTypeF16,
+ },
+ name: "v.patch_embed.weight",
+ shape: shape,
+ }
+
+ got, err := qwen3VLSplitLegacyPatchTensor(source, 3)
+ if err != nil {
+ t.Fatalf("qwen3VLSplitLegacyPatchTensor() error = %v", err)
+ }
+ if len(got) != 2 {
+ t.Fatalf("expected two split tensors, got %d", len(got))
+ }
+ if !slices.Equal(got[0].Shape, []uint64{2, 2, 3, 2}) || !slices.Equal(got[1].Shape, []uint64{2, 2, 3, 2}) {
+ t.Fatalf("unexpected split shapes: %v %v", got[0].Shape, got[1].Shape)
+ }
+
+ first := writeTensorF32(t, got[0])
+ second := writeTensorF32(t, got[1])
+ wantFirst := []float32{0, 1, 2, 3, 8, 9, 10, 11, 16, 17, 18, 19, 24, 25, 26, 27, 32, 33, 34, 35, 40, 41, 42, 43}
+ wantSecond := []float32{4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31, 36, 37, 38, 39, 44, 45, 46, 47}
+ if !slices.Equal(first, wantFirst) {
+ t.Fatalf("unexpected first temporal patch split:\n got %v\nwant %v", first, wantFirst)
+ }
+ if !slices.Equal(second, wantSecond) {
+ t.Fatalf("unexpected second temporal patch split:\n got %v\nwant %v", second, wantSecond)
+ }
+}
+
+func TestQwen3VLConcatQKVWeightsOrder(t *testing.T) {
+ q := sourceTensorF16("v.blk.0.attn_q.weight", []uint64{2, 2}, []float32{0, 1, 2, 3})
+ k := sourceTensorF16("v.blk.0.attn_k.weight", []uint64{2, 2}, []float32{4, 5, 6, 7})
+ v := sourceTensorF16("v.blk.0.attn_v.weight", []uint64{2, 2}, []float32{8, 9, 10, 11})
+
+ got, err := qwen3VLConcatQKVWeights("v.blk.0.attn_qkv.weight", q, k, v)
+ if err != nil {
+ t.Fatalf("qwen3VLConcatQKVWeights() error = %v", err)
+ }
+ if !slices.Equal(got.Shape, []uint64{2, 6}) {
+ t.Fatalf("unexpected qkv shape: %v", got.Shape)
+ }
+
+ if values := writeTensorF16(t, got); !slices.Equal(values, []float32{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}) {
+ t.Fatalf("unexpected qkv raw order: %v", values)
+ }
+}
+
+func TestMistralPixtralVisionQKRepack(t *testing.T) {
+ data := []float32{
+ 0, 1, 2, 3, 4, 5, 6, 7,
+ 8, 9, 10, 11, 12, 13, 14, 15,
+ 16, 17, 18, 19, 20, 21, 22, 23,
+ 24, 25, 26, 27, 28, 29, 30, 31,
+ }
+ got, err := mistralPixtralVisionQKRepack(data, []uint64{8, 4}, 2)
+ if err != nil {
+ t.Fatalf("mistralPixtralVisionQKRepack() error = %v", err)
+ }
+
+ want := []float32{
+ 0, 1, 2, 3, 8, 9, 10, 11,
+ 4, 5, 6, 7, 12, 13, 14, 15,
+ 16, 17, 18, 19, 24, 25, 26, 27,
+ 20, 21, 22, 23, 28, 29, 30, 31,
+ }
+ if !slices.Equal(got, want) {
+ t.Fatalf("unexpected mistral/pixtral qk repack:\n got %v\nwant %v", got, want)
+ }
+}
+
+func TestDecodeQuantizedTensorRows(t *testing.T) {
+ t.Run("q8_0", func(t *testing.T) {
+ q8 := make([]byte, q8_0BlkSize)
+ putF16(q8, 1) // block scale d = 1.0, so decoded values equal the raw int8 quants
+ q8[2] = 3
+ q8[3] = 0xfe // int8(0xfe) = -2
+ gotQ8, err := decodeQ8_0Row(q8, qk8_0)
+ if err != nil {
+ t.Fatalf("decodeQ8_0Row() error = %v", err)
+ }
+ if gotQ8[0] != 3 || gotQ8[1] != -2 {
+ t.Fatalf("unexpected q8_0 decode prefix: %v", gotQ8[:2])
+ }
+ })
+
+ t.Run("q5_0", func(t *testing.T) {
+ q5 := make([]byte, q5_0BlkSize)
+ putF16(q5, 1) // block scale d = 1.0
+ // qh bits 0 and 16 set the fifth (high) bit for elements 0 and 16.
+ binary.LittleEndian.PutUint32(q5[2:], (1<<0)|(1<<16))
+ // 0x21 packs low nibble 1 (element 0) and high nibble 2 (element 16);
+ // with the high bits above they decode as (1|0x10)-16=1 and (2|0x10)-16=2.
+ q5[6] = 0x21
+ gotQ5, err := decodeQ5_0Row(q5, qk5_0)
+ if err != nil {
+ t.Fatalf("decodeQ5_0Row() error = %v", err)
+ }
+ if gotQ5[0] != 1 || gotQ5[16] != 2 {
+ t.Fatalf("unexpected q5_0 decode prefix: %v %v", gotQ5[0], gotQ5[16])
+ }
+ })
+
+ t.Run("q4_K", func(t *testing.T) {
+ q4 := make([]byte, q4KBlkSize)
+ putF16(q4, 1) // super-block scale d = 1.0
+ putF16(q4[2:], 0) // super-block min = 0, so per-sub-block mins drop out
+ for i := 4; i < 16; i++ {
+ q4[i] = 1 // packed 6-bit sub-block scales/mins all decode to 1
+ }
+ for i := 16; i < q4KBlkSize; i++ {
+ q4[i] = 0x21 // packs 4-bit quants: low nibble 1 (first 32 values), high nibble 2 (next 32)
+ }
+ gotQ4, err := decodeQ4KRow(q4, qkK)
+ if err != nil {
+ t.Fatalf("decodeQ4KRow() error = %v", err)
+ }
+ if gotQ4[0] != 1 || gotQ4[31] != 1 || gotQ4[32] != 2 || gotQ4[63] != 2 {
+ t.Fatalf("unexpected q4_k decode prefix: %v %v %v %v", gotQ4[0], gotQ4[31], gotQ4[32], gotQ4[63])
+ }
+ })
+
+ t.Run("q6_K", func(t *testing.T) {
+ q6 := make([]byte, q6KBlkSize)
+ for i := 192; i < 208; i++ {
+ q6[i] = 1 // int8 sub-block scales = 1
+ }
+ putF16(q6[208:], 1) // super-block scale d = 1.0
+ // All-zero 6-bit quants decode as 0-32 = -32 (q6_k centers quants on 32).
+ gotQ6, err := decodeQ6KRow(q6, qkK)
+ if err != nil {
+ t.Fatalf("decodeQ6KRow() error = %v", err)
+ }
+ if gotQ6[0] != -32 || gotQ6[127] != -32 {
+ t.Fatalf("unexpected q6_k decode prefix: %v %v", gotQ6[0], gotQ6[127])
+ }
+ })
+}
+
+// TestNeedsMigrationAlreadyConverted verifies that files already in
+// llama.cpp-compatible form are not re-detected as needing migration, with one
+// positive control per family to keep the detectors honest.
+func TestNeedsMigrationAlreadyConverted(t *testing.T) {
+ // llama3NeedsMetadataFix requires the real Llama 3 marker tokens at their ids.
+ llama3Tokens := make([]string, 128010)
+ llama3Tokens[128006] = "<|start_header_id|>"
+ llama3Tokens[128009] = "<|eot_id|>"
+
+ cases := []struct {
+ name string
+ migrator Migrator
+ kv outKV
+ tensors []*outTensor
+ projectorKV outKV
+ projectorTensors []*outTensor
+ want bool
+ }{
+ {
+ name: "embeddinggemma already converted dense sidecar only",
+ migrator: embeddingGemmaMigrator{},
+ kv: outKV{
+ "general.architecture": "gemma3",
+ },
+ tensors: []*outTensor{
+ fixtureTensor("dense.0.bias", gguf.TensorTypeF16, []uint64{8}),
+ },
+ want: false,
+ },
+ {
+ name: "embeddinggemma legacy dense weight",
+ migrator: embeddingGemmaMigrator{},
+ kv: outKV{
+ "general.architecture": "gemma3",
+ },
+ tensors: []*outTensor{
+ fixtureTensor("dense.0.weight", gguf.TensorTypeF16, []uint64{8, 8}),
+ },
+ want: true,
+ },
+ {
+ name: "gemma3 already converted",
+ migrator: gemma3Migrator{},
+ kv: outKV{
+ "general.architecture": "gemma3",
+ "gemma3.rope.freq_base": float32(1e6),
+ "gemma3.rope.freq_base_swa": float32(1e4),
+ "gemma3.attention.layer_norm_rms_epsilon": float32(1e-6),
+ },
+ tensors: []*outTensor{
+ fixtureTensor("token_embd.weight", gguf.TensorTypeF16, []uint64{2, 8}),
+ },
+ want: false,
+ },
+ {
+ name: "gemma3 legacy rope keys",
+ migrator: gemma3Migrator{},
+ kv: outKV{
+ "general.architecture": "gemma3",
+ "gemma3.rope.global.freq_base": float32(1e6),
+ },
+ tensors: []*outTensor{
+ fixtureTensor("token_embd.weight", gguf.TensorTypeF16, []uint64{2, 8}),
+ },
+ want: true,
+ },
+ {
+ name: "laguna already converted",
+ migrator: lagunaMigrator{},
+ kv: outKV{
+ "general.architecture": "laguna",
+ "laguna.rope.dimension_count_swa": uint32(32),
+ "laguna.rope.freq_base_swa": float32(1e4),
+ },
+ tensors: []*outTensor{
+ fixtureTensor("blk.0.attn_gate.weight", gguf.TensorTypeF16, []uint64{8, 8}),
+ },
+ want: false,
+ },
+ {
+ name: "laguna legacy swa keys and gate tensor",
+ migrator: lagunaMigrator{},
+ kv: outKV{
+ "general.architecture": "laguna",
+ "laguna.rope.swa.dimension_count": uint32(32),
+ "laguna.rope.swa.freq_base": float32(1e4),
+ },
+ tensors: []*outTensor{
+ fixtureTensor("blk.0.attn_g.weight", gguf.TensorTypeF16, []uint64{8, 8}),
+ },
+ want: true,
+ },
+ {
+ name: "laguna legacy swa keys without gate tensor",
+ migrator: lagunaMigrator{},
+ kv: outKV{
+ "general.architecture": "laguna",
+ "laguna.rope.swa.dimension_count": uint32(32),
+ "laguna.rope.swa.freq_base": float32(1e4),
+ },
+ tensors: []*outTensor{
+ fixtureTensor("blk.0.attn_gate.weight", gguf.TensorTypeF16, []uint64{8, 8}),
+ },
+ want: true,
+ },
+ {
+ name: "qwen3next already converted",
+ migrator: qwen3NextMigrator{},
+ kv: outKV{
+ "general.architecture": "qwen3next",
+ },
+ tensors: []*outTensor{
+ fixtureTensor("blk.0.ssm_dt.bias", gguf.TensorTypeF32, []uint64{8}),
+ },
+ want: false,
+ },
+ {
+ name: "qwen3next legacy ssm_dt tensor",
+ migrator: qwen3NextMigrator{},
+ kv: outKV{
+ "general.architecture": "qwen3next",
+ },
+ tensors: []*outTensor{
+ fixtureTensor("blk.0.ssm_dt", gguf.TensorTypeF32, []uint64{8}),
+ },
+ want: true,
+ },
+ {
+ name: "llama3 already converted",
+ migrator: llama3Migrator{},
+ kv: outKV{
+ "general.architecture": "llama",
+ "tokenizer.ggml.pre": "llama-bpe",
+ "tokenizer.ggml.eos_token_id": uint32(128009),
+ "tokenizer.ggml.tokens": llama3Tokens,
+ },
+ tensors: []*outTensor{
+ fixtureTensor("token_embd.weight", gguf.TensorTypeF16, []uint64{2, 8}),
+ },
+ want: false,
+ },
+ {
+ name: "llama3 legacy metadata gap",
+ migrator: llama3Migrator{},
+ kv: outKV{
+ "general.architecture": "llama",
+ "tokenizer.ggml.pre": "default",
+ "tokenizer.ggml.eos_token_id": uint32(128001),
+ "tokenizer.ggml.tokens": llama3Tokens,
+ },
+ tensors: []*outTensor{
+ fixtureTensor("token_embd.weight", gguf.TensorTypeF16, []uint64{2, 8}),
+ },
+ want: true,
+ },
+ {
+ name: "llama3 missing eos with explicit pre",
+ migrator: llama3Migrator{},
+ kv: outKV{
+ "general.architecture": "llama",
+ "tokenizer.ggml.pre": "llama-bpe",
+ "tokenizer.ggml.tokens": llama3Tokens,
+ },
+ tensors: []*outTensor{
+ fixtureTensor("token_embd.weight", gguf.TensorTypeF16, []uint64{2, 8}),
+ },
+ want: false,
+ },
+ {
+ name: "bakllava legacy clip projector",
+ migrator: bakllavaMigrator{},
+ kv: outKV{
+ "general.architecture": "llama",
+ },
+ tensors: []*outTensor{
+ fixtureTensor("token_embd.weight", gguf.TensorTypeF16, []uint64{2, 8}),
+ },
+ projectorKV: outKV{
+ "general.architecture": "clip",
+ "clip.has_vision_encoder": true,
+ },
+ projectorTensors: []*outTensor{
+ fixtureTensor("mm.0.weight", gguf.TensorTypeF16, []uint64{2, 2}),
+ },
+ want: true,
+ },
+ {
+ name: "bakllava clip projector without vision encoder",
+ migrator: bakllavaMigrator{},
+ kv: outKV{
+ "general.architecture": "llama",
+ },
+ tensors: []*outTensor{
+ fixtureTensor("token_embd.weight", gguf.TensorTypeF16, []uint64{2, 8}),
+ },
+ projectorKV: outKV{
+ "general.architecture": "clip",
+ },
+ projectorTensors: []*outTensor{
+ fixtureTensor("mm.0.weight", gguf.TensorTypeF16, []uint64{2, 2}),
+ },
+ want: false,
+ },
+ {
+ name: "bakllava non clip projector",
+ migrator: bakllavaMigrator{},
+ kv: outKV{
+ "general.architecture": "llama",
+ },
+ tensors: []*outTensor{
+ fixtureTensor("token_embd.weight", gguf.TensorTypeF16, []uint64{2, 8}),
+ },
+ projectorKV: outKV{
+ "general.architecture": "bert",
+ "bert.pooling_type": uint32(1),
+ },
+ projectorTensors: []*outTensor{
+ fixtureTensor("token_embd.weight", gguf.TensorTypeF16, []uint64{2, 8}),
+ },
+ want: false,
+ },
+ }
+
+ for _, tt := range cases {
+ t.Run(tt.name, func(t *testing.T) {
+ src := fixtureSourceModel(t, tt.kv, tt.tensors)
+ if tt.projectorKV != nil {
+ projector := fixtureSourceModel(t, tt.projectorKV, tt.projectorTensors)
+ src.ProjectorGGUF = projector.GGUF
+ }
+ if got := tt.migrator.NeedsMigration(src); got != tt.want {
+ t.Fatalf("NeedsMigration() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestGPTOSSExpertFeedForwardLengthFromTensor(t *testing.T) {
+ src := fixtureSourceModel(t, outKV{
+ "general.architecture": "gptoss",
+ "gptoss.feed_forward_length": uint32(4096),
+ }, []*outTensor{
+ fixtureTensor("blk.0.ffn_gate_exps.weight", gguf.TensorTypeF16, []uint64{32, 16, 2}),
+ })
+
+ result, err := (gptossMigrator{}).Migrate(src)
+ if err != nil {
+ t.Fatalf("Migrate() error = %v", err)
+ }
+ if got := result.ModelKV["gpt-oss.expert_feed_forward_length"]; got != uint32(16) {
+ t.Fatalf("expert_feed_forward_length = %v, want 16", got)
+ }
+}
+
+func fixtureSourceModel(t *testing.T, kv outKV, tensors []*outTensor) *SourceModel {
+ t.Helper()
+
+ f, err := os.CreateTemp(t.TempDir(), "source-*.gguf")
+ if err != nil {
+ t.Fatalf("CreateTemp() error = %v", err)
+ }
+ defer f.Close()
+
+ if err := writeGGUF(f, kv, tensors); err != nil {
+ t.Fatalf("WriteGGUF() error = %v", err)
+ }
+
+ g, err := gguf.Open(f.Name())
+ if err != nil {
+ t.Fatalf("gguf.Open(%s) error = %v", f.Name(), err)
+ }
+ t.Cleanup(func() { g.Close() })
+
+ return &SourceModel{
+ GGUFPath: f.Name(),
+ GGUF: g,
+ GGUFData: g.ReaderAt(),
+ GGUFDataOffset: g.TensorDataOffset(),
+ }
+}
+
+func readConfigLayer(t *testing.T, digest string) model.ConfigV2 {
+ t.Helper()
+
+ configPath, err := manifest.BlobsPath(digest)
+ if err != nil {
+ t.Fatalf("BlobsPath(config) error = %v", err)
+ }
+ configFile, err := os.Open(configPath)
+ if err != nil {
+ t.Fatalf("Open(config) error = %v", err)
+ }
+ defer configFile.Close()
+
+ var config model.ConfigV2
+ if err := json.NewDecoder(configFile).Decode(&config); err != nil {
+ t.Fatalf("Decode(config) error = %v", err)
+ }
+ return config
+}
+
+func openGGUFLayer(t *testing.T, digest string) *gguf.File {
+ t.Helper()
+
+ path, err := manifest.BlobsPath(digest)
+ if err != nil {
+ t.Fatalf("BlobsPath(%s) error = %v", digest, err)
+ }
+ f, err := gguf.Open(path)
+ if err != nil {
+ t.Fatalf("gguf.Open(%s) error = %v", path, err)
+ }
+ return f
+}
+
+type testCompatMigrator struct{}
+
+func (testCompatMigrator) NeedsMigration(*SourceModel) bool {
+ return true
+}
+
+func (testCompatMigrator) Migrate(src *SourceModel) (*Result, error) {
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ kv := outKV{}
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+ kv[keyValue.Key] = normalizeGGUFValue(keyValue.Any())
+ }
+ if kv.String("general.architecture") == "" {
+ kv["general.architecture"] = "testcompat"
+ }
+
+ out := make([]*outTensor, 0, len(tensors))
+ for _, tensor := range tensors {
+ out = append(out, copyTensor(tensor.name, tensor))
+ }
+
+ return &Result{
+ ModelKV: kv,
+ ModelTensors: out,
+ }, nil
+}
+
+type countingCompatMigrator struct {
+ calls *atomic.Int32
+}
+
+func (countingCompatMigrator) NeedsMigration(*SourceModel) bool {
+ return true
+}
+
+func (m countingCompatMigrator) Migrate(src *SourceModel) (*Result, error) {
+ m.calls.Add(1)
+ time.Sleep(50 * time.Millisecond)
+ return testCompatMigrator{}.Migrate(src)
+}
+
+func overrideAvailableSpace(t *testing.T, fn func(string) (uint64, error)) {
+ t.Helper()
+
+ old := availableSpaceForPath
+ availableSpaceForPath = fn
+ t.Cleanup(func() { availableSpaceForPath = old })
+}
+
+func registerTestCompatMigrator(t *testing.T) {
+ t.Helper()
+
+ const key = "testcompat"
+ old, ok := migratorsByArchitecture[key]
+ migratorsByArchitecture[key] = []Migrator{testCompatMigrator{}}
+ t.Cleanup(func() {
+ if ok {
+ migratorsByArchitecture[key] = old
+ } else {
+ delete(migratorsByArchitecture, key)
+ }
+ })
+}
+
+func registerCountingCompatMigrator(t *testing.T, calls *atomic.Int32) {
+ t.Helper()
+
+ const key = "testcompat"
+ old, ok := migratorsByArchitecture[key]
+ migratorsByArchitecture[key] = []Migrator{countingCompatMigrator{calls: calls}}
+ t.Cleanup(func() {
+ if ok {
+ migratorsByArchitecture[key] = old
+ } else {
+ delete(migratorsByArchitecture, key)
+ }
+ })
+}
+
+func wrapSourceManifestAsList(t *testing.T, name model.Name) {
+ t.Helper()
+
+ data, err := manifest.ReadManifestData(name)
+ if err != nil {
+ t.Fatalf("ReadManifestData(source) error = %v", err)
+ }
+ var child manifest.Manifest
+ if err := json.Unmarshal(data, &child); err != nil {
+ t.Fatalf("unmarshal child manifest: %v", err)
+ }
+ if err := manifest.FillMetadata(&child); err != nil {
+ t.Fatalf("FillMetadata(child) error = %v", err)
+ }
+ ref, err := manifestReferenceForChild(&child)
+ if err != nil {
+ t.Fatalf("manifestReferenceForChild() error = %v", err)
+ }
+ parent := manifest.Manifest{
+ SchemaVersion: 2,
+ MediaType: manifest.MediaTypeManifestList,
+ Manifests: []manifest.Manifest{ref},
+ }
+ parentData, err := json.Marshal(parent)
+ if err != nil {
+ t.Fatalf("marshal parent manifest: %v", err)
+ }
+ if err := manifest.WriteManifestData(name, parentData); err != nil {
+ t.Fatalf("WriteManifestData(parent) error = %v", err)
+ }
+}
+
+type sourceManifestInput struct {
+ config model.ConfigV2
+ modelKV outKV
+ modelTensors []*outTensor
+ projectorKV outKV
+ projectorTensors []*outTensor
+ template string
+ adapter string
+}
+
+func writeSourceManifest(t *testing.T, name model.Name, input sourceManifestInput) {
+ t.Helper()
+
+ modelLayer := writeFixtureGGUFLayer(t, input.modelKV, input.modelTensors)
+
+ layers := []manifest.Layer{modelLayer}
+ if len(input.projectorTensors) > 0 {
+ projectorLayer := writeFixtureGGUFLayer(t, input.projectorKV, input.projectorTensors)
+ projectorLayer.MediaType = "application/vnd.ollama.image.projector"
+ layers = append(layers, projectorLayer)
+ }
+ if input.template != "" {
+ layer, err := manifest.NewLayer(strings.NewReader(input.template), "application/vnd.ollama.image.template")
+ if err != nil {
+ t.Fatalf("manifest.NewLayer(template) error = %v", err)
+ }
+ layers = append(layers, layer)
+ }
+ if input.adapter != "" {
+ layer, err := manifest.NewLayer(strings.NewReader(input.adapter), "application/vnd.ollama.image.adapter")
+ if err != nil {
+ t.Fatalf("manifest.NewLayer(adapter) error = %v", err)
+ }
+ layers = append(layers, layer)
+ }
+
+ configLayer, err := newConfigLayer(input.config)
+ if err != nil {
+ t.Fatalf("newConfigLayer() error = %v", err)
+ }
+ if err := manifest.WriteManifest(name, configLayer, layers); err != nil {
+ t.Fatalf("WriteManifest() error = %v", err)
+ }
+}
+
+func writeFixtureGGUFLayer(t *testing.T, kv outKV, tensors []*outTensor) manifest.Layer {
+ t.Helper()
+
+ f, err := os.CreateTemp(t.TempDir(), "fixture-*.gguf")
+ if err != nil {
+ t.Fatalf("CreateTemp() error = %v", err)
+ }
+ defer os.Remove(f.Name())
+ defer f.Close()
+
+ if err := writeGGUF(f, kv, tensors); err != nil {
+ t.Fatalf("WriteGGUF() error = %v", err)
+ }
+ if _, err := f.Seek(0, io.SeekStart); err != nil {
+ t.Fatalf("Seek() error = %v", err)
+ }
+
+ layer, err := manifest.NewLayer(f, "application/vnd.ollama.image.model")
+ if err != nil {
+ t.Fatalf("manifest.NewLayer(model) error = %v", err)
+ }
+ return layer
+}
+
+func fixtureTensor(name string, kind gguf.TensorType, shape []uint64) *outTensor {
+ return &outTensor{
+ Name: name,
+ Kind: uint32(kind),
+ Shape: shape,
+ WriterTo: bytes.NewReader(make([]byte, tensorBytes(kind, shape))),
+ }
+}
+
+func tensorBytes(kind gguf.TensorType, shape []uint64) int {
+ var values uint64 = 1
+ for _, dim := range shape {
+ values *= dim
+ }
+ return int(float64(values) * kind.NumBytes())
+}
+
+func writeTensorF32(t *testing.T, tensor *outTensor) []float32 {
+ t.Helper()
+
+ var b bytes.Buffer
+ if _, err := tensor.WriterTo.WriteTo(&b); err != nil {
+ t.Fatalf("WriteTo(%s) error = %v", tensor.Name, err)
+ }
+ if b.Len()%4 != 0 {
+ t.Fatalf("WriteTo(%s) produced %d bytes, not f32 aligned", tensor.Name, b.Len())
+ }
+
+ out := make([]float32, b.Len()/4)
+ for i := range out {
+ out[i] = math.Float32frombits(binary.LittleEndian.Uint32(b.Bytes()[i*4:]))
+ }
+ return out
+}
+
+func writeTensorF16(t *testing.T, tensor *outTensor) []float32 {
+ t.Helper()
+
+ var b bytes.Buffer
+ if _, err := tensor.WriterTo.WriteTo(&b); err != nil {
+ t.Fatalf("WriteTo(%s) error = %v", tensor.Name, err)
+ }
+ if b.Len()%2 != 0 {
+ t.Fatalf("WriteTo(%s) produced %d bytes, not f16 aligned", tensor.Name, b.Len())
+ }
+
+ out := make([]float32, b.Len()/2)
+ for i := range out {
+ out[i] = float16.Frombits(binary.LittleEndian.Uint16(b.Bytes()[i*2:])).Float32()
+ }
+ return out
+}
+
+func sourceTensorF16(name string, shape []uint64, values []float32) *sourceTensor {
+ raw := make([]byte, len(values)*2)
+ for i, value := range values {
+ putF16(raw[i*2:], value)
+ }
+
+ return &sourceTensor{
+ readerAt: bytes.NewReader(raw),
+ info: gguf.TensorInfo{
+ Name: name,
+ Shape: shape,
+ Type: gguf.TensorTypeF16,
+ },
+ name: name,
+ shape: shape,
+ }
+}
+
+func putF16(b []byte, v float32) {
+ binary.LittleEndian.PutUint16(b, float16.Fromfloat32(v).Bits())
+}
+
+func TestEnsureLocalCompatibilityMigrationRepairsDanglingV2Entry(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+ registerTestCompatMigrator(t)
+
+ source := model.ParseName("registry.ollama.ai/library/testcompat:latest")
+ writeSourceManifest(t, source, sourceManifestInput{
+ config: model.ConfigV2{
+ ModelFormat: "gguf",
+ ModelFamily: "testcompat",
+ ModelFamilies: []string{"testcompat"},
+ },
+ modelKV: outKV{
+ "general.architecture": "testcompat",
+ "tokenizer.ggml.tokens": []string{"x"},
+ },
+ modelTensors: []*outTensor{
+ fixtureTensor("token_embd.weight", gguf.TensorTypeF16, []uint64{1, 8}),
+ },
+ })
+
+ // Simulate a store damaged by a pre-manifest-list daemon: the v2 entry
+ // dangles because the old garbage collector removed the manifest-list
+ // document blob, while the legacy source manifest survives.
+ sourceData, err := manifest.ReadManifestData(source)
+ if err != nil {
+ t.Fatalf("ReadManifestData(source) error = %v", err)
+ }
+ if err := manifest.WriteLegacyManifestData(source, sourceData); err != nil {
+ t.Fatalf("WriteLegacyManifestData(source) error = %v", err)
+ }
+
+ v2Path, err := manifest.V2PathForName(source)
+ if err != nil {
+ t.Fatalf("V2PathForName(source) error = %v", err)
+ }
+ if err := os.MkdirAll(filepath.Dir(v2Path), 0o755); err != nil {
+ t.Fatalf("mkdir v2 dir: %v", err)
+ }
+ if err := os.RemoveAll(v2Path); err != nil {
+ t.Fatalf("remove v2 entry: %v", err)
+ }
+ missing := filepath.Join("..", "..", "blobs", "sha256-"+strings.Repeat("0", 64))
+ if err := os.Symlink(missing, v2Path); err != nil {
+ t.Fatalf("symlink dangling v2 entry: %v", err)
+ }
+
+ migrated, err := EnsureLocalCompatibilityMigration(source)
+ if err != nil {
+ t.Fatalf("EnsureLocalCompatibilityMigration after damage error = %v", err)
+ }
+ if !migrated {
+ t.Fatal("expected damaged store to re-migrate")
+ }
+
+ raw, err := manifest.ReadManifestData(source)
+ if err != nil {
+ t.Fatalf("ReadManifestData after repair error = %v", err)
+ }
+ var parent manifest.Manifest
+ if err := json.Unmarshal(raw, &parent); err != nil {
+ t.Fatalf("unmarshal repaired parent manifest: %v", err)
+ }
+ if parent.MediaType != manifest.MediaTypeManifestList {
+ t.Fatalf("repaired manifest mediaType = %q, want manifest list", parent.MediaType)
+ }
+ if _, err := manifest.ParseNamedManifestForRunner(source, manifest.RunnerLlamaCPP); err != nil {
+ t.Fatalf("expected repaired llamacpp child to resolve: %v", err)
+ }
+}
diff --git a/compatmigrate/mistral_pixtral.go b/compatmigrate/mistral_pixtral.go
new file mode 100644
index 000000000..c8674a4c4
--- /dev/null
+++ b/compatmigrate/mistral_pixtral.go
@@ -0,0 +1,227 @@
+package compatmigrate
+
+import (
+ "fmt"
+ "slices"
+ "strings"
+
+ "github.com/ollama/ollama/fs/gguf"
+)
+
+type mistralPixtralMigrator struct{}
+
+// Mirrors detect_ollama_mistral3 in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (mistralPixtralMigrator) NeedsMigration(src *SourceModel) bool {
+ if src.GGUF.KeyValue("general.architecture").String() != "mistral3" {
+ return false
+ }
+
+ return sourceTensorHasPrefix(src, "v.") ||
+ sourceTensorHasPrefix(src, "mm.") ||
+ src.GGUF.KeyValue("rope.scaling.beta_fast").Valid() ||
+ src.GGUF.KeyValue("rope.scaling.mscale_all_dim").Valid() ||
+ src.GGUF.KeyValue("rope.scaling_beta").Valid()
+}
+
+func (mistralPixtralMigrator) Migrate(src *SourceModel) (*Result, error) {
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ imageToken := src.GGUF.KeyValue("image_token_index")
+ if !imageToken.Valid() {
+ return nil, fmt.Errorf("%s has no mistral3.image_token_index", src.Source.DisplayShortest())
+ }
+
+ visionHeads := src.GGUF.KeyValue("vision.attention.head_count").Uint()
+ if visionHeads == 0 {
+ return nil, fmt.Errorf("%s has no mistral3.vision.attention.head_count", src.Source.DisplayShortest())
+ }
+
+ var tokenEmbedding *sourceTensor
+ var modelTensors []*outTensor
+ var projectorTensors []*outTensor
+ for _, tensor := range tensors {
+ if tensor.name == "token_embd.weight" {
+ tokenEmbedding = tensor
+ }
+
+ if isMistralPixtralProjectorTensor(tensor.name) {
+ projectorTensors = append(projectorTensors, copyMistralPixtralProjectorTensor(tensor, visionHeads))
+ continue
+ }
+
+ modelTensors = append(modelTensors, copyTensor(tensor.name, tensor))
+ }
+ if tokenEmbedding == nil {
+ return nil, fmt.Errorf("%s has no token_embd.weight tensor", src.Source.DisplayShortest())
+ }
+
+ // The clean pull/re-create path gets this vector from the original HF
+ // embedding matrix before quantization. Local migration is intentionally a
+ // best-effort compatibility path, so we derive it from the user's installed
+ // GGUF row. For q4/q6 installs this preserves the old local-model quality
+ // instead of silently requiring a full model download on first load.
+ imageBreak, err := copyTensorRowF32("v.token_embd.img_break", tokenEmbedding, imageToken.Uint())
+ if err != nil {
+ return nil, err
+ }
+ projectorTensors = append(projectorTensors, imageBreak)
+
+ return &Result{
+ ModelKV: mistralPixtralModelKV(src),
+ ModelTensors: modelTensors,
+ ProjectorKV: mistralPixtralProjectorKV(src),
+ ProjectorTensors: projectorTensors,
+ }, nil
+}
+
+func mistralPixtralModelKV(src *SourceModel) outKV {
+ modelKV := outKV{}
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+
+ key := keyValue.Key
+ value := normalizeGGUFValue(keyValue.Any())
+ switch {
+ case key == "general.architecture":
+ modelKV[key] = "mistral3"
+ case strings.HasPrefix(key, "general."), strings.HasPrefix(key, "tokenizer."):
+ modelKV[key] = value
+ case strings.HasPrefix(key, "mistral3.vision."),
+ strings.HasPrefix(key, "mistral3.mm."),
+ key == "mistral3.image_token_index",
+ key == "mistral3.spatial_merge_size":
+ continue
+ case key == "mistral3.rope.scaling.beta_fast":
+ modelKV["mistral3.rope.scaling.yarn_beta_fast"] = value
+ case key == "mistral3.rope.scaling.beta_slow":
+ modelKV["mistral3.rope.scaling.yarn_beta_slow"] = value
+ case key == "mistral3.rope.scaling.mscale":
+ if _, ok := modelKV["mistral3.rope.scaling.yarn_log_multiplier"]; !ok {
+ modelKV["mistral3.rope.scaling.yarn_log_multiplier"] = value
+ }
+ case key == "mistral3.rope.scaling.mscale_all_dim":
+ modelKV["mistral3.rope.scaling.yarn_log_multiplier"] = value
+ case key == "mistral3.rope.scaling_beta":
+ modelKV["mistral3.attention.temperature_scale"] = value
+ case strings.HasPrefix(key, "mistral3."):
+ modelKV[key] = value
+ }
+ }
+ if _, ok := modelKV["general.architecture"]; !ok {
+ modelKV["general.architecture"] = "mistral3"
+ }
+ return modelKV
+}
+
+func mistralPixtralProjectorKV(src *SourceModel) outKV {
+ eps := float32(src.GGUF.KeyValue("vision.attention.layer_norm_epsilon").Float())
+ if eps == 0 {
+ eps = 1e-5 // Mirrors the Pixtral config's default vision attention layer-norm epsilon.
+ }
+
+ return outKV{
+ "general.architecture": "clip",
+ "clip.has_vision_encoder": true,
+ "clip.projector_type": "pixtral",
+ "clip.vision.projection_dim": uint32(src.GGUF.KeyValue("feed_forward_length").Uint()),
+ "clip.vision.image_size": uint32(src.GGUF.KeyValue("vision.image_size").Uint()),
+ "clip.vision.patch_size": uint32(src.GGUF.KeyValue("vision.patch_size").Uint()),
+ "clip.vision.embedding_length": uint32(src.GGUF.KeyValue("vision.embedding_length").Uint()),
+ "clip.vision.feed_forward_length": uint32(src.GGUF.KeyValue("vision.feed_forward_length").Uint()),
+ "clip.vision.block_count": uint32(src.GGUF.KeyValue("vision.block_count").Uint()),
+ "clip.vision.attention.head_count": uint32(src.GGUF.KeyValue("vision.attention.head_count").Uint()),
+ "clip.vision.attention.layer_norm_epsilon": eps,
+ "clip.vision.image_mean": []float32{0.48145466, 0.4578275, 0.40821073},
+ "clip.vision.image_std": []float32{0.26862954, 0.26130258, 0.27577711},
+ "clip.rope.freq_base": float32(src.GGUF.KeyValue("vision.rope.freq_base").Float()),
+ "clip.use_silu": true,
+ "clip.vision.spatial_merge_size": uint32(src.GGUF.KeyValue("spatial_merge_size").Uint()),
+ }
+}
+
+func isMistralPixtralProjectorTensor(name string) bool {
+ return strings.HasPrefix(name, "v.") || strings.HasPrefix(name, "mm.")
+}
+
+func copyMistralPixtralProjectorTensor(t *sourceTensor, visionHeads uint64) *outTensor {
+ name := mistralPixtralProjectorTensorName(t.name)
+ writer := t.Clone()
+ outType := compatOutputTensorType(name, t.name, t.info.Type)
+
+ // The generic compat policy preserves patch embeddings as F32 for several
+ // projector families, but Pixtral/Mistral clean imports keep this kernel in
+ // the installed F16 form. Preserve it here so the no-pull path matches the
+ // clean pulled artifact.
+ if name == "v.patch_embd.weight" && t.info.Type == gguf.TensorTypeF16 {
+ outType = gguf.TensorTypeF16
+ }
+
+ if isMistralPixtralVisionQK(name) {
+ writer.SetRepacker(func(_ string, data []float32, shape []uint64) ([]float32, error) {
+ return mistralPixtralVisionQKRepack(data, shape, visionHeads)
+ })
+ }
+ if outType != t.info.Type {
+ writer.SetOutputType(outType)
+ }
+
+ return &outTensor{
+ Name: name,
+ Kind: uint32(outType),
+ Shape: slices.Clone(t.shape),
+ WriterTo: writer,
+ }
+}
+
+func isMistralPixtralVisionQK(name string) bool {
+ return strings.HasPrefix(name, "v.blk.") &&
+ (strings.HasSuffix(name, ".attn_q.weight") || strings.HasSuffix(name, ".attn_k.weight"))
+}
+
+func mistralPixtralVisionQKRepack(data []float32, shape []uint64, heads uint64) ([]float32, error) {
+ if heads == 0 {
+ return nil, fmt.Errorf("mistral pixtral q/k repack has zero attention heads")
+ }
+ if len(shape) != 2 {
+ return nil, fmt.Errorf("mistral pixtral q/k repack requires a 2D tensor, got %v", shape)
+ }
+ if shape[0]%(heads*2) != 0 {
+ return nil, fmt.Errorf("mistral pixtral q/k shape %v is not divisible by heads*2=%d", shape, heads*2)
+ }
+
+ cols := int(shape[0])
+ rows := int(shape[1])
+ if len(data) != cols*rows {
+ return nil, fmt.Errorf("mistral pixtral q/k tensor has %d values, expected %d for shape %v", len(data), cols*rows, shape)
+ }
+
+ inner := cols / int(heads) / 2
+ out := make([]float32, 0, len(data))
+ for head := range int(heads) {
+ for innerIndex := range inner {
+ for pair := range 2 {
+ start := (((head*2 + pair) * inner) + innerIndex) * rows
+ out = append(out, data[start:start+rows]...)
+ }
+ }
+ }
+ return out, nil
+}
+
+func mistralPixtralProjectorTensorName(name string) string {
+ name = strings.Replace(name, "v.patch_conv", "v.patch_embd", 1)
+ name = strings.Replace(name, "v.encoder_norm", "v.pre_ln", 1)
+ name = strings.Replace(name, "attn_output", "attn_out", 1)
+ name = strings.Replace(name, "attn_norm", "ln1", 1)
+ name = strings.Replace(name, "ffn_norm", "ln2", 1)
+ name = strings.Replace(name, "mm.linear_1", "mm.1", 1)
+ name = strings.Replace(name, "mm.linear_2", "mm.2", 1)
+ name = strings.Replace(name, "mm.norm", "mm.input_norm", 1)
+ name = strings.Replace(name, "mm.patch_merger.merging_layer", "mm.patch_merger", 1)
+ return name
+}
diff --git a/compatmigrate/nemotron3.go b/compatmigrate/nemotron3.go
new file mode 100644
index 000000000..f27570121
--- /dev/null
+++ b/compatmigrate/nemotron3.go
@@ -0,0 +1,445 @@
+package compatmigrate
+
+import (
+ "fmt"
+ "math"
+ "slices"
+ "strings"
+)
+
+type nemotron3Migrator struct{}
+
+// Mirrors detect_ollama_nemotron_h_omni in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (nemotron3Migrator) NeedsMigration(src *SourceModel) bool {
+ if src.GGUF.KeyValue("general.architecture").String() != "nemotron_h_omni" {
+ return false
+ }
+ return sourceTensorHasPrefix(src, "v.") ||
+ sourceTensorHasPrefix(src, "a.") ||
+ sourceTensorHasPrefix(src, "mm.")
+}
+
+func (nemotron3Migrator) Migrate(src *SourceModel) (*Result, error) {
+ if arch := src.GGUF.KeyValue("general.architecture").String(); arch != "nemotron_h_omni" {
+ return nil, errUnsupportedFamily
+ }
+
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ var modelTensors []*outTensor
+ var projectorTensors []*outTensor
+ for _, tensor := range tensors {
+ if isNemotron3AudioTensor(tensor.name) {
+ continue
+ }
+ if !isNemotron3ProjectorTensor(tensor.name) {
+ modelTensors = append(modelTensors, copyTensor(tensor.name, tensor))
+ continue
+ }
+
+ projector, err := nemotron3ProjectorTensor(src, tensor)
+ if err != nil {
+ return nil, err
+ }
+ projectorTensors = append(projectorTensors, projector...)
+ }
+
+ return &Result{
+ ModelKV: nemotron3ModelKV(src),
+ ModelTensors: modelTensors,
+ ProjectorKV: nemotron3ProjectorKV(src),
+ ProjectorTensors: projectorTensors,
+ Renderer: "nemotron-3-nano",
+ Parser: "nemotron-3-nano",
+ }, nil
+}
+
+func nemotron3TextArchitecture(src *SourceModel) string {
+ if src.GGUF.KeyValue("expert_count").Uint() > 0 || src.GGUF.KeyValue("expert_used_count").Uint() > 0 {
+ return "nemotron_h_moe"
+ }
+ return "nemotron_h"
+}
+
+func nemotron3ModelKV(src *SourceModel) outKV {
+ arch := nemotron3TextArchitecture(src)
+ out := outKV{"general.architecture": arch}
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+
+ key := keyValue.Key
+ value := normalizeGGUFValue(keyValue.Any())
+ switch {
+ case key == "general.architecture":
+ continue
+ case strings.HasPrefix(key, "general."), strings.HasPrefix(key, "tokenizer."):
+ out[key] = value
+ case strings.HasPrefix(key, "nemotron_h_omni.vision."), strings.HasPrefix(key, "nemotron_h_omni.audio."):
+ continue
+ case strings.HasPrefix(key, "nemotron_h_omni."):
+ out[arch+"."+strings.TrimPrefix(key, "nemotron_h_omni.")] = value
+ }
+ }
+ return out
+}
+
+func nemotron3ProjectorKV(src *SourceModel) outKV {
+ imageSize := uint32(src.GGUF.KeyValue("vision.image_size").Uint())
+ if imageSize == 0 {
+ imageSize = 512
+ }
+ patchSize := uint32(src.GGUF.KeyValue("vision.patch_size").Uint())
+ if patchSize == 0 {
+ patchSize = 16
+ }
+ embeddingLength := uint32(src.GGUF.KeyValue("vision.embedding_length").Uint())
+ if embeddingLength == 0 {
+ embeddingLength = 1280
+ }
+ feedForwardLength := uint32(src.GGUF.KeyValue("vision.feed_forward_length").Uint())
+ if feedForwardLength == 0 {
+ feedForwardLength = embeddingLength * 4
+ }
+ headCount := uint32(src.GGUF.KeyValue("vision.attention.head_count").Uint())
+ if headCount == 0 {
+ headCount = 16
+ }
+ eps := float32(src.GGUF.KeyValue("vision.attention.layer_norm_epsilon").Float())
+ if eps == 0 {
+ eps = 1e-6
+ }
+ scaleFactor := uint32(src.GGUF.KeyValue("vision.projector.scale_factor").Uint())
+ if scaleFactor == 0 {
+ scaleFactor = 2
+ }
+
+ out := outKV{
+ "general.architecture": "clip",
+ "clip.has_vision_encoder": true,
+ "clip.vision.projector_type": "nemotron_v2_vl",
+ "clip.vision.block_count": uint32(src.GGUF.KeyValue("vision.block_count").Uint()),
+ "clip.vision.embedding_length": embeddingLength,
+ "clip.vision.feed_forward_length": feedForwardLength,
+ "clip.vision.attention.head_count": headCount,
+ "clip.vision.attention.layer_norm_epsilon": eps,
+ "clip.vision.patch_size": patchSize,
+ "clip.vision.image_size": imageSize,
+ "clip.vision.num_channels": uint32(3),
+ "clip.vision.image_mean": []float32{0.48145466, 0.4578275, 0.40821073},
+ "clip.vision.image_std": []float32{0.26862954, 0.26130258, 0.27577711},
+ "clip.vision.projector.scale_factor": scaleFactor,
+ "clip.vision.projection_dim": uint32(src.GGUF.KeyValue("embedding_length").Uint()),
+ "clip.use_gelu": true,
+ }
+
+ for _, key := range []string{
+ "vision.max_tiles",
+ "vision.min_num_patches",
+ "vision.max_num_patches",
+ "vision.image_token_id",
+ "vision.image_start_token_id",
+ "vision.image_end_token_id",
+ } {
+ if value := src.GGUF.KeyValue(key); value.Valid() {
+ out["clip."+key] = normalizeGGUFValue(value.Any())
+ }
+ }
+ if mean := src.GGUF.KeyValue("vision.image_mean"); mean.Valid() {
+ out["clip.vision.image_mean"] = normalizeGGUFValue(mean.Any())
+ }
+ if std := src.GGUF.KeyValue("vision.image_std"); std.Valid() {
+ out["clip.vision.image_std"] = normalizeGGUFValue(std.Any())
+ }
+
+ return out
+}
+
+func isNemotron3ProjectorTensor(name string) bool {
+ return strings.HasPrefix(name, "v.") || (strings.HasPrefix(name, "mm.") && !strings.HasPrefix(name, "mm.a."))
+}
+
+func isNemotron3AudioTensor(name string) bool {
+ return strings.HasPrefix(name, "a.") || strings.HasPrefix(name, "mm.a.")
+}
+
+func nemotron3ProjectorTensor(src *SourceModel, tensor *sourceTensor) ([]*outTensor, error) {
+ name := tensor.name
+ if strings.Contains(name, ".attn_qkv.") {
+ return splitSourceTensorDim(tensor, 0,
+ strings.Replace(name, "attn_qkv", "attn_q", 1),
+ strings.Replace(name, "attn_qkv", "attn_k", 1),
+ strings.Replace(name, "attn_qkv", "attn_v", 1),
+ )
+ }
+
+ name, shape, repacker := nemotron3ProjectorTensorTransform(src, tensor)
+ writer := tensor.Clone()
+ writer.shape = slices.Clone(shape)
+ if repacker != nil {
+ writer.SetRepacker(repacker)
+ }
+ outType := compatOutputTensorType(name, tensor.name, tensor.info.Type)
+ if outType != tensor.info.Type || repacker != nil {
+ writer.SetOutputType(outType)
+ }
+ return []*outTensor{{
+ Name: name,
+ Kind: uint32(outType),
+ Shape: shape,
+ WriterTo: writer,
+ }}, nil
+}
+
+func nemotron3ProjectorTensorTransform(src *SourceModel, tensor *sourceTensor) (string, []uint64, repacker) {
+ name := tensor.name
+ shape := slices.Clone(tensor.shape)
+ visionEmbedding := src.GGUF.KeyValue("vision.embedding_length").Uint()
+ if visionEmbedding == 0 {
+ visionEmbedding = 1280
+ }
+ patchSize := src.GGUF.KeyValue("vision.patch_size").Uint()
+ if patchSize == 0 {
+ patchSize = 16
+ }
+ imageSize := src.GGUF.KeyValue("vision.image_size").Uint()
+ if imageSize == 0 {
+ imageSize = 512
+ }
+ targetSide := imageSize / patchSize
+
+ switch name {
+ case "v.cls_embd":
+ name = "v.class_embd"
+ shape = normalizeNemotron3ClassEmbeddingShape(shape, visionEmbedding)
+ case "v.position_embd", "v.position_embd.weight":
+ name = "v.position_embd.weight"
+ shape = nemotron3PositionEmbeddingOutputShape(shape, visionEmbedding, targetSide)
+ return name, shape, func(name string, data []float32, sourceShape []uint64) ([]float32, error) {
+ return downsampleNemotron3PositionEmbedding(name, data, sourceShape, visionEmbedding, targetSide)
+ }
+ case "v.patch_embd.weight":
+ shape = nemotron3PatchEmbeddingOutputShape(shape, patchSize, 3, visionEmbedding)
+ return name, shape, func(name string, data []float32, sourceShape []uint64) ([]float32, error) {
+ return reshapeNemotron3PatchEmbedding(name, data, sourceShape, patchSize, 3, visionEmbedding)
+ }
+ case "mm.norm.weight":
+ name = "mm.model.mlp.0.weight"
+ case "mm.1.weight":
+ name = "mm.model.mlp.1.weight"
+ case "mm.2.weight":
+ name = "mm.model.mlp.3.weight"
+ }
+
+ return name, shape, nil
+}
+
+func normalizeNemotron3ClassEmbeddingShape(shape []uint64, embeddingLength uint64) []uint64 {
+ if len(shape) == 2 && embeddingLength > 0 && shape[0] != embeddingLength && shape[1] == embeddingLength {
+ return []uint64{shape[1], shape[0]}
+ }
+ return slices.Clone(shape)
+}
+
+func nemotron3PositionEmbeddingOutputShape(shape []uint64, embeddingLength, targetSide uint64) []uint64 {
+ if targetSide == 0 {
+ return slices.Clone(shape)
+ }
+ if embeddingLength == 0 {
+ if emb, _, ok := nemotron3PositionEmbeddingLayout(shape); ok {
+ embeddingLength = emb
+ }
+ }
+ if embeddingLength == 0 {
+ return slices.Clone(shape)
+ }
+ return []uint64{embeddingLength, targetSide * targetSide}
+}
+
+func nemotron3PositionEmbeddingLayout(shape []uint64) (embeddingLength, positions uint64, ok bool) {
+ switch len(shape) {
+ case 2:
+ if nemotron3SquareSide(shape[1]) > 0 {
+ return shape[0], shape[1], true
+ }
+ if nemotron3SquareSide(shape[0]) > 0 {
+ return shape[1], shape[0], true
+ }
+ case 3:
+ if shape[0] == 1 && nemotron3SquareSide(shape[1]) > 0 {
+ return shape[2], shape[1], true
+ }
+ if shape[2] == 1 && nemotron3SquareSide(shape[1]) > 0 {
+ return shape[0], shape[1], true
+ }
+ }
+ return 0, 0, false
+}
+
+func downsampleNemotron3PositionEmbedding(name string, data []float32, shape []uint64, embeddingLength, targetSide uint64) ([]float32, error) {
+ if targetSide == 0 {
+ return data, nil
+ }
+
+ detectedEmbedding, positions, ok := nemotron3PositionEmbeddingLayout(shape)
+ if !ok {
+ return nil, fmt.Errorf("downsample %s: unsupported position embedding shape %v", name, shape)
+ }
+ if embeddingLength == 0 {
+ embeddingLength = detectedEmbedding
+ }
+ if embeddingLength != detectedEmbedding {
+ return nil, fmt.Errorf("downsample %s: embedding length %d does not match source shape %v", name, embeddingLength, shape)
+ }
+ if uint64(len(data)) != embeddingLength*positions {
+ return nil, fmt.Errorf("downsample %s: data length %d does not match shape %v", name, len(data), shape)
+ }
+
+ sourceSide := nemotron3SquareSide(positions)
+ if sourceSide == 0 {
+ return nil, fmt.Errorf("downsample %s: position count %d is not square", name, positions)
+ }
+ if sourceSide == targetSide {
+ return normalizeNemotron3PositionEmbeddingData(data, shape, embeddingLength, positions), nil
+ }
+
+ sourceAt := func(pos, emb uint64) float32 {
+ switch len(shape) {
+ case 2:
+ if shape[0] == embeddingLength {
+ return data[emb+embeddingLength*pos]
+ }
+ return data[pos+positions*emb]
+ case 3:
+ if shape[0] == 1 {
+ return data[pos*embeddingLength+emb]
+ }
+ return data[emb*positions+pos]
+ default:
+ return 0
+ }
+ }
+
+ out := make([]float32, embeddingLength*targetSide*targetSide)
+ for y := range targetSide {
+ sourceY := nemotron3AlignCorners(float64(y), targetSide, sourceSide)
+ y0 := uint64(math.Floor(sourceY))
+ y1 := min(y0+1, sourceSide-1)
+ wy := float32(sourceY - float64(y0))
+ for x := range targetSide {
+ sourceX := nemotron3AlignCorners(float64(x), targetSide, sourceSide)
+ x0 := uint64(math.Floor(sourceX))
+ x1 := min(x0+1, sourceSide-1)
+ wx := float32(sourceX - float64(x0))
+
+ for emb := range embeddingLength {
+ v00 := sourceAt(y0*sourceSide+x0, emb)
+ v01 := sourceAt(y0*sourceSide+x1, emb)
+ v10 := sourceAt(y1*sourceSide+x0, emb)
+ v11 := sourceAt(y1*sourceSide+x1, emb)
+ top := v00*(1-wx) + v01*wx
+ bottom := v10*(1-wx) + v11*wx
+ out[emb+embeddingLength*(y*targetSide+x)] = top*(1-wy) + bottom*wy
+ }
+ }
+ }
+ return out, nil
+}
+
+func normalizeNemotron3PositionEmbeddingData(data []float32, shape []uint64, embeddingLength, positions uint64) []float32 {
+ if len(shape) == 2 && shape[0] == embeddingLength {
+ return data
+ }
+ out := make([]float32, embeddingLength*positions)
+ for pos := range positions {
+ for emb := range embeddingLength {
+ switch len(shape) {
+ case 2:
+ out[emb+embeddingLength*pos] = data[pos+positions*emb]
+ case 3:
+ if shape[0] == 1 {
+ out[emb+embeddingLength*pos] = data[pos*embeddingLength+emb]
+ } else {
+ out[emb+embeddingLength*pos] = data[emb*positions+pos]
+ }
+ }
+ }
+ }
+ return out
+}
+
+func nemotron3AlignCorners(target float64, targetSide, sourceSide uint64) float64 {
+ if targetSide <= 1 {
+ return 0
+ }
+ return target * float64(sourceSide-1) / float64(targetSide-1)
+}
+
+func nemotron3PatchEmbeddingOutputShape(shape []uint64, patchSize, channels, embeddingLength uint64) []uint64 {
+ if patchSize == 0 || channels == 0 {
+ return slices.Clone(shape)
+ }
+ flat := patchSize * patchSize * channels
+ if embeddingLength == 0 && len(shape) == 2 {
+ switch {
+ case shape[0] == flat:
+ embeddingLength = shape[1]
+ case shape[1] == flat:
+ embeddingLength = shape[0]
+ }
+ }
+ if embeddingLength == 0 {
+ return slices.Clone(shape)
+ }
+ return []uint64{patchSize, patchSize, channels, embeddingLength}
+}
+
+func reshapeNemotron3PatchEmbedding(name string, data []float32, shape []uint64, patchSize, channels, embeddingLength uint64) ([]float32, error) {
+ if len(shape) != 2 || patchSize == 0 || channels == 0 {
+ return data, nil
+ }
+ flat := patchSize * patchSize * channels
+ if embeddingLength == 0 {
+ switch {
+ case shape[0] == flat:
+ embeddingLength = shape[1]
+ case shape[1] == flat:
+ embeddingLength = shape[0]
+ default:
+ return data, nil
+ }
+ }
+ if uint64(len(data)) != flat*embeddingLength {
+ return nil, fmt.Errorf("reshape %s: data length %d does not match shape %v", name, len(data), shape)
+ }
+
+ out := make([]float32, len(data))
+ for emb := range embeddingLength {
+ for channel := range channels {
+ for y := range patchSize {
+ for x := range patchSize {
+ flatIndex := x + patchSize*(y+patchSize*channel)
+ dst := x + patchSize*(y+patchSize*(channel+channels*emb))
+ src := flatIndex + flat*emb
+ out[dst] = data[src]
+ }
+ }
+ }
+ }
+ return out, nil
+}
+
+func nemotron3SquareSide(n uint64) uint64 {
+ side := uint64(math.Sqrt(float64(n)))
+ if side*side == n {
+ return side
+ }
+ if (side+1)*(side+1) == n {
+ return side + 1
+ }
+ return 0
+}
diff --git a/compatmigrate/nemotron_h_moe.go b/compatmigrate/nemotron_h_moe.go
new file mode 100644
index 000000000..597f5deb4
--- /dev/null
+++ b/compatmigrate/nemotron_h_moe.go
@@ -0,0 +1,85 @@
+package compatmigrate
+
+import (
+ "strconv"
+ "strings"
+)
+
+type nemotronHMoeMigrator struct{}
+
+// Mirrors detect_ollama_nemotron_h_moe in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (nemotronHMoeMigrator) NeedsMigration(src *SourceModel) bool {
+ if src.GGUF.KeyValue("general.architecture").String() != "nemotron_h_moe" {
+ return false
+ }
+ return sourceTensorHasPrefix(src, "blk.1.ffn_latent_in") ||
+ sourceTensorHasPrefix(src, "blk.0.ffn_latent_in") ||
+ sourceTensorHasPrefix(src, "mtp.")
+}
+
+func (nemotronHMoeMigrator) Migrate(src *SourceModel) (*Result, error) {
+ if src.GGUF.KeyValue("general.architecture").String() != "nemotron_h_moe" {
+ return nil, errUnsupportedFamily
+ }
+
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ modelTensors := make([]*outTensor, 0, len(tensors))
+ for _, tensor := range tensors {
+ if strings.HasPrefix(tensor.name, "mtp.") {
+ continue
+ }
+ modelTensors = append(modelTensors, copyTensor(nemotronHMoeTensorName(tensor.name), tensor))
+ }
+
+ modelKV := nemotronHMoeModelKV(src)
+ if !rawGGUFKeyExists(src.GGUF, "nemotron_h_moe.moe_latent_size") {
+ if latentSize, ok := nemotronHMoELatentSize(src); ok {
+ modelKV["nemotron_h_moe.moe_latent_size"] = latentSize
+ }
+ }
+
+ return &Result{
+ ModelKV: modelKV,
+ ModelTensors: modelTensors,
+ }, nil
+}
+
+func nemotronHMoeModelKV(src *SourceModel) outKV {
+ out := outKV{}
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+
+ key := keyValue.Key
+ value := normalizeGGUFValue(keyValue.Any())
+ switch {
+ case strings.HasPrefix(key, "general."), strings.HasPrefix(key, "tokenizer."), strings.HasPrefix(key, "nemotron_h_moe."):
+ out[key] = value
+ }
+ }
+ if _, ok := out["general.architecture"]; !ok {
+ out["general.architecture"] = "nemotron_h_moe"
+ }
+ return out
+}
+
+func nemotronHMoeTensorName(name string) string {
+ name = strings.ReplaceAll(name, ".ffn_latent_in", ".ffn_latent_down")
+ return strings.ReplaceAll(name, ".ffn_latent_out", ".ffn_latent_up")
+}
+
+func nemotronHMoELatentSize(src *SourceModel) (uint32, bool) {
+ for i := range 1024 {
+ shape, ok := sourceTensorShape(src, "blk."+strconv.Itoa(i)+".ffn_latent_in.weight")
+ if !ok || len(shape) < 2 {
+ continue
+ }
+ return uint32(shape[1]), true
+ }
+ return 0, false
+}
diff --git a/compatmigrate/olmo3.go b/compatmigrate/olmo3.go
new file mode 100644
index 000000000..539ca1361
--- /dev/null
+++ b/compatmigrate/olmo3.go
@@ -0,0 +1,50 @@
+package compatmigrate
+
+import (
+ "strings"
+)
+
+type olmo3Migrator struct{}
+
+// Mirrors the olmo3 arch gate for handle_olmo3 in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (olmo3Migrator) NeedsMigration(src *SourceModel) bool {
+ return src.GGUF.KeyValue("general.architecture").String() == "olmo3"
+}
+
+func (olmo3Migrator) Migrate(src *SourceModel) (*Result, error) {
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ modelTensors := make([]*outTensor, 0, len(tensors))
+ for _, tensor := range tensors {
+ modelTensors = append(modelTensors, copyTensor(tensor.name, tensor))
+ }
+
+ modelKV := outKV{}
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+
+ key := keyValue.Key
+ value := normalizeGGUFValue(keyValue.Any())
+ switch {
+ case key == "general.architecture":
+ modelKV[key] = "olmo2"
+ case strings.HasPrefix(key, "olmo3."):
+ modelKV["olmo2."+strings.TrimPrefix(key, "olmo3.")] = value
+ case strings.HasPrefix(key, "general."), strings.HasPrefix(key, "tokenizer."):
+ modelKV[key] = value
+ }
+ }
+ if _, ok := modelKV["general.architecture"]; !ok {
+ modelKV["general.architecture"] = "olmo2"
+ }
+
+ return &Result{
+ ModelKV: modelKV,
+ ModelTensors: modelTensors,
+ }, nil
+}
diff --git a/compatmigrate/qwen25vl.go b/compatmigrate/qwen25vl.go
new file mode 100644
index 000000000..75c438f83
--- /dev/null
+++ b/compatmigrate/qwen25vl.go
@@ -0,0 +1,152 @@
+package compatmigrate
+
+import (
+ "strings"
+)
+
+type qwen25VLMigrator struct{}
+
+// Mirrors detect_ollama_qwen25vl in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (qwen25VLMigrator) NeedsMigration(src *SourceModel) bool {
+ return src.GGUF.KeyValue("general.architecture").String() == "qwen25vl"
+}
+
+func (qwen25VLMigrator) Migrate(src *SourceModel) (*Result, error) {
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ var modelTensors []*outTensor
+ var projectorTensors []*outTensor
+ for _, tensor := range tensors {
+ if strings.HasPrefix(tensor.name, "v.") || strings.HasPrefix(tensor.name, "mm.") {
+ name := qwen25VLProjectorTensorName(tensor.name)
+ switch {
+ case strings.Contains(name, "patch_embd_0.weight"):
+ projectorTensors = append(projectorTensors, copyTensor(strings.Replace(name, "patch_embd_0.weight", "patch_embd.weight", 1), tensor))
+ case strings.Contains(name, "patch_embd_1.weight"):
+ projectorTensors = append(projectorTensors, copyTensor(strings.Replace(name, "patch_embd_1.weight", "patch_embd.weight.1", 1), tensor))
+ case strings.Contains(name, "attn_qkv"):
+ split, err := splitSourceTensorDim(tensor, 0,
+ strings.Replace(name, "attn_qkv", "attn_q", 1),
+ strings.Replace(name, "attn_qkv", "attn_k", 1),
+ strings.Replace(name, "attn_qkv", "attn_v", 1),
+ )
+ if err != nil {
+ return nil, err
+ }
+ projectorTensors = append(projectorTensors, split...)
+ default:
+ projectorTensors = append(projectorTensors, copyTensor(name, tensor))
+ }
+ continue
+ }
+ modelTensors = append(modelTensors, copyTensor(tensor.name, tensor))
+ }
+
+ modelKV := outKV{}
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+
+ key := keyValue.Key
+ switch {
+ case key == "general.architecture":
+ modelKV[key] = "qwen2vl"
+ case strings.HasPrefix(key, "qwen25vl."):
+ modelKV[strings.Replace(key, "qwen25vl.", "qwen2vl.", 1)] = normalizeGGUFValue(keyValue.Any())
+ case strings.HasPrefix(key, "general."), strings.HasPrefix(key, "tokenizer."):
+ modelKV[key] = normalizeGGUFValue(keyValue.Any())
+ }
+ }
+ if sections := qwen25VLMropeSections(src); len(sections) > 0 {
+ modelKV["qwen2vl.rope.dimension_sections"] = sections
+ }
+
+ hidden := uint32(src.GGUF.KeyValue("embedding_length").Uint())
+ visionHidden := uint32(src.GGUF.KeyValue("vision.embedding_length").Uint())
+ nWAPattern := uint32(8) // Qwen2.5-VL window-attention pattern: full attention every 8th layer.
+ if fullatt := src.GGUF.KeyValue("vision.fullatt_block_indexes"); fullatt.Valid() {
+ indexes := fullatt.Ints()
+ if len(indexes) > 0 && indexes[0] >= 0 {
+ nWAPattern = uint32(indexes[0] + 1)
+ }
+ }
+ patchSize := uint32(src.GGUF.KeyValue("vision.patch_size").Uint())
+ projectorKV := outKV{
+ "general.architecture": "clip",
+ "clip.projector_type": "qwen2.5vl_merger",
+ "clip.has_vision_encoder": true,
+ "clip.vision.block_count": uint32(src.GGUF.KeyValue("vision.block_count").Uint()),
+ "clip.vision.embedding_length": visionHidden,
+ "clip.vision.feed_forward_length": visionHidden * 4,
+ "clip.vision.attention.head_count": uint32(src.GGUF.KeyValue("vision.attention.head_count").Uint()),
+ "clip.vision.attention.layer_norm_epsilon": float32(src.GGUF.KeyValue("vision.attention.layer_norm_epsilon").Float()),
+ "clip.vision.num_channels": uint32(src.GGUF.KeyValue("vision.num_channels").Uint()),
+ "clip.vision.patch_size": patchSize,
+ "clip.vision.spatial_merge_size": uint32(src.GGUF.KeyValue("vision.spatial_merge_size").Uint()),
+ "clip.vision.image_size": uint32(560),
+ "clip.vision.projection_dim": hidden,
+ "clip.vision.temporal_patch_size": uint32(src.GGUF.KeyValue("vision.temporal_patch_size").Uint()),
+ "clip.vision.n_wa_pattern": nWAPattern,
+ "clip.use_silu": true,
+ "clip.vision.rope.freq_base": float32(src.GGUF.KeyValue("vision.rope.freq_base").Float()),
+ }
+ if fullatt := src.GGUF.KeyValue("vision.fullatt_block_indexes"); fullatt.Valid() {
+ projectorKV["clip.vision.fullatt_block_indexes"] = normalizeGGUFValue(fullatt.Any())
+ } else {
+ projectorKV["clip.vision.fullatt_block_indexes"] = []int32{7, 15, 23, 31}
+ }
+ if minPixels := src.GGUF.KeyValue("vision.min_pixels"); minPixels.Valid() {
+ projectorKV["clip.vision.min_pixels"] = uint32(minPixels.Uint())
+ }
+ if maxPixels := src.GGUF.KeyValue("vision.max_pixels"); maxPixels.Valid() {
+ projectorKV["clip.vision.max_pixels"] = uint32(maxPixels.Uint())
+ }
+ if mean := src.GGUF.KeyValue("vision.image_mean"); mean.Valid() {
+ projectorKV["clip.vision.image_mean"] = normalizeGGUFValue(mean.Any())
+ }
+ if std := src.GGUF.KeyValue("vision.image_std"); std.Valid() {
+ projectorKV["clip.vision.image_std"] = normalizeGGUFValue(std.Any())
+ }
+ if _, ok := projectorKV["clip.vision.image_mean"]; !ok {
+ // Legacy installed GGUFs do not retain the preprocessor normalization.
+ // Use the standard CLIP normalization as a best-effort local migration
+ // fallback; an explicit pull can still refresh to the fully recreated
+ // artifact if users want exact parity.
+ projectorKV["clip.vision.image_mean"] = []float32{0.48145466, 0.4578275, 0.40821073}
+ projectorKV["clip.vision.image_std"] = []float32{0.26862954, 0.26130258, 0.27577711}
+ }
+
+ return &Result{
+ ModelKV: modelKV,
+ ModelTensors: modelTensors,
+ ProjectorKV: projectorKV,
+ ProjectorTensors: projectorTensors,
+ }, nil
+}
+
+func qwen25VLProjectorTensorName(name string) string {
+ name = strings.Replace(name, "v.merger.mlp.0", "mm.0", 1)
+ name = strings.Replace(name, "v.merger.mlp.2", "mm.2", 1)
+ name = strings.Replace(name, "v.merger.ln_q", "v.post_ln", 1)
+ return name
+}
+
+func qwen25VLMropeSections(src *SourceModel) []int32 {
+ for _, key := range []string{"qwen25vl.rope.dimension_sections", "qwen25vl.rope.mrope_section", "qwen2vl.rope.mrope_section"} {
+ if keyValue := rawGGUFKeyValue(src.GGUF, key); keyValue.Valid() {
+ ints := keyValue.Ints()
+ if len(ints) > 0 {
+ out := make([]int32, 4)
+ for i, v := range ints[:min(len(ints), len(out))] {
+ out[i] = int32(v)
+ }
+ return out
+ }
+ }
+ }
+ return nil
+}
diff --git a/compatmigrate/qwen35.go b/compatmigrate/qwen35.go
new file mode 100644
index 000000000..fb10ac9e0
--- /dev/null
+++ b/compatmigrate/qwen35.go
@@ -0,0 +1,487 @@
+package compatmigrate
+
+import (
+ "fmt"
+ "slices"
+ "strconv"
+ "strings"
+
+ "github.com/ollama/ollama/fs/gguf"
+)
+
+type qwen35Migrator struct{}
+
+// Mirrors detect_ollama_qwen35 and detect_ollama_qwen35moe in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (qwen35Migrator) NeedsMigration(src *SourceModel) bool {
+ arch := src.GGUF.KeyValue("general.architecture").String()
+ if arch != "qwen35" && arch != "qwen35moe" {
+ return false
+ }
+ if src.GGUF.KeyValue("vision.block_count").Valid() ||
+ src.GGUF.KeyValue("image_token_id").Valid() ||
+ src.GGUF.KeyValue("ssm.v_head_reordered").Valid() ||
+ src.GGUF.KeyValue("rope.mrope_interleaved").Valid() ||
+ sourceTensorHasPrefix(src, "mtp.") ||
+ sourceTensorHasPrefix(src, "v.") {
+ return true
+ }
+ return false
+}
+
+func (qwen35Migrator) Migrate(src *SourceModel) (*Result, error) {
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ numChannels := src.GGUF.KeyValue("vision.num_channels").Uint()
+ if numChannels == 0 {
+ numChannels = 3
+ }
+
+ var modelTensors []*outTensor
+ var projectorTensors []*outTensor
+ var mtpTensors []*outTensor
+ nextn := qwen35MTPLayerCount(tensors)
+ baseBlocks := qwen35BaseBlockCount(src, tensors)
+ hasNativeMTP := qwen35HasNativeMTP(tensors)
+ isMoE := src.GGUF.KeyValue("general.architecture").String() == "qwen35moe"
+ mtpExperts := map[string]map[int]*sourceTensor{}
+ projectorQKVWeights := map[string]map[string]*sourceTensor{}
+ projectorQKVBiases := map[string]map[string]*sourceTensor{}
+ for _, tensor := range tensors {
+ if qwen35ProjectorTensor(tensor.name) {
+ name := qwen35ProjectorTensorName(tensor.name)
+ if qwen3VLPatchTensor(name, tensor) {
+ split, err := qwen3VLSplitLegacyPatchTensor(tensor, numChannels)
+ if err != nil {
+ return nil, err
+ }
+ projectorTensors = append(projectorTensors, split...)
+ continue
+ }
+ if fusedName, part, ok := qwen3VLProjectorQKVTarget(name); ok {
+ projectorQKVWeights[fusedName] = ensureTensorParts(projectorQKVWeights[fusedName])
+ projectorQKVWeights[fusedName][part] = tensor
+ continue
+ }
+ if fusedName, part, ok := qwen3VLProjectorQKVBiasTarget(name); ok {
+ projectorQKVBiases[fusedName] = ensureTensorParts(projectorQKVBiases[fusedName])
+ projectorQKVBiases[fusedName][part] = tensor
+ continue
+ }
+
+ projectorTensors = append(projectorTensors, copyTensor(name, tensor))
+ continue
+ }
+ if strings.HasPrefix(tensor.name, "mtp.") && nextn > 0 && baseBlocks > 0 && !hasNativeMTP {
+ names := qwen35MTPTensorNames(tensor.name, baseBlocks, nextn)
+ for _, name := range names {
+ if isMoE {
+ if target, expert, ok := qwen35MTPExpertTensor(name); ok {
+ if mtpExperts[target] == nil {
+ mtpExperts[target] = map[int]*sourceTensor{}
+ }
+ mtpExperts[target][expert] = tensor
+ continue
+ }
+ }
+ mtpTensors = append(mtpTensors, copyQwen35MTPTensor(name, tensor))
+ }
+ continue
+ }
+ if strings.HasPrefix(tensor.name, "mtp.") {
+ continue
+ }
+
+ modelTensors = append(modelTensors, copyTensor(qwen35ModelTensorName(tensor.name), tensor))
+ }
+ mergedMTPExperts, err := qwen35MergedMTPExpertTensors(mtpExperts)
+ if err != nil {
+ return nil, err
+ }
+ mtpTensors = append(mtpTensors, mergedMTPExperts...)
+ modelTensors = append(modelTensors, mtpTensors...)
+ for _, name := range sortedTensorParts(projectorQKVWeights) {
+ parts := projectorQKVWeights[name]
+ if !tensorPartsComplete(parts) {
+ for _, part := range []string{"q", "k", "v"} {
+ if tensor := parts[part]; tensor != nil {
+ projectorTensors = append(projectorTensors, copyTensor(strings.Replace(name, "attn_qkv", "attn_"+part, 1), tensor))
+ }
+ }
+ continue
+ }
+
+ fused, err := qwen3VLConcatQKVWeights(name, parts["q"], parts["k"], parts["v"])
+ if err != nil {
+ return nil, err
+ }
+ projectorTensors = append(projectorTensors, fused)
+ }
+ for _, name := range sortedTensorParts(projectorQKVBiases) {
+ parts := projectorQKVBiases[name]
+ if !tensorPartsComplete(parts) {
+ for _, part := range []string{"q", "k", "v"} {
+ if tensor := parts[part]; tensor != nil {
+ projectorTensors = append(projectorTensors, copyTensor(strings.Replace(name, "attn_qkv", "attn_"+part, 1), tensor))
+ }
+ }
+ continue
+ }
+
+ fused, err := concatSourceTensorsDimKind(0, name, gguf.TensorTypeF32, parts["q"], parts["k"], parts["v"])
+ if err != nil {
+ return nil, err
+ }
+ projectorTensors = append(projectorTensors, fused)
+ }
+
+ modelKV := outKV{}
+ arch := src.GGUF.KeyValue("general.architecture").String()
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+
+ key := keyValue.Key
+ value := normalizeGGUFValue(keyValue.Any())
+ switch {
+ case key == "general.architecture":
+ modelKV[key] = value
+ case strings.HasPrefix(key, arch+".vision."), qwen35VisionTokenKey(key, arch):
+ continue
+ case strings.HasPrefix(key, arch+"."):
+ if key == arch+".attention.head_count_kv" {
+ value = qwen35MaxHeadCountKV(value, 2)
+ }
+ if key == arch+".block_count" && nextn > 0 && baseBlocks > 0 && !hasNativeMTP {
+ value = baseBlocks + nextn
+ }
+ if qwen35DropTextKV(key, arch) {
+ continue
+ }
+ if qwen35RopeSectionKey(key) {
+ value = padInt32Sections(value)
+ }
+ modelKV[key] = value
+ case strings.HasPrefix(key, "general."), strings.HasPrefix(key, "tokenizer."):
+ modelKV[key] = value
+ }
+ }
+ if nextn > 0 && baseBlocks > 0 && !hasNativeMTP {
+ modelKV[arch+".nextn_predict_layers"] = nextn
+ modelKV[arch+".block_count"] = baseBlocks + nextn
+ }
+
+ result := &Result{
+ ModelKV: modelKV,
+ ModelTensors: modelTensors,
+ }
+ if len(projectorTensors) > 0 {
+ result.ProjectorKV = qwen35ProjectorKV(src)
+ result.ProjectorTensors = projectorTensors
+ }
+ return result, nil
+}
+
+func qwen35ModelTensorName(name string) string {
+ if strings.HasSuffix(name, ".ssm_dt") {
+ return name + ".bias"
+ }
+ return name
+}
+
+func qwen35BaseBlockCount(src *SourceModel, tensors []*sourceTensor) uint32 {
+ maxBlock := -1
+ for _, tensor := range tensors {
+ if strings.HasPrefix(tensor.name, "mtp.") || qwen35ProjectorTensor(tensor.name) {
+ continue
+ }
+ if block, ok := tensorBlock(tensor.name); ok && block > maxBlock {
+ maxBlock = block
+ }
+ }
+ if maxBlock < 0 {
+ if blocks := src.GGUF.KeyValue("block_count").Uint(); blocks > 0 {
+ return uint32(blocks)
+ }
+ return 0
+ }
+ return uint32(maxBlock + 1)
+}
+
+func qwen35MTPLayerCount(tensors []*sourceTensor) uint32 {
+ maxLayer := -1
+ hasMTP := false
+ for _, tensor := range tensors {
+ if !strings.HasPrefix(tensor.name, "mtp.") {
+ continue
+ }
+ hasMTP = true
+ rest := strings.TrimPrefix(tensor.name, "mtp.layers.")
+ layer, suffix, ok := strings.Cut(rest, ".")
+ if !ok || suffix == "" {
+ continue
+ }
+ n, err := strconv.Atoi(layer)
+ if err == nil && n > maxLayer {
+ maxLayer = n
+ }
+ }
+ if maxLayer >= 0 {
+ return uint32(maxLayer + 1)
+ }
+ if hasMTP {
+ return 1
+ }
+ return 0
+}
+
+func qwen35HasNativeMTP(tensors []*sourceTensor) bool {
+ for _, tensor := range tensors {
+ if strings.HasPrefix(tensor.name, "blk.") && strings.Contains(tensor.name, ".nextn.") {
+ return true
+ }
+ }
+ return false
+}
+
+func qwen35MTPTensorNames(name string, base, nextn uint32) []string {
+ if rest := strings.TrimPrefix(name, "mtp.layers."); rest != name {
+ layer, suffix, ok := strings.Cut(rest, ".")
+ if !ok || suffix == "" {
+ return nil
+ }
+ idx, err := strconv.ParseUint(layer, 10, 32)
+ if err != nil || uint32(idx) >= nextn {
+ return nil
+ }
+ return []string{fmt.Sprintf("blk.%d.%s", base+uint32(idx), suffix)}
+ }
+
+ var suffix string
+ switch name {
+ case "mtp.fc.weight":
+ suffix = "nextn.eh_proj.weight"
+ case "mtp.pre_fc_norm_embedding.weight":
+ suffix = "nextn.enorm.weight"
+ case "mtp.pre_fc_norm_hidden.weight":
+ suffix = "nextn.hnorm.weight"
+ case "mtp.embed_tokens.weight":
+ suffix = "nextn.embed_tokens.weight"
+ case "mtp.shared_head.head.weight":
+ suffix = "nextn.shared_head_head.weight"
+ case "mtp.shared_head.norm.weight", "mtp.norm.weight":
+ suffix = "nextn.shared_head_norm.weight"
+ default:
+ return nil
+ }
+
+ names := make([]string, 0, nextn)
+ for i := range nextn {
+ names = append(names, fmt.Sprintf("blk.%d.%s", base+i, suffix))
+ }
+ return names
+}
+
+func copyQwen35MTPTensor(name string, tensor *sourceTensor) *outTensor {
+ writer := tensor.Clone()
+ outType := compatOutputTensorType(name, tensor.name, tensor.info.Type)
+ if qwen35ShouldShiftNormAfterMTPRename(name) {
+ writer.SetRepacker(qwen35AddOneRepacker)
+ outType = gguf.TensorTypeF32
+ }
+ if outType != tensor.info.Type {
+ writer.SetOutputType(outType)
+ }
+ return &outTensor{
+ Name: name,
+ Kind: uint32(outType),
+ Shape: slices.Clone(tensor.shape),
+ WriterTo: writer,
+ }
+}
+
+func qwen35AddOneRepacker(_ string, data []float32, _ []uint64) ([]float32, error) {
+ out := slices.Clone(data)
+ for i := range out {
+ out[i] += 1
+ }
+ return out, nil
+}
+
+func qwen35ShouldShiftNormAfterMTPRename(name string) bool {
+ if strings.HasSuffix(name, ".ssm_norm.weight") {
+ return false
+ }
+ return strings.HasSuffix(name, "_norm.weight") ||
+ strings.HasSuffix(name, ".nextn.enorm.weight") ||
+ strings.HasSuffix(name, ".nextn.hnorm.weight")
+}
+
+func qwen35MTPExpertTensor(name string) (string, int, bool) {
+ if !strings.HasPrefix(name, "blk.") {
+ return "", 0, false
+ }
+ parts := strings.Split(name, ".")
+ if len(parts) != 7 || parts[2] != "mlp" || parts[3] != "experts" || parts[6] != "weight" {
+ return "", 0, false
+ }
+ expert, err := strconv.Atoi(parts[4])
+ if err != nil || expert < 0 {
+ return "", 0, false
+ }
+
+ var suffix string
+ switch parts[5] + "." + parts[6] {
+ case "gate_proj.weight":
+ suffix = "ffn_gate_exps.weight"
+ case "up_proj.weight":
+ suffix = "ffn_up_exps.weight"
+ case "down_proj.weight":
+ suffix = "ffn_down_exps.weight"
+ default:
+ return "", 0, false
+ }
+ return strings.Join([]string{parts[0], parts[1], suffix}, "."), expert, true
+}
+
+func qwen35MergedMTPExpertTensors(groups map[string]map[int]*sourceTensor) ([]*outTensor, error) {
+ var out []*outTensor
+ names := make([]string, 0, len(groups))
+ for name := range groups {
+ names = append(names, name)
+ }
+ slices.Sort(names)
+ for _, name := range names {
+ experts := groups[name]
+ indexes := make([]int, 0, len(experts))
+ for index := range experts {
+ indexes = append(indexes, index)
+ }
+ slices.Sort(indexes)
+ parts := make([]*sourceTensor, 0, len(indexes))
+ for i, index := range indexes {
+ if i != index {
+ return nil, fmt.Errorf("non-contiguous qwen3.5 MTP experts for %s", name)
+ }
+ parts = append(parts, experts[index])
+ }
+ merged, err := stackSourceTensors(name, parts...)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, merged)
+ }
+ return out, nil
+}
+
+func qwen35ProjectorTensor(name string) bool {
+ return strings.HasPrefix(name, "v.") || strings.HasPrefix(name, "mm.")
+}
+
+func qwen35ProjectorTensorName(name string) string {
+ return qwen3VLProjectorTensorName(name, nil)
+}
+
+func qwen35ProjectorKV(src *SourceModel) outKV {
+ blockCount := uint32(src.GGUF.KeyValue("vision.block_count").Uint())
+ projectorKV := outKV{
+ "general.architecture": "clip",
+ "clip.projector_type": "qwen3vl_merger",
+ "clip.has_vision_encoder": true,
+ "clip.use_gelu": true,
+ "clip.vision.block_count": blockCount,
+ "clip.vision.embedding_length": uint32(src.GGUF.KeyValue("vision.embedding_length").Uint()),
+ "clip.vision.feed_forward_length": uint32(4304),
+ "clip.vision.attention.head_count": uint32(src.GGUF.KeyValue("vision.attention.head_count").Uint()),
+ "clip.vision.attention.layer_norm_epsilon": float32(1e-6),
+ "clip.vision.patch_size": uint32(src.GGUF.KeyValue("vision.patch_size").Uint()),
+ "clip.vision.spatial_merge_size": uint32(src.GGUF.KeyValue("vision.spatial_merge_size").Uint()),
+ "clip.vision.num_channels": uint32(src.GGUF.KeyValue("vision.num_channels").Uint()),
+ "clip.vision.projection_dim": uint32(src.GGUF.KeyValue("embedding_length").Uint()),
+ "clip.vision.image_size": uint32(768),
+ "clip.vision.image_mean": []float32{0.5, 0.5, 0.5},
+ "clip.vision.image_std": []float32{0.5, 0.5, 0.5},
+ "clip.vision.is_deepstack_layers": make([]bool, blockCount),
+ }
+ if ff := src.GGUF.KeyValue("vision.feed_forward_length"); ff.Valid() {
+ projectorKV["clip.vision.feed_forward_length"] = uint32(ff.Uint())
+ }
+ if imageSize := src.GGUF.KeyValue("vision.image_size"); imageSize.Valid() {
+ projectorKV["clip.vision.image_size"] = uint32(imageSize.Uint())
+ }
+ if eps := src.GGUF.KeyValue("vision.attention.layer_norm_epsilon"); eps.Valid() {
+ projectorKV["clip.vision.attention.layer_norm_epsilon"] = float32(eps.Float())
+ }
+ if mean := src.GGUF.KeyValue("vision.image_mean"); mean.Valid() {
+ projectorKV["clip.vision.image_mean"] = normalizeGGUFValue(mean.Any())
+ }
+ if std := src.GGUF.KeyValue("vision.image_std"); std.Valid() {
+ projectorKV["clip.vision.image_std"] = normalizeGGUFValue(std.Any())
+ }
+ if projectorKV["clip.vision.num_channels"] == uint32(0) {
+ projectorKV["clip.vision.num_channels"] = uint32(3)
+ }
+ return projectorKV
+}
+
+func qwen35MaxHeadCountKV(value any, fallback uint32) any {
+ switch values := value.(type) {
+ case []uint32:
+ var maxValue uint32
+ for _, value := range values {
+ maxValue = max(maxValue, value)
+ }
+ if maxValue == 0 {
+ maxValue = fallback
+ }
+ return maxValue
+ case []int32:
+ var maxValue uint32
+ for _, value := range values {
+ if value > 0 {
+ maxValue = max(maxValue, uint32(value))
+ }
+ }
+ if maxValue == 0 {
+ maxValue = fallback
+ }
+ return maxValue
+ default:
+ return value
+ }
+}
+
+func qwen35VisionTokenKey(key, arch string) bool {
+ switch key {
+ case arch + ".image_token_id", arch + ".vision_start_token_id", arch + ".vision_end_token_id":
+ return true
+ default:
+ return false
+ }
+}
+
+func qwen35DropTextKV(key, arch string) bool {
+ if arch == "qwen35moe" && key == arch+".feed_forward_length" {
+ return true
+ }
+ switch key {
+ case arch + ".ssm.v_head_reordered", arch + ".rope.mrope_interleaved":
+ return true
+ default:
+ return false
+ }
+}
+
+func qwen35RopeSectionKey(key string) bool {
+ key = strings.TrimPrefix(key, "qwen35.")
+ key = strings.TrimPrefix(key, "qwen35moe.")
+ switch key {
+ case "mrope_sections", "rope.mrope_section", "rope.dimension_sections":
+ return true
+ default:
+ return false
+ }
+}
diff --git a/compatmigrate/qwen3next.go b/compatmigrate/qwen3next.go
new file mode 100644
index 000000000..7246224e4
--- /dev/null
+++ b/compatmigrate/qwen3next.go
@@ -0,0 +1,90 @@
+package compatmigrate
+
+import (
+ "strings"
+)
+
+type qwen3NextMigrator struct{}
+
+// Mirrors detect_ollama_qwen3next in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (qwen3NextMigrator) NeedsMigration(src *SourceModel) bool {
+ if src.GGUF.KeyValue("general.architecture").String() != "qwen3next" {
+ return false
+ }
+ for _, tensor := range src.GGUF.TensorInfos() {
+ if strings.HasSuffix(tensor.Name, ".ssm_dt") {
+ return true
+ }
+ }
+ return false
+}
+
+func (qwen3NextMigrator) Migrate(src *SourceModel) (*Result, error) {
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ modelTensors := make([]*outTensor, 0, len(tensors))
+ for _, tensor := range tensors {
+ modelTensors = append(modelTensors, copyTensor(qwen3NextTensorName(tensor.name), tensor))
+ }
+
+ modelKV := outKV{}
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+
+ key := keyValue.Key
+ value := normalizeGGUFValue(keyValue.Any())
+ switch {
+ case key == "qwen3next.attention.head_count_kv":
+ modelKV[key] = qwen3NextMaxHeadCountKV(value)
+ case strings.HasPrefix(key, "general."), strings.HasPrefix(key, "tokenizer."), strings.HasPrefix(key, "qwen3next."):
+ modelKV[key] = value
+ }
+ }
+ if _, ok := modelKV["general.architecture"]; !ok {
+ modelKV["general.architecture"] = "qwen3next"
+ }
+
+ return &Result{
+ ModelKV: modelKV,
+ ModelTensors: modelTensors,
+ }, nil
+}
+
+func qwen3NextTensorName(name string) string {
+ if strings.HasSuffix(name, ".ssm_dt") {
+ return name + ".bias"
+ }
+ return name
+}
+
+func qwen3NextMaxHeadCountKV(value any) any {
+ switch values := value.(type) {
+ case []uint32:
+ var maxValue uint32
+ for _, value := range values {
+ maxValue = max(maxValue, value)
+ }
+ if maxValue == 0 {
+ return value
+ }
+ return maxValue
+ case []int32:
+ var maxValue uint32
+ for _, value := range values {
+ if value > 0 {
+ maxValue = max(maxValue, uint32(value))
+ }
+ }
+ if maxValue == 0 {
+ return value
+ }
+ return maxValue
+ default:
+ return value
+ }
+}
diff --git a/compatmigrate/qwen3vl.go b/compatmigrate/qwen3vl.go
new file mode 100644
index 000000000..1c40bab69
--- /dev/null
+++ b/compatmigrate/qwen3vl.go
@@ -0,0 +1,465 @@
+package compatmigrate
+
+import (
+ "fmt"
+ "io"
+ "math"
+ "slices"
+ "strconv"
+ "strings"
+
+ "github.com/ollama/ollama/fs/gguf"
+)
+
+type qwen3VLMigrator struct{}
+
+// Mirrors detect_ollama_qwen3vl in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (qwen3VLMigrator) NeedsMigration(src *SourceModel) bool {
+ arch := src.GGUF.KeyValue("general.architecture").String()
+ if arch != "qwen3vl" && arch != "qwen3vlmoe" {
+ return false
+ }
+ return !src.GGUF.KeyValue("rope.dimension_sections").Valid()
+}
+
+func (qwen3VLMigrator) Migrate(src *SourceModel) (*Result, error) {
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ deepstackIndexes := qwen3VLDeepstackIndexes(src)
+ numChannels := src.GGUF.KeyValue("vision.num_channels").Uint()
+ if numChannels == 0 {
+ numChannels = 3
+ }
+
+ var modelTensors []*outTensor
+ var projectorTensors []*outTensor
+ projectorQKVWeights := map[string]map[string]*sourceTensor{}
+ projectorQKVBiases := map[string]map[string]*sourceTensor{}
+ for _, tensor := range tensors {
+ if !qwen3VLVisionTensor(tensor.name) {
+ modelTensors = append(modelTensors, copyTensor(tensor.name, tensor))
+ continue
+ }
+
+ name := qwen3VLProjectorTensorName(tensor.name, deepstackIndexes)
+ if qwen3VLPatchTensor(name, tensor) {
+ split, err := qwen3VLSplitLegacyPatchTensor(tensor, numChannels)
+ if err != nil {
+ return nil, err
+ }
+ projectorTensors = append(projectorTensors, split...)
+ continue
+ }
+ if fusedName, part, ok := qwen3VLProjectorQKVTarget(name); ok {
+ projectorQKVWeights[fusedName] = ensureTensorParts(projectorQKVWeights[fusedName])
+ projectorQKVWeights[fusedName][part] = tensor
+ continue
+ }
+ if fusedName, part, ok := qwen3VLProjectorQKVBiasTarget(name); ok {
+ projectorQKVBiases[fusedName] = ensureTensorParts(projectorQKVBiases[fusedName])
+ projectorQKVBiases[fusedName][part] = tensor
+ continue
+ }
+
+ projectorTensors = append(projectorTensors, copyTensor(name, tensor))
+ }
+ for _, name := range sortedTensorParts(projectorQKVWeights) {
+ parts := projectorQKVWeights[name]
+ if !tensorPartsComplete(parts) {
+ for _, part := range []string{"q", "k", "v"} {
+ if tensor := parts[part]; tensor != nil {
+ projectorTensors = append(projectorTensors, copyTensor(strings.Replace(name, "attn_qkv", "attn_"+part, 1), tensor))
+ }
+ }
+ continue
+ }
+
+ fused, err := qwen3VLConcatQKVWeights(name, parts["q"], parts["k"], parts["v"])
+ if err != nil {
+ return nil, err
+ }
+ projectorTensors = append(projectorTensors, fused)
+ }
+ for _, name := range sortedTensorParts(projectorQKVBiases) {
+ parts := projectorQKVBiases[name]
+ if !tensorPartsComplete(parts) {
+ for _, part := range []string{"q", "k", "v"} {
+ if tensor := parts[part]; tensor != nil {
+ projectorTensors = append(projectorTensors, copyTensor(strings.Replace(name, "attn_qkv", "attn_"+part, 1), tensor))
+ }
+ }
+ continue
+ }
+
+ fused, err := concatSourceTensorsDimKind(0, name, gguf.TensorTypeF32, parts["q"], parts["k"], parts["v"])
+ if err != nil {
+ return nil, err
+ }
+ projectorTensors = append(projectorTensors, fused)
+ }
+
+ modelKV := outKV{}
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+
+ key := keyValue.Key
+ switch {
+ case key == "general.architecture":
+ modelKV[key] = normalizeGGUFValue(keyValue.Any())
+ case strings.HasPrefix(key, "qwen3vl.vision."), strings.HasPrefix(key, "qwen3vlmoe.vision."):
+ continue
+ case strings.HasPrefix(key, "qwen3vl."), strings.HasPrefix(key, "qwen3vlmoe."):
+ modelKV[key] = normalizeGGUFValue(keyValue.Any())
+ case strings.HasPrefix(key, "general."), strings.HasPrefix(key, "tokenizer."):
+ modelKV[key] = normalizeGGUFValue(keyValue.Any())
+ }
+ }
+
+ arch := src.GGUF.KeyValue("general.architecture").String()
+ if sections := qwen3VLMropeSections(src); len(sections) > 0 {
+ modelKV[arch+".rope.dimension_sections"] = sections
+ }
+ modelKV[arch+".n_deepstack_layers"] = uint32(len(deepstackIndexes))
+
+ visionHidden := uint32(src.GGUF.KeyValue("vision.embedding_length").Uint())
+ patchSize := uint32(src.GGUF.KeyValue("vision.patch_size").Uint())
+ if patchSize == 0 {
+ patchSize = 16
+ }
+ numPositionEmbeddings := uint32(src.GGUF.KeyValue("vision.num_position_embeddings").Uint())
+ if numPositionEmbeddings == 0 {
+ numPositionEmbeddings = 2304
+ }
+ imageSize := uint32(math.Sqrt(float64(numPositionEmbeddings))) * patchSize
+
+ projectorKV := outKV{
+ "general.architecture": "clip",
+ "clip.projector_type": "qwen3vl_merger",
+ "clip.has_vision_encoder": true,
+ "clip.vision.block_count": uint32(src.GGUF.KeyValue("vision.block_count").Uint()),
+ "clip.vision.embedding_length": visionHidden,
+ "clip.vision.feed_forward_length": visionHidden * 4,
+ "clip.vision.attention.head_count": uint32(src.GGUF.KeyValue("vision.attention.head_count").Uint()),
+ "clip.vision.attention.layer_norm_epsilon": float32(src.GGUF.KeyValue("vision.attention.layer_norm_epsilon").Float()),
+ "clip.vision.num_channels": uint32(src.GGUF.KeyValue("vision.num_channels").Uint()),
+ "clip.vision.patch_size": patchSize,
+ "clip.vision.spatial_merge_size": uint32(src.GGUF.KeyValue("vision.spatial_merge_size").Uint()),
+ "clip.vision.image_size": imageSize,
+ "clip.vision.projection_dim": uint32(src.GGUF.KeyValue("embedding_length").Uint()),
+ "clip.use_gelu": true,
+ "clip.vision.temporal_patch_size": uint32(src.GGUF.KeyValue("vision.temporal_patch_size").Uint()),
+ "clip.vision.rope.freq_base": float32(src.GGUF.KeyValue("vision.rope.freq_base").Float()),
+ }
+ projectorKV["clip.vision.is_deepstack_layers"] = qwen3VLDeepstackMask(uint32(src.GGUF.KeyValue("vision.block_count").Uint()), deepstackIndexes)
+ if ff := src.GGUF.KeyValue("vision.feed_forward_length"); ff.Valid() {
+ projectorKV["clip.vision.feed_forward_length"] = uint32(ff.Uint())
+ }
+ if projection := src.GGUF.KeyValue("vision.out_hidden_size"); projection.Valid() {
+ projectorKV["clip.vision.projection_dim"] = uint32(projection.Uint())
+ }
+ if minPixels := src.GGUF.KeyValue("vision.shortest_edge"); minPixels.Valid() {
+ projectorKV["clip.vision.min_pixels"] = uint32(minPixels.Uint())
+ }
+ if maxPixels := src.GGUF.KeyValue("vision.longest_edge"); maxPixels.Valid() {
+ projectorKV["clip.vision.max_pixels"] = uint32(maxPixels.Uint())
+ }
+ if mean := src.GGUF.KeyValue("vision.image_mean"); mean.Valid() {
+ projectorKV["clip.vision.image_mean"] = normalizeGGUFValue(mean.Any())
+ }
+ if std := src.GGUF.KeyValue("vision.image_std"); std.Valid() {
+ projectorKV["clip.vision.image_std"] = normalizeGGUFValue(std.Any())
+ }
+ if projectorKV["clip.vision.num_channels"] == uint32(0) {
+ projectorKV["clip.vision.num_channels"] = uint32(3)
+ }
+ if projectorKV["clip.vision.temporal_patch_size"] == uint32(0) {
+ projectorKV["clip.vision.temporal_patch_size"] = uint32(2)
+ }
+ if projectorKV["clip.vision.rope.freq_base"] == float32(0) {
+ projectorKV["clip.vision.rope.freq_base"] = float32(10000)
+ }
+ if _, ok := projectorKV["clip.vision.min_pixels"]; !ok {
+ projectorKV["clip.vision.min_pixels"] = uint32(65536)
+ }
+ if _, ok := projectorKV["clip.vision.max_pixels"]; !ok {
+ projectorKV["clip.vision.max_pixels"] = uint32(16777216)
+ }
+
+ return &Result{
+ ModelKV: modelKV,
+ ModelTensors: modelTensors,
+ ProjectorKV: projectorKV,
+ ProjectorTensors: projectorTensors,
+ }, nil
+}
+
+func qwen3VLVisionTensor(name string) bool {
+ return strings.HasPrefix(name, "v.") || strings.HasPrefix(name, "mm.")
+}
+
+func qwen3VLPatchTensor(name string, t *sourceTensor) bool {
+ return name == "v.patch_embd.weight" && len(t.shape) == 4 && t.shape[2] == 2
+}
+
+func qwen3VLSplitLegacyPatchTensor(t *sourceTensor, numChannels uint64) ([]*outTensor, error) {
+ if numChannels == 0 {
+ return nil, fmt.Errorf("split qwen3-vl patch tensor %s: num channels is zero", t.name)
+ }
+ if len(t.shape) != 4 {
+ return nil, fmt.Errorf("split qwen3-vl patch tensor %s: expected rank 4, got %v", t.name, t.shape)
+ }
+
+ width, height, temporal, flat := t.shape[0], t.shape[1], t.shape[2], t.shape[3]
+ if temporal != 2 {
+ return nil, fmt.Errorf("split qwen3-vl patch tensor %s: expected temporal size 2, got %d", t.name, temporal)
+ }
+ if flat%numChannels != 0 {
+ return nil, fmt.Errorf("split qwen3-vl patch tensor %s: flattened channel dimension %d is not divisible by %d", t.name, flat, numChannels)
+ }
+
+ hidden := flat / numChannels
+ names := []string{"v.patch_embd.weight", "v.patch_embd.weight.1"}
+ out := make([]*outTensor, 0, len(names))
+ for temporalIndex, name := range names {
+ temporalIndex := uint64(temporalIndex)
+ shape := []uint64{width, height, numChannels, hidden}
+ writer := t.Clone()
+ writer.shape = slices.Clone(shape)
+ writer.SetRepacker(func(_ string, data []float32, sourceShape []uint64) ([]float32, error) {
+ if len(sourceShape) != 4 {
+ return nil, fmt.Errorf("split qwen3-vl patch tensor %s: expected source rank 4, got %v", t.name, sourceShape)
+ }
+
+ sourceWidth, sourceHeight, sourceTemporal, sourceFlat := sourceShape[0], sourceShape[1], sourceShape[2], sourceShape[3]
+ if sourceTemporal <= temporalIndex {
+ return nil, fmt.Errorf("split qwen3-vl patch tensor %s: temporal index %d out of range for %v", t.name, temporalIndex, sourceShape)
+ }
+ if sourceFlat%numChannels != 0 {
+ return nil, fmt.Errorf("split qwen3-vl patch tensor %s: flattened channel dimension %d is not divisible by %d", t.name, sourceFlat, numChannels)
+ }
+
+ sourceHidden := sourceFlat / numChannels
+ result := make([]float32, sourceWidth*sourceHeight*numChannels*sourceHidden)
+ var dst uint64
+ for outIdx := range sourceHidden {
+ for channel := range numChannels {
+ flatOC := outIdx*numChannels + channel
+ for y := range sourceHeight {
+ for x := range sourceWidth {
+ src := (((flatOC*sourceTemporal+temporalIndex)*sourceHeight)+y)*sourceWidth + x
+ if src >= uint64(len(data)) {
+ return nil, fmt.Errorf("split qwen3-vl patch tensor %s: source index %d out of range %d", t.name, src, len(data))
+ }
+ result[dst] = data[src]
+ dst++
+ }
+ }
+ }
+ }
+ return result, nil
+ })
+
+ outType := compatOutputTensorType(name, t.name, t.info.Type)
+ if outType != t.info.Type {
+ writer.SetOutputType(outType)
+ }
+ out = append(out, &outTensor{
+ Name: name,
+ Kind: uint32(outType),
+ Shape: shape,
+ WriterTo: writer,
+ })
+ }
+
+ return out, nil
+}
+
+func qwen3VLProjectorTensorName(name string, deepstackIndexes []int32) string {
+ name = strings.Replace(name, "v.patch_embed.", "v.patch_embd.", 1)
+ name = strings.Replace(name, "v.pos_embed.", "v.position_embd.", 1)
+ name = strings.Replace(name, ".norm1.", ".ln1.", 1)
+ name = strings.Replace(name, ".norm2.", ".ln2.", 1)
+ name = strings.Replace(name, ".mlp.linear_fc1.", ".ffn_up.", 1)
+ name = strings.Replace(name, ".mlp.linear_fc2.", ".ffn_down.", 1)
+
+ if strings.HasPrefix(name, "v.merger.") {
+ name = strings.Replace(name, "v.merger.linear_fc1", "mm.0", 1)
+ name = strings.Replace(name, "v.merger.linear_fc2", "mm.2", 1)
+ name = strings.Replace(name, "v.merger.norm", "v.post_ln", 1)
+ return name
+ }
+
+ if strings.HasPrefix(name, "v.deepstack_merger.") {
+ name = strings.Replace(name, "v.deepstack_merger.", "v.deepstack.", 1)
+ }
+ if !strings.HasPrefix(name, "v.deepstack.") {
+ return name
+ }
+
+ rest := strings.TrimPrefix(name, "v.deepstack.")
+ parts := strings.SplitN(rest, ".", 2)
+ if len(parts) != 2 {
+ return name
+ }
+
+ seqIdx, err := strconv.Atoi(parts[0])
+ if err != nil || seqIdx < 0 || seqIdx >= len(deepstackIndexes) {
+ return name
+ }
+
+ suffix := parts[1]
+ suffix = strings.Replace(suffix, "linear_fc1", "fc1", 1)
+ suffix = strings.Replace(suffix, "linear_fc2", "fc2", 1)
+ return fmt.Sprintf("v.deepstack.%d.%s", deepstackIndexes[seqIdx], suffix)
+}
+
+func qwen3VLDeepstackIndexes(src *SourceModel) []int32 {
+ if keyValue := src.GGUF.KeyValue("vision.deepstack_visual_indexes"); keyValue.Valid() {
+ ints := keyValue.Ints()
+ if len(ints) > 0 {
+ out := make([]int32, len(ints))
+ for i, v := range ints {
+ out[i] = int32(v)
+ }
+ return out
+ }
+ }
+
+ return []int32{8, 16, 24}
+}
+
+func qwen3VLMropeSections(src *SourceModel) []int32 {
+ for _, key := range []string{"rope.dimension_sections", "rope.mrope_section"} {
+ if keyValue := src.GGUF.KeyValue(key); keyValue.Valid() {
+ ints := keyValue.Ints()
+ if len(ints) > 0 {
+ out := make([]int32, 4)
+ for i, v := range ints[:min(len(ints), len(out))] {
+ out[i] = int32(v)
+ }
+ return out
+ }
+ }
+ }
+
+ // The legacy library GGUFs sampled so far omit the HF mrope_section, but
+ // llama-server requires rope.dimension_sections for Qwen3-VL M-RoPE.
+ return []int32{24, 20, 20, 0}
+}
+
+func qwen3VLProjectorQKVTarget(name string) (string, string, bool) {
+ for _, part := range []string{"q", "k", "v"} {
+ needle := ".attn_" + part + ".weight"
+ if strings.Contains(name, needle) {
+ return strings.Replace(name, needle, ".attn_qkv.weight", 1), part, true
+ }
+ }
+ return "", "", false
+}
+
+func qwen3VLProjectorQKVBiasTarget(name string) (string, string, bool) {
+ for _, part := range []string{"q", "k", "v"} {
+ needle := ".attn_" + part + ".bias"
+ if strings.Contains(name, needle) {
+ return strings.Replace(name, needle, ".attn_qkv.bias", 1), part, true
+ }
+ }
+ return "", "", false
+}
+
+func qwen3VLConcatQKVWeights(name string, tensors ...*sourceTensor) (*outTensor, error) {
+ if len(tensors) == 0 {
+ return nil, fmt.Errorf("concat qwen3-vl qkv tensor %s: no source tensors", name)
+ }
+ if len(tensors[0].shape) != 2 {
+ return nil, fmt.Errorf("concat qwen3-vl qkv tensor %s: expected rank 2, got %v", name, tensors[0].shape)
+ }
+
+ shape := slices.Clone(tensors[0].shape)
+ shape[1] = 0
+ for _, t := range tensors {
+ if len(t.shape) != 2 {
+ return nil, fmt.Errorf("concat qwen3-vl qkv tensor %s: expected rank 2, got %v", name, t.shape)
+ }
+ if t.shape[0] != shape[0] {
+ return nil, fmt.Errorf("concat qwen3-vl qkv tensor %s: incompatible shape %v vs %v", name, shape, t.shape)
+ }
+ shape[1] += t.shape[1]
+ }
+
+ return &outTensor{
+ Name: name,
+ Kind: uint32(gguf.TensorTypeF16),
+ Shape: shape,
+ WriterTo: qwen3VLQKVWeightConcat{tensors: tensors},
+ }, nil
+}
+
+type qwen3VLQKVWeightConcat struct {
+ tensors []*sourceTensor
+}
+
+func (c qwen3VLQKVWeightConcat) GGUFWriteMemoryEstimate() uint64 {
+ var sourceBytes, inputFloatBytes, outputElements uint64
+ for _, source := range c.tensors {
+ sourceBytes = saturatingAdd(sourceBytes, int64ToUint64(source.info.NumBytes()))
+ elements := tensorElementCount(source.shape)
+ inputFloatBytes = saturatingAdd(inputFloatBytes, saturatingMul(elements, 4))
+ outputElements = saturatingAdd(outputElements, elements)
+ }
+
+ return saturatingAdd(sourceBytes, inputFloatBytes, ggufTensorBytes(gguf.TensorTypeF16, outputElements))
+}
+
+func (c qwen3VLQKVWeightConcat) WriteTo(w io.Writer) (int64, error) {
+ var total int64
+ for _, source := range c.tensors {
+ data, err := readSourceTensorFloatData(source)
+ if err != nil {
+ return total, err
+ }
+
+ n, err := encodeFloatTensor(w, gguf.TensorTypeF16, data)
+ total += int64(n)
+ if err != nil {
+ return total, err
+ }
+ }
+
+ return total, nil
+}
+
+func ensureTensorParts(parts map[string]*sourceTensor) map[string]*sourceTensor {
+ if parts != nil {
+ return parts
+ }
+ return map[string]*sourceTensor{}
+}
+
+func tensorPartsComplete(parts map[string]*sourceTensor) bool {
+ return parts["q"] != nil && parts["k"] != nil && parts["v"] != nil
+}
+
+func sortedTensorParts(parts map[string]map[string]*sourceTensor) []string {
+ names := make([]string, 0, len(parts))
+ for name := range parts {
+ names = append(names, name)
+ }
+ slices.Sort(names)
+ return names
+}
+
+func qwen3VLDeepstackMask(blockCount uint32, indexes []int32) []bool {
+ mask := make([]bool, blockCount)
+ for _, idx := range indexes {
+ if idx >= 0 && int(idx) < len(mask) {
+ mask[idx] = true
+ }
+ }
+ return mask
+}
diff --git a/compatmigrate/snowflake_arctic_embed2.go b/compatmigrate/snowflake_arctic_embed2.go
new file mode 100644
index 000000000..4815f4779
--- /dev/null
+++ b/compatmigrate/snowflake_arctic_embed2.go
@@ -0,0 +1,71 @@
+package compatmigrate
+
+import (
+ "encoding/base64"
+ "fmt"
+ "strings"
+)
+
+type snowflakeArcticEmbed2Migrator struct{}
+
+// Mirrors the guard in handle_snowflake_arctic_embed2 in llama/compat/llama-ollama-compat.cpp; keep the two in sync.
+func (snowflakeArcticEmbed2Migrator) NeedsMigration(src *SourceModel) bool {
+ if src.GGUF.KeyValue("general.architecture").String() != "bert" ||
+ src.GGUF.KeyValue("tokenizer.ggml.model").String() != "t5" {
+ return false
+ }
+
+ charsMap := src.GGUF.KeyValue("tokenizer.ggml.precompiled_charsmap")
+ if !charsMap.Valid() {
+ return false
+ }
+ _, ok := charsMap.Any().([]string)
+ return ok
+}
+
+func (snowflakeArcticEmbed2Migrator) Migrate(src *SourceModel) (*Result, error) {
+ tensors, err := readAllSourceTensors(src)
+ if err != nil {
+ return nil, err
+ }
+
+ modelKV := outKV{}
+ for _, keyValue := range src.GGUF.KeyValues() {
+ if !keyValue.Valid() {
+ continue
+ }
+
+ value := keyValue.Any()
+ if keyValue.Key == "tokenizer.ggml.precompiled_charsmap" {
+ chars, ok := value.([]string)
+ if !ok {
+ return nil, fmt.Errorf("unexpected precompiled chars map type %T", value)
+ }
+
+ for i, s := range chars {
+ if len(s) != 1 {
+ return nil, fmt.Errorf("unexpected precompiled chars map entry length %d at %d", len(s), i)
+ }
+ }
+
+ buf, err := base64.StdEncoding.DecodeString(strings.Join(chars, ""))
+ if err != nil {
+ return nil, fmt.Errorf("decode precompiled chars map: %w", err)
+ }
+ modelKV[keyValue.Key] = buf
+ continue
+ }
+
+ modelKV[keyValue.Key] = normalizeGGUFValue(value)
+ }
+
+ modelTensors := make([]*outTensor, 0, len(tensors))
+ for _, tensor := range tensors {
+ modelTensors = append(modelTensors, copyTensor(tensor.name, tensor))
+ }
+
+ return &Result{
+ ModelKV: modelKV,
+ ModelTensors: modelTensors,
+ }, nil
+}
diff --git a/compatmigrate/source_model.go b/compatmigrate/source_model.go
new file mode 100644
index 000000000..f38561606
--- /dev/null
+++ b/compatmigrate/source_model.go
@@ -0,0 +1,255 @@
+package compatmigrate
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "os"
+
+ "github.com/ollama/ollama/fs/gguf"
+ "github.com/ollama/ollama/manifest"
+ "github.com/ollama/ollama/types/model"
+)
+
+func loadSourceModelFromManifest(source model.Name, mf *manifest.Manifest) (*SourceModel, error) {
+ var config model.ConfigV2
+ if mf.Config.Digest != "" {
+ configPath, err := manifest.BlobsPath(mf.Config.Digest)
+ if err != nil {
+ return nil, err
+ }
+
+ f, err := os.Open(configPath)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+
+ if err := json.NewDecoder(f).Decode(&config); err != nil {
+ return nil, err
+ }
+ }
+
+ var modelDigest string
+ var projectorDigest string
+ for _, layer := range mf.Layers {
+ switch layer.MediaType {
+ case manifest.MediaTypeImageModel:
+ modelDigest = layer.Digest
+ case manifest.MediaTypeImageProjector:
+ projectorDigest = layer.Digest
+ }
+ }
+ if modelDigest == "" {
+ return nil, fmt.Errorf("source manifest %s has no GGUF model layer", source.DisplayShortest())
+ }
+
+ modelPath, err := manifest.BlobsPath(modelDigest)
+ if err != nil {
+ return nil, err
+ }
+
+ g, err := gguf.Open(modelPath)
+ if err != nil {
+ return nil, err
+ }
+
+ src := &SourceModel{
+ Source: source,
+ Manifest: mf,
+ Config: config,
+ GGUFPath: modelPath,
+ GGUF: g,
+ GGUFData: g.ReaderAt(),
+ GGUFDataOffset: g.TensorDataOffset(),
+ }
+
+ if projectorDigest != "" {
+ projectorPath, err := manifest.BlobsPath(projectorDigest)
+ if err != nil {
+ g.Close()
+ return nil, err
+ }
+
+ projector, err := gguf.Open(projectorPath)
+ if err != nil {
+ g.Close()
+ return nil, err
+ }
+
+ src.ProjectorPath = projectorPath
+ src.ProjectorGGUF = projector
+ src.ProjectorData = projector.ReaderAt()
+ src.ProjectorDataOffset = projector.TensorDataOffset()
+ }
+
+ return src, nil
+}
+
+func (src *SourceModel) Close() error {
+ var err error
+ if src.GGUF != nil {
+ err = src.GGUF.Close()
+ }
+ if src.ProjectorGGUF != nil {
+ if closeErr := src.ProjectorGGUF.Close(); err == nil {
+ err = closeErr
+ }
+ }
+ return err
+}
+
+func convertedManifest(src *SourceModel, result *Result) (_ *manifest.Manifest, err error) {
+ // Track blobs this conversion writes so a failure partway through does not
+ // strand a multi-GB blob until the next startup prune. Layers cloned from
+ // the source model are excluded — they stay referenced by its manifest.
+ var written []string
+ defer func() {
+ if err != nil && len(written) > 0 {
+ if _, removeErr := manifest.RemoveUnreferencedBlobs(written...); removeErr != nil {
+ slog.Warn("could not remove partial migration blobs", "error", removeErr)
+ }
+ }
+ }()
+
+ var layers []manifest.Layer
+
+ modelLayer, err := writeGGUFLayer(result.ModelKV, result.ModelTensors, manifest.MediaTypeImageModel)
+ if err != nil {
+ return nil, err
+ }
+ layers = append(layers, modelLayer)
+ written = append(written, modelLayer.Digest)
+
+ if len(result.ProjectorTensors) > 0 {
+ projectorLayer, err := writeGGUFLayer(result.ProjectorKV, result.ProjectorTensors, manifest.MediaTypeImageProjector)
+ if err != nil {
+ return nil, err
+ }
+ layers = append(layers, projectorLayer)
+ written = append(written, projectorLayer.Digest)
+ } else if result.PreserveProjector {
+ projectorLayer, err := copySourceProjectorLayer(src)
+ if err != nil {
+ return nil, err
+ }
+ layers = append(layers, projectorLayer)
+ }
+
+ ancillary, err := copyAncillaryLayers(src)
+ if err != nil {
+ return nil, err
+ }
+ layers = append(layers, ancillary...)
+
+ config := src.Config
+ config.ModelFormat = "gguf"
+ config.ModelFamily = result.ModelKV.String("general.architecture")
+ config.ModelFamilies = []string{config.ModelFamily}
+ if len(result.ProjectorTensors) > 0 || result.PreserveProjector {
+ config.ModelFamilies = append(config.ModelFamilies, "clip")
+ }
+ if result.ClearRenderer {
+ config.Renderer = ""
+ } else if result.Renderer != "" {
+ config.Renderer = result.Renderer
+ }
+ if result.ClearParser {
+ config.Parser = ""
+ } else if result.Parser != "" {
+ config.Parser = result.Parser
+ }
+ if result.Requires != "" {
+ config.Requires = result.Requires
+ }
+ config.RemoteHost = ""
+ config.RemoteModel = ""
+
+ configLayer, err := newConfigLayer(config)
+ if err != nil {
+ return nil, err
+ }
+ written = append(written, configLayer.Digest)
+
+ return &manifest.Manifest{
+ SchemaVersion: 2,
+ MediaType: manifest.MediaTypeManifest,
+ Config: configLayer,
+ Layers: layers,
+ Runner: manifest.RunnerLlamaCPP,
+ Format: manifest.FormatGGUF,
+ }, nil
+}
+
+func newConfigLayer(config model.ConfigV2) (manifest.Layer, error) {
+ var b bytes.Buffer
+ if err := json.NewEncoder(&b).Encode(config); err != nil {
+ return manifest.Layer{}, fmt.Errorf("failed to encode config: %w", err)
+ }
+ layer, err := manifest.NewLayer(&b, manifest.MediaTypeImageConfig)
+ if err != nil {
+ return manifest.Layer{}, fmt.Errorf("failed to create config layer: %w", err)
+ }
+ return layer, nil
+}
+
+func copyAncillaryLayers(src *SourceModel) ([]manifest.Layer, error) {
+ var layers []manifest.Layer
+ for _, layer := range src.Manifest.Layers {
+ switch layer.MediaType {
+ case manifest.MediaTypeImageModel,
+ manifest.MediaTypeImageProjector,
+ manifest.MediaTypeImageAdapter,
+ manifest.MediaTypeImageEmbed:
+ continue
+ }
+
+ cloned, err := manifest.NewLayerFromLayer(layer.Digest, layer.MediaType, src.Source.DisplayShortest())
+ if err != nil {
+ return nil, err
+ }
+ cloned.Name = layer.Name
+ layers = append(layers, cloned)
+ }
+
+ return layers, nil
+}
+
+func copySourceProjectorLayer(src *SourceModel) (manifest.Layer, error) {
+ for _, layer := range src.Manifest.Layers {
+ if layer.MediaType != manifest.MediaTypeImageProjector {
+ continue
+ }
+ cloned, err := manifest.NewLayerFromLayer(layer.Digest, layer.MediaType, src.Source.DisplayShortest())
+ if err != nil {
+ return manifest.Layer{}, err
+ }
+ cloned.Name = layer.Name
+ return cloned, nil
+ }
+ return manifest.Layer{}, fmt.Errorf("source manifest %s has no projector layer", src.Source.DisplayShortest())
+}
+
+func writeGGUFLayer(kv outKV, tensors []*outTensor, mediaType string) (manifest.Layer, error) {
+ blobs, err := manifest.BlobsPath("")
+ if err != nil {
+ return manifest.Layer{}, err
+ }
+
+ f, err := os.CreateTemp(blobs, "compat-migrate-*.gguf")
+ if err != nil {
+ return manifest.Layer{}, err
+ }
+ defer os.Remove(f.Name())
+
+ if err := writeGGUF(f, kv, tensors); err != nil {
+ f.Close()
+ return manifest.Layer{}, err
+ }
+ if err := f.Close(); err != nil {
+ return manifest.Layer{}, err
+ }
+
+ return manifest.NewLayerFromFile(f.Name(), mediaType)
+}
diff --git a/compatmigrate/source_tensor.go b/compatmigrate/source_tensor.go
new file mode 100644
index 000000000..8ba52745a
--- /dev/null
+++ b/compatmigrate/source_tensor.go
@@ -0,0 +1,417 @@
+package compatmigrate
+
+import (
+ "encoding/binary"
+ "fmt"
+ "io"
+ "math"
+ "reflect"
+ "slices"
+ "strings"
+ "sync"
+
+ "github.com/d4l3k/go-bfloat16"
+ "github.com/x448/float16"
+
+ "github.com/ollama/ollama/fs/gguf"
+ "github.com/ollama/ollama/manifest"
+)
+
+func readAllSourceTensors(src *SourceModel) ([]*sourceTensor, error) {
+ return readSourceTensors(src.GGUFPath, src.GGUF, src.GGUFData, src.GGUFDataOffset)
+}
+
+func readAllProjectorTensors(src *SourceModel) ([]*sourceTensor, error) {
+ if src.ProjectorGGUF == nil {
+ return nil, fmt.Errorf("source manifest %s has no projector layer", src.Source.DisplayShortest())
+ }
+ return readSourceTensors(src.ProjectorPath, src.ProjectorGGUF, src.ProjectorData, src.ProjectorDataOffset)
+}
+
+func readSourceTensors(path string, g *gguf.File, readerAt io.ReaderAt, dataOffset int64) ([]*sourceTensor, error) {
+ var tensors []*sourceTensor
+ for _, info := range g.TensorInfos() {
+ if !info.Valid() {
+ continue
+ }
+ tensors = append(tensors, &sourceTensor{
+ path: path,
+ readerAt: readerAt,
+ dataOffset: dataOffset,
+ info: info,
+ name: info.Name,
+ shape: slices.Clone(info.Shape),
+ })
+ }
+ return tensors, nil
+}
+
+func copyTensor(name string, t *sourceTensor) *outTensor {
+ writer := t.Clone()
+ outType := compatOutputTensorType(name, t.name, t.info.Type)
+ if outType != t.info.Type {
+ writer.SetOutputType(outType)
+ }
+ return &outTensor{
+ Name: name,
+ Kind: uint32(outType),
+ Shape: slices.Clone(t.shape),
+ WriterTo: writer,
+ }
+}
+
+type repacker func(name string, data []float32, shape []uint64) ([]float32, error)
+
+type sourceTensor struct {
+ path string
+ readerAt io.ReaderAt
+ dataOffset int64
+ info gguf.TensorInfo
+ name string
+ shape []uint64
+ repacker repacker
+ byteLimit int64
+ outputType gguf.TensorType
+ hasOutput bool
+}
+
+func (t *sourceTensor) Clone() *sourceTensor {
+ return &sourceTensor{
+ path: t.path,
+ readerAt: t.readerAt,
+ dataOffset: t.dataOffset,
+ info: t.info,
+ name: t.name,
+ shape: slices.Clone(t.shape),
+ repacker: t.repacker,
+ byteLimit: t.byteLimit,
+ outputType: t.outputType,
+ hasOutput: t.hasOutput,
+ }
+}
+
+func (t *sourceTensor) SetRepacker(fn repacker) {
+ t.repacker = fn
+}
+
+func (t *sourceTensor) SetOutputType(kind gguf.TensorType) {
+ t.outputType = kind
+ t.hasOutput = true
+}
+
+func (t *sourceTensor) encodedType() gguf.TensorType {
+ if t.hasOutput {
+ return t.outputType
+ }
+ return t.info.Type
+}
+
+func (t *sourceTensor) GGUFWriteMemoryEstimate() uint64 {
+ if t.repacker == nil && !t.hasOutput {
+ return uint64(compatCopyBufferSize)
+ }
+
+ sourceBytes := int64ToUint64(t.info.NumBytes())
+ floatBytes := saturatingMul(tensorElementCount(t.info.Shape), 4)
+ if t.repacker != nil {
+ // Repackers often return a new slice while the decoded source slice is
+ // still live, so account for both float buffers.
+ floatBytes = saturatingMul(floatBytes, 2)
+ }
+ outputBytes := int64ToUint64(gguf.TensorInfo{
+ Name: t.name,
+ Shape: t.shape,
+ Type: t.encodedType(),
+ }.NumBytes())
+
+ return saturatingAdd(sourceBytes, floatBytes, outputBytes)
+}
+
+func (t *sourceTensor) WriteTo(w io.Writer) (int64, error) {
+ info := t.info
+ var r io.Reader
+ if t.readerAt != nil {
+ r = io.NewSectionReader(t.readerAt, t.dataOffset+int64(t.info.Offset), t.info.NumBytes())
+ } else {
+ f, err := gguf.Open(t.path)
+ if err != nil {
+ return 0, err
+ }
+ defer f.Close()
+
+ info, r, err = f.TensorReader(t.info.Name)
+ if err != nil {
+ return 0, err
+ }
+ }
+
+ outType := t.encodedType()
+ if t.repacker == nil && !t.hasOutput {
+ buf := compatCopyBufferPool.Get().(*[]byte)
+ defer compatCopyBufferPool.Put(buf)
+ if t.byteLimit > 0 {
+ return copyNBuffer(w, r, t.byteLimit, *buf)
+ }
+ return io.CopyBuffer(w, r, *buf)
+ }
+
+ dataBytes, err := io.ReadAll(r)
+ if err != nil {
+ return 0, err
+ }
+
+ data, err := decodeTensorData(info.Type, dataBytes, info.Shape)
+ if err != nil {
+ return 0, err
+ }
+
+ if t.repacker != nil {
+ data, err = t.repacker(t.name, data, info.Shape)
+ if err != nil {
+ return 0, err
+ }
+ }
+
+ n, err := encodeFloatTensor(w, outType, data)
+ return int64(n), err
+}
+
+const compatCopyBufferSize = 1 << 20
+
+var compatCopyBufferPool = newCompatCopyBufferPool()
+
+func newCompatCopyBufferPool() sync.Pool {
+ return sync.Pool{
+ New: func() any {
+ buf := make([]byte, compatCopyBufferSize)
+ return &buf
+ },
+ }
+}
+
+func copyNBuffer(dst io.Writer, src io.Reader, n int64, buf []byte) (int64, error) {
+ written, err := io.CopyBuffer(dst, io.LimitReader(src, n), buf)
+ if written != n && err == nil {
+ err = io.ErrUnexpectedEOF
+ }
+ return written, err
+}
+
+func tensorElementCount(shape []uint64) uint64 {
+ var count uint64 = 1
+ for _, dim := range shape {
+ count = saturatingMul(count, dim)
+ }
+ return count
+}
+
+func int64ToUint64(n int64) uint64 {
+ if n <= 0 {
+ return 0
+ }
+ return uint64(n)
+}
+
+func saturatingAdd(values ...uint64) uint64 {
+ var out uint64
+ for _, value := range values {
+ if out > ^uint64(0)-value {
+ return ^uint64(0)
+ }
+ out += value
+ }
+ return out
+}
+
+func saturatingMul(a, b uint64) uint64 {
+ if b != 0 && a > ^uint64(0)/b {
+ return ^uint64(0)
+ }
+ return a * b
+}
+
+func compatOutputTensorType(targetName, sourceName string, sourceType gguf.TensorType) gguf.TensorType {
+ if compatTensorMustBeF32(targetName) || compatTensorMustBeF32(sourceName) {
+ return gguf.TensorTypeF32
+ }
+ return sourceType
+}
+
+func compatTensorMustBeF32(name string) bool {
+ return strings.HasSuffix(name, ".ffn_gate_inp.weight") ||
+ strings.HasSuffix(name, ".bias") ||
+ strings.HasSuffix(name, ".shortconv.conv.weight") ||
+ strings.HasSuffix(name, ".ssm_conv1d.weight") ||
+ strings.HasPrefix(name, "a.conv1d.") ||
+ strings.Contains(name, ".conv_dw.") ||
+ name == "token_types.weight" ||
+ name == "v.class_embd" ||
+ name == "v.cls_embd" ||
+ name == "v.positional_embedding_vlm" ||
+ strings.HasPrefix(name, "v.patch_embd.weight") ||
+ strings.HasPrefix(name, "v.patch_embedding.weight") ||
+ name == "v.patch_conv.weight" ||
+ name == "v.position_embd" ||
+ name == "v.position_embd.weight" ||
+ name == "v.position_embedding.weight" ||
+ name == "v.tile_position_embd.weight" ||
+ name == "v.pre_tile_position_embd.weight" ||
+ name == "v.post_tile_position_embd.weight" ||
+ name == "s.position_embd" ||
+ strings.HasSuffix(name, "rel_pos_h") ||
+ strings.HasSuffix(name, "rel_pos_w")
+}
+
+func decodeFloatTensor(kind gguf.TensorType, b []byte) ([]float32, error) {
+ switch kind {
+ case gguf.TensorTypeF32:
+ out := make([]float32, len(b)/4)
+ for i := range out {
+ bits := binary.LittleEndian.Uint32(b[i*4:])
+ out[i] = math.Float32frombits(bits)
+ }
+ return out, nil
+ case gguf.TensorTypeF16:
+ out := make([]float32, len(b)/2)
+ for i := range out {
+ bits := binary.LittleEndian.Uint16(b[i*2:])
+ out[i] = float16.Frombits(bits).Float32()
+ }
+ return out, nil
+ case gguf.TensorTypeBF16:
+ out := make([]float32, len(b)/2)
+ for i := range out {
+ out[i] = bfloat16.ToFloat32(bfloat16.FromBytes(b[i*2 : i*2+2]))
+ }
+ return out, nil
+ default:
+ return nil, fmt.Errorf("repacking tensor type %v is unsupported", kind)
+ }
+}
+
+func encodeFloatTensor(w io.Writer, kind gguf.TensorType, data []float32) (int, error) {
+ switch kind {
+ case gguf.TensorTypeF32:
+ buf := make([]byte, 4*len(data))
+ for i, v := range data {
+ binary.LittleEndian.PutUint32(buf[i*4:], math.Float32bits(v))
+ }
+ return w.Write(buf)
+ case gguf.TensorTypeF16:
+ buf := make([]byte, 2*len(data))
+ for i, v := range data {
+ binary.LittleEndian.PutUint16(buf[i*2:], float16.Fromfloat32(v).Bits())
+ }
+ return w.Write(buf)
+ case gguf.TensorTypeBF16:
+ return w.Write(bfloat16.EncodeFloat32(data))
+ default:
+ return 0, fmt.Errorf("encoding tensor type %v is unsupported", kind)
+ }
+}
+
+func normalizeGGUFValue(v any) any {
+ rv := reflect.ValueOf(v)
+ switch rv.Kind() {
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ if rv.Type().Bits() <= 32 {
+ return int32(rv.Int())
+ }
+ return rv.Int()
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
+ if rv.Type().Bits() <= 32 {
+ return uint32(rv.Uint())
+ }
+ return rv.Uint()
+ case reflect.Float32:
+ return float32(rv.Float())
+ case reflect.Float64:
+ return float32(rv.Float())
+ case reflect.Bool:
+ return rv.Bool()
+ case reflect.String:
+ return rv.String()
+ case reflect.Slice:
+ switch rv.Type().Elem().Kind() {
+ case reflect.String:
+ out := make([]string, rv.Len())
+ for i := range out {
+ out[i] = rv.Index(i).String()
+ }
+ return out
+ case reflect.Bool:
+ out := make([]bool, rv.Len())
+ for i := range out {
+ out[i] = rv.Index(i).Bool()
+ }
+ return out
+ case reflect.Int8:
+ out := make([]int8, rv.Len())
+ for i := range out {
+ out[i] = int8(rv.Index(i).Int())
+ }
+ return out
+ case reflect.Uint8:
+ out := make([]uint8, rv.Len())
+ for i := range out {
+ out[i] = uint8(rv.Index(i).Uint())
+ }
+ return out
+ case reflect.Float32, reflect.Float64:
+ // Model metadata floats fit comfortably in float32; the GGUF
+ // writer has no float64 array support and llama.cpp expects f32
+ // arrays for the keys the migrators carry.
+ out := make([]float32, rv.Len())
+ for i := range out {
+ out[i] = float32(rv.Index(i).Convert(reflect.TypeFor[float64]()).Float())
+ }
+ return out
+ case reflect.Int16, reflect.Int32:
+ out := make([]int32, rv.Len())
+ for i := range out {
+ out[i] = int32(rv.Index(i).Int())
+ }
+ return out
+ case reflect.Int, reflect.Int64:
+ // Preserve 64-bit values (e.g. token ids) rather than silently
+ // truncating them to 32 bits.
+ out := make([]int64, rv.Len())
+ for i := range out {
+ out[i] = rv.Index(i).Int()
+ }
+ return out
+ case reflect.Uint16, reflect.Uint32:
+ out := make([]uint32, rv.Len())
+ for i := range out {
+ out[i] = uint32(rv.Index(i).Uint())
+ }
+ return out
+ case reflect.Uint, reflect.Uint64:
+ out := make([]uint64, rv.Len())
+ for i := range out {
+ out[i] = rv.Index(i).Uint()
+ }
+ return out
+ }
+ }
+
+ return v
+}
+
+// requiredBytesFromSource estimates the disk space a conversion needs: the
+// converted model is roughly the size of the source model layer, padded by
+// the migration margin for metadata growth and tensor dtype promotions, plus
+// fixed headroom. Projector layers are small relative to the model, so they
+// are covered by the margin and headroom rather than summed.
+func requiredBytesFromSource(src *SourceModel) uint64 {
+ var sourceBytes uint64
+ for _, layer := range src.Manifest.Layers {
+ if layer.MediaType == manifest.MediaTypeImageModel {
+ sourceBytes += uint64(layer.Size)
+ }
+ }
+ if sourceBytes == 0 {
+ return compatMigrationHeadroom
+ }
+ return sourceBytes + sourceBytes/compatMigrationMarginDenom + compatMigrationHeadroom
+}
diff --git a/compatmigrate/tensor_layout.go b/compatmigrate/tensor_layout.go
new file mode 100644
index 000000000..8654c06c9
--- /dev/null
+++ b/compatmigrate/tensor_layout.go
@@ -0,0 +1,150 @@
+package compatmigrate
+
+import (
+ "fmt"
+ "slices"
+)
+
+// Row-major float32 helpers for the repackers; dims[0] is the outermost
+// dimension, matching the tensor library they replaced.
+
+func tensorDims(shape []uint64) []int {
+ dims := make([]int, len(shape))
+ for i, d := range shape {
+ dims[i] = int(d)
+ }
+ return dims
+}
+
+func tensorSize(dims []int) int {
+ n := 1
+ for _, d := range dims {
+ n *= d
+ }
+ return n
+}
+
+func checkTensorDims(data []float32, dims []int) error {
+ for _, d := range dims {
+ if d < 0 {
+ return fmt.Errorf("invalid tensor dims %v", dims)
+ }
+ }
+ if want := tensorSize(dims); len(data) != want {
+ return fmt.Errorf("tensor has %d elements, expected %d for dims %v", len(data), want, dims)
+ }
+ return nil
+}
+
+// sliceTensorDim returns elements [start, end) along dim as a new contiguous
+// tensor whose dims[dim] is end-start.
+func sliceTensorDim(data []float32, dims []int, dim, start, end int) ([]float32, error) {
+ if err := checkTensorDims(data, dims); err != nil {
+ return nil, err
+ }
+ if dim < 0 || dim >= len(dims) {
+ return nil, fmt.Errorf("slice dimension %d out of range for dims %v", dim, dims)
+ }
+ if start < 0 || end < start || end > dims[dim] {
+ return nil, fmt.Errorf("slice [%d:%d] out of range for dimension %d of dims %v", start, end, dim, dims)
+ }
+
+ outer := tensorSize(dims[:dim])
+ inner := tensorSize(dims[dim+1:])
+ width := (end - start) * inner
+ out := make([]float32, 0, outer*width)
+ for o := range outer {
+ base := (o*dims[dim] + start) * inner
+ out = append(out, data[base:base+width]...)
+ }
+ return out, nil
+}
+
+type tensorPart struct {
+ data []float32
+ dims []int
+}
+
+// concatTensorDim joins parts along dim; every other dimension must match.
+func concatTensorDim(dim int, parts ...tensorPart) ([]float32, []int, error) {
+ if len(parts) == 0 {
+ return nil, nil, fmt.Errorf("concat: no tensors")
+ }
+ dims := slices.Clone(parts[0].dims)
+ if dim < 0 || dim >= len(dims) {
+ return nil, nil, fmt.Errorf("concat dimension %d out of range for dims %v", dim, dims)
+ }
+ dims[dim] = 0
+ for _, p := range parts {
+ if err := checkTensorDims(p.data, p.dims); err != nil {
+ return nil, nil, err
+ }
+ if len(p.dims) != len(dims) {
+ return nil, nil, fmt.Errorf("concat: rank mismatch %v vs %v", parts[0].dims, p.dims)
+ }
+ for i := range dims {
+ if i != dim && p.dims[i] != dims[i] {
+ return nil, nil, fmt.Errorf("concat: incompatible dims %v vs %v", parts[0].dims, p.dims)
+ }
+ }
+ dims[dim] += p.dims[dim]
+ }
+
+ outer := tensorSize(dims[:dim])
+ inner := tensorSize(dims[dim+1:])
+ out := make([]float32, 0, tensorSize(dims))
+ for o := range outer {
+ for _, p := range parts {
+ width := p.dims[dim] * inner
+ out = append(out, p.data[o*width:(o+1)*width]...)
+ }
+ }
+ return out, dims, nil
+}
+
+// permuteTensor reorders axes so result dimension i is source dimension
+// perm[i], like numpy.transpose.
+func permuteTensor(data []float32, dims []int, perm ...int) ([]float32, []int, error) {
+ if err := checkTensorDims(data, dims); err != nil {
+ return nil, nil, err
+ }
+ if len(perm) != len(dims) {
+ return nil, nil, fmt.Errorf("permutation %v does not match dims %v", perm, dims)
+ }
+
+ srcStrides := make([]int, len(dims))
+ stride := 1
+ for i := len(dims) - 1; i >= 0; i-- {
+ srcStrides[i] = stride
+ stride *= dims[i]
+ }
+
+ seen := make([]bool, len(dims))
+ outDims := make([]int, len(dims))
+ strides := make([]int, len(dims))
+ for i, p := range perm {
+ if p < 0 || p >= len(dims) || seen[p] {
+ return nil, nil, fmt.Errorf("invalid permutation %v for dims %v", perm, dims)
+ }
+ seen[p] = true
+ outDims[i] = dims[p]
+ strides[i] = srcStrides[p]
+ }
+
+ out := make([]float32, len(data))
+ idx := make([]int, len(dims))
+ src := 0
+ for i := range out {
+ out[i] = data[src]
+ for axis := len(idx) - 1; axis >= 0; axis-- {
+ idx[axis]++
+ src += strides[axis]
+ if idx[axis] < outDims[axis] {
+ break
+ }
+ src -= idx[axis] * strides[axis]
+ idx[axis] = 0
+ }
+ }
+ return out, outDims, nil
+}
diff --git a/compatmigrate/tensor_layout_test.go b/compatmigrate/tensor_layout_test.go
new file mode 100644
index 000000000..516e21220
--- /dev/null
+++ b/compatmigrate/tensor_layout_test.go
@@ -0,0 +1,275 @@
+package compatmigrate
+
+import (
+ "slices"
+ "testing"
+
+ "github.com/ollama/ollama/fs/gguf"
+)
+
+func sequence(n int) []float32 {
+ out := make([]float32, n)
+ for i := range out {
+ out[i] = float32(i)
+ }
+ return out
+}
+
+func TestSliceTensorDim(t *testing.T) {
+ data := sequence(12)
+ dims := []int{2, 3, 2}
+
+ cases := []struct {
+ dim, start, end int
+ want []float32
+ }{
+ {dim: 0, start: 1, end: 2, want: []float32{6, 7, 8, 9, 10, 11}},
+ {dim: 1, start: 1, end: 3, want: []float32{2, 3, 4, 5, 8, 9, 10, 11}},
+ {dim: 2, start: 0, end: 1, want: []float32{0, 2, 4, 6, 8, 10}},
+ {dim: 1, start: 0, end: 3, want: data},
+ {dim: 1, start: 1, end: 1, want: []float32{}},
+ }
+ for _, tc := range cases {
+ got, err := sliceTensorDim(data, dims, tc.dim, tc.start, tc.end)
+ if err != nil {
+ t.Fatalf("sliceTensorDim(dim=%d, %d:%d) error = %v", tc.dim, tc.start, tc.end, err)
+ }
+ if !slices.Equal(got, tc.want) {
+ t.Errorf("sliceTensorDim(dim=%d, %d:%d)\n got %v\nwant %v", tc.dim, tc.start, tc.end, got, tc.want)
+ }
+ }
+
+ bad := []struct {
+ name string
+ data []float32
+ dim, start, end int
+ }{
+ {name: "dim out of range", data: data, dim: 3, start: 0, end: 1},
+ {name: "negative dim", data: data, dim: -1, start: 0, end: 1},
+ {name: "end before start", data: data, dim: 1, start: 2, end: 1},
+ {name: "end past dim", data: data, dim: 1, start: 0, end: 4},
+ {name: "negative start", data: data, dim: 1, start: -1, end: 1},
+ {name: "data size mismatch", data: data[:11], dim: 0, start: 0, end: 1},
+ }
+ for _, tc := range bad {
+ if _, err := sliceTensorDim(tc.data, dims, tc.dim, tc.start, tc.end); err == nil {
+ t.Errorf("%s: expected error", tc.name)
+ }
+ }
+}
+
+func TestConcatTensorDim(t *testing.T) {
+ a := tensorPart{data: []float32{0, 1, 2, 3}, dims: []int{2, 2}}
+ b := tensorPart{data: []float32{4, 5, 6, 7, 8, 9}, dims: []int{2, 3}}
+ c := tensorPart{data: []float32{4, 5}, dims: []int{1, 2}}
+
+ got, dims, err := concatTensorDim(1, a, b)
+ if err != nil {
+ t.Fatalf("concatTensorDim(1) error = %v", err)
+ }
+ if !slices.Equal(dims, []int{2, 5}) {
+ t.Errorf("concatTensorDim(1) dims = %v, want [2 5]", dims)
+ }
+ if want := []float32{0, 1, 4, 5, 6, 2, 3, 7, 8, 9}; !slices.Equal(got, want) {
+ t.Errorf("concatTensorDim(1)\n got %v\nwant %v", got, want)
+ }
+
+ got, dims, err = concatTensorDim(0, a, c)
+ if err != nil {
+ t.Fatalf("concatTensorDim(0) error = %v", err)
+ }
+ if !slices.Equal(dims, []int{3, 2}) {
+ t.Errorf("concatTensorDim(0) dims = %v, want [3 2]", dims)
+ }
+ if want := []float32{0, 1, 2, 3, 4, 5}; !slices.Equal(got, want) {
+ t.Errorf("concatTensorDim(0)\n got %v\nwant %v", got, want)
+ }
+
+ got, dims, err = concatTensorDim(0, a)
+ if err != nil {
+ t.Fatalf("concatTensorDim(single) error = %v", err)
+ }
+ if !slices.Equal(dims, a.dims) || !slices.Equal(got, a.data) {
+ t.Errorf("concatTensorDim(single) = %v %v, want %v %v", got, dims, a.data, a.dims)
+ }
+
+ bad := []struct {
+ name string
+ dim int
+ parts []tensorPart
+ }{
+ {name: "no parts", dim: 0},
+ {name: "dim out of range", dim: 2, parts: []tensorPart{a, b}},
+ {name: "incompatible dims", dim: 1, parts: []tensorPart{a, c}},
+ {name: "rank mismatch", dim: 0, parts: []tensorPart{a, {data: []float32{0, 1}, dims: []int{2}}}},
+ {name: "data size mismatch", dim: 0, parts: []tensorPart{a, {data: []float32{0}, dims: []int{1, 2}}}},
+ }
+ for _, tc := range bad {
+ if _, _, err := concatTensorDim(tc.dim, tc.parts...); err == nil {
+ t.Errorf("%s: expected error", tc.name)
+ }
+ }
+}
+
+func TestPermuteTensor(t *testing.T) {
+ cases := []struct {
+ dims []int
+ perm []int
+ wantDims []int
+ want []float32
+ }{
+ {dims: []int{2, 3}, perm: []int{1, 0}, wantDims: []int{3, 2}, want: []float32{0, 3, 1, 4, 2, 5}},
+ {dims: []int{2, 3}, perm: []int{0, 1}, wantDims: []int{2, 3}, want: sequence(6)},
+ {dims: []int{2, 2, 3}, perm: []int{0, 2, 1}, wantDims: []int{2, 3, 2}, want: []float32{0, 3, 1, 4, 2, 5, 6, 9, 7, 10, 8, 11}},
+ {dims: []int{2, 2, 3}, perm: []int{2, 0, 1}, wantDims: []int{3, 2, 2}, want: []float32{0, 3, 6, 9, 1, 4, 7, 10, 2, 5, 8, 11}},
+ {dims: []int{3}, perm: []int{0}, wantDims: []int{3}, want: sequence(3)},
+ }
+ for _, tc := range cases {
+ got, dims, err := permuteTensor(sequence(tensorSize(tc.dims)), tc.dims, tc.perm...)
+ if err != nil {
+ t.Fatalf("permuteTensor(%v, %v) error = %v", tc.dims, tc.perm, err)
+ }
+ if !slices.Equal(dims, tc.wantDims) {
+ t.Errorf("permuteTensor(%v, %v) dims = %v, want %v", tc.dims, tc.perm, dims, tc.wantDims)
+ }
+ if !slices.Equal(got, tc.want) {
+ t.Errorf("permuteTensor(%v, %v)\n got %v\nwant %v", tc.dims, tc.perm, got, tc.want)
+ }
+ }
+
+ bad := []struct {
+ name string
+ data []float32
+ dims []int
+ perm []int
+ }{
+ {name: "perm too short", data: sequence(6), dims: []int{2, 3}, perm: []int{0}},
+ {name: "repeated axis", data: sequence(6), dims: []int{2, 3}, perm: []int{0, 0}},
+ {name: "axis out of range", data: sequence(6), dims: []int{2, 3}, perm: []int{0, 2}},
+ {name: "data size mismatch", data: sequence(5), dims: []int{2, 3}, perm: []int{1, 0}},
+ }
+ for _, tc := range bad {
+ if _, _, err := permuteTensor(tc.data, tc.dims, tc.perm...); err == nil {
+ t.Errorf("%s: expected error", tc.name)
+ }
+ }
+}
+
+// Two heads, each with qkNope=2 and vHeadDim=1 rows of kvLoraRank=3, laid out
+// with heads outermost (kv last) or kv outermost (kv first).
+func TestGLM47FlashRepackKVB(t *testing.T) {
+ mla := glm47FlashMLA{numHeads: 2, qkNope: 2, vHeadDim: 1, kvLoraRank: 3}
+ data := sequence(18)
+
+ cases := []struct {
+ name string
+ kvFirst bool
+ shape []uint64
+ wantK []float32
+ wantV []float32
+ }{
+ {
+ name: "kv last",
+ shape: []uint64{6, 3},
+ wantK: []float32{0, 3, 1, 4, 2, 5, 9, 12, 10, 13, 11, 14},
+ wantV: []float32{6, 7, 8, 15, 16, 17},
+ },
+ {
+ name: "kv first",
+ kvFirst: true,
+ shape: []uint64{3, 6},
+ wantK: []float32{0, 1, 6, 7, 12, 13, 3, 4, 9, 10, 15, 16},
+ wantV: []float32{2, 8, 14, 5, 11, 17},
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ gotK, err := glm47FlashRepackKVB(mla, true, tc.kvFirst, mla.numHeads)("kv_b", data, tc.shape)
+ if err != nil {
+ t.Fatalf("repack K error = %v", err)
+ }
+ if !slices.Equal(gotK, tc.wantK) {
+ t.Errorf("repack K\n got %v\nwant %v", gotK, tc.wantK)
+ }
+
+ gotV, err := glm47FlashRepackKVB(mla, false, tc.kvFirst, mla.numHeads)("kv_b", data, tc.shape)
+ if err != nil {
+ t.Fatalf("repack V error = %v", err)
+ }
+ if !slices.Equal(gotV, tc.wantV) {
+ t.Errorf("repack V\n got %v\nwant %v", gotV, tc.wantV)
+ }
+ })
+ }
+
+ if _, err := glm47FlashRepackKVB(mla, true, false, mla.numHeads)("kv_b", sequence(12), []uint64{4, 3}); err == nil {
+ t.Error("expected error when the tensor does not fill the MLA dims")
+ }
+ if _, err := glm47FlashRepackKVB(mla, true, true, mla.numHeads)("kv_b", data, []uint64{3, 3, 2}); err == nil {
+ t.Error("expected error transposing a 3D kv-first tensor")
+ }
+}
+
+func TestGLM47FlashSplitKVB(t *testing.T) {
+ mla := glm47FlashMLA{numHeads: 2, qkNope: 2, vHeadDim: 1, kvLoraRank: 3, qkRope: 4}
+ data := sequence(18)
+
+ cases := []struct {
+ name string
+ shape []uint64
+ wantK []float32
+ wantV []float32
+ }{
+ {
+ name: "kv last",
+ shape: []uint64{6, 3},
+ wantK: []float32{0, 3, 1, 4, 2, 5, 9, 12, 10, 13, 11, 14},
+ wantV: []float32{6, 7, 8, 15, 16, 17},
+ },
+ {
+ name: "kv first",
+ shape: []uint64{3, 6},
+ wantK: []float32{0, 1, 6, 7, 12, 13, 3, 4, 9, 10, 15, 16},
+ wantV: []float32{2, 8, 14, 5, 11, 17},
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ source := sourceTensorF16("blk.0.attn_kv_b.weight", tc.shape, data)
+ got, err := glm47FlashSplitKVB(source, mla)
+ if err != nil {
+ t.Fatalf("glm47FlashSplitKVB() error = %v", err)
+ }
+ if len(got) != 2 {
+ t.Fatalf("expected k and v tensors, got %d", len(got))
+ }
+
+ k, v := got[0], got[1]
+ if k.Name != "blk.0.attn_k_b.weight" || v.Name != "blk.0.attn_v_b.weight" {
+ t.Errorf("unexpected names %q %q", k.Name, v.Name)
+ }
+ if !slices.Equal(k.Shape, []uint64{2, 3, 2}) {
+ t.Errorf("k shape = %v, want [2 3 2]", k.Shape)
+ }
+ if !slices.Equal(v.Shape, []uint64{3, 1, 2}) {
+ t.Errorf("v shape = %v, want [3 1 2]", v.Shape)
+ }
+ if k.Kind != uint32(gguf.TensorTypeF16) || v.Kind != uint32(gguf.TensorTypeF16) {
+ t.Errorf("unexpected kinds %d %d", k.Kind, v.Kind)
+ }
+ if values := writeTensorF16(t, k); !slices.Equal(values, tc.wantK) {
+ t.Errorf("k values\n got %v\nwant %v", values, tc.wantK)
+ }
+ if values := writeTensorF16(t, v); !slices.Equal(values, tc.wantV) {
+ t.Errorf("v values\n got %v\nwant %v", values, tc.wantV)
+ }
+ })
+ }
+
+ if _, err := glm47FlashSplitKVB(sourceTensorF16("blk.0.attn_kv_b.weight", []uint64{9, 2}, data), mla); err == nil {
+ t.Error("expected error when neither dimension matches kv_lora_rank")
+ }
+ if _, err := glm47FlashSplitKVB(sourceTensorF16("blk.0.attn_kv_b.weight", []uint64{3, 3, 2}, data), mla); err == nil {
+ t.Error("expected error for a 3D source tensor")
+ }
+}
diff --git a/compatmigrate/tensor_ops.go b/compatmigrate/tensor_ops.go
new file mode 100644
index 000000000..3251bd1a0
--- /dev/null
+++ b/compatmigrate/tensor_ops.go
@@ -0,0 +1,379 @@
+package compatmigrate
+
+import (
+ "fmt"
+ "io"
+ "slices"
+
+ "github.com/ollama/ollama/fs/gguf"
+)
+
+func splitSourceTensorDim(t *sourceTensor, dim int, names ...string) ([]*outTensor, error) {
+ if dim < 0 || dim >= len(t.shape) {
+ return nil, fmt.Errorf("split dimension %d out of range for tensor %s shape %v", dim, t.name, t.shape)
+ }
+ if len(names) == 0 {
+ return nil, fmt.Errorf("split tensor %s: no target names", t.name)
+ }
+ if t.shape[dim]%uint64(len(names)) != 0 {
+ return nil, fmt.Errorf("split tensor %s: dimension %d size %d is not divisible by %d", t.name, dim, t.shape[dim], len(names))
+ }
+
+ out := make([]*outTensor, 0, len(names))
+ offset := 0
+ for _, name := range names {
+ part := int(t.shape[dim] / uint64(len(names)))
+ start := offset
+ end := offset + part
+ offset = end
+
+ shape := slices.Clone(t.shape)
+ shape[dim] = uint64(part)
+
+ writer := t.Clone()
+ writer.shape = slices.Clone(shape)
+ writer.SetRepacker(func(_ string, data []float32, sourceShape []uint64) ([]float32, error) {
+ return sliceTensorDim(data, tensorDims(sourceShape), dim, start, end)
+ })
+ outType := compatOutputTensorType(name, t.name, t.info.Type)
+ if outType != t.info.Type {
+ writer.SetOutputType(outType)
+ }
+
+ out = append(out, &outTensor{
+ Name: name,
+ Kind: uint32(outType),
+ Shape: shape,
+ WriterTo: writer,
+ })
+ }
+
+ return out, nil
+}
+
+func concatSourceTensorsDim(dim int, name string, tensors ...*sourceTensor) (*outTensor, error) {
+ if len(tensors) == 0 {
+ return nil, fmt.Errorf("concat tensor %s: no source tensors", name)
+ }
+ if dim < 0 || dim >= len(tensors[0].shape) {
+ return nil, fmt.Errorf("concat tensor %s: dimension %d out of range for shape %v", name, dim, tensors[0].shape)
+ }
+
+ kind := compatOutputTensorType(name, tensors[0].name, tensors[0].info.Type)
+ shape := slices.Clone(tensors[0].shape)
+ shape[dim] = 0
+ for _, t := range tensors {
+ if compatOutputTensorType(name, t.name, t.info.Type) != kind {
+ return nil, fmt.Errorf("concat tensor %s: mixed tensor types %v and %v", name, kind, t.info.Type)
+ }
+ if len(t.shape) != len(shape) {
+ return nil, fmt.Errorf("concat tensor %s: rank mismatch %v vs %v", name, shape, t.shape)
+ }
+ for i := range shape {
+ if i == dim {
+ continue
+ }
+ if t.shape[i] != shape[i] {
+ return nil, fmt.Errorf("concat tensor %s: incompatible shape %v vs %v", name, shape, t.shape)
+ }
+ }
+ shape[dim] += t.shape[dim]
+ }
+
+ return &outTensor{
+ Name: name,
+ Kind: uint32(kind),
+ Shape: shape,
+ WriterTo: sourceTensorConcat{tensors: tensors, dim: dim, kind: kind},
+ }, nil
+}
+
+func concatSourceTensorsSlowDim(dim int, name string, tensors ...*sourceTensor) (*outTensor, error) {
+ if len(tensors) == 0 {
+ return nil, fmt.Errorf("concat tensor %s: no source tensors", name)
+ }
+ if dim < 0 || dim >= len(tensors[0].shape) {
+ return nil, fmt.Errorf("concat tensor %s: dimension %d out of range for shape %v", name, dim, tensors[0].shape)
+ }
+ if dim != len(tensors[0].shape)-1 {
+ return nil, fmt.Errorf("concat tensor %s: dimension %d is not the slowest dimension for shape %v", name, dim, tensors[0].shape)
+ }
+
+ kind := compatOutputTensorType(name, tensors[0].name, tensors[0].info.Type)
+ shape := slices.Clone(tensors[0].shape)
+ shape[dim] = 0
+ for _, t := range tensors {
+ if compatOutputTensorType(name, t.name, t.info.Type) != kind {
+ return nil, fmt.Errorf("concat tensor %s: mixed tensor types %v and %v", name, kind, t.info.Type)
+ }
+ if len(t.shape) != len(shape) {
+ return nil, fmt.Errorf("concat tensor %s: rank mismatch %v vs %v", name, shape, t.shape)
+ }
+ for i := range shape {
+ if i == dim {
+ continue
+ }
+ if t.shape[i] != shape[i] {
+ return nil, fmt.Errorf("concat tensor %s: incompatible shape %v vs %v", name, shape, t.shape)
+ }
+ }
+ shape[dim] += t.shape[dim]
+ }
+
+ return &outTensor{
+ Name: name,
+ Kind: uint32(kind),
+ Shape: shape,
+ WriterTo: sourceTensorSlowDimConcat{tensors: tensors},
+ }, nil
+}
+
+func concatSourceTensorsDimKind(dim int, name string, kind gguf.TensorType, tensors ...*sourceTensor) (*outTensor, error) {
+ if len(tensors) == 0 {
+ return nil, fmt.Errorf("concat tensor %s: no source tensors", name)
+ }
+ if dim < 0 || dim >= len(tensors[0].shape) {
+ return nil, fmt.Errorf("concat tensor %s: dimension %d out of range for shape %v", name, dim, tensors[0].shape)
+ }
+
+ shape := slices.Clone(tensors[0].shape)
+ shape[dim] = 0
+ for _, t := range tensors {
+ if len(t.shape) != len(shape) {
+ return nil, fmt.Errorf("concat tensor %s: rank mismatch %v vs %v", name, shape, t.shape)
+ }
+ for i := range shape {
+ if i == dim {
+ continue
+ }
+ if t.shape[i] != shape[i] {
+ return nil, fmt.Errorf("concat tensor %s: incompatible shape %v vs %v", name, shape, t.shape)
+ }
+ }
+ shape[dim] += t.shape[dim]
+ }
+
+ return &outTensor{
+ Name: name,
+ Kind: uint32(kind),
+ Shape: shape,
+ WriterTo: sourceTensorConcat{tensors: tensors, dim: dim, kind: kind},
+ }, nil
+}
+
+func stackSourceTensors(name string, tensors ...*sourceTensor) (*outTensor, error) {
+ if len(tensors) == 0 {
+ return nil, fmt.Errorf("stack tensor %s: no source tensors", name)
+ }
+
+ kind := compatOutputTensorType(name, tensors[0].name, tensors[0].info.Type)
+ rawCopy := kind == tensors[0].info.Type
+ baseShape := slices.Clone(tensors[0].shape)
+ for _, t := range tensors {
+ outType := compatOutputTensorType(name, t.name, t.info.Type)
+ if outType != kind {
+ return nil, fmt.Errorf("stack tensor %s: mixed tensor types %v and %v", name, kind, t.info.Type)
+ }
+ rawCopy = rawCopy && outType == t.info.Type
+ if !slices.Equal(t.shape, baseShape) {
+ return nil, fmt.Errorf("stack tensor %s: incompatible shape %v vs %v", name, baseShape, t.shape)
+ }
+ }
+
+ shape := slices.Clone(baseShape)
+ if len(shape) >= 3 && shape[2] == 1 {
+ // Some converters emit per-item tensors with a singleton third dim;
+ // reuse it as the stack dimension instead of appending a fourth.
+ shape[2] = uint64(len(tensors))
+ } else {
+ shape = append(shape, uint64(len(tensors)))
+ }
+
+ var writer io.WriterTo = sourceTensorStack{tensors: tensors, kind: kind}
+ if rawCopy {
+ writer = sourceTensorSlowDimConcat{tensors: tensors}
+ }
+
+ return &outTensor{
+ Name: name,
+ Kind: uint32(kind),
+ Shape: shape,
+ WriterTo: writer,
+ }, nil
+}
+
+type sourceTensorConcat struct {
+ tensors []*sourceTensor
+ dim int
+ kind gguf.TensorType
+}
+
+func (c sourceTensorConcat) GGUFWriteMemoryEstimate() uint64 {
+ var sourceBytes, inputFloatBytes, outputElements uint64
+ for _, source := range c.tensors {
+ sourceBytes = saturatingAdd(sourceBytes, int64ToUint64(source.info.NumBytes()))
+ elements := tensorElementCount(source.shape)
+ inputFloatBytes = saturatingAdd(inputFloatBytes, saturatingMul(elements, 4))
+ outputElements = saturatingAdd(outputElements, elements)
+ }
+
+ return saturatingAdd(sourceBytes, inputFloatBytes, saturatingMul(outputElements, 4), ggufTensorBytes(c.kind, outputElements))
+}
+
+func (c sourceTensorConcat) WriteTo(w io.Writer) (int64, error) {
+ parts := make([]tensorPart, 0, len(c.tensors))
+ for _, source := range c.tensors {
+ data, err := readSourceTensorFloatData(source)
+ if err != nil {
+ return 0, err
+ }
+ parts = append(parts, tensorPart{data: data, dims: tensorDims(source.shape)})
+ }
+
+ data, _, err := concatTensorDim(c.dim, parts...)
+ if err != nil {
+ return 0, err
+ }
+
+ n, err := encodeFloatTensor(w, c.kind, data)
+ return int64(n), err
+}
+
+type sourceTensorSlowDimConcat struct {
+ tensors []*sourceTensor
+}
+
+func (c sourceTensorSlowDimConcat) GGUFWriteMemoryEstimate() uint64 {
+ total := uint64(compatCopyBufferSize)
+ for _, source := range c.tensors {
+ total = saturatingAdd(total, int64ToUint64(source.info.NumBytes()))
+ }
+ return total
+}
+
+func (c sourceTensorSlowDimConcat) WriteTo(w io.Writer) (int64, error) {
+ var total int64
+ for _, source := range c.tensors {
+ n, err := source.WriteTo(w)
+ total += n
+ if err != nil {
+ return total, err
+ }
+ }
+ return total, nil
+}
+
+type sourceTensorStack struct {
+ tensors []*sourceTensor
+ kind gguf.TensorType
+}
+
+func (s sourceTensorStack) GGUFWriteMemoryEstimate() uint64 {
+ var sourceBytes, inputFloatBytes, outputElements uint64
+ for _, source := range s.tensors {
+ sourceBytes = saturatingAdd(sourceBytes, int64ToUint64(source.info.NumBytes()))
+ elements := tensorElementCount(source.shape)
+ inputFloatBytes = saturatingAdd(inputFloatBytes, saturatingMul(elements, 4))
+ outputElements = saturatingAdd(outputElements, elements)
+ }
+
+ return saturatingAdd(sourceBytes, inputFloatBytes, ggufTensorBytes(s.kind, outputElements))
+}
+
+func (s sourceTensorStack) WriteTo(w io.Writer) (int64, error) {
+ var total int64
+ for _, source := range s.tensors {
+ data, err := readSourceTensorFloatData(source)
+ if err != nil {
+ return total, err
+ }
+ n, err := encodeFloatTensor(w, s.kind, data)
+ total += int64(n)
+ if err != nil {
+ return total, err
+ }
+ }
+ return total, nil
+}
+
+func ggufTensorBytes(kind gguf.TensorType, elements uint64) uint64 {
+ return uint64(float64(elements) * kind.NumBytes())
+}
+
+func readSourceTensorFloatData(t *sourceTensor) ([]float32, error) {
+ info := t.info
+ var r io.Reader
+ if t.readerAt != nil {
+ r = io.NewSectionReader(t.readerAt, t.dataOffset+int64(t.info.Offset), t.info.NumBytes())
+ } else {
+ f, err := gguf.Open(t.path)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+
+ info, r, err = f.TensorReader(t.info.Name)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ dataBytes, err := io.ReadAll(r)
+ if err != nil {
+ return nil, err
+ }
+
+ return decodeTensorData(info.Type, dataBytes, info.Shape)
+}
+
+func copyTensorPrefix(name string, t *sourceTensor, shape []uint64) *outTensor {
+ writer := t.Clone()
+ writer.shape = slices.Clone(shape)
+ writer.byteLimit = gguf.TensorInfo{Name: name, Shape: shape, Type: t.info.Type}.NumBytes()
+ return &outTensor{
+ Name: name,
+ Kind: uint32(t.info.Type),
+ Shape: slices.Clone(shape),
+ WriterTo: writer,
+ }
+}
+
+func decodeTensorData(kind gguf.TensorType, b []byte, shape []uint64) ([]float32, error) {
+ switch kind {
+ case gguf.TensorTypeQ8_0, gguf.TensorTypeQ5_0, gguf.TensorTypeQ4_K, gguf.TensorTypeQ6_K:
+ if len(shape) == 0 {
+ return nil, fmt.Errorf("decoded tensor shape is empty for %v", kind)
+ }
+
+ cols := int(shape[0])
+ rows := 1
+ if len(shape) > 1 {
+ rows = int(shape[1])
+ }
+ if rows <= 0 || cols <= 0 {
+ return nil, fmt.Errorf("invalid tensor shape %v for %v", shape, kind)
+ }
+
+ rowBytes := gguf.TensorInfo{Name: "row", Shape: []uint64{uint64(cols)}, Type: kind}.NumBytes()
+ if rowBytes <= 0 {
+ return nil, fmt.Errorf("unsupported row width %d for %v", cols, kind)
+ }
+ if want := int(rowBytes) * rows; len(b) != want {
+ return nil, fmt.Errorf("tensor has %d bytes, expected %d for shape %v type %v", len(b), want, shape, kind)
+ }
+
+ out := make([]float32, cols*rows)
+ for row := range rows {
+ start := row * int(rowBytes)
+ end := start + int(rowBytes)
+ decoded, err := decodeTensorRow(kind, b[start:end], cols)
+ if err != nil {
+ return nil, err
+ }
+ copy(out[row*cols:], decoded)
+ }
+ return out, nil
+ default:
+ return decodeFloatTensor(kind, b)
+ }
+}
diff --git a/compatmigrate/tensor_row.go b/compatmigrate/tensor_row.go
new file mode 100644
index 000000000..6ea18550e
--- /dev/null
+++ b/compatmigrate/tensor_row.go
@@ -0,0 +1,271 @@
+package compatmigrate
+
+import (
+ "encoding/binary"
+ "fmt"
+ "io"
+ "slices"
+
+ "github.com/x448/float16"
+
+ "github.com/ollama/ollama/fs/gguf"
+)
+
+const (
+ qk8_0 = 32
+ qk5_0 = 32
+ qkK = 256
+ q8_0BlkSize = 34
+ q5_0BlkSize = 22
+ q4KBlkSize = 144
+ q6KBlkSize = 210
+)
+
+type sourceTensorRow struct {
+ tensor *sourceTensor
+ row uint64
+ shape []uint64
+}
+
+func copyTensorRowF32(name string, t *sourceTensor, row uint64) (*outTensor, error) {
+ if len(t.shape) < 2 {
+ return nil, fmt.Errorf("tensor %s shape %v cannot be row-sliced", t.name, t.shape)
+ }
+ if row >= t.shape[1] {
+ return nil, fmt.Errorf("row %d out of range for tensor %s shape %v", row, t.name, t.shape)
+ }
+
+ return &outTensor{
+ Name: name,
+ Kind: uint32(gguf.TensorTypeF32),
+ Shape: []uint64{t.shape[0]},
+ WriterTo: &sourceTensorRow{tensor: t, row: row, shape: []uint64{t.shape[0]}},
+ }, nil
+}
+
+func (r *sourceTensorRow) WriteTo(w io.Writer) (int64, error) {
+ t := r.tensor
+ rowBytes := gguf.TensorInfo{Name: t.name, Shape: r.shape, Type: t.info.Type}.NumBytes()
+ if rowBytes <= 0 {
+ return 0, fmt.Errorf("unsupported row tensor type %v for %s", t.info.Type, t.name)
+ }
+
+ readerAt := t.readerAt
+ dataOffset := t.dataOffset
+ var g *gguf.File
+ var err error
+ if readerAt == nil {
+ g, err = gguf.Open(t.path)
+ if err != nil {
+ return 0, err
+ }
+ defer g.Close()
+ readerAt = g.ReaderAt()
+ dataOffset = g.TensorDataOffset()
+ }
+
+ b := make([]byte, rowBytes)
+ offset := dataOffset + int64(t.info.Offset) + int64(r.row)*rowBytes
+ if _, err := readerAt.ReadAt(b, offset); err != nil {
+ return 0, err
+ }
+
+ data, err := decodeTensorRow(t.info.Type, b, int(r.shape[0]))
+ if err != nil {
+ return 0, err
+ }
+
+ n, err := encodeFloatTensor(w, gguf.TensorTypeF32, data)
+ return int64(n), err
+}
+
+func (r *sourceTensorRow) GGUFWriteMemoryEstimate() uint64 {
+ rowBytes := int64ToUint64(gguf.TensorInfo{Name: r.tensor.name, Shape: r.shape, Type: r.tensor.info.Type}.NumBytes())
+ floatBytes := saturatingMul(tensorElementCount(r.shape), 4)
+ return saturatingAdd(rowBytes, floatBytes, floatBytes)
+}
+
+func decodeTensorRow(kind gguf.TensorType, b []byte, n int) ([]float32, error) {
+ switch kind {
+ case gguf.TensorTypeF32, gguf.TensorTypeF16, gguf.TensorTypeBF16:
+ out, err := decodeFloatTensor(kind, b)
+ if err != nil {
+ return nil, err
+ }
+ if len(out) != n {
+ return nil, fmt.Errorf("decoded %d values for %v row, expected %d", len(out), kind, n)
+ }
+ return out, nil
+ case gguf.TensorTypeQ8_0:
+ return decodeQ8_0Row(b, n)
+ case gguf.TensorTypeQ5_0:
+ return decodeQ5_0Row(b, n)
+ case gguf.TensorTypeQ4_K:
+ return decodeQ4KRow(b, n)
+ case gguf.TensorTypeQ6_K:
+ return decodeQ6KRow(b, n)
+ default:
+ return nil, fmt.Errorf("row extraction from tensor type %v is unsupported", kind)
+ }
+}
+
+func decodeQ8_0Row(b []byte, n int) ([]float32, error) {
+ if n%qk8_0 != 0 {
+ return nil, fmt.Errorf("q8_0 row length %d is not divisible by %d", n, qk8_0)
+ }
+ if want := n / qk8_0 * q8_0BlkSize; len(b) != want {
+ return nil, fmt.Errorf("q8_0 row has %d bytes, expected %d", len(b), want)
+ }
+
+ out := make([]float32, n)
+ for block := range n / qk8_0 {
+ base := block * q8_0BlkSize
+ d := decodeF16(b[base:])
+ qs := b[base+2 : base+q8_0BlkSize]
+ for i, q := range qs {
+ out[block*qk8_0+i] = d * float32(int8(q))
+ }
+ }
+ return out, nil
+}
+
+func decodeQ5_0Row(b []byte, n int) ([]float32, error) {
+ if n%qk5_0 != 0 {
+ return nil, fmt.Errorf("q5_0 row length %d is not divisible by %d", n, qk5_0)
+ }
+ if want := n / qk5_0 * q5_0BlkSize; len(b) != want {
+ return nil, fmt.Errorf("q5_0 row has %d bytes, expected %d", len(b), want)
+ }
+
+ out := make([]float32, n)
+ for block := range n / qk5_0 {
+ base := block * q5_0BlkSize
+ d := decodeF16(b[base:])
+ qh := binary.LittleEndian.Uint32(b[base+2:])
+ qs := b[base+6 : base+q5_0BlkSize]
+
+ outOffset := block * qk5_0
+ for j, q := range qs {
+ loHighBit := uint8(((qh >> j) << 4) & 0x10)
+ hiHighBit := uint8((qh >> (j + 12)) & 0x10)
+ out[outOffset+j] = d * float32(int((q&0x0f)|loHighBit)-16)
+ out[outOffset+j+qk5_0/2] = d * float32(int((q>>4)|hiHighBit)-16)
+ }
+ }
+ return out, nil
+}
+
+func decodeQ4KRow(b []byte, n int) ([]float32, error) {
+ if n%qkK != 0 {
+ return nil, fmt.Errorf("q4_k row length %d is not divisible by %d", n, qkK)
+ }
+ if want := n / qkK * q4KBlkSize; len(b) != want {
+ return nil, fmt.Errorf("q4_k row has %d bytes, expected %d", len(b), want)
+ }
+
+ out := make([]float32, n)
+ for block := range n / qkK {
+ base := block * q4KBlkSize
+ d := decodeF16(b[base:])
+ min := decodeF16(b[base+2:])
+ scales := b[base+4 : base+16]
+ qs := b[base+16 : base+q4KBlkSize]
+
+ outOffset := block * qkK
+ scaleIndex := 0
+ qOffset := 0
+ for range qkK / 64 {
+ sc, m := scaleMinK4(scaleIndex, scales)
+ d1 := d * float32(sc)
+ m1 := min * float32(m)
+ sc, m = scaleMinK4(scaleIndex+1, scales)
+ d2 := d * float32(sc)
+ m2 := min * float32(m)
+
+ for l := range 32 {
+ out[outOffset+l] = d1*float32(qs[qOffset+l]&0x0f) - m1
+ }
+ for l := range 32 {
+ out[outOffset+32+l] = d2*float32(qs[qOffset+l]>>4) - m2
+ }
+
+ outOffset += 64
+ qOffset += 32
+ scaleIndex += 2
+ }
+ }
+ return out, nil
+}
+
+func scaleMinK4(j int, q []byte) (uint8, uint8) {
+ if j < 4 {
+ return q[j] & 63, q[j+4] & 63
+ }
+ return (q[j+4] & 0x0f) | ((q[j-4] >> 6) << 4), (q[j+4] >> 4) | ((q[j] >> 6) << 4)
+}
+
+func decodeQ6KRow(b []byte, n int) ([]float32, error) {
+ if n%qkK != 0 {
+ return nil, fmt.Errorf("q6_k row length %d is not divisible by %d", n, qkK)
+ }
+ if want := n / qkK * q6KBlkSize; len(b) != want {
+ return nil, fmt.Errorf("q6_k row has %d bytes, expected %d", len(b), want)
+ }
+
+ out := make([]float32, n)
+ for block := range n / qkK {
+ base := block * q6KBlkSize
+ ql := b[base : base+128]
+ qh := b[base+128 : base+192]
+ scales := b[base+192 : base+208]
+ d := decodeF16(b[base+208:])
+
+ outOffset := block * qkK
+ qlOffset := 0
+ qhOffset := 0
+ scaleOffset := 0
+ for range qkK / 128 {
+ for l := range 32 {
+ is := l / 16
+ q1 := int((ql[qlOffset+l+0]&0x0f)|(((qh[qhOffset+l]>>0)&3)<<4)) - 32
+ q2 := int((ql[qlOffset+l+32]&0x0f)|(((qh[qhOffset+l]>>2)&3)<<4)) - 32
+ q3 := int((ql[qlOffset+l+0]>>4)|(((qh[qhOffset+l]>>4)&3)<<4)) - 32
+ q4 := int((ql[qlOffset+l+32]>>4)|(((qh[qhOffset+l]>>6)&3)<<4)) - 32
+
+ out[outOffset+l+0] = d * float32(int8(scales[scaleOffset+is+0])) * float32(q1)
+ out[outOffset+l+32] = d * float32(int8(scales[scaleOffset+is+2])) * float32(q2)
+ out[outOffset+l+64] = d * float32(int8(scales[scaleOffset+is+4])) * float32(q3)
+ out[outOffset+l+96] = d * float32(int8(scales[scaleOffset+is+6])) * float32(q4)
+ }
+ outOffset += 128
+ qlOffset += 64
+ qhOffset += 32
+ scaleOffset += 8
+ }
+ }
+ return out, nil
+}
+
+func decodeF16(b []byte) float32 {
+ return float16.Frombits(binary.LittleEndian.Uint16(b)).Float32()
+}
+
+func f32Tensor(name string, shape []uint64, data []float32) *outTensor {
+ return &outTensor{
+ Name: name,
+ Kind: uint32(gguf.TensorTypeF32),
+ Shape: slices.Clone(shape),
+ WriterTo: tensorFloat32Writer(data),
+ }
+}
+
+type tensorFloat32Writer []float32
+
+func (t tensorFloat32Writer) WriteTo(w io.Writer) (int64, error) {
+ n, err := encodeFloatTensor(w, gguf.TensorTypeF32, []float32(t))
+ return int64(n), err
+}
+
+func (t tensorFloat32Writer) GGUFWriteMemoryEstimate() uint64 {
+ return saturatingMul(uint64(len(t)), 4)
+}
diff --git a/compatmigrate/writer.go b/compatmigrate/writer.go
new file mode 100644
index 000000000..8c26c8949
--- /dev/null
+++ b/compatmigrate/writer.go
@@ -0,0 +1,301 @@
+package compatmigrate
+
+// Minimal serial GGUF writer for one-shot compatibility migrations; kept
+// unexported so GGUF writing stays local to this package.
+
+import (
+ "cmp"
+ "encoding/binary"
+ "fmt"
+ "io"
+ "maps"
+ "math"
+ "os"
+ "slices"
+ "strings"
+
+ "github.com/ollama/ollama/fs/gguf"
+)
+
+// outKV is the metadata of the GGUF file a migration is writing.
+type outKV map[string]any
+
+func (kv outKV) Len() int {
+ return len(kv)
+}
+
+// Keys returns the metadata keys in sorted order, matching what the reader
+// expects of well-formed GGUF files.
+func (kv outKV) Keys() []string {
+ return slices.Sorted(maps.Keys(kv))
+}
+
+func (kv outKV) Value(key string) any {
+ return kv[key]
+}
+
+func (kv outKV) String(key string) string {
+ v, _ := kv[key].(string)
+ return v
+}
+
+func (kv outKV) Uint(key string, fallback uint64) uint64 {
+ switch v := kv[key].(type) {
+ case uint32:
+ return uint64(v)
+ case uint64:
+ return v
+ }
+ return fallback
+}
+
+// outTensor is one tensor of the GGUF file a migration is writing. WriterTo
+// provides the tensor payload.
+type outTensor struct {
+ Name string
+ Kind uint32
+ Offset uint64
+
+ // Shape is the number of elements in each dimension
+ Shape []uint64
+
+ io.WriterTo
+}
+
+// block returns the tensor's layer index, so tensors sort with their layer.
+// Tensors outside any layer sort after them.
+func (t *outTensor) block() (n int) {
+ if _, err := fmt.Sscanf(t.Name, "blk.%d.", &n); err != nil {
+ return math.MaxInt
+ }
+
+ return
+}
+
+// size returns the tensor's size in bytes, padding the final block out to a
+// whole block.
+func (t *outTensor) size() uint64 {
+ var elements uint64 = 1
+ for _, n := range t.Shape {
+ elements *= n
+ }
+ return uint64(float64(elements) * gguf.TensorType(t.Kind).NumBytes())
+}
+
+// writeGGUF writes kv and tensors to f as a GGUF v3 file.
+func writeGGUF(f *os.File, kv outKV, ts []*outTensor) error {
+ arch := kv.String("general.architecture")
+ if arch == "" {
+ return fmt.Errorf("architecture not set")
+ }
+
+ if err := binary.Write(f, binary.LittleEndian, []byte("GGUF")); err != nil {
+ return err
+ }
+
+ if err := binary.Write(f, binary.LittleEndian, uint32(3)); err != nil {
+ return err
+ }
+
+ if err := binary.Write(f, binary.LittleEndian, uint64(len(ts))); err != nil {
+ return err
+ }
+
+ if err := binary.Write(f, binary.LittleEndian, uint64(kv.Len())); err != nil {
+ return err
+ }
+
+ for _, key := range kv.Keys() {
+ if err := writeKV(f, arch, key, kv.Value(key)); err != nil {
+ return err
+ }
+ }
+
+ slices.SortStableFunc(
+ ts,
+ func(a, b *outTensor) int {
+ return cmp.Or(
+ cmp.Compare(a.block(), b.block()),
+ cmp.Compare(a.Name, b.Name),
+ )
+ },
+ )
+
+ alignment := kv.Uint("general.alignment", 32)
+
+ var s uint64
+ for i := range ts {
+ ts[i].Offset = s
+ if err := writeTensorInfo(f, ts[i]); err != nil {
+ return err
+ }
+ s += ts[i].size()
+ s += uint64(padding(int64(s), int64(alignment)))
+ }
+
+ offset, err := f.Seek(0, io.SeekCurrent)
+ if err != nil {
+ return err
+ }
+ offset += padding(offset, int64(alignment))
+
+ for _, t := range ts {
+ if _, err := t.WriteTo(io.NewOffsetWriter(f, offset+int64(t.Offset))); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+const (
+ ggufTypeUint8 uint32 = iota
+ ggufTypeInt8
+ ggufTypeUint16
+ ggufTypeInt16
+ ggufTypeUint32
+ ggufTypeInt32
+ ggufTypeFloat32
+ ggufTypeBool
+ ggufTypeString
+ ggufTypeArray
+ ggufTypeUint64
+ ggufTypeInt64
+ ggufTypeFloat64
+)
+
+func writeKV(w io.Writer, arch, k string, v any) error {
+ if !strings.HasPrefix(k, arch+".") &&
+ !strings.HasPrefix(k, "general.") &&
+ !strings.HasPrefix(k, "adapter.") &&
+ !strings.HasPrefix(k, "tokenizer.") {
+ k = arch + "." + k
+ }
+
+ if err := binary.Write(w, binary.LittleEndian, uint64(len(k))); err != nil {
+ return err
+ }
+
+ if err := binary.Write(w, binary.LittleEndian, []byte(k)); err != nil {
+ return err
+ }
+
+ switch v := v.(type) {
+ case int32:
+ return writeValue(w, ggufTypeInt32, v)
+ case int64:
+ return writeValue(w, ggufTypeInt64, v)
+ case uint32:
+ return writeValue(w, ggufTypeUint32, v)
+ case uint64:
+ return writeValue(w, ggufTypeUint64, v)
+ case float32:
+ return writeValue(w, ggufTypeFloat32, v)
+ case float64:
+ return writeValue(w, ggufTypeFloat64, v)
+ case bool:
+ return writeValue(w, ggufTypeBool, v)
+ case string:
+ return writeString(w, v)
+ case []int8:
+ return writeArray(w, ggufTypeInt8, v)
+ case []uint8:
+ return writeArray(w, ggufTypeUint8, v)
+ case []int32:
+ return writeArray(w, ggufTypeInt32, v)
+ case []int64:
+ return writeArray(w, ggufTypeInt64, v)
+ case []uint32:
+ return writeArray(w, ggufTypeUint32, v)
+ case []uint64:
+ return writeArray(w, ggufTypeUint64, v)
+ case []float32:
+ return writeArray(w, ggufTypeFloat32, v)
+ case []string:
+ return writeArray(w, ggufTypeString, v)
+ case []bool:
+ return writeArray(w, ggufTypeBool, v)
+ default:
+ return fmt.Errorf("improper type for '%s'", k)
+ }
+}
+
+func writeTensorInfo(w io.Writer, t *outTensor) error {
+ if err := binary.Write(w, binary.LittleEndian, uint64(len(t.Name))); err != nil {
+ return err
+ }
+
+ if err := binary.Write(w, binary.LittleEndian, []byte(t.Name)); err != nil {
+ return err
+ }
+
+ if err := binary.Write(w, binary.LittleEndian, uint32(len(t.Shape))); err != nil {
+ return err
+ }
+
+ for _, n := range t.Shape {
+ if err := binary.Write(w, binary.LittleEndian, n); err != nil {
+ return err
+ }
+ }
+
+ if err := binary.Write(w, binary.LittleEndian, t.Kind); err != nil {
+ return err
+ }
+
+ return binary.Write(w, binary.LittleEndian, t.Offset)
+}
+
+func writeValue[V any](w io.Writer, t uint32, v V) error {
+ if err := binary.Write(w, binary.LittleEndian, t); err != nil {
+ return err
+ }
+
+ return binary.Write(w, binary.LittleEndian, v)
+}
+
+func writeString(w io.Writer, s string) error {
+ if err := binary.Write(w, binary.LittleEndian, ggufTypeString); err != nil {
+ return err
+ }
+
+ if err := binary.Write(w, binary.LittleEndian, uint64(len(s))); err != nil {
+ return err
+ }
+
+ _, err := io.Copy(w, strings.NewReader(s))
+ return err
+}
+
+func writeArray[S ~[]E, E any](w io.Writer, t uint32, s S) error {
+ if err := binary.Write(w, binary.LittleEndian, ggufTypeArray); err != nil {
+ return err
+ }
+
+ if err := binary.Write(w, binary.LittleEndian, t); err != nil {
+ return err
+ }
+
+ if err := binary.Write(w, binary.LittleEndian, uint64(len(s))); err != nil {
+ return err
+ }
+
+ if t == ggufTypeString {
+ for _, e := range any(s).([]string) {
+ if err := binary.Write(w, binary.LittleEndian, uint64(len(e))); err != nil {
+ return err
+ }
+
+ if err := binary.Write(w, binary.LittleEndian, []byte(e)); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+
+ return binary.Write(w, binary.LittleEndian, s)
+}
+
+func padding(offset, align int64) int64 {
+ return (align - offset%align) % align
+}
diff --git a/create/manifest.go b/create/manifest.go
index 170479108..76ebe7855 100644
--- a/create/manifest.go
+++ b/create/manifest.go
@@ -100,7 +100,7 @@ func NewSafetensorsManifestWriter(opts SafetensorsManifestOptions) ManifestWrite
if err := checkContext(ctx); err != nil {
return err
}
- return manifest.WriteManifest(name, configLayer, manifestLayers)
+ return manifest.WriteManifestWithMetadata(name, configLayer, manifestLayers, manifest.RunnerMLX, manifest.FormatSafetensors)
}
}
@@ -130,7 +130,7 @@ func safetensorsConfigLayer(config model.ConfigV2) (manifest.Layer, error) {
if err := json.NewEncoder(&b).Encode(config); err != nil {
return manifest.Layer{}, fmt.Errorf("failed to encode config: %w", err)
}
- layer, err := manifest.NewLayer(&b, "application/vnd.docker.container.image.v1+json")
+ layer, err := manifest.NewLayer(&b, manifest.MediaTypeImageConfig)
if err != nil {
return manifest.Layer{}, fmt.Errorf("failed to create config layer: %w", err)
}
diff --git a/docs/api.md b/docs/api.md
index 7787fcf8b..435431add 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -1493,6 +1493,12 @@ curl http://localhost:11434/api/copy -d '{
Returns a 200 OK if successful, or a 404 Not Found if the source model doesn't exist.
+```json
+{
+ "status": "success"
+}
+```
+
## Delete a Model
```
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 86fc5e9dc..eac5f3dc9 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -1514,6 +1514,24 @@ paths:
responses:
"200":
description: Model successfully copied
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/StatusResponse"
+ example:
+ status: "success"
+ "400":
+ description: Model could not be copied
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ErrorResponse"
+ "404":
+ description: Source model not found
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ErrorResponse"
/api/pull:
post:
summary: Pull a model
diff --git a/fs/gguf/gguf.go b/fs/gguf/gguf.go
index 6a9b9bd1e..2ac903b80 100644
--- a/fs/gguf/gguf.go
+++ b/fs/gguf/gguf.go
@@ -485,6 +485,22 @@ func (f *File) NumTensors() int {
return int(f.tensors.count)
}
+// TensorDataOffset returns the byte offset at which tensor data begins. The
+// offset is only known after all tensor metadata has been read because GGUF
+// stores it after the tensor-info table.
+func (f *File) TensorDataOffset() int64 {
+ _ = f.keyValues.rest()
+ _ = f.tensors.rest()
+ return f.offset
+}
+
+// ReaderAt returns a re-readable reader over the whole file. Together with
+// TensorDataOffset it lets callers build section readers for individual
+// tensor payloads.
+func (f *File) ReaderAt() io.ReaderAt {
+ return f.file
+}
+
func (f *File) TensorInfos() iter.Seq2[int, TensorInfo] {
// fast forward through key values if we haven't already
f.keyValues.rest()
diff --git a/fs/gguf/gguf_test.go b/fs/gguf/gguf_test.go
index 03e1f5e4a..bb0679e5c 100644
--- a/fs/gguf/gguf_test.go
+++ b/fs/gguf/gguf_test.go
@@ -5,11 +5,11 @@ import (
"encoding/binary"
"errors"
"os"
+ "path/filepath"
"runtime"
"strconv"
"strings"
"testing"
- "time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
@@ -230,39 +230,6 @@ func TestRead(t *testing.T) {
}
}
-func TestOpenCleansUpPartialLazyReader(t *testing.T) {
- p := createFile(t, []byte{
- 'G', 'G', 'U', 'F',
- 3, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- })
-
- runtime.GC()
- before := runtime.NumGoroutine()
-
- for range 20 {
- f, err := gguf.Open(p)
- if err == nil {
- f.Close()
- t.Fatal("gguf.Open truncated header succeeded")
- }
- }
-
- deadline := time.Now().Add(time.Second)
- for time.Now().Before(deadline) {
- runtime.GC()
- runtime.Gosched()
- if runtime.NumGoroutine() <= before+2 {
- return
- }
- time.Sleep(10 * time.Millisecond)
- }
-
- if after := runtime.NumGoroutine(); after > before+2 {
- t.Fatalf("goroutines after repeated failed gguf.Open = %d, want at most %d", after, before+2)
- }
-}
-
func TestOpenRejectsInvalidMagic(t *testing.T) {
data := append([]byte("nope"), make([]byte, 20)...)
f, err := gguf.Open(createFile(t, data))
@@ -362,7 +329,7 @@ func FuzzOpen(f *testing.F) {
func createFile(tb testing.TB, b []byte) string {
tb.Helper()
- p := tb.TempDir() + "/model.gguf"
+ p := filepath.Join(tb.TempDir(), "model.gguf")
if err := os.WriteFile(p, b, 0o600); err != nil {
tb.Fatal(err)
}
diff --git a/go.mod b/go.mod
index afc6733b8..2b770fc4f 100644
--- a/go.mod
+++ b/go.mod
@@ -13,6 +13,7 @@ require (
github.com/olekukonko/tablewriter v0.0.5
github.com/spf13/cobra v1.7.0
github.com/stretchr/testify v1.10.0
+ github.com/x448/float16 v0.8.4
golang.org/x/sync v0.17.0
golang.org/x/sys v0.37.0
)
@@ -21,6 +22,7 @@ require (
github.com/agnivade/levenshtein v1.1.1
github.com/charmbracelet/bubbletea v1.3.10
github.com/charmbracelet/lipgloss v1.1.0
+ github.com/d4l3k/go-bfloat16 v0.0.0-20211005043715-690c3bdd05f1
github.com/emirpasic/gods/v2 v2.0.0-alpha
github.com/klauspost/compress v1.18.3
github.com/mattn/go-runewidth v0.0.16
diff --git a/go.sum b/go.sum
index b2981189e..c07bb0315 100644
--- a/go.sum
+++ b/go.sum
@@ -34,6 +34,8 @@ github.com/containerd/console v1.0.3 h1:lIr7SlA5PxZyMV30bDW0MGbiOPXwc63yRuCP0ARu
github.com/containerd/console v1.0.3/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
+github.com/d4l3k/go-bfloat16 v0.0.0-20211005043715-690c3bdd05f1 h1:cBzrdJPAFBsgCrDPnZxlp1dF2+k4r1kVpD7+1S1PVjY=
+github.com/d4l3k/go-bfloat16 v0.0.0-20211005043715-690c3bdd05f1/go.mod h1:uw2gLcxEuYUlAd/EXyjc/v55nd3+47YAgWbSXVxPrNI=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -178,6 +180,8 @@ github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65E
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
+github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
+github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
diff --git a/integration/audio_test.go b/integration/audio_test.go
index 3e9b4f96e..6c9148a66 100644
--- a/integration/audio_test.go
+++ b/integration/audio_test.go
@@ -88,35 +88,42 @@ func runAudioResponse(t *testing.T, models []string) {
defer cleanup()
setupAudioModel(ctx, t, client, model)
- audio := decodeTestAudio(t)
- noThink := &api.ThinkValue{Value: false}
-
- req := api.ChatRequest{
- Model: model,
- Think: noThink,
- Messages: []api.Message{
- {
- Role: "user",
- Content: "",
- Images: []api.ImageData{audio},
- },
- },
- Stream: &stream,
- Options: map[string]any{
- "temperature": 0,
- "seed": 123,
- "num_predict": 200,
- },
- }
-
- // The audio asks "Why is the sky blue?" — expect an answer about light/scattering.
- DoChat(ctx, t, client, req, []string{
- "scatter", "light", "blue", "atmosphere", "wavelength", "rayleigh",
- }, 60*time.Second, 10*time.Second)
+ testAudioResponseForModel(t, ctx, client, model, 10*time.Second, 60*time.Second, 10*time.Second)
})
}
}
+func testAudioResponseForModel(t *testing.T, ctx context.Context, client *api.Client, model string, keepAlive time.Duration, initialTimeout, streamTimeout time.Duration) {
+ t.Helper()
+
+ audio := decodeTestAudio(t)
+ noThink := &api.ThinkValue{Value: false}
+
+ req := api.ChatRequest{
+ Model: model,
+ Think: noThink,
+ Messages: []api.Message{
+ {
+ Role: "user",
+ Content: "",
+ Images: []api.ImageData{audio},
+ },
+ },
+ Stream: &stream,
+ KeepAlive: &api.Duration{Duration: keepAlive},
+ Options: map[string]any{
+ "temperature": 0,
+ "seed": 123,
+ "num_predict": 200,
+ },
+ }
+
+ // The audio asks "Why is the sky blue?" — expect an answer about light/scattering.
+ DoChat(ctx, t, client, req, []string{
+ "scatter", "light", "blue", "atmosphere", "wavelength", "rayleigh",
+ }, initialTimeout, streamTimeout)
+}
+
// runOpenAIAudioTranscription tests the /v1/audio/transcriptions endpoint.
func runOpenAIAudioTranscription(t *testing.T, models []string) {
for _, model := range testModels(models) {
diff --git a/integration/compatibility_model_matrix_test.go b/integration/compatibility_model_matrix_test.go
new file mode 100644
index 000000000..421f4974a
--- /dev/null
+++ b/integration/compatibility_model_matrix_test.go
@@ -0,0 +1,128 @@
+//go:build integration && migration
+
+package integration
+
+var compatibilityModelMatrix = []string{
+ // Text / embedding families.
+ "gpt-oss:20b",
+ "gpt-oss:120b",
+ "gpt-oss-safeguard:20b",
+ "gpt-oss-safeguard:120b",
+ "lfm2.5-thinking:1.2b-q4_K_M",
+ "lfm2.5-thinking:1.2b-q8_0",
+ "lfm2.5-thinking:1.2b-bf16",
+ "embeddinggemma:300m",
+ "embeddinggemma:300m-qat-q4_0",
+ "embeddinggemma:300m-qat-q8_0",
+ "snowflake-arctic-embed2:568m",
+ "snowflake-arctic-embed2:568m-l-fp16",
+
+ // Gemma compatibility families.
+ "gemma3:1b",
+ "gemma3:4b",
+ "gemma3:12b",
+ "gemma3:27b",
+ "gemma3n:e2b",
+ "gemma3n:e4b",
+ "gemma4:e2b",
+ "gemma4:e4b",
+ "gemma4:26b",
+ "gemma4:31b",
+
+ // GLM / OCR families.
+ "glm-4.7-flash:q4_K_M",
+ "glm-4.7-flash:q8_0",
+ "glm-4.7-flash:bf16",
+ "deepseek-ocr:3b",
+ "deepseek-ocr:3b-bf16",
+ "glm-ocr:bf16",
+ "glm-ocr:q8_0",
+
+ // Qwen vision / MoE families.
+ "qwen2.5vl:3b",
+ "qwen2.5vl:7b",
+ "qwen2.5vl:32b",
+ "qwen2.5vl:72b",
+ "qwen2.5vl:72b-q8_0",
+ "qwen2.5vl:72b-fp16",
+ "qwen3-vl:2b",
+ "qwen3-vl:2b-instruct",
+ "qwen3-vl:4b-instruct",
+ "qwen3-vl:4b-thinking",
+ "qwen3-vl:8b",
+ "qwen3-vl:8b-instruct",
+ "qwen3-vl:8b-thinking",
+ "qwen3-vl:30b",
+ "qwen3-vl:30b-a3b-instruct",
+ "qwen3-vl:30b-a3b-thinking",
+ "qwen3-vl:32b-instruct",
+ "qwen3-vl:32b-thinking",
+ "qwen3.5:2b",
+ "qwen3.5:35b",
+ "qwen3-coder-next:q4_K_M",
+
+ // Laguna hybrid-attention MoE family.
+ "laguna-xs.2:q4_K_M",
+ "laguna-xs.2:q8_0",
+ "laguna-xs.2:bf16",
+
+ // OLMo compatibility families.
+ "olmo-3:7b-instruct",
+ "olmo-3:7b-think",
+ "olmo-3.1:32b",
+
+ // Mistral / Pixtral-style multimodal families.
+ "ministral-3:3b",
+ "ministral-3:8b",
+ "ministral-3:14b",
+ "mistral-small3.1:24b",
+ "mistral-small3.2:24b",
+
+ // Legacy projector / Nemotron / Llama compatibility families.
+ "bakllava:7b",
+ "llava:7b",
+ "llava:7b-v1.5-q4_K_M",
+ "llava:13b",
+ "llava:13b-v1.5-q4_K_M",
+ "llava:34b",
+ "llava-llama3:8b",
+ "llava-phi3:3.8b",
+ "nemotron-3-super:120b-a12b-q4_K_M",
+ "nemotron3:33b",
+ "dolphin-llama3:8b-v2.9-q4_K_M",
+ "dolphin-llama3:8b-256k-v2.9-q4_K_M",
+ "dolphin-llama3:70b-v2.9-q4_K_M",
+ "llama3-chatqa:8b-v1.5-q4_K_M",
+ "llama3-chatqa:70b-v1.5-q4_K_M",
+ "llama3.2:1b",
+ "llama4",
+}
+
+func compatibilityPublishedModelNames() []string {
+ names := make([]string, 0, len(compatibilityModelMatrix))
+ names = append(names, compatibilityModelMatrix...)
+ return names
+}
+
+func compatibilityMigrationModelNames() []string {
+ names := make([]string, 0, len(compatibilityModelMatrix))
+ for _, name := range compatibilityModelMatrix {
+ switch name {
+ case "glm-4.7-flash:q8_0", "glm-4.7-flash:bf16":
+ // These published variants already use llama.cpp-compatible
+ // deepseek2 metadata, so there is no lazy conversion to validate.
+ continue
+ case "llama3.2:1b":
+ // This current library artifact no longer triggers the Llama 3
+ // metadata patch, so only published compatibility coverage applies.
+ continue
+ case "llava:7b", "llava:13b", "llava:34b", "llava-phi3:3.8b":
+ // These current library artifacts already have projector metadata.
+ // Keep it in published coverage, not lazy-conversion coverage.
+ continue
+ default:
+ names = append(names, name)
+ }
+ }
+ return names
+}
diff --git a/integration/compatibility_models_test.go b/integration/compatibility_models_test.go
new file mode 100644
index 000000000..c12d157ef
--- /dev/null
+++ b/integration/compatibility_models_test.go
@@ -0,0 +1,355 @@
+//go:build integration && migration
+
+package integration
+
+import (
+ "context"
+ "log/slog"
+ "os"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/types/model"
+)
+
+func TestPublishedCompatibilityModels(t *testing.T) {
+ if os.Getenv("OLLAMA_TEST_EXISTING") != "" {
+ t.Skip("published compatibility validation requires a harness-managed server")
+ }
+ skipIfRemote(t)
+
+ softTimeout, hardTimeout := getTimeouts(t)
+ slog.Info("Setting timeouts", "soft", softTimeout, "hard", hardTimeout)
+ ctx, cancel := context.WithTimeout(context.Background(), hardTimeout)
+ defer cancel()
+
+ // OLLAMA_TEST_COMPAT_NAMESPACE points the published-artifact matrix at a
+ // staging namespace until the compatible artifacts land in the library.
+ prefix := os.Getenv("OLLAMA_TEST_COMPAT_NAMESPACE")
+
+ if testModel != "" {
+ runPublishedCompatibilityModelCase(ctx, t, testModel, false)
+ return
+ }
+
+ for _, base := range compatibilityPublishedModelNames() {
+ name := prefixedCompatibilityModel(prefix, base)
+ t.Run(name, func(t *testing.T) {
+ if time.Since(started) > softTimeout {
+ t.Skip("skipping remaining tests to avoid excessive runtime")
+ }
+
+ runPublishedCompatibilityModelCase(ctx, t, name, true)
+ })
+ }
+}
+
+func runPublishedCompatibilityModelCase(ctx context.Context, t *testing.T, name string, isolatedModelStore bool) {
+ t.Helper()
+
+ if strings.HasSuffix(name, "-ggml") {
+ t.Fatalf("%s is a legacy GGML source tag; run migration validation on a temporary copy instead", name)
+ }
+
+ if isolatedModelStore {
+ modelsDir := t.TempDir()
+ t.Setenv("OLLAMA_MODELS", modelsDir)
+ t.Logf("%s: using published compatibility model store %s", name, modelsDir)
+ } else {
+ t.Logf("%s: using configured model store %s", name, os.Getenv("OLLAMA_MODELS"))
+ }
+ t.Setenv("OLLAMA_DEBUG", "2")
+
+ t.Logf("%s: starting server with %s=0", name, migrationCompatEnv)
+ t.Setenv(migrationCompatEnv, "0")
+ patchDisabledClient, _, patchDisabledCleanup := InitServerConnection(ctx, t)
+ defer func() {
+ if patchDisabledCleanup != nil {
+ patchDisabledCleanup()
+ }
+ }()
+
+ t.Logf("%s: pulling published model if needed", name)
+ if err := PullIfMissing(ctx, patchDisabledClient, name); err != nil {
+ t.Fatalf("model %s not available: %v", name, err)
+ }
+
+ patchDisabledShow := showOrFatal(ctx, t, patchDisabledClient, name)
+ if len(patchDisabledShow.Capabilities) == 0 {
+ t.Fatalf("show %s returned no capabilities", name)
+ }
+ slog.Info("validating published compatibility model", "model", name, "capabilities", normalizedCapabilities(patchDisabledShow.Capabilities))
+
+ skipIfModelTooLargeForVRAM(ctx, t, patchDisabledClient, name)
+ patchDisabledValidationStart := len(serverLog.String())
+ validatePublishedCapabilities(ctx, t, patchDisabledClient, name, patchDisabledShow, compatKeepAlive)
+ waitForNoRunningModel(ctx, t, patchDisabledClient, name)
+
+ patchDisabledLogs := serverLog.String()[patchDisabledValidationStart:]
+ if hasCompatPatchEvidence(patchDisabledLogs) {
+ t.Fatalf("%s triggered compatibility patch with %s=0", name, migrationCompatEnv)
+ }
+
+ t.Logf("%s: stopping patch-disabled server", name)
+ patchDisabledCleanup()
+ patchDisabledCleanup = nil
+
+ t.Logf("%s: restarting server with default compatibility patch settings", name)
+ // Safe only because the earlier t.Setenv(migrationCompatEnv, "0") in this test registered a cleanup that restores the original value.
+ os.Unsetenv(migrationCompatEnv)
+ defaultClient, _, defaultCleanup := InitServerConnection(ctx, t)
+ defer defaultCleanup()
+
+ defaultShow := showOrFatal(ctx, t, defaultClient, name)
+ defaultValidationStart := len(serverLog.String())
+ validateCompatibilityPrimaryCapability(ctx, t, defaultClient, name, defaultShow, compatKeepAlive)
+ waitForNoRunningModel(ctx, t, defaultClient, name)
+
+ defaultLogs := serverLog.String()[defaultValidationStart:]
+ if hasCompatPatchEvidence(defaultLogs) {
+ t.Fatalf("%s triggered compatibility patch from published llama.cpp-compatible artifact", name)
+ }
+}
+
+func validatePublishedCapabilities(ctx context.Context, t *testing.T, client *api.Client, name string, resp *api.ShowResponse, keepAlive time.Duration) {
+ t.Helper()
+ capabilities := resp.Capabilities
+ if isModelFamily(name, "glm-ocr") {
+ // glm-ocr is OCR-specialized; generic chat/tools probes are weak even
+ // on the old runner, so validate the intended vision path here.
+ if !hasCapability(capabilities, model.CapabilityVision) {
+ t.Fatalf("%s did not advertise expected vision capability: %v", name, capabilities)
+ }
+ t.Logf("%s: validating vision capability", name)
+ validateCompatibilityVision(ctx, t, client, name, keepAlive)
+ return
+ }
+
+ validated := false
+ if hasCapability(capabilities, model.CapabilityEmbedding) {
+ t.Logf("%s: validating embedding capability", name)
+ testEmbedCosineDistanceCorrelationForModel(t, ctx, client, name, keepAlive)
+ validated = true
+ }
+ if hasCapability(capabilities, model.CapabilityAudio) {
+ t.Logf("%s: validating audio capability", name)
+ testAudioResponseForModel(t, ctx, client, name, keepAlive, compatValidationInitialTimeout, compatValidationStreamTimeout)
+ validated = true
+ }
+ if hasCapability(capabilities, model.CapabilityVision) {
+ t.Logf("%s: validating vision capability", name)
+ validateCompatibilityVision(ctx, t, client, name, keepAlive)
+ validated = true
+ }
+ if hasCapability(capabilities, model.CapabilityCompletion) {
+ t.Logf("%s: validating completion capability", name)
+ if isPlainCompletionOnlyModel(resp) {
+ validateGenerateCompletion(ctx, t, client, name, keepAlive)
+ } else {
+ validateCompatibilityChat(ctx, t, client, name, keepAlive)
+ }
+ validated = true
+ }
+ if hasCapability(capabilities, model.CapabilityThinking) {
+ t.Logf("%s: validating thinking capability", name)
+ validateCompatibilityThinking(ctx, t, client, name, keepAlive)
+ validated = true
+ }
+ if hasCapability(capabilities, model.CapabilityTools) {
+ t.Logf("%s: validating tools capability", name)
+ testBasicToolCallWithNumPredict(t, ctx, client, name, compatToolInitialTimeout, compatToolStreamTimeout, migrationToolNumPredict(name))
+ validated = true
+ }
+ if !validated {
+ t.Fatalf("%s advertised unsupported capability set %v", name, capabilities)
+ }
+}
+
+func validateCompatibilityPrimaryCapability(ctx context.Context, t *testing.T, client *api.Client, name string, resp *api.ShowResponse, keepAlive time.Duration) {
+ t.Helper()
+ capabilities := resp.Capabilities
+ if hasCapability(capabilities, model.CapabilityEmbedding) {
+ testEmbedCosineDistanceCorrelationForModel(t, ctx, client, name, keepAlive)
+ return
+ }
+ if hasCapability(capabilities, model.CapabilityVision) {
+ validateCompatibilityVision(ctx, t, client, name, keepAlive)
+ if hasCapability(capabilities, model.CapabilityTools) && shouldSmokeTools(name) {
+ testBasicToolCallWithNumPredict(t, ctx, client, name, compatToolInitialTimeout, compatToolStreamTimeout, migrationToolNumPredict(name))
+ }
+ return
+ }
+ if hasCapability(capabilities, model.CapabilityTools) && shouldSmokeTools(name) {
+ testBasicToolCallWithNumPredict(t, ctx, client, name, compatToolInitialTimeout, compatToolStreamTimeout, migrationToolNumPredict(name))
+ return
+ }
+ if hasCapability(capabilities, model.CapabilityCompletion) {
+ if isPlainCompletionOnlyModel(resp) {
+ validateGenerateCompletion(ctx, t, client, name, keepAlive)
+ } else {
+ validateCompatibilityChat(ctx, t, client, name, keepAlive)
+ }
+ }
+}
+
+func validateCompatibilityCapabilities(ctx context.Context, t *testing.T, client *api.Client, name string, resp *api.ShowResponse, keepAlive time.Duration) {
+ t.Helper()
+ capabilities := resp.Capabilities
+ if hasCapability(capabilities, model.CapabilityEmbedding) {
+ testEmbedCosineDistanceCorrelationForModel(t, ctx, client, name, keepAlive)
+ return
+ }
+ if hasCapability(capabilities, model.CapabilityAudio) {
+ testAudioResponseForModel(t, ctx, client, name, keepAlive, compatValidationInitialTimeout, compatValidationStreamTimeout)
+ }
+ if hasCapability(capabilities, model.CapabilityVision) {
+ validateCompatibilityVision(ctx, t, client, name, keepAlive)
+ if hasCapability(capabilities, model.CapabilityTools) && shouldSmokeTools(name) {
+ testBasicToolCallWithNumPredict(t, ctx, client, name, compatToolInitialTimeout, compatToolStreamTimeout, migrationToolNumPredict(name))
+ }
+ return
+ }
+ if hasCapability(capabilities, model.CapabilityCompletion) {
+ if isPlainCompletionOnlyModel(resp) {
+ validateGenerateCompletion(ctx, t, client, name, keepAlive)
+ } else {
+ validateCompatibilityChat(ctx, t, client, name, keepAlive)
+ }
+ }
+ if hasCapability(capabilities, model.CapabilityTools) {
+ testBasicToolCallWithNumPredict(t, ctx, client, name, compatToolInitialTimeout, compatToolStreamTimeout, migrationToolNumPredict(name))
+ }
+}
+
+func isPlainCompletionOnlyModel(resp *api.ShowResponse) bool {
+ if !hasCapability(resp.Capabilities, model.CapabilityCompletion) ||
+ hasCapability(resp.Capabilities, model.CapabilityTools) ||
+ hasCapability(resp.Capabilities, model.CapabilityVision) ||
+ hasCapability(resp.Capabilities, model.CapabilityAudio) ||
+ hasCapability(resp.Capabilities, model.CapabilityThinking) {
+ return false
+ }
+ return strings.TrimSpace(resp.Template) == "" || strings.TrimSpace(resp.Template) == "{{ .Prompt }}"
+}
+
+func validateGenerateCompletion(ctx context.Context, t *testing.T, client *api.Client, name string, keepAlive time.Duration) {
+ t.Helper()
+ req := api.GenerateRequest{
+ Model: name,
+ Prompt: "Q: What is the capital of France?\nA:",
+ KeepAlive: &api.Duration{Duration: keepAlive},
+ Options: map[string]any{
+ "temperature": 0.0,
+ "seed": 123,
+ "num_predict": 32,
+ },
+ }
+ DoGenerate(ctx, t, client, req, []string{"paris"}, compatValidationInitialTimeout, compatValidationStreamTimeout)
+}
+
+func validateCompatibilityChat(ctx context.Context, t *testing.T, client *api.Client, model string, keepAlive time.Duration) {
+ t.Helper()
+ req := api.ChatRequest{
+ Model: model,
+ Messages: []api.Message{
+ {
+ Role: "user",
+ Content: blueSkyPrompt,
+ },
+ },
+ KeepAlive: &api.Duration{Duration: keepAlive},
+ Options: map[string]any{
+ "temperature": 0.1,
+ "seed": 123,
+ "num_predict": migrationChatNumPredict,
+ },
+ }
+ msg := DoChat(ctx, t, client, req, blueSkyExpected, compatValidationInitialTimeout, compatValidationStreamTimeout)
+ validateNoTokenizerArtifacts(t, model, msg)
+}
+
+func validateCompatibilityVision(ctx context.Context, t *testing.T, client *api.Client, model string, keepAlive time.Duration) {
+ t.Helper()
+ image, _, defaultImage := decodeTestImages(t)
+ prompt := "Describe what you see in this image briefly."
+ expected := []string{"llama", "pig", "animal", "drawing", "sketch", "build", "model", "open", "cartoon", "character"}
+ if isModelFamily(model, "llama4") {
+ // Avoid llama.cpp's current llama4 multi-tile image path; migration only
+ // needs to prove the vision encoder survives conversion.
+ prompt = "What text is shown in this image?"
+ expected = []string{"ollam", "text"}
+ } else {
+ image = defaultImage
+ }
+ req := api.ChatRequest{
+ Model: model,
+ Messages: []api.Message{
+ {
+ Role: "user",
+ Content: prompt,
+ Images: []api.ImageData{image},
+ },
+ },
+ KeepAlive: &api.Duration{Duration: keepAlive},
+ Options: map[string]any{
+ "temperature": 0.0,
+ "seed": 42,
+ "num_predict": migrationChatNumPredict,
+ },
+ }
+ msg := DoChat(ctx, t, client, req, expected, compatValidationInitialTimeout, compatValidationStreamTimeout)
+ validateNoTokenizerArtifacts(t, model, msg)
+}
+
+func validateCompatibilityThinking(ctx context.Context, t *testing.T, client *api.Client, model string, keepAlive time.Duration) {
+ t.Helper()
+ think := api.ThinkValue{Value: true}
+ stream := false
+ req := api.ChatRequest{
+ Model: model,
+ Stream: &stream,
+ Think: &think,
+ Messages: []api.Message{
+ {Role: "user", Content: "What is 12 * 15? Think briefly."},
+ },
+ KeepAlive: &api.Duration{Duration: keepAlive},
+ Options: map[string]any{
+ "temperature": 0,
+ "seed": 42,
+ "num_predict": migrationToolNumPredict(model),
+ },
+ }
+
+ var response api.ChatResponse
+ if err := client.Chat(ctx, &req, func(cr api.ChatResponse) error {
+ response = cr
+ return nil
+ }); err != nil {
+ t.Fatalf("thinking chat failed: %v", err)
+ }
+
+ combined := response.Message.Thinking + " " + response.Message.Content
+ if !strings.Contains(combined, "180") {
+ t.Fatalf("expected thinking response for %s to contain 180, got thinking=%q content=%q", model, response.Message.Thinking, response.Message.Content)
+ }
+ validateNoTokenizerArtifacts(t, model, &response.Message)
+}
+
+func validateNoTokenizerArtifacts(t *testing.T, model string, msg *api.Message) {
+ t.Helper()
+ if msg == nil {
+ t.Fatalf("%s did not return a chat response", model)
+ }
+ if strings.Contains(msg.Content, "[UNK_BYTE_") {
+ t.Fatalf("%s returned visible tokenizer byte fallback artifacts: %s", model, msg.Content)
+ }
+}
+
+func prefixedCompatibilityModel(prefix, name string) string {
+ if prefix == "" || strings.Contains(strings.Split(name, ":")[0], "/") {
+ return name
+ }
+ return strings.TrimRight(prefix, "/") + "/" + name
+}
diff --git a/integration/embed_test.go b/integration/embed_test.go
index 31f34cd39..d78552cb0 100644
--- a/integration/embed_test.go
+++ b/integration/embed_test.go
@@ -111,67 +111,71 @@ func runEmbedCosineDistanceCorrelation(t *testing.T, models []string) {
if testModel != "" {
requireCapability(ctx, t, client, model, "embedding")
}
- testCases := []struct {
- a string
- b string
- c string
- }{
- {"cat", "kitten", "dog"},
- {"king", "queen", "baron"},
- {"paris", "london", "vancouver"},
- {"The cat is sleeping on the sofa", "A feline is sleeping on the couch", "Quantum physics is complex"},
- {"I love programming in python", "Coding in python brings me joy", "Pizza is delicious"},
- {"Machine learning is fascinating", "Artificial intelligence is amazing", "I need to buy groceries"},
- {"The quick brown fox jumps over the lazy dog", "A fast brown fox leaps over a sleepy dog", "The weather is warm and sunny today"},
- }
+ testEmbedCosineDistanceCorrelationForModel(t, ctx, client, model, 10*time.Second)
+ })
+ }
+}
- for _, tc := range testCases {
- testEmbed := make(map[string][]float32)
- strs := []string{tc.a, tc.b, tc.c}
+func testEmbedCosineDistanceCorrelationForModel(t *testing.T, ctx context.Context, client *api.Client, model string, keepAlive time.Duration) {
+ t.Helper()
- req := api.EmbedRequest{
- Model: model,
- Input: strs,
- KeepAlive: &api.Duration{Duration: 10 * time.Second},
- }
+ testCases := []struct {
+ a string
+ b string
+ c string
+ }{
+ {"cat", "kitten", "dog"},
+ {"king", "queen", "baron"},
+ {"paris", "london", "vancouver"},
+ {"The cat is sleeping on the sofa", "A feline is sleeping on the couch", "Quantum physics is complex"},
+ {"I love programming in python", "Coding in python brings me joy", "Pizza is delicious"},
+ {"Machine learning is fascinating", "Artificial intelligence is amazing", "I need to buy groceries"},
+ {"The quick brown fox jumps over the lazy dog", "A fast brown fox leaps over a sleepy dog", "The weather is warm and sunny today"},
+ }
+
+ for _, tc := range testCases {
+ testEmbed := make(map[string][]float32)
+ strs := []string{tc.a, tc.b, tc.c}
+
+ req := api.EmbedRequest{
+ Model: model,
+ Input: strs,
+ KeepAlive: &api.Duration{Duration: keepAlive},
+ }
- resp, err := embedTestHelper(ctx, client, t, req)
- if err != nil {
- t.Fatal(err)
- }
+ resp, err := embedTestHelper(ctx, client, t, req)
+ if err != nil {
+ t.Fatal(err)
+ }
- for cnt, v := range resp.Embeddings {
- testEmbed[strs[cnt]] = v
- }
+ for cnt, v := range resp.Embeddings {
+ testEmbed[strs[cnt]] = v
+ }
- // Calculate cosine similarities
- cosAB := cosineSimilarity(testEmbed[tc.a], testEmbed[tc.b])
- cosAC := cosineSimilarity(testEmbed[tc.a], testEmbed[tc.c])
+ cosAB := cosineSimilarity(testEmbed[tc.a], testEmbed[tc.b])
+ cosAC := cosineSimilarity(testEmbed[tc.a], testEmbed[tc.c])
- // Calculate distances
- distAB := euclideanDistance(testEmbed[tc.a], testEmbed[tc.b])
- distAC := euclideanDistance(testEmbed[tc.a], testEmbed[tc.c])
+ distAB := euclideanDistance(testEmbed[tc.a], testEmbed[tc.b])
+ distAC := euclideanDistance(testEmbed[tc.a], testEmbed[tc.c])
- manhattanAB := manhattanDistance(testEmbed[tc.a], testEmbed[tc.b])
- manhattanAC := manhattanDistance(testEmbed[tc.a], testEmbed[tc.c])
+ manhattanAB := manhattanDistance(testEmbed[tc.a], testEmbed[tc.b])
+ manhattanAC := manhattanDistance(testEmbed[tc.a], testEmbed[tc.c])
- // Consistency check: if cosAB > cosAC, then distances should be smaller
- if cosAB > cosAC {
- if distAB >= distAC {
- t.Errorf("Euclidean distance inconsistency (%s) for %s-%s-%s: cosAB=%f > cosAC=%f but distAB=%f >= distAC=%f",
- model, tc.a, tc.b, tc.c, cosAB, cosAC, distAB, distAC)
- }
+ // Consistency check: if cosAB > cosAC, then distances should be smaller
+ if cosAB > cosAC {
+ if distAB >= distAC {
+ t.Errorf("Euclidean distance inconsistency (%s) for %s-%s-%s: cosAB=%f > cosAC=%f but distAB=%f >= distAC=%f",
+ model, tc.a, tc.b, tc.c, cosAB, cosAC, distAB, distAC)
+ }
- if manhattanAB >= manhattanAC {
- t.Errorf("Manhattan distance inconsistency (%s) for %s-%s-%s: cosAB=%f > cosAC=%f but manhattanAB=%f >= manhattanAC=%f",
- model, tc.a, tc.b, tc.c, cosAB, cosAC, manhattanAB, manhattanAC)
- }
- } else {
- t.Errorf("Cosine Similarity inconsistency (%s): cosinSim(%s, %s) < cosinSim(%s, %s)",
- model, tc.a, tc.b, tc.a, tc.c)
- }
+ if manhattanAB >= manhattanAC {
+ t.Errorf("Manhattan distance inconsistency (%s) for %s-%s-%s: cosAB=%f > cosAC=%f but manhattanAB=%f >= manhattanAC=%f",
+ model, tc.a, tc.b, tc.c, cosAB, cosAC, manhattanAB, manhattanAC)
}
- })
+ } else {
+ t.Errorf("Cosine Similarity inconsistency (%s): cosinSim(%s, %s) < cosinSim(%s, %s)",
+ model, tc.a, tc.b, tc.a, tc.c)
+ }
}
}
diff --git a/integration/migration_test.go b/integration/migration_test.go
new file mode 100644
index 000000000..04e8a0ab9
--- /dev/null
+++ b/integration/migration_test.go
@@ -0,0 +1,369 @@
+//go:build integration && migration
+
+package integration
+
+import (
+ "context"
+ "os"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/manifest"
+ "github.com/ollama/ollama/parser"
+ "github.com/ollama/ollama/types/model"
+)
+
+const (
+ migrationChatNumPredict = 2048
+ migrationDefaultGoTemplate = "{{ .Prompt }}"
+ migrationCompatEnv = "OLLAMA_LLAMA_CPP_COMPAT"
+ migrationGibiByte = 1 << 30
+
+ // Timeouts for vision/chat/audio/completion capability validations.
+ compatValidationInitialTimeout = 120 * time.Second
+ compatValidationStreamTimeout = 30 * time.Second
+ // Timeouts for the tool-call smoke test.
+ compatToolInitialTimeout = 60 * time.Second
+ compatToolStreamTimeout = 60 * time.Second
+ // keepAlive passed to validation loads so models unload promptly.
+ compatKeepAlive = 10 * time.Second
+
+ // Conversion wait when the source model size is unknown.
+ migrationConversionFallbackTimeout = 5 * time.Minute
+ // Conversion wait scales with source size: base + per-GiB, capped at max.
+ migrationConversionBaseTimeout = 2 * time.Minute
+ migrationConversionPerGiB = 10 * time.Second
+ migrationConversionMaxTimeout = 12 * time.Minute
+ // Poll interval while waiting for the converted manifest child.
+ migrationPollInterval = 2 * time.Second
+ // Wait and poll interval for models to unload after validation.
+ migrationUnloadTimeout = 2 * time.Minute
+ migrationUnloadPollInterval = 500 * time.Millisecond
+)
+
+func TestLocalCompatibilityMigration(t *testing.T) {
+ if os.Getenv("OLLAMA_TEST_EXISTING") != "" {
+ t.Skip("local compatibility migration requires a harness-managed server")
+ }
+ skipIfRemote(t)
+
+ names := compatibilityMigrationModelNames()
+ if testModel != "" {
+ names = []string{testModel}
+ }
+ for _, name := range names {
+ t.Run(name, func(t *testing.T) {
+ runLocalCompatibilityMigrationCase(t, name)
+ })
+ }
+}
+
+func runLocalCompatibilityMigrationCase(t *testing.T, name string) {
+ t.Helper()
+
+ modelsDir := os.Getenv("OLLAMA_MODELS")
+ if testModel == "" || modelsDir == "" {
+ modelsDir = t.TempDir()
+ t.Setenv("OLLAMA_MODELS", modelsDir)
+ }
+ t.Setenv("OLLAMA_DEBUG", "2")
+ t.Logf("%s: using migration model store %s", name, modelsDir)
+
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Minute)
+ defer cancel()
+
+ t.Logf("%s: starting harness-managed server", name)
+ client, _, cleanup := InitServerConnection(ctx, t)
+ defer func() {
+ if cleanup != nil {
+ cleanup()
+ }
+ }()
+
+ t.Logf("%s: pulling source model if needed", name)
+ pullOrSkip(ctx, t, client, name)
+
+ t.Logf("%s: reading source manifest", name)
+ firstShow := showOrFatal(ctx, t, client, name)
+ expectedCapabilities := normalizedCapabilities(firstShow.Capabilities)
+ expectedPromptConfig := promptConfigFromShow(t, firstShow)
+
+ t.Logf("%s: validating first load through legacy source", name)
+ firstValidationStart := len(serverLog.String())
+ validateCompatibilityPrimaryCapability(ctx, t, client, name, firstShow, time.Second)
+ t.Logf("%s: waiting for first load to unload", name)
+ waitForNoRunningModel(ctx, t, client, name)
+
+ firstValidationLogs := serverLog.String()[firstValidationStart:]
+ if !hasCompatPatchEvidence(firstValidationLogs) {
+ t.Fatalf("server log does not prove first load used compatibility patch")
+ }
+
+ conversionTimeout := migrationConversionTimeout(ctx, t, client, name)
+ t.Logf("%s: waiting for background %s conversion", name, manifest.RunnerLlamaCPP)
+ converted := waitForRunnerManifestChild(ctx, t, client, name, manifest.RunnerLlamaCPP, conversionTimeout)
+ t.Logf("%s: converted manifest digest %s", name, converted.Digest)
+ t.Logf("%s: reading converted manifest selection", name)
+ secondShow := showOrFatal(ctx, t, client, name)
+ if child := childSummaryForRunner(secondShow, manifest.RunnerGGML); child == nil {
+ t.Fatalf("converted manifest list for %s does not retain original %s child", name, manifest.RunnerGGML)
+ }
+ if child := childSummaryForRunner(secondShow, manifest.RunnerLlamaCPP); child == nil || !child.Selected {
+ t.Fatalf("converted %s child is not selected for %s after migration", manifest.RunnerLlamaCPP, name)
+ } else if child.Digest != converted.Digest {
+ t.Fatalf("selected %s child digest changed after migration: poll=%s show=%s", manifest.RunnerLlamaCPP, converted.Digest, child.Digest)
+ }
+ if got := normalizedCapabilities(secondShow.Capabilities); !slices.Equal(got, expectedCapabilities) {
+ t.Fatalf("converted %s child capabilities changed: before=%v after=%v", name, expectedCapabilities, got)
+ }
+ if got := promptConfigFromShow(t, secondShow); got != expectedPromptConfig {
+ t.Fatalf("converted %s child prompt config changed: before=%+v after=%+v", name, expectedPromptConfig, got)
+ }
+ t.Logf("%s: validating converted child", name)
+ convertedValidationStart := len(serverLog.String())
+ validateCompatibilityCapabilities(ctx, t, client, name, firstShow, compatKeepAlive)
+ t.Logf("%s: waiting for converted child to unload", name)
+ waitForNoRunningModel(ctx, t, client, name)
+
+ logs := serverLog.String()
+
+ t.Logf("%s: stopping first server before patch-disabled validation", name)
+ cleanup()
+ cleanup = nil
+
+ t.Logf("%s: checking migration and converted-load log evidence", name)
+ migrationComplete := strings.Index(logs, "local compatibility migration completed")
+ if migrationComplete < 0 {
+ t.Fatalf("server log does not contain background migration completion")
+ }
+ convertedValidationLogs := logs[convertedValidationStart:]
+ if !strings.Contains(convertedValidationLogs, "loading model via llama-server") {
+ t.Fatalf("server log does not show converted model load")
+ }
+ if hasCompatPatchEvidence(convertedValidationLogs) {
+ t.Fatalf("converted %s child still triggered compatibility patch after migration", name)
+ }
+
+ t.Logf("%s: restarting server with %s=0", name, migrationCompatEnv)
+ t.Setenv(migrationCompatEnv, "0")
+ patchDisabledClient, _, patchDisabledCleanup := InitServerConnection(ctx, t)
+ defer patchDisabledCleanup()
+
+ t.Logf("%s: validating converted child with compatibility patch disabled", name)
+ patchDisabledValidationStart := len(serverLog.String())
+ patchDisabledShow := showOrFatal(ctx, t, patchDisabledClient, name)
+ if child := childSummaryForRunner(patchDisabledShow, manifest.RunnerLlamaCPP); child == nil || !child.Selected {
+ t.Fatalf("converted %s child is not selected for %s with compatibility patch disabled", manifest.RunnerLlamaCPP, name)
+ }
+ validateCompatibilityCapabilities(ctx, t, patchDisabledClient, name, firstShow, compatKeepAlive)
+ waitForNoRunningModel(ctx, t, patchDisabledClient, name)
+
+ patchDisabledLogs := serverLog.String()[patchDisabledValidationStart:]
+ if hasCompatPatchEvidence(patchDisabledLogs) {
+ t.Fatalf("converted %s child triggered compatibility patch with %s=0", name, migrationCompatEnv)
+ }
+
+ t.Logf("%s: migration validation complete", name)
+}
+
+func migrationConversionTimeout(ctx context.Context, t *testing.T, client *api.Client, model string) time.Duration {
+ t.Helper()
+
+ list, err := client.List(ctx)
+ if err != nil {
+ t.Logf("%s: could not list local model size for conversion timeout: %v", model, err)
+ return migrationConversionFallbackTimeout
+ }
+ for _, candidate := range list.Models {
+ if sameModelName(candidate.Name, model) || sameModelName(candidate.Model, model) {
+ timeout := migrationConversionTimeoutForSize(candidate.Size)
+ t.Logf("%s: waiting up to %s for conversion of %d byte source", model, timeout, candidate.Size)
+ return timeout
+ }
+ }
+ t.Logf("%s: local model size not found for conversion timeout", model)
+ return migrationConversionFallbackTimeout
+}
+
+func migrationConversionTimeoutForSize(size int64) time.Duration {
+ timeout := migrationConversionBaseTimeout
+ if size > 0 {
+ timeout += time.Duration((size+migrationGibiByte-1)/migrationGibiByte) * migrationConversionPerGiB
+ }
+ if timeout > migrationConversionMaxTimeout {
+ return migrationConversionMaxTimeout
+ }
+ return timeout
+}
+
+// hasCompatPatchEvidence reports whether the server log shows a load that went
+// through the llama.cpp compatibility layer. Every handler in
+// llama/compat/llama-ollama-compat.cpp logs its detection with this prefix.
+func hasCompatPatchEvidence(logs string) bool {
+ return strings.Contains(logs, "detected Ollama-format")
+}
+
+func normalizedCapabilities(capabilities []model.Capability) []string {
+ out := make([]string, 0, len(capabilities))
+ for _, capability := range capabilities {
+ out = append(out, string(capability))
+ }
+ slices.Sort(out)
+ return out
+}
+
+func hasCapability(capabilities []model.Capability, capability model.Capability) bool {
+ return slices.Contains(capabilities, capability)
+}
+
+type migrationPromptConfig struct {
+ selectedTemplate string
+ goTemplate string
+ renderer string
+ parser string
+}
+
+func promptConfigFromShow(t *testing.T, resp *api.ShowResponse) migrationPromptConfig {
+ t.Helper()
+
+ out := migrationPromptConfig{selectedTemplate: resp.Template}
+ mf, err := parser.ParseFile(strings.NewReader(resp.Modelfile))
+ if err != nil {
+ t.Fatalf("parse show modelfile: %v", err)
+ }
+ for _, cmd := range mf.Commands {
+ switch cmd.Name {
+ case "template":
+ if strings.TrimSpace(cmd.Args) != migrationDefaultGoTemplate {
+ out.goTemplate = cmd.Args
+ }
+ case "renderer":
+ out.renderer = cmd.Args
+ case "parser":
+ out.parser = cmd.Args
+ }
+ }
+ return out
+}
+
+func showOrFatal(ctx context.Context, t *testing.T, client *api.Client, model string) *api.ShowResponse {
+ t.Helper()
+ resp, err := client.Show(ctx, &api.ShowRequest{Model: model})
+ if err != nil {
+ t.Fatalf("show %s failed: %v", model, err)
+ }
+ return resp
+}
+
+func childSummaryForRunner(resp *api.ShowResponse, runner string) *api.ManifestSummary {
+ for i := range resp.Manifests {
+ if resp.Manifests[i].Runner == runner {
+ return &resp.Manifests[i]
+ }
+ }
+ return nil
+}
+
+func waitForRunnerManifestChild(ctx context.Context, t *testing.T, client *api.Client, model, runner string, timeout time.Duration) api.ManifestSummary {
+ t.Helper()
+ deadline := time.Now().Add(timeout)
+ var lastErr error
+ attempt := 0
+ for time.Now().Before(deadline) {
+ attempt++
+ resp, err := client.Show(ctx, &api.ShowRequest{Model: model})
+ if err == nil {
+ if child := childSummaryForRunner(resp, runner); child != nil {
+ t.Logf("%s: found %s manifest child after %d poll(s)", model, runner, attempt)
+ return *child
+ }
+ } else {
+ lastErr = err
+ }
+ if attempt == 1 || attempt%10 == 0 {
+ t.Logf("%s: waiting for %s manifest child, poll=%d", model, runner, attempt)
+ }
+ time.Sleep(migrationPollInterval)
+ }
+ if lastErr != nil {
+ t.Fatalf("timed out waiting for %s manifest child for %s; last show error: %v", runner, model, lastErr)
+ }
+ t.Fatalf("timed out waiting for %s manifest child for %s", runner, model)
+ return api.ManifestSummary{}
+}
+
+func migrationToolNumPredict(name string) int {
+ if isModelFamily(name, "qwen3-vl") || isModelFamily(name, "qwen3-next") || isModelFamily(name, "laguna-xs.2") || isModelFamily(name, "nemotron-3-nano") {
+ return 2048
+ }
+ return 512
+}
+
+// migrationToolsSmokeModels lists tools-capable library model families used to
+// gate the tools smoke test during migration validation.
+var migrationToolsSmokeModels = []string{
+ "nemotron3:33b",
+ "laguna-xs.2",
+ "gemma4",
+ "lfm2.5-thinking",
+ "qwen3-vl",
+ "gpt-oss:20b",
+ "gpt-oss:120b",
+ "qwen3",
+ "llama3.1",
+ "llama3.2",
+ "mistral",
+ "qwen2.5",
+ "ministral-3",
+ "mistral-nemo",
+ "mistral-small",
+ "mixtral:8x22b",
+ "qwq",
+ "granite3.3",
+}
+
+func shouldSmokeTools(name string) bool {
+ for _, candidate := range migrationToolsSmokeModels {
+ if name == candidate || strings.HasPrefix(name, candidate+":") {
+ return true
+ }
+ }
+ return false
+}
+
+func isModelFamily(model, family string) bool {
+ name := strings.SplitN(model, ":", 2)[0]
+ if slash := strings.LastIndexByte(name, '/'); slash >= 0 {
+ name = name[slash+1:]
+ }
+ return name == family
+}
+
+func waitForNoRunningModel(ctx context.Context, t *testing.T, client *api.Client, model string) {
+ t.Helper()
+ deadline := time.Now().Add(migrationUnloadTimeout)
+ var last []string
+ for time.Now().Before(deadline) {
+ resp, err := client.ListRunning(ctx)
+ if err != nil {
+ t.Fatalf("ps failed while waiting for unload: %v", err)
+ }
+ last = last[:0]
+ running := false
+ for _, m := range resp.Models {
+ last = append(last, m.Name)
+ if sameModelName(m.Name, model) {
+ running = true
+ }
+ }
+ if !running {
+ return
+ }
+ time.Sleep(migrationUnloadPollInterval)
+ }
+ slices.Sort(last)
+ t.Fatalf("timed out waiting for %s to unload; running models: %s", model, strings.Join(last, ", "))
+}
diff --git a/integration/tools_test.go b/integration/tools_test.go
index fa1cebe77..102d09c79 100644
--- a/integration/tools_test.go
+++ b/integration/tools_test.go
@@ -73,8 +73,11 @@ func runAPIToolCallingModelWithClient(t *testing.T, ctx context.Context, client
skipUnderMinVRAM(t, v)
}
requireCapability(ctx, t, client, model, "tools")
+ testBasicToolCall(t, ctx, client, model, initialTimeout, streamTimeout)
+}
- tools := []api.Tool{
+func basicToolCallTools() []api.Tool {
+ return []api.Tool{
{
Type: "function",
Function: api.ToolFunction{
@@ -93,6 +96,22 @@ func runAPIToolCallingModelWithClient(t *testing.T, ctx context.Context, client
},
},
}
+}
+
+func testBasicToolCall(t *testing.T, ctx context.Context, client *api.Client, model string, initialTimeout, streamTimeout time.Duration) {
+ t.Helper()
+ testBasicToolCallWithNumPredict(t, ctx, client, model, initialTimeout, streamTimeout, 0)
+}
+
+func testBasicToolCallWithNumPredict(t *testing.T, ctx context.Context, client *api.Client, model string, initialTimeout, streamTimeout time.Duration, numPredict int) {
+ t.Helper()
+
+ options := map[string]any{
+ "temperature": 0,
+ }
+ if numPredict > 0 {
+ options["num_predict"] = numPredict
+ }
req := api.ChatRequest{
Model: model,
@@ -102,10 +121,8 @@ func runAPIToolCallingModelWithClient(t *testing.T, ctx context.Context, client
Content: "Call get_weather with location set to San Francisco.",
},
},
- Tools: tools,
- Options: map[string]any{
- "temperature": 0,
- },
+ Tools: basicToolCallTools(),
+ Options: options,
KeepAlive: &api.Duration{Duration: 10 * time.Second},
}
diff --git a/integration/utils_test.go b/integration/utils_test.go
index 0d7a4973e..cc7b86662 100644
--- a/integration/utils_test.go
+++ b/integration/utils_test.go
@@ -171,6 +171,31 @@ func GetTestEndpoint() (*api.Client, string) {
http.DefaultClient), fmt.Sprintf("%s:%s", host, port)
}
+func skipIfRemote(t *testing.T) {
+ t.Helper()
+
+ ollamaHost := os.Getenv("OLLAMA_HOST")
+ if ollamaHost == "" {
+ return
+ }
+ if !strings.Contains(ollamaHost, "://") {
+ ollamaHost = "http://" + ollamaHost
+ }
+ u, err := url.Parse(ollamaHost)
+ if err != nil {
+ t.Skipf("skipping local-server test with unparseable OLLAMA_HOST=%q", os.Getenv("OLLAMA_HOST"))
+ }
+
+ host := u.Hostname()
+ if host == "" || strings.EqualFold(host, "localhost") {
+ return
+ }
+ if ip := net.ParseIP(host); ip != nil && (ip.IsLoopback() || ip.IsUnspecified()) {
+ return
+ }
+ t.Skipf("skipping local-server test with remote OLLAMA_HOST=%q", os.Getenv("OLLAMA_HOST"))
+}
+
// Server lifecycle management
var (
serverMutex sync.Mutex
@@ -253,10 +278,15 @@ func PullIfMissing(ctx context.Context, client *api.Client, modelName string) er
}
slog.Info("model missing", "model", modelName)
- stallDuration := 2 * time.Minute // Includes checksum verification, which can take a while on larger models and slower systems.
+ var maxTotal int64
+ stallDuration := pullStallDuration(maxTotal)
stallTimer := time.NewTimer(stallDuration)
fn := func(resp api.ProgressResponse) error {
// fmt.Print(".")
+ if resp.Total > maxTotal {
+ maxTotal = resp.Total
+ stallDuration = pullStallDuration(maxTotal)
+ }
if !stallTimer.Reset(stallDuration) {
return errors.New("stall was detected, aborting status reporting")
}
@@ -276,12 +306,24 @@ func PullIfMissing(ctx context.Context, client *api.Client, modelName string) er
select {
case <-stallTimer.C:
- return errors.New("download stalled")
+ return fmt.Errorf("download stalled after %s without progress", stallDuration)
case <-done:
return pullError
}
}
+func pullStallDuration(total int64) time.Duration {
+ const gibiByte = 1 << 30
+
+ // The base includes checksum verification, which can take a while on
+ // larger models and slower systems.
+ timeout := 2 * time.Minute
+ if total > 0 {
+ timeout += time.Duration((total+gibiByte-1)/gibiByte) * 4 * time.Second
+ }
+ return min(timeout, 15*time.Minute)
+}
+
var serverProcMutex sync.Mutex
// Returns an Client, the testEndpoint, and a cleanup function, fails the test on errors
@@ -691,12 +733,16 @@ func skipIfModelTooLargeForVRAM(ctx context.Context, t *testing.T, client *api.C
t.Fatalf("list models failed %v", err)
}
for _, m := range resp.Models {
- if m.Name == modelName && float32(m.Size)*0.75 > float32(maxVram) {
+ if sameModelName(m.Name, modelName) && float32(m.Size)*0.75 > float32(maxVram) {
t.Skipf("model %s is too large %s for available VRAM %s", modelName, format.HumanBytes(m.Size), format.HumanBytes(int64(maxVram)))
}
}
}
+func sameModelName(a, b string) bool {
+ return a == b || strings.TrimSuffix(a, ":latest") == strings.TrimSuffix(b, ":latest")
+}
+
func skipUnderMinVRAM(t *testing.T, gb uint64) {
// TODO use info API in the future
if s := os.Getenv("OLLAMA_MAX_VRAM"); s != "" {
diff --git a/llama/compat/llama-ollama-compat.cpp b/llama/compat/llama-ollama-compat.cpp
index 17db74547..3e1cbddd4 100644
--- a/llama/compat/llama-ollama-compat.cpp
+++ b/llama/compat/llama-ollama-compat.cpp
@@ -31,6 +31,15 @@ namespace {
#define OLLAMA_COMPAT_LOG_INFO(...) do { LLAMA_LOG_INFO(__VA_ARGS__); } while (0)
#define OLLAMA_COMPAT_LOG_ERROR(...) LLAMA_LOG_ERROR(__VA_ARGS__)
+// Every handler's detection log line starts with "detected Ollama-format".
+// That prefix is load-bearing: integration/migration_test.go
+// (hasCompatPatchEvidence) greps server logs for it to prove whether a load
+// went through this compatibility layer. Keep it when adding handlers.
+//
+// The detect_ollama_* checks also mirror the Go-side NeedsMigration methods
+// in compatmigrate/ (one migrator per family); keep the two in sync so lazy
+// migration converts exactly the files this layer would patch.
+
double elapsed_ms(std::chrono::steady_clock::time_point start) {
return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
}
@@ -204,20 +213,17 @@ constexpr const char * kGemma3ChatTemplate = R"jinja({{ bos_token }}{% if messag
// An Ollama-format gemma3 file declares arch="gemma3" AND exhibits at
// least one converter quirk. Different converter versions produced
-// different quirks (4B/12B/27B have embedded vision + mm KVs; 1B uses
+// different quirks (4B/12B/27B have embedded vision tensors; 1B uses
// non-standard rope key names; all of them omit layer_norm_rms_epsilon).
bool detect_ollama_gemma3(const gguf_context * meta, const ggml_context * ctx) {
const int64_t arch_kid = gguf_find_key(meta, "general.architecture");
if (arch_kid < 0) return false;
if (std::strcmp(gguf_get_val_str(meta, arch_kid), "gemma3") != 0) return false;
- return has_key(meta, "gemma3.mm.tokens_per_image")
- || any_tensor_with_prefix(ctx, "v.")
+ return any_tensor_with_prefix(ctx, "v.")
|| any_tensor_with_prefix(ctx, "mm.")
|| has_key(meta, "gemma3.rope.global.freq_base")
|| has_key(meta, "gemma3.rope.local.freq_base")
- || has_key(meta, "tokenizer.ggml.add_padding_token")
- || has_key(meta, "tokenizer.ggml.add_unknown_token")
|| !has_key(meta, "gemma3.attention.layer_norm_rms_epsilon");
}
@@ -496,7 +502,7 @@ void handle_snowflake_arctic_embed2(gguf_context * meta) {
}
gguf_set_arr_data(meta, key, GGUF_TYPE_UINT8, decoded.data(), decoded.size());
- OLLAMA_COMPAT_LOG_INFO("%s: converted tokenizer precompiled charsmap to byte array\n", __func__);
+ OLLAMA_COMPAT_LOG_INFO("%s: detected Ollama-format snowflake-arctic-embed2 GGUF; converted tokenizer precompiled charsmap to byte array\n", __func__);
}
// =========================================================================
@@ -901,12 +907,10 @@ bool detect_ollama_qwen35moe(const gguf_context * meta, const ggml_context * ctx
// Published-model markers. llama.cpp-converted qwen35moe files have none
// of these: vision KVs live in a separate mmproj, MTP tensors are dropped,
- // head_count_kv is a scalar, and the extra rope / ssm / feed_forward KVs
- // are either absent or stored differently.
+ // head_count_kv is a scalar, and the extra rope / ssm KVs are absent.
return has_key(meta, "qwen35moe.vision.block_count")
|| has_key(meta, "qwen35moe.image_token_id")
|| has_key(meta, "qwen35moe.ssm.v_head_reordered")
- || has_key(meta, "qwen35moe.feed_forward_length")
|| has_key(meta, "qwen35moe.rope.mrope_interleaved")
|| any_tensor_with_prefix(ctx, "mtp.")
|| any_tensor_with_prefix(ctx, "v.");
@@ -957,7 +961,7 @@ bool detect_ollama_qwen3next(const gguf_context * meta) {
void handle_qwen3next(gguf_context * meta, ggml_context * ctx) {
if (!detect_ollama_qwen3next(meta)) return;
- OLLAMA_COMPAT_LOG_INFO("%s: detected qwen3next GGUF with ssm_dt tensors; applying compatibility fixes\n", __func__);
+ OLLAMA_COMPAT_LOG_INFO("%s: detected Ollama-format qwen3next GGUF with ssm_dt tensors; applying compatibility fixes\n", __func__);
collapse_u32_array_to_max(meta, "qwen3next.attention.head_count_kv", 0);
rename_qwen_ssm_dt_bias_tensors(meta, ctx);
}
@@ -1321,7 +1325,7 @@ bool detect_ollama_llama3_metadata_gap(const gguf_context * meta) {
void handle_llama3_metadata(gguf_context * meta) {
if (!detect_ollama_llama3_metadata_gap(meta)) return;
- OLLAMA_COMPAT_LOG_INFO("%s: detected Llama 3 tokenizer metadata gap; applying compatibility fixes\n", __func__);
+ OLLAMA_COMPAT_LOG_INFO("%s: detected Ollama-format llama GGUF with Llama 3 tokenizer metadata gap; applying compatibility fixes\n", __func__);
if (string_kv_missing_or_default(meta, "tokenizer.ggml.pre")) {
gguf_set_val_str(meta, "tokenizer.ggml.pre", "llama-bpe");
@@ -2769,6 +2773,10 @@ void handle_llama4_clip(gguf_context * meta, ggml_context * ctx) {
for (const auto & [from, to] : kLlama4ClipRenames) {
rename_tensors_containing(meta, ctx, from, to);
}
+
+ // Keep the live mmproj path aligned with converted llama.cpp projectors.
+ promote_tensor_to_f32(meta, ctx, "v.patch_embd.weight");
+ promote_tensor_to_f32(meta, ctx, "v.position_embd.weight");
}
// =========================================================================
@@ -3213,7 +3221,7 @@ bool needs_default_llava_projector_type(const gguf_context * meta) {
void handle_missing_llava_projector_type(gguf_context * meta) {
if (!needs_default_llava_projector_type(meta)) return;
- OLLAMA_COMPAT_LOG_INFO("%s: detected LLaVA/BakLLaVA projector without projector type; defaulting to mlp\n", __func__);
+ OLLAMA_COMPAT_LOG_INFO("%s: detected Ollama-format LLaVA/BakLLaVA projector without projector type; defaulting to mlp\n", __func__);
gguf_set_val_str(meta, "clip.projector_type", "mlp");
}
diff --git a/llm/server.go b/llm/server.go
index ee8a794f7..dc254c340 100644
--- a/llm/server.go
+++ b/llm/server.go
@@ -85,6 +85,13 @@ type LlamaServerConfig struct {
DraftModelShardPaths []string
}
+// IsLlamaCPP reports whether the server is backed by the llama.cpp
+// llama-server runner implementation.
+func IsLlamaCPP(s LlamaServer) bool {
+ _, ok := s.(*llamaServerRunner)
+ return ok
+}
+
// LoadModel loads GGUF model metadata from disk.
//
// It collects array values for arrays with a size less than or equal to
diff --git a/manifest/downgrade_test.go b/manifest/downgrade_test.go
new file mode 100644
index 000000000..f1f7ca4a2
--- /dev/null
+++ b/manifest/downgrade_test.go
@@ -0,0 +1,263 @@
+package manifest
+
+import (
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/ollama/ollama/types/model"
+)
+
+func digestOf(data []byte) string {
+ sum := sha256.Sum256(data)
+ return fmt.Sprintf("%x", sum)
+}
+
+// downgradePrune simulates a pre-manifest-list daemon's startup garbage
+// collection: every file in blobs that no legacy manifest references through
+// its config or layers is deleted.
+func downgradePrune(t *testing.T) {
+ t.Helper()
+
+ blobs, err := BlobsPath("")
+ if err != nil {
+ t.Fatal(err)
+ }
+ entries, err := os.ReadDir(blobs)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ legacyRoot, err := Path()
+ if err != nil {
+ t.Fatal(err)
+ }
+ retained := make(map[string]struct{})
+ err = filepath.Walk(legacyRoot, func(path string, info os.FileInfo, err error) error {
+ if err != nil || info.IsDir() {
+ return err
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return err
+ }
+ var m Manifest
+ if err := json.Unmarshal(data, &m); err != nil {
+ return err
+ }
+ for _, layer := range append(m.Layers, m.Config) {
+ if layer.Digest == "" {
+ continue
+ }
+ digest, err := canonicalBlobDigest(layer.Digest)
+ if err != nil {
+ continue
+ }
+ retained[digest] = struct{}{}
+ }
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ for _, entry := range entries {
+ digest, ok := DigestReference(entry.Name())
+ if !ok {
+ continue
+ }
+ if _, used := retained[digest]; used {
+ continue
+ }
+ if err := os.Remove(filepath.Join(blobs, entry.Name())); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func danglingEntry(t *testing.T, name model.Name) {
+ t.Helper()
+
+ v2Path, err := V2PathForName(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.MkdirAll(filepath.Dir(v2Path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.RemoveAll(v2Path); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(filepath.Join("..", "..", "blobs", "sha256-"+strings.Repeat("0", 64)), v2Path); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestResolvePathForNameFallsBackWhenV2EntryDangling(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ name := model.ParseName("example")
+
+ config, err := NewLayer(strings.NewReader(`{"model_type":"test"}`), MediaTypeImageConfig)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := WriteLegacyManifestData(name, mustMarshal(t, Manifest{SchemaVersion: 2, Config: config})); err != nil {
+ t.Fatal(err)
+ }
+ danglingEntry(t, name)
+
+ path, err := ResolvePathForName(name)
+ if err != nil {
+ t.Fatalf("resolve with dangling v2 entry: %v", err)
+ }
+ if _, err := os.Stat(path); err != nil {
+ t.Fatalf("resolved path %s: %v", path, err)
+ }
+ if got, err := V2PathForName(name); err == nil && path == got {
+ t.Fatal("resolved dangling v2 entry instead of the legacy manifest")
+ }
+}
+
+func TestResolvePathForNameDanglingWithoutLegacyIsNotExists(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ name := model.ParseName("example")
+ danglingEntry(t, name)
+
+ if _, err := ResolvePathForName(name); err == nil {
+ t.Fatal("resolved a dangling v2 entry with no fallback")
+ } else if !os.IsNotExist(err) {
+ t.Fatalf("resolve error = %v, want not exist", err)
+ }
+}
+
+func mustMarshal(t *testing.T, m Manifest) []byte {
+ t.Helper()
+
+ data, err := json.Marshal(m)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return data
+}
+
+// TestDowngradePruneKeepsManifestListBlobs covers the downgrade round trip:
+// v2 manifest documents must survive a pre-manifest-list daemon's garbage
+// collection when a legacy anchor references them.
+func TestDowngradePruneKeepsManifestListBlobs(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ name := model.ParseName("example")
+
+ // Build the model the way a pull does: layers, then a child manifest
+ // blob, then the parent list, then the legacy anchor.
+ weights, err := NewLayer(strings.NewReader("weights"), MediaTypeImageModel)
+ if err != nil {
+ t.Fatal(err)
+ }
+ config, err := NewLayer(strings.NewReader(`{"model_type":"test"}`), MediaTypeImageConfig)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ child := Manifest{SchemaVersion: 2, Config: config, Layers: []Layer{weights}}
+ childDigest, err := WriteManifestBlob(mustMarshal(t, child))
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ childRef, err := NewManifestReference(childDigest, RunnerLlamaCPP, FormatGGUF)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ parentDigest, err := WriteManifestList(name, []Manifest{childRef})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if err := WriteLegacyAnchor(name, &child, parentDigest, childDigest); err != nil {
+ t.Fatal(err)
+ }
+
+ downgradePrune(t)
+
+ for digest, what := range map[string]string{
+ parentDigest: "parent manifest list blob",
+ childDigest: "child manifest blob",
+ weights.Digest: "weights blob",
+ } {
+ path, err := BlobsPath(digest)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(path); err != nil {
+ t.Fatalf("%s did not survive the downgrade prune: %v", what, err)
+ }
+ }
+
+ // The v2 entry must still resolve after re-upgrade.
+ path, err := ResolvePathForName(name)
+ if err != nil {
+ t.Fatalf("resolve after downgrade prune: %v", err)
+ }
+ var parent Manifest
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := json.Unmarshal(data, &parent); err != nil {
+ t.Fatal(err)
+ }
+ if parent.MediaType != MediaTypeManifestList || len(parent.Manifests) != 1 {
+ t.Fatalf("resolved manifest = %+v, want the manifest list", parent)
+ }
+}
+
+// TestDowngradePruneKeepsPlainPullBlobs covers plain pulls: the anchor
+// references the model's own manifest document blob.
+func TestDowngradePruneKeepsPlainPullBlobs(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ name := model.ParseName("example")
+
+ weights, err := NewLayer(strings.NewReader("weights"), MediaTypeImageModel)
+ if err != nil {
+ t.Fatal(err)
+ }
+ config, err := NewLayer(strings.NewReader(`{"model_type":"test"}`), MediaTypeImageConfig)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ mf := Manifest{SchemaVersion: 2, Config: config, Layers: []Layer{weights}}
+ data := mustMarshal(t, mf)
+ if err := WriteManifestData(name, data); err != nil {
+ t.Fatal(err)
+ }
+
+ parentDigest := "sha256:" + digestOf(data)
+ if err := WriteLegacyAnchor(name, &mf, parentDigest); err != nil {
+ t.Fatal(err)
+ }
+
+ downgradePrune(t)
+
+ for digest, what := range map[string]string{
+ parentDigest: "manifest document blob",
+ weights.Digest: "weights blob",
+ } {
+ path, err := BlobsPath(digest)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(path); err != nil {
+ t.Fatalf("%s did not survive the downgrade prune: %v", what, err)
+ }
+ }
+}
diff --git a/manifest/layer.go b/manifest/layer.go
index 9088a3187..e1125166e 100644
--- a/manifest/layer.go
+++ b/manifest/layer.go
@@ -20,7 +20,20 @@ type Layer struct {
const (
MediaTypeImageTensor = "application/vnd.ollama.image.tensor"
+ MediaTypeImageJSON = "application/vnd.ollama.image.json"
MediaTypeImageDraft = "application/vnd.ollama.image.draft"
+
+ MediaTypeImageModel = "application/vnd.ollama.image.model"
+ MediaTypeImageProjector = "application/vnd.ollama.image.projector"
+ MediaTypeImageAdapter = "application/vnd.ollama.image.adapter"
+ MediaTypeImageEmbed = "application/vnd.ollama.image.embed"
+ MediaTypeImageTemplate = "application/vnd.ollama.image.template"
+ MediaTypeImageSystem = "application/vnd.ollama.image.system"
+ MediaTypeImageLicense = "application/vnd.ollama.image.license"
+ MediaTypeImageParams = "application/vnd.ollama.image.params"
+ MediaTypeImageMessages = "application/vnd.ollama.image.messages"
+
+ MediaTypeImageConfig = "application/vnd.docker.container.image.v1+json"
)
func NewLayer(r io.Reader, mediatype string) (Layer, error) {
@@ -74,6 +87,50 @@ func NewLayer(r io.Reader, mediatype string) (Layer, error) {
}, nil
}
+func NewLayerFromFile(path, mediatype string) (Layer, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return Layer{}, err
+ }
+
+ sha256sum := sha256.New()
+ n, err := io.Copy(sha256sum, f)
+ if err != nil {
+ f.Close()
+ return Layer{}, err
+ }
+ if err := f.Close(); err != nil {
+ return Layer{}, err
+ }
+
+ digest := fmt.Sprintf("sha256:%x", sha256sum.Sum(nil))
+ blob, err := BlobsPath(digest)
+ if err != nil {
+ return Layer{}, err
+ }
+
+ status := "using existing layer"
+ if _, err := os.Stat(blob); err != nil {
+ status = "creating new layer"
+ if err := os.Rename(path, blob); err != nil {
+ return Layer{}, err
+ }
+ if err := os.Chmod(blob, 0o644); err != nil {
+ return Layer{}, err
+ }
+ }
+ if err := touchLayer(blob); err != nil {
+ return Layer{}, err
+ }
+
+ return Layer{
+ MediaType: mediatype,
+ Digest: digest,
+ Size: n,
+ Status: fmt.Sprintf("%s %s", status, digest),
+ }, nil
+}
+
func NewLayerFromLayer(digest, mediatype, from string) (Layer, error) {
if digest == "" {
return Layer{}, errors.New("creating new layer from layer with empty digest")
@@ -124,25 +181,6 @@ func (l *Layer) Remove() error {
return nil
}
- // Ignore corrupt manifests to avoid blocking deletion of layers that are freshly orphaned
- ms, err := Manifests(true)
- if err != nil {
- return err
- }
-
- for _, m := range ms {
- for _, layer := range append(m.Layers, m.Config) {
- if layer.Digest == l.Digest {
- // something is using this layer
- return nil
- }
- }
- }
-
- blob, err := BlobsPath(l.Digest)
- if err != nil {
- return err
- }
-
- return os.Remove(blob)
+ _, err := RemoveUnreferencedBlobs(l.Digest)
+ return err
}
diff --git a/manifest/manifest.go b/manifest/manifest.go
index f84270705..be54ce12a 100644
--- a/manifest/manifest.go
+++ b/manifest/manifest.go
@@ -1,27 +1,142 @@
package manifest
import (
+ "bytes"
"crypto/sha256"
- "encoding/hex"
"encoding/json"
+ "errors"
"fmt"
"io"
"log/slog"
"os"
"path/filepath"
+ "regexp"
+ "runtime"
+ "slices"
+ "strings"
+ "sync"
"github.com/ollama/ollama/types/model"
)
+var (
+ blobFilenamePattern = regexp.MustCompile(`^sha256-[0-9a-fA-F]{64}$`)
+ manifestStoreMu sync.Mutex
+
+ // ErrNoCompatibleManifest is returned when a manifest list does not contain
+ // a child manifest for the requested runner.
+ ErrNoCompatibleManifest = errors.New("no compatible manifest found")
+)
+
+const (
+ MediaTypeManifest = "application/vnd.docker.distribution.manifest.v2+json"
+ MediaTypeManifestList = "application/vnd.ollama.manifest.list.v2+json"
+
+ RunnerMLX = "mlx"
+ RunnerGGML = "ggml"
+ RunnerLlamaCPP = "llamacpp"
+
+ FormatSafetensors = "safetensors"
+ FormatGGUF = "gguf"
+)
+
type Manifest struct {
- SchemaVersion int `json:"schemaVersion"`
- MediaType string `json:"mediaType"`
- Config Layer `json:"config"`
- Layers []Layer `json:"layers"`
+ SchemaVersion int `json:"schemaVersion"`
+ MediaType string `json:"mediaType"`
+ Config Layer `json:"config"`
+ Layers []Layer `json:"layers"`
+ Runner string `json:"runner,omitempty"`
+ Format string `json:"format,omitempty"`
+ Manifests []Manifest `json:"manifests,omitempty"`
+
+ filepath string
+ fi os.FileInfo
+ digest string
+ selectedDigest string
+ name model.Name
+}
+
+func (m Manifest) isReference() bool {
+ return m.MediaType != MediaTypeManifestList && m.digest != "" && m.Config.Digest == "" && len(m.Layers) == 0
+}
+
+func (m Manifest) MarshalJSON() ([]byte, error) {
+ if m.MediaType == MediaTypeManifestList {
+ return json.Marshal(struct {
+ SchemaVersion int `json:"schemaVersion"`
+ MediaType string `json:"mediaType"`
+ Manifests []Manifest `json:"manifests"`
+ }{
+ SchemaVersion: m.SchemaVersion,
+ MediaType: m.MediaType,
+ Manifests: m.Manifests,
+ })
+ }
+
+ if m.isReference() {
+ return json.Marshal(struct {
+ MediaType string `json:"mediaType"`
+ Digest string `json:"digest"`
+ Runner string `json:"runner,omitempty"`
+ Format string `json:"format,omitempty"`
+ }{
+ MediaType: m.MediaType,
+ Digest: m.BlobDigest(),
+ Runner: m.Runner,
+ Format: m.Format,
+ })
+ }
+
+ return json.Marshal(struct {
+ SchemaVersion int `json:"schemaVersion"`
+ MediaType string `json:"mediaType"`
+ Config Layer `json:"config"`
+ Layers []Layer `json:"layers"`
+ Runner string `json:"runner,omitempty"`
+ Format string `json:"format,omitempty"`
+ }{
+ SchemaVersion: m.SchemaVersion,
+ MediaType: m.MediaType,
+ Config: m.Config,
+ Layers: m.Layers,
+ Runner: m.Runner,
+ Format: m.Format,
+ })
+}
+
+func (m *Manifest) UnmarshalJSON(data []byte) error {
+ var raw struct {
+ SchemaVersion int `json:"schemaVersion"`
+ MediaType string `json:"mediaType"`
+ Config Layer `json:"config"`
+ Layers []Layer `json:"layers"`
+ Runner string `json:"runner,omitempty"`
+ Format string `json:"format,omitempty"`
+ Manifests []Manifest `json:"manifests,omitempty"`
+ Digest string `json:"digest,omitempty"`
+ }
+ if err := json.Unmarshal(data, &raw); err != nil {
+ return err
+ }
+
+ *m = Manifest{
+ SchemaVersion: raw.SchemaVersion,
+ MediaType: raw.MediaType,
+ Config: raw.Config,
+ Layers: raw.Layers,
+ Runner: raw.Runner,
+ Format: raw.Format,
+ Manifests: raw.Manifests,
+ }
+ if raw.Digest != "" {
+ digest, err := canonicalBlobDigest(raw.Digest)
+ if err != nil {
+ return err
+ }
+ m.digest = strings.TrimPrefix(digest, "sha256:")
+ }
- filepath string
- fi os.FileInfo
- digest string
+ return nil
}
func (m *Manifest) Size() (size int64) {
@@ -32,10 +147,49 @@ func (m *Manifest) Size() (size int64) {
return
}
+// TotalSizeForName returns the combined size of unique config and layer blobs
+// reachable from the named manifest object. Manifest blobs themselves are not
+// included in the total.
+func TotalSizeForName(n model.Name) (int64, error) {
+ if !n.IsFullyQualified() {
+ return 0, model.Unqualified(n)
+ }
+
+ p, root, err := resolveManifestPath(n)
+ if err != nil {
+ return 0, err
+ }
+
+ data, _, _, err := readVerifiedManifest(p, root)
+ if err != nil {
+ return 0, err
+ }
+
+ return totalSizeForManifestData(data)
+}
+
func (m *Manifest) Digest() string {
return m.digest
}
+// SelectedDigest returns the digest of the runnable manifest selected from a
+// manifest list. For non-list manifests, it is the same as Digest.
+func (m *Manifest) SelectedDigest() string {
+ if m.selectedDigest != "" {
+ return m.selectedDigest
+ }
+
+ return m.digest
+}
+
+func (m *Manifest) BlobDigest() string {
+ if m.digest == "" {
+ return ""
+ }
+
+ return "sha256:" + m.digest
+}
+
func (m *Manifest) FileInfo() os.FileInfo {
return m.fi
}
@@ -83,175 +237,1422 @@ func (m *Manifest) TensorLayers() []Layer {
return layers
}
-func (m *Manifest) Remove() error {
- if err := os.Remove(m.filepath); err != nil {
- return err
+// RemoveNamed removes a named manifest object and then removes any blobs that
+// were reachable only from that object. The removed blob digests are returned
+// even alongside an error, so callers can clean up anything derived from
+// them.
+func RemoveNamed(n model.Name) ([]string, error) {
+ if digest, ok, err := ResolveDigestReferenceName(n); err != nil {
+ return nil, err
+ } else if ok {
+ return removeDigestReference(digest)
}
- manifests, err := Path()
+ candidates, err := ReferencedBlobDigestsForName(n)
if err != nil {
- return err
+ return nil, err
+ }
+
+ if err := removeNamedManifestPaths(n); err != nil {
+ return nil, err
}
- return PruneDirectory(manifests)
+ return RemoveUnreferencedBlobs(candidates...)
}
-// RemoveLayers deletes the layers no other manifest references. The digests it
-// removed are returned even alongside an error, so callers can clean up
-// anything derived from them.
-func (m *Manifest) RemoveLayers() ([]string, error) {
- ms, err := Manifests(true)
+func removeDigestReference(digest string) ([]string, error) {
+ data, err := readManifestBlob(digest)
if err != nil {
return nil, err
}
- // Build set of digests still in use by other manifests
- inUse := make(map[string]struct{})
- for _, other := range ms {
- for _, layer := range append(other.Layers, other.Config) {
- if layer.Digest != "" {
- inUse[layer.Digest] = struct{}{}
- }
- }
+ digest, err = canonicalBlobDigest(digest)
+ if err != nil {
+ return nil, err
}
- // Remove layers not used by any other manifest
- var removed []string
- for _, layer := range append(m.Layers, m.Config) {
- if layer.Digest == "" {
+ candidates, err := referencedBlobDigestsForData(digest, data)
+ if err != nil {
+ return nil, err
+ }
+
+ extraCandidates, err := removeDigestFromManifestLists(digest)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := removeNamedManifestPathsForDigest(digest); err != nil {
+ return nil, err
+ }
+
+ candidates = append(candidates, extraCandidates...)
+ return RemoveUnreferencedBlobs(candidates...)
+}
+
+// ChildManifestDigest returns the digest identifying a manifest-list child:
+// its blob digest when it is a reference, otherwise the digest of its
+// canonical JSON encoding.
+func ChildManifestDigest(child Manifest) (string, error) {
+ if digest := child.BlobDigest(); digest != "" {
+ return digest, nil
+ }
+
+ data, err := json.Marshal(child)
+ if err != nil {
+ return "", err
+ }
+ sum := sha256.Sum256(data)
+ return fmt.Sprintf("sha256:%x", sum), nil
+}
+
+func removeDigestFromManifestLists(digest string) ([]string, error) {
+ target := strings.TrimPrefix(digest, "sha256:")
+ refs, err := namedManifestRefs(true)
+ if err != nil {
+ return nil, err
+ }
+
+ var candidates []string
+ for n, ref := range refs {
+ data, _, parentDigest, err := readVerifiedManifest(ref.path, ref.root)
+ if err != nil {
+ slog.Warn("bad manifest", "name", n, "error", err)
+ continue
+ }
+
+ parent, err := parseManifest(data)
+ if err != nil {
+ slog.Warn("bad manifest", "name", n, "error", err)
+ continue
+ }
+ if parent.MediaType != MediaTypeManifestList {
+ continue
+ }
+
+ kept := parent.Manifests[:0]
+ removed := false
+ for _, child := range parent.Manifests {
+ childDigest, err := ChildManifestDigest(child)
+ if err != nil {
+ return candidates, err
+ }
+ if strings.EqualFold(strings.TrimPrefix(childDigest, "sha256:"), target) {
+ removed = true
+ continue
+ }
+ kept = append(kept, child)
+ }
+ if !removed {
continue
}
- if _, used := inUse[layer.Digest]; used {
+
+ candidates = append(candidates, blobDigest(parentDigest))
+ if len(kept) == 0 {
+ if err := removeNamedManifestPaths(n); err != nil {
+ return candidates, err
+ }
continue
}
- blob, err := BlobsPath(layer.Digest)
+
+ parent.Manifests = kept
+ updated, err := json.Marshal(parent)
if err != nil {
- return removed, err
+ return candidates, err
}
- if err := os.Remove(blob); os.IsNotExist(err) {
- slog.Debug("layer does not exist", "digest", layer.Digest)
- } else if err != nil {
- return removed, err
+ if err := WriteManifestData(n, updated); err != nil {
+ return candidates, err
}
- removed = append(removed, layer.Digest)
}
- return removed, nil
+ return candidates, nil
}
-func ParseNamedManifest(n model.Name) (*Manifest, error) {
- if !n.IsFullyQualified() {
- return nil, model.Unqualified(n)
+func removeNamedManifestPathsForDigest(digest string) error {
+ digest, err := canonicalBlobDigest(digest)
+ if err != nil {
+ return err
}
+ target := strings.TrimPrefix(digest, "sha256:")
- manifests, err := Path()
+ refs, err := namedManifestRefs(true)
if err != nil {
- return nil, err
+ return err
+ }
+ for n, ref := range refs {
+ _, _, refDigest, err := readVerifiedManifest(ref.path, ref.root)
+ if err != nil {
+ slog.Warn("bad manifest", "name", n, "error", err)
+ continue
+ }
+ if !strings.EqualFold(refDigest, target) {
+ continue
+ }
+ if err := os.Remove(ref.path); err != nil && !os.IsNotExist(err) {
+ return err
+ }
}
- p := filepath.Join(manifests, n.Filepath())
+ return pruneManifestRoots()
+}
- var m Manifest
- f, err := os.Open(p)
- if err != nil {
- return nil, err
+// ReferencedBlobDigestsForName returns the blob digests reachable from the
+// named manifest object as stored on disk. Manifest lists include the parent
+// list blob, every child manifest blob, and each child's config and layer blobs.
+func ReferencedBlobDigestsForName(n model.Name) ([]string, error) {
+ if !n.IsFullyQualified() {
+ return nil, model.Unqualified(n)
}
- defer f.Close()
- fi, err := f.Stat()
+ p, root, err := resolveManifestPath(n)
if err != nil {
return nil, err
}
- sha256sum := sha256.New()
- if err := json.NewDecoder(io.TeeReader(f, sha256sum)).Decode(&m); err != nil {
+ data, _, digest, err := readVerifiedManifest(p, root)
+ if err != nil {
return nil, err
}
- m.filepath = p
- m.fi = fi
- m.digest = hex.EncodeToString(sha256sum.Sum(nil))
-
- return &m, nil
+ return referencedBlobDigestsForData(digest, data)
}
-func WriteManifest(name model.Name, config Layer, layers []Layer) error {
- manifests, err := Path()
+// RetainedBlobDigests returns the complete set of blob digests reachable from
+// all named manifest objects in the local store.
+func RetainedBlobDigests() (map[string]struct{}, error) {
+ refs, err := namedManifestRefs(true)
if err != nil {
- return err
+ return nil, err
}
- p := filepath.Join(manifests, name.Filepath())
- if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
- return err
+ retained := make(map[string]struct{})
+ for n, ref := range refs {
+ data, _, digest, err := readVerifiedManifest(ref.path, ref.root)
+ if err != nil {
+ slog.Warn("bad manifest", "name", n, "error", err)
+ continue
+ }
+
+ digests, err := referencedBlobDigestsForData(digest, data)
+ if err != nil {
+ slog.Warn("bad manifest", "name", n, "error", err)
+ continue
+ }
+
+ for _, digest := range digests {
+ retained[digest] = struct{}{}
+ }
}
- f, err := os.Create(p)
- if err != nil {
- return err
+ return retained, nil
+}
+
+func referencedBlobDigestsForData(manifestDigest string, data []byte) ([]string, error) {
+ var digests []string
+ seen := make(map[string]struct{})
+
+ add := func(digest string) error {
+ if digest == "" {
+ return nil
+ }
+
+ digest, err := canonicalBlobDigest(digest)
+ if err != nil {
+ return err
+ }
+ if _, ok := seen[digest]; ok {
+ return nil
+ }
+ seen[digest] = struct{}{}
+ digests = append(digests, digest)
+
+ return nil
}
- defer f.Close()
+ addManifest := func(m *Manifest) error {
+ for _, layer := range append(m.Layers, m.Config) {
+ if err := add(layer.Digest); err != nil {
+ return err
+ }
+ }
- m := Manifest{
- SchemaVersion: 2,
- MediaType: "application/vnd.docker.distribution.manifest.v2+json",
- Config: config,
- Layers: layers,
+ return nil
}
- return json.NewEncoder(f).Encode(m)
-}
+ if err := add(blobDigest(manifestDigest)); err != nil {
+ return nil, err
+ }
-func Manifests(continueOnError bool) (map[model.Name]*Manifest, error) {
- manifests, err := Path()
+ m, err := parseManifest(data)
if err != nil {
return nil, err
}
+ if m.MediaType == MediaTypeManifestList {
+ for i := range m.Manifests {
+ child := &m.Manifests[i]
+ if err := add(child.BlobDigest()); err != nil {
+ return nil, err
+ }
+ if child.isReference() {
+ resolved, ok, err := parseManifestBlobIfExists(child.BlobDigest())
+ if err != nil {
+ return nil, err
+ }
+ if !ok {
+ continue
+ }
+ child = resolved
+ }
+ if err := addManifest(child); err != nil {
+ return nil, err
+ }
+ }
+
+ return digests, nil
+ }
- // TODO(mxyng): use something less brittle
- matches, err := filepath.Glob(filepath.Join(manifests, "*", "*", "*", "*"))
- if err != nil {
+ if err := addManifest(m); err != nil {
return nil, err
}
- ms := make(map[model.Name]*Manifest)
- for _, match := range matches {
- fi, err := os.Stat(match)
+ return digests, nil
+}
+
+func totalSizeForManifestData(data []byte) (int64, error) {
+ seen := make(map[string]struct{})
+
+ addLayer := func(layer Layer) (int64, error) {
+ if layer.Digest == "" {
+ return 0, nil
+ }
+
+ digest, err := canonicalBlobDigest(layer.Digest)
if err != nil {
- return nil, err
+ return 0, err
}
+ if _, ok := seen[digest]; ok {
+ return 0, nil
+ }
+ seen[digest] = struct{}{}
- if !fi.IsDir() {
- rel, err := filepath.Rel(manifests, match)
+ return layer.Size, nil
+ }
+
+ addManifest := func(m *Manifest) (int64, error) {
+ var size int64
+ for _, layer := range append(m.Layers, m.Config) {
+ layerSize, err := addLayer(layer)
if err != nil {
- if !continueOnError {
- return nil, fmt.Errorf("%s %w", match, err)
- }
- slog.Warn("bad filepath", "path", match, "error", err)
- continue
+ return 0, err
}
+ size += layerSize
+ }
- n := model.ParseNameFromFilepath(rel)
- if !n.IsValid() {
- if !continueOnError {
- return nil, fmt.Errorf("%s %w", rel, err)
+ return size, nil
+ }
+
+ m, err := parseManifest(data)
+ if err != nil {
+ return 0, err
+ }
+ if m.MediaType == MediaTypeManifestList {
+ var size int64
+ for i := range m.Manifests {
+ child := &m.Manifests[i]
+ if child.isReference() {
+ resolved, ok, err := parseManifestBlobIfExists(child.BlobDigest())
+ if err != nil {
+ return 0, err
}
- slog.Warn("bad manifest name", "path", rel)
- continue
+ if !ok {
+ continue
+ }
+ child = resolved
}
- m, err := ParseNamedManifest(n)
+ childSize, err := addManifest(child)
if err != nil {
- if !continueOnError {
- return nil, fmt.Errorf("%s %w", n, err)
- }
- slog.Warn("bad manifest", "name", n, "error", err)
- continue
+ return 0, err
}
+ size += childSize
+ }
+
+ return size, nil
+ }
+
+ return addManifest(m)
+}
+
+// RemoveUnreferencedBlobs removes the candidate blobs that no other manifest
+// references. The digests it removed are returned even alongside an error, so
+// callers can clean up anything derived from them.
+func RemoveUnreferencedBlobs(candidates ...string) ([]string, error) {
+ manifestStoreMu.Lock()
+ defer manifestStoreMu.Unlock()
+
+ return removeUnreferencedBlobs(candidates...)
+}
+
+func removeUnreferencedBlobs(candidates ...string) ([]string, error) {
+ inUse, err := RetainedBlobDigests()
+ if err != nil {
+ return nil, err
+ }
+
+ var removed []string
+ for _, digest := range candidates {
+ if digest == "" {
+ continue
+ }
+ digest, err = canonicalBlobDigest(digest)
+ if err != nil {
+ return removed, err
+ }
+ if _, used := inUse[digest]; used {
+ continue
+ }
- ms[n] = m
+ blob, err := BlobsPath(digest)
+ if err != nil {
+ return removed, err
+ }
+ if err := os.Remove(blob); os.IsNotExist(err) {
+ slog.Debug("blob does not exist", "digest", digest)
+ } else if err != nil {
+ return removed, err
+ } else {
+ removed = append(removed, digest)
}
}
- return ms, nil
+ return removed, nil
+}
+
+func ParseNamedManifest(n model.Name) (*Manifest, error) {
+ return parseNamedManifest(n, runnerPreferences())
+}
+
+// ParseNamedManifestForRunner returns the named manifest selected for runner.
+// If the named object is a manifest list, runner must match one child entry.
+func ParseNamedManifestForRunner(n model.Name, runner string) (*Manifest, error) {
+ return parseNamedManifest(n, runnerPreferencesFor(runner))
+}
+
+func parseNamedManifest(n model.Name, preferences []string) (*Manifest, error) {
+ if !n.IsFullyQualified() {
+ return nil, model.Unqualified(n)
+ }
+
+ p, root, err := resolveManifestPath(n)
+ if err != nil {
+ return nil, err
+ }
+
+ return parseManifestFile(normalizeLogicalName(n), p, root, preferences)
+}
+
+func ReadManifestData(n model.Name) ([]byte, error) {
+ if !n.IsFullyQualified() {
+ return nil, model.Unqualified(n)
+ }
+
+ p, root, err := resolveManifestPath(n)
+ if err != nil {
+ return nil, err
+ }
+
+ f, _, err := OpenVerifiedManifest(p, root)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+
+ return io.ReadAll(f)
+}
+
+// ReadSelectedManifestData returns the runnable manifest bytes for a named
+// model. If the named object is a manifest list, it returns the selected child
+// manifest according to local runner preferences.
+func ReadSelectedManifestData(n model.Name) ([]byte, error) {
+ if !n.IsFullyQualified() {
+ return nil, model.Unqualified(n)
+ }
+
+ p, root, err := resolveManifestPath(n)
+ if err != nil {
+ return nil, err
+ }
+
+ data, _, _, err := readVerifiedManifest(p, root)
+ if err != nil {
+ return nil, err
+ }
+
+ m, err := parseManifest(data)
+ if err != nil {
+ return nil, err
+ }
+ if m.MediaType == MediaTypeManifestList {
+ child, err := selectManifest(m.Manifests)
+ if err != nil {
+ return nil, err
+ }
+ return json.Marshal(child)
+ }
+
+ return data, nil
+}
+
+func parseManifestFile(name model.Name, path, root string, preferences []string) (*Manifest, error) {
+ data, fi, digest, err := readVerifiedManifest(path, root)
+ if err != nil {
+ return nil, err
+ }
+
+ return parseManifestData(name, path, fi, digest, data, preferences)
+}
+
+func parseManifestData(name model.Name, path string, fi os.FileInfo, digest string, data []byte, preferences []string) (*Manifest, error) {
+ m, err := parseManifest(data)
+ if err != nil {
+ return nil, err
+ }
+ if m.MediaType == MediaTypeManifestList {
+ child, err := selectManifestWithPreferences(m.Manifests, preferences)
+ if err != nil {
+ return nil, err
+ }
+ selectedDigest := child.digest
+ child.filepath = path
+ child.fi = fi
+ child.digest = digest
+ child.selectedDigest = selectedDigest
+ child.name = name
+ return child, nil
+ }
+
+ // A single-entry preference list means the caller asked for a specific
+ // runner. Legacy manifests predate runner metadata, so derive the
+ // effective runner from the config rather than silently serving whatever
+ // is stored when the request cannot be honored.
+ if len(preferences) == 1 {
+ runner := canonicalRunner(m.Runner)
+ if runner == "" {
+ if config, err := readConfigV2(m.Config.Digest); err == nil {
+ runner, _ = MetadataForConfig(config)
+ }
+ }
+ if runner != "" && runner != canonicalRunner(preferences[0]) {
+ return nil, fmt.Errorf("%w for runners: %s", ErrNoCompatibleManifest, preferences[0])
+ }
+ }
+
+ m.Runner = canonicalRunner(m.Runner)
+ m.filepath = path
+ m.fi = fi
+ m.digest = digest
+ m.name = name
+
+ return m, nil
+}
+
+func selectManifest(manifests []Manifest) (*Manifest, error) {
+ return selectManifestWithPreferences(manifests, runnerPreferences())
+}
+
+// SelectManifestReferenceForRunner returns the manifest-list child selected for runner
+// without resolving it from the local blob store.
+func SelectManifestReferenceForRunner(manifests []Manifest, runner string) (*Manifest, error) {
+ return selectManifestReferenceWithPreferences(manifests, runnerPreferencesFor(runner))
+}
+
+func selectManifestWithPreferences(manifests []Manifest, preferences []string) (*Manifest, error) {
+ for _, runner := range preferences {
+ child, err := selectManifestReferenceWithPreferences(manifests, []string{runner})
+ if err != nil {
+ if errors.Is(err, ErrNoCompatibleManifest) {
+ continue
+ }
+ return nil, err
+ }
+
+ resolved, ok, err := resolveLocalManifestReference(child)
+ if err != nil {
+ return nil, err
+ }
+ if ok {
+ return resolved, nil
+ }
+ }
+
+ return nil, fmt.Errorf("%w for runners: %s", ErrNoCompatibleManifest, strings.Join(preferences, ", "))
+}
+
+// ResolveManifestReference resolves a manifest-list child to its full local
+// manifest, reading and digest-verifying the referenced blob when the child is
+// a bare reference. ok is false when the referenced blob is not local.
+func ResolveManifestReference(child Manifest) (*Manifest, bool, error) {
+ return resolveLocalManifestReference(&child)
+}
+
+func resolveLocalManifestReference(child *Manifest) (*Manifest, bool, error) {
+ if child.isReference() {
+ childDigest := child.digest
+ resolved, ok, err := parseManifestBlobIfExists(child.BlobDigest())
+ if err != nil || !ok {
+ return nil, ok, err
+ }
+ if resolved.Runner == "" {
+ resolved.Runner = child.Runner
+ }
+ if resolved.Format == "" {
+ resolved.Format = child.Format
+ }
+ if resolved.digest == "" {
+ resolved.digest = childDigest
+ }
+ child = resolved
+ }
+ child.Runner = canonicalRunner(child.Runner)
+ return child, true, nil
+}
+
+func selectManifestReferenceWithPreferences(manifests []Manifest, preferences []string) (*Manifest, error) {
+ for _, runner := range preferences {
+ for i := range manifests {
+ if manifests[i].MediaType != "" && manifests[i].MediaType != MediaTypeManifest {
+ continue
+ }
+ if canonicalRunner(manifests[i].Runner) != "" && canonicalRunner(manifests[i].Runner) == canonicalRunner(runner) {
+ child := manifests[i]
+ if !child.isReference() && child.digest == "" {
+ canonical, err := json.Marshal(child)
+ if err != nil {
+ return nil, err
+ }
+ sum := sha256.Sum256(canonical)
+ child.digest = fmt.Sprintf("%x", sum)
+ }
+ child.Runner = canonicalRunner(child.Runner)
+ return &child, nil
+ }
+ }
+ }
+
+ return nil, fmt.Errorf("%w for runners: %s", ErrNoCompatibleManifest, strings.Join(preferences, ", "))
+}
+
+func runnerPreferences() []string {
+ if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" {
+ return []string{RunnerMLX, RunnerLlamaCPP, RunnerGGML}
+ }
+
+ return []string{RunnerLlamaCPP, RunnerGGML, RunnerMLX}
+}
+
+func runnerPreferencesFor(runner string) []string {
+ runner = canonicalRunner(runner)
+ if runner == "" {
+ return runnerPreferences()
+ }
+
+ return []string{runner}
+}
+
+func canonicalRunner(runner string) string {
+ return strings.ToLower(strings.TrimSpace(runner))
+}
+
+// MetadataForConfig returns the default manifest-list runner and weight format
+// for a model config. It is intentionally conservative: GGUF models created by
+// the legacy path are tagged ggml, while converted GGUF manifests can override
+// the runner to llamacpp when they are written.
+func MetadataForConfig(config model.ConfigV2) (runner, format string) {
+ switch strings.ToLower(config.ModelFormat) {
+ case FormatSafetensors:
+ return RunnerMLX, FormatSafetensors
+ case FormatGGUF, "ggml":
+ return RunnerGGML, FormatGGUF
+ default:
+ return "", strings.ToLower(config.ModelFormat)
+ }
+}
+
+// FillMetadataForConfig populates missing runner/format metadata using the
+// model config without overwriting explicit manifest-list child metadata.
+func FillMetadataForConfig(m *Manifest, config model.ConfigV2) {
+ runner, format := MetadataForConfig(config)
+ if m.Runner == "" {
+ m.Runner = runner
+ } else {
+ m.Runner = canonicalRunner(m.Runner)
+ }
+ if m.Format == "" {
+ m.Format = format
+ } else {
+ m.Format = strings.ToLower(strings.TrimSpace(m.Format))
+ }
+}
+
+// FillMetadata populates missing runner/format metadata by reading the
+// manifest's config blob, and canonicalizes what is already present. It
+// returns an error when the metadata cannot be determined.
+func FillMetadata(m *Manifest) error {
+ if m.Runner != "" && m.Format != "" {
+ m.Runner = canonicalRunner(m.Runner)
+ m.Format = strings.ToLower(strings.TrimSpace(m.Format))
+ return nil
+ }
+
+ config, err := readConfigV2(m.Config.Digest)
+ if err != nil {
+ return err
+ }
+ FillMetadataForConfig(m, config)
+ if m.Runner == "" || m.Format == "" {
+ return errors.New("manifest is missing runner or format metadata")
+ }
+ return nil
+}
+
+func readConfigV2(digest string) (model.ConfigV2, error) {
+ var config model.ConfigV2
+ if digest == "" {
+ return config, errors.New("manifest is missing config digest")
+ }
+
+ configPath, err := BlobsPath(digest)
+ if err != nil {
+ return config, err
+ }
+ f, err := os.Open(configPath)
+ if err != nil {
+ return config, err
+ }
+ defer f.Close()
+
+ return config, json.NewDecoder(f).Decode(&config)
+}
+
+func parseManifest(data []byte) (*Manifest, error) {
+ var m Manifest
+ if err := json.Unmarshal(data, &m); err != nil {
+ return nil, err
+ }
+ if m.MediaType == MediaTypeManifestList {
+ for i := range m.Manifests {
+ if m.Manifests[i].MediaType == MediaTypeManifestList {
+ return nil, errors.New("nested manifest lists are not supported")
+ }
+ if m.Manifests[i].isReference() {
+ continue
+ }
+
+ canonical, err := json.Marshal(m.Manifests[i])
+ if err != nil {
+ return nil, err
+ }
+ sum := sha256.Sum256(canonical)
+ m.Manifests[i].digest = fmt.Sprintf("%x", sum)
+ }
+ }
+
+ return &m, nil
+}
+
+func readManifestBlob(digest string) ([]byte, error) {
+ digest, err := canonicalBlobDigest(digest)
+ if err != nil {
+ return nil, err
+ }
+
+ blobPath, err := BlobsPath(digest)
+ if err != nil {
+ return nil, err
+ }
+
+ data, err := os.ReadFile(blobPath)
+ if err != nil {
+ return nil, err
+ }
+ if err := checkBlobDigestReader(bytes.NewReader(data), digest); err != nil {
+ return nil, err
+ }
+
+ return data, nil
+}
+
+func parseManifestBlobIfExists(digest string) (*Manifest, bool, error) {
+ data, err := readManifestBlob(digest)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil, false, nil
+ }
+ return nil, false, err
+ }
+
+ m, err := parseManifest(data)
+ if err != nil {
+ return nil, false, err
+ }
+
+ return m, true, nil
+}
+
+func canonicalBlobDigest(digest string) (string, error) {
+ if _, err := BlobsPath(digest); err != nil {
+ return "", err
+ }
+
+ return NormalizeDigest(digest), nil
+}
+
+// NormalizeDigest canonicalizes a blob digest for comparison: lowercase, with
+// the filesystem's "sha256-" separator spelling folded to "sha256:". It does
+// not validate the digest.
+func NormalizeDigest(digest string) string {
+ return strings.ToLower(strings.Replace(strings.TrimSpace(digest), "-", ":", 1))
+}
+
+// SameDigest reports whether two blob digests refer to the same content,
+// tolerating case, separator, and bare-hex spelling differences.
+func SameDigest(a, b string) bool {
+ return a != "" && blobDigest(NormalizeDigest(a)) == blobDigest(NormalizeDigest(b))
+}
+
+func blobDigest(digest string) string {
+ if digest == "" {
+ return ""
+ }
+
+ digest = strings.ToLower(digest)
+ if strings.HasPrefix(digest, "sha256:") || strings.HasPrefix(digest, "sha256-") {
+ return digest
+ }
+
+ return "sha256:" + digest
+}
+
+func WriteManifest(name model.Name, config Layer, layers []Layer) error {
+ return WriteManifestWithMetadata(name, config, layers, "", "")
+}
+
+// WriteManifestWithMetadata stores a single runnable manifest with optional
+// runner and weight format metadata.
+func WriteManifestWithMetadata(name model.Name, config Layer, layers []Layer, runner, format string) error {
+ m := Manifest{
+ SchemaVersion: 2,
+ MediaType: MediaTypeManifest,
+ Config: config,
+ Layers: layers,
+ Runner: canonicalRunner(runner),
+ Format: format,
+ }
+
+ var b bytes.Buffer
+ if err := json.NewEncoder(&b).Encode(m); err != nil {
+ return err
+ }
+
+ return WriteManifestData(name, b.Bytes())
+}
+
+// NewManifestReference returns a manifest-list entry that points at an existing
+// child manifest blob.
+func NewManifestReference(digest, runner, format string) (Manifest, error) {
+ digest, err := canonicalBlobDigest(digest)
+ if err != nil {
+ return Manifest{}, err
+ }
+
+ return Manifest{
+ MediaType: MediaTypeManifest,
+ Runner: canonicalRunner(runner),
+ Format: format,
+ digest: strings.TrimPrefix(digest, "sha256:"),
+ }, nil
+}
+
+// WriteManifestBlob stores raw manifest bytes as a content-addressed blob.
+func WriteManifestBlob(data []byte) (string, error) {
+ return writeManifestBlob(data)
+}
+
+// WriteManifestData stores raw manifest bytes as a content-addressed blob and
+// updates the v2 named manifest path to reference that blob. Any legacy named
+// manifest for the same model is removed after the v2 write succeeds.
+func WriteManifestData(name model.Name, data []byte) error {
+ return writeManifestData(name, data, true)
+}
+
+// WriteManifestDataPreserveLegacy updates the v2 named manifest path without
+// removing legacy manifest entries for the same model.
+func WriteManifestDataPreserveLegacy(name model.Name, data []byte) error {
+ return writeManifestData(name, data, false)
+}
+
+// WriteManifestList stores a manifest list referencing refs under name. It
+// returns the digest of the stored manifest-list document blob.
+func WriteManifestList(name model.Name, refs []Manifest) (string, error) {
+ return writeManifestList(name, refs, false)
+}
+
+// WriteManifestListPreserveLegacy stores a manifest list while keeping any
+// legacy named manifest for the same model in place as a downgrade anchor. It
+// returns the digest of the stored manifest-list document blob.
+func WriteManifestListPreserveLegacy(name model.Name, refs []Manifest) (string, error) {
+ return writeManifestList(name, refs, true)
+}
+
+func writeManifestList(name model.Name, refs []Manifest, preserveLegacy bool) (string, error) {
+ parent := Manifest{
+ SchemaVersion: 2,
+ MediaType: MediaTypeManifestList,
+ Manifests: refs,
+ }
+ data, err := json.Marshal(parent)
+ if err != nil {
+ return "", err
+ }
+ digest := fmt.Sprintf("sha256:%x", sha256.Sum256(data))
+ if preserveLegacy {
+ return digest, WriteManifestDataPreserveLegacy(name, data)
+ }
+ return digest, WriteManifestData(name, data)
+}
+
+func writeManifestData(name model.Name, data []byte, removeLegacy bool) error {
+ if !name.IsFullyQualified() {
+ return model.Unqualified(name)
+ }
+
+ manifestStoreMu.Lock()
+ defer manifestStoreMu.Unlock()
+
+ digest, err := writeManifestBlob(data)
+ if err != nil {
+ return err
+ }
+
+ if err := linkManifest(name, digest); err != nil {
+ return err
+ }
+
+ if !removeLegacy {
+ return nil
+ }
+
+ return removeLegacyManifestPaths(name)
+}
+
+// WriteLegacyAnchor writes mf as a legacy manifest at name with the v2
+// manifest blobs named by manifestDigests appended as layers. The extra layers
+// exist only so a pre-manifest-list daemon's garbage collector, which retains
+// just the digests listed by legacy manifests, cannot delete the manifest
+// blobs during a downgrade.
+func WriteLegacyAnchor(name model.Name, mf *Manifest, manifestDigests ...string) error {
+ if mf == nil {
+ return errors.New("downgrade anchor requires a manifest")
+ }
+
+ anchor := *mf
+ anchor.Layers = slices.Clone(mf.Layers)
+ for _, manifestDigest := range manifestDigests {
+ digest, err := canonicalBlobDigest(manifestDigest)
+ if err != nil {
+ return err
+ }
+ data, err := readManifestBlob(digest)
+ if err != nil {
+ return err
+ }
+ mediaType := MediaTypeManifest
+ var m Manifest
+ if err := json.Unmarshal(data, &m); err == nil && m.MediaType == MediaTypeManifestList {
+ mediaType = MediaTypeManifestList
+ }
+ anchor.Layers = append(anchor.Layers, Layer{
+ MediaType: mediaType,
+ Digest: digest,
+ Size: int64(len(data)),
+ })
+ }
+
+ data, err := json.Marshal(anchor)
+ if err != nil {
+ return err
+ }
+
+ return WriteLegacyManifestData(name, data)
+}
+
+// WriteLegacyManifestData stores raw manifest bytes in the legacy named
+// manifest tree for compatibility with older Ollama releases.
+func WriteLegacyManifestData(name model.Name, data []byte) error {
+ if !name.IsFullyQualified() {
+ return model.Unqualified(name)
+ }
+
+ manifestStoreMu.Lock()
+ defer manifestStoreMu.Unlock()
+
+ name = normalizeLogicalName(name)
+ if !legacyManifestPathSupported(name) {
+ return nil
+ }
+
+ manifestPath, err := LegacyPathForName(name)
+ if err != nil {
+ return err
+ }
+ if err := os.MkdirAll(filepath.Dir(manifestPath), 0o755); err != nil {
+ return err
+ }
+
+ temp, err := os.CreateTemp(filepath.Dir(manifestPath), ".manifest-*")
+ if err != nil {
+ return err
+ }
+ tempName := temp.Name()
+ defer os.Remove(tempName)
+
+ if _, err := temp.Write(data); err != nil {
+ temp.Close()
+ return err
+ }
+ if err := temp.Close(); err != nil {
+ return err
+ }
+ if err := os.Chmod(tempName, 0o644); err != nil {
+ return err
+ }
+
+ return replaceManifestPath(tempName, manifestPath)
+}
+
+func linkManifest(name model.Name, digest string) error {
+ manifestPath, err := V2PathForName(name)
+ if err != nil {
+ return err
+ }
+ blobPath, err := BlobsPath(digest)
+ if err != nil {
+ return err
+ }
+ if _, err := os.Stat(blobPath); err != nil {
+ return err
+ }
+ if err := checkBlobDigest(blobPath, digest); err != nil {
+ return err
+ }
+
+ if err := os.MkdirAll(filepath.Dir(manifestPath), 0o755); err != nil {
+ return err
+ }
+
+ if rel, err := filepath.Rel(filepath.Dir(manifestPath), blobPath); err == nil {
+ tempName, err := tempManifestPath(filepath.Dir(manifestPath))
+ if err != nil {
+ return err
+ }
+ defer os.Remove(tempName)
+ if err := os.Symlink(rel, tempName); err == nil {
+ return replaceManifestPath(tempName, manifestPath)
+ }
+ }
+
+ return copyManifestFile(blobPath, manifestPath)
+}
+
+func writeManifestBlob(data []byte) (string, error) {
+ sum := sha256.Sum256(data)
+ digest := fmt.Sprintf("sha256:%x", sum)
+
+ blobPath, err := BlobsPath(digest)
+ if err != nil {
+ return "", err
+ }
+ if existing, err := os.ReadFile(blobPath); err == nil && bytes.Equal(existing, data) {
+ return digest, nil
+ }
+
+ blobs, err := BlobsPath("")
+ if err != nil {
+ return "", err
+ }
+ temp, err := os.CreateTemp(blobs, "sha256-")
+ if err != nil {
+ return "", err
+ }
+ tempName := temp.Name()
+ defer os.Remove(tempName)
+
+ if _, err := temp.Write(data); err != nil {
+ temp.Close()
+ return "", err
+ }
+ if err := temp.Close(); err != nil {
+ return "", err
+ }
+ if err := os.Chmod(tempName, 0o644); err != nil {
+ return "", err
+ }
+ if err := os.Rename(tempName, blobPath); err != nil {
+ // Accept a racing identical blob; otherwise leave it untouched.
+ if existing, readErr := os.ReadFile(blobPath); readErr == nil && bytes.Equal(existing, data) {
+ return digest, nil
+ }
+ return "", err
+ }
+
+ return digest, nil
+}
+
+func copyManifestFile(src, dst string) error {
+ in, err := os.Open(src)
+ if err != nil {
+ return err
+ }
+ defer in.Close()
+
+ temp, err := os.CreateTemp(filepath.Dir(dst), ".manifest-*")
+ if err != nil {
+ return err
+ }
+ tempName := temp.Name()
+ defer os.Remove(tempName)
+
+ if _, err := io.Copy(temp, in); err != nil {
+ temp.Close()
+ return err
+ }
+ if err := temp.Close(); err != nil {
+ return err
+ }
+ if err := os.Chmod(tempName, 0o644); err != nil {
+ return err
+ }
+
+ return replaceManifestPath(tempName, dst)
+}
+
+func tempManifestPath(dir string) (string, error) {
+ temp, err := os.CreateTemp(dir, ".manifest-*")
+ if err != nil {
+ return "", err
+ }
+ tempName := temp.Name()
+ if err := temp.Close(); err != nil {
+ os.Remove(tempName)
+ return "", err
+ }
+ if err := os.Remove(tempName); err != nil {
+ return "", err
+ }
+
+ return tempName, nil
+}
+
+func replaceManifestPath(tempName, dst string) error {
+ if err := os.Rename(tempName, dst); err == nil {
+ return nil
+ } else if runtime.GOOS != "windows" {
+ return err
+ }
+
+ // Windows does not replace an existing destination with Rename. The store
+ // mutex keeps this path safe within a process; callers still prepare the new
+ // ref before the old one is removed.
+ if err := os.Remove(dst); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+
+ return os.Rename(tempName, dst)
+}
+
+// OpenVerifiedManifest opens a named manifest path rooted under root. Symlinks must resolve to a
+// blob whose basename is sha256-<hex> and whose bytes hash to that digest.
+// Regular-file manifests are treated as legacy/copy fallback manifests and are
+// opened without mutating the local store.
+func OpenVerifiedManifest(path, root string) (*os.File, string, error) {
+ resolvedRoot, err := filepath.EvalSymlinks(root)
+ if err != nil {
+ return nil, "", err
+ }
+
+ info, err := os.Lstat(path)
+ if err != nil {
+ return nil, "", err
+ }
+
+ target, err := evalAbs(path)
+ if err != nil {
+ return nil, "", err
+ }
+
+ if info.Mode()&os.ModeSymlink != 0 {
+ base := filepath.Base(target)
+ if !blobFilenamePattern.MatchString(base) {
+ return nil, "", fmt.Errorf("manifest symlink target %q is not a sha256 blob", target)
+ }
+
+ digest := strings.ToLower(strings.TrimPrefix(base, "sha256-"))
+ blobPath, err := BlobsPath("sha256:" + digest)
+ if err != nil {
+ return nil, "", err
+ }
+ if !sameFile(target, blobPath) {
+ return nil, "", fmt.Errorf("manifest symlink target %q does not match blob %q", target, blobPath)
+ }
+
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, "", err
+ }
+ if err := checkBlobDigestReader(f, "sha256:"+digest); err != nil {
+ f.Close()
+ return nil, "", err
+ }
+ if _, err := f.Seek(0, io.SeekStart); err != nil {
+ f.Close()
+ return nil, "", err
+ }
+
+ return f, digest, nil
+ }
+
+ if !pathWithin(target, resolvedRoot) {
+ return nil, "", fmt.Errorf("manifest path %q resolves outside manifest directory", path)
+ }
+
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, "", err
+ }
+
+ h := sha256.New()
+ if _, err := io.Copy(h, f); err != nil {
+ f.Close()
+ return nil, "", err
+ }
+ if _, err := f.Seek(0, io.SeekStart); err != nil {
+ f.Close()
+ return nil, "", err
+ }
+ digest := fmt.Sprintf("%x", h.Sum(nil))
+
+ return f, digest, nil
+}
+
+// MigrateManifestLinks moves legacy named manifests into manifests-v2. This is currently unwired but
+// will be added in the future.
+func MigrateManifestLinks() (int, error) {
+ manifests, err := Path()
+ if err != nil {
+ return 0, err
+ }
+
+ // TODO(mxyng): use something less brittle
+ matches, err := filepath.Glob(filepath.Join(manifests, "*", "*", "*", "*"))
+ if err != nil {
+ return 0, err
+ }
+
+ var migrated int
+ for _, match := range matches {
+ fi, err := os.Stat(match)
+ if err != nil {
+ return migrated, err
+ }
+ if fi.IsDir() {
+ continue
+ }
+
+ rel, err := filepath.Rel(manifests, match)
+ if err != nil {
+ return migrated, fmt.Errorf("%s %w", match, err)
+ }
+
+ n := model.ParseNameFromFilepath(rel)
+ if !n.IsFullyQualified() {
+ slog.Warn("bad manifest name", "path", rel)
+ continue
+ }
+
+ data, err := readManifestPath(match, manifests)
+ if err != nil {
+ return migrated, err
+ }
+ if err := WriteManifestData(normalizeLogicalName(n), data); err != nil {
+ return migrated, err
+ }
+ migrated++
+ }
+
+ return migrated, nil
+}
+
+func readManifestPath(path, root string) ([]byte, error) {
+ data, _, _, err := readVerifiedManifest(path, root)
+ return data, err
+}
+
+func readVerifiedManifest(path, root string) ([]byte, os.FileInfo, string, error) {
+ f, digest, err := OpenVerifiedManifest(path, root)
+ if err != nil {
+ return nil, nil, "", err
+ }
+ defer f.Close()
+
+ fi, err := os.Lstat(path)
+ if err != nil {
+ return nil, nil, "", err
+ }
+
+ data, err := io.ReadAll(f)
+ if err != nil {
+ return nil, nil, "", err
+ }
+
+ return data, fi, digest, nil
+}
+
+func pathWithin(path, root string) bool {
+ rel, err := filepath.Rel(root, path)
+ return err == nil && rel != "." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) && rel != ".."
+}
+
+func evalAbs(path string) (string, error) {
+ abs, err := filepath.Abs(path)
+ if err != nil {
+ return "", err
+ }
+ return filepath.EvalSymlinks(abs)
+}
+
+func sameFile(a, b string) bool {
+ ai, err := os.Stat(a)
+ if err != nil {
+ return false
+ }
+ bi, err := os.Stat(b)
+ if err != nil {
+ return false
+ }
+ return os.SameFile(ai, bi)
+}
+
+func checkBlobDigest(path, digest string) error {
+ f, err := os.Open(path)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+
+ return checkBlobDigestReader(f, digest)
+}
+
+func checkBlobDigestReader(r io.Reader, digest string) error {
+ h := sha256.New()
+ if _, err := io.Copy(h, r); err != nil {
+ return err
+ }
+
+ got := fmt.Sprintf("sha256:%x", h.Sum(nil))
+ if got != strings.ToLower(strings.Replace(digest, "-", ":", 1)) {
+ return errors.New("digest mismatch")
+ }
+
+ return nil
+}
+
+func Manifests(continueOnError bool) (map[model.Name]*Manifest, error) {
+ refs, err := namedManifestRefs(continueOnError)
+ if err != nil {
+ return nil, err
+ }
+
+ ms := make(map[model.Name]*Manifest, len(refs))
+ for n, ref := range refs {
+ m, err := parseManifestFile(n, ref.path, ref.root, runnerPreferences())
+ if err != nil {
+ if !continueOnError {
+ return nil, fmt.Errorf("%s %w", n, err)
+ }
+ slog.Warn("bad manifest", "name", n, "error", err)
+ continue
+ }
+
+ ms[n] = m
+ }
+ return ms, nil
+}
+
+type namedManifestRef struct {
+ path string
+ root string
+}
+
+func namedManifestRefs(continueOnError bool) (map[model.Name]namedManifestRef, error) {
+ refs := make(map[model.Name]namedManifestRef)
+
+ manifestsV2, err := V2Path()
+ if err != nil {
+ return nil, err
+ }
+ if err := collectManifestRefs(refs, manifestsV2, continueOnError); err != nil {
+ return nil, err
+ }
+
+ manifests, err := Path()
+ if err != nil {
+ return nil, err
+ }
+ if err := collectManifestRefs(refs, manifests, continueOnError); err != nil {
+ return nil, err
+ }
+
+ return refs, nil
+}
+
+func collectManifestRefs(refs map[model.Name]namedManifestRef, root string, continueOnError bool) error {
+ // TODO(mxyng): use something less brittle
+ matches, err := filepath.Glob(filepath.Join(root, "*", "*", "*", "*"))
+ if err != nil {
+ return err
+ }
+
+ for _, match := range matches {
+ fi, err := os.Lstat(match)
+ if err != nil {
+ return err
+ }
+
+ if !fi.IsDir() {
+ rel, err := filepath.Rel(root, match)
+ if err != nil {
+ if !continueOnError {
+ return fmt.Errorf("%s %w", match, err)
+ }
+ slog.Warn("bad filepath", "path", match, "error", err)
+ continue
+ }
+
+ n := parseStoredManifestFilepath(rel)
+ if !n.IsValid() {
+ if !continueOnError {
+ return fmt.Errorf("invalid manifest name: %s", rel)
+ }
+ slog.Warn("bad manifest name", "path", rel)
+ continue
+ }
+
+ n = normalizeLogicalName(n)
+ if _, ok := refs[n]; ok {
+ continue
+ }
+
+ refs[n] = namedManifestRef{path: match, root: root}
+ }
+ }
+
+ return nil
}
diff --git a/manifest/manifest_test.go b/manifest/manifest_test.go
index 9eb83789e..765a6795d 100644
--- a/manifest/manifest_test.go
+++ b/manifest/manifest_test.go
@@ -1,32 +1,1141 @@
package manifest
import (
+ "bytes"
+ "crypto/sha256"
"encoding/json"
+ "errors"
+ "fmt"
"os"
"path/filepath"
"slices"
+ "strings"
"testing"
+ "time"
"github.com/ollama/ollama/types/model"
)
+func createManifestAtRoot(t *testing.T, path, root, name string) {
+ t.Helper()
+
+ p := filepath.Join(path, root, name)
+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
+ t.Fatal(err)
+ }
+
+ f, err := os.Create(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+
+ if err := json.NewEncoder(f).Encode(Manifest{}); err != nil {
+ t.Fatal(err)
+ }
+}
+
func createManifest(t *testing.T, path, name string) {
t.Helper()
+ createManifestAtRoot(t, path, "manifests", name)
+}
+
+func createManifestForTest(configDigest, layerDigest, runner string) Manifest {
+ return Manifest{
+ SchemaVersion: 2,
+ MediaType: MediaTypeManifest,
+ Runner: runner,
+ Format: FormatGGUF,
+ Config: Layer{
+ MediaType: "application/vnd.docker.container.image.v1+json",
+ Digest: configDigest,
+ Size: 12,
+ },
+ Layers: []Layer{
+ {
+ MediaType: "application/vnd.ollama.image.model",
+ Digest: layerDigest,
+ Size: 34,
+ },
+ },
+ }
+}
+
+func createManifestListData(t *testing.T, manifests ...Manifest) []byte {
+ t.Helper()
+
+ ml := Manifest{
+ SchemaVersion: 2,
+ MediaType: MediaTypeManifestList,
+ Manifests: manifests,
+ }
+
+ data, err := json.Marshal(ml)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ return data
+}
+
+func writeManifestBlobForTest(t *testing.T, data []byte) string {
+ t.Helper()
+
+ digest, err := writeManifestBlob(data)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ return digest
+}
+
+func TestWriteManifestStoresManifestAsBlob(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ name := model.ParseName("example")
+ config := Layer{
+ MediaType: "application/vnd.docker.container.image.v1+json",
+ Digest: "sha256:" + strings.Repeat("a", 64),
+ Size: 12,
+ }
+
+ if err := WriteManifest(name, config, nil); err != nil {
+ t.Fatal(err)
+ }
+
+ manifestPath, err := V2PathForName(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ manifestData, err := os.ReadFile(manifestPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ sum := sha256.Sum256(manifestData)
+ digest := fmt.Sprintf("sha256:%x", sum)
+ blobPath, err := BlobsPath(digest)
+ if err != nil {
+ t.Fatal(err)
+ }
+ blobData, err := os.ReadFile(blobPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(blobData, manifestData) {
+ t.Fatal("manifest path and blob content differ")
+ }
+
+ m, err := ParseNamedManifest(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := m.Digest(); got != fmt.Sprintf("%x", sum) {
+ t.Fatalf("digest = %q, want %x", got, sum)
+ }
+ if got := m.BlobDigest(); got != digest {
+ t.Fatalf("blob digest = %q, want %q", got, digest)
+ }
+}
+
+func TestV2ManifestPathEscapesHostPort(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ name := model.ParseNameBare("127.0.0.1:12345/library/test:latest")
+ data := []byte(`{"schemaVersion":2,"mediaType":"application/vnd.docker.distribution.manifest.v2+json"}`)
+ if err := WriteManifestData(name, data); err != nil {
+ t.Fatal(err)
+ }
+
+ manifestPath, err := V2PathForName(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ root, err := V2Path()
+ if err != nil {
+ t.Fatal(err)
+ }
+ rel, err := filepath.Rel(root, manifestPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ parts := strings.Split(rel, string(filepath.Separator))
+ if len(parts) != 4 {
+ t.Fatalf("manifest path %q has %d parts, want 4", rel, len(parts))
+ }
+ if got, want := parts[0], "127.0.0.1%3A12345"; got != want {
+ t.Fatalf("encoded host path part = %q, want %q", got, want)
+ }
+
+ gotData, err := ReadManifestData(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(gotData, data) {
+ t.Fatal("read manifest data differs from written manifest data")
+ }
+
+ manifests, err := Manifests(false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := manifests[name]; !ok {
+ t.Fatalf("manifest %s was not enumerated", name)
+ }
+}
+
+func TestManifestStoreLockKeepsManifestBlobDuringConcurrentPrune(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ name := model.ParseName("example")
+ data := []byte(`{"schemaVersion":2,"mediaType":"application/vnd.docker.distribution.manifest.v2+json"}`)
+ sum := sha256.Sum256(data)
+ digest := fmt.Sprintf("sha256:%x", sum)
+ blobPath, err := BlobsPath(digest)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ manifestStoreMu.Lock()
+ locked := true
+ unlock := func() {
+ if locked {
+ manifestStoreMu.Unlock()
+ locked = false
+ }
+ }
+ defer unlock()
+
+ if got, err := writeManifestBlob(data); err != nil {
+ t.Fatal(err)
+ } else if !SameDigest(got, digest) {
+ t.Fatalf("manifest blob digest = %q, want %q", got, digest)
+ }
+
+ pruneDone := make(chan error, 1)
+ go func() {
+ _, err := RemoveUnreferencedBlobs(digest)
+ pruneDone <- err
+ }()
+
+ select {
+ case err := <-pruneDone:
+ t.Fatalf("prune completed before manifest link was visible: %v", err)
+ case <-time.After(100 * time.Millisecond):
+ }
+
+ if err := linkManifest(name, digest); err != nil {
+ t.Fatal(err)
+ }
+ unlock()
+
+ if err := <-pruneDone; err != nil {
+ t.Fatal(err)
+ }
+
+ if _, err := os.Stat(blobPath); err != nil {
+ t.Fatalf("manifest blob was pruned after link: %v", err)
+ }
+ if _, err := ParseNamedManifest(name); err != nil {
+ t.Fatalf("manifest was not readable after concurrent prune: %v", err)
+ }
+}
+
+func TestWriteManifestBlobDoesNotRemoveDestinationOnRenameFailure(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ data := []byte(`{"schemaVersion":2,"mediaType":"application/vnd.docker.distribution.manifest.v2+json"}`)
+ sum := sha256.Sum256(data)
+ digest := fmt.Sprintf("sha256:%x", sum)
+ blobPath, err := BlobsPath(digest)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Mkdir(blobPath, 0o755); err != nil {
+ t.Fatal(err)
+ }
+
+ if _, err := writeManifestBlob(data); err == nil {
+ t.Fatal("writeManifestBlob succeeded with an existing directory at the blob path")
+ }
+
+ fi, err := os.Lstat(blobPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !fi.IsDir() {
+ t.Fatalf("blob path was replaced; mode = %s, want directory", fi.Mode())
+ }
+}
+
+func TestParseNamedManifestUsesNamedPathModTime(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ name := model.ParseName("example")
+ data := []byte(`{"schemaVersion":2,"mediaType":"application/vnd.docker.distribution.manifest.v2+json"}`)
+ if err := WriteManifestData(name, data); err != nil {
+ t.Fatal(err)
+ }
+
+ manifestPath, err := ResolvePathForName(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ namedInfo, err := os.Lstat(manifestPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ mf, err := ParseNamedManifest(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ blobPath, err := BlobsPath(mf.BlobDigest())
+ if err != nil {
+ t.Fatal(err)
+ }
+ oldBlobTime := namedInfo.ModTime().Add(-time.Hour)
+ if err := os.Chtimes(blobPath, oldBlobTime, oldBlobTime); err != nil {
+ t.Fatal(err)
+ }
+
+ mf, err = ParseNamedManifest(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := mf.FileInfo().ModTime(); !got.Equal(namedInfo.ModTime()) {
+ t.Fatalf("manifest mod time = %s, want named path %s", got, namedInfo.ModTime())
+ }
+}
+
+func TestDigestReference(t *testing.T) {
+ hex := strings.Repeat("a", 64)
+ digest, ok := DigestReference("sha256-" + hex)
+ if !ok {
+ t.Fatal("DigestReference() did not parse valid reference")
+ }
+ if digest != "sha256:"+hex {
+ t.Fatalf("digest = %q, want sha256:%s", digest, hex)
+ }
+
+ for _, ref := range []string{
+ "sha256:" + hex,
+ "/tmp/sha256-" + hex,
+ "../sha256-" + hex,
+ "library/sha256-" + hex,
+ "sha256-" + strings.Repeat("g", 64),
+ } {
+ if _, ok := DigestReference(ref); ok {
+ t.Fatalf("DigestReference(%q) parsed unexpectedly", ref)
+ }
+ }
+}
+
+func TestParseNamedManifestByDigestReference(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ m := createManifestForTest(
+ "sha256:"+strings.Repeat("a", 64),
+ "sha256:"+strings.Repeat("b", 64),
+ RunnerLlamaCPP,
+ )
+ data, err := json.Marshal(m)
+ if err != nil {
+ t.Fatal(err)
+ }
+ digest := writeManifestBlobForTest(t, data)
+ digestRef := strings.Replace(digest, ":", "-", 1)
+
+ got, err := ParseNamedManifest(model.ParseName(digestRef))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.BlobDigest() != digest {
+ t.Fatalf("BlobDigest() = %q, want %q", got.BlobDigest(), digest)
+ }
+ if got.Runner != RunnerLlamaCPP {
+ t.Fatalf("Runner = %q, want %q", got.Runner, RunnerLlamaCPP)
+ }
+}
+
+func TestParseManifestListByDigestReference(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ child := createManifestForTest(
+ "sha256:"+strings.Repeat("a", 64),
+ "sha256:"+strings.Repeat("b", 64),
+ RunnerGGML,
+ )
+ childData, err := json.Marshal(child)
+ if err != nil {
+ t.Fatal(err)
+ }
+ childDigest := writeManifestBlobForTest(t, childData)
+ childRef, err := NewManifestReference(childDigest, RunnerGGML, FormatGGUF)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ parentData := createManifestListData(t, childRef)
+ parentDigest := writeManifestBlobForTest(t, parentData)
+ parentRef := strings.Replace(parentDigest, ":", "-", 1)
+
+ raw, err := ReadManifestData(model.ParseName(parentRef))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(raw, parentData) {
+ t.Fatal("ReadManifestData() returned different parent manifest bytes")
+ }
+
+ got, err := ParseNamedManifestForRunner(model.ParseName(parentRef), RunnerGGML)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.BlobDigest() != parentDigest {
+ t.Fatalf("BlobDigest() = %q, want parent %q", got.BlobDigest(), parentDigest)
+ }
+ if got.SelectedDigest() != strings.TrimPrefix(childDigest, "sha256:") {
+ t.Fatalf("SelectedDigest() = %q, want child %q", got.SelectedDigest(), strings.TrimPrefix(childDigest, "sha256:"))
+ }
+ if got.Runner != RunnerGGML {
+ t.Fatalf("Runner = %q, want %q", got.Runner, RunnerGGML)
+ }
+}
+
+func TestRemoveNamedByDigestReference(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ name := model.ParseName("example")
+ if err := WriteManifest(
+ name,
+ Layer{
+ MediaType: "application/vnd.docker.container.image.v1+json",
+ Digest: "sha256:" + strings.Repeat("a", 64),
+ Size: 12,
+ },
+ nil,
+ ); err != nil {
+ t.Fatal(err)
+ }
+
+ m, err := ParseNamedManifest(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ digestRef := strings.Replace(m.BlobDigest(), ":", "-", 1)
+
+ if _, err := RemoveNamed(model.ParseName(digestRef)); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := ResolvePathForName(name); !os.IsNotExist(err) {
+ t.Fatalf("ResolvePathForName() error = %v, want not exist", err)
+ }
+ blobPath, err := BlobsPath(m.BlobDigest())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(blobPath); !os.IsNotExist(err) {
+ t.Fatalf("manifest blob still exists, stat error = %v", err)
+ }
+}
+
+func TestSelectManifestUsesRunnerPreference(t *testing.T) {
+ ml := Manifest{
+ SchemaVersion: 2,
+ MediaType: MediaTypeManifestList,
+ Manifests: []Manifest{
+ createManifestForTest("sha256:"+strings.Repeat("a", 64), "sha256:"+strings.Repeat("b", 64), RunnerGGML),
+ createManifestForTest("sha256:"+strings.Repeat("c", 64), "sha256:"+strings.Repeat("d", 64), RunnerLlamaCPP),
+ },
+ }
+
+ child, err := selectManifestWithPreferences(ml.Manifests, []string{RunnerLlamaCPP, RunnerGGML})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if child.Runner != RunnerLlamaCPP {
+ t.Fatalf("runner = %q, want %q", child.Runner, RunnerLlamaCPP)
+ }
+}
+
+func TestSelectManifestReferenceDoesNotResolveBlob(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ ref, err := NewManifestReference("sha256:"+strings.Repeat("a", 64), RunnerGGML, FormatGGUF)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ child, err := selectManifestReferenceWithPreferences([]Manifest{ref}, []string{RunnerGGML})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := child.BlobDigest(); got != "sha256:"+strings.Repeat("a", 64) {
+ t.Fatalf("blob digest = %q, want selected reference digest", got)
+ }
+
+ child, err = SelectManifestReferenceForRunner([]Manifest{ref}, RunnerGGML)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := child.BlobDigest(); got != "sha256:"+strings.Repeat("a", 64) {
+ t.Fatalf("blob digest = %q, want selected reference digest", got)
+ }
+}
+
+func TestSelectManifestRejectsOldOllamaRunner(t *testing.T) {
+ _, err := selectManifestWithPreferences([]Manifest{
+ createManifestForTest("sha256:"+strings.Repeat("a", 64), "sha256:"+strings.Repeat("b", 64), "ollama"),
+ }, []string{RunnerGGML})
+ if !errors.Is(err, ErrNoCompatibleManifest) {
+ t.Fatalf("err = %v, want %v", err, ErrNoCompatibleManifest)
+ }
+}
+
+func TestParseNamedManifestResolvesManifestList(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ name := model.ParseName("example")
+
+ ggml := createManifestForTest("sha256:"+strings.Repeat("a", 64), "sha256:"+strings.Repeat("b", 64), RunnerGGML)
+ ggmlData, err := json.Marshal(ggml)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ggmlDigest := writeManifestBlobForTest(t, ggmlData)
+
+ llamacpp := createManifestForTest("sha256:"+strings.Repeat("c", 64), "sha256:"+strings.Repeat("d", 64), RunnerLlamaCPP)
+ llamacppData, err := json.Marshal(llamacpp)
+ if err != nil {
+ t.Fatal(err)
+ }
+ llamacppDigest := writeManifestBlobForTest(t, llamacppData)
+
+ parentData := createManifestListData(t, llamacpp, ggml)
+
+ if err := WriteManifestData(name, parentData); err != nil {
+ t.Fatal(err)
+ }
+
+ m, err := ParseNamedManifest(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ parentSum := sha256.Sum256(parentData)
+ if got := m.Digest(); got != fmt.Sprintf("%x", parentSum) {
+ t.Fatalf("digest = %q, want %x", got, parentSum)
+ }
+ if got := m.BlobDigest(); got != fmt.Sprintf("sha256:%x", parentSum) {
+ t.Fatalf("blob digest = %q, want sha256:%x", got, parentSum)
+ }
+ if got := m.SelectedDigest(); got != strings.TrimPrefix(llamacppDigest, "sha256:") {
+ t.Fatalf("selected digest = %q, want %q", got, strings.TrimPrefix(llamacppDigest, "sha256:"))
+ }
+ if got := m.Runner; got != RunnerLlamaCPP {
+ t.Fatalf("runner = %q, want %q", got, RunnerLlamaCPP)
+ }
+ if got := m.Format; got != FormatGGUF {
+ t.Fatalf("format = %q, want %q", got, FormatGGUF)
+ }
+ if got := m.Config.Digest; got != "sha256:"+strings.Repeat("c", 64) {
+ t.Fatalf("config digest = %q, want selected child config", got)
+ }
+
+ m, err = ParseNamedManifestForRunner(name, RunnerLlamaCPP)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := m.Runner; got != RunnerLlamaCPP {
+ t.Fatalf("runner = %q, want %q", got, RunnerLlamaCPP)
+ }
+ if got := m.SelectedDigest(); got != strings.TrimPrefix(llamacppDigest, "sha256:") {
+ t.Fatalf("selected digest = %q, want %q", got, strings.TrimPrefix(llamacppDigest, "sha256:"))
+ }
+ if got := m.Config.Digest; got != "sha256:"+strings.Repeat("c", 64) {
+ t.Fatalf("config digest = %q, want selected child config", got)
+ }
+
+ referenced, err := ReferencedBlobDigestsForName(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, digest := range []string{llamacppDigest, ggmlDigest} {
+ if !slices.Contains(referenced, digest) {
+ t.Fatalf("referenced blob digests missing child manifest %s", digest)
+ }
+ }
+
+ raw, err := ReadManifestData(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(raw, parentData) {
+ t.Fatal("ReadManifestData did not return the parent manifest list")
+ }
+
+ selected, err := ReadSelectedManifestData(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(selected, llamacppData) {
+ t.Fatal("ReadSelectedManifestData did not return the selected child manifest")
+ }
+}
+
+func TestTotalSizeForNameIncludesAllManifestListChildren(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ name := model.ParseName("example")
+
+ sharedLayerData := []byte("shared layer")
+ ggufConfigData := []byte("gguf config")
+ ggufLayerData := []byte("gguf layer")
+ mlxConfigData := []byte("mlx config")
+ mlxLayerData := []byte("mlx layer")
+
+ sharedLayerDigest := writeManifestBlobForTest(t, sharedLayerData)
+ ggufConfigDigest := writeManifestBlobForTest(t, ggufConfigData)
+ ggufLayerDigest := writeManifestBlobForTest(t, ggufLayerData)
+ mlxConfigDigest := writeManifestBlobForTest(t, mlxConfigData)
+ mlxLayerDigest := writeManifestBlobForTest(t, mlxLayerData)
+
+ gguf := Manifest{
+ SchemaVersion: 2,
+ MediaType: MediaTypeManifest,
+ Runner: RunnerGGML,
+ Format: FormatGGUF,
+ Config: Layer{
+ MediaType: "application/vnd.docker.container.image.v1+json",
+ Digest: ggufConfigDigest,
+ Size: int64(len(ggufConfigData)),
+ },
+ Layers: []Layer{
+ {
+ MediaType: "application/vnd.ollama.image.model",
+ Digest: sharedLayerDigest,
+ Size: int64(len(sharedLayerData)),
+ },
+ {
+ MediaType: "application/vnd.ollama.image.model",
+ Digest: ggufLayerDigest,
+ Size: int64(len(ggufLayerData)),
+ },
+ },
+ }
+ ggufData, err := json.Marshal(gguf)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ggufManifestDigest := writeManifestBlobForTest(t, ggufData)
+ ggufRef, err := NewManifestReference(ggufManifestDigest, gguf.Runner, gguf.Format)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ mlx := Manifest{
+ SchemaVersion: 2,
+ MediaType: MediaTypeManifest,
+ Runner: RunnerMLX,
+ Format: FormatSafetensors,
+ Config: Layer{
+ MediaType: "application/vnd.docker.container.image.v1+json",
+ Digest: mlxConfigDigest,
+ Size: int64(len(mlxConfigData)),
+ },
+ Layers: []Layer{
+ {
+ MediaType: MediaTypeImageTensor,
+ Digest: sharedLayerDigest,
+ Size: int64(len(sharedLayerData)),
+ },
+ {
+ MediaType: MediaTypeImageTensor,
+ Digest: mlxLayerDigest,
+ Size: int64(len(mlxLayerData)),
+ },
+ },
+ }
+ mlxData, err := json.Marshal(mlx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ mlxManifestDigest := writeManifestBlobForTest(t, mlxData)
+ mlxRef, err := NewManifestReference(mlxManifestDigest, mlx.Runner, mlx.Format)
+ if err != nil {
+ t.Fatal(err)
+ }
- p := filepath.Join(path, "manifests", name)
- if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
+ if err := WriteManifestData(name, createManifestListData(t, ggufRef, mlxRef)); err != nil {
t.Fatal(err)
}
- f, err := os.Create(p)
+ size, err := TotalSizeForName(name)
if err != nil {
t.Fatal(err)
}
- defer f.Close()
- if err := json.NewEncoder(f).Encode(Manifest{}); err != nil {
+ want := int64(len(ggufConfigData) + len(sharedLayerData) + len(ggufLayerData) + len(mlxConfigData) + len(mlxLayerData))
+ if size != want {
+ t.Fatalf("size = %d, want %d", size, want)
+ }
+}
+
+func TestPartialManifestListTracksPresentAndMissingChildren(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ name := model.ParseName("example")
+
+ configData := []byte("gguf config")
+ layerData := []byte("gguf layer")
+ configDigest := writeManifestBlobForTest(t, configData)
+ layerDigest := writeManifestBlobForTest(t, layerData)
+
+ child := Manifest{
+ SchemaVersion: 2,
+ MediaType: MediaTypeManifest,
+ Runner: RunnerGGML,
+ Format: FormatGGUF,
+ Config: Layer{
+ MediaType: "application/vnd.docker.container.image.v1+json",
+ Digest: configDigest,
+ Size: int64(len(configData)),
+ },
+ Layers: []Layer{
+ {
+ MediaType: "application/vnd.ollama.image.model",
+ Digest: layerDigest,
+ Size: int64(len(layerData)),
+ },
+ },
+ }
+ childData, err := json.Marshal(child)
+ if err != nil {
+ t.Fatal(err)
+ }
+ childDigest := writeManifestBlobForTest(t, childData)
+ childRef, err := NewManifestReference(childDigest, child.Runner, child.Format)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ missingDigest := "sha256:" + strings.Repeat("e", 64)
+ missingRef, err := NewManifestReference(missingDigest, RunnerMLX, FormatSafetensors)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ parentData := createManifestListData(t, childRef, missingRef)
+ if err := WriteManifestData(name, parentData); err != nil {
+ t.Fatal(err)
+ }
+ parentSum := sha256.Sum256(parentData)
+ parentDigest := fmt.Sprintf("sha256:%x", parentSum)
+
+ referenced, err := ReferencedBlobDigestsForName(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, digest := range []string{parentDigest, childDigest, missingDigest, configDigest, layerDigest} {
+ if !slices.Contains(referenced, digest) {
+ t.Fatalf("referenced blob digests missing %s: %#v", digest, referenced)
+ }
+ }
+
+ size, err := TotalSizeForName(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := int64(len(configData) + len(layerData))
+ if size != want {
+ t.Fatalf("size = %d, want %d", size, want)
+ }
+}
+
+func TestParseNamedManifestLeavesLegacyManifestInPlace(t *testing.T) {
+ models := t.TempDir()
+ t.Setenv("OLLAMA_MODELS", models)
+
+ name := model.ParseName("example")
+ createManifest(t, models, name.Filepath())
+
+ manifestPath, err := PathForName(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if _, err := ParseNamedManifest(name); err != nil {
+ t.Fatal(err)
+ }
+
+ fi, err := os.Lstat(manifestPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if fi.Mode()&os.ModeSymlink != 0 {
+ t.Fatal("legacy manifest was converted to a symlink while reading")
+ }
+
+ data, err := os.ReadFile(manifestPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ sum := sha256.Sum256(data)
+ blobPath, err := BlobsPath(fmt.Sprintf("sha256:%x", sum))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(blobPath); !os.IsNotExist(err) {
+ t.Fatalf("legacy manifest read created blob: %v", err)
+ }
+}
+
+func TestMigrateManifestLinks(t *testing.T) {
+ models := t.TempDir()
+ t.Setenv("OLLAMA_MODELS", models)
+
+ name := model.ParseName("example")
+ createManifest(t, models, name.Filepath())
+
+ migrated, err := MigrateManifestLinks()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if migrated != 1 {
+ t.Fatalf("migrated = %d, want 1", migrated)
+ }
+
+ manifestPath, err := V2PathForName(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ manifestData, err := os.ReadFile(manifestPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ sum := sha256.Sum256(manifestData)
+ blobPath, err := BlobsPath(fmt.Sprintf("sha256:%x", sum))
+ if err != nil {
+ t.Fatal(err)
+ }
+ blobData, err := os.ReadFile(blobPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(blobData, manifestData) {
+ t.Fatal("migrated manifest path and blob content differ")
+ }
+
+ legacyPath, err := PathForName(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(legacyPath); !os.IsNotExist(err) {
+ t.Fatalf("legacy manifest still exists: %v", err)
+ }
+
+ migrated, err = MigrateManifestLinks()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if migrated != 0 {
+ t.Fatalf("migrated on second run = %d, want 0", migrated)
+ }
+
+ if _, err := MigrateManifestLinks(); err != nil {
+ t.Fatal(err)
+ }
+ manifestDataAfter, err := os.ReadFile(manifestPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(manifestDataAfter, manifestData) {
+ t.Fatal("second migration changed manifest content")
+ }
+}
+
+func TestRemoveNamedRemovesUnreferencedManifestBlob(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ name := model.ParseName("example")
+ if err := WriteManifest(name, Layer{}, nil); err != nil {
+ t.Fatal(err)
+ }
+
+ m, err := ParseNamedManifest(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ blobPath, err := BlobsPath(m.BlobDigest())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(blobPath); err != nil {
+ t.Fatal(err)
+ }
+
+ if _, err := RemoveNamed(name); err != nil {
+ t.Fatal(err)
+ }
+
+ if _, err := os.Stat(blobPath); !os.IsNotExist(err) {
+ t.Fatalf("manifest blob still exists: %v", err)
+ }
+}
+
+func TestRemoveNamedTracksManifestListChildBlobs(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ ggmlConfigDigest := writeManifestBlobForTest(t, []byte("ggml config"))
+ ggmlLayerDigest := writeManifestBlobForTest(t, []byte("ggml layer"))
+ ggml := createManifestForTest(ggmlConfigDigest, ggmlLayerDigest, RunnerGGML)
+ ggmlData, err := json.Marshal(ggml)
+ if err != nil {
+ t.Fatal(err)
+ }
+ writeManifestBlobForTest(t, ggmlData)
+
+ llamacppConfigDigest := writeManifestBlobForTest(t, []byte("llamacpp config"))
+ llamacppLayerDigest := writeManifestBlobForTest(t, []byte("llamacpp layer"))
+ llamacpp := createManifestForTest(llamacppConfigDigest, llamacppLayerDigest, RunnerLlamaCPP)
+ llamacppData, err := json.Marshal(llamacpp)
+ if err != nil {
+ t.Fatal(err)
+ }
+ writeManifestBlobForTest(t, llamacppData)
+
+ parentData := createManifestListData(t, ggml, llamacpp)
+
+ nameA := model.ParseName("example-a")
+ nameB := model.ParseName("example-b")
+ if err := WriteManifestData(nameA, parentData); err != nil {
+ t.Fatal(err)
+ }
+ if err := WriteManifestData(nameB, parentData); err != nil {
+ t.Fatal(err)
+ }
+
+ parentSum := sha256.Sum256(parentData)
+ parentPath, err := BlobsPath(fmt.Sprintf("sha256:%x", parentSum))
+ if err != nil {
+ t.Fatal(err)
+ }
+ referencedBlobs, err := ReferencedBlobDigestsForName(nameA)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if _, err := RemoveNamed(nameA); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(parentPath); err != nil {
+ t.Fatalf("parent list blob was removed while another model uses it: %v", err)
+ }
+ for _, digest := range referencedBlobs {
+ blob, err := BlobsPath(digest)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(blob); err != nil {
+ t.Fatalf("referenced blob %s was removed while another model uses it: %v", digest, err)
+ }
+ }
+
+ if _, err := RemoveNamed(nameB); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(parentPath); !os.IsNotExist(err) {
+ t.Fatalf("parent list blob still exists after final remove: %v", err)
+ }
+ for _, digest := range referencedBlobs {
+ blob, err := BlobsPath(digest)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(blob); !os.IsNotExist(err) {
+ t.Fatalf("referenced blob %s still exists after final remove: %v", digest, err)
+ }
+ }
+}
+
+func TestRemoveNamedDigestRemovesManifestListChild(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ ggmlConfigDigest := writeManifestBlobForTest(t, []byte("ggml config"))
+ ggmlLayerDigest := writeManifestBlobForTest(t, []byte("ggml layer"))
+ ggml := createManifestForTest(ggmlConfigDigest, ggmlLayerDigest, RunnerGGML)
+ ggmlData, err := json.Marshal(ggml)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ggmlDigest := writeManifestBlobForTest(t, ggmlData)
+
+ llamacppConfigDigest := writeManifestBlobForTest(t, []byte("llamacpp config"))
+ llamacppLayerDigest := writeManifestBlobForTest(t, []byte("llamacpp layer"))
+ llamacpp := createManifestForTest(llamacppConfigDigest, llamacppLayerDigest, RunnerLlamaCPP)
+ llamacppData, err := json.Marshal(llamacpp)
+ if err != nil {
+ t.Fatal(err)
+ }
+ llamacppDigest := writeManifestBlobForTest(t, llamacppData)
+
+ ggmlRef, err := NewManifestReference(ggmlDigest, RunnerGGML, FormatGGUF)
+ if err != nil {
+ t.Fatal(err)
+ }
+ llamacppRef, err := NewManifestReference(llamacppDigest, RunnerLlamaCPP, FormatGGUF)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ name := model.ParseName("example")
+ if err := WriteManifestData(name, createManifestListData(t, ggmlRef, llamacppRef)); err != nil {
+ t.Fatal(err)
+ }
+
+ digestName := model.ParseName(strings.Replace(llamacppDigest, ":", "-", 1))
+ if _, err := RemoveNamed(digestName); err != nil {
+ t.Fatal(err)
+ }
+
+ data, err := ReadManifestData(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var parent Manifest
+ if err := json.Unmarshal(data, &parent); err != nil {
+ t.Fatal(err)
+ }
+ if len(parent.Manifests) != 1 {
+ t.Fatalf("manifest child count = %d, want 1", len(parent.Manifests))
+ }
+ if parent.Manifests[0].Runner != RunnerGGML {
+ t.Fatalf("remaining runner = %q, want %q", parent.Manifests[0].Runner, RunnerGGML)
+ }
+
+ childPath, err := BlobsPath(llamacppDigest)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(childPath); !os.IsNotExist(err) {
+ t.Fatalf("removed child manifest blob still exists: %v", err)
+ }
+}
+
+func TestParseNamedManifestRejectsUnsafeSymlinks(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ name := model.ParseName("example")
+ manifestPath, err := PathForName(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.MkdirAll(filepath.Dir(manifestPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+
+ t.Run("non blob basename", func(t *testing.T) {
+ target := filepath.Join(t.TempDir(), "not-a-blob")
+ if err := os.WriteFile(target, []byte(`{"schemaVersion":2}`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Remove(manifestPath); err != nil && !os.IsNotExist(err) {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(target, manifestPath); err != nil {
+ t.Skipf("symlink unavailable: %v", err)
+ }
+
+ _, err := ParseNamedManifest(name)
+ if err == nil || !strings.Contains(err.Error(), "not a sha256 blob") {
+ t.Fatalf("err = %v, want not a sha256 blob", err)
+ }
+ })
+
+ t.Run("blob basename outside blob store", func(t *testing.T) {
+ data := []byte(`{"schemaVersion":2,"mediaType":"application/vnd.docker.distribution.manifest.v2+json"}`)
+ sum := sha256.Sum256(data)
+ target := filepath.Join(t.TempDir(), fmt.Sprintf("sha256-%x", sum))
+ if err := os.WriteFile(target, data, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Remove(manifestPath); err != nil && !os.IsNotExist(err) {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(target, manifestPath); err != nil {
+ t.Skipf("symlink unavailable: %v", err)
+ }
+
+ _, err := ParseNamedManifest(name)
+ if err == nil || !strings.Contains(err.Error(), "does not match blob") {
+ t.Fatalf("err = %v, want does not match blob", err)
+ }
+ })
+}
+
+func TestParseNamedManifestPrefersV2(t *testing.T) {
+ models := t.TempDir()
+ t.Setenv("OLLAMA_MODELS", models)
+
+ name := model.ParseName("example")
+
+ legacyPath, err := PathForName(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.MkdirAll(filepath.Dir(legacyPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(legacyPath, []byte(`{"schemaVersion":2,"mediaType":"legacy"}`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := WriteManifestData(name, []byte(`{"schemaVersion":2,"mediaType":"v2"}`)); err != nil {
+ t.Fatal(err)
+ }
+
+ m, err := ParseNamedManifest(name)
+ if err != nil {
t.Fatal(err)
}
+ if m.MediaType != "v2" {
+ t.Fatalf("media type = %q, want %q", m.MediaType, "v2")
+ }
+}
+
+func TestManifestsV2ShadowsLegacy(t *testing.T) {
+ models := t.TempDir()
+ t.Setenv("OLLAMA_MODELS", models)
+
+ name := model.ParseName("example")
+ createManifest(t, models, name.Filepath())
+ if err := WriteManifestData(name, []byte(`{"schemaVersion":2,"mediaType":"v2"}`)); err != nil {
+ t.Fatal(err)
+ }
+
+ ms, err := Manifests(true)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if len(ms) != 1 {
+ t.Fatalf("manifest count = %d, want 1", len(ms))
+ }
+
+ var m *Manifest
+ for gotName, gotManifest := range ms {
+ if gotName.EqualFold(model.ParseName("example")) {
+ m = gotManifest
+ break
+ }
+ }
+ if m == nil {
+ t.Fatalf("missing v2 manifest for %s", name)
+ }
+ if m.MediaType != "v2" {
+ t.Fatalf("media type = %q, want %q", m.MediaType, "v2")
+ }
}
func TestManifests(t *testing.T) {
@@ -148,3 +1257,40 @@ func TestManifests(t *testing.T) {
})
}
}
+
+func TestTensorLayers(t *testing.T) {
+ m := &Manifest{Layers: []Layer{
+ {MediaType: MediaTypeImageTensor, Size: 1000},
+ {MediaType: MediaTypeImageJSON, Size: 500},
+ {MediaType: MediaTypeImageTensor, Size: 2000},
+ }}
+
+ got := m.TensorLayers()
+ if len(got) != 2 || got[0].Size != 1000 || got[1].Size != 2000 {
+ t.Fatalf("TensorLayers() = %+v, want the two tensor layers", got)
+ }
+}
+
+func TestReadConfig(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ layer, err := NewLayer(strings.NewReader(`{"model_type":"test"}`), MediaTypeImageJSON)
+ if err != nil {
+ t.Fatal(err)
+ }
+ layer.Name = "config.json"
+ m := &Manifest{Layers: []Layer{layer}}
+
+ var cfg struct {
+ ModelType string `json:"model_type"`
+ }
+ if err := m.ReadConfigJSON("config.json", &cfg); err != nil {
+ t.Fatal(err)
+ }
+ if cfg.ModelType != "test" {
+ t.Fatalf("model_type = %q, want %q", cfg.ModelType, "test")
+ }
+ if _, err := m.ReadConfig("missing.json"); err == nil {
+ t.Fatal("ReadConfig(missing.json) returned nil error")
+ }
+}
diff --git a/manifest/paths.go b/manifest/paths.go
index df452794e..79af2e7f4 100644
--- a/manifest/paths.go
+++ b/manifest/paths.go
@@ -6,13 +6,27 @@ import (
"os"
"path/filepath"
"regexp"
+ "runtime"
"strings"
"github.com/ollama/ollama/envconfig"
"github.com/ollama/ollama/types/model"
)
-var ErrInvalidDigestFormat = errors.New("invalid digest format")
+var (
+ ErrAmbiguousDigestPrefix = errors.New("ambiguous digest prefix")
+ ErrInvalidDigestFormat = errors.New("invalid digest format")
+ digestPrefixPattern = regexp.MustCompile(`^[0-9a-fA-F]{12,64}$`)
+)
+
+const (
+ legacyDirName = "manifests"
+ v2DirName = "manifests-v2"
+ defaultPublicHost = "registry.ollama.ai"
+ v2CanonicalHost = "ollama.com"
+ defaultNamespace = "library"
+ defaultTag = "latest"
+)
// a manifest spells a digest with ":", a filename with "-"
var digestPattern = regexp.MustCompile(`^sha256[:-][0-9a-fA-F]{64}$`)
@@ -27,7 +41,15 @@ func ValidateDigest(digest string) error {
}
func Path() (string, error) {
- path := filepath.Join(envconfig.Models(), "manifests")
+ return manifestPath(legacyDirName)
+}
+
+func V2Path() (string, error) {
+ return manifestPath(v2DirName)
+}
+
+func manifestPath(dir string) (string, error) {
+ path := filepath.Join(envconfig.Models(), dir)
if err := os.MkdirAll(path, 0o755); err != nil {
return "", fmt.Errorf("%w: ensure path elements are traversable", err)
}
@@ -37,6 +59,10 @@ func Path() (string, error) {
// PathForName returns the path to the manifest file for a specific model name.
func PathForName(n model.Name) (string, error) {
+ return LegacyPathForName(n)
+}
+
+func LegacyPathForName(n model.Name) (string, error) {
if !n.IsValid() {
return "", os.ErrNotExist
}
@@ -49,6 +75,325 @@ func PathForName(n model.Name) (string, error) {
return filepath.Join(manifests, n.Filepath()), nil
}
+func V2PathForName(n model.Name) (string, error) {
+ if !n.IsValid() {
+ return "", os.ErrNotExist
+ }
+
+ manifests, err := V2Path()
+ if err != nil {
+ return "", err
+ }
+
+ return filepath.Join(manifests, v2NameFilepath(canonicalV2Name(n))), nil
+}
+
+func ResolvePathForName(n model.Name) (string, error) {
+ path, _, err := resolveManifestPath(n)
+ return path, err
+}
+
+func resolveManifestPath(n model.Name) (string, string, error) {
+ if !n.IsValid() {
+ return "", "", os.ErrNotExist
+ }
+
+ if digest, ok, err := ResolveDigestReferenceName(n); err != nil {
+ return "", "", err
+ } else if ok {
+ blobPath, err := BlobsPath(digest)
+ if err != nil {
+ return "", "", err
+ }
+ if _, err := os.Lstat(blobPath); err == nil {
+ root, err := BlobsPath("")
+ return blobPath, root, err
+ } else if !os.IsNotExist(err) {
+ return "", "", err
+ }
+
+ return "", "", os.ErrNotExist
+ }
+
+ v2Path, err := V2PathForName(n)
+ if err != nil {
+ return "", "", err
+ }
+ // Stat, not Lstat: a v2 entry is a symlink, and a dangling one (for
+ // example after a pre-v2 daemon garbage-collected its manifest blob)
+ // must fall through to the legacy manifest instead of being selected.
+ if _, err := os.Stat(v2Path); err == nil {
+ root, err := V2Path()
+ return v2Path, root, err
+ } else if !os.IsNotExist(err) {
+ return "", "", err
+ }
+
+ legacyRoot, err := Path()
+ if err != nil {
+ return "", "", err
+ }
+ for _, legacyName := range legacyNameCandidates(n) {
+ if !legacyManifestPathSupported(legacyName) {
+ continue
+ }
+ legacyPath := filepath.Join(legacyRoot, legacyName.Filepath())
+ if _, err := os.Lstat(legacyPath); err == nil {
+ return legacyPath, legacyRoot, nil
+ } else if !os.IsNotExist(err) {
+ return "", "", err
+ }
+ }
+
+ return "", "", os.ErrNotExist
+}
+
+func removeNamedManifestPaths(n model.Name) error {
+ candidates := legacyNameCandidates(n)
+ paths := make([]string, 0, 1+len(candidates))
+
+ v2Path, err := V2PathForName(n)
+ if err != nil {
+ return err
+ }
+ paths = append(paths, v2Path)
+
+ for _, legacyName := range candidates {
+ if !legacyManifestPathSupported(legacyName) {
+ continue
+ }
+ legacyPath, err := LegacyPathForName(legacyName)
+ if err != nil {
+ return err
+ }
+ paths = append(paths, legacyPath)
+ }
+
+ for _, path := range paths {
+ if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ }
+
+ return pruneManifestRoots()
+}
+
+func removeLegacyManifestPaths(n model.Name) error {
+ for _, legacyName := range legacyNameCandidates(n) {
+ if !legacyManifestPathSupported(legacyName) {
+ continue
+ }
+ legacyPath, err := LegacyPathForName(legacyName)
+ if err != nil {
+ return err
+ }
+ if err := os.Remove(legacyPath); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ }
+
+ legacyRoot, err := Path()
+ if err != nil {
+ return err
+ }
+
+ if err := PruneDirectory(legacyRoot); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+
+ return nil
+}
+
+func pruneManifestRoots() error {
+ roots := []func() (string, error){Path, V2Path}
+ for _, rootFn := range roots {
+ root, err := rootFn()
+ if err != nil {
+ return err
+ }
+ if err := PruneDirectory(root); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ }
+
+ return nil
+}
+
+// normalizeLogicalName maps any public host to the legacy default
+// so that map keys use a single identity regardless of on-disk host.
+func normalizeLogicalName(n model.Name) model.Name {
+ if isDefaultPublicHost(n.Host) {
+ n.Host = defaultPublicHost
+ }
+
+ return n
+}
+
+// canonicalV2Name maps any public host to the v2 canonical host
+// for use in manifests-v2/ on-disk paths.
+func canonicalV2Name(n model.Name) model.Name {
+ if isDefaultPublicHost(n.Host) {
+ n.Host = v2CanonicalHost
+ }
+
+ return n
+}
+
+func v2NameFilepath(n model.Name) string {
+ if !n.IsFullyQualified() {
+ panic("illegal attempt to get filepath of invalid name")
+ }
+ return filepath.Join(
+ encodeV2ManifestHost(n.Host),
+ n.Namespace,
+ n.Model,
+ n.Tag,
+ )
+}
+
+func parseStoredManifestFilepath(s string) model.Name {
+ parts := strings.Split(s, string(filepath.Separator))
+ if len(parts) != 4 {
+ return model.Name{}
+ }
+
+ n := model.Name{
+ Host: decodeV2ManifestHost(parts[0]),
+ Namespace: parts[1],
+ Model: parts[2],
+ Tag: parts[3],
+ }
+ if !n.IsFullyQualified() {
+ return model.Name{}
+ }
+ return n
+}
+
+func encodeV2ManifestHost(host string) string {
+ return strings.ReplaceAll(host, ":", "%3A")
+}
+
+func decodeV2ManifestHost(host string) string {
+ return strings.NewReplacer("%3A", ":", "%3a", ":").Replace(host)
+}
+
+func legacyNameCandidates(n model.Name) []model.Name {
+ names := []model.Name{n}
+ if !isDefaultPublicHost(n.Host) {
+ return names
+ }
+
+ alt := n
+ switch {
+ case strings.EqualFold(n.Host, defaultPublicHost):
+ alt.Host = v2CanonicalHost
+ default:
+ alt.Host = defaultPublicHost
+ }
+
+ return append(names, alt)
+}
+
+func legacyManifestPathSupported(n model.Name) bool {
+ // Windows cannot represent host:port registry names in the legacy manifest tree.
+ return runtime.GOOS != "windows" || !strings.Contains(n.Host, ":")
+}
+
+func isDefaultPublicHost(host string) bool {
+ return strings.EqualFold(host, defaultPublicHost) || strings.EqualFold(host, v2CanonicalHost)
+}
+
+// DigestReference parses a bare local manifest blob reference in sha256-<hex>
+// filename form. It deliberately rejects paths and registry digest syntax; this
+// form identifies blobs already present in the local Ollama model store.
+func DigestReference(ref string) (string, bool) {
+ ref = strings.TrimSpace(ref)
+ if !blobFilenamePattern.MatchString(ref) {
+ return "", false
+ }
+
+ return "sha256:" + strings.ToLower(strings.TrimPrefix(ref, "sha256-")), true
+}
+
+// ResolveDigestReference resolves a local manifest blob reference in sha256-hex,
+// sha256:hex, or bare hex prefix form.
+func ResolveDigestReference(ref string) (string, bool, error) {
+ ref = strings.TrimSpace(ref)
+ ref = strings.ToLower(strings.Replace(ref, "-", ":", 1))
+ ref = strings.TrimPrefix(ref, "sha256:")
+ if !digestPrefixPattern.MatchString(ref) {
+ return "", false, nil
+ }
+ if len(ref) == 64 {
+ return "sha256:" + ref, true, nil
+ }
+
+ digest, err := resolveBlobDigestPrefix(ref)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return "", false, nil
+ }
+ return "", true, err
+ }
+ return digest, true, nil
+}
+
+// DigestReferenceName returns the local blob digest for names that are the
+// default model-name expansion of a digest reference.
+func DigestReferenceName(n model.Name) (string, bool) {
+ digest, ok, err := ResolveDigestReferenceName(n)
+ if err != nil {
+ return "", false
+ }
+ return digest, ok
+}
+
+func ResolveDigestReferenceName(n model.Name) (string, bool, error) {
+ if !n.IsFullyQualified() {
+ return "", false, nil
+ }
+ if !isDefaultPublicHost(n.Host) || !strings.EqualFold(n.Namespace, defaultNamespace) || !strings.EqualFold(n.Tag, defaultTag) {
+ return "", false, nil
+ }
+
+ return ResolveDigestReference(n.Model)
+}
+
+// IsDigestReferenceName reports whether n names a local manifest blob instead
+// of a model tag.
+func IsDigestReferenceName(n model.Name) bool {
+ _, ok := DigestReferenceName(n)
+ return ok
+}
+
+func resolveBlobDigestPrefix(prefix string) (string, error) {
+ root, err := BlobsPath("")
+ if err != nil {
+ return "", err
+ }
+ matches, err := filepath.Glob(filepath.Join(root, "sha256-"+prefix+"*"))
+ if err != nil {
+ return "", err
+ }
+
+ var digest string
+ for _, match := range matches {
+ base := filepath.Base(match)
+ if !blobFilenamePattern.MatchString(base) {
+ continue
+ }
+ if digest != "" {
+ return "", fmt.Errorf("%w %q", ErrAmbiguousDigestPrefix, prefix)
+ }
+ digest = "sha256:" + strings.TrimPrefix(base, "sha256-")
+ }
+ if digest == "" {
+ return "", os.ErrNotExist
+ }
+
+ return digest, nil
+}
+
func BlobsPath(digest string) (string, error) {
// the empty digest names the blobs directory
if digest != "" {
diff --git a/server/create.go b/server/create.go
index cb56aa196..8f7d30b13 100644
--- a/server/create.go
+++ b/server/create.go
@@ -19,11 +19,13 @@ import (
"path/filepath"
"runtime/debug"
"slices"
+ "strconv"
"strings"
"github.com/gin-gonic/gin"
"github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/compatmigrate"
"github.com/ollama/ollama/create"
"github.com/ollama/ollama/envconfig"
"github.com/ollama/ollama/format"
@@ -55,6 +57,18 @@ const (
maxCreateFiles = 1024
)
+type manifestListRequestError struct {
+ err error
+}
+
+func (e manifestListRequestError) Error() string {
+ return e.err.Error()
+}
+
+func newManifestListRequestError(format string, args ...any) error {
+ return manifestListRequestError{err: fmt.Errorf(format, args...)}
+}
+
func (s *Server) CreateHandler(c *gin.Context) {
config := new(model.ConfigV2)
@@ -143,16 +157,44 @@ func (s *Server) CreateHandler(c *gin.Context) {
send(resp)
}
- oldManifest, _ := manifest.ParseNamedManifest(name)
+ oldManifestDigests, _ := manifest.ReferencedBlobDigestsForName(name)
+
+ if len(r.List) > 0 {
+ if err := createManifestList(r, name, fn); err != nil {
+ status := http.StatusInternalServerError
+ var requestErr manifestListRequestError
+ if errors.As(err, &requestErr) {
+ status = http.StatusBadRequest
+ }
+ send(gin.H{"error": err.Error(), "status": status})
+ return
+ }
+
+ if !envconfig.NoPrune() && len(oldManifestDigests) > 0 {
+ removed, err := manifest.RemoveUnreferencedBlobs(oldManifestDigests...)
+ removeGGUFMetadata(removed...)
+ if err != nil {
+ send(gin.H{"error": err.Error()})
+ return
+ }
+ }
+
+ send(api.ProgressResponse{Status: "success"})
+ return
+ }
if fileType == "safetensors" {
if err := createSafetensorsModel(reqCtx, r, name, fn); err != nil {
send(createSafetensorsErrorResponse(err))
return
}
- if err := pruneOldManifestLayers(oldManifest); err != nil {
- send(gin.H{"error": err.Error()})
- return
+ if !envconfig.NoPrune() && len(oldManifestDigests) > 0 {
+ removed, err := manifest.RemoveUnreferencedBlobs(oldManifestDigests...)
+ removeGGUFMetadata(removed...)
+ if err != nil {
+ send(gin.H{"error": err.Error()})
+ return
+ }
}
send(api.ProgressResponse{Status: "success"})
return
@@ -266,9 +308,13 @@ func (s *Server) CreateHandler(c *gin.Context) {
return
}
- if err := pruneOldManifestLayers(oldManifest); err != nil {
- send(gin.H{"error": err.Error()})
- return
+ if !envconfig.NoPrune() && len(oldManifestDigests) > 0 {
+ removed, err := manifest.RemoveUnreferencedBlobs(oldManifestDigests...)
+ removeGGUFMetadata(removed...)
+ if err != nil {
+ send(gin.H{"error": err.Error()})
+ return
+ }
}
send(api.ProgressResponse{Status: "success"})
}()
@@ -281,15 +327,6 @@ func (s *Server) CreateHandler(c *gin.Context) {
streamResponse(c, ch)
}
-func pruneOldManifestLayers(oldManifest *manifest.Manifest) error {
- if envconfig.NoPrune() || oldManifest == nil {
- return nil
- }
- removed, err := oldManifest.RemoveLayers()
- removeGGUFMetadata(removed...)
- return err
-}
-
func recoverCreatePanic(send func(any) bool) {
if r := recover(); r != nil {
slog.Error("panic in create background goroutine", "panic", r, "stack", string(debug.Stack()))
@@ -799,6 +836,17 @@ func createModel(ctx context.Context, r api.CreateRequest, name model.Name, base
}
if layer.GGUF != nil {
+ switch layer.MediaType {
+ case "application/vnd.ollama.image.model", manifest.MediaTypeImageDraft:
+ rewritten, changed, err := compatmigrate.RewriteLlama3MetadataLayer(layer.Layer)
+ if err != nil {
+ return err
+ }
+ if changed {
+ layer.Layer = rewritten
+ }
+ }
+
switch layer.MediaType {
case "application/vnd.ollama.image.model":
config.ModelFormat = cmp.Or(config.ModelFormat, "gguf")
@@ -868,16 +916,163 @@ func createModel(ctx context.Context, r api.CreateRequest, name model.Name, base
}
fn(api.ProgressResponse{Status: "writing manifest"})
+ runner, format := manifest.MetadataForConfig(*config)
+ if format == manifest.FormatGGUF {
+ // On failure the conservative ggml default stands: it flags the model
+ // for inspection rather than failing the create.
+ if detected, err := compatmigrate.RunnerForManifest(name, &manifest.Manifest{Config: *configLayer, Layers: layers}); err != nil {
+ slog.Warn("couldn't detect runner for created model", "model", name.DisplayShortest(), "error", err)
+ } else {
+ runner = detected
+ }
+ }
if err := ctx.Err(); err != nil {
return err
}
- if err := manifest.WriteManifest(name, *configLayer, layers); err != nil {
+ if err := manifest.WriteManifestWithMetadata(name, *configLayer, layers, runner, format); err != nil {
return err
}
return nil
}
+func createManifestList(r api.CreateRequest, name model.Name, fn func(resp api.ProgressResponse)) error {
+ if err := validateCreateManifestListRequest(r); err != nil {
+ return err
+ }
+
+ manifests := make([]manifest.Manifest, 0, len(r.List))
+ signatures := make([]manifestListChildSignature, 0, len(r.List))
+ seenDigests := make(map[string]string)
+ seenRunners := make(map[string]string)
+ var anchorChild *manifest.Manifest
+ for _, ref := range r.List {
+ ref = strings.TrimSpace(ref)
+ if ref == "" {
+ return newManifestListRequestError("manifest list contains an empty model")
+ }
+
+ fn(api.ProgressResponse{Status: fmt.Sprintf("reading manifest %s", ref)})
+
+ modelRef, err := parseAndValidateModelRef(ref)
+ if err != nil {
+ return err
+ }
+ if modelRef.Source == modelSourceCloud {
+ return newManifestListRequestError("manifest list entries must be local models: %s", ref)
+ }
+
+ childName, err := getExistingName(modelRef.Name)
+ if err != nil {
+ return err
+ }
+
+ data, err := manifest.ReadManifestData(childName)
+ if err != nil {
+ return fmt.Errorf("read manifest %s: %w", ref, err)
+ }
+
+ var child manifest.Manifest
+ if err := json.Unmarshal(data, &child); err != nil {
+ return err
+ }
+ if child.MediaType == manifest.MediaTypeManifestList {
+ return newManifestListRequestError("manifest list entry %s is already a manifest list", ref)
+ }
+
+ if err := manifest.FillMetadata(&child); err != nil {
+ return fmt.Errorf("manifest list entry %s: %w", ref, err)
+ }
+ if child.Format == manifest.FormatGGUF {
+ // On failure the conservative ggml default stands: it flags the
+ // model for inspection rather than failing the create.
+ if runner, err := compatmigrate.RunnerForManifest(childName, &child); err != nil {
+ slog.Warn("couldn't detect runner for manifest list entry", "entry", ref, "error", err)
+ } else {
+ child.Runner = runner
+ }
+ }
+
+ signature, err := newManifestListChildSignature(ref, childName, &child)
+ if err != nil {
+ return err
+ }
+ signatures = append(signatures, signature)
+
+ childData, err := json.Marshal(child)
+ if err != nil {
+ return err
+ }
+ childDigest, err := manifest.WriteManifestBlob(childData)
+ if err != nil {
+ return err
+ }
+
+ if previous, ok := seenDigests[childDigest]; ok {
+ return newManifestListRequestError("manifest list entries %s and %s resolve to the same manifest", previous, ref)
+ }
+ runner := strings.ToLower(strings.TrimSpace(child.Runner))
+ if previous, ok := seenRunners[runner]; ok {
+ return newManifestListRequestError("manifest list entries %s and %s use the same runner %q", previous, ref, child.Runner)
+ }
+ seenDigests[childDigest] = ref
+ seenRunners[runner] = ref
+
+ childRef, err := manifest.NewManifestReference(childDigest, child.Runner, child.Format)
+ if err != nil {
+ return err
+ }
+
+ // The downgrade anchor describes the child a pre-manifest-list daemon
+ // would load itself: the GGML child when one is listed, else the first.
+ if anchorChild == nil || (anchorChild.Runner != manifest.RunnerGGML && child.Runner == manifest.RunnerGGML) {
+ childCopy := child
+ anchorChild = &childCopy
+ }
+
+ manifests = append(manifests, childRef)
+ }
+
+ warnManifestListDrift(signatures, fn)
+
+ fn(api.ProgressResponse{Status: "writing manifest list"})
+ parentDigest, err := manifest.WriteManifestList(name, manifests)
+ if err != nil {
+ return err
+ }
+
+ // Extra layers reference the manifest blobs so a downgrade's garbage
+ // collector cannot delete them.
+ manifestDigests := []string{parentDigest}
+ for _, childRef := range manifests {
+ digest, err := manifest.ChildManifestDigest(childRef)
+ if err != nil {
+ return err
+ }
+ manifestDigests = append(manifestDigests, digest)
+ }
+ return manifest.WriteLegacyAnchor(name, anchorChild, manifestDigests...)
+}
+
+func validateCreateManifestListRequest(r api.CreateRequest) error {
+ if len(r.List) == 0 {
+ return newManifestListRequestError("manifest list must contain at least one model")
+ }
+
+ switch {
+ case r.From != "", r.RemoteHost != "", len(r.Files) > 0, len(r.DraftFiles) > 0:
+ return newManifestListRequestError("manifest list creation cannot be combined with model creation options")
+ case r.Template != "", r.System != "", r.License != nil, len(r.Parameters) > 0, len(r.Messages) > 0:
+ return newManifestListRequestError("manifest list creation cannot be combined with model creation options")
+ case r.Renderer != "", r.Parser != "", r.Requires != "", len(r.Info) > 0:
+ return newManifestListRequestError("manifest list creation cannot be combined with model creation options")
+ case r.Quantize != "", r.Quantization != "", r.DraftQuantize != "":
+ return newManifestListRequestError("manifest list creation cannot be combined with model creation options")
+ default:
+ return nil
+ }
+}
+
func ggufLayersWithMediaType(digest, sourceName, mediaType string, fn func(resp api.ProgressResponse)) ([]*modelLayer, error) {
var layers []*modelLayer
@@ -938,9 +1133,151 @@ func createConfigLayer(config model.ConfigV2) (*manifest.Layer, error) {
if err := json.NewEncoder(&b).Encode(config); err != nil {
return nil, err
}
- layer, err := manifest.NewLayer(&b, "application/vnd.docker.container.image.v1+json")
+ layer, err := manifest.NewLayer(&b, manifest.MediaTypeImageConfig)
if err != nil {
return nil, err
}
return &layer, nil
}
+
+// manifestListChildSignature holds the fields compared across manifest list
+// entries so accidental drift across runner variants is visible at creation
+// time. Runner and format are expected to differ; these fields describe the
+// model itself.
+type manifestListChildSignature struct {
+ ref string
+ config model.ConfigV2
+ caps []model.Capability
+ capsKnown bool
+}
+
+func newManifestListChildSignature(ref string, name model.Name, child *manifest.Manifest) (manifestListChildSignature, error) {
+ config, err := readModelListConfig(child)
+ if err != nil {
+ return manifestListChildSignature{}, fmt.Errorf("read config for manifest list entry %s: %w", ref, err)
+ }
+
+ caps, capsKnown := manifestListChildCapabilities(name)
+ return manifestListChildSignature{ref: ref, config: config, caps: caps, capsKnown: capsKnown}, nil
+}
+
+// manifestListChildCapabilities renders the same capability list show and
+// /api/tags report, so drift warnings match what users see. A child that
+// cannot be loaded leaves capabilities unknown rather than failing the
+// combine.
+func manifestListChildCapabilities(name model.Name) ([]model.Capability, bool) {
+ m, err := GetModel(name.String())
+ if err != nil {
+ slog.Warn("could not load model to check capabilities", "model", name.String(), "error", err)
+ return nil, false
+ }
+ return m.Capabilities(), true
+}
+
+// warnManifestListDrift warns when manifest list entries disagree on fields
+// that describe the same model. Unset fields never count as drift: legacy
+// manifests often carry them only in their model files. Differences are
+// warnings, not errors, because runner pairs legitimately vary in what they
+// support.
+func warnManifestListDrift(signatures []manifestListChildSignature, fn func(resp api.ProgressResponse)) {
+ if len(signatures) < 2 {
+ return
+ }
+
+ base := signatures[0]
+ for _, child := range signatures[1:] {
+ warnDrift(fn, "model family", base, child,
+ base.config.ModelFamily, child.config.ModelFamily)
+ warnDrift(fn, "model families", base, child,
+ joinNonEmpty(base.config.ModelFamilies), joinNonEmpty(child.config.ModelFamilies))
+ warnDrift(fn, "parameter size", base, child,
+ base.config.ModelType, child.config.ModelType)
+ warnDrift(fn, "context length", base, child,
+ nonZeroInt(base.config.ContextLen), nonZeroInt(child.config.ContextLen))
+ warnDrift(fn, "embedding length", base, child,
+ nonZeroInt(base.config.EmbedLen), nonZeroInt(child.config.EmbedLen))
+ warnDrift(fn, "parser", base, child,
+ base.config.Parser, child.config.Parser)
+ warnDrift(fn, "renderer", base, child,
+ base.config.Renderer, child.config.Renderer)
+ warnDriftDtype(fn, base, child)
+ warnDriftCapabilities(fn, base, child)
+ }
+}
+
+func joinNonEmpty(values []string) string {
+ if len(values) == 0 {
+ return ""
+ }
+ return strings.Join(values, ",")
+}
+
+func nonZeroInt(n int) string {
+ if n == 0 {
+ return ""
+ }
+ return strconv.Itoa(n)
+}
+
+func warnDrift(fn func(resp api.ProgressResponse), field string, base, child manifestListChildSignature, baseValue, childValue string) {
+ if baseValue == "" || childValue == "" || baseValue == childValue {
+ return
+ }
+ warning := fmt.Sprintf("warning: manifest list entries differ in %s: %s=%s, %s=%s", field, base.ref, baseValue, child.ref, childValue)
+ fn(api.ProgressResponse{Status: warning})
+ slog.Warn("manifest list entries differ", "field", field,
+ base.ref, baseValue, child.ref, childValue)
+}
+
+func warnDriftDtype(fn func(resp api.ProgressResponse), base, child manifestListChildSignature) {
+ baseClass, childClass := dtypeClass(base.config.FileType), dtypeClass(child.config.FileType)
+ if baseClass == "" || childClass == "" || baseClass == childClass {
+ return
+ }
+ warnDrift(fn, "quantization class", base, child,
+ fmt.Sprintf("%s (%s)", base.config.FileType, baseClass),
+ fmt.Sprintf("%s (%s)", child.config.FileType, childClass))
+}
+
+func warnDriftCapabilities(fn func(resp api.ProgressResponse), base, child manifestListChildSignature) {
+ if !base.capsKnown || !child.capsKnown {
+ return
+ }
+ baseCaps, childCaps := capabilitiesValue(base.caps), capabilitiesValue(child.caps)
+ if baseCaps == childCaps {
+ return
+ }
+ warnDrift(fn, "capabilities", base, child, baseCaps, childCaps)
+}
+
+func capabilitiesValue(caps []model.Capability) string {
+ names := make([]string, len(caps))
+ for i, c := range caps {
+ names[i] = c.String()
+ }
+ slices.Sort(names)
+ return "[" + strings.Join(names, " ") + "]"
+}
+
+// dtypeClass maps a model file type to a coarse precision class so
+// runner-native spellings of the same precision compare equal: Q4_K_M and
+// nvfp4 are both 4-bit, and bf16 and F16 are both unquantized.
+func dtypeClass(fileType string) string {
+ switch strings.ToLower(fileType) {
+ case "":
+ return ""
+ case "q4_0", "q4_1", "q4_k_m", "q4_k_s", "iq4_xs", "iq4_nl",
+ "4bit", "mxfp4", "nvfp4":
+ return "4-bit"
+ case "q5_0", "q5_1", "q5_k_m", "q5_k_s", "5bit":
+ return "5-bit"
+ case "q6_k", "6bit":
+ return "6-bit"
+ case "q8_0", "q8_1", "iq8", "8bit", "mxfp8":
+ return "8-bit"
+ case "f16", "bf16", "f32", "fp16", "unquantized":
+ return "unquantized"
+ default:
+ return strings.ToLower(fileType)
+ }
+}
diff --git a/server/gguf_metadata.go b/server/gguf_metadata.go
index 96bc33c33..aec8836f2 100644
--- a/server/gguf_metadata.go
+++ b/server/gguf_metadata.go
@@ -350,3 +350,39 @@ func oversized(v any) bool {
}
return false
}
+
+// jsonSafeValues returns the metadata values json.Marshal can represent.
+// Real GGUF files carry non-finite floats (e.g. gemma3n pads
+// activation_sparsity_scale with -Inf), which would otherwise fail the whole
+// show response.
+func jsonSafeValues(m *fsgguf.Metadata) map[string]any {
+ values := m.Values()
+ for key, value := range values {
+ if !jsonRepresentable(value) {
+ delete(values, key)
+ }
+ }
+ return values
+}
+
+func jsonRepresentable(v any) bool {
+ switch v := v.(type) {
+ case float32:
+ return finite(float64(v))
+ case float64:
+ return finite(v)
+ case []float32:
+ for _, f := range v {
+ if !finite(float64(f)) {
+ return false
+ }
+ }
+ case []float64:
+ for _, f := range v {
+ if !finite(f) {
+ return false
+ }
+ }
+ }
+ return true
+}
diff --git a/server/images.go b/server/images.go
index 1c19d8154..0a59b913b 100644
--- a/server/images.go
+++ b/server/images.go
@@ -2,6 +2,7 @@ package server
import (
"bytes"
+ "cmp"
"context"
"crypto/sha256"
"encoding/json"
@@ -32,6 +33,8 @@ import (
"github.com/ollama/ollama/types/model"
"github.com/ollama/ollama/version"
"github.com/ollama/ollama/x/transfer"
+
+ "golang.org/x/mod/semver"
)
// Blobs newer than this may belong to another process that has not written its
@@ -77,6 +80,8 @@ type Model struct {
System string
License []string
Digest string
+ ManifestDigest string
+ Runner string
Options map[string]any
GenerationDefaults model.GenerationDefaults
Messages []api.Message
@@ -246,6 +251,15 @@ func chatTemplateHasToolRoundTrip(chatTemplate string) bool {
strings.Contains(chatTemplate, "ipython"))
}
+// chatTemplateHasToolCallIDs detects Mistral-style templates that round-trip
+// tool-call IDs via the [CALL_ID] token. Go templates cannot carry the ID, so
+// these templates must win the renderer preference or multi-turn tool calls
+// break. This applies to any model with such a template, not just migrated
+// ones.
+func chatTemplateHasToolCallIDs(chatTemplate string) bool {
+ return strings.Contains(chatTemplate, "[CALL_ID]") && strings.Contains(chatTemplate, "tool_call.id")
+}
+
func goTemplateCapabilities(t *template.Template) []model.Capability {
if t == nil {
return nil
@@ -316,6 +330,10 @@ func shouldPreferChatTemplate(chatTemplate string, chatTemplateCaps []model.Capa
return false
}
+ if chatTemplateHasToolCallIDs(chatTemplate) {
+ return true
+ }
+
return chatTemplateHasToolRoundTrip(chatTemplate) && !goTemplateHasToolRoundTrip(goTemplate)
}
@@ -653,18 +671,33 @@ func (m *Model) String() string {
return modelfile.String()
}
+// GetModel loads a model without constraining the runner, letting manifest
+// lists resolve to the preferred child.
func GetModel(name string) (*Model, error) {
+ return GetModelForRunner(name, "")
+}
+
+// GetModelForRunner returns model metadata for name, selecting runner from a
+// manifest list when one is specified.
+func GetModelForRunner(name, runner string) (*Model, error) {
n := model.ParseName(name)
- mf, err := manifest.ParseNamedManifest(n)
+ mf, err := manifest.ParseNamedManifestForRunner(n, runner)
if err != nil {
return nil, err
}
+ manifestDigest := mf.SelectedDigest()
+ if manifestDigest == "" {
+ manifestDigest = mf.Digest()
+ }
+
m := &Model{
- Name: n.String(),
- ShortName: n.DisplayShortest(),
- Digest: mf.Digest(),
- Template: template.DefaultTemplate,
+ Name: n.String(),
+ ShortName: n.DisplayShortest(),
+ Digest: mf.Digest(),
+ ManifestDigest: manifestDigest,
+ Runner: mf.Runner,
+ Template: template.DefaultTemplate,
}
if mf.Config.Digest != "" {
@@ -803,79 +836,83 @@ func GetModel(name string) (*Model, error) {
return m, nil
}
-func CopyModel(src, dst model.Name) error {
+// CopyModel copies src to dst, returning a warning when a manifest list is
+// narrowed to the children held locally.
+func CopyModel(src, dst model.Name) (string, error) {
if !dst.IsFullyQualified() {
- return model.Unqualified(dst)
+ return "", model.Unqualified(dst)
}
if !src.IsFullyQualified() {
- return model.Unqualified(src)
+ return "", model.Unqualified(src)
}
if src.Filepath() == dst.Filepath() {
- return nil
+ return "", nil
}
- manifests, err := manifest.Path()
+ data, err := manifest.ReadManifestData(src)
if err != nil {
- return err
+ return "", err
}
- dstpath := filepath.Join(manifests, dst.Filepath())
- if err := os.MkdirAll(filepath.Dir(dstpath), 0o755); err != nil {
- return err
- }
-
- srcpath := filepath.Join(manifests, src.Filepath())
- srcfile, err := os.Open(srcpath)
- if err != nil {
- return err
- }
- defer srcfile.Close()
-
- dstfile, err := os.Create(dstpath)
+ data, warning, err := narrowManifestListToLocal(data)
if err != nil {
- return err
+ return "", err
}
- defer dstfile.Close()
- _, err = io.Copy(dstfile, srcfile)
- return err
+ return warning, manifest.WriteManifestData(dst, data)
}
-func deleteUnusedLayers(deleteMap map[string]struct{}) error {
- // Ignore corrupt manifests to avoid blocking deletion of layers that are freshly orphaned
- manifests, err := manifest.Manifests(true)
- if err != nil {
- return err
+// narrowManifestListToLocal drops manifest list children whose manifests are
+// not local, returning the rewritten document and a warning naming what went.
+func narrowManifestListToLocal(data []byte) ([]byte, string, error) {
+ var mf manifest.Manifest
+ if err := json.Unmarshal(data, &mf); err != nil {
+ return nil, "", err
+ }
+ if mf.MediaType != manifest.MediaTypeManifestList {
+ return data, "", nil
}
- for _, manifest := range manifests {
- for _, layer := range manifest.Layers {
- delete(deleteMap, layer.Digest)
+ var kept []manifest.Manifest
+ var dropped []string
+ for _, child := range mf.Manifests {
+ if _, err := resolveShowManifestChild(child); err != nil {
+ if !errors.Is(err, os.ErrNotExist) {
+ return nil, "", err
+ }
+ dropped = append(dropped, cmp.Or(child.Runner, "unknown"))
+ continue
}
+ kept = append(kept, child)
+ }
- delete(deleteMap, manifest.Config.Digest)
+ if len(dropped) == 0 {
+ return data, "", nil
+ }
+ if len(kept) == 0 {
+ return nil, "", fmt.Errorf("%w: pull one of %s before copying", manifest.ErrNoCompatibleManifest, strings.Join(dropped, ", "))
}
- // only delete the files which are still in the deleteMap
- for k := range deleteMap {
- fp, err := manifest.BlobsPath(k)
- if err != nil {
- slog.Info(fmt.Sprintf("couldn't get file path for '%s': %v", k, err))
- continue
- }
- if err := os.Remove(fp); err != nil && !errors.Is(err, os.ErrNotExist) {
- slog.Info(fmt.Sprintf("couldn't remove file '%s': %v", fp, err))
- continue
- }
- removeGGUFMetadata(k)
+ narrowed := mf
+ narrowed.Manifests = kept
+ out, err := json.Marshal(narrowed)
+ if err != nil {
+ return nil, "", err
}
- return nil
+ var runners []string
+ for _, child := range kept {
+ runners = append(runners, cmp.Or(child.Runner, "unknown"))
+ }
+ warning := fmt.Sprintf("Warning: discarded %s (not pulled locally); copy contains %s",
+ strings.Join(dropped, ", "), strings.Join(runners, ", "))
+
+ return out, warning, nil
}
func PruneLayers() error {
- deleteMap := make(map[string]struct{})
+ var candidates []string
p, err := manifest.BlobsPath("")
if err != nil {
return err
@@ -916,18 +953,19 @@ func PruneLayers() error {
continue
}
- deleteMap[name] = struct{}{}
+ candidates = append(candidates, name)
}
- slog.Info(fmt.Sprintf("total blobs: %d", len(deleteMap)))
+ slog.Info(fmt.Sprintf("total blobs: %d", len(candidates)))
- if err := deleteUnusedLayers(deleteMap); err != nil {
+ removed, err := manifest.RemoveUnreferencedBlobs(candidates...)
+ if err != nil {
slog.Error(fmt.Sprintf("couldn't remove unused layers: %v", err))
return nil
}
pruneGGUFMetadata()
- slog.Info(fmt.Sprintf("total unused blobs removed: %d", len(deleteMap)))
+ slog.Info(fmt.Sprintf("total unused blobs removed: %d", len(removed)))
return nil
}
@@ -940,30 +978,50 @@ func PushModel(ctx context.Context, name string, regOpts *registryOptions, fn fu
return errInsecureProtocol
}
- mf, err := manifest.ParseNamedManifest(n)
+ manifestJSON, err := manifest.ReadManifestData(n)
if err != nil {
fn(api.ProgressResponse{Status: "couldn't retrieve manifest"})
return err
}
- var layers []manifest.Layer
- layers = append(layers, mf.Layers...)
- if mf.Config.Digest != "" {
- layers = append(layers, mf.Config)
+ var stored manifest.Manifest
+ if err := json.Unmarshal(manifestJSON, &stored); err != nil {
+ fn(api.ProgressResponse{Status: "couldn't retrieve manifest"})
+ return err
}
- // Use fast transfer for models with tensor layers (many small blobs)
- if hasTensorLayers(layers) {
- // Read raw manifest JSON to preserve tensor metadata fields
- manifestPath, err := manifest.PathForName(n)
+ var layers []manifest.Layer
+ manifestMediaType := manifest.MediaTypeManifest
+
+ if stored.MediaType == manifest.MediaTypeManifestList {
+ layers, err = pushLayersForManifestList(stored)
if err != nil {
return err
}
- manifestJSON, err := os.ReadFile(manifestPath)
+ manifestMediaType = manifest.MediaTypeManifestList
+ } else {
+ mf, err := manifest.ParseNamedManifest(n)
if err != nil {
+ fn(api.ProgressResponse{Status: "couldn't retrieve manifest"})
return err
}
- if err := pushWithTransfer(ctx, n, layers, manifestJSON, regOpts, fn); err != nil {
+
+ layers = append(layers, mf.Layers...)
+ if mf.Config.Digest != "" {
+ layers = append(layers, mf.Config)
+ }
+
+ if !hasTensorLayers(layers) {
+ manifestJSON, err = json.Marshal(mf)
+ if err != nil {
+ return err
+ }
+ }
+ }
+
+ // Use fast transfer for models with tensor layers (many small blobs)
+ if hasTensorLayers(layers) {
+ if err := pushWithTransfer(ctx, n, layers, manifestJSON, manifestMediaType, regOpts, fn); err != nil {
return err
}
fn(api.ProgressResponse{Status: "success"})
@@ -981,13 +1039,8 @@ func PushModel(ctx context.Context, name string, regOpts *registryOptions, fn fu
requestURL := n.BaseURL()
requestURL = requestURL.JoinPath("v2", n.DisplayNamespaceModel(), "manifests", n.Tag)
- manifestJSON, err := json.Marshal(mf)
- if err != nil {
- return err
- }
-
headers := make(http.Header)
- headers.Set("Content-Type", "application/vnd.docker.distribution.manifest.v2+json")
+ headers.Set("Content-Type", manifestMediaType)
resp, err := makeRequestWithRetry(ctx, http.MethodPut, requestURL, headers, bytes.NewReader(manifestJSON), regOpts)
if err != nil {
return err
@@ -999,22 +1052,87 @@ func PushModel(ctx context.Context, name string, regOpts *registryOptions, fn fu
return nil
}
-func PullModel(ctx context.Context, name string, regOpts *registryOptions, fn func(api.ProgressResponse)) error {
+func pushLayersForManifestList(parent manifest.Manifest) ([]manifest.Layer, error) {
+ seen := make(map[string]struct{})
+ var layers []manifest.Layer
+
+ addLayer := func(layer manifest.Layer) error {
+ if layer.Digest == "" {
+ return nil
+ }
+ if _, ok := seen[layer.Digest]; ok {
+ return nil
+ }
+ if layer.Size == 0 {
+ p, err := manifest.BlobsPath(layer.Digest)
+ if err != nil {
+ return err
+ }
+ fi, err := os.Stat(p)
+ if err != nil {
+ return err
+ }
+ layer.Size = fi.Size()
+ }
+ seen[layer.Digest] = struct{}{}
+ layers = append(layers, layer)
+ return nil
+ }
+
+ for _, child := range parent.Manifests {
+ childDigest := child.BlobDigest()
+ if childDigest == "" {
+ return nil, errors.New("manifest list child is missing digest")
+ }
+ // Resolve before sizing the child: its descriptor carries no size, so
+ // addLayer would stat a missing blob and lose the actionable error.
+ resolved, err := resolveShowManifestChild(child)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ // pull materializes only the selected child; the others stay
+ // bare references until pulled explicitly.
+ return nil, fmt.Errorf("manifest child for runner %q is not local; pull it with --runner %s before pushing", child.Runner, child.Runner)
+ }
+ return nil, err
+ }
+
+ if err := addLayer(manifest.Layer{
+ MediaType: manifest.MediaTypeManifest,
+ Digest: childDigest,
+ }); err != nil {
+ return nil, err
+ }
+
+ for _, layer := range resolved.Layers {
+ if err := addLayer(layer); err != nil {
+ return nil, err
+ }
+ }
+ if err := addLayer(resolved.Config); err != nil {
+ return nil, err
+ }
+ }
+
+ return layers, nil
+}
+
+func PullModel(ctx context.Context, name string, runner string, regOpts *registryOptions, fn func(api.ProgressResponse)) error {
n := model.ParseName(name)
// build deleteMap to prune unused layers
deleteMap := make(map[string]struct{})
- existingMf, err := manifest.ParseNamedManifest(n)
+ existingDigests, err := manifest.ReferencedBlobDigestsForName(n)
if errors.Is(err, os.ErrNotExist) {
// noop
} else if err != nil {
slog.Warn("pulling model with bad existing manifest", "name", name, "error", err)
} else {
- for _, l := range existingMf.Layers {
- deleteMap[l.Digest] = struct{}{}
- }
- if existingMf.Config.Digest != "" {
- deleteMap[existingMf.Config.Digest] = struct{}{}
+ for _, digest := range existingDigests {
+ if blob, err := manifest.BlobsPath(digest); err == nil {
+ if _, err := os.Stat(blob); err == nil {
+ deleteMap[digest] = struct{}{}
+ }
+ }
}
}
@@ -1028,13 +1146,38 @@ func PullModel(ctx context.Context, name string, regOpts *registryOptions, fn fu
if err != nil {
return fmt.Errorf("pull model manifest: %s", err)
}
- if hasTensorLayers(mf.Layers) {
+ selectedChildDigest := ""
+ if mf.MediaType == manifest.MediaTypeManifestList {
+ var childDigest string
+ mf, childDigest, err = pullSelectedManifest(ctx, n, mf, runner, regOpts, fn)
+ if err != nil {
+ return err
+ }
+ selectedChildDigest = childDigest
+ } else if runner != "" {
+ // The registry served a plain manifest, so there is no variant to
+ // select. Honor an explicit runner request by rejecting a declared
+ // mismatch instead of silently pulling whatever is stored. Manifests
+ // without runner metadata cannot be checked before their config blob
+ // is local, so they proceed as before.
+ if mf.Runner != "" && !strings.EqualFold(mf.Runner, runner) {
+ return fmt.Errorf("%w for runners: %s", manifest.ErrNoCompatibleManifest, runner)
+ }
+ }
+
+ // Checked against the selected child: a manifest list carries no layers of
+ // its own, so testing the parent would skip the gate entirely.
+ if requiresMLX(mf) {
if err := mlx.CheckInit(); err != nil {
slog.Debug("MLX is unavailable for safetensors model pull", "error", err)
return errors.New("this model requires MLX support, but the MLX runtime is not available")
}
}
+ if err := checkModelRequires(ctx, n, mf, regOpts); err != nil {
+ return err
+ }
+
var layers []manifest.Layer
layers = append(layers, mf.Layers...)
if mf.Config.Digest != "" {
@@ -1046,6 +1189,7 @@ func PullModel(ctx context.Context, name string, regOpts *registryOptions, fn fu
if err := pullWithTransfer(ctx, n, layers, manifestData, regOpts, fn); err != nil {
return err
}
+ writePullDowngradeAnchor(n, mf, manifestData, selectedChildDigest)
fn(api.ProgressResponse{Status: "success"})
return nil
}
@@ -1101,25 +1245,18 @@ func PullModel(ctx context.Context, name string, regOpts *registryOptions, fn fu
fn(api.ProgressResponse{Status: "writing manifest"})
- fp, err := manifest.PathForName(n)
- if err != nil {
- return err
- }
- if err := os.MkdirAll(filepath.Dir(fp), 0o755); err != nil {
+ if err := manifest.WriteManifestData(n, manifestData); err != nil {
+ slog.Info(fmt.Sprintf("couldn't write manifest for %s", n.DisplayShortest()))
return err
}
- err = os.WriteFile(fp, manifestData, 0o644)
- if err != nil {
- slog.Info(fmt.Sprintf("couldn't write to %s", fp))
- return err
- }
+ writePullDowngradeAnchor(n, mf, manifestData, selectedChildDigest)
- slog.Debug("manifest written", "path", fp, "sha256", fmt.Sprintf("%x", sha256.Sum256(manifestData)), "size", len(manifestData))
+ slog.Debug("manifest written", "name", n.DisplayShortest(), "sha256", fmt.Sprintf("%x", sha256.Sum256(manifestData)), "size", len(manifestData))
if !envconfig.NoPrune() && len(deleteMap) > 0 {
fn(api.ProgressResponse{Status: "removing unused layers"})
- if err := deleteUnusedLayers(deleteMap); err != nil {
+ if _, err := manifest.RemoveUnreferencedBlobs(candidateBlobDigests(deleteMap)...); err != nil {
fn(api.ProgressResponse{Status: fmt.Sprintf("couldn't remove unused layers: %v", err)})
}
}
@@ -1129,6 +1266,16 @@ func PullModel(ctx context.Context, name string, regOpts *registryOptions, fn fu
return nil
}
+// requiresMLX reports whether serving mf needs the MLX runtime. A declared
+// runner is authoritative; manifests predating runner metadata are judged by
+// their tensor layers.
+func requiresMLX(mf *manifest.Manifest) bool {
+ if mf.Runner != "" {
+ return strings.EqualFold(mf.Runner, manifest.RunnerMLX)
+ }
+ return hasTensorLayers(mf.Layers)
+}
+
// hasTensorLayers checks if any layer has tensor media type.
func hasTensorLayers(layers []manifest.Layer) bool {
for _, layer := range layers {
@@ -1139,8 +1286,144 @@ func hasTensorLayers(layers []manifest.Layer) bool {
return false
}
-// pullWithTransfer uses the simplified x/transfer package for downloading blobs.
-func pullWithTransfer(ctx context.Context, n model.Name, layers []manifest.Layer, manifestData []byte, regOpts *registryOptions, fn func(api.ProgressResponse)) error {
+func candidateBlobDigests(m map[string]struct{}) []string {
+ digests := make([]string, 0, len(m))
+ for digest := range m {
+ digests = append(digests, digest)
+ }
+
+ return digests
+}
+
+// checkModelRequires makes sure the model is compatible with the local
+// Ollama version before any model layers are downloaded.
+func checkModelRequires(ctx context.Context, n model.Name, mf *manifest.Manifest, regOpts *registryOptions) error {
+ if mf == nil || mf.Config.Digest == "" {
+ return nil
+ }
+
+ if err := verifyBlob(mf.Config.Digest); err != nil {
+ if !errors.Is(err, os.ErrNotExist) && !errors.Is(err, errDigestMismatch) {
+ return err
+ }
+ if err := downloadWithTransfer(ctx, n, []manifest.Layer{mf.Config}, regOpts, func(api.ProgressResponse) {}); err != nil {
+ slog.Debug("skipping requires check: config fetch failed", "model", n.DisplayShortest(), "error", err)
+ return nil
+ }
+ if err := verifyBlob(mf.Config.Digest); err != nil {
+ slog.Debug("skipping requires check: config verify failed", "model", n.DisplayShortest(), "error", err)
+ return nil
+ }
+ }
+
+ blobPath, err := manifest.BlobsPath(mf.Config.Digest)
+ if err != nil {
+ return err
+ }
+ data, err := os.ReadFile(blobPath)
+ if err != nil {
+ return err
+ }
+
+ var cfg model.ConfigV2
+ if err := json.Unmarshal(data, &cfg); err != nil {
+ return err
+ }
+
+ return checkPullRequires(cfg.Requires, version.Version)
+}
+
+// checkPullRequires reports whether the pulling client satisfies the model's
+// declared minimum version.
+func checkPullRequires(requires, clientVersion string) error {
+ if requires == "" {
+ return nil
+ }
+ if clientVersion == "0.0.0" {
+ return nil
+ }
+ requires = "v" + strings.TrimPrefix(requires, "v")
+ if !semver.IsValid(requires) {
+ slog.Debug("ignoring malformed requires version", "requires", requires)
+ return nil
+ }
+ if semver.Compare(requires, "v"+clientVersion) > 0 {
+ return fmt.Errorf("model requires ollama version %s or newer (this client is v%s)", requires, clientVersion)
+ }
+ return nil
+}
+
+func pullSelectedManifest(ctx context.Context, n model.Name, parent *manifest.Manifest, runner string, regOpts *registryOptions, fn func(api.ProgressResponse)) (*manifest.Manifest, string, error) {
+ child, err := manifest.SelectManifestReferenceForRunner(parent.Manifests, runner)
+ if err != nil {
+ return nil, "", err
+ }
+
+ childDigest := child.BlobDigest()
+ if childDigest == "" {
+ return nil, "", errors.New("manifest list child is missing digest")
+ }
+
+ layer, err := remoteBlobLayer(ctx, n, childDigest, manifest.MediaTypeManifest, regOpts)
+ if err != nil {
+ return nil, "", err
+ }
+
+ // The child manifest is metadata; model progress starts with its layers.
+ if err := downloadWithTransfer(ctx, n, []manifest.Layer{layer}, regOpts, func(api.ProgressResponse) {}); err != nil {
+ return nil, "", err
+ }
+
+ if err := verifyBlob(childDigest); err != nil {
+ return nil, "", err
+ }
+ blobPath, err := manifest.BlobsPath(childDigest)
+ if err != nil {
+ return nil, "", err
+ }
+ data, err := os.ReadFile(blobPath)
+ if err != nil {
+ return nil, "", err
+ }
+
+ var mf manifest.Manifest
+ if err := json.Unmarshal(data, &mf); err != nil {
+ return nil, "", err
+ }
+ if mf.MediaType == manifest.MediaTypeManifestList {
+ return nil, "", errors.New("nested manifest lists are not supported")
+ }
+ if mf.Runner == "" {
+ mf.Runner = child.Runner
+ }
+ if mf.Format == "" {
+ mf.Format = child.Format
+ }
+
+ return &mf, childDigest, nil
+}
+
+func remoteBlobLayer(ctx context.Context, n model.Name, digest, mediaType string, regOpts *registryOptions) (manifest.Layer, error) {
+ requestURL := n.BaseURL().JoinPath("v2", n.DisplayNamespaceModel(), "blobs", digest)
+ resp, err := makeRequestWithRetry(ctx, http.MethodHead, requestURL, nil, nil, regOpts)
+ if err != nil {
+ return manifest.Layer{}, err
+ }
+ defer resp.Body.Close()
+
+ size, err := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)
+ if err != nil {
+ return manifest.Layer{}, err
+ }
+
+ return manifest.Layer{
+ MediaType: mediaType,
+ Digest: digest,
+ Size: size,
+ }, nil
+}
+
+func downloadWithTransfer(ctx context.Context, n model.Name, layers []manifest.Layer, regOpts *registryOptions, fn func(api.ProgressResponse)) error {
blobs := make([]transfer.Blob, len(layers))
for i, layer := range layers {
blobs[i] = transfer.Blob{
@@ -1197,27 +1480,43 @@ func pullWithTransfer(ctx context.Context, n model.Name, layers []manifest.Layer
return err
}
- // Write manifest
- fn(api.ProgressResponse{Status: "writing manifest"})
+ return nil
+}
- fp, err := manifest.PathForName(n)
- if err != nil {
- return err
+// writePullDowngradeAnchor writes a legacy manifest at the pulled name so a
+// pre-manifest-list daemon can load the model and its garbage collector
+// retains the referenced blobs.
+func writePullDowngradeAnchor(n model.Name, mf *manifest.Manifest, manifestData []byte, selectedChildDigest string) {
+ manifestDigests := []string{fmt.Sprintf("sha256:%x", sha256.Sum256(manifestData))}
+ if selectedChildDigest != "" {
+ manifestDigests = append(manifestDigests, selectedChildDigest)
+ }
+ // Best effort: the pull itself succeeded, so a failed downgrade anchor is
+ // logged rather than failing the request.
+ if err := manifest.WriteLegacyAnchor(n, mf, manifestDigests...); err != nil {
+ slog.Warn("couldn't write downgrade anchor for pulled model", "model", n.DisplayShortest(), "error", err)
}
- if err := os.MkdirAll(filepath.Dir(fp), 0o755); err != nil {
+}
+
+// pullWithTransfer uses the simplified x/transfer package for downloading blobs.
+func pullWithTransfer(ctx context.Context, n model.Name, layers []manifest.Layer, manifestData []byte, regOpts *registryOptions, fn func(api.ProgressResponse)) error {
+ if err := downloadWithTransfer(ctx, n, layers, regOpts, fn); err != nil {
return err
}
- if err := os.WriteFile(fp, manifestData, 0o644); err != nil {
+ // Write manifest
+ fn(api.ProgressResponse{Status: "writing manifest"})
+
+ if err := manifest.WriteManifestData(n, manifestData); err != nil {
return err
}
- slog.Debug("manifest written", "path", fp, "sha256", fmt.Sprintf("%x", sha256.Sum256(manifestData)), "size", len(manifestData))
+ slog.Debug("manifest written", "name", n.DisplayShortest(), "sha256", fmt.Sprintf("%x", sha256.Sum256(manifestData)), "size", len(manifestData))
return nil
}
// pushWithTransfer uses the simplified x/transfer package for uploading blobs and manifest.
-func pushWithTransfer(ctx context.Context, n model.Name, layers []manifest.Layer, manifestJSON []byte, regOpts *registryOptions, fn func(api.ProgressResponse)) error {
+func pushWithTransfer(ctx context.Context, n model.Name, layers []manifest.Layer, manifestJSON []byte, manifestMediaType string, regOpts *registryOptions, fn func(api.ProgressResponse)) error {
blobs := make([]transfer.Blob, len(layers))
for i, layer := range layers {
blobs[i] = transfer.Blob{
@@ -1270,6 +1569,7 @@ func pushWithTransfer(ctx context.Context, n model.Name, layers []manifest.Layer
GetToken: getToken,
Logger: slog.Default(),
Manifest: manifestJSON,
+ ManifestMediaType: manifestMediaType,
ManifestRef: n.Tag,
Repository: n.DisplayNamespaceModel(),
AllowPrivateHosts: regOpts != nil && regOpts.Insecure,
@@ -1280,7 +1580,7 @@ func pullModelManifest(ctx context.Context, n model.Name, regOpts *registryOptio
requestURL := n.BaseURL().JoinPath("v2", n.DisplayNamespaceModel(), "manifests", n.Tag)
headers := make(http.Header)
- headers.Set("Accept", "application/vnd.docker.distribution.manifest.v2+json")
+ headers.Set("Accept", strings.Join([]string{manifest.MediaTypeManifestList, manifest.MediaTypeManifest}, ", "))
resp, err := makeRequestWithRetry(ctx, http.MethodGet, requestURL, headers, nil, regOpts)
if err != nil {
return nil, nil, err
diff --git a/server/images_test.go b/server/images_test.go
index a5502e26e..3abcec24d 100644
--- a/server/images_test.go
+++ b/server/images_test.go
@@ -1,8 +1,10 @@
package server
import (
+ "bytes"
"context"
"crypto/sha256"
+ "encoding/json"
"errors"
"fmt"
"net"
@@ -10,7 +12,9 @@ import (
"net/http/httptest"
"net/url"
"os"
+ "strconv"
"strings"
+ "sync"
"sync/atomic"
"testing"
"time"
@@ -20,6 +24,7 @@ import (
"github.com/ollama/ollama/manifest"
"github.com/ollama/ollama/template"
"github.com/ollama/ollama/types/model"
+ "github.com/ollama/ollama/version"
)
func TestPruneLayersSkipsRecentOrphans(t *testing.T) {
@@ -132,7 +137,7 @@ func TestGetModelTemplateMetadata(t *testing.T) {
}, nil)
writeTestModelManifest(t, "template-disabled", digest, customTemplate)
- m, err := GetModel("template-disabled")
+ m, err := GetModelForRunner("template-disabled", "")
if err != nil {
t.Fatal(err)
}
@@ -157,7 +162,7 @@ func TestGetModelTemplateMetadata(t *testing.T) {
}, nil)
writeTestModelManifest(t, "chat-template-tools", digest, customTemplate)
- m, err := GetModel("chat-template-tools")
+ m, err := GetModelForRunner("chat-template-tools", "")
if err != nil {
t.Fatal(err)
}
@@ -179,7 +184,7 @@ func TestGetModelTemplateMetadata(t *testing.T) {
}, nil)
writeTestModelManifest(t, "chat-template-tools-thinking", digest, "{{ range .Messages }}{{ if .Thinking }}<think>{{ .Thinking }}</think>{{ end }}{{ .Content }}{{ end }}")
- m, err := GetModel("chat-template-tools-thinking")
+ m, err := GetModelForRunner("chat-template-tools-thinking", "")
if err != nil {
t.Fatal(err)
}
@@ -213,7 +218,7 @@ func TestGetModelTemplateMetadata(t *testing.T) {
{{ range .ToolCalls }}{{ .Function.Name }}{{ end }}
{{ end }}`)
- m, err := GetModel("chat-template-tool-round-trip")
+ m, err := GetModelForRunner("chat-template-tool-round-trip", "")
if err != nil {
t.Fatal(err)
}
@@ -248,7 +253,7 @@ func TestGetModelTemplateMetadata(t *testing.T) {
{{ if .ToolCalls }}<|tool_call|>{{ range .ToolCalls }}{{ .Function.Name }}{{ end }}{{ else }}{{ .Content }}{{ end }}
{{ end }}`)
- m, err := GetModel("chat-template-weaker-tools")
+ m, err := GetModelForRunner("chat-template-weaker-tools", "")
if err != nil {
t.Fatal(err)
}
@@ -263,6 +268,36 @@ func TestGetModelTemplateMetadata(t *testing.T) {
}
})
+ t.Run("prefers Mistral chat template with tool call IDs", func(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+ t.Setenv("OLLAMA_GO_TEMPLATE", "")
+
+ _, digest := createBinFile(t, map[string]any{
+ "general.architecture": "llama",
+ "tokenizer.chat_template": `{% if tools %}{{ tools }}{% endif %}
+{% for message in messages %}
+{% if message.get('tool_calls') %}{% for tool_call in message.tool_calls %}[TOOL_CALLS]{{ tool_call.function.name }}[CALL_ID]{{ tool_call.id }}[ARGS]{{ tool_call['function']['arguments']|tojson }}{% endfor %}{% endif %}
+{% if message['role'] == 'tool' %}tool_response{{ message['content'] }}{% endif %}
+{% endfor %}`,
+ }, nil)
+ writeTestModelManifest(t, "chat-template-tool-call-ids", digest, `{{ if .Tools }}tools{{ end }}
+{{ range .Messages }}
+{{ if eq .Role "tool" }}tool_response{{ else }}{{ .Role }}{{ end }}
+{{ if .ToolCalls }}[TOOL_CALLS]{{ range .ToolCalls }}{{ .Function.Name }}[CALL_ID]0[ARGS]{{ .Function.Arguments }}{{ end }}{{ else }}{{ .Content }}{{ end }}
+{{ end }}`)
+
+ m, err := GetModelForRunner("chat-template-tool-call-ids", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !m.PreferChatTemplate {
+ t.Fatal("expected chat template to be preferred")
+ }
+ if got := m.CheckCapabilities(model.CapabilityTools); got != nil {
+ t.Fatalf("expected tools capability, got %v", got)
+ }
+ })
+
t.Run("respects explicit Go TEMPLATE enablement", func(t *testing.T) {
t.Setenv("OLLAMA_MODELS", t.TempDir())
t.Setenv("OLLAMA_GO_TEMPLATE", "1")
@@ -273,7 +308,7 @@ func TestGetModelTemplateMetadata(t *testing.T) {
}, nil)
writeTestModelManifest(t, "go-template-forced", digest, customTemplate)
- m, err := GetModel("go-template-forced")
+ m, err := GetModelForRunner("go-template-forced", "")
if err != nil {
t.Fatal(err)
}
@@ -295,7 +330,7 @@ func TestGetModelTemplateMetadata(t *testing.T) {
}, nil)
writeTestModelManifest(t, "go-template-disabled", digest, customTemplate)
- m, err := GetModel("go-template-disabled")
+ m, err := GetModelForRunner("go-template-disabled", "")
if err != nil {
t.Fatal(err)
}
@@ -316,7 +351,7 @@ func TestGetModelTemplateMetadata(t *testing.T) {
}, nil)
writeTestModelManifest(t, "missing-chat-template", digest, customTemplate)
- m, err := GetModel("missing-chat-template")
+ m, err := GetModelForRunner("missing-chat-template", "")
if err != nil {
t.Fatal(err)
}
@@ -377,6 +412,341 @@ func loadTestMetadata(t *testing.T, m *Model) {
}
}
+func TestPushLayersForManifestListIncludesChildManifests(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ writeChild := func(name, runner, formatName, layerMediaType string) (manifest.Manifest, manifest.Layer, manifest.Layer) {
+ t.Helper()
+
+ config, err := manifest.NewLayer(strings.NewReader(name+" config"), "application/vnd.docker.container.image.v1+json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ layer, err := manifest.NewLayer(strings.NewReader(name+" layer"), layerMediaType)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := manifest.WriteManifestWithMetadata(model.ParseName(name), config, []manifest.Layer{layer}, runner, formatName); err != nil {
+ t.Fatal(err)
+ }
+ mf, err := manifest.ParseNamedManifestForRunner(model.ParseName(name), runner)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return *mf, config, layer
+ }
+
+ mlx, mlxConfig, mlxLayer := writeChild("library/push-mlx:latest", manifest.RunnerMLX, manifest.FormatSafetensors, manifest.MediaTypeImageTensor)
+ ggml, ggmlConfig, ggmlLayer := writeChild("library/push-ggml:latest", manifest.RunnerGGML, manifest.FormatGGUF, "application/vnd.ollama.image.model")
+
+ mlxRef, err := manifest.NewManifestReference(mlx.BlobDigest(), mlx.Runner, mlx.Format)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ggmlRef, err := manifest.NewManifestReference(ggml.BlobDigest(), ggml.Runner, ggml.Format)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ layers, err := pushLayersForManifestList(manifest.Manifest{
+ SchemaVersion: 2,
+ MediaType: manifest.MediaTypeManifestList,
+ Manifests: []manifest.Manifest{mlxRef, ggmlRef},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ want := map[string]string{
+ mlx.BlobDigest(): manifest.MediaTypeManifest,
+ ggml.BlobDigest(): manifest.MediaTypeManifest,
+ mlxConfig.Digest: mlxConfig.MediaType,
+ mlxLayer.Digest: mlxLayer.MediaType,
+ ggmlConfig.Digest: ggmlConfig.MediaType,
+ ggmlLayer.Digest: ggmlLayer.MediaType,
+ }
+ if len(layers) != len(want) {
+ t.Fatalf("layer count = %d, want %d: %#v", len(layers), len(want), layers)
+ }
+ for _, layer := range layers {
+ if wantMediaType, ok := want[layer.Digest]; !ok {
+ t.Fatalf("unexpected layer digest %q", layer.Digest)
+ } else if layer.MediaType != wantMediaType {
+ t.Fatalf("layer %q media type = %q, want %q", layer.Digest, layer.MediaType, wantMediaType)
+ }
+ if layer.Size == 0 {
+ t.Fatalf("layer %q has zero size", layer.Digest)
+ }
+ }
+ if !hasTensorLayers(layers) {
+ t.Fatal("manifest list push layers did not preserve tensor media type")
+ }
+}
+
+func TestCopyModelNarrowsManifestListToLocalChildren(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ writeChild := func(name, runner, formatName string) manifest.Manifest {
+ t.Helper()
+
+ config, err := manifest.NewLayer(strings.NewReader(name+" config"), "application/vnd.docker.container.image.v1+json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ layer, err := manifest.NewLayer(strings.NewReader(name+" layer"), "application/vnd.ollama.image.model")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := manifest.WriteManifestWithMetadata(model.ParseName(name), config, []manifest.Layer{layer}, runner, formatName); err != nil {
+ t.Fatal(err)
+ }
+ mf, err := manifest.ParseNamedManifestForRunner(model.ParseName(name), runner)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return *mf
+ }
+
+ local := writeChild("library/narrow-local:latest", manifest.RunnerGGML, manifest.FormatGGUF)
+ localRef, err := manifest.NewManifestReference(local.BlobDigest(), local.Runner, local.Format)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // A child the registry advertised but pull never materialized.
+ absentRef, err := manifest.NewManifestReference(fmt.Sprintf("sha256:%064d", 1), manifest.RunnerMLX, manifest.FormatSafetensors)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ writeList := func(name string, refs []manifest.Manifest) model.Name {
+ t.Helper()
+ n := model.ParseName(name)
+ if _, err := manifest.WriteManifestList(n, refs); err != nil {
+ t.Fatal(err)
+ }
+ return n
+ }
+
+ t.Run("drops absent children and warns", func(t *testing.T) {
+ src := writeList("library/narrow-src:latest", []manifest.Manifest{localRef, absentRef})
+ dst := model.ParseName("library/narrow-dst:latest")
+
+ warning, err := CopyModel(src, dst)
+ if err != nil {
+ t.Fatalf("CopyModel() = %v, want nil", err)
+ }
+ if !strings.Contains(warning, manifest.RunnerMLX) {
+ t.Errorf("warning = %q, want it to name the dropped %s child", warning, manifest.RunnerMLX)
+ }
+
+ data, err := manifest.ReadManifestData(dst)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var copied manifest.Manifest
+ if err := json.Unmarshal(data, &copied); err != nil {
+ t.Fatal(err)
+ }
+ if len(copied.Manifests) != 1 {
+ t.Fatalf("copy has %d children, want 1: %#v", len(copied.Manifests), copied.Manifests)
+ }
+ if got := copied.Manifests[0].BlobDigest(); got != local.BlobDigest() {
+ t.Errorf("copied child digest = %q, want %q", got, local.BlobDigest())
+ }
+ })
+
+ t.Run("fully local list is copied verbatim", func(t *testing.T) {
+ src := writeList("library/intact-src:latest", []manifest.Manifest{localRef})
+ dst := model.ParseName("library/intact-dst:latest")
+
+ warning, err := CopyModel(src, dst)
+ if err != nil {
+ t.Fatalf("CopyModel() = %v, want nil", err)
+ }
+ if warning != "" {
+ t.Errorf("warning = %q, want none", warning)
+ }
+
+ srcData, err := manifest.ReadManifestData(src)
+ if err != nil {
+ t.Fatal(err)
+ }
+ dstData, err := manifest.ReadManifestData(dst)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(srcData, dstData) {
+ t.Errorf("copy differs from source:\n got %s\nwant %s", dstData, srcData)
+ }
+ })
+
+ t.Run("no local children is an error", func(t *testing.T) {
+ src := writeList("library/empty-src:latest", []manifest.Manifest{absentRef})
+ dst := model.ParseName("library/empty-dst:latest")
+
+ if _, err := CopyModel(src, dst); !errors.Is(err, manifest.ErrNoCompatibleManifest) {
+ t.Fatalf("CopyModel() = %v, want ErrNoCompatibleManifest", err)
+ }
+ if _, err := manifest.ReadManifestData(dst); err == nil {
+ t.Error("destination manifest was written despite the error")
+ }
+ })
+}
+
+func TestPullModelManifestListDownloadsSelectedChildOnly(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ configData := []byte(`{"architecture":"test"}`)
+ configDigest := fmt.Sprintf("sha256:%x", sha256.Sum256(configData))
+ layerData := bytes.Repeat([]byte("selected tensor layer"), 64)
+ layerDigest := fmt.Sprintf("sha256:%x", sha256.Sum256(layerData))
+
+ child := manifest.Manifest{
+ SchemaVersion: 2,
+ MediaType: manifest.MediaTypeManifest,
+ Runner: manifest.RunnerLlamaCPP,
+ Format: manifest.FormatGGUF,
+ Config: manifest.Layer{
+ MediaType: "application/vnd.docker.container.image.v1+json",
+ Digest: configDigest,
+ Size: int64(len(configData)),
+ },
+ Layers: []manifest.Layer{
+ {
+ MediaType: manifest.MediaTypeImageTensor,
+ Digest: layerDigest,
+ Size: int64(len(layerData)),
+ },
+ },
+ }
+ childData, err := json.Marshal(child)
+ if err != nil {
+ t.Fatal(err)
+ }
+ childDigest := fmt.Sprintf("sha256:%x", sha256.Sum256(childData))
+ childRef, err := manifest.NewManifestReference(childDigest, manifest.RunnerLlamaCPP, manifest.FormatGGUF)
+ if err != nil {
+ t.Fatal(err)
+ }
+ unselectedDigest := "sha256:" + strings.Repeat("f", 64)
+ unselectedRef, err := manifest.NewManifestReference(unselectedDigest, manifest.RunnerGGML, manifest.FormatGGUF)
+ if err != nil {
+ t.Fatal(err)
+ }
+ parent := manifest.Manifest{
+ SchemaVersion: 2,
+ MediaType: manifest.MediaTypeManifestList,
+ Manifests: []manifest.Manifest{childRef, unselectedRef},
+ }
+ parentData, err := json.Marshal(parent)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ blobs := map[string][]byte{
+ childDigest: childData,
+ configDigest: configData,
+ layerDigest: layerData,
+ }
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/v2/library/test/manifests/latest":
+ w.Header().Set("Content-Type", manifest.MediaTypeManifestList)
+ w.Header().Set("Content-Length", strconv.Itoa(len(parentData)))
+ _, _ = w.Write(parentData)
+ case (r.Method == http.MethodHead || r.Method == http.MethodGet) && strings.HasPrefix(r.URL.Path, "/v2/library/test/blobs/"):
+ digest := strings.TrimPrefix(r.URL.Path, "/v2/library/test/blobs/")
+ if digest == unselectedDigest {
+ t.Errorf("requested unselected child manifest %s", digest)
+ http.Error(w, "unselected child requested", http.StatusNotFound)
+ return
+ }
+ data, ok := blobs[digest]
+ if !ok {
+ http.NotFound(w, r)
+ return
+ }
+ w.Header().Set("Content-Length", strconv.Itoa(len(data)))
+ if r.Method == http.MethodGet {
+ _, _ = w.Write(data)
+ }
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer ts.Close()
+
+ name := strings.TrimPrefix(ts.URL, "http://") + "/library/test:latest"
+ // Blobs download in parallel, so progress arrives from several goroutines.
+ var mu sync.Mutex
+ var progress []api.ProgressResponse
+ if err := PullModel(t.Context(), name, "", &registryOptions{Insecure: true}, func(resp api.ProgressResponse) {
+ mu.Lock()
+ defer mu.Unlock()
+ progress = append(progress, resp)
+ }); err != nil {
+ t.Fatal(err)
+ }
+
+ payloadTotal := int64(len(configData) + len(layerData))
+ childManifestTotal := int64(len(childData))
+ if payloadTotal == childManifestTotal {
+ t.Fatalf("test fixture payload total equals child manifest size: %d", payloadTotal)
+ }
+ var sawPayloadProgress bool
+ for _, resp := range progress {
+ if resp.Digest != "sha256:model" {
+ continue
+ }
+ if resp.Total == childManifestTotal {
+ t.Fatalf("reported child manifest as model progress: %#v", resp)
+ }
+ if resp.Total == payloadTotal {
+ sawPayloadProgress = true
+ }
+ }
+ if !sawPayloadProgress {
+ t.Fatalf("missing selected payload progress with total %d in %#v", payloadTotal, progress)
+ }
+
+ n := model.ParseName(name)
+ gotParentData, err := manifest.ReadManifestData(n)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(gotParentData, parentData) {
+ t.Fatal("named manifest does not contain the parent manifest list")
+ }
+
+ m, err := manifest.ParseNamedManifest(n)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if m.Runner != manifest.RunnerLlamaCPP {
+ t.Fatalf("runner = %q, want %q", m.Runner, manifest.RunnerLlamaCPP)
+ }
+ if m.Config.Digest != configDigest {
+ t.Fatalf("config digest = %q, want %q", m.Config.Digest, configDigest)
+ }
+
+ for _, digest := range []string{childDigest, configDigest, layerDigest} {
+ path, err := manifest.BlobsPath(digest)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(path); err != nil {
+ t.Fatalf("expected blob %s to exist: %v", digest, err)
+ }
+ }
+ path, err := manifest.BlobsPath(unselectedDigest)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Fatalf("unselected child manifest blob exists: %v", err)
+ }
+}
+
func TestModelCapabilities(t *testing.T) {
// Create completion model (llama architecture without vision)
completionModelPath, _ := createBinFile(t, gguftest.KV{
@@ -912,7 +1282,7 @@ func TestPullModelDuplicateDigestVerifiesBlob(t *testing.T) {
n := model.ParseName(u.Host + "/test/attack")
n.ProtocolScheme = "http"
- err = PullModel(t.Context(), n.String(), &registryOptions{Insecure: true}, func(api.ProgressResponse) {})
+ err = PullModel(t.Context(), n.String(), "", &registryOptions{Insecure: true}, func(api.ProgressResponse) {})
if !errors.Is(err, errDigestMismatch) {
t.Fatalf("PullModel = %v, want errDigestMismatch (unverified blob would persist)", err)
}
@@ -1043,3 +1413,81 @@ func TestPullManifestRedirectPolicy(t *testing.T) {
})
}
}
+
+func TestCheckPullRequires(t *testing.T) {
+ tests := []struct {
+ name string
+ requires string
+ clientVersion string
+ wantErr bool
+ wantMessage string
+ }{
+ {
+ name: "empty requires passes",
+ requires: "",
+ clientVersion: "0.33.3",
+ },
+ {
+ name: "older requirement passes",
+ requires: "0.33.0",
+ clientVersion: "0.33.3",
+ },
+ {
+ name: "exact requirement passes",
+ requires: "0.33.3",
+ clientVersion: "0.33.3",
+ },
+ {
+ name: "newer requirement fails",
+ requires: "0.35.0",
+ clientVersion: "0.33.3",
+ wantErr: true,
+ wantMessage: "model requires ollama version v0.35.0 or newer (this client is v0.33.3)",
+ },
+ {
+ name: "dev build skips check",
+ requires: "99.0.0",
+ clientVersion: "0.0.0",
+ },
+ {
+ name: "v-prefixed requirement passes",
+ requires: "v0.33.0",
+ clientVersion: "0.33.3",
+ },
+ {
+ name: "malformed requirement fails open",
+ requires: "banana",
+ clientVersion: "0.33.3",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := checkPullRequires(tt.requires, tt.clientVersion)
+ if tt.wantErr {
+ if err == nil {
+ t.Fatalf("checkPullRequires(%q, %q) = nil, want error", tt.requires, tt.clientVersion)
+ }
+ if err.Error() != tt.wantMessage {
+ t.Fatalf("checkPullRequires error = %q, want %q", err.Error(), tt.wantMessage)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("checkPullRequires(%q, %q) = %v, want nil", tt.requires, tt.clientVersion, err)
+ }
+ })
+ }
+}
+
+func TestCheckPullRequiresUsesRunningVersion(t *testing.T) {
+ oldVersion := version.Version
+ t.Cleanup(func() { version.Version = oldVersion })
+
+ // A dev build skips the check, but a stamped client that is too old
+ // must fail the pull before any model layers are downloaded.
+ version.Version = "0.33.3"
+ if err := checkPullRequires("0.35.0", version.Version); err == nil {
+ t.Fatal("expected stamped client below requires to fail")
+ }
+}
diff --git a/server/model.go b/server/model.go
index 046cca348..5af513db3 100644
--- a/server/model.go
+++ b/server/model.go
@@ -29,7 +29,7 @@ func parseFromModel(ctx context.Context, name model.Name, fn func(api.ProgressRe
m, err := manifest.ParseNamedManifest(name)
switch {
case errors.Is(err, os.ErrNotExist):
- if err := PullModel(ctx, name.String(), &registryOptions{}, fn); err != nil {
+ if err := PullModel(ctx, name.String(), "", &registryOptions{}, fn); err != nil {
return nil, config, err
}
diff --git a/server/model_list.go b/server/model_list.go
index 4936f15c5..83003bdfd 100644
--- a/server/model_list.go
+++ b/server/model_list.go
@@ -5,7 +5,9 @@ import (
"context"
"encoding/json"
"log/slog"
+ "os"
"slices"
+ "strings"
"time"
"github.com/ollama/ollama/api"
@@ -15,7 +17,8 @@ import (
)
// listModels builds /api/tags from the manifests and the per-blob metadata
-// files, extracting for any blob that has none yet.
+// files, extracting for any blob that has none yet. Manifest lists contribute
+// one row per child runner.
func listModels(ctx context.Context) ([]api.ListModelResponse, error) {
manifests, err := manifest.Manifests(true)
if err != nil {
@@ -30,21 +33,137 @@ func listModels(ctx context.Context) ([]api.ListModelResponse, error) {
}
}
- summary, err := describeModel(name, mf)
+ rows, err := describeModelRows(name, mf)
if err != nil {
slog.Warn("failed to describe model", "model", name.String(), "error", err)
continue
}
- models = append(models, summary)
+ models = append(models, rows...)
}
sortListModelResponses(models)
return models, nil
}
-// describeModel describes one model for /api/tags. Capabilities come from the
-// same Model.Capabilities() the inference path uses, so the two cannot drift.
-func describeModel(name model.Name, mf *manifest.Manifest) (api.ListModelResponse, error) {
+// describeModelRows describes one named manifest for /api/tags. A manifest
+// list describes one row per child runner, keyed by the child digest and
+// carrying the parent's modification time; every other manifest describes
+// itself.
+func describeModelRows(name model.Name, mf *manifest.Manifest) ([]api.ListModelResponse, error) {
+ parent, modified, ok, err := readManifestList(name)
+ if err != nil {
+ return nil, err
+ }
+ if !ok {
+ runner, err := displayRunnerForManifest(mf)
+ if err != nil {
+ return nil, err
+ }
+
+ m, err := GetModel(name.String())
+ if err != nil {
+ slog.Warn("could not load model to describe it", "model", name.String(), "error", err)
+ m = nil
+ }
+
+ row, err := describeModelFromManifest(name, mf, runner, m)
+ if err != nil {
+ return nil, err
+ }
+ return []api.ListModelResponse{row}, nil
+ }
+
+ rows := make([]api.ListModelResponse, 0, len(parent.Manifests))
+ for _, child := range parent.Manifests {
+ digest, err := manifest.ChildManifestDigest(child)
+ if err != nil {
+ return nil, err
+ }
+ resolved, ok, err := resolveLocalShowManifestChild(child)
+ if err != nil {
+ return nil, err
+ }
+ if !ok {
+ continue
+ }
+
+ runner, err := normalizeRunner(child.Runner)
+ if err != nil {
+ return nil, err
+ }
+
+ m, err := GetModelForRunner(name.String(), child.Runner)
+ if err != nil {
+ slog.Warn("could not load model to describe it", "model", name.String(), "runner", child.Runner, "error", err)
+ m = nil
+ }
+
+ row, err := describeModelFromManifest(name, resolved, runner, m)
+ if err != nil {
+ return nil, err
+ }
+ row.Digest = strings.TrimPrefix(digest, "sha256:")
+ row.Size = resolved.Size()
+ if !modified.IsZero() {
+ row.ModifiedAt = modified
+ }
+ rows = append(rows, row)
+ }
+
+ return rows, nil
+}
+
+// readManifestList returns the named manifest parsed as a manifest list along
+// with its modification time. It reports ok=false when the name is not a
+// manifest list.
+func readManifestList(name model.Name) (*manifest.Manifest, time.Time, bool, error) {
+ data, err := manifest.ReadManifestData(name)
+ if err != nil {
+ return nil, time.Time{}, false, err
+ }
+
+ var parent manifest.Manifest
+ if err := json.Unmarshal(data, &parent); err != nil {
+ return nil, time.Time{}, false, err
+ }
+ if parent.MediaType != manifest.MediaTypeManifestList {
+ return nil, time.Time{}, false, nil
+ }
+
+ path, err := manifest.ResolvePathForName(name)
+ if err != nil {
+ return nil, time.Time{}, false, err
+ }
+ fi, err := os.Lstat(path)
+ if err != nil {
+ return nil, time.Time{}, false, err
+ }
+
+ return &parent, fi.ModTime(), true, nil
+}
+
+// displayRunnerForManifest returns the runner /api/tags reports for a
+// manifest. Legacy manifests predate runner metadata; those report the
+// default the scheduler applies for the config's weight format.
+func displayRunnerForManifest(mf *manifest.Manifest) (string, error) {
+ runner := mf.Runner
+ if runner == "" {
+ cfg, err := readModelListConfig(mf)
+ if err != nil {
+ return "", err
+ }
+ runner, _ = manifest.MetadataForConfig(cfg)
+ }
+ if runner != "" {
+ return normalizeRunner(runner)
+ }
+ return "", nil
+}
+
+// describeModelFromManifest describes one manifest, enriching the row from
+// the loaded model when one is available. Capabilities come from the same
+// Model.Capabilities() the inference path uses, so the two cannot drift.
+func describeModelFromManifest(name model.Name, mf *manifest.Manifest, runner string, m *Model) (api.ListModelResponse, error) {
cfg, err := readModelListConfig(mf)
if err != nil {
return api.ListModelResponse{}, err
@@ -61,7 +180,7 @@ func describeModel(name model.Name, mf *manifest.Manifest) (api.ListModelRespons
RemoteModel: cfg.RemoteModel,
RemoteHost: cfg.RemoteHost,
Size: mf.Size(),
- Digest: mf.Digest(),
+ Digest: strings.TrimPrefix(mf.Digest(), "sha256:"),
ModifiedAt: modified,
Details: api.ModelDetails{
Format: cfg.ModelFormat,
@@ -71,14 +190,13 @@ func describeModel(name model.Name, mf *manifest.Manifest) (api.ListModelRespons
QuantizationLevel: cfg.FileType,
ContextLength: cfg.ContextLen,
EmbeddingLength: cfg.EmbedLen,
+ Runner: runner,
},
}
- m, err := GetModel(name.String())
- if err != nil {
- // A model that will not load is the one a user most needs to see, in
- // order to remove it. Report what the manifest says.
- slog.Warn("could not load model to describe it", "model", name.String(), "error", err)
+ // A model that will not load is the one a user most needs to see, in
+ // order to remove it. Report what the manifest says.
+ if m == nil {
return summary, nil
}
summary.Details.ParentModel = m.ParentModel
@@ -128,6 +246,15 @@ func isUnknownQuantization(quantization string) bool {
func sortListModelResponses(models []api.ListModelResponse) {
slices.SortStableFunc(models, func(i, j api.ListModelResponse) int {
// Preserve the existing /api/tags order: most recently modified first.
- return cmp.Compare(j.ModifiedAt.Unix(), i.ModifiedAt.Unix())
+ if c := j.ModifiedAt.Compare(i.ModifiedAt); c != 0 {
+ return c
+ }
+ // Rows that share an mtime (manifest-list children under one parent,
+ // models created within the same instant) would otherwise follow map
+ // iteration order; tie-break so row order is deterministic.
+ if c := cmp.Compare(i.Name, j.Name); c != 0 {
+ return c
+ }
+ return cmp.Compare(i.Digest, j.Digest)
})
}
diff --git a/server/model_resolver.go b/server/model_resolver.go
index cbbeffa37..4929e306d 100644
--- a/server/model_resolver.go
+++ b/server/model_resolver.go
@@ -1,7 +1,11 @@
package server
import (
+ "fmt"
+ "strings"
+
"github.com/ollama/ollama/internal/modelref"
+ "github.com/ollama/ollama/manifest"
"github.com/ollama/ollama/types/model"
)
@@ -40,6 +44,9 @@ func parseAndValidateModelRef(raw string) (parsedModelRef, error) {
if err != nil {
return zero, err
}
+ if ref, ok, err := parseDigestModelRef(parsed); ok || err != nil {
+ return ref, err
+ }
name := model.ParseName(parsed.Base)
if !name.IsValid() {
@@ -79,3 +86,68 @@ func parseNormalizePullModelRef(raw string) (parsedModelRef, error) {
Source: parsedRef.Source,
}, nil
}
+
+func parseDeleteModelRef(raw string) (parsedModelRef, error) {
+ parsedRef, err := modelref.ParseRef(raw)
+ if err != nil {
+ return parsedModelRef{}, err
+ }
+ if ref, ok, err := parseDigestModelRef(parsedRef); ok || err != nil {
+ return ref, err
+ }
+
+ return parseNormalizePullModelRef(raw)
+}
+
+func parseDigestModelRef(parsed modelref.ParsedRef) (parsedModelRef, bool, error) {
+ name, ok, err := digestModelName(parsed.Base)
+ if !ok || err != nil {
+ return parsedModelRef{}, ok, err
+ }
+ if parsed.Source == modelSourceCloud {
+ return parsedModelRef{}, true, fmt.Errorf("digest references are local: %s", parsed.Original)
+ }
+
+ return parsedModelRef{
+ Original: parsed.Original,
+ Base: name.DisplayShortest(),
+ Name: name,
+ Source: parsed.Source,
+ }, true, nil
+}
+
+func digestModelName(ref string) (model.Name, bool, error) {
+ if runner, digestRef, ok := strings.Cut(ref, ":"); ok {
+ if normalized, err := normalizeRunner(runner); err == nil && normalized != "" {
+ digest, ok, err := manifest.ResolveDigestReference(digestRef)
+ if !ok || err != nil {
+ return model.Name{}, ok, err
+ }
+ name, err := runnerDigestModelName(digest, normalized)
+ return name, true, err
+ }
+ }
+
+ digest, ok, err := manifest.ResolveDigestReference(ref)
+ if !ok || err != nil {
+ return model.Name{}, ok, err
+ }
+ return digestReferenceName(digest), true, nil
+}
+
+func runnerDigestModelName(digest, runner string) (model.Name, error) {
+ name := digestReferenceName(digest)
+ m, err := manifest.ParseNamedManifestForRunner(name, runner)
+ if err != nil {
+ return model.Name{}, err
+ }
+ if selected := m.SelectedDigest(); selected != "" && !manifest.SameDigest(digest, selected) {
+ name = digestReferenceName(selected)
+ }
+ return name, nil
+}
+
+func digestReferenceName(digest string) model.Name {
+ digest = strings.ToLower(strings.Replace(digest, ":", "-", 1))
+ return model.ParseName(digest)
+}
diff --git a/server/model_show_cache.go b/server/model_show_cache.go
index a779d0f6c..f829e4774 100644
--- a/server/model_show_cache.go
+++ b/server/model_show_cache.go
@@ -29,10 +29,11 @@ metadata, quantization details, remote metadata, and model-specific fields.
TODO(parthsareen): Consider removing show cache if /api/tags grows to cover
the remaining callers.
-Local model entries are stored lazily by canonical model name and verbose flag,
-with the manifest digest recorded in the entry. The manifest digest is the
-freshness boundary: if the model content changes, the digest changes, so the
-previous response is replaced instead of accumulating under an old digest key.
+Local model entries are stored lazily by canonical model name, runner, and
+verbose flag, with the manifest digest recorded in the entry. The manifest
+digest is the freshness boundary: if the model content changes, the digest
+changes, so the previous response is replaced instead of accumulating under an
+old digest key.
Requests with System or Options overlays bypass the cache because those overlays
mutate the effective show response.
@@ -87,6 +88,7 @@ type modelShowCache struct {
// served and disappear on process restart.
type modelShowLocalKey struct {
Model string
+ Runner string
Verbose bool
}
@@ -203,11 +205,16 @@ func (c *modelShowCache) setLocal(key modelShowLocalKey, digest string, resp *ap
c.mu.Unlock()
}
-func (c *modelShowCache) hasLocal(key modelShowLocalKey, digest string) bool {
- c.mu.RLock()
- entry, ok := c.local[key]
- c.mu.RUnlock()
- return ok && entry.Digest == digest && entry.Response != nil
+func (c *modelShowCache) invalidateLocal(name model.Name) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ modelName := name.String()
+ for key := range c.local {
+ if key.Model == modelName {
+ delete(c.local, key)
+ }
+ }
}
func (c *modelShowCache) getCloud(key modelShowCloudKey) (*api.ShowResponse, bool) {
@@ -290,48 +297,6 @@ func (c *modelShowCache) refreshCloud(ctx context.Context, key modelShowCloudKey
return nil
}
-// hydrateLocal scans manifests at startup and refreshes only entries missing
-// for the current digest. It hydrates non-verbose responses only, avoiding an
-// expensive tensor walk for users who have never asked for verbose show data.
-func (c *modelShowCache) hydrateLocal(ctx context.Context) error {
- manifests, err := manifest.Manifests(true)
- if err != nil {
- return err
- }
-
- for name, mf := range manifests {
- if err := ctx.Err(); err != nil {
- return err
- }
-
- if modelShowManifestIsRemote(mf) {
- continue
- }
-
- modelName := name.String()
- digest := mf.Digest()
- key := modelShowLocalKey{
- Model: modelName,
- Verbose: false,
- }
- if c.hasLocal(key, digest) {
- continue
- }
-
- resp, err := c.getModelInfo(api.ShowRequest{Model: modelName})
- if err != nil {
- slog.Warn("failed to hydrate local model show cache", "model", modelName, "error", err)
- continue
- }
- if resp.RemoteHost != "" {
- continue
- }
-
- c.setLocal(key, digest, resp)
- }
- return nil
-}
-
// hydrateCloud refreshes cloud show entries by listing cloud tags and fetching
// /api/show for each returned model with bounded concurrency. Per-model show
// failures are logged and skipped so one bad cloud entry does not prevent the
@@ -525,22 +490,28 @@ func modelShowStatusError(resp *http.Response, body []byte) error {
// on-disk model name and returns the current manifest digest used to validate
// the cached entry.
func modelShowLocalKeyForRequest(req api.ShowRequest) (modelShowLocalKey, string, error) {
+ runner, err := normalizeRunner(req.Runner)
+ if err != nil {
+ return modelShowLocalKey{}, "", err
+ }
+
name := model.ParseName(req.Model)
if !name.IsValid() {
return modelShowLocalKey{}, "", model.Unqualified(name)
}
- name, err := getExistingName(name)
+ name, err = getExistingName(name)
if err != nil {
return modelShowLocalKey{}, "", err
}
- mf, err := manifest.ParseNamedManifest(name)
+ mf, err := manifest.ParseNamedManifestForRunner(name, runner)
if err != nil {
return modelShowLocalKey{}, "", err
}
return modelShowLocalKey{
Model: name.String(),
+ Runner: runner,
Verbose: req.Verbose,
}, mf.Digest(), nil
}
@@ -565,30 +536,6 @@ func modelShowNormalizeCloudModel(modelName string) string {
return modelName
}
-// modelShowManifestIsRemote checks whether a manifest represents a local stub
-// for a remote model. Startup hydration skips these so the local content cache
-// does not store entries whose freshness is governed by cloud state.
-func modelShowManifestIsRemote(mf *manifest.Manifest) bool {
- if mf == nil || mf.Config.Digest == "" {
- return false
- }
-
- f, err := mf.Config.Open()
- if err != nil {
- slog.Warn("failed to open manifest config while checking model show cache eligibility", "error", err)
- return false
- }
- defer f.Close()
-
- var cfg model.ConfigV2
- if err := json.NewDecoder(f).Decode(&cfg); err != nil {
- slog.Warn("failed to decode manifest config while checking model show cache eligibility", "error", err)
- return false
- }
-
- return cfg.RemoteHost != "" || cfg.RemoteModel != ""
-}
-
// cloneShowResponse deep-copies mutable fields of api.ShowResponse before
// storing or returning cached entries. The response contains maps and slices,
// and some handlers mutate ModelInfo before writing JSON.
@@ -602,6 +549,7 @@ func cloneShowResponse(in *api.ShowResponse) *api.ShowResponse {
out.Details.Families = slices.Clone(in.Details.Families)
out.Messages = cloneMessages(in.Messages)
out.Capabilities = slices.Clone(in.Capabilities)
+ out.Manifests = slices.Clone(in.Manifests)
out.ModelInfo = cloneAnyMap(in.ModelInfo)
out.ProjectorInfo = cloneAnyMap(in.ProjectorInfo)
out.Tensors = cloneTensors(in.Tensors)
diff --git a/server/model_show_cache_test.go b/server/model_show_cache_test.go
index 70312d648..d4ce8a335 100644
--- a/server/model_show_cache_test.go
+++ b/server/model_show_cache_test.go
@@ -117,34 +117,43 @@ func TestModelShowCacheLocalVerboseVariantsAreSeparate(t *testing.T) {
}
}
-func TestModelShowCacheLocalHydrationSkipsUnchangedInMemory(t *testing.T) {
+func TestModelShowCacheLocalKeyUsesRunnerSelectionAndParentDigest(t *testing.T) {
gin.SetMode(gin.TestMode)
- setTestHome(t, t.TempDir())
- createShowCacheModel(t, "show-cache-hydrate", map[string]any{"test.context_length": uint32(1024)})
-
- cache := newModelShowCache()
- calls := 0
- cache.getModelInfo = func(req api.ShowRequest) (*api.ShowResponse, error) {
- calls++
- return showCacheTestResponse(calls, req.Verbose), nil
- }
-
- if err := cache.hydrateLocal(context.Background()); err != nil {
- t.Fatalf("first hydrateLocal failed: %v", err)
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ writeShowManifestVariant(t, "show-cache-mlx", manifest.RunnerMLX, manifest.FormatSafetensors, modelpkg.ConfigV2{
+ ModelFormat: manifest.FormatSafetensors,
+ Capabilities: []string{"completion"},
+ }, nil)
+ writeShowManifestVariant(t, "show-cache-ggml", manifest.RunnerGGML, manifest.FormatGGUF, modelpkg.ConfigV2{
+ ModelFormat: manifest.FormatGGUF,
+ Capabilities: []string{"completion"},
+ }, map[string]any{"test.context_length": uint32(1024)})
+
+ writeManifestListFixture(t, "show-cache-list",
+ manifestListFixtureChild{name: "show-cache-mlx", runner: manifest.RunnerMLX, format: manifest.FormatSafetensors},
+ manifestListFixtureChild{name: "show-cache-ggml", runner: manifest.RunnerGGML, format: manifest.FormatGGUF},
+ )
+
+ key, digest, err := modelShowLocalKeyForRequest(api.ShowRequest{
+ Model: "show-cache-list",
+ Runner: manifest.RunnerMLX,
+ })
+ if err != nil {
+ t.Fatal(err)
}
- if err := cache.hydrateLocal(context.Background()); err != nil {
- t.Fatalf("second hydrateLocal failed: %v", err)
+ if key.Runner != manifest.RunnerMLX {
+ t.Fatalf("runner = %q, want %q", key.Runner, manifest.RunnerMLX)
}
- resp, err := cache.GetLocal(api.ShowRequest{Model: "show-cache-hydrate"})
+ parent, err := manifest.ParseNamedManifestForRunner(modelpkg.ParseName("show-cache-list"), manifest.RunnerMLX)
if err != nil {
- t.Fatalf("GetLocal after hydration failed: %v", err)
+ t.Fatal(err)
}
-
- if calls != 1 {
- t.Fatalf("getModelInfo calls after unchanged in-memory hydration = %d, want 1", calls)
+ if digest != parent.Digest() {
+ t.Fatalf("digest = %q, want parent manifest-list digest %q", digest, parent.Digest())
}
- if resp.ModelInfo["call"] != 1 {
- t.Fatalf("hydrated call marker = %v, want 1", resp.ModelInfo["call"])
+ if digest == parent.SelectedDigest() {
+ t.Fatalf("digest = selected child digest %q; want parent digest so available-runners changes invalidate the cache", digest)
}
}
diff --git a/server/routes.go b/server/routes.go
index 6ca00a2e0..249187dbb 100644
--- a/server/routes.go
+++ b/server/routes.go
@@ -33,6 +33,7 @@ import (
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/auth"
+ "github.com/ollama/ollama/compatmigrate"
"github.com/ollama/ollama/discover"
"github.com/ollama/ollama/envconfig"
"github.com/ollama/ollama/format"
@@ -210,13 +211,52 @@ func usesAutomaticNumBatch(model *Model, requestOpts map[string]any) bool {
return true
}
+func normalizeRunner(runner string) (string, error) {
+ switch strings.ToLower(strings.TrimSpace(runner)) {
+ case "":
+ return "", nil
+ case manifest.RunnerMLX, "mlxrunner":
+ return manifest.RunnerMLX, nil
+ case manifest.RunnerGGML:
+ return manifest.RunnerGGML, nil
+ case manifest.RunnerLlamaCPP, "llama.cpp", "llama-cpp", "llama_cpp":
+ return manifest.RunnerLlamaCPP, nil
+ default:
+ return "", fmt.Errorf("unknown runner %q", runner)
+ }
+}
+
// scheduleRunner schedules a runner after validating inputs such as capabilities and model options.
// It returns the allocated runner, model instance, and consolidated options if successful and error otherwise.
-func (s *Server) scheduleRunner(ctx context.Context, model *Model, caps []model.Capability, requestOpts map[string]any, keepAlive *api.Duration, shift *bool) (llm.LlamaServer, *Model, *api.Options, error) {
- if model == nil || model.Name == "" {
+func (s *Server) scheduleRunner(ctx context.Context, name, selectedRunner string, caps []model.Capability, requestOpts map[string]any, keepAlive *api.Duration, shift *bool) (llm.LlamaServer, *Model, *api.Options, error) {
+ if name == "" {
return nil, nil, nil, fmt.Errorf("model %w", errRequired)
}
+ parsedName := model.ParseName(name)
+ if parsedName.IsValid() {
+ existingName, err := getExistingName(parsedName)
+ if err != nil {
+ return nil, nil, nil, err
+ }
+ name = existingName.String()
+ }
+ selectedName := model.ParseName(name)
+
+ model, err := GetModelForRunner(name, selectedRunner)
+ if err != nil {
+ return nil, nil, nil, err
+ }
+ if !manifest.IsDigestReferenceName(selectedName) {
+ runner := model.Runner
+ if runner == "" && model.isGGUF() {
+ runner = manifest.RunnerGGML
+ }
+ if runner == manifest.RunnerGGML {
+ compatmigrate.StartLocalCompatibilityMigration(selectedName)
+ }
+ }
+
if slices.Contains(model.Config.ModelFamilies, "mllama") && len(model.ProjectorPaths) > 0 {
return nil, nil, nil, fmt.Errorf("'llama3.2-vision' is no longer compatible with your version of Ollama and has been replaced by a newer version. To re-download, run 'ollama pull llama3.2-vision'")
}
@@ -293,10 +333,18 @@ func (s *Server) GenerateHandler(c *gin.Context) {
// TODO(drifkin): evaluate an `/api/*` passthrough for cloud where the
// original body (modulo model name normalization) is sent to cloud.
req.Model = modelRef.Base
+ req.Runner = ""
proxyCloudJSONRequest(c, req, cloudErrRemoteInferenceUnavailable)
return
}
+ if runner, err := normalizeRunner(req.Runner); err != nil {
+ c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ } else {
+ req.Runner = runner
+ }
+
name := modelRef.Name
// We cannot currently consolidate this into GetModel because all we'll
@@ -307,11 +355,13 @@ func (s *Server) GenerateHandler(c *gin.Context) {
return
}
- m, err := GetModel(name.String())
+ m, err := GetModelForRunner(name.String(), req.Runner)
if err != nil {
switch {
case errors.Is(err, fs.ErrNotExist):
c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
+ case errors.Is(err, manifest.ErrNoCompatibleManifest):
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
case err.Error() == errtypes.InvalidModelNameErrMsg:
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
default:
@@ -351,6 +401,7 @@ func (s *Server) GenerateHandler(c *gin.Context) {
}
req.Model = m.Config.RemoteModel
+ req.Runner = ""
if req.Template == "" && m.Template.String() != "" {
req.Template = m.Template.String()
@@ -499,7 +550,7 @@ func (s *Server) GenerateHandler(c *gin.Context) {
}
}
- r, m, opts, err := s.scheduleRunner(c.Request.Context(), m, caps, req.Options, req.KeepAlive, req.Shift)
+ r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), req.Runner, caps, req.Options, req.KeepAlive, req.Shift)
if errors.Is(err, errCapabilityCompletion) {
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("%q does not support generate", req.Model)})
return
@@ -858,10 +909,18 @@ func (s *Server) EmbedHandler(c *gin.Context) {
if modelRef.Source == modelSourceCloud {
req.Model = modelRef.Base
+ req.Runner = ""
proxyCloudJSONRequest(c, req, cloudErrRemoteInferenceUnavailable)
return
}
+ if runner, err := normalizeRunner(req.Runner); err != nil {
+ c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ } else {
+ req.Runner = runner
+ }
+
var input []string
switch i := req.Input.(type) {
@@ -890,13 +949,7 @@ func (s *Server) EmbedHandler(c *gin.Context) {
return
}
- m, err := GetModel(name.String())
- if err != nil {
- handleScheduleError(c, req.Model, err)
- return
- }
-
- r, m, opts, err := s.scheduleRunner(c.Request.Context(), m, []model.Capability{}, req.Options, req.KeepAlive, nil)
+ r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), req.Runner, []model.Capability{}, req.Options, req.KeepAlive, nil)
if err != nil {
handleScheduleError(c, req.Model, err)
return
@@ -1096,19 +1149,21 @@ func (s *Server) EmbeddingsHandler(c *gin.Context) {
if modelRef.Source == modelSourceCloud {
req.Model = modelRef.Base
+ req.Runner = ""
proxyCloudJSONRequest(c, req, cloudErrRemoteInferenceUnavailable)
return
}
- name := modelRef.Name
-
- m, err := GetModel(name.String())
- if err != nil {
- handleScheduleError(c, req.Model, err)
+ if runner, err := normalizeRunner(req.Runner); err != nil {
+ c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
+ } else {
+ req.Runner = runner
}
- r, m, _, err := s.scheduleRunner(c.Request.Context(), m, []model.Capability{}, req.Options, req.KeepAlive, nil)
+ name := modelRef.Name
+
+ r, m, _, err := s.scheduleRunner(c.Request.Context(), name.String(), req.Runner, []model.Capability{}, req.Options, req.KeepAlive, nil)
if err != nil {
handleScheduleError(c, req.Model, err)
return
@@ -1169,6 +1224,12 @@ func (s *Server) PullHandler(c *gin.Context) {
return
}
+ runner, err := normalizeRunner(req.Runner)
+ if err != nil {
+ c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ }
+
ch := make(chan any)
go func() {
defer close(ch)
@@ -1183,10 +1244,14 @@ func (s *Server) PullHandler(c *gin.Context) {
ctx, cancel := context.WithCancel(c.Request.Context())
defer cancel()
- if err := PullModel(ctx, name.DisplayShortest(), regOpts, fn); err != nil {
+ if err := PullModel(ctx, name.DisplayShortest(), runner, regOpts, fn); err != nil {
ch <- gin.H{"error": err.Error()}
return
}
+
+ if s.modelCaches != nil && s.modelCaches.show != nil {
+ s.modelCaches.show.invalidateLocal(name)
+ }
}()
if req.Stream != nil && !*req.Stream {
@@ -1258,6 +1323,10 @@ func (s *Server) PushHandler(c *gin.Context) {
// is.
func getExistingName(n model.Name) (model.Name, error) {
var zero model.Name
+ if manifest.IsDigestReferenceName(n) {
+ return n, nil
+ }
+
existing, err := manifest.Manifests(true)
if err != nil {
return zero, err
@@ -1324,7 +1393,7 @@ func (s *Server) DeleteHandler(c *gin.Context) {
return
}
- modelRef, err := parseNormalizePullModelRef(cmp.Or(r.Model, r.Name))
+ modelRef, err := parseDeleteModelRef(cmp.Or(r.Model, r.Name))
if err != nil {
switch {
case errors.Is(err, errConflictingModelSource):
@@ -1343,7 +1412,7 @@ func (s *Server) DeleteHandler(c *gin.Context) {
return
}
- m, err := manifest.ParseNamedManifest(n)
+ removed, err := manifest.RemoveNamed(n)
if err != nil {
switch {
case os.IsNotExist(err):
@@ -1353,18 +1422,7 @@ func (s *Server) DeleteHandler(c *gin.Context) {
}
return
}
-
- if err := m.Remove(); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
- return
- }
-
- removed, err := m.RemoveLayers()
removeGGUFMetadata(removed...)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
- return
- }
}
func (s *Server) ShowHandler(c *gin.Context) {
@@ -1397,6 +1455,8 @@ func (s *Server) ShowHandler(c *gin.Context) {
if modelRef.Source == modelSourceCloud {
req.Model = modelRef.Base
+ req.Runner = ""
+ req.AllManifests = false
if modelShowCacheable(req) && s.modelCaches != nil && s.modelCaches.show != nil {
if disabled, _ := internalcloud.Status(); disabled {
c.JSON(http.StatusForbidden, gin.H{"error": internalcloud.DisabledError(cloudErrRemoteModelDetailsUnavailable)})
@@ -1416,6 +1476,15 @@ func (s *Server) ShowHandler(c *gin.Context) {
return
}
+ if req.Runner, err = normalizeRunner(req.Runner); err != nil {
+ c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ }
+ if req.AllManifests && req.Runner != "" {
+ c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "runner cannot be used with all_manifests"})
+ return
+ }
+
name := modelRef.Name
name, err = getExistingName(name)
if err != nil {
@@ -1425,23 +1494,24 @@ func (s *Server) ShowHandler(c *gin.Context) {
req.Model = name.DisplayShortest()
var resp *api.ShowResponse
+ if req.AllManifests {
+ resp, err := GetAllManifestsInfo(req)
+ if err != nil {
+ writeShowError(c, req.Model, err)
+ return
+ }
+
+ c.JSON(http.StatusOK, resp)
+ return
+ }
+
if modelShowCacheable(req) && s.modelCaches != nil && s.modelCaches.show != nil {
resp, err = s.modelCaches.show.GetLocal(req)
} else {
resp, err = GetModelInfo(req)
}
if err != nil {
- var statusErr api.StatusError
- switch {
- case os.IsNotExist(err):
- c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
- case errors.As(err, &statusErr):
- c.JSON(statusErr.StatusCode, gin.H{"error": statusErr.ErrorMessage})
- case err.Error() == errtypes.InvalidModelNameErrMsg:
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
- default:
- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
- }
+ writeShowError(c, req.Model, err)
return
}
@@ -1464,16 +1534,25 @@ func (s *Server) ShowHandler(c *gin.Context) {
}
func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
+ runner, err := normalizeRunner(req.Runner)
+ if err != nil {
+ return nil, api.StatusError{
+ StatusCode: http.StatusBadRequest,
+ ErrorMessage: err.Error(),
+ }
+ }
+ req.Runner = runner
+
name := model.ParseName(req.Model)
if !name.IsValid() {
return nil, model.Unqualified(name)
}
- name, err := getExistingName(name)
+ name, err = getExistingName(name)
if err != nil {
return nil, err
}
- m, err := GetModel(name.String())
+ m, err := GetModelForRunner(name.String(), req.Runner)
if err != nil {
return nil, err
}
@@ -1494,11 +1573,12 @@ func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
Families: m.Config.ModelFamilies,
ParameterSize: m.Config.ModelType,
QuantizationLevel: m.Config.FileType,
+ Runner: m.Runner,
}
// For safetensors LLM models, populate details from config.json.
if m.Config.ModelFormat == "safetensors" && slices.Contains(m.Config.Capabilities, "completion") {
- if info, err := getSafetensorsLLMInfo(name); err == nil {
+ if info, err := getSafetensorsLLMInfoForRunner(name, req.Runner); err == nil {
if arch, ok := info["general.architecture"].(string); ok && arch != "" {
modelDetails.Family = arch
}
@@ -1508,7 +1588,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 := getSafetensorsDtype(name); err == nil && dtype != "" {
+ if dtype, err := getSafetensorsDtypeForRunner(name, req.Runner); err == nil && dtype != "" {
modelDetails.QuantizationLevel = dtype
}
}
@@ -1523,7 +1603,7 @@ func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
msgs[i] = api.Message{Role: msg.Role, Content: msg.Content}
}
- mf, err := manifest.ParseNamedManifest(name)
+ mf, err := manifest.ParseNamedManifestForRunner(name, req.Runner)
if err != nil {
return nil, err
}
@@ -1543,6 +1623,12 @@ func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
ModelInfo: make(map[string]any),
}
+ if summaries, err := manifestSummariesForShow(name, mf.SelectedDigest()); err != nil {
+ return nil, err
+ } else {
+ resp.Manifests = summaries
+ }
+
if m.Config.RemoteHost != "" {
resp.RemoteHost = m.Config.RemoteHost
resp.RemoteModel = m.Config.RemoteModel
@@ -1610,12 +1696,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 := getSafetensorsLLMInfo(name); err == nil {
+ if info, err := getSafetensorsLLMInfoForRunner(name, req.Runner); err == nil {
resp.ModelInfo = info
}
// Populate tensor info if verbose
if req.Verbose {
- if tensors, err := getSafetensorsTensorInfo(name); err == nil {
+ if tensors, err := getSafetensorsTensorInfoForRunner(name, req.Runner); err == nil {
resp.Tensors = tensors
}
}
@@ -1628,7 +1714,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 := getSafetensorsTensorInfo(name); err == nil {
+ if tensors, err := getSafetensorsTensorInfoForRunner(name, req.Runner); err == nil {
resp.Tensors = tensors
}
}
@@ -1647,7 +1733,7 @@ func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
}
}
- modelInfo := kvData.Values()
+ modelInfo := jsonSafeValues(kvData)
delete(modelInfo, "general.name")
delete(modelInfo, "tokenizer.chat_template")
resp.ModelInfo = modelInfo
@@ -1669,7 +1755,7 @@ func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
if err != nil {
return nil, err
}
- projectorInfo := projectorData.Values()
+ projectorInfo := jsonSafeValues(projectorData)
resp.ProjectorInfo = projectorInfo
}
@@ -1722,12 +1808,17 @@ func (s *Server) CopyHandler(c *gin.Context) {
return
}
- src := model.ParseName(r.Source)
- if !src.IsValid() {
+ srcRef, err := parseAndValidateModelRef(r.Source)
+ if err != nil {
+ c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("source %q is invalid", r.Source)})
+ return
+ }
+ if srcRef.Source == modelSourceCloud {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("source %q is invalid", r.Source)})
return
}
- src, err := getExistingName(src)
+ src := srcRef.Name
+ src, err = getExistingName(src)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
@@ -1744,10 +1835,16 @@ func (s *Server) CopyHandler(c *gin.Context) {
return
}
- if err := CopyModel(src, dst); errors.Is(err, os.ErrNotExist) {
+ warning, err := CopyModel(src, dst)
+ switch {
+ case errors.Is(err, os.ErrNotExist):
c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model %q not found", r.Source)})
- } else if err != nil {
+ case errors.Is(err, manifest.ErrNoCompatibleManifest):
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ case err != nil:
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+ default:
+ c.JSON(http.StatusOK, api.ProgressResponse{Status: cmp.Or(warning, "success")})
}
}
@@ -2031,13 +2128,15 @@ func Serve(ln net.Listener) error {
return err
}
- manifestsPath, err := manifest.Path()
- if err != nil {
- return err
- }
+ for _, rootFn := range []func() (string, error){manifest.Path, manifest.V2Path} {
+ manifestsPath, err := rootFn()
+ if err != nil {
+ return err
+ }
- if err := manifest.PruneDirectory(manifestsPath); err != nil {
- return err
+ if err := manifest.PruneDirectory(manifestsPath); err != nil && !os.IsNotExist(err) {
+ return err
+ }
}
}
}
@@ -2336,6 +2435,22 @@ func (s *Server) PsHandler(c *gin.Context) {
for _, v := range s.sched.loadedModels() {
m := v.model
displayName := model.ParseName(m.ShortName).DisplayShortest()
+ digest := m.ManifestDigest
+ if digest == "" {
+ digest = m.Digest
+ }
+ runner := v.runner
+ if runner == "" {
+ runner = m.Runner
+ }
+ if runner == "" {
+ // Legacy manifests predate runner metadata; report the default
+ // the scheduler applies for the config's weight format.
+ runner, _ = manifest.MetadataForConfig(m.Config)
+ }
+ if normalized, err := normalizeRunner(runner); err == nil && normalized != "" {
+ runner = normalized
+ }
modelDetails := api.ModelDetails{
Format: m.Config.ModelFormat,
Family: m.Config.ModelFamily,
@@ -2344,16 +2459,19 @@ func (s *Server) PsHandler(c *gin.Context) {
QuantizationLevel: m.Config.FileType,
}
- models = append(models, api.ProcessModelResponse{
+ mr := api.ProcessModelResponse{
Model: displayName,
Name: displayName,
Size: v.size,
SizeVRAM: v.sizeVRAM,
- Digest: m.Digest,
+ Digest: digest,
Details: modelDetails,
ExpiresAt: v.expiresAt,
ContextLength: v.contextLength,
- })
+ Runner: runner,
+ }
+
+ models = append(models, mr)
}
slices.SortStableFunc(models, func(i, j api.ProcessModelResponse) int {
@@ -2548,6 +2666,7 @@ func (s *Server) ChatHandler(c *gin.Context) {
if modelRef.Source == modelSourceCloud {
req.Model = modelRef.Base
+ req.Runner = ""
if c.GetBool(cloudWebSearchOrchestrationKey) {
proxyCloudJSONRequestWithPath(c, req, "/api/chat", cloudErrRemoteInferenceUnavailable)
return
@@ -2556,6 +2675,13 @@ func (s *Server) ChatHandler(c *gin.Context) {
return
}
+ if runner, err := normalizeRunner(req.Runner); err != nil {
+ c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ } else {
+ req.Runner = runner
+ }
+
name := modelRef.Name
name, err = getExistingName(name)
@@ -2564,11 +2690,13 @@ func (s *Server) ChatHandler(c *gin.Context) {
return
}
- m, err := GetModel(name.String())
+ m, err := GetModelForRunner(name.String(), req.Runner)
if err != nil {
switch {
case os.IsNotExist(err):
c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
+ case errors.Is(err, manifest.ErrNoCompatibleManifest):
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
case err.Error() == errtypes.InvalidModelNameErrMsg:
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
default:
@@ -2622,6 +2750,7 @@ func (s *Server) ChatHandler(c *gin.Context) {
}
req.Model = m.Config.RemoteModel
+ req.Runner = ""
if req.Options == nil {
req.Options = map[string]any{}
}
@@ -2728,7 +2857,7 @@ func (s *Server) ChatHandler(c *gin.Context) {
}
}
- r, m, opts, err := s.scheduleRunner(c.Request.Context(), m, caps, req.Options, req.KeepAlive, req.Shift)
+ r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), req.Runner, caps, req.Options, req.KeepAlive, req.Shift)
if errors.Is(err, errCapabilityCompletion) {
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("%q does not support chat", req.Model)})
return
@@ -3130,6 +3259,8 @@ func handleScheduleError(c *gin.Context, name string, err error) {
switch {
case errors.Is(err, errCapabilities), errors.Is(err, errRequired):
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ case errors.Is(err, manifest.ErrNoCompatibleManifest):
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
case errors.Is(err, context.Canceled):
c.JSON(499, gin.H{"error": "request canceled"})
case errors.Is(err, ErrMaxQueue):
diff --git a/server/routes_cloud_test.go b/server/routes_cloud_test.go
index 6ca8929cb..a5c33df1d 100644
--- a/server/routes_cloud_test.go
+++ b/server/routes_cloud_test.go
@@ -179,7 +179,7 @@ func TestExplicitCloudPassthroughAPIAndV1(t *testing.T) {
local := httptest.NewServer(router)
defer local.Close()
- reqBody := `{"model":"kimi-k2.5:cloud","prompt":"hello","stream":false}`
+ reqBody := `{"model":"kimi-k2.5:cloud","prompt":"hello","stream":false,"runner":"bad"}`
req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, local.URL+"/api/generate", bytes.NewBufferString(reqBody))
if err != nil {
t.Fatal(err)
@@ -205,6 +205,9 @@ func TestExplicitCloudPassthroughAPIAndV1(t *testing.T) {
if !strings.Contains(capture.body, `"model":"kimi-k2.5"`) {
t.Fatalf("expected normalized model in upstream body, got %q", capture.body)
}
+ if strings.Contains(capture.body, `"runner"`) {
+ t.Fatalf("expected local-only runner to be omitted from upstream body, got %q", capture.body)
+ }
if got := capture.header.Get("X-Test-Header"); got != "api-header" {
t.Fatalf("expected forwarded X-Test-Header=api-header, got %q", got)
@@ -231,7 +234,7 @@ func TestExplicitCloudPassthroughAPIAndV1(t *testing.T) {
local := httptest.NewServer(router)
defer local.Close()
- reqBody := `{"model":"kimi-k2.5:cloud","messages":[{"role":"user","content":"hello"}],"stream":false}`
+ reqBody := `{"model":"kimi-k2.5:cloud","messages":[{"role":"user","content":"hello"}],"stream":false,"runner":"bad"}`
req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, local.URL+"/api/chat", bytes.NewBufferString(reqBody))
if err != nil {
t.Fatal(err)
@@ -259,6 +262,9 @@ func TestExplicitCloudPassthroughAPIAndV1(t *testing.T) {
if !strings.Contains(capture.body, `"model":"kimi-k2.5"`) {
t.Fatalf("expected normalized model in upstream body, got %q", capture.body)
}
+ if strings.Contains(capture.body, `"runner"`) {
+ t.Fatalf("expected local-only runner to be omitted from upstream body, got %q", capture.body)
+ }
})
t.Run("api embed", func(t *testing.T) {
@@ -363,7 +369,7 @@ func TestExplicitCloudPassthroughAPIAndV1(t *testing.T) {
local := httptest.NewServer(router)
defer local.Close()
- reqBody := `{"model":"kimi-k2.5:cloud"}`
+ reqBody := `{"model":"kimi-k2.5:cloud","runner":"bad","all_manifests":true}`
req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, local.URL+"/api/show", bytes.NewBufferString(reqBody))
if err != nil {
t.Fatal(err)
@@ -388,6 +394,9 @@ func TestExplicitCloudPassthroughAPIAndV1(t *testing.T) {
if !strings.Contains(capture.body, `"model":"kimi-k2.5"`) {
t.Fatalf("expected normalized model in upstream body, got %q", capture.body)
}
+ if strings.Contains(capture.body, `"runner"`) || strings.Contains(capture.body, `"all_manifests"`) {
+ t.Fatalf("expected local-only manifest selectors to be omitted from upstream body, got %q", capture.body)
+ }
})
t.Run("v1 chat completions bypasses conversion", func(t *testing.T) {
diff --git a/server/routes_create_test.go b/server/routes_create_test.go
index b382034bc..e83bb38df 100644
--- a/server/routes_create_test.go
+++ b/server/routes_create_test.go
@@ -26,6 +26,7 @@ import (
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/create"
+ "github.com/ollama/ollama/envconfig"
"github.com/ollama/ollama/fs/gguf"
st "github.com/ollama/ollama/fs/safetensors"
gguftest "github.com/ollama/ollama/internal/testutil/gguf"
@@ -752,12 +753,44 @@ func checkFileExists(t *testing.T, p string, expect []string) {
if err != nil {
t.Fatal(err)
}
+ if strings.HasSuffix(filepath.ToSlash(p), "/blobs/*") {
+ actual = slices.DeleteFunc(actual, isManifestBlobForTest)
+ }
if diff := gocmp.Diff(expect, actual, gocmpopts.SortSlices(strings.Compare), gocmpopts.EquateEmpty()); diff != "" {
t.Errorf("file exists mismatch (-want +got):\n%s", diff)
}
}
+func checkManifestFiles(t *testing.T, names ...string) {
+ t.Helper()
+
+ expect := make([]string, len(names))
+ for i, name := range names {
+ p, err := manifest.V2PathForName(model.ParseName(name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ expect[i] = p
+ }
+
+ checkFileExists(t, filepath.Join(envconfig.Models(), "manifests-v2", "*", "*", "*", "*"), expect)
+}
+
+func isManifestBlobForTest(path string) bool {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return false
+ }
+
+ var m manifest.Manifest
+ if err := json.Unmarshal(data, &m); err != nil {
+ return false
+ }
+
+ return m.SchemaVersion != 0 && m.MediaType != "" && (m.Config.Digest != "" || len(m.Layers) > 0)
+}
+
func TestCreateFromBin(t *testing.T) {
gin.SetMode(gin.TestMode)
@@ -779,9 +812,7 @@ func TestCreateFromBin(t *testing.T) {
t.Fatalf("expected status code 200, actual %d", w.Code)
}
- checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
- })
+ checkManifestFiles(t, "test")
checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
filepath.Join(p, "blobs", "sha256-eb4aa77a05d4846c309cc5ccf00a3eeda12d4d207bde3ec2b597bed8a73c3a9d"),
@@ -855,9 +886,7 @@ func TestCreateFromModel(t *testing.T) {
t.Fatalf("expected status code 200, actual %d", w.Code)
}
- checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
- })
+ checkManifestFiles(t, "test")
w = createRequest(t, s.CreateHandler, api.CreateRequest{
Name: "test2",
@@ -869,10 +898,7 @@ func TestCreateFromModel(t *testing.T) {
t.Fatalf("expected status code 200, actual %d", w.Code)
}
- checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test2", "latest"),
- })
+ checkManifestFiles(t, "test", "test2")
checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
filepath.Join(p, "blobs", "sha256-eb4aa77a05d4846c309cc5ccf00a3eeda12d4d207bde3ec2b597bed8a73c3a9d"),
@@ -969,9 +995,7 @@ func TestCreateRemovesLayers(t *testing.T) {
t.Fatalf("expected status code 200, actual %d", w.Code)
}
- checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
- })
+ checkManifestFiles(t, "test")
checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
filepath.Join(p, "blobs", "sha256-89a2116c3a82d6a97f59f748d86ed4417214353fd178ee54df418fde32495fad"),
@@ -990,9 +1014,7 @@ func TestCreateRemovesLayers(t *testing.T) {
t.Fatalf("expected status code 200, actual %d", w.Code)
}
- checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
- })
+ checkManifestFiles(t, "test")
checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
filepath.Join(p, "blobs", "sha256-eb4aa77a05d4846c309cc5ccf00a3eeda12d4d207bde3ec2b597bed8a73c3a9d"),
@@ -1001,6 +1023,262 @@ func TestCreateRemovesLayers(t *testing.T) {
})
}
+func writeManifestListVariant(t *testing.T, name, modelFormat string) {
+ t.Helper()
+
+ configData, err := json.Marshal(model.ConfigV2{
+ ModelFormat: modelFormat,
+ Capabilities: []string{"completion"},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ configLayer, err := manifest.NewLayer(bytes.NewReader(configData), "application/vnd.docker.container.image.v1+json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ modelLayer, err := manifest.NewLayer(strings.NewReader(name+" layer"), "application/vnd.ollama.image.license")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if err := manifest.WriteManifest(model.ParseName(name), configLayer, []manifest.Layer{modelLayer}); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestCreateManifestList(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+ var s Server
+
+ writeManifestListVariant(t, "test-gguf", manifest.FormatGGUF)
+ writeManifestListVariant(t, "test-safetensors", manifest.FormatSafetensors)
+
+ w := createRequest(t, s.CreateHandler, api.CreateRequest{
+ Model: "test-list",
+ List: []string{"test-gguf", "test-safetensors"},
+ Stream: &stream,
+ })
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected status code 200, actual %d: %s", w.Code, w.Body.String())
+ }
+
+ data, err := manifest.ReadManifestData(model.ParseName("test-list"))
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ var parent manifest.Manifest
+ if err := json.Unmarshal(data, &parent); err != nil {
+ t.Fatal(err)
+ }
+ if parent.MediaType != manifest.MediaTypeManifestList {
+ t.Fatalf("mediaType = %q, want %q", parent.MediaType, manifest.MediaTypeManifestList)
+ }
+ if len(parent.Manifests) != 2 {
+ t.Fatalf("manifest count = %d, want 2", len(parent.Manifests))
+ }
+
+ selected, err := manifest.ParseNamedManifest(model.ParseName("test-list"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if selected.Config.Digest == "" {
+ t.Fatal("selected manifest is missing config")
+ }
+
+ mlxInfo, err := GetModelInfo(api.ShowRequest{Model: "test-list", Runner: manifest.RunnerMLX})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if mlxInfo.Details.Format != manifest.FormatSafetensors {
+ t.Fatalf("mlx show format = %q, want %q", mlxInfo.Details.Format, manifest.FormatSafetensors)
+ }
+
+ want := map[string]string{
+ manifest.RunnerGGML: manifest.FormatGGUF,
+ manifest.RunnerMLX: manifest.FormatSafetensors,
+ }
+ for _, child := range parent.Manifests {
+ if got := want[child.Runner]; got != child.Format {
+ t.Fatalf("child runner/format = %q/%q, want one of %v", child.Runner, child.Format, want)
+ }
+ if child.BlobDigest() == "" {
+ t.Fatal("child manifest reference is missing digest")
+ }
+ if child.Config.Digest != "" || len(child.Layers) != 0 {
+ t.Fatalf("child manifest reference embedded config/layers: config=%q layers=%d", child.Config.Digest, len(child.Layers))
+ }
+
+ childBlob, err := manifest.BlobsPath(child.BlobDigest())
+ if err != nil {
+ t.Fatal(err)
+ }
+ childData, err := os.ReadFile(childBlob)
+ if err != nil {
+ t.Fatalf("child manifest blob missing: %v", err)
+ }
+ var resolved manifest.Manifest
+ if err := json.Unmarshal(childData, &resolved); err != nil {
+ t.Fatal(err)
+ }
+ if resolved.Config.Digest == "" || len(resolved.Layers) == 0 {
+ t.Fatalf("resolved child manifest missing config/layers: config=%q layers=%d", resolved.Config.Digest, len(resolved.Layers))
+ }
+ }
+
+ // The legacy downgrade anchor must reference the manifest document blobs
+ // so a pre-manifest-list daemon cannot garbage-collect them.
+ legacyPath, err := manifest.LegacyPathForName(model.ParseName("test-list"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ legacyData, err := os.ReadFile(legacyPath)
+ if err != nil {
+ t.Fatalf("legacy downgrade anchor missing: %v", err)
+ }
+ var anchor manifest.Manifest
+ if err := json.Unmarshal(legacyData, &anchor); err != nil {
+ t.Fatal(err)
+ }
+ docLayers := make(map[string]string)
+ for _, layer := range anchor.Layers {
+ if layer.MediaType == manifest.MediaTypeManifestList || layer.MediaType == manifest.MediaTypeManifest {
+ docLayers[layer.Digest] = layer.MediaType
+ }
+ }
+ wantDocs := map[string]string{
+ "parent manifest list": manifest.MediaTypeManifestList,
+ "ggml child manifest": manifest.MediaTypeManifest,
+ "safetensors child manifest": manifest.MediaTypeManifest,
+ }
+ if len(docLayers) != len(wantDocs) {
+ t.Fatalf("anchor manifest document layers = %v, want %d documents", docLayers, len(wantDocs))
+ }
+ for digest := range docLayers {
+ if _, err := os.Stat(mustBlobsPath(t, digest)); err != nil {
+ t.Fatalf("anchor document %s missing: %v", digest, err)
+ }
+ }
+
+ // The anchor describes the GGML child, which is what a pre-manifest-list
+ // daemon would load itself.
+ if anchor.Runner != manifest.RunnerGGML {
+ t.Fatalf("anchor runner = %q, want %q", anchor.Runner, manifest.RunnerGGML)
+ }
+}
+
+func TestCreateManifestListRejectsAmbiguousChildren(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ for _, tt := range []struct {
+ name string
+ models []string
+ wantError string
+ }{
+ {
+ name: "duplicate digest",
+ models: []string{"test-gguf-a", "test-gguf-a"},
+ wantError: "resolve to the same manifest",
+ },
+ {
+ name: "duplicate runner",
+ models: []string{"test-gguf-a", "test-gguf-b"},
+ wantError: "use the same runner",
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+ var s Server
+
+ writeManifestListVariant(t, "test-gguf-a", manifest.FormatGGUF)
+ writeManifestListVariant(t, "test-gguf-b", manifest.FormatGGUF)
+
+ w := createRequest(t, s.CreateHandler, api.CreateRequest{
+ Model: "test-list",
+ List: tt.models,
+ Stream: &stream,
+ })
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("status code = %d, want 400: %s", w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), tt.wantError) {
+ t.Fatalf("error = %s, want substring %q", w.Body.String(), tt.wantError)
+ }
+ })
+ }
+}
+
+func TestCreateManifestListRejectsInvalidRequests(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ req api.CreateRequest
+ wantError string
+ }{
+ {
+ name: "empty list",
+ req: api.CreateRequest{},
+ wantError: "must contain at least one model",
+ },
+ {
+ name: "from",
+ req: api.CreateRequest{
+ List: []string{"test-gguf", "test-safetensors"},
+ From: "base-model",
+ },
+ wantError: "cannot be combined",
+ },
+ {
+ name: "draft files",
+ req: api.CreateRequest{
+ List: []string{"test-gguf", "test-safetensors"},
+ DraftFiles: map[string]string{"draft.gguf": "sha256-test"},
+ },
+ wantError: "cannot be combined",
+ },
+ {
+ name: "template",
+ req: api.CreateRequest{
+ List: []string{"test-gguf", "test-safetensors"},
+ Template: "{{ .Prompt }}",
+ },
+ wantError: "cannot be combined",
+ },
+ {
+ name: "renderer",
+ req: api.CreateRequest{
+ List: []string{"test-gguf", "test-safetensors"},
+ Renderer: "qwen3",
+ },
+ wantError: "cannot be combined",
+ },
+ {
+ name: "quantize",
+ req: api.CreateRequest{
+ List: []string{"test-gguf", "test-safetensors"},
+ Quantize: "Q4_K_M",
+ },
+ wantError: "cannot be combined",
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ err := validateCreateManifestListRequest(tt.req)
+ if err == nil {
+ t.Fatal("expected error")
+ }
+ if !strings.Contains(err.Error(), tt.wantError) {
+ t.Fatalf("error = %v, want substring %q", err, tt.wantError)
+ }
+ var requestErr manifestListRequestError
+ if !errors.As(err, &requestErr) {
+ t.Fatalf("error = %T, want manifestListRequestError so CreateHandler responds with %d", err, http.StatusBadRequest)
+ }
+ })
+ }
+}
+
func TestCreateUnsetsSystem(t *testing.T) {
gin.SetMode(gin.TestMode)
@@ -1020,9 +1298,7 @@ func TestCreateUnsetsSystem(t *testing.T) {
t.Fatalf("expected status code 200, actual %d", w.Code)
}
- checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
- })
+ checkManifestFiles(t, "test")
checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
filepath.Join(p, "blobs", "sha256-eb4aa77a05d4846c309cc5ccf00a3eeda12d4d207bde3ec2b597bed8a73c3a9d"),
@@ -1041,9 +1317,7 @@ func TestCreateUnsetsSystem(t *testing.T) {
t.Fatalf("expected status code 200, actual %d", w.Code)
}
- checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
- })
+ checkManifestFiles(t, "test")
checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
filepath.Join(p, "blobs", "sha256-eb4aa77a05d4846c309cc5ccf00a3eeda12d4d207bde3ec2b597bed8a73c3a9d"),
@@ -1074,9 +1348,7 @@ func TestCreateMergeParameters(t *testing.T) {
t.Fatalf("expected status code 200, actual %d", w.Code)
}
- checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
- })
+ checkManifestFiles(t, "test")
checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
filepath.Join(p, "blobs", "sha256-1d0ad71299d48c2fb7ae2b98e683643e771f8a5b72be34942af90d97a91c1e37"),
@@ -1099,10 +1371,7 @@ func TestCreateMergeParameters(t *testing.T) {
t.Fatalf("expected status code 200, actual %d", w.Code)
}
- checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test2", "latest"),
- })
+ checkManifestFiles(t, "test", "test2")
// Display contents of each blob in the directory
blobDir := filepath.Join(p, "blobs")
@@ -1157,10 +1426,7 @@ func TestCreateMergeParameters(t *testing.T) {
t.Fatalf("expected status code 200, actual %d", w.Code)
}
- checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test2", "latest"),
- })
+ checkManifestFiles(t, "test", "test2")
checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
filepath.Join(p, "blobs", "sha256-12f58bb75cb3042d69a7e013ab87fb3c3c7088f50ddc62f0c77bd332f0d44d35"),
@@ -1216,9 +1482,7 @@ func TestCreateReplacesMessages(t *testing.T) {
t.Fatalf("expected status code 200, actual %d", w.Code)
}
- checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
- })
+ checkManifestFiles(t, "test")
checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
filepath.Join(p, "blobs", "sha256-298baeaf6928a60cf666d88d64a1ba606feb43a2865687c39e40652e407bffc4"),
@@ -1250,10 +1514,7 @@ func TestCreateReplacesMessages(t *testing.T) {
t.Fatalf("expected status code 200, actual %d", w.Code)
}
- checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test2", "latest"),
- })
+ checkManifestFiles(t, "test", "test2")
// Old layers will not have been pruned
checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
@@ -1310,9 +1571,7 @@ func TestCreateTemplateSystem(t *testing.T) {
t.Fatalf("expected status code 200, actual %d", w.Code)
}
- checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
- })
+ checkManifestFiles(t, "test")
checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
filepath.Join(p, "blobs", "sha256-eb4aa77a05d4846c309cc5ccf00a3eeda12d4d207bde3ec2b597bed8a73c3a9d"),
@@ -1537,9 +1796,7 @@ func TestCreateLicenses(t *testing.T) {
t.Fatalf("expected status code 200, actual %d", w.Code)
}
- checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
- })
+ checkManifestFiles(t, "test")
checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
filepath.Join(p, "blobs", "sha256-2af71558e438db0b73a20beab92dc278a94e1bbe974c00c1a33e3ab62d53a608"),
@@ -1867,10 +2124,29 @@ func TestDetectModelTypeFromFiles(t *testing.T) {
}
})
- t.Run("mixed model types", func(t *testing.T) {
+ t.Run("safetensors file with sidecars", func(t *testing.T) {
+ p := t.TempDir()
+ t.Setenv("OLLAMA_MODELS", p)
+
+ configDigest := createTestBlob(t, []byte(`{"model_type":"test"}`))
files := map[string]string{
- "model.gguf": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "model.safetensors": "sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "model.safetensors": "sha256:abc123",
+ "config.json": configDigest,
+ }
+
+ modelType, err := detectModelTypeFromFiles(files)
+ if err != nil {
+ t.Fatalf("detectModelTypeFromFiles() error = %v", err)
+ }
+ if modelType != "safetensors" {
+ t.Fatalf("expected model type 'safetensors', got %q", modelType)
+ }
+ })
+
+ t.Run("mixed file types", func(t *testing.T) {
+ files := map[string]string{
+ "model.gguf": "sha256:abc123",
+ "model.safetensors": "sha256:def456",
}
_, err := detectModelTypeFromFiles(files)
@@ -2957,3 +3233,206 @@ func TestCreateFromSafetensorsModel_PreservesLayerNames(t *testing.T) {
t.Error("tokenizer.json layer name not preserved in derived model")
}
}
+
+func mustBlobsPath(t *testing.T, digest string) string {
+ t.Helper()
+
+ path, err := manifest.BlobsPath(digest)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return path
+}
+
+func writeDriftVariant(t *testing.T, name, format string, config model.ConfigV2) {
+ t.Helper()
+
+ configData, err := json.Marshal(config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ configLayer, err := manifest.NewLayer(bytes.NewReader(configData), "application/vnd.docker.container.image.v1+json")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ var layers []manifest.Layer
+ switch format {
+ case manifest.FormatGGUF:
+ _, digest := createBinFile(t, map[string]any{"general.architecture": "test"}, nil)
+ modelLayer, err := manifest.NewLayerFromLayer(digest, "application/vnd.ollama.image.model", name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ layers = append(layers, modelLayer)
+ case manifest.FormatSafetensors:
+ layers = append(layers, createShowSafetensorsLayer(t, name+".weight", []int64{2, 2}))
+ }
+
+ if err := manifest.WriteManifest(model.ParseName(name), configLayer, layers); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func driftWarnings(t *testing.T, name string, children []model.ConfigV2) []string {
+ t.Helper()
+
+ for i, child := range children {
+ writeDriftVariant(t, fmt.Sprintf("drift-%d", i), child.ModelFormat, child)
+ }
+
+ refs := make([]string, len(children))
+ for i := range children {
+ refs[i] = fmt.Sprintf("drift-%d", i)
+ }
+
+ var warnings []string
+ err := createManifestList(api.CreateRequest{Name: name, List: refs}, model.ParseName(name), func(resp api.ProgressResponse) {
+ if strings.HasPrefix(resp.Status, "warning:") {
+ warnings = append(warnings, resp.Status)
+ }
+ })
+ if err != nil {
+ t.Fatalf("createManifestList() error = %v", err)
+ }
+ return warnings
+}
+
+func TestCreateManifestListWarnsOnDrift(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ baseConfig := func(format string) model.ConfigV2 {
+ return model.ConfigV2{
+ ModelFormat: format,
+ ModelFamily: "testfam",
+ ModelFamilies: []string{"testfam"},
+ ModelType: "1B",
+ FileType: "Q4_K_M",
+ ContextLen: 8192,
+ EmbedLen: 2048,
+ Parser: "test",
+ Renderer: "test",
+ Capabilities: []string{"completion"},
+ }
+ }
+
+ tests := []struct {
+ name string
+ mutate func(config *model.ConfigV2)
+ wantSubstring string
+ }{
+ {
+ name: "context length drift",
+ mutate: func(config *model.ConfigV2) {
+ config.ContextLen = 131072
+ },
+ wantSubstring: "context length: drift-0=8192, drift-1=131072",
+ },
+ {
+ name: "model family drift",
+ mutate: func(config *model.ConfigV2) {
+ config.ModelFamily = "otherfam"
+ config.ModelFamilies = []string{"otherfam"}
+ },
+ wantSubstring: "model family: drift-0=testfam, drift-1=otherfam",
+ },
+ {
+ name: "parameter size drift",
+ mutate: func(config *model.ConfigV2) {
+ config.ModelType = "7B"
+ },
+ wantSubstring: "parameter size: drift-0=1B, drift-1=7B",
+ },
+ {
+ name: "quantization class drift",
+ mutate: func(config *model.ConfigV2) {
+ config.FileType = "Q8_0"
+ },
+ wantSubstring: "quantization class: drift-0=Q4_K_M (4-bit), drift-1=Q8_0 (8-bit)",
+ },
+ {
+ name: "parser drift",
+ mutate: func(config *model.ConfigV2) {
+ config.Parser = "other"
+ },
+ wantSubstring: "parser: drift-0=test, drift-1=other",
+ },
+ {
+ name: "renderer drift",
+ mutate: func(config *model.ConfigV2) {
+ config.Renderer = "other"
+ },
+ wantSubstring: "renderer: drift-0=test, drift-1=other",
+ },
+ {
+ name: "capabilities drift",
+ mutate: func(config *model.ConfigV2) {
+ config.Capabilities = []string{"completion", "tools"}
+ },
+ wantSubstring: "capabilities: drift-0=[completion], drift-1=[completion tools]",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ first := baseConfig(manifest.FormatGGUF)
+ second := baseConfig(manifest.FormatSafetensors)
+ tt.mutate(&second)
+
+ warnings := driftWarnings(t, "drift-test", []model.ConfigV2{first, second})
+ found := slices.ContainsFunc(warnings, func(w string) bool {
+ return strings.Contains(w, tt.wantSubstring)
+ })
+ if !found {
+ t.Fatalf("warnings = %v, want one containing %q", warnings, tt.wantSubstring)
+ }
+ })
+ }
+
+ t.Run("unset fields are not drift", func(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ first := baseConfig(manifest.FormatGGUF)
+ second := baseConfig(manifest.FormatSafetensors)
+ second.ModelFamily = ""
+ second.ModelFamilies = nil
+ second.ModelType = ""
+ second.ContextLen = 0
+ second.FileType = ""
+
+ warnings := driftWarnings(t, "drift-unset", []model.ConfigV2{first, second})
+ if len(warnings) != 0 {
+ t.Fatalf("warnings = %v, want none", warnings)
+ }
+ })
+
+ t.Run("same precision class is not drift", func(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ first := baseConfig(manifest.FormatGGUF)
+ second := baseConfig(manifest.FormatSafetensors)
+ second.FileType = "nvfp4"
+
+ warnings := driftWarnings(t, "drift-class", []model.ConfigV2{first, second})
+ for _, warning := range warnings {
+ if strings.Contains(warning, "quantization") {
+ t.Fatalf("warnings = %v, want no quantization warning", warnings)
+ }
+ }
+ })
+
+ t.Run("no drift is silent", func(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ first := baseConfig(manifest.FormatGGUF)
+ second := baseConfig(manifest.FormatSafetensors)
+
+ warnings := driftWarnings(t, "drift-clean", []model.ConfigV2{first, second})
+ if len(warnings) != 0 {
+ t.Fatalf("warnings = %v, want none", warnings)
+ }
+ })
+}
diff --git a/server/routes_delete_test.go b/server/routes_delete_test.go
index 0c9aa843d..1babe5860 100644
--- a/server/routes_delete_test.go
+++ b/server/routes_delete_test.go
@@ -42,10 +42,7 @@ func TestDelete(t *testing.T) {
t.Fatalf("expected status code 200, actual %d", w.Code)
}
- checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test", "latest"),
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test2", "latest"),
- })
+ checkManifestFiles(t, "test", "test2")
checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
filepath.Join(p, "blobs", "sha256-eb4aa77a05d4846c309cc5ccf00a3eeda12d4d207bde3ec2b597bed8a73c3a9d"),
@@ -59,9 +56,7 @@ func TestDelete(t *testing.T) {
t.Fatalf("expected status code 200, actual %d", w.Code)
}
- checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "test2", "latest"),
- })
+ checkManifestFiles(t, "test2")
checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{
filepath.Join(p, "blobs", "sha256-eb4aa77a05d4846c309cc5ccf00a3eeda12d4d207bde3ec2b597bed8a73c3a9d"),
@@ -75,7 +70,7 @@ func TestDelete(t *testing.T) {
t.Fatalf("expected status code 200, actual %d", w.Code)
}
- checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{})
+ checkManifestFiles(t)
checkFileExists(t, filepath.Join(p, "blobs", "*"), []string{})
}
@@ -108,7 +103,7 @@ func TestDeleteDuplicateLayers(t *testing.T) {
t.Errorf("expected status code 200, actual %d", w.Code)
}
- checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{})
+ checkManifestFiles(t)
}
func TestDeleteCloudSourceNormalizesToLegacyName(t *testing.T) {
@@ -128,14 +123,12 @@ func TestDeleteCloudSourceNormalizesToLegacyName(t *testing.T) {
t.Fatalf("expected status code 200, actual %d", w.Code)
}
- checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{
- filepath.Join(p, "manifests", "registry.ollama.ai", "library", "gpt-oss", "20b-cloud"),
- })
+ checkManifestFiles(t, "gpt-oss:20b-cloud")
w = createRequest(t, s.DeleteHandler, api.DeleteRequest{Name: "gpt-oss:20b:cloud"})
if w.Code != http.StatusOK {
t.Fatalf("expected status code 200, actual %d (%s)", w.Code, w.Body.String())
}
- checkFileExists(t, filepath.Join(p, "manifests", "*", "*", "*", "*"), []string{})
+ checkManifestFiles(t)
}
diff --git a/server/routes_generate_test.go b/server/routes_generate_test.go
index da350eead..846689f54 100644
--- a/server/routes_generate_test.go
+++ b/server/routes_generate_test.go
@@ -190,6 +190,91 @@ func newServerWithMockRunner(t *testing.T, mock *mockRunner) *Server {
return s
}
+func TestEmbeddingHandlersUseRunnerSelection(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ writeShowManifestVariant(t, "embed-ggml", manifest.RunnerGGML, manifest.FormatGGUF, model.ConfigV2{
+ ModelFormat: manifest.FormatGGUF,
+ Capabilities: []string{string(model.CapabilityEmbedding)},
+ }, map[string]any{
+ "general.architecture": "llama",
+ })
+ writeShowManifestVariant(t, "embed-mlx", manifest.RunnerMLX, manifest.FormatSafetensors, model.ConfigV2{
+ ModelFormat: manifest.FormatSafetensors,
+ Capabilities: []string{string(model.CapabilityEmbedding)},
+ }, nil)
+ writeManifestListFixture(t, "embed-list",
+ manifestListFixtureChild{name: "embed-ggml", runner: manifest.RunnerGGML, format: manifest.FormatGGUF},
+ manifestListFixtureChild{name: "embed-mlx", runner: manifest.RunnerMLX, format: manifest.FormatSafetensors},
+ )
+
+ tests := []struct {
+ name string
+ handler func(*Server) func(*gin.Context)
+ body any
+ }{
+ {
+ name: "embed",
+ handler: func(s *Server) func(*gin.Context) { return s.EmbedHandler },
+ body: api.EmbedRequest{
+ Model: "embed-list",
+ Runner: manifest.RunnerMLX,
+ Input: "",
+ },
+ },
+ {
+ name: "embeddings",
+ handler: func(s *Server) func(*gin.Context) { return s.EmbeddingsHandler },
+ body: api.EmbeddingRequest{
+ Model: "embed-list",
+ Runner: manifest.RunnerMLX,
+ Prompt: "",
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ selectedRunner := make(chan string, 1)
+ mock := &mockRunner{}
+ s := &Server{
+ sched: &Scheduler{
+ pendingReqCh: make(chan *LlmRequest, 1),
+ finishedReqCh: make(chan *LlmRequest, 1),
+ expiredCh: make(chan *runnerRef, 1),
+ unloadedCh: make(chan any, 1),
+ loaded: make(map[string]*runnerRef),
+ newServerFn: newMockServer(mock),
+ getGpuFn: getGpuFn,
+ getSystemInfoFn: getSystemInfoFn,
+ waitForRecovery: 250 * time.Millisecond,
+ loadFn: func(req *LlmRequest, _ ml.SystemInfo, _ []ml.DeviceInfo, _ bool) bool {
+ selectedRunner <- req.model.Runner
+ req.successCh <- &runnerRef{llama: mock}
+ return false
+ },
+ },
+ }
+ go s.sched.Run(t.Context())
+
+ w := createRequest(t, tt.handler(s), tt.body)
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d: %s", w.Code, http.StatusOK, w.Body.String())
+ }
+
+ select {
+ case got := <-selectedRunner:
+ if got != manifest.RunnerMLX {
+ t.Fatalf("scheduled runner = %q, want %q", got, manifest.RunnerMLX)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("timed out waiting for scheduler")
+ }
+ })
+ }
+}
+
func createMinimalGGUFModel(t *testing.T, s *Server, name string, kv gguftest.KV, tmpl string, info map[string]any) {
t.Helper()
diff --git a/server/routes_list_test.go b/server/routes_list_test.go
index 9417c6292..f12188e85 100644
--- a/server/routes_list_test.go
+++ b/server/routes_list_test.go
@@ -1,12 +1,14 @@
package server
import (
+ "bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"slices"
+ "strings"
"testing"
"time"
@@ -106,7 +108,7 @@ func TestOpenAIListMatchesTagsModels(t *testing.T) {
t.Helper()
parsed := model.ParseName(name)
- path, err := manifest.PathForName(parsed)
+ path, err := manifest.ResolvePathForName(parsed)
if err != nil {
t.Fatalf("manifest path for %s: %v", name, err)
}
@@ -171,3 +173,279 @@ func TestOpenAIListMatchesTagsModels(t *testing.T) {
t.Fatalf("first /v1/models id = %q, want %q", got, want)
}
}
+
+// makeManifestListConfig writes a minimal model config blob for format and
+// returns its layer.
+func makeManifestListConfig(t *testing.T, format string) manifest.Layer {
+ t.Helper()
+
+ data, err := json.Marshal(model.ConfigV2{ModelFormat: format})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ layer, err := manifest.NewLayer(bytes.NewReader(data), "application/vnd.docker.container.image.v1+json")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ return layer
+}
+
+type manifestListFixtureChild struct {
+ name string
+ runner string
+ format string
+}
+
+// writeManifestListFixture assembles a manifest list named name from
+// already-written child manifests and writes it. It returns the parsed child
+// manifests in the same order as children so callers can inspect their
+// digests and layers.
+func writeManifestListFixture(t *testing.T, name string, children ...manifestListFixtureChild) []*manifest.Manifest {
+ t.Helper()
+
+ refs := make([]manifest.Manifest, 0, len(children))
+ manifests := make([]*manifest.Manifest, 0, len(children))
+ for _, child := range children {
+ m, err := manifest.ParseNamedManifestForRunner(model.ParseName(child.name), child.runner)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ref, err := manifest.NewManifestReference(m.BlobDigest(), child.runner, child.format)
+ if err != nil {
+ t.Fatal(err)
+ }
+ manifests = append(manifests, m)
+ refs = append(refs, ref)
+ }
+
+ parentData, err := json.Marshal(manifest.Manifest{
+ SchemaVersion: 2,
+ MediaType: manifest.MediaTypeManifestList,
+ Manifests: refs,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := manifest.WriteManifestData(model.ParseName(name), parentData); err != nil {
+ t.Fatal(err)
+ }
+
+ return manifests
+}
+
+func TestListIncludesManifestListChildrenAsSeparateRows(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ ggufConfig := makeManifestListConfig(t, manifest.FormatGGUF)
+ mlxConfig := makeManifestListConfig(t, manifest.FormatSafetensors)
+
+ sharedBlob, err := manifest.NewLayer(bytes.NewReader([]byte("shared-weights")), "application/vnd.ollama.image.model")
+ if err != nil {
+ t.Fatal(err)
+ }
+ ggufBlob, err := manifest.NewLayer(bytes.NewReader([]byte("gguf-weights")), "application/vnd.ollama.image.model")
+ if err != nil {
+ t.Fatal(err)
+ }
+ mlxBlob, err := manifest.NewLayer(bytes.NewReader([]byte("mlx-weights")), manifest.MediaTypeImageTensor)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ ggufLayers := []manifest.Layer{
+ sharedBlob,
+ ggufBlob,
+ }
+ if err := manifest.WriteManifestWithMetadata(model.ParseName("test-gguf"), ggufConfig, ggufLayers, manifest.RunnerGGML, manifest.FormatGGUF); err != nil {
+ t.Fatal(err)
+ }
+
+ mlxLayers := []manifest.Layer{
+ {
+ MediaType: manifest.MediaTypeImageTensor,
+ Digest: sharedBlob.Digest,
+ Size: sharedBlob.Size,
+ },
+ mlxBlob,
+ }
+ if err := manifest.WriteManifestWithMetadata(model.ParseName("test-mlx"), mlxConfig, mlxLayers, manifest.RunnerMLX, manifest.FormatSafetensors); err != nil {
+ t.Fatal(err)
+ }
+
+ children := writeManifestListFixture(t, "test-list",
+ manifestListFixtureChild{name: "test-gguf", runner: manifest.RunnerGGML, format: manifest.FormatGGUF},
+ manifestListFixtureChild{name: "test-mlx", runner: manifest.RunnerMLX, format: manifest.FormatSafetensors},
+ )
+ ggufManifest, mlxManifest := children[0], children[1]
+ parentPath, err := manifest.ResolvePathForName(model.ParseName("test-list"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ parentInfo, err := os.Lstat(parentPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ parentModified := parentInfo.ModTime()
+
+ s := Server{}
+
+ w := createRequest(t, s.ListHandler, nil)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected status code 200, actual %d", w.Code)
+ }
+
+ var resp api.ListResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatal(err)
+ }
+
+ var listed []api.ListModelResponse
+ for i := range resp.Models {
+ if resp.Models[i].Name == "test-list:latest" {
+ listed = append(listed, resp.Models[i])
+ }
+ }
+ if len(listed) != 2 {
+ t.Fatalf("test-list:latest rows = %d, want 2: %+v", len(listed), listed)
+ }
+
+ wantSizes := map[string]int64{
+ strings.TrimPrefix(ggufManifest.BlobDigest(), "sha256:"): ggufConfig.Size + sharedBlob.Size + ggufBlob.Size,
+ strings.TrimPrefix(mlxManifest.BlobDigest(), "sha256:"): mlxConfig.Size + sharedBlob.Size + mlxBlob.Size,
+ }
+ wantRunners := map[string]string{
+ strings.TrimPrefix(ggufManifest.BlobDigest(), "sha256:"): manifest.RunnerGGML,
+ strings.TrimPrefix(mlxManifest.BlobDigest(), "sha256:"): manifest.RunnerMLX,
+ }
+ for _, row := range listed {
+ want, ok := wantSizes[row.Digest]
+ if !ok {
+ t.Fatalf("unexpected digest for test-list row: %+v", row)
+ }
+ if row.Size != want {
+ t.Fatalf("size for %s = %d, want %d", row.Digest, row.Size, want)
+ }
+ if !row.ModifiedAt.Equal(parentModified) {
+ t.Fatalf("modified_at for %s = %s, want parent %s", row.Digest, row.ModifiedAt, parentModified)
+ }
+ if row.Details.Runner != wantRunners[row.Digest] {
+ t.Fatalf("runner for %s = %q, want %q", row.Digest, row.Details.Runner, wantRunners[row.Digest])
+ }
+ delete(wantSizes, row.Digest)
+ }
+ if len(wantSizes) != 0 {
+ t.Fatalf("missing list rows for digests: %+v", wantSizes)
+ }
+}
+
+func TestBuildModelListSummaryRejectsInvalidRunner(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ cfg := makeManifestListConfig(t, manifest.FormatGGUF)
+ layer, err := manifest.NewLayer(bytes.NewReader([]byte("weights")), "application/vnd.ollama.image.model")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := manifest.WriteManifestWithMetadata(model.ParseName("test-invalid"), cfg, []manifest.Layer{layer}, "bad", manifest.FormatGGUF); err != nil {
+ t.Fatal(err)
+ }
+
+ mf, err := manifest.ParseNamedManifest(model.ParseName("test-invalid"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = displayRunnerForManifest(mf)
+ if err == nil || err.Error() != `unknown runner "bad"` {
+ t.Fatalf("error = %v, want unknown runner", err)
+ }
+}
+
+func TestCopyManifestListByNameAndChildDigest(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ ggufConfig := makeManifestListConfig(t, manifest.FormatGGUF)
+ mlxConfig := makeManifestListConfig(t, manifest.FormatSafetensors)
+
+ ggufBlob, err := manifest.NewLayer(bytes.NewReader([]byte("gguf-weights")), "application/vnd.ollama.image.model")
+ if err != nil {
+ t.Fatal(err)
+ }
+ mlxBlob, err := manifest.NewLayer(bytes.NewReader([]byte("mlx-weights")), manifest.MediaTypeImageTensor)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if err := manifest.WriteManifestWithMetadata(model.ParseName("copy-gguf"), ggufConfig, []manifest.Layer{ggufBlob}, manifest.RunnerGGML, manifest.FormatGGUF); err != nil {
+ t.Fatal(err)
+ }
+ if err := manifest.WriteManifestWithMetadata(model.ParseName("copy-mlx"), mlxConfig, []manifest.Layer{mlxBlob}, manifest.RunnerMLX, manifest.FormatSafetensors); err != nil {
+ t.Fatal(err)
+ }
+
+ children := writeManifestListFixture(t, "copy-list",
+ manifestListFixtureChild{name: "copy-gguf", runner: manifest.RunnerGGML, format: manifest.FormatGGUF},
+ manifestListFixtureChild{name: "copy-mlx", runner: manifest.RunnerMLX, format: manifest.FormatSafetensors},
+ )
+ ggufManifest := children[0]
+
+ var s Server
+ w := createRequest(t, s.CopyHandler, api.CopyRequest{
+ Source: "copy-list",
+ Destination: "copy-list-copy",
+ })
+ if w.Code != http.StatusOK {
+ t.Fatalf("copy manifest list status = %d, want 200: %s", w.Code, w.Body.String())
+ }
+ copiedList, err := manifest.ReadManifestData(model.ParseName("copy-list-copy"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var copiedParent manifest.Manifest
+ if err := json.Unmarshal(copiedList, &copiedParent); err != nil {
+ t.Fatal(err)
+ }
+ if copiedParent.MediaType != manifest.MediaTypeManifestList || len(copiedParent.Manifests) != 2 {
+ t.Fatalf("copied parent = %+v, want manifest list with 2 children", copiedParent)
+ }
+
+ childDigestRef := strings.Replace(ggufManifest.BlobDigest(), ":", "-", 1)
+ w = createRequest(t, s.CopyHandler, api.CopyRequest{
+ Source: childDigestRef,
+ Destination: "copy-child",
+ })
+ if w.Code != http.StatusOK {
+ t.Fatalf("copy child digest status = %d, want 200: %s", w.Code, w.Body.String())
+ }
+ copiedChild, err := manifest.ParseNamedManifest(model.ParseName("copy-child"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if copiedChild.MediaType == manifest.MediaTypeManifestList {
+ t.Fatal("copying a child digest produced a manifest list")
+ }
+ if copiedChild.BlobDigest() != ggufManifest.BlobDigest() {
+ t.Fatalf("copied child digest = %s, want %s", copiedChild.BlobDigest(), ggufManifest.BlobDigest())
+ }
+}
+
+func TestCopyRejectsExplicitCloudSource(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ createShowCacheModel(t, "copy-cloud", map[string]any{"test.context_length": uint32(1024)})
+
+ var s Server
+ w := createRequest(t, s.CopyHandler, api.CopyRequest{
+ Source: "copy-cloud:cloud",
+ Destination: "copy-cloud-local",
+ })
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("copy cloud source status = %d, want 400: %s", w.Code, w.Body.String())
+ }
+}
diff --git a/server/routes_test.go b/server/routes_test.go
index 458353d0f..d9c7219aa 100644
--- a/server/routes_test.go
+++ b/server/routes_test.go
@@ -20,6 +20,7 @@ import (
"sort"
"strings"
"testing"
+ "time"
"unicode"
"github.com/gin-gonic/gin"
@@ -33,6 +34,202 @@ import (
"github.com/ollama/ollama/version"
)
+func TestPsHandlerUsesRunningManifestAndRunner(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ childDigest := strings.Repeat("a", 64)
+ s := Server{
+ sched: &Scheduler{
+ loaded: map[string]*runnerRef{
+ "test": {
+ model: &Model{
+ ShortName: "test-model:latest",
+ Digest: strings.Repeat("b", 64),
+ ManifestDigest: childDigest,
+ Runner: manifest.RunnerMLX,
+ Config: model.ConfigV2{
+ ModelFormat: manifest.FormatSafetensors,
+ },
+ },
+ runner: manifest.RunnerMLX,
+ totalSize: 1024,
+ vramSize: 1024,
+ expiresAt: time.Now().Add(time.Hour),
+ sessionDuration: time.Hour,
+ },
+ },
+ },
+ }
+
+ w := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(w)
+ c.Request = httptest.NewRequest(http.MethodGet, "/api/ps", nil)
+
+ s.PsHandler(c)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d: %s", w.Code, http.StatusOK, w.Body.String())
+ }
+
+ var resp api.ProcessResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatal(err)
+ }
+ if len(resp.Models) != 1 {
+ t.Fatalf("model count = %d, want 1", len(resp.Models))
+ }
+ if resp.Models[0].Digest != childDigest {
+ t.Fatalf("digest = %q, want child digest %q", resp.Models[0].Digest, childDigest)
+ }
+ if resp.Models[0].Runner != manifest.RunnerMLX {
+ t.Fatalf("runner = %q, want %q", resp.Models[0].Runner, manifest.RunnerMLX)
+ }
+}
+
+func TestNormalizeRunner(t *testing.T) {
+ tests := []struct {
+ name string
+ runner string
+ want string
+ wantErr bool
+ }{
+ {name: "empty", runner: "", want: ""},
+ {name: "mlx", runner: "mlx", want: manifest.RunnerMLX},
+ {name: "mlxrunner alias", runner: "mlxrunner", want: manifest.RunnerMLX},
+ {name: "ggml", runner: "ggml", want: manifest.RunnerGGML},
+ {name: "llamacpp", runner: "llamacpp", want: manifest.RunnerLlamaCPP},
+ {name: "llama.cpp alias", runner: "llama.cpp", want: manifest.RunnerLlamaCPP},
+ {name: "llama-cpp alias", runner: "llama-cpp", want: manifest.RunnerLlamaCPP},
+ {name: "llama_cpp alias", runner: "llama_cpp", want: manifest.RunnerLlamaCPP},
+ {name: "trim and case fold", runner: " MLXRunner ", want: manifest.RunnerMLX},
+ {name: "unknown", runner: "bad", wantErr: true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := normalizeRunner(tt.runner)
+ if tt.wantErr {
+ if err == nil {
+ t.Fatal("expected error")
+ }
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got != tt.want {
+ t.Fatalf("runner = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestRouteHandlersRejectUnknownRunner(t *testing.T) {
+ tests := []struct {
+ name string
+ handler func(*Server) func(*gin.Context)
+ body any
+ }{
+ {
+ name: "generate",
+ handler: func(s *Server) func(*gin.Context) { return s.GenerateHandler },
+ body: api.GenerateRequest{
+ Model: "test",
+ Runner: "bad",
+ },
+ },
+ {
+ name: "chat",
+ handler: func(s *Server) func(*gin.Context) { return s.ChatHandler },
+ body: api.ChatRequest{
+ Model: "test",
+ Runner: "bad",
+ },
+ },
+ {
+ name: "embed",
+ handler: func(s *Server) func(*gin.Context) { return s.EmbedHandler },
+ body: api.EmbedRequest{
+ Model: "test",
+ Runner: "bad",
+ },
+ },
+ {
+ name: "embeddings",
+ handler: func(s *Server) func(*gin.Context) { return s.EmbeddingsHandler },
+ body: api.EmbeddingRequest{
+ Model: "test",
+ Runner: "bad",
+ },
+ },
+ {
+ name: "pull",
+ handler: func(s *Server) func(*gin.Context) { return s.PullHandler },
+ body: api.PullRequest{
+ Name: "test",
+ Runner: "bad",
+ },
+ },
+ {
+ name: "show",
+ handler: func(s *Server) func(*gin.Context) { return s.ShowHandler },
+ body: api.ShowRequest{
+ Model: "test",
+ Runner: "bad",
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+ var s Server
+
+ w := createRequest(t, tt.handler(&s), tt.body)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("status = %d, want %d: %s", w.Code, http.StatusBadRequest, w.Body.String())
+ }
+ if got := strings.TrimSpace(w.Body.String()); got != `{"error":"unknown runner \"bad\""}` {
+ t.Fatalf("response = %s", got)
+ }
+ })
+ }
+}
+
+func TestHandleScheduleErrorNoCompatibleManifest(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ w := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(w)
+
+ handleScheduleError(c, "test", fmt.Errorf("%w for runners: mlx", manifest.ErrNoCompatibleManifest))
+
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("status = %d, want %d: %s", w.Code, http.StatusBadRequest, w.Body.String())
+ }
+ if got := strings.TrimSpace(w.Body.String()); got != `{"error":"no compatible manifest found for runners: mlx"}` {
+ t.Fatalf("response = %s", got)
+ }
+}
+
+// Show answers a missing runner variant with 404 so the client's
+// show-then-pull path fetches it, unlike the schedule path above.
+func TestWriteShowErrorNoCompatibleManifest(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ w := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(w)
+
+ writeShowError(c, "test", fmt.Errorf("%w for runners: mlx", manifest.ErrNoCompatibleManifest))
+
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want %d: %s", w.Code, http.StatusNotFound, w.Body.String())
+ }
+ if got := strings.TrimSpace(w.Body.String()); got != `{"error":"no compatible manifest found for runners: mlx"}` {
+ t.Fatalf("response = %s", got)
+ }
+}
+
func createTestFile(t *testing.T, name string) (string, string) {
t.Helper()
@@ -261,7 +458,7 @@ func TestRoutes(t *testing.T) {
}
// Verify the model was deleted
- _, err := GetModel("model-to-delete")
+ _, err := GetModelForRunner("model-to-delete", "")
if err == nil || !os.IsNotExist(err) {
t.Errorf("expected model to be deleted, got error %v", err)
}
@@ -360,7 +557,7 @@ func TestRoutes(t *testing.T) {
t.Errorf("expected status code 200, got %d", resp.StatusCode)
}
- model, err := GetModel("t-bone")
+ model, err := GetModelForRunner("t-bone", "")
if err != nil {
t.Fatalf("failed to get model: %v", err)
}
@@ -387,7 +584,7 @@ func TestRoutes(t *testing.T) {
req.Body = io.NopCloser(bytes.NewReader(jsonData))
},
Expected: func(t *testing.T, resp *http.Response) {
- model, err := GetModel("beefsteak")
+ model, err := GetModelForRunner("beefsteak", "")
if err != nil {
t.Fatalf("failed to get model: %v", err)
}
@@ -554,6 +751,41 @@ func TestGetModelInfo_SafetensorsUsesStoredFileType(t *testing.T) {
}
}
+func TestGetModelInfoSafetensorsTensorInfoRequiresVerbose(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ writeShowManifestVariant(t, "show-safetensors-tensors", manifest.RunnerMLX, manifest.FormatSafetensors, model.ConfigV2{
+ ModelFormat: manifest.FormatSafetensors,
+ Capabilities: []string{"completion"},
+ }, nil)
+
+ resp, err := GetModelInfo(api.ShowRequest{
+ Model: "show-safetensors-tensors",
+ Runner: manifest.RunnerMLX,
+ })
+ if err != nil {
+ t.Fatalf("GetModelInfo() error = %v", err)
+ }
+ if len(resp.Tensors) != 0 {
+ t.Fatalf("non-verbose tensor count = %d, want 0", len(resp.Tensors))
+ }
+
+ resp, err = GetModelInfo(api.ShowRequest{
+ Model: "show-safetensors-tensors",
+ Runner: manifest.RunnerMLX,
+ Verbose: true,
+ })
+ if err != nil {
+ t.Fatalf("GetModelInfo(verbose) error = %v", err)
+ }
+ if len(resp.Tensors) != 1 {
+ t.Fatalf("verbose tensor count = %d, want 1", len(resp.Tensors))
+ }
+ if resp.Tensors[0].Name != "show-safetensors-tensors.weight" {
+ t.Fatalf("tensor name = %q, want %q", resp.Tensors[0].Name, "show-safetensors-tensors.weight")
+ }
+}
+
func TestGetModelInfoRepairsUnknownGGUFFileType(t *testing.T) {
t.Setenv("OLLAMA_MODELS", t.TempDir())
@@ -668,11 +900,14 @@ func TestManifestCaseSensitivity(t *testing.T) {
checkManifestList := func() {
t.Helper()
- mandir := filepath.Join(os.Getenv("OLLAMA_MODELS"), "manifests/")
+ mandir, err := manifest.V2Path()
+ if err != nil {
+ t.Fatalf("failed to resolve v2 manifest path: %v", err)
+ }
var entries []string
t.Logf("dir entries:")
fsys := os.DirFS(mandir)
- err := fs.WalkDir(fsys, ".", func(path string, info fs.DirEntry, err error) error {
+ err = fs.WalkDir(fsys, ".", func(path string, info fs.DirEntry, err error) error {
if err != nil {
return err
}
@@ -695,7 +930,14 @@ func TestManifestCaseSensitivity(t *testing.T) {
g := entries[0] // raw path
g = filepath.ToSlash(g)
- w := model.ParseName(wantStableName).Filepath()
+ wp, err := manifest.V2PathForName(model.ParseName(wantStableName))
+ if err != nil {
+ t.Fatalf("failed to resolve expected manifest path: %v", err)
+ }
+ w, err := filepath.Rel(mandir, wp)
+ if err != nil {
+ t.Fatalf("failed to make expected manifest path relative: %v", err)
+ }
w = filepath.ToSlash(w)
if g != w {
t.Errorf("\ngot: %s\nwant: %s", g, w)
@@ -826,6 +1068,360 @@ func TestShowTemplateUsesSelectedRuntimeTemplate(t *testing.T) {
}
}
+func createShowSafetensorsLayer(t *testing.T, tensorName string, shape []int64) manifest.Layer {
+ t.Helper()
+
+ header := map[string]any{
+ tensorName: map[string]any{
+ "dtype": "F32",
+ "shape": shape,
+ "data_offsets": []int64{0, 16},
+ },
+ }
+ headerData, err := json.Marshal(header)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ var buf bytes.Buffer
+ if err := binary.Write(&buf, binary.LittleEndian, uint64(len(headerData))); err != nil {
+ t.Fatal(err)
+ }
+ buf.Write(headerData)
+
+ layer, err := manifest.NewLayer(bytes.NewReader(buf.Bytes()), manifest.MediaTypeImageTensor)
+ if err != nil {
+ t.Fatal(err)
+ }
+ layer.Name = tensorName
+
+ return layer
+}
+
+func writeShowManifestVariant(t *testing.T, name, runner, format string, cfg model.ConfigV2, kv map[string]any, extraLayers ...manifest.Layer) {
+ t.Helper()
+
+ configData, err := json.Marshal(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ configLayer, err := manifest.NewLayer(bytes.NewReader(configData), "application/vnd.docker.container.image.v1+json")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ layers := make([]manifest.Layer, 0, len(extraLayers)+1)
+ switch format {
+ case manifest.FormatGGUF:
+ _, digest := createBinFile(t, kv, nil)
+ modelLayer, err := manifest.NewLayerFromLayer(digest, "application/vnd.ollama.image.model", name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ layers = append(layers, modelLayer)
+ case manifest.FormatSafetensors:
+ layers = append(layers, createShowSafetensorsLayer(t, name+".weight", []int64{2, 2}))
+ }
+
+ layers = append(layers, extraLayers...)
+ if err := manifest.WriteManifestWithMetadata(model.ParseName(name), configLayer, layers, runner, format); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestShowAllManifestsNonListReturnsSingleManifest(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ var s Server
+
+ _, digest := createBinFile(t, map[string]any{"general.architecture": "test"}, nil)
+ createRequest(t, s.CreateHandler, api.CreateRequest{
+ Name: "show-model",
+ Files: map[string]string{"model.gguf": digest},
+ })
+
+ w := createRequest(t, s.ShowHandler, api.ShowRequest{
+ Model: "show-model",
+ AllManifests: true,
+ })
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected status code 200, actual %d: %s", w.Code, w.Body.String())
+ }
+
+ var resp api.ShowManifestsResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatal(err)
+ }
+ if len(resp.Manifests) != 1 {
+ t.Fatalf("manifest count = %d, want 1", len(resp.Manifests))
+ }
+ // No compatibility detector fires for this GGUF, so it is llama.cpp's.
+ if resp.Manifests[0].Runner != manifest.RunnerLlamaCPP {
+ t.Fatalf("runner = %q, want %q", resp.Manifests[0].Runner, manifest.RunnerLlamaCPP)
+ }
+ if resp.Manifests[0].Details.Format != manifest.FormatGGUF {
+ t.Fatalf("format = %q, want %q", resp.Manifests[0].Details.Format, manifest.FormatGGUF)
+ }
+ if resp.Manifests[0].ModelInfo["general.architecture"] != "test" {
+ t.Fatalf("architecture = %v, want %q", resp.Manifests[0].ModelInfo["general.architecture"], "test")
+ }
+}
+
+func TestShowAllManifestsManifestListDedupesLicenses(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ licenseLayer, err := manifest.NewLayer(bytes.NewReader([]byte("Apache-2.0")), "application/vnd.ollama.image.license")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ writeShowManifestVariant(t, "show-mlx", manifest.RunnerMLX, manifest.FormatSafetensors, model.ConfigV2{
+ ModelFormat: manifest.FormatSafetensors,
+ ModelFamily: "qwen3_5_moe",
+ ModelType: "35.1B",
+ FileType: "nvfp4",
+ Requires: "0.19.0",
+ Capabilities: []string{"completion", "vision", "thinking", "tools"},
+ }, nil, licenseLayer)
+
+ writeShowManifestVariant(t, "show-ggml", manifest.RunnerGGML, manifest.FormatGGUF, model.ConfigV2{
+ ModelFormat: manifest.FormatGGUF,
+ ModelFamily: "qwen35moe",
+ ModelType: "36.0B",
+ FileType: "Q4_K_M",
+ Capabilities: []string{"completion", "vision", "thinking", "tools"},
+ }, map[string]any{"general.architecture": "qwen35moe"}, licenseLayer)
+
+ mlxManifest, err := manifest.ParseNamedManifestForRunner(model.ParseName("show-mlx"), manifest.RunnerMLX)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ggmlManifest, err := manifest.ParseNamedManifestForRunner(model.ParseName("show-ggml"), manifest.RunnerGGML)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ mlxRef, err := manifest.NewManifestReference(mlxManifest.BlobDigest(), manifest.RunnerMLX, manifest.FormatSafetensors)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ggmlRef, err := manifest.NewManifestReference(ggmlManifest.BlobDigest(), manifest.RunnerGGML, manifest.FormatGGUF)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ parentData, err := json.Marshal(manifest.Manifest{
+ SchemaVersion: 2,
+ MediaType: manifest.MediaTypeManifestList,
+ Manifests: []manifest.Manifest{mlxRef, ggmlRef},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := manifest.WriteManifestData(model.ParseName("show-list"), parentData); err != nil {
+ t.Fatal(err)
+ }
+
+ var s Server
+ w := createRequest(t, s.ShowHandler, api.ShowRequest{
+ Model: "show-list",
+ AllManifests: true,
+ })
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected status code 200, actual %d: %s", w.Code, w.Body.String())
+ }
+
+ var resp api.ShowManifestsResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatal(err)
+ }
+ if len(resp.Manifests) != 2 {
+ t.Fatalf("manifest count = %d, want 2", len(resp.Manifests))
+ }
+ if resp.Manifests[0].Runner != manifest.RunnerMLX || resp.Manifests[1].Runner != manifest.RunnerGGML {
+ t.Fatalf("runner order = [%q %q], want [%q %q]", resp.Manifests[0].Runner, resp.Manifests[1].Runner, manifest.RunnerMLX, manifest.RunnerGGML)
+ }
+ if resp.License != "Apache-2.0" {
+ t.Fatalf("license = %q, want %q", resp.License, "Apache-2.0")
+ }
+ if resp.Manifests[0].License != "Apache-2.0" || resp.Manifests[1].License != "Apache-2.0" {
+ t.Fatalf("child licenses = [%q %q], want both Apache-2.0", resp.Manifests[0].License, resp.Manifests[1].License)
+ }
+ if resp.Manifests[0].Requires != "0.19.0" {
+ t.Fatalf("mlx requires = %q, want %q", resp.Manifests[0].Requires, "0.19.0")
+ }
+ if len(resp.Manifests[0].Tensors) != 0 {
+ t.Fatalf("non-verbose mlx tensor count = %d, want 0", len(resp.Manifests[0].Tensors))
+ }
+
+ w = createRequest(t, s.ShowHandler, api.ShowRequest{
+ Model: "show-list",
+ AllManifests: true,
+ Verbose: true,
+ })
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected verbose status code 200, actual %d: %s", w.Code, w.Body.String())
+ }
+ resp = api.ShowManifestsResponse{}
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatal(err)
+ }
+ if len(resp.Manifests[0].Tensors) != 1 {
+ t.Fatalf("verbose mlx tensor count = %d, want 1", len(resp.Manifests[0].Tensors))
+ }
+ if resp.Manifests[0].Tensors[0].Name != "show-mlx.weight" {
+ t.Fatalf("mlx tensor name = %q, want %q", resp.Manifests[0].Tensors[0].Name, "show-mlx.weight")
+ }
+}
+
+func TestShowManifestListIncludesChildSummaries(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ writeShowManifestVariant(t, "show-mlx", manifest.RunnerMLX, manifest.FormatSafetensors, model.ConfigV2{
+ ModelFormat: manifest.FormatSafetensors,
+ ModelFamily: "qwen3_5_moe",
+ ModelType: "35.1B",
+ FileType: "nvfp4",
+ }, nil)
+
+ writeShowManifestVariant(t, "show-ggml", manifest.RunnerGGML, manifest.FormatGGUF, model.ConfigV2{
+ ModelFormat: manifest.FormatGGUF,
+ ModelFamily: "qwen35moe",
+ ModelType: "36.0B",
+ FileType: "Q4_K_M",
+ }, map[string]any{"general.architecture": "qwen35moe"})
+
+ mlxManifest, err := manifest.ParseNamedManifestForRunner(model.ParseName("show-mlx"), manifest.RunnerMLX)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ggmlManifest, err := manifest.ParseNamedManifestForRunner(model.ParseName("show-ggml"), manifest.RunnerGGML)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ mlxRef, err := manifest.NewManifestReference(mlxManifest.BlobDigest(), manifest.RunnerMLX, manifest.FormatSafetensors)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ggmlRef, err := manifest.NewManifestReference(ggmlManifest.BlobDigest(), manifest.RunnerGGML, manifest.FormatGGUF)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ parentData, err := json.Marshal(manifest.Manifest{
+ SchemaVersion: 2,
+ MediaType: manifest.MediaTypeManifestList,
+ Manifests: []manifest.Manifest{mlxRef, ggmlRef},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := manifest.WriteManifestData(model.ParseName("show-list"), parentData); err != nil {
+ t.Fatal(err)
+ }
+
+ var s Server
+ w := createRequest(t, s.ShowHandler, api.ShowRequest{
+ Model: "show-list",
+ Runner: manifest.RunnerGGML,
+ })
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected status code 200, actual %d: %s", w.Code, w.Body.String())
+ }
+
+ var resp api.ShowResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatal(err)
+ }
+ if len(resp.Manifests) != 2 {
+ t.Fatalf("manifest summary count = %d, want 2", len(resp.Manifests))
+ }
+ if resp.Details.Runner != manifest.RunnerGGML {
+ t.Fatalf("details runner = %q, want %q", resp.Details.Runner, manifest.RunnerGGML)
+ }
+ if resp.Manifests[0].Digest != mlxManifest.BlobDigest() || resp.Manifests[0].Runner != manifest.RunnerMLX {
+ t.Fatalf("first summary = %#v, want mlx %s", resp.Manifests[0], mlxManifest.BlobDigest())
+ }
+ if resp.Manifests[1].Digest != ggmlManifest.BlobDigest() || resp.Manifests[1].Runner != manifest.RunnerGGML || !resp.Manifests[1].Selected {
+ t.Fatalf("second summary = %#v, want selected ggml %s", resp.Manifests[1], ggmlManifest.BlobDigest())
+ }
+}
+
+func TestShowManifestListRejectsInvalidChildRunner(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ writeShowManifestVariant(t, "show-good", manifest.RunnerGGML, manifest.FormatGGUF, model.ConfigV2{
+ ModelFormat: manifest.FormatGGUF,
+ ModelFamily: "test",
+ ModelType: "1B",
+ }, map[string]any{"general.architecture": "test"})
+ writeShowManifestVariant(t, "show-bad", "bad", manifest.FormatGGUF, model.ConfigV2{
+ ModelFormat: manifest.FormatGGUF,
+ ModelFamily: "test",
+ ModelType: "1B",
+ }, map[string]any{"general.architecture": "test"})
+
+ goodManifest, err := manifest.ParseNamedManifestForRunner(model.ParseName("show-good"), manifest.RunnerGGML)
+ if err != nil {
+ t.Fatal(err)
+ }
+ badManifest, err := manifest.ParseNamedManifestForRunner(model.ParseName("show-bad"), "bad")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ goodRef, err := manifest.NewManifestReference(goodManifest.BlobDigest(), manifest.RunnerGGML, manifest.FormatGGUF)
+ if err != nil {
+ t.Fatal(err)
+ }
+ badRef, err := manifest.NewManifestReference(badManifest.BlobDigest(), "bad", manifest.FormatGGUF)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ parentData, err := json.Marshal(manifest.Manifest{
+ SchemaVersion: 2,
+ MediaType: manifest.MediaTypeManifestList,
+ Manifests: []manifest.Manifest{goodRef, badRef},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := manifest.WriteManifestData(model.ParseName("show-list"), parentData); err != nil {
+ t.Fatal(err)
+ }
+
+ var s Server
+ w := createRequest(t, s.ShowHandler, api.ShowRequest{
+ Model: "show-list",
+ Runner: manifest.RunnerGGML,
+ })
+ if w.Code != http.StatusInternalServerError {
+ t.Fatalf("expected status code 500, actual %d: %s", w.Code, w.Body.String())
+ }
+ if got := strings.TrimSpace(w.Body.String()); got != `{"error":"unknown runner \"bad\""}` {
+ t.Fatalf("response = %s", got)
+ }
+}
+
+func TestShowAllManifestsRejectsRunnerSelection(t *testing.T) {
+ var s Server
+
+ w := createRequest(t, s.ShowHandler, api.ShowRequest{
+ Model: "show-model",
+ Runner: manifest.RunnerMLX,
+ AllManifests: true,
+ })
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected status code 400, actual %d: %s", w.Code, w.Body.String())
+ }
+ if got := strings.TrimSpace(w.Body.String()); got != `{"error":"runner cannot be used with all_manifests"}` {
+ t.Fatalf("response = %s", got)
+ }
+}
+
func TestShowCopilotUserAgentOverwritesExistingBasename(t *testing.T) {
t.Setenv("OLLAMA_MODELS", t.TempDir())
@@ -1188,3 +1784,37 @@ func TestWaitForStream(t *testing.T) {
})
}
}
+
+func TestShowOmitsNonFiniteGGUFValues(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ var s Server
+
+ // Real models ship non-finite floats (gemma3n pads its
+ // activation_sparsity_scale with -Inf); the show response must still
+ // serialize.
+ _, digest := createBinFile(t, gguftest.KV{
+ "general.architecture": "test",
+ "test.activation_sparsity_scale": []float32{
+ 1.6448535, float32(math.Inf(-1)),
+ },
+ }, nil)
+
+ createRequest(t, s.CreateHandler, api.CreateRequest{
+ Name: "show-non-finite",
+ Files: map[string]string{"model.gguf": digest},
+ })
+
+ w := createRequest(t, s.ShowHandler, api.ShowRequest{Name: "show-non-finite"})
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected status code 200, actual %d: %s", w.Code, w.Body.String())
+ }
+
+ var resp api.ShowResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := resp.ModelInfo["test.activation_sparsity_scale"]; ok {
+ t.Fatalf("activation_sparsity_scale = %v, want omitted", resp.ModelInfo["test.activation_sparsity_scale"])
+ }
+}
diff --git a/server/sched.go b/server/sched.go
index 535491349..5f5cb51b8 100644
--- a/server/sched.go
+++ b/server/sched.go
@@ -22,6 +22,7 @@ import (
"github.com/ollama/ollama/fs/gguf"
"github.com/ollama/ollama/llm"
"github.com/ollama/ollama/logutil"
+ "github.com/ollama/ollama/manifest"
"github.com/ollama/ollama/ml"
"github.com/ollama/ollama/mlxrunner"
"github.com/ollama/ollama/types/model"
@@ -107,7 +108,8 @@ func InitScheduler(ctx context.Context) *Scheduler {
// schedulerModelKey returns the scheduler map key for a model.
// GGUF-backed models use ModelPath; safetensors/image models without a
-// ModelPath use manifest digest so distinct models don't collide.
+// ModelPath use the selected manifest digest so distinct child manifests don't
+// collide.
func schedulerModelKey(m *Model) string {
if m == nil {
return ""
@@ -119,6 +121,9 @@ func schedulerModelKey(m *Model) string {
}
return m.ModelPath
}
+ if m.ManifestDigest != "" {
+ return "manifest:" + m.ManifestDigest
+ }
if m.Digest != "" {
return "digest:" + m.Digest
}
@@ -698,6 +703,14 @@ iGPUScan:
req.opts.NumCtx = effectiveNumCtx
req.contextShift = resolveContextShift(req.shift, req.model)
}
+ runnerName := req.model.Runner
+ if req.model.IsMLX() && runnerName == "" {
+ runnerName = manifest.RunnerMLX
+ } else if llm.IsLlamaCPP(llama) {
+ // The loaded process is authoritative: a llama.cpp server may serve
+ // the model even when the manifest metadata says ggml.
+ runnerName = manifest.RunnerLlamaCPP
+ }
runner := &runnerRef{
model: req.model,
modelPath: req.model.ModelPath,
@@ -707,6 +720,7 @@ iGPUScan:
sessionDuration: sessionDuration,
gpus: gpuIDs,
discreteGPUs: discreteGPUs,
+ runner: runnerName,
totalSize: totalSize,
vramSize: vramSize,
loading: true,
@@ -1353,6 +1367,7 @@ type runnerRef struct {
loading bool // True only during initial load, then false forever
gpus []ml.DeviceID // Recorded at time of provisioning
discreteGPUs bool // True if all devices are discrete GPUs - used to skip VRAM recovery check for iGPUs
+ runner string
vramSize uint64
totalSize uint64
@@ -1727,10 +1742,21 @@ func (s *Scheduler) unloadAllRunners() {
func (s *Scheduler) expireRunner(model *Model) {
modelKey := schedulerModelKey(model)
+ var runners []*runnerRef
+
s.loadedMu.Lock()
- runner, ok := s.loaded[modelKey]
+ if runner, ok := s.loaded[modelKey]; ok {
+ runners = append(runners, runner)
+ } else if model != nil && model.Name != "" {
+ for _, runner := range s.loaded {
+ if runner.model != nil && runner.model.Name == model.Name {
+ runners = append(runners, runner)
+ }
+ }
+ }
s.loadedMu.Unlock()
- if ok {
+
+ for _, runner := range runners {
runner.refMu.Lock()
runner.expiresAt = time.Now()
if runner.expireTimer != nil {
@@ -1749,6 +1775,7 @@ func (s *Scheduler) expireRunner(model *Model) {
// use without holding any scheduler locks.
type loadedModel struct {
model *Model
+ runner string
size int64
sizeVRAM int64
contextLength int
@@ -1777,6 +1804,7 @@ func (s *Scheduler) loadedModels() []loadedModel {
}
lm := loadedModel{
model: r.model,
+ runner: r.runner,
size: int64(r.totalSize),
sizeVRAM: int64(r.vramSize),
expiresAt: r.expiresAt,
diff --git a/server/sched_test.go b/server/sched_test.go
index 829144f52..b16686bbf 100644
--- a/server/sched_test.go
+++ b/server/sched_test.go
@@ -13,6 +13,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/compatmigrate"
"github.com/ollama/ollama/format"
"github.com/ollama/ollama/fs/gguf"
gguftest "github.com/ollama/ollama/internal/testutil/gguf"
@@ -25,7 +26,10 @@ func TestMain(m *testing.M) {
os.Setenv("OLLAMA_DEBUG", "1")
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}))
slog.SetDefault(logger)
- os.Exit(m.Run())
+ restoreMigrators := compatmigrate.SetMigratorsForTesting(nil)
+ code := m.Run()
+ restoreMigrators()
+ os.Exit(code)
}
func TestSchedInit(t *testing.T) {
@@ -423,7 +427,7 @@ func TestSchedRequestsMultipleLoadedModels(t *testing.T) {
b.req.sessionDuration = &api.Duration{Duration: 5 * time.Millisecond}
c := newScenarioRequest(t, ctx, "model-c-10g-cpu", 10*format.GigaByte, nil, nil /* No GPU load */)
c.req.opts.NumGPU = 0 // CPU load, will be allowed
- b.req.sessionDuration = &api.Duration{Duration: 10 * time.Millisecond} // longer than b to cause the scheduler to favor unloading b over c
+ c.req.sessionDuration = &api.Duration{Duration: 10 * time.Millisecond} // longer than b to cause the scheduler to favor unloading b over c
d := newScenarioRequest(t, ctx, "model-d-10g-gpu", 13*format.GigaByte, nil, map[ml.DeviceID]uint64{{Library: "Metal"}: 13 * format.GigaByte}) // Needs prior unloaded
s.newServerFn = a.newServer
@@ -488,25 +492,25 @@ func TestSchedRequestsMultipleLoadedModels(t *testing.T) {
require.Len(t, s.loaded, 3)
s.loadedMu.Unlock()
a.ctxDone() // Won't help since this one isn't big enough to make room
- time.Sleep(2 * time.Millisecond)
s.pendingReqCh <- d.req
- // finish prior request, so new model can load
- time.Sleep(6 * time.Millisecond)
- s.loadedMu.Lock()
- require.Len(t, s.loaded, 2)
- s.loadedMu.Unlock()
- // Mark b done so it can unload
- b.ctxDone()
- // Report recovered VRAM usage so scheduler will finish waiting and unload
- time.Sleep(1 * time.Millisecond)
+ require.Eventually(t, func() bool {
+ s.loadedMu.Lock()
+ defer s.loadedMu.Unlock()
+ return len(s.loaded) == 2
+ }, 500*time.Millisecond, 10*time.Millisecond)
+
+ // Report recovered VRAM usage before releasing b so the next fit check sees it.
gMu.Lock()
g.FreeMemory = 24 * format.GigaByte
gMu.Unlock()
+ b.ctxDone()
select {
case resp := <-d.req.successCh:
require.Equal(t, resp.llama, d.srv)
require.Empty(t, s.pendingReqCh)
require.Empty(t, d.req.errCh)
+ case err := <-d.req.errCh:
+ t.Fatal(err.Error())
case <-ctx.Done():
t.Fatal("timeout")
}
@@ -619,6 +623,35 @@ func TestSchedulerModelKeyIncludesGGUFShards(t *testing.T) {
}
}
+func TestSchedGetRunnerUsesManifestDigestKeyWhenModelPathEmpty(t *testing.T) {
+ ctx, done := context.WithTimeout(t.Context(), 100*time.Millisecond)
+ defer done()
+
+ s := InitScheduler(ctx)
+ opts := api.DefaultOptions()
+ opts.NumCtx = 4
+
+ loadedModel := &Model{Name: "list", Digest: "parent", ManifestDigest: "child-a"}
+ loadedRunner := &runnerRef{
+ model: loadedModel,
+ modelKey: schedulerModelKey(loadedModel),
+ llama: &mockLlm{vramByGPU: map[ml.DeviceID]uint64{}},
+ Options: &opts,
+ numParallel: 1,
+ }
+
+ s.loadedMu.Lock()
+ s.loaded[loadedRunner.modelKey] = loadedRunner
+ s.loadedMu.Unlock()
+
+ reqModel := &Model{Name: "list", Digest: "parent", ManifestDigest: "child-b"}
+ successCh, errCh := s.getRunner(ctx, reqModel, opts, nil, false, false, nil)
+
+ require.Empty(t, successCh)
+ require.Empty(t, errCh)
+ require.Len(t, s.pendingReqCh, 1)
+}
+
func TestSchedGetRunnerReusesSameDigestWhenModelPathEmpty(t *testing.T) {
ctx, done := context.WithTimeout(t.Context(), 100*time.Millisecond)
defer done()
@@ -770,14 +803,15 @@ func TestSchedPrematureExpired(t *testing.T) {
t.Fatal("timeout")
}
time.Sleep(scenario1a.req.sessionDuration.Duration)
- scenario1a.ctxDone()
- time.Sleep(20 * time.Millisecond)
- require.LessOrEqual(t, len(s.finishedReqCh), 1)
- time.Sleep(10 * time.Millisecond)
- require.Empty(t, s.finishedReqCh)
s.loadedMu.Lock()
- require.Empty(t, s.loaded)
+ require.Len(t, s.loaded, 1)
s.loadedMu.Unlock()
+ scenario1a.ctxDone()
+ require.Eventually(t, func() bool {
+ s.loadedMu.Lock()
+ defer s.loadedMu.Unlock()
+ return len(s.loaded) == 0
+ }, 500*time.Millisecond, 10*time.Millisecond)
// also shouldn't happen in real life
s.finishedReqCh <- scenario1a.req
diff --git a/server/show_manifest.go b/server/show_manifest.go
new file mode 100644
index 000000000..390566417
--- /dev/null
+++ b/server/show_manifest.go
@@ -0,0 +1,251 @@
+package server
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "os"
+ "strings"
+
+ "github.com/gin-gonic/gin"
+
+ "github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/manifest"
+ "github.com/ollama/ollama/types/errtypes"
+ "github.com/ollama/ollama/types/model"
+)
+
+func writeShowError(c *gin.Context, model string, err error) {
+ var statusErr api.StatusError
+ switch {
+ case os.IsNotExist(err):
+ c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", model)})
+ case errors.Is(err, manifest.ErrNoCompatibleManifest):
+ // Not found rather than bad request: the client's show-then-pull path
+ // treats 404 as "fetch it", which is what a missing runner variant needs.
+ c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
+ case errors.As(err, &statusErr):
+ c.JSON(statusErr.StatusCode, gin.H{"error": statusErr.ErrorMessage})
+ case err.Error() == errtypes.InvalidModelNameErrMsg:
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ default:
+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+ }
+}
+
+func readBlobData(digest string) ([]byte, error) {
+ blobPath, err := manifest.BlobsPath(digest)
+ if err != nil {
+ return nil, err
+ }
+
+ return os.ReadFile(blobPath)
+}
+
+func resolveShowManifestChild(child manifest.Manifest) (*manifest.Manifest, error) {
+ resolved, ok, err := resolveLocalShowManifestChild(child)
+ if err != nil {
+ return nil, err
+ }
+ if !ok {
+ return nil, os.ErrNotExist
+ }
+
+ return resolved, nil
+}
+
+func resolveLocalShowManifestChild(child manifest.Manifest) (*manifest.Manifest, bool, error) {
+ if child.MediaType == manifest.MediaTypeManifestList {
+ return nil, false, errors.New("nested manifest lists are not supported")
+ }
+
+ return manifest.ResolveManifestReference(child)
+}
+
+func manifestSummariesForShow(name model.Name, selectedDigest string) ([]api.ManifestSummary, error) {
+ if manifest.IsDigestReferenceName(name) {
+ return nil, nil
+ }
+
+ data, err := manifest.ReadManifestData(name)
+ if err != nil {
+ return nil, err
+ }
+
+ var parent manifest.Manifest
+ if err := json.Unmarshal(data, &parent); err != nil {
+ return nil, err
+ }
+ if parent.MediaType != manifest.MediaTypeManifestList {
+ return nil, nil
+ }
+ if selectedDigest != "" && !strings.HasPrefix(selectedDigest, "sha256:") && !strings.HasPrefix(selectedDigest, "sha256-") {
+ selectedDigest = "sha256:" + selectedDigest
+ }
+
+ summaries := make([]api.ManifestSummary, 0, len(parent.Manifests))
+ for _, child := range parent.Manifests {
+ resolved, ok, err := resolveLocalShowManifestChild(child)
+ if err != nil {
+ return nil, err
+ }
+ if !ok {
+ continue
+ }
+ digest, err := manifest.ChildManifestDigest(child)
+ if err != nil {
+ return nil, err
+ }
+
+ runner, err := normalizeRunner(resolved.Runner)
+ if err != nil {
+ return nil, err
+ }
+ summaries = append(summaries, api.ManifestSummary{
+ Digest: digest,
+ Runner: runner,
+ Format: resolved.Format,
+ Selected: manifest.SameDigest(digest, selectedDigest),
+ })
+ }
+ // Only report manifests when there is a real choice: a single-child list
+ // behaves like a plain model, and show omits the runner rows for it.
+ if len(summaries) < 2 {
+ return nil, nil
+ }
+
+ return summaries, nil
+}
+
+func collectManifestLicenseText(children []manifest.Manifest) (string, error) {
+ seen := make(map[string]struct{})
+ var licenses []string
+
+ for _, child := range children {
+ for _, layer := range child.Layers {
+ if layer.MediaType != manifest.MediaTypeImageLicense || layer.Digest == "" {
+ continue
+ }
+
+ digest := layer.Digest
+ if _, ok := seen[digest]; ok {
+ continue
+ }
+
+ data, err := readBlobData(digest)
+ if err != nil {
+ return "", err
+ }
+
+ seen[digest] = struct{}{}
+ licenses = append(licenses, string(data))
+ }
+ }
+
+ return strings.Join(licenses, "\n"), nil
+}
+
+func GetAllManifestsInfo(req api.ShowRequest) (*api.ShowManifestsResponse, error) {
+ runner, err := normalizeRunner(req.Runner)
+ if err != nil {
+ return nil, api.StatusError{
+ StatusCode: http.StatusBadRequest,
+ ErrorMessage: err.Error(),
+ }
+ }
+ req.Runner = runner
+ if req.Runner != "" {
+ return nil, api.StatusError{
+ StatusCode: http.StatusBadRequest,
+ ErrorMessage: "runner cannot be used with all_manifests",
+ }
+ }
+
+ name := model.ParseName(req.Model)
+ if !name.IsValid() {
+ return nil, model.Unqualified(name)
+ }
+ name, err = getExistingName(name)
+ if err != nil {
+ return nil, err
+ }
+ req.Model = name.String()
+
+ data, err := manifest.ReadManifestData(name)
+ if err != nil {
+ return nil, err
+ }
+
+ var parent manifest.Manifest
+ if err := json.Unmarshal(data, &parent); err != nil {
+ return nil, err
+ }
+
+ if parent.MediaType != manifest.MediaTypeManifestList {
+ resp, err := GetModelInfo(req)
+ if err != nil {
+ return nil, err
+ }
+
+ mf, err := manifest.ParseNamedManifestForRunner(name, "")
+ if err != nil {
+ return nil, err
+ }
+
+ return &api.ShowManifestsResponse{
+ Manifests: []api.ShowManifest{{
+ Runner: mf.Runner,
+ ShowResponse: *resp,
+ }},
+ License: resp.License,
+ }, nil
+ }
+
+ resolvedChildren := make([]manifest.Manifest, 0, len(parent.Manifests))
+ resp := &api.ShowManifestsResponse{
+ Manifests: make([]api.ShowManifest, 0, len(parent.Manifests)),
+ }
+ for _, child := range parent.Manifests {
+ resolved, ok, err := resolveLocalShowManifestChild(child)
+ if err != nil {
+ return nil, err
+ }
+ if !ok {
+ continue
+ }
+ if resolved.Runner == "" {
+ return nil, fmt.Errorf("manifest list child %q is missing runner metadata", resolved.BlobDigest())
+ }
+ runner, err := normalizeRunner(resolved.Runner)
+ if err != nil {
+ return nil, err
+ }
+ resolved.Runner = runner
+
+ resolvedChildren = append(resolvedChildren, *resolved)
+
+ childResp, err := GetModelInfo(api.ShowRequest{
+ Model: req.Model,
+ Runner: resolved.Runner,
+ System: req.System,
+ Verbose: req.Verbose,
+ Options: req.Options,
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ resp.Manifests = append(resp.Manifests, api.ShowManifest{
+ Runner: resolved.Runner,
+ ShowResponse: *childResp,
+ })
+ }
+
+ resp.License, err = collectManifestLicenseText(resolvedChildren)
+ if err != nil {
+ return nil, err
+ }
+
+ return resp, nil
+}
diff --git a/server/show_safetensors.go b/server/show_safetensors.go
index 3591d49c9..e5ff10a1a 100644
--- a/server/show_safetensors.go
+++ b/server/show_safetensors.go
@@ -41,10 +41,11 @@ type modelConfig struct {
} `json:"text_config"`
}
-// 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) {
- mf, err := manifest.ParseNamedManifest(name)
+// getSafetensorsLLMInfoForRunner extracts model information from the safetensors
+// LLM manifest selected for runner. It reads the config.json layer and returns a
+// map compatible with GGML's KV format.
+func getSafetensorsLLMInfoForRunner(name model.Name, runner string) (map[string]any, error) {
+ mf, err := manifest.ParseNamedManifestForRunner(name, runner)
if err != nil {
return nil, fmt.Errorf("failed to load manifest: %w", err)
}
@@ -210,10 +211,11 @@ func getParameterCountFromManifest(mf *manifest.Manifest) (int64, error) {
return total, nil
}
-// 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) {
- mf, err := manifest.ParseNamedManifest(name)
+// getSafetensorsTensorInfoForRunner extracts tensor information from the safetensors
+// model layers selected for runner. Each tensor is stored as a minimal safetensors
+// file with an 88-byte header containing metadata.
+func getSafetensorsTensorInfoForRunner(name model.Name, runner string) ([]api.Tensor, error) {
+ mf, err := manifest.ParseNamedManifestForRunner(name, runner)
if err != nil {
return nil, fmt.Errorf("failed to load manifest: %w", err)
}
@@ -303,11 +305,12 @@ func getTensorInfoFromManifest(mf *manifest.Manifest) ([]api.Tensor, error) {
return tensors, nil
}
-// 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) {
- mf, err := manifest.ParseNamedManifest(name)
+// getSafetensorsDtypeForRunner returns the quantization type for the safetensors
+// manifest selected for runner. 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 getSafetensorsDtypeForRunner(name model.Name, runner string) (string, error) {
+ mf, err := manifest.ParseNamedManifestForRunner(name, runner)
if err != nil {
return "", fmt.Errorf("failed to load manifest: %w", err)
}
diff --git a/server/show_safetensors_test.go b/server/show_safetensors_test.go
index faddd6da2..ffa4981a0 100644
--- a/server/show_safetensors_test.go
+++ b/server/show_safetensors_test.go
@@ -554,6 +554,99 @@ func TestGetTensorInfoFromManifest_Quantized(t *testing.T) {
}
}
+func createSafetensorsManifestForRunner(t *testing.T, name, runner, tensorName string) manifest.Manifest {
+ t.Helper()
+
+ configLayer, err := manifest.NewLayer(bytes.NewReader([]byte("{}")), "application/vnd.docker.container.image.v1+json")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ header := map[string]any{
+ tensorName: map[string]any{
+ "dtype": "F32",
+ "shape": []int64{2, 3},
+ "data_offsets": []int64{0, 24},
+ },
+ }
+ headerData, err := json.Marshal(header)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ var buf bytes.Buffer
+ if err := binary.Write(&buf, binary.LittleEndian, uint64(len(headerData))); err != nil {
+ t.Fatal(err)
+ }
+ buf.Write(headerData)
+
+ tensorLayer, err := manifest.NewLayer(bytes.NewReader(buf.Bytes()), manifest.MediaTypeImageTensor)
+ if err != nil {
+ t.Fatal(err)
+ }
+ tensorLayer.Name = tensorName
+
+ if err := manifest.WriteManifestWithMetadata(model.ParseName(name), configLayer, []manifest.Layer{tensorLayer}, runner, manifest.FormatSafetensors); err != nil {
+ t.Fatal(err)
+ }
+
+ mf, err := manifest.ParseNamedManifestForRunner(model.ParseName(name), runner)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ return *mf
+}
+
+func TestGetSafetensorsTensorInfoForRunnerSelectsChildManifest(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+
+ mlxManifest := createSafetensorsManifestForRunner(t, "runner-mlx", manifest.RunnerMLX, "mlx.weight")
+ ggmlManifest := createSafetensorsManifestForRunner(t, "runner-ggml", manifest.RunnerGGML, "ggml.weight")
+
+ mlxRef, err := manifest.NewManifestReference(mlxManifest.BlobDigest(), manifest.RunnerMLX, manifest.FormatSafetensors)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ggmlRef, err := manifest.NewManifestReference(ggmlManifest.BlobDigest(), manifest.RunnerGGML, manifest.FormatSafetensors)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ parentData, err := json.Marshal(manifest.Manifest{
+ SchemaVersion: 2,
+ MediaType: manifest.MediaTypeManifestList,
+ Manifests: []manifest.Manifest{ggmlRef, mlxRef},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := manifest.WriteManifestData(model.ParseName("runner-list"), parentData); err != nil {
+ t.Fatal(err)
+ }
+
+ for _, tt := range []struct {
+ runner string
+ want string
+ }{
+ {runner: manifest.RunnerMLX, want: "mlx.weight"},
+ {runner: manifest.RunnerGGML, want: "ggml.weight"},
+ } {
+ t.Run(tt.runner, func(t *testing.T) {
+ tensors, err := getSafetensorsTensorInfoForRunner(model.ParseName("runner-list"), tt.runner)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(tensors) != 1 {
+ t.Fatalf("tensor count = %d, want 1", len(tensors))
+ }
+ if tensors[0].Name != tt.want {
+ t.Fatalf("tensor name = %q, want %q", tensors[0].Name, tt.want)
+ }
+ })
+ }
+}
+
func TestGetParameterCountFromManifest(t *testing.T) {
// Create a temp directory for blobs and set OLLAMA_MODELS
tempDir := t.TempDir()
@@ -1160,11 +1253,11 @@ func TestGetSafetensorsDtypeChoosesLowestPrecisionQuantizedBlob(t *testing.T) {
t.Fatalf("failed to write manifest: %v", err)
}
- got, err := getSafetensorsDtype(name)
+ got, err := getSafetensorsDtypeForRunner(name, "")
if err != nil {
- t.Fatalf("getSafetensorsDtype() error = %v", err)
+ t.Fatalf("getSafetensorsDtypeForRunner() error = %v", err)
}
if got != "nvfp4" {
- t.Fatalf("getSafetensorsDtype() = %q, want nvfp4", got)
+ t.Fatalf("getSafetensorsDtypeForRunner() = %q, want nvfp4", got)
}
}
diff --git a/x/transfer/transfer.go b/x/transfer/transfer.go
index 49b14d6b4..2833960d9 100644
--- a/x/transfer/transfer.go
+++ b/x/transfer/transfer.go
@@ -90,9 +90,10 @@ type UploadOptions struct {
AllowPrivateHosts bool // Permits cross-host redirects to local addresses
// Manifest fields (optional) - if set, manifest is pushed after all blobs complete
- Manifest []byte // Raw manifest JSON to push
- ManifestRef string // Tag or digest for the manifest (e.g., "latest", "sha256:...")
- Repository string // Repository path for manifest URL (e.g., "library/model")
+ Manifest []byte // Raw manifest JSON to push
+ ManifestMediaType string // Manifest Content-Type; required when Manifest is set
+ ManifestRef string // Tag or digest for the manifest (e.g., "latest", "sha256:...")
+ Repository string // Repository path for manifest URL (e.g., "library/model")
}
// AuthChallenge represents a parsed WWW-Authenticate challenge.
diff --git a/x/transfer/transfer_test.go b/x/transfer/transfer_test.go
index c183a929f..b00e3d990 100644
--- a/x/transfer/transfer_test.go
+++ b/x/transfer/transfer_test.go
@@ -19,6 +19,12 @@ import (
"time"
)
+type roundTripFunc func(*http.Request) (*http.Response, error)
+
+func (fn roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
+ return fn(req)
+}
+
// chunkedSession tracks accumulated PATCH body bytes for an upload session.
// Tests that mock the registry use it to handle the GGUF-style POST → PATCH →
// PUT-finalize flow without each test reimplementing the bookkeeping.
@@ -1545,10 +1551,12 @@ func TestDefaultUserAgent(t *testing.T) {
// TestManifestPush verifies that manifest is pushed after blobs
func TestManifestPush(t *testing.T) {
+ const mediaType = "application/vnd.docker.distribution.manifest.v2+json"
+
clientDir := t.TempDir()
blob, _ := createTestBlob(t, clientDir, 1000)
- testManifest := []byte(`{"schemaVersion":2,"mediaType":"application/vnd.docker.distribution.manifest.v2+json"}`)
+ testManifest := []byte(`{"schemaVersion":2,"mediaType":"` + mediaType + `"}`)
testRepo := "library/test-model"
testRef := "latest"
@@ -1588,12 +1596,13 @@ func TestManifestPush(t *testing.T) {
serverURL = server.URL
err := Upload(context.Background(), UploadOptions{
- Blobs: []Blob{blob},
- BaseURL: server.URL,
- SrcDir: clientDir,
- Manifest: testManifest,
- ManifestRef: testRef,
- Repository: testRepo,
+ Blobs: []Blob{blob},
+ BaseURL: server.URL,
+ SrcDir: clientDir,
+ Manifest: testManifest,
+ ManifestMediaType: mediaType,
+ ManifestRef: testRef,
+ Repository: testRepo,
})
if err != nil {
t.Fatalf("Upload failed: %v", err)
@@ -1613,13 +1622,45 @@ func TestManifestPush(t *testing.T) {
t.Errorf("Manifest path mismatch: got %s, want %s", manifestPath, expectedPath)
}
- if manifestContentType != "application/vnd.docker.distribution.manifest.v2+json" {
+ if manifestContentType != mediaType {
t.Errorf("Manifest content type mismatch: got %s", manifestContentType)
}
t.Logf("Manifest push test passed: received %d bytes at %s", len(manifestReceived), manifestPath)
}
+func TestPushManifestContentType(t *testing.T) {
+ const mediaType = "application/vnd.ollama.manifest.list.v2+json"
+
+ var gotContentType, gotPath string
+ u := &uploader{
+ client: &http.Client{
+ Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ gotContentType = req.Header.Get("Content-Type")
+ gotPath = req.URL.Path
+ return &http.Response{
+ StatusCode: http.StatusCreated,
+ Body: io.NopCloser(strings.NewReader("")),
+ Header: make(http.Header),
+ Request: req,
+ }, nil
+ }),
+ },
+ baseURL: "https://example.com",
+ userAgent: "test",
+ }
+
+ if err := u.pushManifest(context.Background(), "library/test-model", "latest", []byte("{}"), mediaType); err != nil {
+ t.Fatal(err)
+ }
+ if gotContentType != mediaType {
+ t.Fatalf("content type = %q, want %q", gotContentType, mediaType)
+ }
+ if gotPath != "/v2/library/test-model/manifests/latest" {
+ t.Fatalf("path = %q", gotPath)
+ }
+}
+
// ==================== Throughput Benchmarks ====================
func BenchmarkDownloadThroughput(b *testing.B) {
diff --git a/x/transfer/upload.go b/x/transfer/upload.go
index 0cffdb29e..4e898de0f 100644
--- a/x/transfer/upload.go
+++ b/x/transfer/upload.go
@@ -186,8 +186,11 @@ func upload(ctx context.Context, opts UploadOptions) error {
}
if len(opts.Manifest) > 0 && opts.ManifestRef != "" && opts.Repository != "" {
+ if opts.ManifestMediaType == "" {
+ return errors.New("manifest push requires a manifest media type")
+ }
logutil.Trace("pushing manifest", "repo", opts.Repository, "ref", opts.ManifestRef, "size", len(opts.Manifest))
- if err := u.pushManifest(ctx, opts.Repository, opts.ManifestRef, opts.Manifest); err != nil {
+ if err := u.pushManifest(ctx, opts.Repository, opts.ManifestRef, opts.Manifest, opts.ManifestMediaType); err != nil {
logutil.Trace("manifest push failed", "error", err)
return err
}
@@ -775,9 +778,9 @@ func computePartsWithLimits(totalSize int64, nParts int, minPart, maxPart int64)
return parts
}
-func (u *uploader) pushManifest(ctx context.Context, repo, ref string, manifest []byte) error {
+func (u *uploader) pushManifest(ctx context.Context, repo, ref string, manifest []byte, mediaType string) error {
req, _ := http.NewRequestWithContext(ctx, http.MethodPut, fmt.Sprintf("%s/v2/%s/manifests/%s", u.baseURL, repo, ref), bytes.NewReader(manifest))
- req.Header.Set("Content-Type", "application/vnd.docker.distribution.manifest.v2+json")
+ req.Header.Set("Content-Type", mediaType)
req.Header.Set("User-Agent", u.userAgent)
prev := u.authToken()
if prev != "" {
@@ -795,7 +798,7 @@ func (u *uploader) pushManifest(ctx context.Context, repo, ref string, manifest
if err := u.refreshToken(ctx, ch, prev); err != nil {
return err
}
- return u.pushManifest(ctx, repo, ref, manifest)
+ return u.pushManifest(ctx, repo, ref, manifest, mediaType)
}
if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK {