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>
194 lines
5.5 KiB
Go
194 lines
5.5 KiB
Go
// 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
|
|
}
|