From 443bf126122ab062a5243f48649c555c9bb3013e Mon Sep 17 00:00:00 2001 From: Ziad Arafat Date: Wed, 11 Nov 2026 13:56:51 -0700 Subject: [PATCH] gpu-run and the gpu-broker binary (serve, ollama-proxy) Co-Authored-By: Claude Opus 5.5 --- cmd/gpu-broker/main.go | 137 ++++++++++++++++++++++++++++++++++++ cmd/gpu-broker/main_test.go | 27 +++++++ cmd/gpu-run/main.go | 40 +++++++++++ internal/run/run.go | 128 +++++++++++++++++++++++++++++++++ internal/run/run_test.go | 42 +++++++++++ 5 files changed, 374 insertions(+) create mode 100644 cmd/gpu-broker/main.go create mode 100644 cmd/gpu-broker/main_test.go create mode 100644 cmd/gpu-run/main.go create mode 100644 internal/run/run.go create mode 100644 internal/run/run_test.go diff --git a/cmd/gpu-broker/main.go b/cmd/gpu-broker/main.go new file mode 100644 index 0000000..9c49a53 --- /dev/null +++ b/cmd/gpu-broker/main.go @@ -0,0 +1,137 @@ +// gpu-broker: the GPU scheduler daemon (serve) and the Ollama proxy (ollama-proxy). +package main + +import ( + "context" + "flag" + "fmt" + "log/slog" + "net/http" + "os" + "os/signal" + "strconv" + "strings" + "syscall" + "time" + + "gitea.godemperordoge.org/ziadarafat/gpu-broker/internal/nvsmi" + "gitea.godemperordoge.org/ziadarafat/gpu-broker/internal/ollamaproxy" + "gitea.godemperordoge.org/ziadarafat/gpu-broker/internal/sched" + "gitea.godemperordoge.org/ziadarafat/gpu-broker/internal/server" +) + +func main() { + if len(os.Args) < 2 { + fmt.Fprintln(os.Stderr, "usage: gpu-broker serve|ollama-proxy [flags]") + os.Exit(2) + } + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + var err error + switch os.Args[1] { + case "serve": + err = serve(ctx, os.Args[2:]) + case "ollama-proxy": + err = proxy(ctx, os.Args[2:]) + default: + err = fmt.Errorf("unknown command %q", os.Args[1]) + } + if err != nil { + slog.Error("exit", "err", err) + os.Exit(1) + } +} + +// reserves parses "0=1500,1=0". +func reserves(s string) (map[int]int, error) { + out := map[int]int{} + for _, part := range strings.Split(s, ",") { + if part == "" { + continue + } + k, v, ok := strings.Cut(part, "=") + gpu, err1 := strconv.Atoi(k) + mb, err2 := strconv.Atoi(v) + if !ok || err1 != nil || err2 != nil { + return nil, fmt.Errorf("bad reserve %q (want gpu=MB)", part) + } + out[gpu] = mb + } + return out, nil +} + +func ints(s string) []int { + var out []int + for _, f := range strings.Split(s, ",") { + if n, err := strconv.Atoi(strings.TrimSpace(f)); err == nil { + out = append(out, n) + } + } + return out +} + +func serve(ctx context.Context, args []string) error { + fs := flag.NewFlagSet("serve", flag.ExitOnError) + listen := fs.String("listen", "127.0.0.1:8130", "address") + reserve := fs.String("reserve", "0=1500", "VRAM per GPU nobody may lease, gpu=MB,...") + window := fs.Duration("load-window", time.Minute, "how long a fresh lease's VRAM is counted") + ttl := fs.Duration("lease-ttl", 5*time.Minute, "leases expire unless renewed") + every := fs.Duration("sample", 2*time.Second, "nvidia-smi interval") + fs.Parse(args) + res, err := reserves(*reserve) + if err != nil { + return err + } + s := sched.New(sched.Config{ReserveMB: res, LoadWindow: *window, LeaseTTL: *ttl}, time.Now) + go server.Tick(ctx, s, 500*time.Millisecond) + go func() { + t := time.NewTicker(*every) + defer t.Stop() + for { + if gpus, err := nvsmi.Sample(ctx); err != nil { + slog.Warn("sample failed", "err", err) + } else { + s.Observe(gpus) + } + select { + case <-ctx.Done(): + return + case <-t.C: + } + } + }() + return listenAndServe(ctx, *listen, server.Handler(s, *ttl)) +} + +func proxy(ctx context.Context, args []string) error { + fs := flag.NewFlagSet("ollama-proxy", flag.ExitOnError) + listen := fs.String("listen", "0.0.0.0:11434", "address (where clients expect Ollama)") + upstream := fs.String("upstream", "http://127.0.0.1:11435", "Ollama") + broker := fs.String("broker", "http://127.0.0.1:8130", "gpu-broker") + wait := fs.Duration("max-wait", time.Minute, "queue time before the CPU fallback") + threads := fs.Int("cpu-threads", 4, "num_thread on CPU fallback") + prefer := fs.String("prefer", "1", "GPUs to fill first") + fs.Parse(args) + p, err := ollamaproxy.New(ollamaproxy.Config{ + Upstream: *upstream, Broker: *broker, MaxWait: *wait, CPUThreads: *threads, Prefer: ints(*prefer), + }) + if err != nil { + return err + } + return listenAndServe(ctx, *listen, p) +} + +func listenAndServe(ctx context.Context, addr string, h http.Handler) error { + srv := &http.Server{Addr: addr, Handler: h, ReadHeaderTimeout: 10 * time.Second} + go func() { + <-ctx.Done() + sctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + _ = srv.Shutdown(sctx) + }() + slog.Info("listening", "addr", addr) + if err := srv.ListenAndServe(); err != http.ErrServerClosed { + return err + } + return nil +} diff --git a/cmd/gpu-broker/main_test.go b/cmd/gpu-broker/main_test.go new file mode 100644 index 0000000..603ae23 --- /dev/null +++ b/cmd/gpu-broker/main_test.go @@ -0,0 +1,27 @@ +package main + +import ( + "reflect" + "testing" +) + +func TestReserves(t *testing.T) { + got, err := reserves("0=1500,1=0") + if err != nil || !reflect.DeepEqual(got, map[int]int{0: 1500, 1: 0}) { + t.Fatalf("%v %v", got, err) + } + for _, bad := range []string{"0", "a=1", "0=x"} { + if _, err := reserves(bad); err == nil { + t.Errorf("reserves(%q) accepted", bad) + } + } + if got, err := reserves(""); err != nil || len(got) != 0 { + t.Fatalf("empty: %v %v", got, err) + } +} + +func TestInts(t *testing.T) { + if got := ints("1, 0"); !reflect.DeepEqual(got, []int{1, 0}) { + t.Fatalf("%v", got) + } +} diff --git a/cmd/gpu-run/main.go b/cmd/gpu-run/main.go new file mode 100644 index 0000000..16982af --- /dev/null +++ b/cmd/gpu-run/main.go @@ -0,0 +1,40 @@ +// gpu-run: gpu-run [flags] -- command args... Lease a GPU for a command, or run it CPU-capped. +package main + +import ( + "context" + "flag" + "fmt" + "os" + "time" + + "gitea.godemperordoge.org/ziadarafat/gpu-broker/internal/api" + "gitea.godemperordoge.org/ziadarafat/gpu-broker/internal/run" +) + +func main() { + broker := flag.String("broker", "http://127.0.0.1:8130", "gpu-broker") + client := flag.String("client", "", "name shown in the broker's status (default: the command)") + vram := flag.Int("vram", 0, "VRAM the command needs, MB (required)") + priority := flag.String("priority", "batch", "batch, interactive or realtime") + wait := flag.Duration("max-wait", 10*time.Minute, "queue time before running on the CPU") + quota := flag.Int("cpu-quota", 400, "CPU cap on fallback, percent (100 = one core; 0 = none)") + spread := flag.Bool("spread", false, "may use more than one GPU") + flag.Parse() + cmd := flag.Args() + if len(cmd) == 0 || *vram <= 0 { + fmt.Fprintln(os.Stderr, "usage: gpu-run --vram MB [--priority batch] [--max-wait 10m] -- command args...") + os.Exit(2) + } + if *client == "" { + *client = cmd[0] + } + code, err := run.Run(context.Background(), run.Options{ + Broker: *broker, Client: *client, Priority: api.Priority(*priority), VRAMMB: *vram, + MaxWait: *wait, CPUQuota: *quota, Spread: *spread, + }, cmd) + if err != nil { + fmt.Fprintln(os.Stderr, "gpu-run:", err) + } + os.Exit(code) +} diff --git a/internal/run/run.go b/internal/run/run.go new file mode 100644 index 0000000..ed1d202 --- /dev/null +++ b/internal/run/run.go @@ -0,0 +1,128 @@ +// Package run is gpu-run: lease a GPU for a command, or run it CPU-capped. +package run + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "os/signal" + "syscall" + "time" + + "gitea.godemperordoge.org/ziadarafat/gpu-broker/internal/api" +) + +// Grant is the part of the broker's answer gpu-run needs. +type Grant struct { + GPU int // -1 = CPU + LeaseID string +} + +// Plan returns the argv and extra environment for running cmd under grant. +// GPU: the command sees only that card. CPU: no cards, and a systemd scope +// caps it at cpuQuota percent (100 = one core) because arceus overheats. +func Plan(g Grant, cmd []string, cpuQuota int, root bool) ([]string, []string) { + if g.GPU >= 0 { + dev := fmt.Sprint(g.GPU) + return cmd, []string{"CUDA_VISIBLE_DEVICES=" + dev, "NVIDIA_VISIBLE_DEVICES=" + dev, "GPU_BROKER_DEVICE=gpu"} + } + env := []string{"CUDA_VISIBLE_DEVICES=", "NVIDIA_VISIBLE_DEVICES=void", "GPU_BROKER_DEVICE=cpu"} + if cpuQuota <= 0 { + return cmd, env + } + argv := []string{"systemd-run"} + if !root { + argv = append(argv, "--user") + } + argv = append(argv, "--scope", "--quiet", "--collect", "-p", fmt.Sprintf("CPUQuota=%d%%", cpuQuota), "--") + return append(argv, cmd...), env +} + +// Options for Run. +type Options struct { + Broker string + Client string + Priority api.Priority + VRAMMB int + MaxWait time.Duration + CPUQuota int + Spread bool +} + +// Run leases, runs cmd, renews while it runs, releases, and returns its exit code. +func Run(ctx context.Context, o Options, cmd []string) (int, error) { + b, err := api.NewClientWithResponses(o.Broker) + if err != nil { + return 1, err + } + wait, fallback, spread := int(o.MaxWait/time.Second), true, o.Spread + resp, err := b.AcquireLeaseWithResponse(ctx, api.AcquireLeaseJSONRequestBody{ + Client: o.Client, Priority: o.Priority, VramMb: o.VRAMMB, + MaxWaitS: &wait, CpuFallback: &fallback, Spread: &spread, + }) + g := Grant{GPU: -1} + switch { + case err != nil || resp.JSON200 == nil: + fmt.Fprintf(os.Stderr, "gpu-run: broker unavailable (%v); running on the CPU\n", err) + case resp.JSON200.Device == api.Gpu: + g.GPU = resp.JSON200.Gpu + if resp.JSON200.LeaseId != nil { + g.LeaseID = *resp.JSON200.LeaseId + } + } + argv, env := Plan(g, cmd, o.CPUQuota, os.Geteuid() == 0) + fmt.Fprintf(os.Stderr, "gpu-run: %s on %s\n", o.Client, map[bool]string{true: fmt.Sprintf("GPU %d", g.GPU), false: "CPU"}[g.GPU >= 0]) + + c := exec.CommandContext(ctx, argv[0], argv[1:]...) + c.Stdin, c.Stdout, c.Stderr = os.Stdin, os.Stdout, os.Stderr + c.Env = append(os.Environ(), env...) + if err := c.Start(); err != nil { + release(b, g.LeaseID) + return 127, err + } + stop := make(chan struct{}) + if g.LeaseID != "" { + go func() { + t := time.NewTicker(time.Minute) + defer t.Stop() + for { + select { + case <-stop: + return + case <-t.C: + _, _ = b.RenewLease(context.Background(), g.LeaseID) + } + } + }() + } + sig := make(chan os.Signal, 1) + signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) + go func() { + for s := range sig { + _ = c.Process.Signal(s) + } + }() + err = c.Wait() + close(stop) + signal.Stop(sig) + release(b, g.LeaseID) + var exit *exec.ExitError + if errors.As(err, &exit) { + return exit.ExitCode(), nil + } + if err != nil { + return 1, err + } + return 0, nil +} + +func release(b *api.ClientWithResponses, id string) { + if id == "" { + return + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _, _ = b.ReleaseLease(ctx, id) +} diff --git a/internal/run/run_test.go b/internal/run/run_test.go new file mode 100644 index 0000000..55f16a5 --- /dev/null +++ b/internal/run/run_test.go @@ -0,0 +1,42 @@ +package run + +import ( + "reflect" + "testing" +) + +func TestGPUGrantPinsTheCard(t *testing.T) { + argv, env := Plan(Grant{GPU: 1}, []string{"whisper", "a.mkv"}, 400, false) + if !reflect.DeepEqual(argv, []string{"whisper", "a.mkv"}) { + t.Fatalf("argv %v", argv) + } + if !reflect.DeepEqual(env, []string{"CUDA_VISIBLE_DEVICES=1", "NVIDIA_VISIBLE_DEVICES=1", "GPU_BROKER_DEVICE=gpu"}) { + t.Fatalf("env %v", env) + } +} + +func TestCPUGrantHidesGPUsAndCapsTheCPU(t *testing.T) { + argv, env := Plan(Grant{GPU: -1}, []string{"whisper", "a.mkv"}, 400, true) + want := []string{"systemd-run", "--scope", "--quiet", "--collect", "-p", "CPUQuota=400%", "--", "whisper", "a.mkv"} + if !reflect.DeepEqual(argv, want) { + t.Fatalf("argv %v", argv) + } + if !reflect.DeepEqual(env, []string{"CUDA_VISIBLE_DEVICES=", "NVIDIA_VISIBLE_DEVICES=void", "GPU_BROKER_DEVICE=cpu"}) { + t.Fatalf("env %v", env) + } +} + +func TestUnprivilegedCPUCapUsesTheUserManager(t *testing.T) { + argv, _ := Plan(Grant{GPU: -1}, []string{"job"}, 200, false) + want := []string{"systemd-run", "--user", "--scope", "--quiet", "--collect", "-p", "CPUQuota=200%", "--", "job"} + if !reflect.DeepEqual(argv, want) { + t.Fatalf("argv %v", argv) + } +} + +func TestNoCapWhenZero(t *testing.T) { + argv, _ := Plan(Grant{GPU: -1}, []string{"job"}, 0, true) + if !reflect.DeepEqual(argv, []string{"job"}) { + t.Fatalf("argv %v", argv) + } +}