Ollama proxy; spread leases across GPUs
The proxy leases a not-yet-loaded model's size (+20%) and forces CPU-only with 4 threads on a CPU grant; loaded models, other endpoints and a down broker pass through. Spread leases let a model use both cards, as Ollama does with gemma4-12b (8.4 GB > the 1080's 8 GB). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
29fafa8b3e
commit
20b1bc4c27
7 files changed
+512
-35
No files matched your search
@@ -103,6 +103,10 @@ components:
|
||||
type: array
|
||||
items: {type: integer}
|
||||
description: GPU indexes to try first.
|
||||
spread:
|
||||
type: boolean
|
||||
default: false
|
||||
description: May be split across GPUs (Ollama splits a model that fits no single card).
|
||||
Grant:
|
||||
type: object
|
||||
required: [device, gpu]
|
||||
|
||||
+28
-24
@@ -134,7 +134,10 @@ type LeaseRequest struct {
|
||||
// Prefer GPU indexes to try first.
|
||||
Prefer *[]int `json:"prefer,omitempty"`
|
||||
Priority Priority `json:"priority"`
|
||||
VramMb int `json:"vram_mb"`
|
||||
|
||||
// Spread May be split across GPUs (Ollama splits a model that fits no single card).
|
||||
Spread *bool `json:"spread,omitempty"`
|
||||
VramMb int `json:"vram_mb"`
|
||||
}
|
||||
|
||||
// Priority defines model for Priority.
|
||||
@@ -1623,29 +1626,30 @@ func (sh *strictHandler) Status(w http.ResponseWriter, r *http.Request) {
|
||||
// const string: with thousands of chunks the chained `+` fold is several
|
||||
// times slower for the Go compiler than parsing a slice literal.
|
||||
var swaggerSpec = []string{
|
||||
"vFdtb9u2E/8qB/7/wBJAkeUm2woVe5EWQzqgA4KuWQc0gUNLZ4sNRarkKYkR6LsPJCX5QXKaFO1emabI",
|
||||
"e/zd744PLNNlpRUqsix9YBU3vERC4/+9Q27xj9wthWIpqzgVLGKKl8hSJnIWMYNfamEwZymZGiNmswJL",
|
||||
"7m7QqnKnLBmhlqxpGnfYVlpZ9MLPjZ5LLN0y04pQkVvyqpIi4yS0mny2Wrm9tcz/G1ywlP1vsrZ6Er7a",
|
||||
"SSfPa8rRZkZU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Qsgrgtg9L01j",
|
||||
"NBKBQ4N3WMDBdSDzNSgTrsYR5fANOIwA+hIruCvRMPgY0P6gyKMhjuL41d/TLM3SMVijl2+4AsvGl2h8",
|
||||
"N96nl0YkwiuvUUw4pY4i6swqdBQ5MmYZTFNbo5G1EhNxnGbpMbNQ+jLkz+h2PCpXk9kCQypxggU1/Hzp",
|
||||
"B7dHL5BXWfbLXh+dhoHHxwafFEFTgzQFlJJC8HKmZiBgnBT5kcIi2Kd1lawtDQwob7XNbwga45XuOKoI",
|
||||
"5g4xWcW6JwMEz5gy1sGaSR2RuB1uA3aah7wPDOleeUj+rS2WvwyxramsbdvHb8n2N0YrvnwGgnUWx0o4",
|
||||
"CHgGtDooD1Om4UmW7ZO9Mnb9Ek3Eyfj4Ref/mr3k/COqjB5U0UaeaPS4mwafYub2Ud187H8dVro+Mup/",
|
||||
"DGivdgJzskvOThUjqcnGMqE8lLIAqXnaW3Z1h4exQUdGoRBt0v+xMwbv/hhXQkHs4n/yM/FZPxAHy1M3",
|
||||
"Kf1Gwncahhh/fkFJbIkUShPzPXS3GJc2EaE3dcg2TouJKL2vJ6PRqsZPXo+PM9Fetf8fAA==",
|
||||
}
|
||||
|
||||
// decodeSpec returns the embedded OpenAPI spec as raw JSON bytes,
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
// Package ollamaproxy sits in front of Ollama and asks the broker before a model loads.
|
||||
//
|
||||
// Requests for a model that's already loaded go straight through. For one that
|
||||
// isn't, the proxy leases its size (from Ollama's model list, +20% for context)
|
||||
// from the broker. On a GPU grant the request is forwarded unchanged and the
|
||||
// lease released when the response ends (the model then shows in nvidia-smi).
|
||||
// On a CPU grant, native requests get options.num_gpu = 0 and a small
|
||||
// num_thread, so the model runs entirely on a few CPU cores instead of
|
||||
// spilling partly onto all of them. If the broker can't be reached, requests
|
||||
// pass through untouched: the broker must never take Ollama down.
|
||||
package ollamaproxy
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.godemperordoge.org/ziadarafat/gpu-broker/internal/api"
|
||||
)
|
||||
|
||||
const mib = 1 << 20
|
||||
|
||||
// Native endpoints whose body has "options"; the OpenAI-compatible ones are
|
||||
// leased too but can't be forced onto the CPU.
|
||||
var native = map[string]bool{"/api/chat": true, "/api/generate": true, "/api/embed": true, "/api/embeddings": true}
|
||||
var openai = map[string]bool{"/v1/chat/completions": true, "/v1/completions": true, "/v1/embeddings": true}
|
||||
|
||||
// Config for the proxy.
|
||||
type Config struct {
|
||||
Upstream string // Ollama, e.g. http://127.0.0.1:11435
|
||||
Broker string // gpu-broker, e.g. http://127.0.0.1:8130
|
||||
MaxWait time.Duration // queue time before the CPU fallback
|
||||
CPUThreads int // num_thread on CPU fallback
|
||||
Prefer []int // GPUs to try first (the 1080 for LLMs)
|
||||
}
|
||||
|
||||
// Proxy is an http.Handler.
|
||||
type Proxy struct {
|
||||
cfg Config
|
||||
upstream *url.URL
|
||||
rp *httputil.ReverseProxy
|
||||
broker *api.ClientWithResponses
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
// New builds a proxy.
|
||||
func New(cfg Config) (*Proxy, error) {
|
||||
u, err := url.Parse(cfg.Upstream)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b, err := api.NewClientWithResponses(cfg.Broker)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rp := httputil.NewSingleHostReverseProxy(u)
|
||||
rp.FlushInterval = -1 // stream tokens as they come
|
||||
return &Proxy{cfg: cfg, upstream: u, rp: rp, broker: b, http: &http.Client{Timeout: 10 * time.Second}}, nil
|
||||
}
|
||||
|
||||
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost || !(native[r.URL.Path] || openai[r.URL.Path]) {
|
||||
p.rp.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
raw, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var body map[string]any
|
||||
if json.Unmarshal(raw, &body) != nil {
|
||||
p.forward(w, r, raw)
|
||||
return
|
||||
}
|
||||
model, _ := body["model"].(string)
|
||||
lease, device := p.lease(r.Context(), model)
|
||||
if lease != "" {
|
||||
defer p.release(lease)
|
||||
}
|
||||
if device == api.Cpu && native[r.URL.Path] {
|
||||
opts, _ := body["options"].(map[string]any)
|
||||
if opts == nil {
|
||||
opts = map[string]any{}
|
||||
}
|
||||
opts["num_gpu"] = 0
|
||||
opts["num_thread"] = p.cfg.CPUThreads
|
||||
body["options"] = opts
|
||||
if changed, err := json.Marshal(body); err == nil {
|
||||
raw = changed
|
||||
}
|
||||
slog.Info("CPU fallback", "model", model, "path", r.URL.Path)
|
||||
}
|
||||
p.forward(w, r, raw)
|
||||
}
|
||||
|
||||
func (p *Proxy) forward(w http.ResponseWriter, r *http.Request, body []byte) {
|
||||
r.Body = io.NopCloser(bytes.NewReader(body))
|
||||
r.ContentLength = int64(len(body))
|
||||
r.Header.Del("Content-Length")
|
||||
p.rp.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// lease returns the lease id ("" when none) and the device to use. Anything
|
||||
// unexpected means "GPU, no lease": let Ollama decide as it always has.
|
||||
func (p *Proxy) lease(ctx context.Context, model string) (string, api.GrantDevice) {
|
||||
if model == "" || p.loaded(model) {
|
||||
return "", api.Gpu
|
||||
}
|
||||
size := p.size(model)
|
||||
if size == 0 {
|
||||
return "", api.Gpu
|
||||
}
|
||||
wait := int(p.cfg.MaxWait / time.Second)
|
||||
fallback, spread := true, true // Ollama splits a model across both cards when needed
|
||||
prefer := p.cfg.Prefer
|
||||
resp, err := p.broker.AcquireLeaseWithResponse(ctx, api.AcquireLeaseJSONRequestBody{
|
||||
Client: "ollama:" + model, Priority: api.Interactive, VramMb: size * 12 / 10 / mib,
|
||||
MaxWaitS: &wait, CpuFallback: &fallback, Prefer: &prefer, Spread: &spread,
|
||||
})
|
||||
if err != nil || resp.JSON200 == nil {
|
||||
slog.Warn("broker unavailable; passing through", "model", model, "err", err)
|
||||
return "", api.Gpu
|
||||
}
|
||||
if resp.JSON200.LeaseId != nil {
|
||||
return *resp.JSON200.LeaseId, resp.JSON200.Device
|
||||
}
|
||||
return "", resp.JSON200.Device
|
||||
}
|
||||
|
||||
func (p *Proxy) release(id string) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_, _ = p.broker.ReleaseLease(ctx, id)
|
||||
}
|
||||
|
||||
// fullName adds Ollama's default tag.
|
||||
func fullName(model string) string {
|
||||
if strings.Contains(model, ":") {
|
||||
return model
|
||||
}
|
||||
return model + ":latest"
|
||||
}
|
||||
|
||||
func (p *Proxy) getJSON(path string, into any) error {
|
||||
resp, err := p.http.Get(p.upstream.JoinPath(path).String())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
return json.NewDecoder(resp.Body).Decode(into)
|
||||
}
|
||||
|
||||
type modelList struct {
|
||||
Models []struct {
|
||||
Name string `json:"name"`
|
||||
Size int `json:"size"`
|
||||
} `json:"models"`
|
||||
}
|
||||
|
||||
func (p *Proxy) loaded(model string) bool {
|
||||
var ps modelList
|
||||
if p.getJSON("/api/ps", &ps) != nil {
|
||||
return false
|
||||
}
|
||||
for _, m := range ps.Models {
|
||||
if m.Name == fullName(model) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// size is the model's file size in bytes, 0 if Ollama doesn't have it.
|
||||
func (p *Proxy) size(model string) int {
|
||||
var tags modelList
|
||||
if p.getJSON("/api/tags", &tags) != nil {
|
||||
return 0
|
||||
}
|
||||
for _, m := range tags.Models {
|
||||
if m.Name == fullName(model) {
|
||||
return m.Size
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package ollamaproxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.godemperordoge.org/ziadarafat/gpu-broker/internal/sched"
|
||||
"gitea.godemperordoge.org/ziadarafat/gpu-broker/internal/server"
|
||||
)
|
||||
|
||||
const gib = 1 << 30
|
||||
|
||||
// fakeOllama serves /api/tags and /api/ps like Ollama and records inference bodies.
|
||||
type fakeOllama struct {
|
||||
mu sync.Mutex
|
||||
loaded []string
|
||||
bodies []map[string]any
|
||||
paths []string
|
||||
}
|
||||
|
||||
func (f *fakeOllama) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.paths = append(f.paths, r.Method+" "+r.URL.Path)
|
||||
switch r.URL.Path {
|
||||
case "/api/tags":
|
||||
json.NewEncoder(w).Encode(map[string]any{"models": []map[string]any{
|
||||
{"name": "gemma4-12b-qat:latest", "size": 7 * gib},
|
||||
{"name": "qwen3.5-9b-gpu:latest", "size": 7 * gib},
|
||||
}})
|
||||
case "/api/ps":
|
||||
var models []map[string]any
|
||||
for _, m := range f.loaded {
|
||||
models = append(models, map[string]any{"name": m, "size_vram": 7 * gib})
|
||||
}
|
||||
json.NewEncoder(w).Encode(map[string]any{"models": models})
|
||||
default:
|
||||
var body map[string]any
|
||||
json.NewDecoder(r.Body).Decode(&body)
|
||||
f.bodies = append(f.bodies, body)
|
||||
w.Header().Set("Content-Type", "application/x-ndjson")
|
||||
io.WriteString(w, `{"message":{"content":"hi"},"done":false}`+"\n")
|
||||
w.(http.Flusher).Flush()
|
||||
io.WriteString(w, `{"done":true}`+"\n")
|
||||
}
|
||||
}
|
||||
|
||||
type rig struct {
|
||||
proxy *httptest.Server
|
||||
ollama *fakeOllama
|
||||
sched *sched.Scheduler
|
||||
}
|
||||
|
||||
// newRig wires proxy -> fake Ollama, with a real broker whose GPUs have used0/used1 MB in use.
|
||||
func newRig(t *testing.T, used0, used1 int, brokerUp bool) *rig {
|
||||
t.Helper()
|
||||
s := sched.New(sched.Config{ReserveMB: map[int]int{0: 1500}, LoadWindow: time.Minute, LeaseTTL: time.Minute}, time.Now)
|
||||
s.Observe([]sched.GPU{{Index: 0, TotalMB: 6144, UsedMB: used0}, {Index: 1, TotalMB: 8192, UsedMB: used1}})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
go server.Tick(ctx, s, 20*time.Millisecond)
|
||||
broker := httptest.NewServer(server.Handler(s, time.Minute))
|
||||
t.Cleanup(broker.Close)
|
||||
brokerURL := broker.URL
|
||||
if !brokerUp {
|
||||
brokerURL = "http://127.0.0.1:1" // nothing listens there
|
||||
}
|
||||
o := &fakeOllama{}
|
||||
up := httptest.NewServer(o)
|
||||
t.Cleanup(up.Close)
|
||||
p, err := New(Config{Upstream: up.URL, Broker: brokerURL, MaxWait: time.Second, CPUThreads: 4, Prefer: []int{1}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
px := httptest.NewServer(p)
|
||||
t.Cleanup(px.Close)
|
||||
return &rig{proxy: px, ollama: o, sched: s}
|
||||
}
|
||||
|
||||
func (r *rig) chat(t *testing.T, model string, extra string) string {
|
||||
t.Helper()
|
||||
body := `{"model":"` + model + `","messages":[{"role":"user","content":"hi"}]` + extra + `}`
|
||||
resp, err := http.Post(r.proxy.URL+"/api/chat", "application/json", strings.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
out, _ := io.ReadAll(resp.Body)
|
||||
return string(out)
|
||||
}
|
||||
|
||||
func (r *rig) lastBody(t *testing.T) map[string]any {
|
||||
t.Helper()
|
||||
r.ollama.mu.Lock()
|
||||
defer r.ollama.mu.Unlock()
|
||||
if len(r.ollama.bodies) == 0 {
|
||||
t.Fatal("Ollama got no request")
|
||||
}
|
||||
return r.ollama.bodies[len(r.ollama.bodies)-1]
|
||||
}
|
||||
|
||||
func TestFreeGPUForwardsTheRequestUnchanged(t *testing.T) {
|
||||
r := newRig(t, 0, 0, true)
|
||||
out := r.chat(t, "gemma4-12b-qat", `,"options":{"temperature":0}`)
|
||||
if !strings.Contains(out, `"done":true`) {
|
||||
t.Fatalf("response %q", out)
|
||||
}
|
||||
body := r.lastBody(t)
|
||||
if body["options"].(map[string]any)["num_gpu"] != nil {
|
||||
t.Fatalf("GPU request was changed: %v", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLeaseSizeComesFromTheModelListAndIsReleasedAfter(t *testing.T) {
|
||||
r := newRig(t, 0, 0, true)
|
||||
r.chat(t, "gemma4-12b-qat", "")
|
||||
// the lease was released once the response finished
|
||||
if n := len(r.sched.Status().Leases); n != 0 {
|
||||
t.Fatalf("%d leases left", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBusyGPUsSendTheRequestToTheCPUWithFewThreads(t *testing.T) {
|
||||
r := newRig(t, 6144, 8192, true)
|
||||
r.chat(t, "gemma4-12b-qat", `,"options":{"temperature":0}`)
|
||||
opts := r.lastBody(t)["options"].(map[string]any)
|
||||
if opts["num_gpu"] != float64(0) || opts["num_thread"] != float64(4) || opts["temperature"] != float64(0) {
|
||||
t.Fatalf("options %v", opts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadedModelsSkipTheBroker(t *testing.T) {
|
||||
r := newRig(t, 6144, 8192, true) // GPUs look full: because the model is already on them
|
||||
r.ollama.loaded = []string{"gemma4-12b-qat:latest"}
|
||||
r.chat(t, "gemma4-12b-qat", "")
|
||||
if r.lastBody(t)["options"] != nil {
|
||||
t.Fatalf("loaded model was sent to the CPU: %v", r.lastBody(t))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBrokerDownPassesThrough(t *testing.T) {
|
||||
r := newRig(t, 0, 0, false)
|
||||
out := r.chat(t, "gemma4-12b-qat", "")
|
||||
if !strings.Contains(out, `"done":true`) || r.lastBody(t)["options"] != nil {
|
||||
t.Fatalf("got %q / %v", out, r.lastBody(t))
|
||||
}
|
||||
}
|
||||
|
||||
func TestOtherEndpointsPassThrough(t *testing.T) {
|
||||
r := newRig(t, 6144, 8192, true)
|
||||
resp, err := http.Get(r.proxy.URL + "/api/tags")
|
||||
if err != nil || resp.StatusCode != 200 {
|
||||
t.Fatalf("%v %v", err, resp)
|
||||
}
|
||||
if len(r.sched.Status().Leases)+len(r.sched.Status().Waiting) != 0 {
|
||||
t.Fatal("tags asked the broker")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownModelsPassThrough(t *testing.T) {
|
||||
r := newRig(t, 6144, 8192, true)
|
||||
r.chat(t, "not-pulled-yet", "")
|
||||
if r.lastBody(t)["options"] != nil {
|
||||
t.Fatal("unknown model was changed")
|
||||
}
|
||||
}
|
||||
+72
-11
@@ -50,6 +50,7 @@ type Request struct {
|
||||
MaxWait time.Duration // 0 = wait as long as it takes
|
||||
CPUFallback bool // after MaxWait (or if it can never fit), answer CPU instead of failing
|
||||
Prefer []int // GPUs to try first, in order
|
||||
Spread bool // may be split across GPUs (Ollama splits a model that fits no single card)
|
||||
}
|
||||
|
||||
// Grant is the answer: a GPU (or CPU) and the lease to renew and release.
|
||||
@@ -69,8 +70,9 @@ type Config struct {
|
||||
type lease struct {
|
||||
id string
|
||||
client string
|
||||
gpu int
|
||||
vram int
|
||||
gpu int // primary GPU
|
||||
vram int // total
|
||||
parts map[int]int // VRAM per GPU
|
||||
granted time.Time
|
||||
expires time.Time
|
||||
}
|
||||
@@ -116,7 +118,7 @@ func (s *Scheduler) Observe(gpus []GPU) {
|
||||
func (s *Scheduler) Acquire(ctx context.Context, req Request) (Grant, error) {
|
||||
s.mu.Lock()
|
||||
now := s.now()
|
||||
if req.VRAMMB > s.largest() {
|
||||
if req.VRAMMB > s.largest(req.Spread) {
|
||||
s.mu.Unlock()
|
||||
if req.CPUFallback {
|
||||
return Grant{GPU: CPU}, nil
|
||||
@@ -195,11 +197,16 @@ func (s *Scheduler) Tick() {
|
||||
s.schedule()
|
||||
}
|
||||
|
||||
// largest is the most VRAM any single GPU could ever lease.
|
||||
func (s *Scheduler) largest() int {
|
||||
best := 0
|
||||
// largest is the most VRAM one request could ever lease: on one GPU, or on all together.
|
||||
func (s *Scheduler) largest(spread bool) int {
|
||||
best, sum := 0, 0
|
||||
for _, g := range s.gpus {
|
||||
best = max(best, g.TotalMB-s.cfg.ReserveMB[g.Index])
|
||||
usable := g.TotalMB - s.cfg.ReserveMB[g.Index]
|
||||
best = max(best, usable)
|
||||
sum += max(usable, 0)
|
||||
}
|
||||
if spread {
|
||||
return sum
|
||||
}
|
||||
return best
|
||||
}
|
||||
@@ -212,7 +219,9 @@ func (s *Scheduler) free(now time.Time) map[int]int {
|
||||
}
|
||||
for _, l := range s.leases {
|
||||
if now.Sub(l.granted) < s.cfg.LoadWindow {
|
||||
free[l.gpu] -= l.vram
|
||||
for g, mb := range l.parts {
|
||||
free[g] -= mb
|
||||
}
|
||||
}
|
||||
}
|
||||
return free
|
||||
@@ -234,13 +243,15 @@ func (s *Scheduler) schedule() {
|
||||
return queue[i].seq < queue[j].seq
|
||||
})
|
||||
for _, w := range queue {
|
||||
gpu, ok := pick(w.req, free)
|
||||
parts, gpu, ok := place(w.req, free)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
free[gpu] -= w.req.VRAMMB
|
||||
for g, mb := range parts {
|
||||
free[g] -= mb
|
||||
}
|
||||
l := &lease{
|
||||
id: newID(), client: w.req.Client, gpu: gpu, vram: w.req.VRAMMB,
|
||||
id: newID(), client: w.req.Client, gpu: gpu, vram: w.req.VRAMMB, parts: parts,
|
||||
granted: now, expires: now.Add(s.cfg.LeaseTTL),
|
||||
}
|
||||
s.leases[l.id] = l
|
||||
@@ -249,6 +260,56 @@ func (s *Scheduler) schedule() {
|
||||
}
|
||||
}
|
||||
|
||||
// place decides where a request goes: one GPU, or (Spread) split over several,
|
||||
// filling preferred GPUs first and then those with the most room.
|
||||
func place(req Request, free map[int]int) (map[int]int, int, bool) {
|
||||
if g, ok := pick(req, free); ok {
|
||||
return map[int]int{g: req.VRAMMB}, g, true
|
||||
}
|
||||
if !req.Spread {
|
||||
return nil, 0, false
|
||||
}
|
||||
order := append([]int(nil), req.Prefer...)
|
||||
var rest []int
|
||||
for g := range free {
|
||||
if !contains(order, g) {
|
||||
rest = append(rest, g)
|
||||
}
|
||||
}
|
||||
sort.Slice(rest, func(i, j int) bool {
|
||||
if free[rest[i]] != free[rest[j]] {
|
||||
return free[rest[i]] > free[rest[j]]
|
||||
}
|
||||
return rest[i] < rest[j]
|
||||
})
|
||||
order = append(order, rest...)
|
||||
parts, need, primary := map[int]int{}, req.VRAMMB, -2
|
||||
for _, g := range order {
|
||||
take := min(max(free[g], 0), need)
|
||||
if take <= 0 {
|
||||
continue
|
||||
}
|
||||
if primary == -2 {
|
||||
primary = g
|
||||
}
|
||||
parts[g] = take
|
||||
need -= take
|
||||
if need == 0 {
|
||||
return parts, primary, true
|
||||
}
|
||||
}
|
||||
return nil, 0, false
|
||||
}
|
||||
|
||||
func contains(xs []int, x int) bool {
|
||||
for _, v := range xs {
|
||||
if v == x {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// pick returns a preferred GPU that fits, else the one with the most room.
|
||||
func pick(req Request, free map[int]int) (int, bool) {
|
||||
for _, g := range req.Prefer {
|
||||
|
||||
@@ -250,3 +250,42 @@ func TestCancelledRequestLeavesTheQueue(t *testing.T) {
|
||||
t.Fatalf("%d still queued", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSpreadRequestsMayUseBothGPUs(t *testing.T) {
|
||||
c := newClock()
|
||||
s := yveltal(c)
|
||||
// 8600 MB fits no single card but fits 1080 (8192) + 1060 (6144-1500) together
|
||||
r := waitFor(t, acquire(s, Request{Client: "ollama", Priority: Interactive, VRAMMB: 8600, Spread: true, Prefer: []int{1}}))
|
||||
if r.err != nil || r.grant.GPU != 1 {
|
||||
t.Fatalf("got %+v, %v; want GPU 1 first", r.grant, r.err)
|
||||
}
|
||||
// the preferred card filled first, the rest went to GPU 0: 8192 + 408
|
||||
free := map[int]int{}
|
||||
for _, g := range s.Status().GPUs {
|
||||
free[g.Index] = g.FreeMB
|
||||
}
|
||||
if free[1] != 0 || free[0] != 4644-408 {
|
||||
t.Fatalf("free after spread lease: %v", free)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSpreadRequestsWaitWhenTheTotalIsShort(t *testing.T) {
|
||||
c := newClock()
|
||||
s := yveltal(c)
|
||||
s.Observe([]GPU{{Index: 0, TotalMB: 6144, UsedMB: 4000}, {Index: 1, TotalMB: 8192, UsedMB: 2000}})
|
||||
// free: 644 + 6192 = 6836 < 8600
|
||||
ch := acquire(s, Request{Client: "ollama", Priority: Interactive, VRAMMB: 8600, Spread: true, MaxWait: time.Hour})
|
||||
stillWaiting(t, ch)
|
||||
}
|
||||
|
||||
func TestSpreadIsOnlyTooBigBeyondAllGPUsTogether(t *testing.T) {
|
||||
s := yveltal(newClock())
|
||||
r := waitFor(t, acquire(s, Request{Client: "ollama", Priority: Interactive, VRAMMB: 12800, Spread: true}))
|
||||
if r.err != nil || r.grant.GPU == CPU {
|
||||
t.Fatalf("12800 MB fits 8192 + 4644 = 12836: got %+v, %v", r.grant, r.err)
|
||||
}
|
||||
r = waitFor(t, acquire(s, Request{Client: "big", Priority: Interactive, VRAMMB: 17000, Spread: true, CPUFallback: true}))
|
||||
if r.grant.GPU != CPU {
|
||||
t.Fatalf("17 GB can't fit: got %+v", r.grant)
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,9 @@ func (h handlers) AcquireLease(ctx context.Context, r api.AcquireLeaseRequestObj
|
||||
if body.Prefer != nil {
|
||||
req.Prefer = *body.Prefer
|
||||
}
|
||||
if body.Spread != nil {
|
||||
req.Spread = *body.Spread
|
||||
}
|
||||
g, err := h.s.Acquire(ctx, req)
|
||||
switch {
|
||||
case errors.Is(err, sched.ErrTooBig):
|
||||
|
||||
Reference in new issue
Block a user