Skip to content

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

mlx: keep loaded model memory resident (#17367)

Daniel Hiltgen9eef4a7195dc
diff --git a/x/mlxrunner/mlx/memory.go b/x/mlxrunner/mlx/memory.go
index a243b72c0..f75937bad 100644
--- a/x/mlxrunner/mlx/memory.go
+++ b/x/mlxrunner/mlx/memory.go
@@ -1,12 +1,14 @@
package mlx
// #include "generated.h"
+// #include <stdlib.h>
import "C"
import (
"fmt"
"log/slog"
"strconv"
+ "unsafe"
)
func (b Byte) String() string {
@@ -66,6 +68,46 @@ func ResetPeakMemory() {
C.mlx_reset_peak_memory()
}
+// MaxRecommendedWorkingSetSize returns the device's recommended upper bound
+// for resident Metal allocations.
+func MaxRecommendedWorkingSetSize() (int, error) {
+ info := C.mlx_device_info_new()
+ if err := mlxCall("get device info failed", func() C.int {
+ return C.mlx_device_info_get(&info, DefaultDevice().ctx)
+ }); err != nil {
+ C.mlx_device_info_free(info)
+ return 0, err
+ }
+ defer C.mlx_device_info_free(info)
+
+ key := C.CString("max_recommended_working_set_size")
+ defer C.free(unsafe.Pointer(key))
+
+ var size C.size_t
+ if err := mlxCall("max recommended working set size unavailable", func() C.int {
+ return C.mlx_device_info_get_size(&size, info, key)
+ }); err != nil {
+ return 0, err
+ }
+ return int(size), nil
+}
+
+// SetWiredLimit sets the maximum amount of Metal memory MLX keeps resident and
+// returns the previous limit.
+func SetWiredLimit(limit int) (int, error) {
+ if limit < 0 {
+ return 0, fmt.Errorf("mlx: wired limit must be non-negative")
+ }
+
+ var previous C.size_t
+ if err := mlxCall("set wired limit failed", func() C.int {
+ return C.mlx_set_wired_limit(&previous, C.size_t(limit))
+ }); err != nil {
+ return 0, err
+ }
+ return int(previous), nil
+}
+
type Memory struct{}
func (Memory) LogValue() slog.Value {
diff --git a/x/mlxrunner/mlx/memory_test.go b/x/mlxrunner/mlx/memory_test.go
new file mode 100644
index 000000000..8eceb848c
--- /dev/null
+++ b/x/mlxrunner/mlx/memory_test.go
@@ -0,0 +1,64 @@
+package mlx
+
+import (
+ "errors"
+ "fmt"
+ "math"
+ "slices"
+ "testing"
+)
+
+func TestSetWiredLimitRejectsOversizeWithoutChangingLimit(t *testing.T) {
+ skipIfNoMLX(t)
+ if !GPUIsAvailable() {
+ t.Skip("MLX GPU not available")
+ }
+
+ var testErr error
+ withMLXThread(t, func() {
+ testErr = checkWiredLimitRejectsOversize()
+ })
+ if testErr != nil {
+ t.Fatal(testErr)
+ }
+}
+
+func checkWiredLimitRejectsOversize() (err error) {
+ maxRecommended, err := MaxRecommendedWorkingSetSize()
+ if err != nil {
+ return err
+ }
+ if maxRecommended == math.MaxInt {
+ return errors.New("recommended working set cannot be exceeded by an int")
+ }
+
+ previous, err := SetWiredLimit(maxRecommended)
+ if err != nil {
+ return err
+ }
+ defer func() {
+ if _, restoreErr := SetWiredLimit(previous); restoreErr != nil {
+ err = errors.Join(err, fmt.Errorf("restore wired limit: %w", restoreErr))
+ }
+ }()
+
+ if _, err := SetWiredLimit(maxRecommended + 1); err == nil {
+ return errors.New("SetWiredLimit accepted a limit above the recommended working set")
+ }
+
+ current, err := SetWiredLimit(maxRecommended)
+ if err != nil {
+ return err
+ }
+ if current != maxRecommended {
+ return fmt.Errorf("wired limit after rejected update = %d, want %d", current, maxRecommended)
+ }
+
+ a := FromValues([]float32{1, 2, 3, 4}, 2, 2)
+ b := Matmul(a, a)
+ Eval(b)
+ if got, want := b.Floats(), []float32{7, 10, 15, 22}; !slices.Equal(got, want) {
+ return fmt.Errorf("evaluation after rejected update = %v, want %v", got, want)
+ }
+ return nil
+}
diff --git a/x/mlxrunner/mlx/mlx.go b/x/mlxrunner/mlx/mlx.go
index 291410573..c863b9f3e 100644
--- a/x/mlxrunner/mlx/mlx.go
+++ b/x/mlxrunner/mlx/mlx.go
@@ -35,7 +35,10 @@ package mlx
// }
import "C"
-import "runtime"
+import (
+ "fmt"
+ "runtime"
+)
func init() {
// Replace the default exit(-1) error handler with one that captures
@@ -51,11 +54,9 @@ func Version() string {
return C.GoString(C.mlx_string_data(str))
}
-// mlxCheck locks the goroutine to its OS thread, clears the captured error
-// state, calls fn, and panics with the captured message if fn returns non-zero.
-// The thread lock ensures the thread-local error state is read from the same
-// thread that executed the call.
-func mlxCheck(fallback string, fn func() C.int) {
+// mlxCall locks the goroutine to its OS thread so the thread-local error state
+// is read from the same thread that executed fn.
+func mlxCall(fallback string, fn func() C.int) error {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
@@ -65,7 +66,16 @@ func mlxCheck(fallback string, fn func() C.int) {
if msg == "" {
msg = fallback
}
- panic("mlx: " + msg)
+ return fmt.Errorf("mlx: %s", msg)
+ }
+ return nil
+}
+
+// mlxCheck panics with the captured MLX error. Most array operations cannot
+// recover from a failed graph construction or evaluation.
+func mlxCheck(fallback string, fn func() C.int) {
+ if err := mlxCall(fallback, fn); err != nil {
+ panic(err.Error())
}
}
diff --git a/x/mlxrunner/runner.go b/x/mlxrunner/runner.go
index e74f0f150..ec77b356e 100644
--- a/x/mlxrunner/runner.go
+++ b/x/mlxrunner/runner.go
@@ -101,6 +101,7 @@ func (r *Runner) Load(modelName string) error {
}
mlx.Sweep()
mlx.Eval(collected...)
+ configureWiredMemory()
r.Model = m
r.Tokenizer = m.Tokenizer()
@@ -114,6 +115,41 @@ func (r *Runner) Load(modelName string) error {
return nil
}
+func configureWiredMemory() {
+ if !mlx.GPUIsAvailable() {
+ return
+ }
+
+ active := mlx.ActiveMemory()
+ maxRecommended, err := mlx.MaxRecommendedWorkingSetSize()
+ if err != nil {
+ slog.Warn("Unable to query MLX recommended working set; using pageable memory", "error", err)
+ return
+ }
+
+ limit := min(active, maxRecommended)
+ previous, err := mlx.SetWiredLimit(limit)
+ if err != nil {
+ slog.Warn("Unable to configure MLX wired memory; using pageable memory",
+ "active", mlx.PrettyBytes(active),
+ "limit", mlx.PrettyBytes(limit),
+ "error", err)
+ return
+ }
+
+ if active > maxRecommended {
+ slog.Warn("MLX model exceeds the recommended working set; performance may be degraded",
+ "active", mlx.PrettyBytes(active),
+ "recommended", mlx.PrettyBytes(maxRecommended))
+ }
+ // Limiting residency to the loaded model's active allocations avoids
+ // reserving the remaining capacity for growing KV caches.
+ slog.Debug("Configured MLX wired memory",
+ "active", mlx.PrettyBytes(active),
+ "limit", mlx.PrettyBytes(limit),
+ "previous", mlx.PrettyBytes(previous))
+}
+
// loadTensorsFromManifest loads all tensor blobs from the manifest into a
// flat map, deduplicating by digest and remapping safetensors key suffixes.
//