mirror of
https://github.com/ollama/ollama.git
synced 2026-12-04 00:21:20 +00:00
mlxrunner: choose default parallelism from available memory (#19785)
When OLLAMA_NUM_PARALLEL is unset, select 1, 2, 4 or 8 slots using available memory and estimated per-client storage at the model's context limit. Preserve explicit settings and retain the serial default under memory pressure, for unknown cache layouts and on other backends.
This commit is contained in:
1 parent
73ee71ddcc
commit
0b243a141a
10 files changed
+301
-27
No files matched your search
+1
-1
@@ -342,7 +342,7 @@ Parallel request processing for a given model results in increasing the context
|
||||
The following server settings may be used to adjust how Ollama handles concurrent requests on most platforms:
|
||||
|
||||
- `OLLAMA_MAX_LOADED_MODELS` - The maximum number of models that can be loaded concurrently provided they fit in available memory. The default is 3 \* the number of GPUs or 3 for CPU inference.
|
||||
- `OLLAMA_NUM_PARALLEL` - The maximum number of parallel requests each model will process at the same time, default 1. Required RAM will scale by `OLLAMA_NUM_PARALLEL` * `OLLAMA_CONTEXT_LENGTH`.
|
||||
- `OLLAMA_NUM_PARALLEL` - The maximum number of parallel requests each model will process at the same time. When unset or zero, MLX on Metal chooses a conservative default based on available memory and the model's cache requirements; other backends default to 1. Set an explicit value to override this choice. More parallel requests require more memory.
|
||||
- `OLLAMA_MAX_QUEUE` - The maximum number of requests Ollama will queue when busy before rejecting additional requests. The default is 512
|
||||
|
||||
Note: Windows with Radeon GPUs currently default to 1 model maximum due to limitations in ROCm v5.7 for available VRAM reporting. Once ROCm v6.2 is available, Windows Radeon will follow the defaults above. You may enable concurrent model loads on Radeon on Windows, but ensure you don't load more models than will fit into your GPU's VRAM.
|
||||
|
||||
+3
-3
@@ -273,8 +273,8 @@ func Uint(key string, defaultValue uint) func() uint {
|
||||
}
|
||||
|
||||
var (
|
||||
// NumParallel sets the number of parallel model requests. NumParallel can be configured via the OLLAMA_NUM_PARALLEL environment variable.
|
||||
NumParallel = Uint("OLLAMA_NUM_PARALLEL", 1)
|
||||
// NumParallel sets the number of parallel model requests. Zero selects the backend default. NumParallel can be configured via the OLLAMA_NUM_PARALLEL environment variable.
|
||||
NumParallel = Uint("OLLAMA_NUM_PARALLEL", 0)
|
||||
// MaxRunners sets the maximum number of loaded models. MaxRunners can be configured via the OLLAMA_MAX_LOADED_MODELS environment variable.
|
||||
MaxRunners = Uint("OLLAMA_MAX_LOADED_MODELS", 0)
|
||||
// MaxQueue sets the maximum number of queued requests. MaxQueue can be configured via the OLLAMA_MAX_QUEUE environment variable.
|
||||
@@ -332,7 +332,7 @@ func AsMap() map[string]EnvVar {
|
||||
"OLLAMA_NO_CLOUD": {"OLLAMA_NO_CLOUD", NoCloud(), "Disable Ollama cloud features (remote inference and web search)"},
|
||||
"OLLAMA_NOHISTORY": {"OLLAMA_NOHISTORY", NoHistory(), "Do not preserve readline history"},
|
||||
"OLLAMA_NOPRUNE": {"OLLAMA_NOPRUNE", NoPrune(), "Do not prune model blobs on startup"},
|
||||
"OLLAMA_NUM_PARALLEL": {"OLLAMA_NUM_PARALLEL", NumParallel(), "Maximum number of parallel requests"},
|
||||
"OLLAMA_NUM_PARALLEL": {"OLLAMA_NUM_PARALLEL", NumParallel(), "Maximum number of parallel requests (0 selects the backend default)"},
|
||||
"OLLAMA_ORIGINS": {"OLLAMA_ORIGINS", AllowedOrigins(), "A comma separated list of allowed origins"},
|
||||
"OLLAMA_SCHED_SPREAD": {"OLLAMA_SCHED_SPREAD", SchedSpread(), "Always schedule model across all GPUs"},
|
||||
"OLLAMA_CONTEXT_LENGTH": {"OLLAMA_CONTEXT_LENGTH", ContextLength(), "Context length to use unless otherwise specified (default: 4k/32k/256k based on VRAM)"},
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package envconfig
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNumParallelDefault(t *testing.T) {
|
||||
t.Setenv("OLLAMA_NUM_PARALLEL", "")
|
||||
if NumParallel() != 0 {
|
||||
t.Fatal("unset parallelism must select the backend default")
|
||||
}
|
||||
t.Setenv("OLLAMA_NUM_PARALLEL", "1")
|
||||
if NumParallel() != 1 {
|
||||
t.Fatal("explicit serial setting was lost")
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ func runConcurrentChat(t *testing.T, modelName string) {
|
||||
req[i].Think = &api.ThinkValue{Value: false}
|
||||
req[i].Options = map[string]any{"num_predict": 256, "num_ctx": 4096}
|
||||
}
|
||||
numParallel := int(envconfig.NumParallel() + 1)
|
||||
numParallel := max(int(envconfig.NumParallel()), 1) + 1
|
||||
iterLimit := 3
|
||||
|
||||
softTimeout, hardTimeout := getTimeouts(t)
|
||||
|
||||
Vendored
+45
@@ -0,0 +1,45 @@
|
||||
package cache
|
||||
|
||||
import "math"
|
||||
|
||||
// EstimateMemory budgets one request's live cache, copies and checkpoints using
|
||||
// tensor shapes from a fresh cache's first forward. It does not evaluate arrays
|
||||
// or allocate storage.
|
||||
// Unknown or uninitialized caches cannot safely increase automatic parallelism.
|
||||
func EstimateMemory(c Cache, tokens, checkpoints int) (int64, bool) {
|
||||
if c == nil {
|
||||
return 0, true // Some layers share another layer's cache.
|
||||
}
|
||||
if tokens <= 0 || checkpoints < 0 {
|
||||
return 0, false
|
||||
}
|
||||
var bytes int64
|
||||
for _, a := range c.State() {
|
||||
if a != nil {
|
||||
bytes += int64(a.NumBytes())
|
||||
}
|
||||
}
|
||||
if bytes <= 0 || c.Offset() <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
var count int64
|
||||
switch c := c.(type) {
|
||||
case *KVCache:
|
||||
bytes /= int64(c.Offset())
|
||||
// Full-attention snapshots share the live prefix until it is copied.
|
||||
count = 2 * ((int64(tokens) + int64(c.step) - 1) / int64(c.step) * int64(c.step))
|
||||
case *RotatingKVCache:
|
||||
bytes /= int64(min(c.Offset(), c.maxSize))
|
||||
count = int64(min(tokens, c.maxSize)) * (2 + int64(checkpoints))
|
||||
case *RecurrentCache:
|
||||
// Bounded state is retained at each prompt checkpoint, plus live state
|
||||
// and a copy when the next request resumes or rewinds it.
|
||||
count = 2 + int64(checkpoints)
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
if count <= 0 || bytes > math.MaxInt64/count {
|
||||
return 0, false
|
||||
}
|
||||
return bytes * count, true
|
||||
}
|
||||
Vendored
+49
@@ -0,0 +1,49 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/ollama/ollama/mlx"
|
||||
"github.com/ollama/ollama/mlx/mlxtest"
|
||||
)
|
||||
|
||||
func TestEstimateMemory(t *testing.T) {
|
||||
mlxtest.Run(t, func(t *mlxtest.T) {
|
||||
b := newKVBatch(0, 1)
|
||||
k := mlx.Zeros(mlx.DTypeFloat16, 1, 4, 1, 8)
|
||||
full := NewKVCache()
|
||||
window := NewRotatingKVCache(4)
|
||||
full.Update(b, k, k)
|
||||
window.Update(b, k, k)
|
||||
recurrent := NewRecurrentCache(3, 8, 2, 4, 8)
|
||||
recurrent.Get(b, mlx.DTypeFloat16)
|
||||
recurrent.Put(b, []*mlx.Array{recurrent.convState}, []*mlx.Array{recurrent.deltaState})
|
||||
defer full.Free()
|
||||
defer window.Free()
|
||||
defer recurrent.Free()
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
cache Cache
|
||||
tokens, checkpoints int
|
||||
want int64
|
||||
}{
|
||||
{"full", full, 1024, 2, 2 * 1024 * 128},
|
||||
{"capacity_rounding", full, 257, 0, 2 * 512 * 128},
|
||||
{"window", window, 1024, 2, 4 * 4 * 128},
|
||||
{"short_window", window, 2, 0, 2 * 2 * 128},
|
||||
{"recurrent", recurrent, 1024, 2, 4 * (3*8*2 + 2*4*8*4)},
|
||||
{"shared_layer", nil, 1024, 2, 0},
|
||||
} {
|
||||
got, ok := EstimateMemory(tc.cache, tc.tokens, tc.checkpoints)
|
||||
if !ok || got != tc.want {
|
||||
t.Errorf("%s: bytes=%d known=%v, want %d", tc.name, got, ok, tc.want)
|
||||
}
|
||||
}
|
||||
if _, ok := EstimateMemory(NewKVCache(), 1024, 2); ok {
|
||||
t.Fatal("uninitialized attention cache was treated as known")
|
||||
}
|
||||
if _, ok := EstimateMemory(full, -1, 2); ok {
|
||||
t.Fatal("invalid context was treated as known")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package mlxrunner
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
|
||||
"github.com/ollama/ollama/discover"
|
||||
"github.com/ollama/ollama/mlx"
|
||||
)
|
||||
|
||||
// Prefill and drafting also allocate buffers outside the cache. Reserve a shared
|
||||
// 4 GiB: the measured 4k–64k workloads on M2/M5 Macs included about 3 GiB of
|
||||
// additional temporary prefill storage on the older, smaller Mac.
|
||||
const parallelWorkspace = 4 << 30
|
||||
|
||||
func defaultParallelism(fullContextBytes, headroom int64) int {
|
||||
if fullContextBytes <= 0 || headroom <= parallelWorkspace {
|
||||
return 1
|
||||
}
|
||||
for _, parallel := range []int{8, 4, 2} {
|
||||
if fullContextBytes <= (headroom-parallelWorkspace)/int64(parallel) {
|
||||
return parallel
|
||||
}
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
func (r *Runner) configureParallelism() {
|
||||
if r.parallel > 0 {
|
||||
return
|
||||
}
|
||||
r.parallel = 1
|
||||
// Automatic capacity is qualified on Metal. Other backends retain the
|
||||
// existing serial default until their device budgets are qualified too.
|
||||
if !mlx.MetalIsAvailable() || r.fullContextBytes <= 0 {
|
||||
return
|
||||
}
|
||||
limit, err := mlx.MaxRecommendedWorkingSetSize()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
monitor, err := discover.NewMemoryMonitor()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer monitor.Close()
|
||||
memory, err := monitor.Read()
|
||||
if err != nil || memory.Pressure >= discover.PressureElevated || memory.FreeMemoryAboveTarget != nil && *memory.FreeMemoryAboveTarget < 0 {
|
||||
return
|
||||
}
|
||||
headroom := min(int64(limit)-int64(mlx.ActiveMemory()), memory.AvailableRAM)
|
||||
r.parallel = defaultParallelism(r.fullContextBytes, headroom)
|
||||
slog.Info("MLX automatic parallelism", "parallel", r.parallel, "context_length", r.contextLength,
|
||||
"full_context_bytes", r.fullContextBytes, "workspace", parallelWorkspace, "headroom", headroom)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package mlxrunner
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/ollama/ollama/mlx/mlxtest"
|
||||
)
|
||||
|
||||
func TestDefaultParallelism(t *testing.T) {
|
||||
const gib = 1 << 30
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
fullContextBytes, available int64
|
||||
want int
|
||||
}{
|
||||
{"unknown", 0, 128 * gib, 1},
|
||||
{"pressure", 4 * gib, -gib, 1},
|
||||
{"tight", 4 * gib, 10 * gib, 1},
|
||||
{"two", 4 * gib, 12 * gib, 2},
|
||||
{"four", 4 * gib, 20 * gib, 4},
|
||||
{"eight", 4 * gib, 36 * gib, 8},
|
||||
{"long_context", 16 * gib, 36 * gib, 2},
|
||||
{"large_system", 4 * gib, 512 * gib, 8},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := defaultParallelism(tc.fullContextBytes, tc.available); got != tc.want {
|
||||
t.Fatalf("got %d clients, want %d", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParallelismPreservesExplicitSetting(t *testing.T) {
|
||||
r := Runner{parallel: 3}
|
||||
r.configureParallelism()
|
||||
if r.parallel != 3 {
|
||||
t.Fatal("explicit parallelism changed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelShapesBudget(t *testing.T) {
|
||||
mlxtest.Run(t, func(t *mlxtest.T) {
|
||||
m := &scoringTestModel{}
|
||||
width, bytes := modelShapes(m, nil, 1024)
|
||||
// One float32 K/V value per token, two float32 recurrent values,
|
||||
// and eight hidden values retained while scoring.
|
||||
const target = 2*1024*2*4 + 3*2*4
|
||||
const hidden = 2 * 1024 * 8 * 4
|
||||
if width != 8 || bytes != target+hidden {
|
||||
t.Fatalf("width=%d bytes=%d, want 8 and %d", width, bytes, target+hidden)
|
||||
}
|
||||
width, bytes = modelShapes(m, nil, 0)
|
||||
if width != 8 || bytes != 0 {
|
||||
t.Fatalf("explicit capacity: width=%d bytes=%d, want 8 and 0", width, bytes)
|
||||
}
|
||||
})
|
||||
}
|
||||
+76
-21
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"slices"
|
||||
@@ -102,15 +103,16 @@ type queuedRequest interface {
|
||||
}
|
||||
|
||||
type Runner struct {
|
||||
parallel int
|
||||
Model model.Model
|
||||
weights *mlx.Scope
|
||||
Tokenizer *tokenizer.Tokenizer
|
||||
Requests chan queuedRequest
|
||||
Sampler *sample.Sampler
|
||||
cache *prefixCache
|
||||
contextLength int
|
||||
mlxThread *mlxthread.Thread
|
||||
parallel int
|
||||
fullContextBytes int64 // Estimated per-client storage at the model context limit.
|
||||
Model model.Model
|
||||
weights *mlx.Scope
|
||||
Tokenizer *tokenizer.Tokenizer
|
||||
Requests chan queuedRequest
|
||||
Sampler *sample.Sampler
|
||||
cache *prefixCache
|
||||
contextLength int
|
||||
mlxThread *mlxthread.Thread
|
||||
// grammarEngine is the structured-output subsystem; nil when the grammar
|
||||
// library or vocabulary failed to load.
|
||||
grammarEngine *grammarEngine
|
||||
@@ -132,6 +134,7 @@ func (r *Runner) Load(modelName string) error {
|
||||
r.weights = mlx.NewScope()
|
||||
r.weights.Attach(weights...)
|
||||
configureWiredMemory()
|
||||
r.configureParallelism()
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -222,7 +225,13 @@ func (r *Runner) loadModel(modelName string) (weights []*mlx.Array, err error) {
|
||||
r.cache = newPrefixCache(slices.Concat(caches, draftCaches))
|
||||
r.Sampler = sample.New(r.contextLength)
|
||||
r.spec = newSpeculation(r, pipelineSlot, draftModel, caches, draftCaches)
|
||||
r.grammarEngine = newGrammarEngine(logitsWidth(m), r.Tokenizer)
|
||||
var capacity int
|
||||
if r.parallel <= 0 && mlx.MetalIsAvailable() {
|
||||
capacity = r.contextLength
|
||||
}
|
||||
width, fullContextBytes := modelShapes(m, draftModel, capacity)
|
||||
r.fullContextBytes = fullContextBytes
|
||||
r.grammarEngine = newGrammarEngine(width, r.Tokenizer)
|
||||
|
||||
return w
|
||||
})
|
||||
@@ -248,26 +257,72 @@ func newDraftCaches(draft model.DraftModel) []cache.Cache {
|
||||
return draft.NewCaches()
|
||||
}
|
||||
|
||||
// logitsWidth reads a model's logits width off a one-token forward's static
|
||||
// shape — the same Forward and Unembed path decode logits take. Nothing is
|
||||
// evaluated.
|
||||
func logitsWidth(m model.Model) (width int) {
|
||||
// modelShapes inspects the existing one-token load graph without evaluating it.
|
||||
// Cache dimensions come from the same forward used for inference, including the
|
||||
// drafter. Budget the actual model limit: num_ctx is only a soft limit in MLX.
|
||||
func modelShapes(m model.Model, draft model.DraftModel, tokens int) (width int, fullContextBytes int64) {
|
||||
mlx.Scoped(func() {
|
||||
caches := m.NewCaches()
|
||||
hidden, _ := m.Forward(&batch.Batch{
|
||||
var draftCaches []cache.Cache
|
||||
if tokens > 0 {
|
||||
draftCaches = newDraftCaches(draft)
|
||||
}
|
||||
defer func() {
|
||||
for _, c := range slices.Concat(caches, draftCaches) {
|
||||
if c != nil {
|
||||
c.Free()
|
||||
}
|
||||
}
|
||||
}()
|
||||
b := &batch.Batch{
|
||||
InputIDs: mlx.FromValues([]int32{0}, 1, 1),
|
||||
SeqOffsets: []int32{0},
|
||||
SeqQueryLens: []int32{1},
|
||||
}, cache.Layers(caches))
|
||||
}
|
||||
hidden, aux := m.Forward(b, cache.Layers(caches))
|
||||
logits := m.Unembed(hidden)
|
||||
width = logits.Dim(logits.NumDims() - 1)
|
||||
for _, c := range caches {
|
||||
if c != nil {
|
||||
c.Free()
|
||||
}
|
||||
if tokens <= 0 {
|
||||
return
|
||||
}
|
||||
if len(draftCaches) > 0 {
|
||||
if aux == nil {
|
||||
return
|
||||
}
|
||||
b.Hidden = aux
|
||||
draft.Forward(b, cache.Layers(caches), cache.Layers(draftCaches))
|
||||
}
|
||||
checkpoints := (tokens + prefillSnapshotInterval - 1) / prefillSnapshotInterval
|
||||
for _, c := range caches {
|
||||
bytes, ok := cache.EstimateMemory(c, tokens, checkpoints)
|
||||
if !ok || bytes > math.MaxInt64-fullContextBytes {
|
||||
fullContextBytes = 0
|
||||
return
|
||||
}
|
||||
fullContextBytes += bytes
|
||||
}
|
||||
if fullContextBytes == 0 {
|
||||
return
|
||||
}
|
||||
// Scoring keeps the target's hidden outputs and briefly holds both
|
||||
// sides of a growing concatenation. It does not run the drafter.
|
||||
hiddenBytes := int64(hidden.NumBytes())
|
||||
if hiddenBytes > (math.MaxInt64-fullContextBytes)/int64(tokens)/2 {
|
||||
fullContextBytes = 0
|
||||
return
|
||||
}
|
||||
scoreBytes := fullContextBytes + 2*hiddenBytes*int64(tokens)
|
||||
for _, c := range draftCaches {
|
||||
bytes, ok := cache.EstimateMemory(c, tokens, checkpoints)
|
||||
if !ok || bytes > math.MaxInt64-fullContextBytes {
|
||||
fullContextBytes = 0
|
||||
return
|
||||
}
|
||||
fullContextBytes += bytes
|
||||
}
|
||||
fullContextBytes = max(fullContextBytes, scoreBytes)
|
||||
})
|
||||
return width
|
||||
return width, fullContextBytes
|
||||
}
|
||||
|
||||
func configureWiredMemory() {
|
||||
|
||||
+1
-1
@@ -63,7 +63,7 @@ func Execute(args []string) error {
|
||||
defer cancelRunner()
|
||||
|
||||
runner := Runner{
|
||||
parallel: max(1, int(envconfig.NumParallel())),
|
||||
parallel: int(envconfig.NumParallel()),
|
||||
Requests: make(chan queuedRequest),
|
||||
mlxThread: worker,
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user