Skip to content

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

Add a model metadata cache to reduce Ollama’s per-request overhead (#17752)

Gaurav Garga5165c53acc5
diff --git a/server/images.go b/server/images.go
index 23fb932b6..9515e3558 100644
--- a/server/images.go
+++ b/server/images.go
@@ -80,6 +80,9 @@ type Model struct {
Messages []api.Message
Template *template.Template
+
+ capabilities []model.Capability
+ capabilitiesCached bool
}
func (m *Model) IsMLX() bool {
@@ -107,6 +110,10 @@ const (
// Capabilities returns the capabilities that the model supports
func (m *Model) Capabilities() []model.Capability {
+ if m.capabilitiesCached {
+ return slices.Clone(m.capabilities)
+ }
+
capabilities := m.capabilitiesForTemplate(templateCapabilitySelected, nil)
if len(capabilities) == 0 {
slog.Warn("unknown capabilities for model", "model", m.Name)
diff --git a/server/model_caches.go b/server/model_caches.go
index 6c09b477c..06f9e52b9 100644
--- a/server/model_caches.go
+++ b/server/model_caches.go
@@ -6,6 +6,7 @@ type modelCaches struct {
recommendations *modelRecommendationsCache
show *modelShowCache
modelList *modelListCache
+ inference *inferenceModelCache
}
func newModelCaches() *modelCaches {
@@ -13,6 +14,7 @@ func newModelCaches() *modelCaches {
recommendations: newModelRecommendationsCache(),
show: newModelShowCache(),
modelList: newModelListCache(),
+ inference: newInferenceModelCache(),
}
}
diff --git a/server/model_inference_cache.go b/server/model_inference_cache.go
new file mode 100644
index 000000000..a5edcbd44
--- /dev/null
+++ b/server/model_inference_cache.go
@@ -0,0 +1,121 @@
+package server
+
+import (
+ "maps"
+ "slices"
+ "strconv"
+ "sync"
+
+ "github.com/ollama/ollama/envconfig"
+ "github.com/ollama/ollama/manifest"
+ "github.com/ollama/ollama/types/model"
+ "golang.org/x/sync/singleflight"
+)
+
+// inferenceModelCache stores fully resolved model metadata and capabilities.
+// Model blobs are content-addressed, and the manifest digest is the freshness
+// boundary, so cached entries remain valid until the model is recreated or
+// pulled with different content.
+type inferenceModelCache struct {
+ mu sync.RWMutex
+ entries map[inferenceModelCacheKey]inferenceModelCacheEntry
+ loads singleflight.Group
+
+ loadModel func(string) (*Model, error)
+}
+
+type inferenceModelCacheKey struct {
+ name string
+ goTemplate bool
+ goTemplateSet bool
+}
+
+type inferenceModelCacheEntry struct {
+ digest string
+ model *Model
+}
+
+func newInferenceModelCache() *inferenceModelCache {
+ return &inferenceModelCache{
+ entries: make(map[inferenceModelCacheKey]inferenceModelCacheEntry),
+ loadModel: GetModel,
+ }
+}
+
+func (c *inferenceModelCache) Get(name string) (*Model, error) {
+ n := model.ParseName(name)
+ mf, err := manifest.ParseNamedManifest(n)
+ if err != nil {
+ return nil, err
+ }
+
+ key := inferenceModelCacheKey{
+ name: n.String(),
+ goTemplate: envconfig.GoTemplate(true),
+ goTemplateSet: goTemplateEnvSet(),
+ }
+ digest := mf.Digest()
+
+ c.mu.RLock()
+ entry, ok := c.entries[key]
+ c.mu.RUnlock()
+ if ok && entry.digest == digest {
+ return cloneInferenceModel(entry.model), nil
+ }
+
+ loadKey := key.name + "\x00" + digest + "\x00" + strconv.FormatBool(key.goTemplate) + "\x00" + strconv.FormatBool(key.goTemplateSet)
+ v, err, _ := c.loads.Do(loadKey, func() (any, error) {
+ c.mu.RLock()
+ entry, ok := c.entries[key]
+ c.mu.RUnlock()
+ if ok && entry.digest == digest {
+ return entry.model, nil
+ }
+
+ m, err := c.loadModel(name)
+ if err != nil {
+ return nil, err
+ }
+ m.capabilities = m.Capabilities()
+ m.capabilitiesCached = true
+
+ c.mu.Lock()
+ c.entries[key] = inferenceModelCacheEntry{digest: m.Digest, model: m}
+ c.mu.Unlock()
+ return m, nil
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ return cloneInferenceModel(v.(*Model)), nil
+}
+
+func cloneInferenceModel(src *Model) *Model {
+ if src == nil {
+ return nil
+ }
+
+ dst := *src
+ dst.Config.ModelFamilies = slices.Clone(src.Config.ModelFamilies)
+ dst.Config.Capabilities = slices.Clone(src.Config.Capabilities)
+ if src.Config.Draft != nil {
+ draft := *src.Config.Draft
+ dst.Config.Draft = &draft
+ }
+ dst.AdapterPaths = slices.Clone(src.AdapterPaths)
+ dst.ProjectorPaths = slices.Clone(src.ProjectorPaths)
+ dst.License = slices.Clone(src.License)
+ dst.Options = maps.Clone(src.Options)
+ dst.Messages = slices.Clone(src.Messages)
+ dst.capabilities = slices.Clone(src.capabilities)
+
+ return &dst
+}
+
+func (s *Server) getModel(name string) (*Model, error) {
+ if s != nil && s.modelCaches != nil && s.modelCaches.inference != nil {
+ return s.modelCaches.inference.Get(name)
+ }
+ return GetModel(name)
+}
diff --git a/server/model_inference_cache_test.go b/server/model_inference_cache_test.go
new file mode 100644
index 000000000..fb53202e2
--- /dev/null
+++ b/server/model_inference_cache_test.go
@@ -0,0 +1,121 @@
+package server
+
+import (
+ "slices"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/ollama/ollama/fs/ggml"
+ "github.com/ollama/ollama/types/model"
+)
+
+func TestInferenceModelCache(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+ t.Setenv("OLLAMA_GO_TEMPLATE", "")
+
+ _, completionDigest := createBinFile(t, ggml.KV{
+ "general.architecture": "llama",
+ }, nil)
+ writeTestModelManifest(t, "inference-cache", completionDigest, "{{ .Prompt }}")
+
+ cache := newInferenceModelCache()
+ loadCount := 0
+ cache.loadModel = func(name string) (*Model, error) {
+ loadCount++
+ return GetModel(name)
+ }
+
+ first, err := cache.Get("inference-cache")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if loadCount != 1 {
+ t.Fatalf("load count = %d, want 1", loadCount)
+ }
+ if !first.capabilitiesCached {
+ t.Fatal("capabilities were not cached")
+ }
+ if got := first.Capabilities(); !slices.Contains(got, model.CapabilityCompletion) {
+ t.Fatalf("capabilities = %v, want completion", got)
+ }
+
+ // Returned models are request-local clones. Mutating one must not alter the
+ // cached model or a later request.
+ first.Config.Parser = "mutated"
+ first.Config.ModelFamilies[0] = "mutated"
+ first.capabilities[0] = model.CapabilityImage
+
+ second, err := cache.Get("inference-cache")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if loadCount != 1 {
+ t.Fatalf("cache hit load count = %d, want 1", loadCount)
+ }
+ if second.Config.Parser == "mutated" || slices.Contains(second.Config.ModelFamilies, "mutated") {
+ t.Fatalf("cached model was mutated: %#v", second.Config)
+ }
+ if got := second.Capabilities(); !slices.Contains(got, model.CapabilityCompletion) || slices.Contains(got, model.CapabilityImage) {
+ t.Fatalf("cached capabilities = %v, want completion only", got)
+ }
+
+ // Recreating the manifest changes its digest and invalidates the entry.
+ _, embeddingDigest := createBinFile(t, ggml.KV{
+ "general.architecture": "bert",
+ "bert.pooling_type": uint32(1),
+ }, nil)
+ writeTestModelManifest(t, "inference-cache", embeddingDigest, "{{ .Prompt }}")
+
+ third, err := cache.Get("inference-cache")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if loadCount != 2 {
+ t.Fatalf("invalidated load count = %d, want 2", loadCount)
+ }
+ if got := third.Capabilities(); !slices.Contains(got, model.CapabilityEmbedding) || slices.Contains(got, model.CapabilityCompletion) {
+ t.Fatalf("refreshed capabilities = %v, want embedding only", got)
+ }
+}
+
+func TestInferenceModelCacheConcurrentMiss(t *testing.T) {
+ t.Setenv("OLLAMA_MODELS", t.TempDir())
+ t.Setenv("OLLAMA_GO_TEMPLATE", "")
+
+ _, digest := createBinFile(t, ggml.KV{
+ "general.architecture": "llama",
+ }, nil)
+ writeTestModelManifest(t, "inference-cache-concurrent", digest, "{{ .Prompt }}")
+
+ cache := newInferenceModelCache()
+ var loadCount atomic.Int32
+ cache.loadModel = func(name string) (*Model, error) {
+ loadCount.Add(1)
+ time.Sleep(10 * time.Millisecond)
+ return GetModel(name)
+ }
+
+ var wg sync.WaitGroup
+ errs := make(chan error, 8)
+ for range 8 {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ _, err := cache.Get("inference-cache-concurrent")
+ errs <- err
+ }()
+ }
+ wg.Wait()
+ close(errs)
+
+ for err := range errs {
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ if got := loadCount.Load(); got != 1 {
+ t.Fatalf("load count = %d, want 1", got)
+ }
+}
diff --git a/server/routes.go b/server/routes.go
index 3a027a9ea..619778091 100644
--- a/server/routes.go
+++ b/server/routes.go
@@ -199,22 +199,17 @@ func usesAutomaticNumBatch(model *Model, requestOpts map[string]any) bool {
// 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, name string, caps []model.Capability, requestOpts map[string]any, keepAlive *api.Duration, shift *bool) (llm.LlamaServer, *Model, *api.Options, error) {
- if name == "" {
+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 == "" {
return nil, nil, nil, fmt.Errorf("model %w", errRequired)
}
- model, err := GetModel(name)
- if err != nil {
- return nil, nil, nil, err
- }
-
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'")
}
if err := model.CheckCapabilities(caps...); err != nil {
- return nil, nil, nil, fmt.Errorf("%s %w", name, err)
+ return nil, nil, nil, fmt.Errorf("%s %w", model.Name, err)
}
numCtxAuto := usesAutomaticNumCtx(model, requestOpts)
@@ -287,7 +282,7 @@ func (s *Server) GenerateHandler(c *gin.Context) {
return
}
- m, err := GetModel(name.String())
+ m, err := s.getModel(name.String())
if err != nil {
switch {
case errors.Is(err, fs.ErrNotExist):
@@ -468,7 +463,7 @@ func (s *Server) GenerateHandler(c *gin.Context) {
}
}
- r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), caps, req.Options, req.KeepAlive, req.Shift)
+ r, m, opts, err := s.scheduleRunner(c.Request.Context(), m, 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
@@ -839,7 +834,13 @@ func (s *Server) EmbedHandler(c *gin.Context) {
return
}
- r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), []model.Capability{}, req.Options, req.KeepAlive, nil)
+ m, err := s.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)
if err != nil {
handleScheduleError(c, req.Model, err)
return
@@ -1051,7 +1052,13 @@ func (s *Server) EmbeddingsHandler(c *gin.Context) {
name := modelRef.Name
- r, m, _, err := s.scheduleRunner(c.Request.Context(), name.String(), []model.Capability{}, req.Options, req.KeepAlive, nil)
+ m, err := s.getModel(name.String())
+ if err != nil {
+ handleScheduleError(c, req.Model, err)
+ return
+ }
+
+ r, m, _, err := s.scheduleRunner(c.Request.Context(), m, []model.Capability{}, req.Options, req.KeepAlive, nil)
if err != nil {
handleScheduleError(c, req.Model, err)
return
@@ -2460,7 +2467,7 @@ func (s *Server) ChatHandler(c *gin.Context) {
return
}
- m, err := GetModel(name.String())
+ m, err := s.getModel(name.String())
if err != nil {
switch {
case os.IsNotExist(err):
@@ -2613,7 +2620,7 @@ func (s *Server) ChatHandler(c *gin.Context) {
}
}
- r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), caps, req.Options, req.KeepAlive, req.Shift)
+ r, m, opts, err := s.scheduleRunner(c.Request.Context(), m, 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