Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.
imagegen: remove MLX image generation code (#16615)
Jeffrey Morgan4713800b08b2
diff --git a/Dockerfile b/Dockerfileindex 46de5c49b..bc9cfc3ca 100644--- a/Dockerfile+++ b/Dockerfile@@ -213,7 +213,7 @@ ENV CGO_LDFLAGS="-L/usr/local/cuda-13/lib64 -L/usr/local/cuda-13/targets/x86_64-WORKDIR /go/src/github.com/ollama/ollamaCOPY CMakeLists.txt CMakePresets.json .COPY cmake cmake-COPY x/imagegen/mlx x/imagegen/mlx+COPY x/mlxrunner/mlx x/mlxrunner/mlxCOPY go.mod go.sum .COPY MLX_VERSION MLX_C_VERSION .RUN curl -fsSL https://golang.org/dl/go$(awk '/^go/ { print $2 }' go.mod).linux-$(case $(uname -m) in x86_64) echo amd64 ;; aarch64) echo arm64 ;; esac).tar.gz | tar xz -C /usr/localdiff --git a/api/types.go b/api/types.goindex ce11b661f..86f0edf32 100644--- a/api/types.go+++ b/api/types.go@@ -127,20 +127,6 @@ type GenerateRequest struct {// each with an associated log probability. Only applies when Logprobs is true.// Valid values are 0-20. Default is 0 (only return the selected token's logprob).TopLogprobs int `json:"top_logprobs,omitempty"`-- // Experimental: Image generation fields (may change or be removed)-- // Width is the width of the generated image in pixels.- // Only used for image generation models.- Width int32 `json:"width,omitempty"`-- // Height is the height of the generated image in pixels.- // Only used for image generation models.- Height int32 `json:"height,omitempty"`-- // Steps is the number of diffusion steps for image generation.- // Only used for image generation models.- Steps int32 `json:"steps,omitempty"`}// ChatRequest describes a request sent by [Client.Chat].@@ -941,20 +927,6 @@ type GenerateResponse struct {// Logprobs contains log probability information for the generated tokens,// if requested via the Logprobs parameter.Logprobs []Logprob `json:"logprobs,omitempty"`-- // Experimental: Image generation fields (may change or be removed)-- // Image contains a base64-encoded generated image.- // Only present for image generation models.- Image string `json:"image,omitempty"`-- // Completed is the number of completed steps in image generation.- // Only present for image generation models during streaming.- Completed int64 `json:"completed,omitempty"`-- // Total is the total number of steps for image generation.- // Only present for image generation models during streaming.- Total int64 `json:"total,omitempty"`}// ModelDetails provides details about a model.diff --git a/cmake/mlx/CMakeLists.txt b/cmake/mlx/CMakeLists.txtindex 123845f4e..c9cd82eea 100644--- a/cmake/mlx/CMakeLists.txt+++ b/cmake/mlx/CMakeLists.txt@@ -50,7 +50,7 @@ endif()option(OLLAMA_MLX_GENERATE_WRAPPERS "Regenerate MLX Go wrappers" OFF)message(STATUS "Setting up MLX (this takes a while...)")-add_subdirectory(${OLLAMA_SOURCE_DIR}/x/imagegen/mlx ${CMAKE_BINARY_DIR}/x/imagegen/mlx)+add_subdirectory(${OLLAMA_SOURCE_DIR}/x/mlxrunner/mlx ${CMAKE_BINARY_DIR}/x/mlxrunner/mlx)# Find CUDA toolkit if MLX is built with CUDA support.find_package(CUDAToolkit)@@ -293,9 +293,10 @@ endif()# RUNTIME_DEPENDENCIES auto-excludes it via POST_EXCLUDE_FILES_STRICT because# dlfcn-win32 is a known CMake target with its own install rules (which install# to the wrong destination). We must install it explicitly here.-if(WIN32)- install(FILES ${OLLAMA_BUILD_DIR}/dl.dll- DESTINATION ${OLLAMA_INSTALL_DIR}+if(WIN32 AND TARGET dl)+ install(TARGETS dl+ RUNTIME DESTINATION ${OLLAMA_INSTALL_DIR}+ LIBRARY DESTINATION ${OLLAMA_INSTALL_DIR}COMPONENT MLX)endif()diff --git a/cmd/cmd.go b/cmd/cmd.goindex e65d125b4..4f1380d02 100644--- a/cmd/cmd.go+++ b/cmd/cmd.go@@ -56,7 +56,6 @@ import ("github.com/ollama/ollama/version"xcreate "github.com/ollama/ollama/x/create"xcreateclient "github.com/ollama/ollama/x/create/client"- "github.com/ollama/ollama/x/imagegen")func init() {@@ -192,7 +191,7 @@ func resolveExperimentalLocalModelDir(ref, filename string) string {}candidate := filepath.Join(filepath.Dir(filename), ref)- if xcreate.IsSafetensorsModelDir(candidate) || xcreate.IsTensorModelDir(candidate) {+ if xcreate.IsSafetensorsModelDir(candidate) {return candidate}@@ -230,8 +229,7 @@ func CreateHandler(cmd *cobra.Command, args []string) error {return fmt.Errorf("invalid model name: %s", modelName)}- // Check for --experimental flag for safetensors model creation- // This gates both safetensors LLM and imagegen model creation+ // Check for --experimental flag for safetensors model creation.experimental, _ := cmd.Flags().GetBool("experimental")draftQuantize, _ := cmd.Flags().GetString("draft-quantize")if experimental {@@ -877,12 +875,8 @@ func RunHandler(cmd *cobra.Command, args []string) error {return generateEmbedding(cmd, name, opts.Prompt, opts.KeepAlive, truncate, dimensions)}- // Check if this is an image generation modelif slices.Contains(info.Capabilities, model.CapabilityImage) {- if opts.Prompt == "" && !interactive {- return errors.New("image generation models require a prompt. Usage: ollama run " + name + " \"your prompt here\"")- }- return imagegen.RunCLI(cmd, name, opts.Prompt, interactive, opts.KeepAlive)+ return errors.New("image generation models are not currently supported")}if interactive {@@ -1247,6 +1241,10 @@ func ShowHandler(cmd *cobra.Command, args []string) error {return err}+ if slices.Contains(resp.Capabilities, model.CapabilityImage) {+ return errors.New("image generation models are not currently supported")+ }+if flagsSet == 1 {switch showType {case "license":@@ -2330,12 +2328,6 @@ func NewCLI() *cobra.Command {runCmd.Flags().Bool("truncate", false, "For embedding models: truncate inputs exceeding context length (default: true). Set --truncate=false to error instead")runCmd.Flags().Int("dimensions", 0, "Truncate output embeddings to specified dimension (embedding models only)")- // Image generation flags (width, height, steps, seed, etc.)- imagegen.RegisterFlags(runCmd)-- runCmd.Flags().Bool("imagegen", false, "Use the imagegen runner for LLM inference")- runCmd.Flags().MarkHidden("imagegen")-stopCmd := &cobra.Command{Use: "stop MODEL",Short: "Stop a running model",@@ -2477,7 +2469,6 @@ func NewCLI() *cobra.Command {} {switch cmd {case runCmd:- imagegen.AppendFlagsDocs(cmd)appendEnvDocs(cmd, []envconfig.EnvVar{envVars["OLLAMA_EDITOR"], envVars["OLLAMA_HOST"], envVars["OLLAMA_NOHISTORY"]})case serveCmd:appendEnvDocs(cmd, []envconfig.EnvVar{diff --git a/cmd/cmd_test.go b/cmd/cmd_test.goindex 821c0eee9..b2970d976 100644--- a/cmd/cmd_test.go+++ b/cmd/cmd_test.go@@ -2079,7 +2079,7 @@ func TestRunOptions_Copy_ThinkValueVariants(t *testing.T) {}}-func TestShowInfoImageGen(t *testing.T) {+func TestShowInfoImageCapability(t *testing.T) {var b bytes.Buffererr := showInfo(&api.ShowResponse{Details: api.ModelDetails{diff --git a/docs/api.md b/docs/api.mdindex af549090c..371b91198 100644--- a/docs/api.md+++ b/docs/api.md@@ -59,15 +59,6 @@ Advanced parameters (optional):- `keep_alive`: controls how long the model will stay loaded into memory following the request (default: `5m`)- `context` (deprecated): the context parameter returned from a previous request to `/generate`, this can be used to keep a short conversational memory-Experimental image generation parameters (for image generation models only):--> [!WARNING]-> These parameters are experimental and may change in future versions.--- `width`: width of the generated image in pixels-- `height`: height of the generated image in pixels-- `steps`: number of diffusion steps-#### Structured outputsStructured outputs are supported by providing a JSON schema in the `format` parameter. The model will generate a response that matches the schema. See the [structured outputs](#request-structured-outputs) example below.@@ -1880,55 +1871,3 @@ curl http://localhost:11434/api/version"version": "0.5.1"}```--## Experimental Features--### Image Generation (Experimental)--> [!WARNING]-> Image generation is experimental and may change in future versions.--Image generation is now supported through the standard `/api/generate` endpoint when using image generation models. The API automatically detects when an image generation model is being used.--See the [Generate a completion](#generate-a-completion) section for the full API documentation. The experimental image generation parameters (`width`, `height`, `steps`) are documented there.--#### Example--##### Request--```shell-curl http://localhost:11434/api/generate -d '{- "model": "x/z-image-turbo",- "prompt": "a sunset over mountains",- "width": 1024,- "height": 768-}'-```--##### Response (streaming)--Progress updates during generation:--```json-{- "model": "x/z-image-turbo",- "created_at": "2024-01-15T10:30:00.000000Z",- "completed": 5,- "total": 20,- "done": false-}-```--##### Final Response--```json-{- "model": "x/z-image-turbo",- "created_at": "2024-01-15T10:30:15.000000Z",- "image": "iVBORw0KGgoAAAANSUhEUg...",- "done": true,- "done_reason": "stop",- "total_duration": 15000000000,- "load_duration": 2000000000-}-```diff --git a/docs/api/openai-compatibility.mdx b/docs/api/openai-compatibility.mdxindex a74a23f6d..4b34fa096 100644--- a/docs/api/openai-compatibility.mdx+++ b/docs/api/openai-compatibility.mdx@@ -279,73 +279,6 @@ curl -X POST http://localhost:11434/v1/chat/completions \- [x] `dimensions`- [ ] `user`-### `/v1/images/generations` (experimental)--> Note: This endpoint is experimental and may change or be removed in future versions.--Generate images using image generation models.--<CodeGroup dropdown>--```python images.py-from openai import OpenAI--client = OpenAI(- base_url='http://localhost:11434/v1/',- api_key='ollama', # required but ignored-)--response = client.images.generate(- model='x/z-image-turbo',- prompt='A cute robot learning to paint',- size='1024x1024',- response_format='b64_json',-)-print(response.data[0].b64_json[:50] + '...')-```--```javascript images.js-import OpenAI from "openai";--const openai = new OpenAI({- baseURL: "http://localhost:11434/v1/",- apiKey: "ollama", // required but ignored-});--const response = await openai.images.generate({- model: "x/z-image-turbo",- prompt: "A cute robot learning to paint",- size: "1024x1024",- response_format: "b64_json",-});--console.log(response.data[0].b64_json.slice(0, 50) + "...");-```--```shell images.sh-curl -X POST http://localhost:11434/v1/images/generations \--H "Content-Type: application/json" \--d '{- "model": "x/z-image-turbo",- "prompt": "A cute robot learning to paint",- "size": "1024x1024",- "response_format": "b64_json"-}'-```--</CodeGroup>--#### Supported request fields--- [x] `model`-- [x] `prompt`-- [x] `size` (e.g. "1024x1024")-- [x] `response_format` (only `b64_json` supported)-- [ ] `n`-- [ ] `quality`-- [ ] `style`-- [ ] `user`-### `/v1/responses`> Note: Added in Ollama v0.13.3diff --git a/integration/create_imagegen_test.go b/integration/create_imagegen_test.godeleted file mode 100644index 53903e7a6..000000000--- a/integration/create_imagegen_test.go+++ /dev/null@@ -1,107 +0,0 @@-//go:build integration && imagegen--package integration--import (- "context"- "encoding/base64"- "os"- "path/filepath"- "strings"- "testing"- "time"-- "github.com/ollama/ollama/api"-)--func TestCreateImageGen(t *testing.T) {- skipIfRemote(t)- skipUnderMinVRAM(t, 13)-- // Allow overriding the model directory via env var for local testing,- // since the model is ~33GB and may already be downloaded elsewhere.- modelDir := os.Getenv("OLLAMA_TEST_IMAGEGEN_MODEL_DIR")- if modelDir == "" {- modelDir = filepath.Join(testdataModelsDir, "Z-Image-Turbo")- downloadHFModel(t, "Tongyi-MAI/Z-Image-Turbo", modelDir)- } else {- t.Logf("Using existing imagegen model at %s", modelDir)- }-- // Verify it looks like a valid imagegen model directory- if _, err := os.Stat(filepath.Join(modelDir, "model_index.json")); err != nil {- t.Fatalf("model_index.json not found in %s — not a valid imagegen model directory", modelDir)- }-- ensureMLXLibraryPath(t)-- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)- defer cancel()-- client, _, cleanup := InitServerConnection(ctx, t)- defer cleanup()-- modelName := "test-z-image-turbo-create"-- absModelDir, err := filepath.Abs(modelDir)- if err != nil {- t.Fatalf("Failed to get absolute path: %v", err)- }-- // Create a Modelfile pointing to the diffusers model directory- tmpModelfile := filepath.Join(t.TempDir(), "Modelfile")- if err := os.WriteFile(tmpModelfile, []byte("FROM "+absModelDir+"\n"), 0o644); err != nil {- t.Fatalf("Failed to write Modelfile: %v", err)- }-- t.Logf("Creating imagegen model from %s", absModelDir)- runOllamaCreate(ctx, t, modelName, "--experimental", "-f", tmpModelfile)-- // Verify model exists via show- showReq := &api.ShowRequest{Name: modelName}- showResp, err := client.Show(ctx, showReq)- if err != nil {- t.Fatalf("Model show failed after create: %v", err)- }- t.Logf("Created model details: %+v", showResp.Details)-- // Generate an image to verify the model isn't corrupted- t.Log("Generating test image...")- imageBase64, err := generateImage(ctx, client, modelName, "A red circle on a white background")- if err != nil {- if strings.Contains(err.Error(), "image generation not available") {- t.Skip("Target system does not support image generation")- } else if strings.Contains(err.Error(), "insufficient memory for image generation") {- t.Skip("insufficient memory for image generation")- } else if strings.Contains(err.Error(), "ollama-mlx: no such file or directory") {- t.Skip("unsupported architecture")- }- t.Fatalf("Image generation failed: %v", err)- }-- // Verify we got valid image data- imageData, err := base64.StdEncoding.DecodeString(imageBase64)- if err != nil {- t.Fatalf("Failed to decode base64 image: %v", err)- }-- t.Logf("Generated image: %d bytes", len(imageData))-- if len(imageData) < 1000 {- t.Fatalf("Generated image suspiciously small (%d bytes), likely corrupted", len(imageData))- }-- // Check for PNG or JPEG magic bytes- isPNG := len(imageData) >= 4 && imageData[0] == 0x89 && imageData[1] == 'P' && imageData[2] == 'N' && imageData[3] == 'G'- isJPEG := len(imageData) >= 2 && imageData[0] == 0xFF && imageData[1] == 0xD8- if !isPNG && !isJPEG {- t.Fatalf("Generated image is neither PNG nor JPEG (first bytes: %x)", imageData[:min(8, len(imageData))])- }- t.Logf("Image format validated (PNG=%v, JPEG=%v)", isPNG, isJPEG)-- // Cleanup: delete the model- deleteReq := &api.DeleteRequest{Model: modelName}- if err := client.Delete(ctx, deleteReq); err != nil {- t.Logf("Warning: failed to delete test model: %v", err)- }-}diff --git a/integration/create_test.go b/integration/create_test.goindex 3cd5e8129..37b136cf3 100644--- a/integration/create_test.go+++ b/integration/create_test.go@@ -19,7 +19,7 @@ import (const testdataModelsDir = "testdata/models"// skipIfRemote skips the test if OLLAMA_HOST points to a non-local server.-// Safetensors/imagegen creation requires localhost since it reads model files+// Safetensors creation requires localhost since it reads model files.// from disk and uses the --experimental CLI path.func skipIfRemote(t *testing.T) {t.Helper()@@ -43,7 +43,7 @@ func skipIfRemote(t *testing.T) {if ip != nil && (ip.IsLoopback() || ip.IsUnspecified()) {return}- t.Skipf("safetensors/imagegen creation requires a local server (OLLAMA_HOST=%s)", host)+ t.Skipf("safetensors creation requires a local server (OLLAMA_HOST=%s)", host)}// findHFCLI returns the path to the HuggingFace CLI, or "" if not found.diff --git a/integration/imagegen_test.go b/integration/imagegen_test.godeleted file mode 100644index 29d64bce2..000000000--- a/integration/imagegen_test.go+++ /dev/null@@ -1,149 +0,0 @@-//go:build integration--package integration--import (- "context"- "encoding/base64"- "fmt"- "strings"- "testing"- "time"-- "github.com/ollama/ollama/api"-)--func runImageGeneration(t *testing.T) {- if testModel != "" {- t.Skip("uses hardcoded models, not applicable with model override")- }- skipUnderMinVRAM(t, 32)-- type testCase struct {- imageGenModel string- visionModel string- prompt string- expectedWords []string- }-- testCases := []testCase{- {- imageGenModel: "jmorgan/z-image-turbo",- visionModel: "qwen2.5vl:3b",- prompt: "A cartoon style llama flying like a superhero through the air with clouds in the background",- expectedWords: []string{"llama", "flying", "cartoon", "cloud", "sky", "superhero", "air", "animal", "camelid"},- },- }-- for _, tc := range testCases {- t.Run(fmt.Sprintf("%s->%s", tc.imageGenModel, tc.visionModel), func(t *testing.T) {- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)- defer cancel()-- client, _, cleanup := InitServerConnection(ctx, t)- defer cleanup()-- // Pull both models- pullOrSkip(ctx, t, client, tc.imageGenModel)- pullOrSkip(ctx, t, client, tc.visionModel)-- // Generate the image- t.Logf("Generating image with prompt: %s", tc.prompt)- imageBase64, err := generateImage(ctx, client, tc.imageGenModel, tc.prompt)- if err != nil {- skipIfMLXUnsupported(t, err)- if strings.Contains(err.Error(), "image generation not available") {- t.Skip("Target system does not support image generation")- } else if strings.Contains(err.Error(), "executable file not found in") { // Windows pattern, not yet supported- t.Skip("Windows does not support image generation yet")- } else if strings.Contains(err.Error(), "CUDA driver version is insufficient") {- t.Skip("Driver is too old")- } else if strings.Contains(err.Error(), "insufficient memory for image generation") {- t.Skip("insufficient memory for image generation")- } else if strings.Contains(err.Error(), "error while loading shared libraries: libcuda.so.1") { // AMD GPU or CPU- t.Skip("CUDA GPU is not available")- } else if strings.Contains(err.Error(), "ollama-mlx: no such file or directory") {- // most likely linux arm - not supported yet- t.Skip("unsupported architecture")- } else if strings.Contains(err.Error(), "are available") {- t.Skip("insufficient VRAM for image generation model")- } else if strings.Contains(err.Error(), "failed to create server") {- t.Skip("image generation server failed to start")- }- t.Fatalf("failed to generate image: %v", err)- }-- imageData, err := base64.StdEncoding.DecodeString(imageBase64)- if err != nil {- t.Fatalf("failed to decode image: %v", err)- }- t.Logf("Generated image: %d bytes", len(imageData))-- // Preload vision model and check GPU loading- preloadGenerateModel(ctx, t, client, api.GenerateRequest{Model: tc.visionModel})-- // Use vision model to describe the image- chatReq := api.ChatRequest{- Model: tc.visionModel,- Messages: []api.Message{- {- Role: "user",- Content: "Describe this image in detail. What is shown? What style is it? What is the main subject doing?",- Images: []api.ImageData{imageData},- },- },- Stream: &stream,- Options: map[string]any{- "seed": 42,- "temperature": 0.0,- },- }-- // Verify the vision model's response contains expected keywords- response := DoChat(ctx, t, client, chatReq, tc.expectedWords, 240*time.Second, 30*time.Second)- if response != nil {- t.Logf("Vision model response: %s", response.Content)-- // Additional detailed check for keywords- content := strings.ToLower(response.Content)- foundWords := []string{}- missingWords := []string{}- for _, word := range tc.expectedWords {- if strings.Contains(content, word) {- foundWords = append(foundWords, word)- } else {- missingWords = append(missingWords, word)- }- }- t.Logf("Found keywords: %v", foundWords)- if len(missingWords) > 0 {- t.Logf("Missing keywords (at least one was found so test passed): %v", missingWords)- }- }- })- }-}--// generateImage calls the Ollama API to generate an image and returns the base64 image data-func generateImage(ctx context.Context, client *api.Client, model, prompt string) (string, error) {- var imageBase64 string-- err := client.Generate(ctx, &api.GenerateRequest{- Model: model,- Prompt: prompt,- }, func(resp api.GenerateResponse) error {- if resp.Image != "" {- imageBase64 = resp.Image- }- return nil- })- if err != nil {- return "", fmt.Errorf("failed to generate image: %w", err)- }-- if imageBase64 == "" {- return "", fmt.Errorf("no image data in response")- }-- return imageBase64, nil-}diff --git a/integration/utils_test.go b/integration/utils_test.goindex c5e4559c8..2d0fa2804 100644--- a/integration/utils_test.go+++ b/integration/utils_test.go@@ -609,8 +609,7 @@ func preloadGenerateModel(ctx context.Context, t *testing.T, client *api.Client,// through and fail the test — we never want to mask a real Mac regression.//// The fingerprints are the exact wrapper strings produced by the MLX code-// paths (see x/mlxrunner/server.go, x/mlxrunner/mlx/dynamic.go,-// x/imagegen/mlx/mlx.go, x/imagegen/memory.go). Model-level errors+// paths (see x/mlxrunner/server.go, x/mlxrunner/mlx/dynamic.go). Model-level errors// (unsupported architecture, tensor mismatches, runtime failures) do not// contain these strings, so this helper will not mask them.func skipIfMLXUnsupported(t *testing.T, err error) {@@ -627,8 +626,8 @@ func skipIfMLXUnsupported(t *testing.T, err error) {"MLX not available:","failed to load MLX dynamic library","failed to load MLX function symbols",- "image generation on macOS requires Apple Silicon",- "image generation is not supported on",+ "MLX on macOS requires Apple Silicon",+ "MLX is not supported on",} {if strings.Contains(msg, s) {t.Skipf("MLX not available on target %s/%s (runner %s/%s): %v", targetGOOS, targetGOARCH, runtime.GOOS, runtime.GOARCH, err)diff --git a/llm/server.go b/llm/server.goindex 4f91ddc2d..a11b7f83f 100644--- a/llm/server.go+++ b/llm/server.go@@ -221,12 +221,6 @@ type CompletionRequest struct {// TopLogprobs specifies the number of most likely alternative tokens to return (0-20)TopLogprobs int-- // Image generation fields- Width int32 `json:"width,omitempty"`- Height int32 `json:"height,omitempty"`- Steps int32 `json:"steps,omitempty"`- Seed int64 `json:"seed,omitempty"`}type ChatRequest struct {@@ -295,13 +289,4 @@ type CompletionResponse struct {// Logprobs contains log probability information if requestedLogprobs []Logprob `json:"logprobs,omitempty"`-- // Image contains base64-encoded image data for image generation- Image string `json:"image,omitempty"`-- // Step is the current step in image generation- Step int `json:"step,omitempty"`-- // TotalSteps is the total number of steps for image generation- TotalSteps int `json:"total_steps,omitempty"`}diff --git a/middleware/openai.go b/middleware/openai.goindex 1f9eb080e..dcc45af35 100644--- a/middleware/openai.go+++ b/middleware/openai.go@@ -570,115 +570,6 @@ func ResponsesMiddleware() gin.HandlerFunc {}}-type ImageWriter struct {- BaseWriter-}--func (w *ImageWriter) writeResponse(data []byte) (int, error) {- var generateResponse api.GenerateResponse- if err := json.Unmarshal(data, &generateResponse); err != nil {- return 0, err- }-- // Only write response when done with image- if generateResponse.Done && generateResponse.Image != "" {- w.ResponseWriter.Header().Set("Content-Type", "application/json")- return len(data), json.NewEncoder(w.ResponseWriter).Encode(openai.ToImageGenerationResponse(generateResponse))- }-- return len(data), nil-}--func (w *ImageWriter) Write(data []byte) (int, error) {- code := w.ResponseWriter.Status()- if code != http.StatusOK {- return w.writeError(data)- }-- return w.writeResponse(data)-}--func ImageGenerationsMiddleware() gin.HandlerFunc {- return func(c *gin.Context) {- var req openai.ImageGenerationRequest- if err := c.ShouldBindJSON(&req); err != nil {- c.AbortWithStatusJSON(http.StatusBadRequest, openai.NewError(http.StatusBadRequest, err.Error()))- return- }-- if req.Prompt == "" {- c.AbortWithStatusJSON(http.StatusBadRequest, openai.NewError(http.StatusBadRequest, "prompt is required"))- return- }-- if req.Model == "" {- c.AbortWithStatusJSON(http.StatusBadRequest, openai.NewError(http.StatusBadRequest, "model is required"))- return- }-- var b bytes.Buffer- if err := json.NewEncoder(&b).Encode(openai.FromImageGenerationRequest(req)); err != nil {- c.AbortWithStatusJSON(http.StatusInternalServerError, openai.NewError(http.StatusInternalServerError, err.Error()))- return- }-- c.Request.Body = io.NopCloser(&b)-- w := &ImageWriter{- BaseWriter: BaseWriter{ResponseWriter: c.Writer},- }-- c.Writer = w- c.Next()- }-}--func ImageEditsMiddleware() gin.HandlerFunc {- return func(c *gin.Context) {- var req openai.ImageEditRequest- if err := c.ShouldBindJSON(&req); err != nil {- c.AbortWithStatusJSON(http.StatusBadRequest, openai.NewError(http.StatusBadRequest, err.Error()))- return- }-- if req.Prompt == "" {- c.AbortWithStatusJSON(http.StatusBadRequest, openai.NewError(http.StatusBadRequest, "prompt is required"))- return- }-- if req.Model == "" {- c.AbortWithStatusJSON(http.StatusBadRequest, openai.NewError(http.StatusBadRequest, "model is required"))- return- }-- if req.Image == "" {- c.AbortWithStatusJSON(http.StatusBadRequest, openai.NewError(http.StatusBadRequest, "image is required"))- return- }-- genReq, err := openai.FromImageEditRequest(req)- if err != nil {- c.AbortWithStatusJSON(http.StatusBadRequest, openai.NewError(http.StatusBadRequest, err.Error()))- return- }-- var b bytes.Buffer- if err := json.NewEncoder(&b).Encode(genReq); err != nil {- c.AbortWithStatusJSON(http.StatusInternalServerError, openai.NewError(http.StatusInternalServerError, err.Error()))- return- }-- c.Request.Body = io.NopCloser(&b)-- w := &ImageWriter{- BaseWriter: BaseWriter{ResponseWriter: c.Writer},- }-- c.Writer = w- c.Next()- }-}-// TranscriptionWriter collects streamed chat responses and outputs a transcription response.type TranscriptionWriter struct {BaseWriterdiff --git a/middleware/openai_test.go b/middleware/openai_test.goindex 39fc2c907..f7b3e9e69 100644--- a/middleware/openai_test.go+++ b/middleware/openai_test.go@@ -1256,283 +1256,6 @@ func TestRetrieveMiddleware(t *testing.T) {}}-func TestImageGenerationsMiddleware(t *testing.T) {- type testCase struct {- name string- body string- req api.GenerateRequest- err openai.ErrorResponse- }-- var capturedRequest *api.GenerateRequest-- testCases := []testCase{- {- name: "image generation basic",- body: `{- "model": "test-model",- "prompt": "a beautiful sunset"- }`,- req: api.GenerateRequest{- Model: "test-model",- Prompt: "a beautiful sunset",- },- },- {- name: "image generation with size",- body: `{- "model": "test-model",- "prompt": "a beautiful sunset",- "size": "512x768"- }`,- req: api.GenerateRequest{- Model: "test-model",- Prompt: "a beautiful sunset",- Width: 512,- Height: 768,- },- },- {- name: "image generation missing prompt",- body: `{- "model": "test-model"- }`,- err: openai.ErrorResponse{- Error: openai.Error{- Message: "prompt is required",- Type: "invalid_request_error",- },- },- },- {- name: "image generation missing model",- body: `{- "prompt": "a beautiful sunset"- }`,- err: openai.ErrorResponse{- Error: openai.Error{- Message: "model is required",- Type: "invalid_request_error",- },- },- },- }-- endpoint := func(c *gin.Context) {- c.Status(http.StatusOK)- }-- gin.SetMode(gin.TestMode)- router := gin.New()- router.Use(ImageGenerationsMiddleware(), captureRequestMiddleware(&capturedRequest))- router.Handle(http.MethodPost, "/api/generate", endpoint)-- for _, tc := range testCases {- t.Run(tc.name, func(t *testing.T) {- req, _ := http.NewRequest(http.MethodPost, "/api/generate", strings.NewReader(tc.body))- req.Header.Set("Content-Type", "application/json")-- defer func() { capturedRequest = nil }()-- resp := httptest.NewRecorder()- router.ServeHTTP(resp, req)-- if tc.err.Error.Message != "" {- var errResp openai.ErrorResponse- if err := json.Unmarshal(resp.Body.Bytes(), &errResp); err != nil {- t.Fatal(err)- }- if diff := cmp.Diff(tc.err, errResp); diff != "" {- t.Fatalf("errors did not match:\n%s", diff)- }- return- }-- if resp.Code != http.StatusOK {- t.Fatalf("expected status 200, got %d: %s", resp.Code, resp.Body.String())- }-- if diff := cmp.Diff(&tc.req, capturedRequest); diff != "" {- t.Fatalf("requests did not match:\n%s", diff)- }- })- }-}--func TestImageWriterResponse(t *testing.T) {- gin.SetMode(gin.TestMode)-- // Test that ImageWriter transforms GenerateResponse to OpenAI format- endpoint := func(c *gin.Context) {- resp := api.GenerateResponse{- Model: "test-model",- CreatedAt: time.Unix(1234567890, 0).UTC(),- Done: true,- Image: "dGVzdC1pbWFnZS1kYXRh", // base64 of "test-image-data"- }- data, _ := json.Marshal(resp)- c.Writer.Write(append(data, '\n'))- }-- router := gin.New()- router.Use(ImageGenerationsMiddleware())- router.Handle(http.MethodPost, "/api/generate", endpoint)-- body := `{"model": "test-model", "prompt": "test"}`- req, _ := http.NewRequest(http.MethodPost, "/api/generate", strings.NewReader(body))- req.Header.Set("Content-Type", "application/json")-- resp := httptest.NewRecorder()- router.ServeHTTP(resp, req)-- if resp.Code != http.StatusOK {- t.Fatalf("expected status 200, got %d: %s", resp.Code, resp.Body.String())- }-- var imageResp openai.ImageGenerationResponse- if err := json.Unmarshal(resp.Body.Bytes(), &imageResp); err != nil {- t.Fatalf("failed to unmarshal response: %v", err)- }-- if imageResp.Created != 1234567890 {- t.Errorf("expected created 1234567890, got %d", imageResp.Created)- }-- if len(imageResp.Data) != 1 {- t.Fatalf("expected 1 image, got %d", len(imageResp.Data))- }-- if imageResp.Data[0].B64JSON != "dGVzdC1pbWFnZS1kYXRh" {- t.Errorf("expected image data 'dGVzdC1pbWFnZS1kYXRh', got %s", imageResp.Data[0].B64JSON)- }-}--func TestImageEditsMiddleware(t *testing.T) {- type testCase struct {- name string- body string- req api.GenerateRequest- err openai.ErrorResponse- }-- var capturedRequest *api.GenerateRequest-- // Base64-encoded test image (1x1 pixel PNG)- testImage := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="- decodedImage, _ := base64.StdEncoding.DecodeString("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=")-- testCases := []testCase{- {- name: "image edit basic",- body: `{- "model": "test-model",- "prompt": "make it blue",- "image": "` + testImage + `"- }`,- req: api.GenerateRequest{- Model: "test-model",- Prompt: "make it blue",- Images: []api.ImageData{decodedImage},- },- },- {- name: "image edit with size",- body: `{- "model": "test-model",- "prompt": "make it blue",- "image": "` + testImage + `",- "size": "512x768"- }`,- req: api.GenerateRequest{- Model: "test-model",- Prompt: "make it blue",- Images: []api.ImageData{decodedImage},- Width: 512,- Height: 768,- },- },- {- name: "image edit missing prompt",- body: `{- "model": "test-model",- "image": "` + testImage + `"- }`,- err: openai.ErrorResponse{- Error: openai.Error{- Message: "prompt is required",- Type: "invalid_request_error",- },- },- },- {- name: "image edit missing model",- body: `{- "prompt": "make it blue",- "image": "` + testImage + `"- }`,- err: openai.ErrorResponse{- Error: openai.Error{- Message: "model is required",- Type: "invalid_request_error",- },- },- },- {- name: "image edit missing image",- body: `{- "model": "test-model",- "prompt": "make it blue"- }`,- err: openai.ErrorResponse{- Error: openai.Error{- Message: "image is required",- Type: "invalid_request_error",- },- },- },- }-- endpoint := func(c *gin.Context) {- c.Status(http.StatusOK)- }-- gin.SetMode(gin.TestMode)- router := gin.New()- router.Use(ImageEditsMiddleware(), captureRequestMiddleware(&capturedRequest))- router.Handle(http.MethodPost, "/api/generate", endpoint)-- for _, tc := range testCases {- t.Run(tc.name, func(t *testing.T) {- req, _ := http.NewRequest(http.MethodPost, "/api/generate", strings.NewReader(tc.body))- req.Header.Set("Content-Type", "application/json")-- defer func() { capturedRequest = nil }()-- resp := httptest.NewRecorder()- router.ServeHTTP(resp, req)-- if tc.err.Error.Message != "" {- var errResp openai.ErrorResponse- if err := json.Unmarshal(resp.Body.Bytes(), &errResp); err != nil {- t.Fatal(err)- }- if diff := cmp.Diff(tc.err, errResp); diff != "" {- t.Fatalf("errors did not match:\n%s", diff)- }- return- }-- if resp.Code != http.StatusOK {- t.Fatalf("expected status 200, got %d: %s", resp.Code, resp.Body.String())- }-- if diff := cmp.Diff(&tc.req, capturedRequest); diff != "" {- t.Fatalf("requests did not match:\n%s", diff)- }- })- }-}-func zstdCompress(t *testing.T, data []byte) []byte {t.Helper()var buf bytes.Bufferdiff --git a/openai/openai.go b/openai/openai.goindex cf8b65f21..553381136 100644--- a/openai/openai.go+++ b/openai/openai.go@@ -786,63 +786,6 @@ func FromCompleteRequest(r CompletionRequest) (api.GenerateRequest, error) {}, nil}-// ImageGenerationRequest is an OpenAI-compatible image generation request.-type ImageGenerationRequest struct {- Model string `json:"model"`- Prompt string `json:"prompt"`- N int `json:"n,omitempty"`- Size string `json:"size,omitempty"`- ResponseFormat string `json:"response_format,omitempty"`- Seed *int64 `json:"seed,omitempty"`-}--// ImageGenerationResponse is an OpenAI-compatible image generation response.-type ImageGenerationResponse struct {- Created int64 `json:"created"`- Data []ImageURLOrData `json:"data"`-}--// ImageURLOrData contains either a URL or base64-encoded image data.-type ImageURLOrData struct {- URL string `json:"url,omitempty"`- B64JSON string `json:"b64_json,omitempty"`-}--// FromImageGenerationRequest converts an OpenAI image generation request to an Ollama GenerateRequest.-func FromImageGenerationRequest(r ImageGenerationRequest) api.GenerateRequest {- req := api.GenerateRequest{- Model: r.Model,- Prompt: r.Prompt,- }- // Parse size if provided (e.g., "1024x768")- if r.Size != "" {- var w, h int32- if _, err := fmt.Sscanf(r.Size, "%dx%d", &w, &h); err == nil {- req.Width = w- req.Height = h- }- }- if r.Seed != nil {- if req.Options == nil {- req.Options = map[string]any{}- }- req.Options["seed"] = *r.Seed- }- return req-}--// ToImageGenerationResponse converts an Ollama GenerateResponse to an OpenAI ImageGenerationResponse.-func ToImageGenerationResponse(resp api.GenerateResponse) ImageGenerationResponse {- var data []ImageURLOrData- if resp.Image != "" {- data = []ImageURLOrData{{B64JSON: resp.Image}}- }- return ImageGenerationResponse{- Created: resp.CreatedAt.Unix(),- Data: data,- }-}-// TranscriptionResponse is the response format for /v1/audio/transcriptions.type TranscriptionResponse struct {Text string `json:"text"`@@ -883,47 +826,3 @@ func FromTranscriptionRequest(r TranscriptionRequest) (*api.ChatRequest, error)},}, nil}--// ImageEditRequest is an OpenAI-compatible image edit request.-type ImageEditRequest struct {- Model string `json:"model"`- Prompt string `json:"prompt"`- Image string `json:"image"` // Base64-encoded image data- Size string `json:"size,omitempty"` // e.g., "1024x1024"- Seed *int64 `json:"seed,omitempty"`-}--// FromImageEditRequest converts an OpenAI image edit request to an Ollama GenerateRequest.-func FromImageEditRequest(r ImageEditRequest) (api.GenerateRequest, error) {- req := api.GenerateRequest{- Model: r.Model,- Prompt: r.Prompt,- }-- // Decode the input image- if r.Image != "" {- imgData, err := decodeImageURL(r.Image)- if err != nil {- return api.GenerateRequest{}, fmt.Errorf("invalid image: %w", err)- }- req.Images = append(req.Images, imgData)- }-- // Parse size if provided (e.g., "1024x768")- if r.Size != "" {- var w, h int32- if _, err := fmt.Sscanf(r.Size, "%dx%d", &w, &h); err == nil {- req.Width = w- req.Height = h- }- }-- if r.Seed != nil {- if req.Options == nil {- req.Options = map[string]any{}- }- req.Options["seed"] = *r.Seed- }-- return req, nil-}diff --git a/openai/openai_test.go b/openai/openai_test.goindex 81c64d6b5..f57de8873 100644--- a/openai/openai_test.go+++ b/openai/openai_test.go@@ -824,86 +824,3 @@ func TestFromChatRequest_TopLogprobsRange(t *testing.T) {})}}--func TestFromImageEditRequest_Basic(t *testing.T) {- req := ImageEditRequest{- Model: "test-model",- Prompt: "make it blue",- Image: prefix + image,- }-- result, err := FromImageEditRequest(req)- if err != nil {- t.Fatalf("unexpected error: %v", err)- }-- if result.Model != "test-model" {- t.Errorf("expected model 'test-model', got %q", result.Model)- }-- if result.Prompt != "make it blue" {- t.Errorf("expected prompt 'make it blue', got %q", result.Prompt)- }-- if len(result.Images) != 1 {- t.Fatalf("expected 1 image, got %d", len(result.Images))- }-}--func TestFromImageEditRequest_WithSize(t *testing.T) {- req := ImageEditRequest{- Model: "test-model",- Prompt: "make it blue",- Image: prefix + image,- Size: "512x768",- }-- result, err := FromImageEditRequest(req)- if err != nil {- t.Fatalf("unexpected error: %v", err)- }-- if result.Width != 512 {- t.Errorf("expected width 512, got %d", result.Width)- }-- if result.Height != 768 {- t.Errorf("expected height 768, got %d", result.Height)- }-}--func TestFromImageEditRequest_WithSeed(t *testing.T) {- seed := int64(12345)- req := ImageEditRequest{- Model: "test-model",- Prompt: "make it blue",- Image: prefix + image,- Seed: &seed,- }-- result, err := FromImageEditRequest(req)- if err != nil {- t.Fatalf("unexpected error: %v", err)- }-- if result.Options == nil {- t.Fatal("expected options to be set")- }-- if result.Options["seed"] != seed {- t.Errorf("expected seed %d, got %v", seed, result.Options["seed"])- }-}--func TestFromImageEditRequest_InvalidImage(t *testing.T) {- req := ImageEditRequest{- Model: "test-model",- Prompt: "make it blue",- Image: "not-valid-base64",- }-- _, err := FromImageEditRequest(req)- if err == nil {- t.Error("expected error for invalid image")- }-}diff --git a/progress/stepbar.go b/progress/stepbar.goindex facbded78..fe10a9e10 100644--- a/progress/stepbar.go+++ b/progress/stepbar.go@@ -5,7 +5,7 @@ import ("strings")-// StepBar displays step-based progress (e.g., for image generation steps).+// StepBar displays step-based progress.type StepBar struct {message stringcurrent intdiff --git a/runner/runner.go b/runner/runner.goindex 4ead22e02..fec9e1633 100644--- a/runner/runner.go+++ b/runner/runner.go@@ -3,7 +3,6 @@ package runnerimport ("fmt"- "github.com/ollama/ollama/x/imagegen""github.com/ollama/ollama/x/mlxrunner")@@ -14,11 +13,9 @@ func Execute(args []string) error {if len(args) > 0 {switch args[0] {- case "--imagegen-engine":- return imagegen.Execute(args[1:])case "--mlx-engine":return mlxrunner.Execute(args[1:])}}- return fmt.Errorf("unknown runner engine, expected --imagegen-engine or --mlx-engine")+ return fmt.Errorf("unknown runner engine, expected --mlx-engine")}diff --git a/server/routes.go b/server/routes.goindex ed75d15ac..38244a33f 100644--- a/server/routes.go+++ b/server/routes.go@@ -50,7 +50,6 @@ import ("github.com/ollama/ollama/types/errtypes""github.com/ollama/ollama/types/model""github.com/ollama/ollama/version"- imagegenmanifest "github.com/ollama/ollama/x/imagegen/manifest"xserver "github.com/ollama/ollama/x/server")@@ -218,9 +217,6 @@ func (s *Server) scheduleRunner(ctx context.Context, name string, caps []model.Creturn nil, nil, nil, fmt.Errorf("%s %w", name, err)}- // Deprecated runner override option; ignore if present.- delete(requestOpts, "use_imagegen_runner")-numCtxAuto := usesAutomaticNumCtx(model, requestOpts)embeddingBatchDefault := shouldApplyEmbeddingBatchDefault(model, requestOpts)numBatchAuto := usesAutomaticNumBatch(model, requestOpts) && !embeddingBatchDefault@@ -423,9 +419,8 @@ func (s *Server) GenerateHandler(c *gin.Context) {return}- // Handle image generation modelsif slices.Contains(m.Capabilities(), model.CapabilityImage) {- s.handleImageGenerate(c, req, name.String(), checkpointStart)+ c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "image generation models are not currently supported"})return}@@ -1413,15 +1408,6 @@ func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {QuantizationLevel: m.Config.FileType,}- // For image generation models, populate details from imagegen package- if slices.Contains(m.Capabilities(), model.CapabilityImage) {- if info, err := imagegenmanifest.GetModelInfo(name.String()); err == nil {- modelDetails.Family = info.Architecture- modelDetails.ParameterSize = format.HumanNumber(uint64(info.ParameterCount))- modelDetails.QuantizationLevel = info.Quantization- }- }-// For safetensors LLM models (experimental), populate details from config.jsonif m.Config.ModelFormat == "safetensors" && slices.Contains(m.Config.Capabilities, "completion") {if info, err := xserver.GetSafetensorsLLMInfo(name); err == nil {@@ -1533,7 +1519,11 @@ func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {return resp, nil}- if slices.Contains(m.Capabilities(), model.CapabilityImage) {+ // For safetensors LLM models (experimental), populate ModelInfo from config.json+ if m.Config.ModelFormat == "safetensors" && slices.Contains(m.Config.Capabilities, "completion") {+ if info, err := xserver.GetSafetensorsLLMInfo(name); err == nil {+ resp.ModelInfo = info+ }// Populate tensor info if verboseif req.Verbose {if tensors, err := xserver.GetSafetensorsTensorInfo(name); err == nil {@@ -1543,11 +1533,10 @@ func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {return resp, nil}- // For safetensors LLM models (experimental), populate ModelInfo from config.json- if m.Config.ModelFormat == "safetensors" && slices.Contains(m.Config.Capabilities, "completion") {- if info, err := xserver.GetSafetensorsLLMInfo(name); err == nil {- resp.ModelInfo = info- }+ // Image generation models are stored as safetensors tensor layers with no+ // GGUF model layer to introspect; return what we have (incl. the "image"+ // capability) rather than failing to load a non-existent model file.+ if slices.Contains(m.Capabilities(), model.CapabilityImage) {// Populate tensor info if verboseif req.Verbose {if tensors, err := xserver.GetSafetensorsTensorInfo(name); err == nil {@@ -1912,9 +1901,6 @@ func (s *Server) GenerateRoutes() (http.Handler, error) {r.GET("/v1/models", middleware.ListMiddleware(), s.ListHandler)r.GET("/v1/models/:model", cloudModelPathPassthroughMiddleware(cloudErrRemoteModelDetailsUnavailable), middleware.RetrieveMiddleware(), s.ShowHandler)r.POST("/v1/responses", s.withInferenceRequestLogging("/v1/responses", cloudPassthroughMiddleware(cloudErrRemoteInferenceUnavailable), middleware.ResponsesMiddleware(), s.ChatHandler)...)- // OpenAI-compatible image generation endpoints- r.POST("/v1/images/generations", cloudPassthroughMiddleware(cloudErrRemoteInferenceUnavailable), middleware.ImageGenerationsMiddleware(), s.GenerateHandler)- r.POST("/v1/images/edits", cloudPassthroughMiddleware(cloudErrRemoteInferenceUnavailable), middleware.ImageEditsMiddleware(), s.GenerateHandler)// OpenAI-compatible audio endpointr.POST("/v1/audio/transcriptions", middleware.TranscriptionMiddleware(), s.ChatHandler)@@ -3130,120 +3116,3 @@ func filterThinkTags(msgs []api.Message, m *Model) []api.Message {}return msgs}--// handleImageGenerate handles image generation requests within GenerateHandler.-// This is called when the model has the Image capability.-func (s *Server) handleImageGenerate(c *gin.Context, req api.GenerateRequest, modelName string, checkpointStart time.Time) {- // Validate image dimensions- const maxDimension int32 = 4096- if req.Width > maxDimension || req.Height > maxDimension {- c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("width and height must be <= %d", maxDimension)})- return- }-- // Schedule the runner for image generation- runner, m, _, err := s.scheduleRunner(c.Request.Context(), modelName, []model.Capability{model.CapabilityImage}, nil, req.KeepAlive, nil)- if err != nil {- handleScheduleError(c, req.Model, err)- return- }-- checkpointLoaded := time.Now()-- // Handle load-only request (empty prompt)- if req.Prompt == "" {- c.JSON(http.StatusOK, api.GenerateResponse{- Model: req.Model,- CreatedAt: time.Now().UTC(),- Done: true,- DoneReason: "load",- })- return- }-- // Check streaming preference- isStreaming := req.Stream == nil || *req.Stream-- contentType := "application/x-ndjson"- if !isStreaming {- contentType = "application/json; charset=utf-8"- }- c.Header("Content-Type", contentType)-- // Get seed from options if provided- var seed int64- if s, ok := req.Options["seed"]; ok {- switch v := s.(type) {- case int:- seed = int64(v)- case int64:- seed = v- case float64:- seed = int64(v)- }- }-- var media []llm.MediaData- for i, imgData := range req.Images {- media = append(media, llm.NewMediaData(i, imgData))- }-- var streamStarted bool- var finalResponse api.GenerateResponse-- if err := runner.Completion(c.Request.Context(), llm.CompletionRequest{- Prompt: req.Prompt,- Width: req.Width,- Height: req.Height,- Steps: req.Steps,- Seed: seed,- Media: media,- }, func(cr llm.CompletionResponse) {- streamStarted = true- res := api.GenerateResponse{- Model: req.Model,- CreatedAt: time.Now().UTC(),- Done: cr.Done,- }-- if cr.TotalSteps > 0 {- res.Completed = int64(cr.Step)- res.Total = int64(cr.TotalSteps)- }-- if cr.Image != "" {- res.Image = cr.Image- }-- if cr.Done {- res.DoneReason = cr.DoneReason.String()- res.Metrics.TotalDuration = time.Since(checkpointStart)- res.Metrics.LoadDuration = checkpointLoaded.Sub(checkpointStart)- }-- if !isStreaming {- finalResponse = res- return- }-- data, _ := json.Marshal(res)- c.Writer.Write(append(data, '\n'))- c.Writer.Flush()- }); err != nil {- s.sched.expireRunnersForRuntimeOOM(m, err)- // Only send JSON error if streaming hasn't started yet- // (once streaming starts, headers are committed and we can't change status code)- if !isStreaming || !streamStarted {- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- } else {- data, _ := json.Marshal(gin.H{"error": err.Error()})- c.Writer.Write(append(data, '\n'))- c.Writer.Flush()- }- return- }-- if !isStreaming {- c.JSON(http.StatusOK, finalResponse)- }-}diff --git a/server/routes_generate_test.go b/server/routes_generate_test.goindex 789e43fb2..5de22f78b 100644--- a/server/routes_generate_test.go+++ b/server/routes_generate_test.go@@ -4,7 +4,6 @@ import ("bytes""context""encoding/json"- "errors""io""net/http""net/http/httptest"@@ -3185,108 +3184,7 @@ func TestGenerateWithImages(t *testing.T) {})}-// TestImageGenerateStreamFalse tests that image generation respects stream=false-// and returns a single JSON response instead of streaming ndjson.-func TestImageGenerateStreamFalse(t *testing.T) {- t.Setenv("OLLAMA_CONTEXT_LENGTH", "4096")- gin.SetMode(gin.TestMode)-- p := t.TempDir()- t.Setenv("OLLAMA_MODELS", p)-- mock := mockRunner{}- mock.CompletionFn = func(ctx context.Context, r llm.CompletionRequest, fn func(r llm.CompletionResponse)) error {- fn(llm.CompletionResponse{Step: 1, TotalSteps: 3, Done: false})- fn(llm.CompletionResponse{Step: 2, TotalSteps: 3, Done: false})- fn(llm.CompletionResponse{Step: 3, TotalSteps: 3, Done: true, DoneReason: llm.DoneReasonStop, Image: "base64image"})- return nil- }-- // Create model manifest with image capability- n := model.ParseName("test-image")- cfg := model.ConfigV2{Capabilities: []string{"image"}}- var b bytes.Buffer- if err := json.NewEncoder(&b).Encode(&cfg); err != nil {- t.Fatal(err)- }- configLayer, err := manifest.NewLayer(&b, "application/vnd.docker.container.image.v1+json")- if err != nil {- t.Fatal(err)- }- if err := manifest.WriteManifest(n, configLayer, nil); err != nil {- t.Fatal(err)- }-- loadedModel, err := GetModel("test-image")- if err != nil {- t.Fatal(err)- }-- opts, err := (&Server{}).modelOptions(loadedModel, nil)- if err != nil {- t.Fatal(err)- }- s := Server{- sched: &Scheduler{- pendingReqCh: make(chan *LlmRequest, 1),- finishedReqCh: make(chan *LlmRequest, 1),- expiredCh: make(chan *runnerRef, 1),- unloadedCh: make(chan any, 1),- loaded: map[string]*runnerRef{- schedulerModelKey(loadedModel): {- llama: &mock,- Options: &opts,- model: loadedModel,- isImagegen: true,- numParallel: 1,- },- },- newServerFn: newMockServer(&mock),- getGpuFn: getGpuFn,- getSystemInfoFn: getSystemInfoFn,- },- }-- go s.sched.Run(t.Context())-- streamFalse := false- w := createRequest(t, s.GenerateHandler, api.GenerateRequest{- Model: "test-image",- Prompt: "test prompt",- Stream: &streamFalse,- })-- if w.Code != http.StatusOK {- t.Fatalf("expected status 200, got %d: %s", w.Code, w.Body.String())- }-- if ct := w.Header().Get("Content-Type"); ct != "application/json; charset=utf-8" {- t.Errorf("expected Content-Type 'application/json; charset=utf-8', got %q", ct)- }-- body := w.Body.String()- lines := strings.Split(strings.TrimSpace(body), "\n")- if len(lines) != 1 {- t.Errorf("expected 1 response line, got %d:\n%s", len(lines), body)- }-- var resp api.GenerateResponse- if err := json.Unmarshal([]byte(lines[0]), &resp); err != nil {- t.Fatalf("failed to parse response: %v", err)- }-- if resp.Image != "base64image" {- t.Errorf("expected image 'base64image', got %q", resp.Image)- }-- if !resp.Done {- t.Errorf("expected done=true")- }-}--func newImageGenerateTestServer(t *testing.T, mock *mockRunner) Server {- t.Helper()-+func TestImageGenerateUnsupported(t *testing.T) {t.Setenv("OLLAMA_CONTEXT_LENGTH", "4096")gin.SetMode(gin.TestMode)@@ -3307,99 +3205,15 @@ func newImageGenerateTestServer(t *testing.T, mock *mockRunner) Server {t.Fatal(err)}- loadedModel, err := GetModel("test-image")- if err != nil {- t.Fatal(err)- }-- opts, err := (&Server{}).modelOptions(loadedModel, nil)- if err != nil {- t.Fatal(err)- }- s := Server{- sched: &Scheduler{- pendingReqCh: make(chan *LlmRequest, 1),- finishedReqCh: make(chan *LlmRequest, 1),- expiredCh: make(chan *runnerRef, 1),- unloadedCh: make(chan any, 1),- loaded: map[string]*runnerRef{- schedulerModelKey(loadedModel): {- llama: mock,- Options: &opts,- model: loadedModel,- isImagegen: true,- numParallel: 1,- },- },- newServerFn: newMockServer(mock),- getGpuFn: getGpuFn,- getSystemInfoFn: getSystemInfoFn,- },- }-- go s.sched.Run(t.Context())- return s-}--func TestImageGenerateStreamFalseErrorAfterProgress(t *testing.T) {- mock := mockRunner{}- mock.CompletionFn = func(ctx context.Context, r llm.CompletionRequest, fn func(r llm.CompletionResponse)) error {- fn(llm.CompletionResponse{Step: 1, TotalSteps: 3, Done: false})- return errors.New("runner died")- }- s := newImageGenerateTestServer(t, &mock)-- streamFalse := false- w := createRequest(t, s.GenerateHandler, api.GenerateRequest{- Model: "test-image",- Prompt: "test prompt",- Stream: &streamFalse,- })-- if w.Code != http.StatusInternalServerError {- t.Fatalf("expected status 500, got %d: %s", w.Code, w.Body.String())- }- if !strings.Contains(w.Body.String(), "runner died") {- t.Fatalf("expected runner error in body, got %q", w.Body.String())- }-}--func TestImageGenerateStreamingErrorAfterProgress(t *testing.T) {- mock := mockRunner{}- mock.CompletionFn = func(ctx context.Context, r llm.CompletionRequest, fn func(r llm.CompletionResponse)) error {- fn(llm.CompletionResponse{Step: 1, TotalSteps: 3, Done: false})- return errors.New("runner died")- }- s := newImageGenerateTestServer(t, &mock)-- w := createRequest(t, s.GenerateHandler, api.GenerateRequest{+ w := createRequest(t, (&Server{}).GenerateHandler, api.GenerateRequest{Model: "test-image",Prompt: "test prompt",})- if w.Code != http.StatusOK {- t.Fatalf("expected status 200 after streaming started, got %d: %s", w.Code, w.Body.String())- }- lines := strings.Split(strings.TrimSpace(w.Body.String()), "\n")- if len(lines) != 2 {- t.Fatalf("expected progress and error lines, got %d:\n%s", len(lines), w.Body.String())- }-- var progress api.GenerateResponse- if err := json.Unmarshal([]byte(lines[0]), &progress); err != nil {- t.Fatalf("failed to parse progress response: %v", err)- }- if progress.Completed != 1 || progress.Total != 3 || progress.Done {- t.Fatalf("progress response = %+v", progress)- }-- var errorResponse struct {- Error string `json:"error"`- }- if err := json.Unmarshal([]byte(lines[1]), &errorResponse); err != nil {- t.Fatalf("failed to parse error response: %v", err)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected status 400, got %d: %s", w.Code, w.Body.String())}- if errorResponse.Error != "runner died" {- t.Fatalf("error = %q, want runner died", errorResponse.Error)+ if !strings.Contains(w.Body.String(), "image generation models are not currently supported") {+ t.Fatalf("expected unsupported error in body, got %q", w.Body.String())}}diff --git a/server/sched.go b/server/sched.goindex f9ed5cd3e..ade914353 100644--- a/server/sched.go+++ b/server/sched.go@@ -23,7 +23,6 @@ import ("github.com/ollama/ollama/logutil""github.com/ollama/ollama/ml""github.com/ollama/ollama/types/model"- "github.com/ollama/ollama/x/imagegen""github.com/ollama/ollama/x/mlxrunner")@@ -586,11 +585,7 @@ func (s *Scheduler) load(req *LlmRequest, systemInfo ml.SystemInfo, gpus []ml.De}} else {modelName := req.model.ShortName- if slices.Contains(req.model.Config.Capabilities, "image") {- llama, err = imagegen.NewServer(modelName)- } else {- llama, err = mlxrunner.NewClient(modelName, req.opts.NumCtx)- }+ llama, err = mlxrunner.NewClient(modelName, req.opts.NumCtx)}if err != nil {slog.Info("failed to create server", "model", req.model.ShortName, "error", err)@@ -707,7 +702,6 @@ iGPUScan:sessionDuration: sessionDuration,gpus: gpuIDs,discreteGPUs: discreteGPUs,- isImagegen: slices.Contains(req.model.Config.Capabilities, "image"),totalSize: totalSize,vramSize: vramSize,loading: true,@@ -1350,7 +1344,6 @@ type runnerRef struct {loading bool // True only during initial load, then false forevergpus []ml.DeviceID // Recorded at time of provisioningdiscreteGPUs bool // True if all devices are discrete GPUs - used to skip VRAM recovery check for iGPUs- isImagegen bool // True if loaded via imagegen runner (vs mlxrunner)vramSize uint64totalSize uint64@@ -1390,12 +1383,6 @@ func (runner *runnerRef) needsReload(ctx context.Context, req *LlmRequest) boolrunner.refMu.Lock()defer runner.refMu.Unlock()- // Check if runner type (imagegen vs mlxrunner) matches what's requested.- wantImagegen := slices.Contains(req.model.Config.Capabilities, "image")- if runner.isImagegen != wantImagegen {- return true- }-timeout := 10 * time.Secondif runner.loading {timeout = 2 * time.Minute // Initial load can take a long time for big models on slow systems...diff --git a/server/sched_test.go b/server/sched_test.goindex 78505bd0e..0a7b848f7 100644--- a/server/sched_test.go+++ b/server/sched_test.go@@ -2157,9 +2157,7 @@ func (s *mockLlm) HasExited() bool { return ffunc (s *mockLlm) GetActiveDeviceIDs() []ml.DeviceID { return nil }func (s *mockLlm) ContextLength() int { return s.contextLength }-// TestImageGenRunnerCanBeEvicted verifies that an image generation model-// loaded in the scheduler can be evicted when idle.-func TestImageGenRunnerCanBeEvicted(t *testing.T) {+func TestRunnerCanBeEvicted(t *testing.T) {ctx, done := context.WithTimeout(t.Context(), 500*time.Millisecond)defer done()@@ -2167,33 +2165,28 @@ func TestImageGenRunnerCanBeEvicted(t *testing.T) {s.getGpuFn = getGpuFns.getSystemInfoFn = getSystemInfoFn- // Simulate an image gen runner already loaded- imageGenRunner := &runnerRef{- model: &Model{Name: "z-image", ModelPath: "/fake/image/model"},- modelPath: "/fake/image/model",+ loadedRunner := &runnerRef{+ model: &Model{Name: "test", ModelPath: "/fake/model"},+ modelPath: "/fake/model",llama: &mockLlm{vramSize: 21 * format.GigaByte, vramByGPU: map[ml.DeviceID]uint64{}},sessionDuration: 5 * time.Millisecond,refCount: 0, // idle}s.loadedMu.Lock()- s.loaded["/fake/image/model"] = imageGenRunner+ s.loaded["/fake/model"] = loadedRunners.loadedMu.Unlock()- // Verify the image gen runner is loadeds.loadedMu.Lock()require.Len(t, s.loaded, 1)s.loadedMu.Unlock()- // findRunnerToUnload should find the idle image gen runnerrunner := s.findRunnerToUnload()require.NotNil(t, runner)- require.Equal(t, "/fake/image/model", runner.modelPath)+ require.Equal(t, "/fake/model", runner.modelPath)}-// TestImageGenSchedulerCoexistence verifies that image generation models-// can coexist with language models in the scheduler and VRAM is tracked correctly.-func TestImageGenSchedulerCoexistence(t *testing.T) {+func TestSchedulerTracksMultipleLoadedRunners(t *testing.T) {ctx, done := context.WithTimeout(t.Context(), 500*time.Millisecond)defer done()@@ -2201,19 +2194,18 @@ func TestImageGenSchedulerCoexistence(t *testing.T) {s.getGpuFn = getGpuFns.getSystemInfoFn = getSystemInfoFn- // Load both an imagegen runner and a language model runner- imageGenRunner := &runnerRef{- model: &Model{Name: "flux", ModelPath: "/fake/flux/model"},- modelPath: "/fake/flux/model",+ firstRunner := &runnerRef{+ model: &Model{Name: "first", ModelPath: "/fake/first/model"},+ modelPath: "/fake/first/model",llama: &mockLlm{vramSize: 8 * format.GigaByte, vramByGPU: map[ml.DeviceID]uint64{{Library: "Metal"}: 8 * format.GigaByte}},sessionDuration: 10 * time.Millisecond,numParallel: 1,refCount: 0,}- langModelRunner := &runnerRef{- model: &Model{Name: "llama3", ModelPath: "/fake/llama3/model"},- modelPath: "/fake/llama3/model",+ secondRunner := &runnerRef{+ model: &Model{Name: "second", ModelPath: "/fake/second/model"},+ modelPath: "/fake/second/model",llama: &mockLlm{vramSize: 4 * format.GigaByte, vramByGPU: map[ml.DeviceID]uint64{{Library: "Metal"}: 4 * format.GigaByte}},sessionDuration: 10 * time.Millisecond,numParallel: 1,@@ -2221,18 +2213,16 @@ func TestImageGenSchedulerCoexistence(t *testing.T) {}s.loadedMu.Lock()- s.loaded["/fake/flux/model"] = imageGenRunner- s.loaded["/fake/llama3/model"] = langModelRunner+ s.loaded["/fake/first/model"] = firstRunner+ s.loaded["/fake/second/model"] = secondRunners.loadedMu.Unlock()- // Verify both are loadeds.loadedMu.Lock()require.Len(t, s.loaded, 2)- require.NotNil(t, s.loaded["/fake/flux/model"])- require.NotNil(t, s.loaded["/fake/llama3/model"])+ require.NotNil(t, s.loaded["/fake/first/model"])+ require.NotNil(t, s.loaded["/fake/second/model"])s.loadedMu.Unlock()- // Verify updateFreeSpace accounts for bothgpus := []ml.DeviceInfo{{DeviceID: ml.DeviceID{Library: "Metal"},@@ -2242,7 +2232,6 @@ func TestImageGenSchedulerCoexistence(t *testing.T) {}s.updateFreeSpace(gpus)- // Free memory should be reduced by both modelsexpectedFree := uint64(24*format.GigaByte) - uint64(8*format.GigaByte) - uint64(4*format.GigaByte)require.Equal(t, expectedFree, gpus[0].FreeMemory)}diff --git a/x/create/client/create.go b/x/create/client/create.goindex c4f61755d..8f6014ce0 100644--- a/x/create/client/create.go+++ b/x/create/client/create.go@@ -382,19 +382,6 @@ func newManifestWriter(opts CreateOptions, capabilities []string, parserName, rereturn fmt.Errorf("invalid model name: %s", modelName)}- // TODO: find a better way to detect image input support- // For now, hardcode Flux2KleinPipeline as supporting vision (image input)- caps := capabilities- modelIndex := filepath.Join(opts.ModelDir, "model_index.json")- if data, err := os.ReadFile(modelIndex); err == nil {- var cfg struct {- ClassName string `json:"_class_name"`- }- if json.Unmarshal(data, &cfg) == nil && cfg.ClassName == "Flux2KleinPipeline" {- caps = append(caps, "vision")- }- }-// Create config blob with version requirement.configData := model.ConfigV2{}if opts.BaseConfig != nil {@@ -404,7 +391,7 @@ func newManifestWriter(opts CreateOptions, capabilities []string, parserName, reif opts.Quantize != "" || configData.FileType == "" {configData.FileType = strings.ToLower(strings.TrimSpace(opts.Quantize))}- configData.Capabilities = caps+ configData.Capabilities = capabilitiesconfigData.Requires = MinOllamaVersionif opts.Modelfile != nil && opts.Modelfile.Requires != "" {configData.Requires = opts.Modelfile.Requiresdiff --git a/x/create/create.go b/x/create/create.goindex feca0c932..06e07b6fd 100644--- a/x/create/create.go+++ b/x/create/create.go@@ -126,13 +126,6 @@ func IsSafetensorsLLMModel(modelName string) bool {return config.ModelFormat == "safetensors" && slices.Contains(config.Capabilities, "completion")}-// IsTensorModelDir checks if the directory contains a diffusers-style tensor model-// by looking for model_index.json, which is the standard diffusers pipeline config.-func IsTensorModelDir(dir string) bool {- _, err := os.Stat(filepath.Join(dir, "model_index.json"))- return err == nil-}-// IsSafetensorsModelDir checks if the directory contains a standard safetensors model// by looking for config.json and at least one .safetensors file.func IsSafetensorsModelDir(dir string) bool {diff --git a/x/create/create_test.go b/x/create/create_test.goindex 4ba48b492..59e4dcbdf 100644--- a/x/create/create_test.go+++ b/x/create/create_test.go@@ -15,50 +15,6 @@ import (st "github.com/ollama/ollama/x/safetensors")-func TestIsTensorModelDir(t *testing.T) {- tests := []struct {- name string- setup func(dir string) error- expected bool- }{- {- name: "valid diffusers model with model_index.json",- setup: func(dir string) error {- return os.WriteFile(filepath.Join(dir, "model_index.json"), []byte(`{"_class_name": "FluxPipeline"}`), 0o644)- },- expected: true,- },- {- name: "empty directory",- setup: func(dir string) error {- return nil- },- expected: false,- },- {- name: "directory with other files but no model_index.json",- setup: func(dir string) error {- return os.WriteFile(filepath.Join(dir, "config.json"), []byte(`{}`), 0o644)- },- expected: false,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- dir := t.TempDir()- if err := tt.setup(dir); err != nil {- t.Fatalf("setup failed: %v", err)- }-- got := IsTensorModelDir(dir)- if got != tt.expected {- t.Errorf("IsTensorModelDir() = %v, want %v", got, tt.expected)- }- })- }-}-func TestValidateScalarFloat32TensorData(t *testing.T) {td := st.NewTensorDataFromBytes("linear.weight_scale_2", "F32", []int32{}, encodeFloat32s(2))diff --git a/x/imagegen/.gitignore b/x/imagegen/.gitignoredeleted file mode 100644index 2b00c701a..000000000--- a/x/imagegen/.gitignore+++ /dev/null@@ -1,38 +0,0 @@-# Build directories-build/-dist/--# CMake-CMakeCache.txt-CMakeFiles/-cmake_install.cmake-Makefile-*.cmake--# IDE-.idea/-.vscode/-*.swp-*.swo-*~--# macOS-.DS_Store-*.dSYM/--# Go-*.exe-*.exe~-*.dll-*.so-*.dylib--# Python-*.npy--/engine-weights-outputs--prompt.txt-negative.txtdiff --git a/x/imagegen/README.md b/x/imagegen/README.mddeleted file mode 100644index 10d4beafa..000000000--- a/x/imagegen/README.md+++ /dev/null@@ -1,250 +0,0 @@-# Image Generation in Ollama (Experimental)--Generate images from text prompts using local AI models.--## Quick Start--```bash-# Run with a prompt-ollama run z-image "a sunset over mountains"-Generating: step 30/30-Image saved to: /tmp/ollama-image-1704067200.png-```--On macOS, the generated image will automatically open in Preview.--## Supported Models--| Model | VRAM Required | Notes |-|-------|---------------|-------|-| z-image | ~12GB | Based on Flux architecture |--## CLI Usage--```bash-# Generate an image-ollama run z-image "a cat playing piano"--# Check if model is running-ollama ps--# Stop the model-ollama stop z-image-```--## API--### OpenAI-Compatible Endpoint--```bash-POST /v1/images/generations-```--**Request:**-```json-{- "model": "z-image",- "prompt": "a sunset over mountains",- "size": "1024x1024",- "response_format": "b64_json"-}-```--**Response:**-```json-{- "created": 1704067200,- "data": [- {- "b64_json": "iVBORw0KGgo..."- }- ]-}-```--### Example: cURL--```bash-curl http://localhost:11434/v1/images/generations \- -H "Content-Type: application/json" \- -d '{- "model": "z-image",- "prompt": "a white cat",- "size": "1024x1024"- }'-```--### Example: Save to File--```bash-curl -s http://localhost:11434/v1/images/generations \- -H "Content-Type: application/json" \- -d '{- "model": "z-image",- "prompt": "a white cat",- "size": "1024x1024"- }' | jq -r '.data[0].b64_json' | base64 -d > image.png-```--### Streaming Progress--Enable streaming to receive progress updates via SSE:--```bash-curl http://localhost:11434/v1/images/generations \- -H "Content-Type: application/json" \- -d '{"model": "z-image", "prompt": "a sunset", "stream": true}'-```--Events:-```-event: progress-data: {"step": 1, "total": 30}--event: progress-data: {"step": 2, "total": 30}-...--event: done-data: {"created": 1704067200, "data": [{"b64_json": "..."}]}-```--## Parameters--| Parameter | Type | Default | Description |-|-----------|------|---------|-------------|-| model | string | required | Model name |-| prompt | string | required | Text description of image |-| size | string | "1024x1024" | Image dimensions (WxH) |-| n | int | 1 | Number of images (currently only 1 supported) |-| response_format | string | "b64_json" | "b64_json" or "url" |-| stream | bool | false | Enable progress streaming |--## Requirements--- macOS with Apple Silicon (M1/M2/M3/M4)-- CUDA: tested on CUDA 12 Blackwell, more testing coming soon-- Sufficient VRAM (see model table above)-- Ollama built with MLX support--## Limitations--- macOS only (uses MLX backend)-- Single image per request-- Fixed step count (30 steps)-- Modelfiles not yet supported (use `ollama create` from model directory)-------# Tensor Model Storage Format--Tensor models store each tensor as a separate blob with metadata in the manifest. This enables faster downloads (parallel fetching) and deduplication (shared tensors are stored once).--## Manifest Structure--The manifest follows the standard ollama format with tensor-specific layer metadata:--```json-{- "schemaVersion": 2,- "mediaType": "application/vnd.docker.distribution.manifest.v2+json",- "config": { "digest": "sha256:...", "size": 1234 },- "layers": [- {- "mediaType": "application/vnd.ollama.image.tensor",- "digest": "sha256:25b36eed...",- "size": 49807448,- "name": "text_encoder/model.layers.0.mlp.down_proj.weight",- "dtype": "BF16",- "shape": [2560, 9728]- },- {- "mediaType": "application/vnd.ollama.image.json",- "digest": "sha256:abc123...",- "size": 512,- "name": "text_encoder/config.json"- }- ]-}-```--Each tensor layer includes:-- `name`: Path-style tensor name (e.g., `text_encoder/model.layers.0.mlp.down_proj.weight`)-- `dtype`: Data type (BF16, F32, etc.)-- `shape`: Tensor dimensions--Config layers use the same path-style naming (e.g., `tokenizer/tokenizer.json`).--## Blob Format--Each tensor blob is a minimal safetensors file:--```-[8 bytes: header size (uint64 LE)]-[~80 bytes: JSON header, padded to 8-byte alignment]-[N bytes: raw tensor data]-```--Header contains a single tensor named `"data"`:--```json-{"data":{"dtype":"BF16","shape":[2560,9728],"data_offsets":[0,49807360]}}-```--## Why Include the Header?--The ~88 byte safetensors header enables MLX's native `mlx_load_safetensors` function, which:--1. **Uses mmap** - Maps file directly into memory, no copies-2. **Zero-copy to GPU** - MLX reads directly from mapped pages-3. **No custom code** - Standard MLX API, battle-tested--Without the header, we'd need custom C++ code to create MLX arrays from raw mmap'd data. MLX's public API doesn't expose this - it always copies when creating arrays from external pointers.--The overhead is negligible: 88 bytes per tensor = ~100KB total for a 13GB model (0.0007%).--## Why Per-Tensor Blobs?--**Deduplication**: Blobs are content-addressed by SHA256. If two models share identical tensors (same weights, dtype, shape), they share the same blob file.--Example: Model A and Model B both use the same text encoder. The text encoder's 400 tensors are stored once, referenced by both manifests.--```-~/.ollama/models/- blobs/- sha256-25b36eed... <- shared by both models- sha256-abc123...- manifests/- library/model-a/latest <- references sha256-25b36eed- library/model-b/latest <- references sha256-25b36eed-```--## Import Flow--```-cd ./weights/Z-Image-Turbo-ollama create z-image--1. Scan component directories (text_encoder/, transformer/, vae/)-2. For each .safetensors file:- - Extract individual tensors- - Wrap each in minimal safetensors format (88B header + data)- - Write to blob store (SHA256 content-addressed)- - Add layer entry to manifest with path-style name-3. Copy config files (*.json) as config layers-4. Write manifest-```--## FP8 Quantization--Z-Image supports FP8 quantization to reduce memory usage by ~50% while maintaining image quality.--### Usage--```bash-cd ./weights/Z-Image-Turbo-ollama create z-image-fp8 --quantize fp8-```--This quantizes weights during import. The resulting model will be ~15GB instead of ~31GB.-diff --git a/x/imagegen/cache/cache.go b/x/imagegen/cache/cache.godeleted file mode 100644index d4e19ba55..000000000--- a/x/imagegen/cache/cache.go+++ /dev/null@@ -1,170 +0,0 @@-package cache--import "github.com/ollama/ollama/x/imagegen/mlx"--type Cache interface {- Update(k, v *mlx.Array, seqLen int) (*mlx.Array, *mlx.Array)- Offset() int- Len() int- State() []*mlx.Array- Reset()-}--type KVCache struct {- keys, values *mlx.Array- offset int- step int-}--func NewKVCache() *KVCache {- return &KVCache{step: 256}-}--func (c *KVCache) Update(k, v *mlx.Array, seqLen int) (*mlx.Array, *mlx.Array) {- prev := c.offset- shape := k.Shape()- B, H, Dk := shape[0], shape[1], shape[3]- Dv := v.Shape()[3]-- // Grow buffer if needed- if c.keys == nil || (prev+seqLen) > int(c.keys.Shape()[2]) {- nSteps := (c.step + seqLen - 1) / c.step- newK := mlx.Zeros([]int32{B, H, int32(nSteps * c.step), Dk}, k.Dtype())- newV := mlx.Zeros([]int32{B, H, int32(nSteps * c.step), Dv}, v.Dtype())-- if c.keys != nil {- if prev%c.step != 0 {- c.keys = mlx.Slice(c.keys, []int32{0, 0, 0, 0}, []int32{B, H, int32(prev), Dk})- c.values = mlx.Slice(c.values, []int32{0, 0, 0, 0}, []int32{B, H, int32(prev), Dv})- }- c.keys = mlx.Concatenate([]*mlx.Array{c.keys, newK}, 2)- c.values = mlx.Concatenate([]*mlx.Array{c.values, newV}, 2)- } else {- c.keys, c.values = newK, newV- }- }-- c.offset += seqLen- c.keys = mlx.SliceUpdateInplace(c.keys, k, []int32{0, 0, int32(prev), 0}, []int32{B, H, int32(c.offset), Dk})- c.values = mlx.SliceUpdateInplace(c.values, v, []int32{0, 0, int32(prev), 0}, []int32{B, H, int32(c.offset), Dv})-- return mlx.Slice(c.keys, []int32{0, 0, 0, 0}, []int32{B, H, int32(c.offset), Dk}),- mlx.Slice(c.values, []int32{0, 0, 0, 0}, []int32{B, H, int32(c.offset), Dv})-}--func (c *KVCache) State() []*mlx.Array {- if c.keys == nil {- return nil- }- return []*mlx.Array{c.keys, c.values}-}--func (c *KVCache) Offset() int { return c.offset }-func (c *KVCache) Len() int { return c.offset }--// Reset clears the cache state for a new generation session-func (c *KVCache) Reset() {- c.keys = nil- c.values = nil- c.offset = 0-}--// RotatingKVCache implements sliding window attention with bounded memory-type RotatingKVCache struct {- keys, values *mlx.Array- offset int- maxSize int- step int- idx int-}--func NewRotatingKVCache(maxSize int) *RotatingKVCache {- return &RotatingKVCache{maxSize: maxSize, step: 256}-}--func (c *RotatingKVCache) Update(k, v *mlx.Array, seqLen int) (*mlx.Array, *mlx.Array) {- if seqLen > 1 {- return c.updateConcat(k, v, seqLen)- }- return c.updateInPlace(k, v)-}--func (c *RotatingKVCache) updateInPlace(k, v *mlx.Array) (*mlx.Array, *mlx.Array) {- shape := k.Shape()- B, H, Dk := shape[0], shape[1], shape[3]- Dv := v.Shape()[3]-- // Grow buffer if not yet at max- if c.keys == nil || (c.idx >= int(c.keys.Shape()[2]) && int(c.keys.Shape()[2]) < c.maxSize) {- var cap int- if c.keys != nil {- cap = int(c.keys.Shape()[2])- }- newSize := min(c.step, c.maxSize-cap)- newK := mlx.Zeros([]int32{B, H, int32(newSize), Dk}, k.Dtype())- newV := mlx.Zeros([]int32{B, H, int32(newSize), Dv}, v.Dtype())- if c.keys != nil {- c.keys = mlx.Concatenate([]*mlx.Array{c.keys, newK}, 2)- c.values = mlx.Concatenate([]*mlx.Array{c.values, newV}, 2)- } else {- c.keys, c.values = newK, newV- }- }-- // Rotate when hitting max- if c.idx >= c.maxSize {- c.idx = 0- }-- c.keys = mlx.SliceUpdateInplace(c.keys, k, []int32{0, 0, int32(c.idx), 0}, []int32{B, H, int32(c.idx + 1), Dk})- c.values = mlx.SliceUpdateInplace(c.values, v, []int32{0, 0, int32(c.idx), 0}, []int32{B, H, int32(c.idx + 1), Dv})-- c.offset++- c.idx++-- validLen := int32(min(c.offset, c.maxSize))- return mlx.Slice(c.keys, []int32{0, 0, 0, 0}, []int32{B, H, validLen, Dk}),- mlx.Slice(c.values, []int32{0, 0, 0, 0}, []int32{B, H, validLen, Dv})-}--func (c *RotatingKVCache) updateConcat(k, v *mlx.Array, seqLen int) (*mlx.Array, *mlx.Array) {- shape := k.Shape()- B, H, Dk := shape[0], shape[1], shape[3]- Dv := v.Shape()[3]-- if c.keys == nil {- c.keys, c.values = k, v- } else {- c.keys = mlx.Concatenate([]*mlx.Array{c.keys, k}, 2)- c.values = mlx.Concatenate([]*mlx.Array{c.values, v}, 2)- }- c.offset += seqLen-- // Trim to max_size to maintain sliding window- cap := int(c.keys.Shape()[2])- if trim := cap - c.maxSize; trim > 0 {- c.keys = mlx.Slice(c.keys, []int32{0, 0, int32(trim), 0}, []int32{B, H, int32(cap), Dk})- c.values = mlx.Slice(c.values, []int32{0, 0, int32(trim), 0}, []int32{B, H, int32(cap), Dv})- }-- c.idx = int(c.keys.Shape()[2])- return c.keys, c.values-}--func (c *RotatingKVCache) State() []*mlx.Array {- if c.keys == nil {- return nil- }- return []*mlx.Array{c.keys, c.values}-}--func (c *RotatingKVCache) Offset() int { return c.offset }-func (c *RotatingKVCache) Len() int { return min(c.offset, c.maxSize) }--// Reset clears the cache state for a new generation session-func (c *RotatingKVCache) Reset() {- c.keys = nil- c.values = nil- c.offset = 0- c.idx = 0-}diff --git a/x/imagegen/cache/step.go b/x/imagegen/cache/step.godeleted file mode 100644index 066f2f645..000000000--- a/x/imagegen/cache/step.go+++ /dev/null@@ -1,162 +0,0 @@-package cache--import "github.com/ollama/ollama/x/imagegen/mlx"--// StepCache caches layer outputs across diffusion denoising steps.-// Based on DeepCache (CVPR 2024) and Learning-to-Cache (NeurIPS 2024):-// shallow layers change little between consecutive steps, so we can-// cache their outputs and skip recomputation on non-refresh steps.-//-// Supports both single-stream and dual-stream architectures:-// - Single-stream: use Get/Set for the single output per layer-// - Dual-stream: use Get/Set for stream 1 (imgH), Get2/Set2 for stream 2 (txtH)-//-// Usage (single-stream):-//-// cache := NewStepCache(15) // cache first 15 layers-// for step := 0; step < numSteps; step++ {-// refresh := cache.ShouldRefresh(step, 3) // refresh every 3 steps-// for i, layer := range layers {-// if i < 15 && !refresh && cache.Get(i) != nil {-// output = cache.Get(i) // reuse cached-// } else {-// output = layer.Forward(input)-// if i < 15 && refresh {-// cache.Set(i, output)-// }-// }-// }-// }-// cache.Free() // cleanup when done-//-// Usage (dual-stream):-//-// cache := NewStepCache(15)-// for step := 0; step < numSteps; step++ {-// refresh := cache.ShouldRefresh(step, 3)-// for i, layer := range layers {-// if i < 15 && !refresh && cache.Get(i) != nil {-// imgH, txtH = cache.Get(i), cache.Get2(i)-// } else {-// imgH, txtH = layer.Forward(imgH, txtH, ...)-// if i < 15 && refresh {-// cache.Set(i, imgH)-// cache.Set2(i, txtH)-// }-// }-// }-// }-type StepCache struct {- layers []*mlx.Array // cached layer outputs (stream 1)- layers2 []*mlx.Array // cached layer outputs (stream 2, for dual-stream models)- constant *mlx.Array // optional constant (e.g., text embeddings)-}--// NewStepCache creates a cache for the given number of layers.-func NewStepCache(numLayers int) *StepCache {- return &StepCache{- layers: make([]*mlx.Array, numLayers),- layers2: make([]*mlx.Array, numLayers),- }-}--// ShouldRefresh returns true if the cache should be refreshed at this step.-// Refresh happens on step 0, interval, 2*interval, etc.-func (c *StepCache) ShouldRefresh(step, interval int) bool {- return step%interval == 0-}--// Get returns the cached output for a layer, or nil if not cached.-func (c *StepCache) Get(layer int) *mlx.Array {- if layer < len(c.layers) {- return c.layers[layer]- }- return nil-}--// Set stores a layer output (stream 1), freeing any previous value.-func (c *StepCache) Set(layer int, arr *mlx.Array) {- if layer < len(c.layers) {- if c.layers[layer] != nil {- c.layers[layer].Free()- }- c.layers[layer] = arr- }-}--// Get2 returns the cached output for a layer (stream 2), or nil if not cached.-// Used for dual-stream architectures.-func (c *StepCache) Get2(layer int) *mlx.Array {- if layer < len(c.layers2) {- return c.layers2[layer]- }- return nil-}--// Set2 stores a layer output (stream 2), freeing any previous value.-// Used for dual-stream architectures.-func (c *StepCache) Set2(layer int, arr *mlx.Array) {- if layer < len(c.layers2) {- if c.layers2[layer] != nil {- c.layers2[layer].Free()- }- c.layers2[layer] = arr- }-}--// GetConstant returns the cached constant value.-func (c *StepCache) GetConstant() *mlx.Array {- return c.constant-}--// SetConstant stores a constant value, freeing any previous value.-func (c *StepCache) SetConstant(arr *mlx.Array) {- if c.constant != nil {- c.constant.Free()- }- c.constant = arr-}--// Arrays returns all non-nil cached arrays (for pool.Keep).-func (c *StepCache) Arrays() []*mlx.Array {- var result []*mlx.Array- if c.constant != nil {- result = append(result, c.constant)- }- for _, arr := range c.layers {- if arr != nil {- result = append(result, arr)- }- }- for _, arr := range c.layers2 {- if arr != nil {- result = append(result, arr)- }- }- return result-}--// Free releases all cached arrays. Call when generation completes.-func (c *StepCache) Free() {- if c.constant != nil {- c.constant.Free()- c.constant = nil- }- for i, arr := range c.layers {- if arr != nil {- arr.Free()- c.layers[i] = nil- }- }- for i, arr := range c.layers2 {- if arr != nil {- arr.Free()- c.layers2[i] = nil- }- }-}--// NumLayers returns the number of layers this cache can store.-func (c *StepCache) NumLayers() int {- return len(c.layers)-}diff --git a/x/imagegen/cache/teacache.go b/x/imagegen/cache/teacache.godeleted file mode 100644index fb06047ea..000000000--- a/x/imagegen/cache/teacache.go+++ /dev/null@@ -1,195 +0,0 @@-// Package cache provides caching mechanisms for diffusion model inference.-package cache--import (- "github.com/ollama/ollama/x/imagegen/mlx"-)--// TeaCache implements Timestep Embedding Aware Caching for diffusion models.-// It caches the transformer output and reuses it when timestep values-// are similar between consecutive steps.-//-// For CFG (classifier-free guidance), it caches pos and neg predictions-// separately and always computes CFG fresh to avoid error amplification.-//-// Reference: "Timestep Embedding Tells: It's Time to Cache for Video Diffusion Model"-// https://github.com/ali-vilab/TeaCache-type TeaCache struct {- // Cached transformer output from last computed step (non-CFG mode)- cachedOutput *mlx.Array-- // Cached CFG outputs (pos and neg separately)- cachedPosOutput *mlx.Array- cachedNegOutput *mlx.Array-- // Previous timestep value for difference calculation- prevTimestep float32-- // Accumulated difference for rescaling- accumulatedDiff float32-- // Configuration- threshold float32 // Threshold for recomputation decision- rescaleFactor float32 // Model-specific rescaling factor- skipEarlySteps int // Number of early steps to never cache-- // Statistics- cacheHits int- cacheMisses int-}--// TeaCacheConfig holds configuration for TeaCache.-type TeaCacheConfig struct {- // Threshold for recomputation. Lower = more cache hits, potential quality loss.- // Recommended: 0.05-0.15 for image models- Threshold float32-- // Rescale factor to adjust timestep embedding differences.- // Model-specific, typically 1.0-2.0- RescaleFactor float32-- // SkipEarlySteps: number of early steps to always compute (never cache).- // Set to 2-3 for CFG mode to preserve structure. 0 = no skipping.- SkipEarlySteps int-}--// DefaultTeaCacheConfig returns default configuration for TeaCache.-func DefaultTeaCacheConfig() *TeaCacheConfig {- return &TeaCacheConfig{- Threshold: 0.1,- RescaleFactor: 1.0,- }-}--// NewTeaCache creates a new TeaCache instance.-func NewTeaCache(cfg *TeaCacheConfig) *TeaCache {- if cfg == nil {- cfg = DefaultTeaCacheConfig()- }- return &TeaCache{- threshold: cfg.Threshold,- rescaleFactor: cfg.RescaleFactor,- skipEarlySteps: cfg.SkipEarlySteps,- }-}--// ShouldCompute determines if we should compute the full forward pass-// or reuse the cached output based on timestep similarity.-//-// Algorithm:-// 1. First step always computes-// 2. Subsequent steps compare |currTimestep - prevTimestep| * rescaleFactor-// 3. If accumulated difference > threshold, compute new output-// 4. Otherwise, reuse cached output-func (tc *TeaCache) ShouldCompute(step int, timestep float32) bool {- // Always compute early steps (critical for structure)- // Check both regular cache and CFG cache- hasCachedOutput := tc.cachedOutput != nil || tc.HasCFGCache()- if step < tc.skipEarlySteps || step == 0 || !hasCachedOutput {- return true- }-- // Compute absolute difference between current and previous timestep- diff := timestep - tc.prevTimestep- if diff < 0 {- diff = -diff- }-- // Apply rescaling factor- scaledDiff := diff * tc.rescaleFactor-- // Accumulate difference (helps track drift over multiple cached steps)- tc.accumulatedDiff += scaledDiff-- // Decision based on accumulated difference- if tc.accumulatedDiff > tc.threshold {- tc.accumulatedDiff = 0 // Reset accumulator- return true- }-- return false-}--// UpdateCache stores the computed output for potential reuse (non-CFG mode).-func (tc *TeaCache) UpdateCache(output *mlx.Array, timestep float32) {- // Free previous cached output- if tc.cachedOutput != nil {- tc.cachedOutput.Free()- }-- // Store new cached values- tc.cachedOutput = output- tc.prevTimestep = timestep- tc.cacheMisses++-}--// UpdateCFGCache stores pos and neg outputs separately for CFG mode.-// This allows CFG to be computed fresh each step, avoiding error amplification.-func (tc *TeaCache) UpdateCFGCache(posOutput, negOutput *mlx.Array, timestep float32) {- // Free previous cached outputs- if tc.cachedPosOutput != nil {- tc.cachedPosOutput.Free()- }- if tc.cachedNegOutput != nil {- tc.cachedNegOutput.Free()- }-- // Store new cached values- tc.cachedPosOutput = posOutput- tc.cachedNegOutput = negOutput- tc.prevTimestep = timestep- tc.cacheMisses++-}--// GetCached returns the cached output (non-CFG mode).-func (tc *TeaCache) GetCached() *mlx.Array {- tc.cacheHits++- return tc.cachedOutput-}--// GetCFGCached returns cached pos and neg outputs for CFG mode.-func (tc *TeaCache) GetCFGCached() (pos, neg *mlx.Array) {- tc.cacheHits++- return tc.cachedPosOutput, tc.cachedNegOutput-}--// HasCFGCache returns true if CFG cache is available.-func (tc *TeaCache) HasCFGCache() bool {- return tc.cachedPosOutput != nil && tc.cachedNegOutput != nil-}--// Arrays returns all arrays that should be kept alive.-func (tc *TeaCache) Arrays() []*mlx.Array {- var arrays []*mlx.Array- if tc.cachedOutput != nil {- arrays = append(arrays, tc.cachedOutput)- }- if tc.cachedPosOutput != nil {- arrays = append(arrays, tc.cachedPosOutput)- }- if tc.cachedNegOutput != nil {- arrays = append(arrays, tc.cachedNegOutput)- }- return arrays-}--// Stats returns cache hit/miss statistics.-func (tc *TeaCache) Stats() (hits, misses int) {- return tc.cacheHits, tc.cacheMisses-}--// Free releases all cached arrays.-func (tc *TeaCache) Free() {- if tc.cachedOutput != nil {- tc.cachedOutput.Free()- tc.cachedOutput = nil- }- if tc.cachedPosOutput != nil {- tc.cachedPosOutput.Free()- tc.cachedPosOutput = nil- }- if tc.cachedNegOutput != nil {- tc.cachedNegOutput.Free()- tc.cachedNegOutput = nil- }-}diff --git a/x/imagegen/cli.go b/x/imagegen/cli.godeleted file mode 100644index e5de34efa..000000000--- a/x/imagegen/cli.go+++ /dev/null@@ -1,576 +0,0 @@-// cli.go provides CLI commands for image generation models.-//-// TODO (jmorganca): Integrate these commands into cmd/cmd.go when stable.-// Currently these are separate to keep experimental code isolated.--package imagegen--import (- "encoding/base64"- "errors"- "fmt"- "io"- "net/http"- "os"- "regexp"- "slices"- "strconv"- "strings"- "time"-- "github.com/spf13/cobra"-- "github.com/ollama/ollama/api"- "github.com/ollama/ollama/envconfig"- "github.com/ollama/ollama/progress"- "github.com/ollama/ollama/readline"-)--// ImageGenOptions holds options for image generation.-// These can be set via environment variables or interactive commands.-type ImageGenOptions struct {- Width int- Height int- Steps int- Seed int- NegativePrompt string-}--// DefaultOptions returns the default image generation options.-func DefaultOptions() ImageGenOptions {- return ImageGenOptions{- Width: 1024,- Height: 1024,- Steps: 0, // 0 means model default- Seed: 0, // 0 means random- }-}--// RegisterFlags adds image generation flags to the given command.-// Flags are hidden since they only apply to image generation models.-func RegisterFlags(cmd *cobra.Command) {- cmd.Flags().Int("width", 1024, "Image width")- cmd.Flags().Int("height", 1024, "Image height")- cmd.Flags().Int("steps", 0, "Denoising steps (0 = model default)")- cmd.Flags().Int("seed", 0, "Random seed (0 for random)")- cmd.Flags().String("negative", "", "Negative prompt")- // Hide from main flags section - shown in separate section via AppendFlagsDocs- cmd.Flags().MarkHidden("width")- cmd.Flags().MarkHidden("height")- cmd.Flags().MarkHidden("steps")- cmd.Flags().MarkHidden("seed")- cmd.Flags().MarkHidden("negative")-}--// AppendFlagsDocs appends image generation flags documentation to the command's usage template.-func AppendFlagsDocs(cmd *cobra.Command) {- usage := `-Image Generation Flags (experimental):- --width int Image width- --height int Image height- --steps int Denoising steps- --seed int Random seed- --negative str Negative prompt-`- cmd.SetUsageTemplate(cmd.UsageTemplate() + usage)-}--// RunCLI handles the CLI for image generation models.-// Returns true if it handled the request, false if the caller should continue with normal flow.-// Supports flags: --width, --height, --steps, --seed, --negative-// Image paths can be included in the prompt and will be extracted automatically.-func RunCLI(cmd *cobra.Command, name string, prompt string, interactive bool, keepAlive *api.Duration) error {- // Get options from flags (with env var defaults)- opts := DefaultOptions()- if cmd != nil && cmd.Flags() != nil {- if v, err := cmd.Flags().GetInt("width"); err == nil && v > 0 {- opts.Width = v- }- if v, err := cmd.Flags().GetInt("height"); err == nil && v > 0 {- opts.Height = v- }- if v, err := cmd.Flags().GetInt("steps"); err == nil && v > 0 {- opts.Steps = v- }- if v, err := cmd.Flags().GetInt("seed"); err == nil && v != 0 {- opts.Seed = v- }- if v, err := cmd.Flags().GetString("negative"); err == nil && v != "" {- opts.NegativePrompt = v- }- }-- if interactive {- return runInteractive(cmd, name, keepAlive, opts)- }-- // One-shot generation- return generateImageWithOptions(cmd, name, prompt, keepAlive, opts)-}--// generateImageWithOptions generates an image with the given options.-func generateImageWithOptions(cmd *cobra.Command, modelName, prompt string, keepAlive *api.Duration, opts ImageGenOptions) error {- client, err := api.ClientFromEnvironment()- if err != nil {- return err- }-- // Extract any image paths from the prompt- prompt, images, err := extractFileData(prompt)- if err != nil {- return err- }-- req := &api.GenerateRequest{- Model: modelName,- Prompt: prompt,- Images: images,- Width: int32(opts.Width),- Height: int32(opts.Height),- Steps: int32(opts.Steps),- }- if opts.Seed != 0 {- req.Options = map[string]any{"seed": opts.Seed}- }- if keepAlive != nil {- req.KeepAlive = keepAlive- }-- // Show loading spinner until generation starts- p := progress.NewProgress(os.Stderr)- spinner := progress.NewSpinner("")- p.Add("", spinner)-- var stepBar *progress.StepBar- var imageBase64 string- err = client.Generate(cmd.Context(), req, func(resp api.GenerateResponse) error {- // Handle progress updates using structured fields- if resp.Total > 0 {- if stepBar == nil {- spinner.Stop()- stepBar = progress.NewStepBar("Generating", int(resp.Total))- p.Add("", stepBar)- }- stepBar.Set(int(resp.Completed))- }-- // Handle final response with image data- if resp.Done && resp.Image != "" {- imageBase64 = resp.Image- }-- return nil- })-- p.StopAndClear()- if err != nil {- return err- }-- if imageBase64 != "" {- // Decode base64 and save to CWD- imageData, err := base64.StdEncoding.DecodeString(imageBase64)- if err != nil {- return fmt.Errorf("failed to decode image: %w", err)- }-- // Create filename from prompt- safeName := sanitizeFilename(prompt)- if len(safeName) > 50 {- safeName = safeName[:50]- }- timestamp := time.Now().Format("20060102-150405")- filename := fmt.Sprintf("%s-%s.png", safeName, timestamp)-- if err := os.WriteFile(filename, imageData, 0o644); err != nil {- return fmt.Errorf("failed to save image: %w", err)- }-- displayImageInTerminal(filename)- fmt.Printf("Image saved to: %s\n", filename)- }-- return nil-}--// runInteractive runs an interactive REPL for image generation.-func runInteractive(cmd *cobra.Command, modelName string, keepAlive *api.Duration, opts ImageGenOptions) error {- client, err := api.ClientFromEnvironment()- if err != nil {- return err- }-- // Preload the model with the specified keepalive- p := progress.NewProgress(os.Stderr)- spinner := progress.NewSpinner("")- p.Add("", spinner)-- preloadReq := &api.GenerateRequest{- Model: modelName,- KeepAlive: keepAlive,- }- if err := client.Generate(cmd.Context(), preloadReq, func(resp api.GenerateResponse) error {- return nil- }); err != nil {- p.StopAndClear()- return fmt.Errorf("failed to load model: %w", err)- }- p.StopAndClear()-- scanner, err := readline.New(readline.Prompt{- Prompt: ">>> ",- Placeholder: "Describe an image to generate (/help for commands)",- })- if err != nil {- return err- }-- if envconfig.NoHistory() {- scanner.HistoryDisable()- }-- for {- line, err := scanner.Readline()- switch {- case errors.Is(err, io.EOF):- fmt.Println()- return nil- case errors.Is(err, readline.ErrInterrupt):- if line == "" {- fmt.Println("\nUse Ctrl + d or /bye to exit.")- }- continue- case err != nil:- return err- }-- line = strings.TrimSpace(line)- if line == "" {- continue- }-- // Handle commands- switch {- case strings.HasPrefix(line, "/bye"):- return nil- case strings.HasPrefix(line, "/?"), strings.HasPrefix(line, "/help"):- printInteractiveHelp()- continue- case strings.HasPrefix(line, "/set "):- if err := handleSetCommand(line[5:], &opts); err != nil {- fmt.Fprintf(os.Stderr, "Error: %v\n", err)- }- continue- case strings.HasPrefix(line, "/show"):- printCurrentSettings(opts)- continue- case strings.HasPrefix(line, "/"):- // Check if it's a file path, not a command- args := strings.Fields(line)- isFile := false- for _, f := range extractFileNames(line) {- if strings.HasPrefix(f, args[0]) {- isFile = true- break- }- }- if !isFile {- fmt.Fprintf(os.Stderr, "Unknown command: %s (try /help)\n", args[0])- continue- }- }-- // Extract any image paths from the input- prompt, images, err := extractFileData(line)- if err != nil {- fmt.Fprintf(os.Stderr, "Error: %v\n", err)- continue- }-- // Generate image with current options- req := &api.GenerateRequest{- Model: modelName,- Prompt: prompt,- Images: images,- Width: int32(opts.Width),- Height: int32(opts.Height),- Steps: int32(opts.Steps),- }- if opts.Seed != 0 {- req.Options = map[string]any{"seed": opts.Seed}- }- if keepAlive != nil {- req.KeepAlive = keepAlive- }-- // Show loading spinner until generation starts- p := progress.NewProgress(os.Stderr)- spinner := progress.NewSpinner("")- p.Add("", spinner)-- var stepBar *progress.StepBar- var imageBase64 string-- err = client.Generate(cmd.Context(), req, func(resp api.GenerateResponse) error {- // Handle progress updates using structured fields- if resp.Total > 0 {- if stepBar == nil {- spinner.Stop()- stepBar = progress.NewStepBar("Generating", int(resp.Total))- p.Add("", stepBar)- }- stepBar.Set(int(resp.Completed))- }-- // Handle final response with image data- if resp.Done && resp.Image != "" {- imageBase64 = resp.Image- }-- return nil- })-- p.StopAndClear()- if err != nil {- fmt.Fprintf(os.Stderr, "Error: %v\n", err)- continue- }-- // Save image to current directory with descriptive name- if imageBase64 != "" {- // Decode base64 image data- imageData, err := base64.StdEncoding.DecodeString(imageBase64)- if err != nil {- fmt.Fprintf(os.Stderr, "Error decoding image: %v\n", err)- continue- }-- // Create filename from prompt (sanitized)- safeName := sanitizeFilename(line)- if len(safeName) > 50 {- safeName = safeName[:50]- }- timestamp := time.Now().Format("20060102-150405")- filename := fmt.Sprintf("%s-%s.png", safeName, timestamp)-- if err := os.WriteFile(filename, imageData, 0o644); err != nil {- fmt.Fprintf(os.Stderr, "Error saving image: %v\n", err)- continue- }-- displayImageInTerminal(filename)- fmt.Printf("Image saved to: %s\n", filename)- }-- fmt.Println()- }-}--// sanitizeFilename removes characters that aren't safe for filenames.-func sanitizeFilename(s string) string {- s = strings.ToLower(s)- s = strings.ReplaceAll(s, " ", "-")- // Remove any character that's not alphanumeric or hyphen- var result strings.Builder- for _, r := range s {- if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' {- result.WriteRune(r)- }- }- return result.String()-}--// printInteractiveHelp prints help for interactive mode commands.-// TODO: reconcile /set commands with /set parameter in text gen REPL (cmd/cmd.go)-func printInteractiveHelp() {- fmt.Fprintln(os.Stderr, "Commands:")- fmt.Fprintln(os.Stderr, " /set width <n> Set image width")- fmt.Fprintln(os.Stderr, " /set height <n> Set image height")- fmt.Fprintln(os.Stderr, " /set steps <n> Set denoising steps")- fmt.Fprintln(os.Stderr, " /set seed <n> Set random seed")- fmt.Fprintln(os.Stderr, " /set negative <s> Set negative prompt")- fmt.Fprintln(os.Stderr, " /show Show current settings")- fmt.Fprintln(os.Stderr, " /bye Exit")- fmt.Fprintln(os.Stderr)- fmt.Fprintln(os.Stderr, "Or type a prompt to generate an image.")- fmt.Fprintln(os.Stderr)-}--// printCurrentSettings prints the current image generation settings.-func printCurrentSettings(opts ImageGenOptions) {- fmt.Fprintf(os.Stderr, "Current settings:\n")- fmt.Fprintf(os.Stderr, " width: %d\n", opts.Width)- fmt.Fprintf(os.Stderr, " height: %d\n", opts.Height)- fmt.Fprintf(os.Stderr, " steps: %d\n", opts.Steps)- fmt.Fprintf(os.Stderr, " seed: %d (0=random)\n", opts.Seed)- if opts.NegativePrompt != "" {- fmt.Fprintf(os.Stderr, " negative: %s\n", opts.NegativePrompt)- }- fmt.Fprintln(os.Stderr)-}--// handleSetCommand handles /set commands to change options.-func handleSetCommand(args string, opts *ImageGenOptions) error {- parts := strings.SplitN(args, " ", 2)- if len(parts) < 2 {- return fmt.Errorf("usage: /set <option> <value>")- }-- key := strings.ToLower(parts[0])- value := strings.TrimSpace(parts[1])-- switch key {- case "width", "w":- v, err := strconv.Atoi(value)- if err != nil || v <= 0 {- return fmt.Errorf("width must be a positive integer")- }- opts.Width = v- fmt.Fprintf(os.Stderr, "Set width to %d\n", v)- case "height", "h":- v, err := strconv.Atoi(value)- if err != nil || v <= 0 {- return fmt.Errorf("height must be a positive integer")- }- opts.Height = v- fmt.Fprintf(os.Stderr, "Set height to %d\n", v)- case "steps", "s":- v, err := strconv.Atoi(value)- if err != nil || v <= 0 {- return fmt.Errorf("steps must be a positive integer")- }- opts.Steps = v- fmt.Fprintf(os.Stderr, "Set steps to %d\n", v)- case "seed":- v, err := strconv.Atoi(value)- if err != nil {- return fmt.Errorf("seed must be an integer")- }- opts.Seed = v- fmt.Fprintf(os.Stderr, "Set seed to %d\n", v)- case "negative", "neg", "n":- opts.NegativePrompt = value- if value == "" {- fmt.Fprintln(os.Stderr, "Cleared negative prompt")- } else {- fmt.Fprintf(os.Stderr, "Set negative prompt to: %s\n", value)- }- default:- return fmt.Errorf("unknown option: %s (try /help)", key)- }- return nil-}--// displayImageInTerminal attempts to render an image inline in the terminal.-// Supports iTerm2, Kitty, WezTerm, Ghostty, and other terminals with inline image support.-// Returns true if the image was displayed, false otherwise.-func displayImageInTerminal(imagePath string) bool {- // Check if terminal supports inline images- termProgram := os.Getenv("TERM_PROGRAM")- kittyWindowID := os.Getenv("KITTY_WINDOW_ID")- weztermPane := os.Getenv("WEZTERM_PANE")- ghostty := os.Getenv("GHOSTTY_RESOURCES_DIR")-- // Read the image file- data, err := os.ReadFile(imagePath)- if err != nil {- return false- }-- encoded := base64.StdEncoding.EncodeToString(data)-- switch {- case termProgram == "iTerm.app" || termProgram == "WezTerm" || weztermPane != "":- // iTerm2/WezTerm inline image protocol- // ESC ] 1337 ; File = [arguments] : base64 BEL- fmt.Printf("\033]1337;File=inline=1;preserveAspectRatio=1:%s\a\n", encoded)- return true-- case kittyWindowID != "" || ghostty != "" || termProgram == "ghostty":- // Kitty graphics protocol (also used by Ghostty)- // Send in chunks for large images- const chunkSize = 4096- for i := 0; i < len(encoded); i += chunkSize {- end := min(i+chunkSize, len(encoded))- chunk := encoded[i:end]-- if i == 0 {- // First chunk: a=T (transmit), f=100 (PNG), m=1 (more chunks follow) or m=0 (last chunk)- more := 1- if end >= len(encoded) {- more = 0- }- fmt.Printf("\033_Ga=T,f=100,m=%d;%s\033\\", more, chunk)- } else if end >= len(encoded) {- // Last chunk- fmt.Printf("\033_Gm=0;%s\033\\", chunk)- } else {- // Middle chunk- fmt.Printf("\033_Gm=1;%s\033\\", chunk)- }- }- fmt.Println()- return true-- default:- return false- }-}--// extractFileNames finds image file paths in the input string.-func extractFileNames(input string) []string {- // Regex to match file paths with image extensions- regexPattern := `(?:[a-zA-Z]:)?(?:\./|/|\\)[\S\\ ]+?\.(?i:jpg|jpeg|png|webp)\b`- re := regexp.MustCompile(regexPattern)- return re.FindAllString(input, -1)-}--// extractFileData extracts image data from file paths found in the input.-// Returns the cleaned prompt (with file paths removed) and the image data.-func extractFileData(input string) (string, []api.ImageData, error) {- filePaths := extractFileNames(input)- var imgs []api.ImageData-- for _, fp := range filePaths {- // Normalize shell escapes- nfp := strings.ReplaceAll(fp, "\\ ", " ")- nfp = strings.ReplaceAll(nfp, "\\(", "(")- nfp = strings.ReplaceAll(nfp, "\\)", ")")- nfp = strings.ReplaceAll(nfp, "%20", " ")-- data, err := getImageData(nfp)- if errors.Is(err, os.ErrNotExist) {- continue- } else if err != nil {- return "", nil, err- }- fmt.Fprintf(os.Stderr, "Added image '%s'\n", nfp)- input = strings.ReplaceAll(input, fp, "")- imgs = append(imgs, data)- }- return strings.TrimSpace(input), imgs, nil-}--// getImageData reads and validates image data from a file.-func getImageData(filePath string) ([]byte, error) {- file, err := os.Open(filePath)- if err != nil {- return nil, err- }- defer file.Close()-- buf := make([]byte, 512)- _, err = file.Read(buf)- if err != nil {- return nil, err- }-- contentType := http.DetectContentType(buf)- allowedTypes := []string{"image/jpeg", "image/jpg", "image/png", "image/webp"}- if !slices.Contains(allowedTypes, contentType) {- return nil, fmt.Errorf("invalid image type: %s", contentType)- }-- // Re-read the full file- return os.ReadFile(filePath)-}diff --git a/x/imagegen/cmd/engine/README.md b/x/imagegen/cmd/engine/README.mddeleted file mode 100644index e6ab2f5d3..000000000--- a/x/imagegen/cmd/engine/README.md+++ /dev/null@@ -1,25 +0,0 @@-# MLX Engine--Experimental MLX backend for running models on Apple Silicon and CUDA.--## Build--```bash-go build -o engine ./x/imagegen/cmd/engine-```--## Text Generation--Text generation models are no longer supported by this engine.--## Image Generation--```bash-./engine -zimage -model /path/to/z-image -prompt "a cat" -output cat.png-```--Options:--- `-width`, `-height` - image dimensions (default 1024x1024)-- `-steps` - denoising steps (default 9)-- `-seed` - random seed (default 42)diff --git a/x/imagegen/cmd/engine/generate.go b/x/imagegen/cmd/engine/generate.godeleted file mode 100644index 0f7f65345..000000000--- a/x/imagegen/cmd/engine/generate.go+++ /dev/null@@ -1,360 +0,0 @@-package main--import (- "context"- "fmt"- "time"- "unicode/utf8"-- "github.com/ollama/ollama/x/imagegen/cache"- "github.com/ollama/ollama/x/imagegen/mlx"- "github.com/ollama/ollama/x/imagegen/tokenizer"-)--// Dedicated stream for generation (like mlx-lm's generation_stream)-var generationStream *mlx.Stream--// utf8Streamer buffers decoded text and emits only complete UTF-8 characters.-// This handles cases where tokenizers output partial multi-byte sequences.-type utf8Streamer struct {- buffer []byte-}--// Write adds decoded text to the buffer and returns complete UTF-8 characters.-func (s *utf8Streamer) Write(text string) string {- s.buffer = append(s.buffer, text...)-- // Find the last position that ends with a complete UTF-8 character- validLen := 0- for i := 0; i < len(s.buffer); {- r, size := utf8.DecodeRune(s.buffer[i:])- if r == utf8.RuneError && size == 1 {- // Invalid or incomplete UTF-8 sequence at this position- // Check if it could be a valid start of a multi-byte sequence- if len(s.buffer)-i < 4 {- // Might be incomplete, keep it in buffer- break- }- // Definitely invalid, skip this byte- i++- validLen = i- } else {- i += size- validLen = i- }- }-- if validLen == 0 {- return ""- }-- result := string(s.buffer[:validLen])- s.buffer = s.buffer[validLen:]- return result-}--// Flush returns any remaining buffered bytes (may be incomplete UTF-8).-func (s *utf8Streamer) Flush() string {- if len(s.buffer) == 0 {- return ""- }- result := string(s.buffer)- s.buffer = nil- return result-}--// withStream runs fn with the generation stream as default-func withStream(fn func()) {- // Lazy initialization of generationStream- if generationStream == nil {- generationStream = mlx.NewStream()- }- orig := mlx.GetDefaultStream()- mlx.SetDefaultStream(generationStream)- fn()- mlx.SetDefaultStream(orig)-}--type Model interface {- Tokenizer() *tokenizer.Tokenizer- VocabSize() int32- NewCache(maxSeqLen int32) []cache.Cache- Forward(input *mlx.Array, caches []cache.Cache) *mlx.Array-}--// ChatModel is an optional interface for models that support chat formatting-type ChatModel interface {- FormatPrompt(prompt string) string-}--// MultimodalModel is for models that support image input-type MultimodalModel interface {- Model- FormatPromptWithImage(prompt string) string- ExpandImageTokens(tokens []int32) []int32- ForwardWithImage(tokens *mlx.Array, image *mlx.Array, caches []cache.Cache) *mlx.Array- ImageSize() int32 // Returns expected image size for preprocessing-}--// ImageLoader loads and preprocesses an image for multimodal models-// Returns nil if path is empty-type ImageLoader func(path string, imageSize int32) (*mlx.Array, error)--type input struct {- Prompt string- Image *mlx.Array // Optional preprocessed image for multimodal models- MaxTokens int- Temperature float32- TopP float32- TopK int- WiredLimitGB int // Metal wired memory limit in GB (default 32)-}--type output struct {- Text string- Done bool- PrefillTokSec float64- GenTokSec float64-}--// Decoder wraps model + cache for autoregressive generation.-type Decoder struct {- model Model- caches []cache.Cache- vocabSize int32- temp float32- topK int- topP float32- token *mlx.Array // Current token (kept across pools)- oldCacheState []*mlx.Array // Preallocated slice for old cache state- image *mlx.Array // Optional image for multimodal prefill-}--func NewDecoder(m Model, temp float32, topK int, topP float32) *Decoder {- caches := m.NewCache(0)- return &Decoder{- model: m,- caches: caches,- vocabSize: m.VocabSize(),- temp: temp,- topK: topK,- topP: topP,- oldCacheState: make([]*mlx.Array, 0, len(caches)*2),- }-}--// SetImage sets the image for multimodal prefill (call before prefill)-func (d *Decoder) SetImage(img *mlx.Array) {- d.image = img-}--func (d *Decoder) prefill(inputIDs []int32) int {- processed := 0-- // Track old cache state to free after each chunk- var oldCacheState []*mlx.Array-- // For multimodal models with an image, we need to process all tokens together- // in the first forward pass so the image embeddings can be inserted properly.- // Skip chunking for multimodal prefill.- isMultimodal := d.image != nil-- // Process all-but-1 tokens in chunks, eval cache state for memory management- // Skip chunking for multimodal - process everything in the final step- if !isMultimodal {- for len(inputIDs) > 1 {- chunkSize := min(2048, len(inputIDs)-1)- if chunkSize <= 0 {- break- }- chunk := inputIDs[:chunkSize]-- // Save old cache state before forward- oldCacheState = oldCacheState[:0]- for _, c := range d.caches {- oldCacheState = append(oldCacheState, c.State()...)- }-- var cacheState []*mlx.Array- withStream(func() {- x := mlx.NewArrayInt32(chunk, []int32{1, int32(len(chunk))})- d.model.Forward(x, d.caches)- for _, c := range d.caches {- cacheState = append(cacheState, c.State()...)- }- })- mlx.Eval(cacheState...)-- // Free old cache state- for _, arr := range oldCacheState {- if arr != nil {- arr.Free()- }- }-- inputIDs = inputIDs[chunkSize:]- processed += chunkSize- }- }-- // Save old cache state before final step- oldCacheState = oldCacheState[:0]- for _, c := range d.caches {- oldCacheState = append(oldCacheState, c.State()...)- }-- // Final token + sampling (or all tokens for multimodal)- withStream(func() {- x := mlx.NewArrayInt32(inputIDs, []int32{1, int32(len(inputIDs))})- mlx.Eval(x) // Materialize before any other evals-- var logits *mlx.Array- // Use ForwardWithImage if we have an image and model supports it- if d.image != nil {- if mm, ok := d.model.(MultimodalModel); ok {- logits = mm.ForwardWithImage(x, d.image, d.caches)- d.image = nil // Only use image for first forward- } else {- logits = d.model.Forward(x, d.caches)- }- } else {- logits = d.model.Forward(x, d.caches)- }- d.token = sample(logits, d.temp, d.topK, d.topP, d.vocabSize)- })- // Keep cache state (token auto-kept by AsyncEval)- for _, c := range d.caches {- mlx.Keep(c.State()...)- }- mlx.AsyncEval(d.token)-- // Free old cache state from before final step- for _, arr := range oldCacheState {- if arr != nil {- arr.Free()- }- }-- mlx.ClearCache()-- return processed + len(inputIDs)-}--func (d *Decoder) step() int32 {- prevToken := d.token-- // Save old cache state (reuse preallocated slice)- d.oldCacheState = d.oldCacheState[:0]- for _, c := range d.caches {- d.oldCacheState = append(d.oldCacheState, c.State()...)- }-- withStream(func() {- logits := d.model.Forward(mlx.Reshape(prevToken, 1, 1), d.caches)- d.token = sample(logits, d.temp, d.topK, d.topP, d.vocabSize)- })- // Keep token and new cache state so they survive cleanup- mlx.Keep(d.token)- for _, c := range d.caches {- mlx.Keep(c.State()...)- }- mlx.AsyncEval(d.token)-- // Sync on previous token (GPU already working on next step)- val := prevToken.ItemInt32()-- // Free old token and old cache state- prevToken.Free()- for _, arr := range d.oldCacheState {- arr.Free()- }- return val-}--func generate(ctx context.Context, m Model, in input, cb func(output)) error {- mlx.EnableCompile()- wiredLimit := in.WiredLimitGB- if wiredLimit <= 0 {- wiredLimit = 32 // default 32GB- }- mlx.MetalSetWiredLimit(uint64(wiredLimit) << 30)-- temp := in.Temperature- if temp < 0 {- temp = 0.7- }-- tok := m.Tokenizer()- dec := NewDecoder(m, temp, in.TopK, in.TopP)-- // Apply chat template - use image template if we have an image- prompt := in.Prompt- var tokens []int32- if mm, ok := m.(MultimodalModel); ok && in.Image != nil {- prompt = mm.FormatPromptWithImage(prompt)- tokens = tok.Encode(prompt, true)- tokens = mm.ExpandImageTokens(tokens) // Expand <start_of_image> to 256 image tokens- dec.SetImage(in.Image)- } else if cm, ok := m.(ChatModel); ok {- prompt = cm.FormatPrompt(prompt)- tokens = tok.Encode(prompt, true)- } else {- tokens = tok.Encode(prompt, true)- }-- prefillStart := time.Now()- prefillTokens := dec.prefill(tokens)- // Prefill measurement should include time to first token (like mlx-lm)- // Step() waits for prefill to complete and returns first token- firstToken := dec.step()- prefillTokSec := float64(prefillTokens) / time.Since(prefillStart).Seconds()-- genStart := time.Now()- maxTokens := max(in.MaxTokens, 100)- var genTokens int-- // UTF-8 streamer to handle partial multi-byte characters- streamer := &utf8Streamer{}-- // Handle first token- genTokens++- if tok.IsEOS(firstToken) {- cb(output{Done: true, PrefillTokSec: prefillTokSec, GenTokSec: 0})- return nil- }- if text := streamer.Write(tok.Decode([]int32{firstToken})); text != "" {- cb(output{Text: text})- }-- for n := 1; n < maxTokens; n++ {- if ctx.Err() != nil {- return ctx.Err()- }- token := dec.step()- genTokens++-- if tok.IsEOS(token) {- break- }- if text := streamer.Write(tok.Decode([]int32{token})); text != "" {- cb(output{Text: text})- }-- if n%256 == 0 {- mlx.ClearCache()- }- }-- // Flush any remaining buffered bytes- if text := streamer.Flush(); text != "" {- cb(output{Text: text})- }-- fmt.Printf("\nPeak memory: %.2fGB\n", float64(mlx.MetalGetPeakMemory())/(1<<30))- cb(output{- Done: true,- PrefillTokSec: prefillTokSec,- GenTokSec: float64(genTokens) / time.Since(genStart).Seconds(),- })- return nil-}diff --git a/x/imagegen/cmd/engine/image.go b/x/imagegen/cmd/engine/image.godeleted file mode 100644index 94f92fd9d..000000000--- a/x/imagegen/cmd/engine/image.go+++ /dev/null@@ -1,87 +0,0 @@-package main--import (- "fmt"- "image"- "image/png"- "os"- "path/filepath"-- "github.com/ollama/ollama/x/imagegen/mlx"-)--// saveImageArray saves an MLX array as a PNG image.-// Expected format: [B, C, H, W] with values in [0, 1] range and C=3 (RGB).-func saveImageArray(arr *mlx.Array, path string) error {- img, err := arrayToImage(arr)- if err != nil {- return err- }- return savePNG(img, path)-}--func savePNG(img *image.RGBA, path string) error {- if filepath.Ext(path) != ".png" {- path = path + ".png"- }- f, err := os.Create(path)- if err != nil {- return err- }- defer f.Close()- return png.Encode(f, img)-}--func arrayToImage(arr *mlx.Array) (*image.RGBA, error) {- shape := arr.Shape()- if len(shape) != 4 {- return nil, fmt.Errorf("expected 4D array [B, C, H, W], got %v", shape)- }-- // Transform to [H, W, C] for image conversion- img := mlx.Squeeze(arr, 0)- arr.Free()- img = mlx.Transpose(img, 1, 2, 0)- img = mlx.Contiguous(img)- mlx.Eval(img)-- imgShape := img.Shape()- H := int(imgShape[0])- W := int(imgShape[1])- C := int(imgShape[2])-- if C != 3 {- img.Free()- return nil, fmt.Errorf("expected 3 channels (RGB), got %d", C)- }-- // Copy to CPU and free GPU memory- data := img.Data()- img.Free()-- // Write directly to Pix slice (faster than SetRGBA)- goImg := image.NewRGBA(image.Rect(0, 0, W, H))- pix := goImg.Pix- for y := range H {- for x := range W {- srcIdx := (y*W + x) * C- dstIdx := (y*W + x) * 4- pix[dstIdx+0] = uint8(clampF(data[srcIdx+0]*255+0.5, 0, 255))- pix[dstIdx+1] = uint8(clampF(data[srcIdx+1]*255+0.5, 0, 255))- pix[dstIdx+2] = uint8(clampF(data[srcIdx+2]*255+0.5, 0, 255))- pix[dstIdx+3] = 255- }- }-- return goImg, nil-}--func clampF(v, min, max float32) float32 {- if v < min {- return min- }- if v > max {- return max- }- return v-}diff --git a/x/imagegen/cmd/engine/main.go b/x/imagegen/cmd/engine/main.godeleted file mode 100644index 712d5cea9..000000000--- a/x/imagegen/cmd/engine/main.go+++ /dev/null@@ -1,277 +0,0 @@-package main--import (- "context"- "encoding/json"- "flag"- "fmt"- "image"- _ "image/jpeg"- _ "image/png"- "log"- "os"- "path/filepath"- "runtime/pprof"-- "github.com/ollama/ollama/x/imagegen"- "github.com/ollama/ollama/x/imagegen/mlx"- "github.com/ollama/ollama/x/imagegen/models/flux2"- "github.com/ollama/ollama/x/imagegen/models/zimage"- "github.com/ollama/ollama/x/imagegen/safetensors"-)--// stringSlice is a flag type that accumulates multiple values-type stringSlice []string--func (s *stringSlice) String() string {- return fmt.Sprintf("%v", *s)-}--func (s *stringSlice) Set(value string) error {- *s = append(*s, value)- return nil-}--func main() {- modelPath := flag.String("model", "", "Model directory")- prompt := flag.String("prompt", "Hello", "Prompt")-- // Text generation params- maxTokens := flag.Int("max-tokens", 100, "Max tokens")- temperature := flag.Float64("temperature", 0.7, "Temperature")- topP := flag.Float64("top-p", 0.9, "Top-p sampling")- topK := flag.Int("top-k", 40, "Top-k sampling")- imagePath := flag.String("image", "", "Image path for multimodal models")-- // Image generation params- width := flag.Int("width", 0, "Image width (0 = auto from input or 1024)")- height := flag.Int("height", 0, "Image height (0 = auto from input or 1024)")- steps := flag.Int("steps", 0, "Denoising steps (0 = model default)")- seed := flag.Int64("seed", 42, "Random seed")- out := flag.String("output", "output.png", "Output path")-- // Utility flags- listTensors := flag.Bool("list", false, "List tensors only")- cpuProfile := flag.String("cpuprofile", "", "Write CPU profile to file")- gpuCapture := flag.String("gpu-capture", "", "Capture GPU trace to .gputrace file (run with MTL_CAPTURE_ENABLED=1)")- wiredLimitGB := flag.Int("wired-limit", 32, "Metal wired memory limit in GB")-- // Legacy mode flags- zimageFlag := flag.Bool("zimage", false, "Z-Image generation")- flux2Flag := flag.Bool("flux2", false, "FLUX.2 Klein generation")- var inputImages stringSlice- flag.Var(&inputImages, "input-image", "Input image for image editing (can be specified multiple times)")- negativePrompt := flag.String("negative-prompt", "", "Negative prompt for CFG (empty = no CFG, matching Python)")- cfgScale := flag.Float64("cfg-scale", 4.0, "CFG scale for image editing")- teaCache := flag.Bool("teacache", false, "Enable TeaCache for faster inference")- teaCacheThreshold := flag.Float64("teacache-threshold", 0.1, "TeaCache threshold (lower = more aggressive caching)")- fusedQKV := flag.Bool("fused-qkv", false, "Enable fused QKV projection for faster attention")-- flag.Parse()-- if *modelPath == "" {- flag.Usage()- return- }-- if err := mlx.InitMLX(); err != nil {- log.Fatalf("MLX initialization failed: %v", err)- }-- // Restore strict error handling now that we know MLX is working.- // During InitMLX(), a safe handler prevented exit(-1) on GPU errors.- mlx.RestoreDefaultErrorHandler()-- // CPU profiling- if *cpuProfile != "" {- f, err := os.Create(*cpuProfile)- if err != nil {- log.Fatal(err)- }- defer f.Close()- if err := pprof.StartCPUProfile(f); err != nil {- log.Fatal(err)- }- defer pprof.StopCPUProfile()- }-- var err error-- // Handle legacy mode flags that aren't unified yet- switch {- case *zimageFlag:- m := &zimage.Model{}- if loadErr := m.Load(*modelPath); loadErr != nil {- log.Fatal(loadErr)- }- var img *mlx.Array- img, err = m.GenerateFromConfig(context.Background(), &zimage.GenerateConfig{- Prompt: *prompt,- NegativePrompt: *negativePrompt,- CFGScale: float32(*cfgScale),- Width: int32(*width),- Height: int32(*height),- Steps: *steps,- Seed: *seed,- CapturePath: *gpuCapture,- TeaCache: *teaCache,- TeaCacheThreshold: float32(*teaCacheThreshold),- FusedQKV: *fusedQKV,- })- if err == nil {- err = saveImageArray(img, *out)- }- case *flux2Flag:- m := &flux2.Model{}- if loadErr := m.Load(*modelPath); loadErr != nil {- log.Fatal(loadErr)- }- // Load input images with EXIF orientation correction- var loadedImages []image.Image- for _, path := range inputImages {- img, loadErr := loadImageWithEXIF(path)- if loadErr != nil {- log.Fatalf("Failed to load image %s: %v", path, loadErr)- }- loadedImages = append(loadedImages, img)- }- // When input images provided and user didn't override dimensions, use 0 to match input- fluxWidth := int32(*width)- fluxHeight := int32(*height)- if len(loadedImages) > 0 && *width == 0 && *height == 0 {- // Both unset, will auto-detect from input- } else if len(loadedImages) > 0 && *width == 0 {- fluxWidth = 0 // Compute from height + aspect ratio- } else if len(loadedImages) > 0 && *height == 0 {- fluxHeight = 0 // Compute from width + aspect ratio- }- var img *mlx.Array- img, err = m.GenerateFromConfig(context.Background(), &flux2.GenerateConfig{- Prompt: *prompt,- Width: fluxWidth,- Height: fluxHeight,- Steps: *steps,- GuidanceScale: float32(*cfgScale),- Seed: *seed,- CapturePath: *gpuCapture,- InputImages: loadedImages,- })- if err == nil {- err = saveImageArray(img, *out)- }- case *listTensors:- err = listModelTensors(*modelPath)- default:- // llm path- m, err := load(*modelPath)- if err != nil {- log.Fatal(err)- }-- // Load image if provided and model supports it.- var image *mlx.Array- if *imagePath != "" {- if mm, ok := m.(interface{ ImageSize() int32 }); ok {- image, err = imagegen.ProcessImage(*imagePath, mm.ImageSize())- if err != nil {- log.Fatal("load image:", err)- }- } else {- log.Fatal("model does not support image input")- }- }-- if err := generate(context.Background(), m, input{- Prompt: *prompt,- Image: image,- MaxTokens: *maxTokens,- Temperature: float32(*temperature),- TopP: float32(*topP),- TopK: *topK,- WiredLimitGB: *wiredLimitGB,- }, func(out output) {- if out.Text != "" {- fmt.Print(out.Text)- }- if out.Done {- fmt.Printf("\n\n[prefill: %.1f tok/s, gen: %.1f tok/s]\n", out.PrefillTokSec, out.GenTokSec)- }- }); err != nil {- log.Fatal(err)- }- }-- if err != nil {- log.Fatal(err)- }-}--func listModelTensors(modelPath string) error {- weights, err := safetensors.LoadModelWeights(modelPath)- if err != nil {- return err- }- for _, name := range weights.ListTensors() {- info, _ := weights.GetTensorInfo(name)- fmt.Printf("%s: %v (%s)\n", name, info.Shape, info.Dtype)- }- return nil-}--func load(modelPath string) (Model, error) {- kind, err := detectModelKind(modelPath)- if err != nil {- return nil, fmt.Errorf("detect model kind: %w", err)- }-- switch kind {- default:- return nil, fmt.Errorf("model type %q is not supported by x/imagegen/cmd/engine", kind)- }-}--func detectModelKind(modelPath string) (string, error) {- indexPath := filepath.Join(modelPath, "model_index.json")- if _, err := os.Stat(indexPath); err == nil {- data, err := os.ReadFile(indexPath)- if err != nil {- return "", fmt.Errorf("read %s: %w", indexPath, err)- }- var index struct {- ClassName string `json:"_class_name"`- }- if err := json.Unmarshal(data, &index); err == nil {- switch index.ClassName {- case "FluxPipeline", "ZImagePipeline":- return "zimage", nil- case "Flux2KleinPipeline":- return "flux2", nil- }- }- return "zimage", nil- }-- configPath := filepath.Join(modelPath, "config.json")- data, err := os.ReadFile(configPath)- if err != nil {- return "", fmt.Errorf("no config.json or model_index.json found: %w", err)- }-- var cfg struct {- ModelType string `json:"model_type"`- }- if err := json.Unmarshal(data, &cfg); err != nil {- return "", fmt.Errorf("parse config.json: %w", err)- }-- return cfg.ModelType, nil-}--// loadImageWithEXIF loads an image from a file path with EXIF orientation correction.-func loadImageWithEXIF(path string) (image.Image, error) {- data, err := os.ReadFile(path)- if err != nil {- return nil, fmt.Errorf("read file: %w", err)- }- return imagegen.DecodeImage(data)-}diff --git a/x/imagegen/cmd/engine/sample.go b/x/imagegen/cmd/engine/sample.godeleted file mode 100644index 165c40774..000000000--- a/x/imagegen/cmd/engine/sample.go+++ /dev/null@@ -1,47 +0,0 @@-package main--import "github.com/ollama/ollama/x/imagegen/mlx"--// sampleTopK samples from top-k logits using global random state-func sampleTopK(scaledLogits *mlx.Array, k int) *mlx.Array {- neg := mlx.Neg(scaledLogits)- indices := mlx.Argpartition(neg, k-1, -1)- topKIdx := mlx.Slice(indices, []int32{0}, []int32{int32(k)})- values := mlx.TakeAlongAxis(scaledLogits, topKIdx, -1)- sampled := mlx.RandomCategorical(values, -1, 1)- return mlx.Take(topKIdx, sampled, -1)-}--// sampleTopP samples using nucleus sampling with global random state-func sampleTopP(scaledLogits *mlx.Array, p float32, vocabSize int32) *mlx.Array {- sorted := mlx.Argsort(mlx.Neg(scaledLogits), -1)- sortedLogits := mlx.TakeAlongAxis(scaledLogits, sorted, -1)- probs := mlx.Softmax(sortedLogits, -1)- cumProbs := mlx.Cumsum(probs, -1)- mask := mlx.LessScalar(cumProbs, p)- negInf := mlx.FullDtype(float32(-1e9), scaledLogits.Dtype(), vocabSize)- masked := mlx.Where(mask, sortedLogits, negInf)- sampled := mlx.RandomCategorical(masked, -1, 1)- return mlx.Take(sorted, sampled, -1)-}--// sample samples from logits at the last position-func sample(logits *mlx.Array, temp float32, topK int, topP float32, vocab int32) *mlx.Array {- // Get last position logits: [1, L, vocab] -> [vocab]- shape := logits.Shape()- seqLen := shape[1]- lastLogits := mlx.Slice(logits, []int32{0, seqLen - 1, 0}, []int32{1, seqLen, vocab})- lastLogits = mlx.Reshape(lastLogits, vocab)-- if temp == 0 {- return mlx.Argmax(lastLogits, -1, false)- }- scaled := mlx.DivScalar(lastLogits, temp)- if topK > 0 && topK < int(vocab) {- return sampleTopK(scaled, topK)- }- if topP > 0 && topP < 1.0 {- return sampleTopP(scaled, topP, vocab)- }- return mlx.RandomCategorical(scaled, -1, 1)-}diff --git a/x/imagegen/docs/blob-format.md b/x/imagegen/docs/blob-format.mddeleted file mode 100644index 768f1c2f9..000000000--- a/x/imagegen/docs/blob-format.md+++ /dev/null@@ -1,158 +0,0 @@-# Tensor Blob Format--Ollama stores model tensors as individual blobs in the safetensors format. Each blob contains a logical tensor (or a combined quantized tensor with its scale/bias components), or a group of logical tensors (e.g. shared experts for a given layer along with the scale/bias components for that tensor).--## Safetensors File Format--Every blob follows the [safetensors](https://github.com/huggingface/safetensors) layout:--```-[8 bytes: header_size (uint64 LE)] [header_size bytes: JSON header] [tensor data region]-```--The JSON header maps tensor names to their dtype, shape, and byte offsets within the data region. A special `__metadata__` key holds string-to-string metadata.--## Unquantized Blobs--An unquantized blob stores a single tensor keyed by its name:--```json-{- "model.layers.0.self_attn.q_proj.weight": {- "dtype": "BF16",- "shape": [2560, 2560],- "data_offsets": [0, 13107200]- }-}-```--The tensor key is the full tensor name. Dtype is typically `BF16` or `F32`.--## Quantized Blobs (Combined Format)--A quantized blob stores the packed weight, scaling factors, and optional zero-point biases in a single file. Tensor keys use the tensor name, with `.scale` and `.bias` suffixes for the auxiliary tensors:--```json-{- "__metadata__": {- "quant_type": "int4",- "group_size": "32"- },- "model.layers.0.mlp.up_proj.weight": {- "dtype": "U32",- "shape": [2560, 320],- "data_offsets": [0, 3276800]- },- "model.layers.0.mlp.up_proj.weight.scale": {- "dtype": "BF16",- "shape": [2560, 80],- "data_offsets": [3276800, 3686400]- },- "model.layers.0.mlp.up_proj.weight.bias": {- "dtype": "BF16",- "shape": [2560, 80],- "data_offsets": [3686400, 4096000]- }-}-```--### Metadata Fields--| Field | Description |-|---|---|-| `quant_type` | Quantization type: `int4`, `int8`, `nvfp4`, or `mxfp8` |-| `group_size` | Number of elements per quantization group (e.g., `32`, `64`) |--### Tensor Keys--| Key | Description |-|---|---|-| `{name}` | Packed quantized weights (dtype `U32`) |-| `{name}.scale` | Per-group scaling factors |-| `{name}.bias` | Per-group zero-point offsets (affine modes only) |--## Quantization Types--| Type | Bits | Group Size | Mode | Has Bias |-|---|---|---|---|---|-| `int4` | 4 | 32 | affine | yes |-| `int8` | 8 | 64 | affine | yes |-| `nvfp4` | 4 | 16 | nvfp4 | no |-| `mxfp8` | 8 | 32 | mxfp8 | no |--**Affine modes** (`int4`, `int8`) use `scale + bias` for dequantization. The bias tensor provides the zero-point offset.--**Non-affine modes** (`nvfp4`, `mxfp8`) use only `scale` with specialized E4M3 scale formats.--### Packed Weight Shape--Quantized weights are packed into `uint32` values:-- **4-bit** (int4, nvfp4): 8 values per uint32, so `packed_cols = original_cols / 8`-- **8-bit** (int8, mxfp8): 4 values per uint32, so `packed_cols = original_cols / 4`--Scale shape: `[rows, original_cols / group_size]`--## Manifest References--Blobs are referenced from the model manifest as layers:--```json-{- "mediaType": "application/vnd.ollama.image.tensor",- "digest": "sha256:abc123...",- "size": 4096150,- "name": "model.layers.0.mlp.up_proj.weight"-}-```--Each tensor (quantized or not) is one layer in the manifest. The layer name matches the tensor key in the blob header.--## Packed Blobs (Expert Groups)--For MoE (Mixture of Experts) models, expert tensors from the same layer are packed into a single blob to reduce blob count and improve loading efficiency. A packed blob is a standard safetensors file containing multiple tensor entries:--```json-{- "model.layers.1.mlp.experts.0.down_proj.weight": {- "dtype": "U32",- "shape": [2560, 640],- "data_offsets": [0, 6553600]- },- "model.layers.1.mlp.experts.0.down_proj.weight.scale": {- "dtype": "BF16",- "shape": [2560, 40],- "data_offsets": [6553600, 6963200]- },- "model.layers.1.mlp.experts.0.gate_proj.weight": {- "dtype": "U32",- "shape": [10240, 320],- "data_offsets": [6963200, 20070400]- },- "model.layers.1.mlp.experts.0.gate_proj.weight.scale": { "..." : "..." }-}-```--### Grouping Rules--- `model.layers.{L}.mlp.experts.*` tensors are packed into one blob per layer-- `model.layers.{L}.mlp.shared_experts.*` tensors are packed into one blob per layer-- All other tensors remain as individual blobs--### Manifest Representation--One manifest layer per packed group, using the group prefix as the layer name:--```json-{- "mediaType": "application/vnd.ollama.image.tensor",- "digest": "sha256:...",- "size": 123456789,- "name": "model.layers.1.mlp.experts"-}-```--## Loading--At load time, `mlx_load_safetensors` opens each blob via mmap for zero-copy access. For combined quantized blobs, the loader extracts `{name}`, `{name}.scale`, and `{name}.bias` tensors and caches them as `name`, `name + "_scale"`, and `name + "_qbias"` respectively, maintaining compatibility with the weight loading interface.--For packed blobs, if the manifest layer name (group prefix) is not found as a tensor key, the loader parses the blob header to discover all tensor names and loads each individually.diff --git a/x/imagegen/image.go b/x/imagegen/image.godeleted file mode 100644index ea419b821..000000000--- a/x/imagegen/image.go+++ /dev/null@@ -1,293 +0,0 @@-package imagegen--import (- "bytes"- "encoding/base64"- "fmt"- "image"- "image/color"- "image/draw"- _ "image/jpeg"- "image/png"- "os"- "path/filepath"-- "github.com/ollama/ollama/x/imagegen/mlx"-)--// SaveImage saves an MLX array as a PNG image file.-// Expected format: [B, C, H, W] with values in [0, 1] range and C=3 (RGB).-func SaveImage(arr *mlx.Array, path string) error {- img, err := ArrayToImage(arr)- if err != nil {- return err- }-- if filepath.Ext(path) != ".png" {- path = path + ".png"- }-- f, err := os.Create(path)- if err != nil {- return err- }- defer f.Close()-- return png.Encode(f, img)-}--// EncodeImageBase64 encodes an MLX array as a base64-encoded PNG.-// Expected format: [B, C, H, W] with values in [0, 1] range and C=3 (RGB).-func EncodeImageBase64(arr *mlx.Array) (string, error) {- img, err := ArrayToImage(arr)- if err != nil {- return "", err- }-- var buf bytes.Buffer- if err := png.Encode(&buf, img); err != nil {- return "", err- }-- return base64.StdEncoding.EncodeToString(buf.Bytes()), nil-}--// ArrayToImage converts an MLX array to a Go image.RGBA.-// Expected format: [B, C, H, W] with values in [0, 1] range and C=3 (RGB).-func ArrayToImage(arr *mlx.Array) (*image.RGBA, error) {- shape := arr.Shape()- if len(shape) != 4 {- return nil, fmt.Errorf("expected 4D array [B, C, H, W], got %v", shape)- }-- // Transform to [H, W, C] for image conversion- // Free intermediate arrays to avoid memory leak- squeezed := mlx.Squeeze(arr, 0)- transposed := mlx.Transpose(squeezed, 1, 2, 0)- squeezed.Free()- img := mlx.Contiguous(transposed)- transposed.Free()- mlx.Eval(img)-- imgShape := img.Shape()- H := int(imgShape[0])- W := int(imgShape[1])- C := int(imgShape[2])-- if C != 3 {- img.Free()- return nil, fmt.Errorf("expected 3 channels (RGB), got %d", C)- }-- // Copy to CPU and free GPU memory- data := img.Data()- img.Free()-- // Write directly to Pix slice (faster than SetRGBA)- goImg := image.NewRGBA(image.Rect(0, 0, W, H))- pix := goImg.Pix- for y := range H {- for x := range W {- srcIdx := (y*W + x) * C- dstIdx := (y*W + x) * 4- pix[dstIdx+0] = uint8(clampF(data[srcIdx+0]*255+0.5, 0, 255))- pix[dstIdx+1] = uint8(clampF(data[srcIdx+1]*255+0.5, 0, 255))- pix[dstIdx+2] = uint8(clampF(data[srcIdx+2]*255+0.5, 0, 255))- pix[dstIdx+3] = 255- }- }-- return goImg, nil-}--func clampF(v, min, max float32) float32 {- if v < min {- return min- }- if v > max {- return max- }- return v-}--// DecodeImage decodes image bytes with EXIF orientation applied.-// Transparent images are composited onto a white background.-func DecodeImage(data []byte) (image.Image, error) {- orientation := readJPEGOrientation(data)-- img, _, err := image.Decode(bytes.NewReader(data))- if err != nil {- return nil, err- }-- img = flattenAlpha(img)- return applyOrientation(img, orientation), nil-}--// flattenAlpha composites an image onto a white background,-// removing any transparency. This is needed because image-// generation models don't handle alpha channels well.-func flattenAlpha(img image.Image) image.Image {- if _, ok := img.(*image.RGBA); !ok {- if _, ok := img.(*image.NRGBA); !ok {- // No alpha channel, return as-is- return img- }- }-- bounds := img.Bounds()- dst := image.NewRGBA(bounds)-- // Fill with white background- draw.Draw(dst, bounds, &image.Uniform{color.White}, image.Point{}, draw.Src)-- // Composite the image on top- draw.Draw(dst, bounds, img, bounds.Min, draw.Over)-- return dst-}--// readJPEGOrientation extracts EXIF orientation from JPEG bytes.-// Returns 1 (normal) for non-JPEG or if orientation not found.-func readJPEGOrientation(data []byte) int {- if len(data) < 2 || data[0] != 0xFF || data[1] != 0xD8 {- return 1 // Not JPEG- }-- r := bytes.NewReader(data[2:])- for {- var marker [2]byte- if _, err := r.Read(marker[:]); err != nil || marker[0] != 0xFF {- return 1- }-- if marker[1] == 0xE1 { // APP1 (EXIF)- var lenBytes [2]byte- if _, err := r.Read(lenBytes[:]); err != nil {- return 1- }- segLen := int(uint16(lenBytes[0])<<8|uint16(lenBytes[1])) - 2- if segLen < 14 {- r.Seek(int64(segLen), 1)- continue- }- seg := make([]byte, segLen)- if _, err := r.Read(seg); err != nil {- return 1- }- if string(seg[:4]) == "Exif" && seg[4] == 0 && seg[5] == 0 {- return parseTIFFOrientation(seg[6:])- }- continue- }-- if marker[1] == 0xD9 || marker[1] == 0xDA {- return 1 // EOI or SOS- }- if marker[1] >= 0xD0 && marker[1] <= 0xD7 {- continue // RST markers- }-- var lenBytes [2]byte- if _, err := r.Read(lenBytes[:]); err != nil {- return 1- }- segLen := int(uint16(lenBytes[0])<<8|uint16(lenBytes[1])) - 2- if segLen > 0 {- r.Seek(int64(segLen), 1)- }- }-}--func parseTIFFOrientation(tiff []byte) int {- if len(tiff) < 8 {- return 1- }-- var big bool- switch string(tiff[:2]) {- case "MM":- big = true- case "II":- big = false- default:- return 1- }-- u16 := func(b []byte) uint16 {- if big {- return uint16(b[0])<<8 | uint16(b[1])- }- return uint16(b[1])<<8 | uint16(b[0])- }- u32 := func(b []byte) uint32 {- if big {- return uint32(b[0])<<24 | uint32(b[1])<<16 | uint32(b[2])<<8 | uint32(b[3])- }- return uint32(b[3])<<24 | uint32(b[2])<<16 | uint32(b[1])<<8 | uint32(b[0])- }-- if u16(tiff[2:4]) != 42 {- return 1- }-- ifdOffset := u32(tiff[4:8])- if int(ifdOffset)+2 > len(tiff) {- return 1- }-- numEntries := u16(tiff[ifdOffset : ifdOffset+2])- for i := range int(numEntries) {- offset := ifdOffset + 2 + uint32(i)*12- if int(offset)+12 > len(tiff) {- break- }- if u16(tiff[offset:offset+2]) == 0x0112 { // Orientation tag- o := int(u16(tiff[offset+8 : offset+10]))- if o >= 1 && o <= 8 {- return o- }- return 1- }- }- return 1-}--func applyOrientation(img image.Image, orientation int) image.Image {- if orientation <= 1 || orientation > 8 {- return img- }-- bounds := img.Bounds()- w, h := bounds.Dx(), bounds.Dy()-- outW, outH := w, h- if orientation >= 5 {- outW, outH = h, w- }-- out := image.NewRGBA(image.Rect(0, 0, outW, outH))- for y := range h {- for x := range w {- var dx, dy int- switch orientation {- case 2:- dx, dy = w-1-x, y- case 3:- dx, dy = w-1-x, h-1-y- case 4:- dx, dy = x, h-1-y- case 5:- dx, dy = y, x- case 6:- dx, dy = h-1-y, x- case 7:- dx, dy = h-1-y, w-1-x- case 8:- dx, dy = y, w-1-x- }- out.Set(dx, dy, img.At(x+bounds.Min.X, y+bounds.Min.Y))- }- }- return out-}diff --git a/x/imagegen/image_processor.go b/x/imagegen/image_processor.godeleted file mode 100644index 8e1dc72a9..000000000--- a/x/imagegen/image_processor.go+++ /dev/null@@ -1,56 +0,0 @@-package imagegen--import (- "fmt"- "image"- _ "image/jpeg"- _ "image/png"- "os"-- "github.com/ollama/ollama/x/imagegen/mlx"- "golang.org/x/image/draw"-)--// ProcessImage loads and preprocesses an image for multimodal vision towers.-// Returns [1, H, W, C] tensor in NHWC format normalized for SigLIP.-func ProcessImage(path string, imageSize int32) (*mlx.Array, error) {- f, err := os.Open(path)- if err != nil {- return nil, fmt.Errorf("open image: %w", err)- }- defer f.Close()-- img, _, err := image.Decode(f)- if err != nil {- return nil, fmt.Errorf("decode image: %w", err)- }-- return ProcessImageData(img, imageSize)-}--// ProcessImageData preprocesses an image.Image for multimodal vision towers.-func ProcessImageData(img image.Image, imageSize int32) (*mlx.Array, error) {- // Resize to target size using bilinear interpolation.- resized := image.NewRGBA(image.Rect(0, 0, int(imageSize), int(imageSize)))- draw.BiLinear.Scale(resized, resized.Bounds(), img, img.Bounds(), draw.Over, nil)-- // Convert to float32 array [H, W, C] and normalize.- // SigLIP normalization: (pixel / 255.0 - 0.5) / 0.5 = pixel / 127.5 - 1.0.- data := make([]float32, imageSize*imageSize*3)- idx := 0- for y := range imageSize {- for x := range imageSize {- r, g, b, _ := resized.At(int(x), int(y)).RGBA()- // RGBA returns 16-bit values, convert to 8-bit.- data[idx] = float32(r>>8)/127.5 - 1.0- data[idx+1] = float32(g>>8)/127.5 - 1.0- data[idx+2] = float32(b>>8)/127.5 - 1.0- idx += 3- }- }-- // Create MLX array [1, H, W, C] for NHWC layout.- arr := mlx.NewArrayFloat32(data, []int32{1, imageSize, imageSize, 3})- mlx.Eval(arr) // Materialize to prevent use-after-free.- return arr, nil-}diff --git a/x/imagegen/imagegen.go b/x/imagegen/imagegen.godeleted file mode 100644index c4b586505..000000000--- a/x/imagegen/imagegen.go+++ /dev/null@@ -1,132 +0,0 @@-package imagegen--import (- "context"- "encoding/json"- "fmt"- "log/slog"- "net/http"- "sync"- "time"-- "github.com/ollama/ollama/x/imagegen/manifest"- "github.com/ollama/ollama/x/imagegen/mlx"- "github.com/ollama/ollama/x/imagegen/models/flux2"- "github.com/ollama/ollama/x/imagegen/models/zimage"-)--// ImageModel is the interface for image generation models.-type ImageModel interface {- GenerateImage(ctx context.Context, prompt string, width, height int32, steps int, seed int64, progress func(step, total int)) (*mlx.Array, error)-}--var imageGenMu sync.Mutex--// loadImageModel loads an image generation model.-func (s *server) loadImageModel() error {- // Check memory requirements before loading- var requiredMemory uint64- if modelManifest, err := manifest.LoadManifest(s.modelName); err == nil {- requiredMemory = uint64(modelManifest.TotalTensorSize())- }- availableMemory := mlx.GetMemoryLimit()- if availableMemory > 0 && requiredMemory > 0 && availableMemory < requiredMemory {- return fmt.Errorf("insufficient memory for image generation: need %d GB, have %d GB",- requiredMemory/(1024*1024*1024), availableMemory/(1024*1024*1024))- }-- // Detect model type and load appropriate model- modelType := DetectModelType(s.modelName)- slog.Info("detected image model type", "type", modelType)-- var model ImageModel- switch modelType {- case "Flux2KleinPipeline":- m := &flux2.Model{}- if err := m.Load(s.modelName); err != nil {- return fmt.Errorf("failed to load flux2 model: %w", err)- }- model = m- default:- // Default to Z-Image for ZImagePipeline, FluxPipeline, etc.- m := &zimage.Model{}- if err := m.Load(s.modelName); err != nil {- return fmt.Errorf("failed to load zimage model: %w", err)- }- model = m- }-- s.imageModel = model- return nil-}--// handleImageCompletion handles image generation requests.-func (s *server) handleImageCompletion(w http.ResponseWriter, r *http.Request, req Request) {- // Serialize generation requests - MLX model may not handle concurrent generation- imageGenMu.Lock()- defer imageGenMu.Unlock()-- // Set seed if not provided- if req.Seed <= 0 {- req.Seed = time.Now().UnixNano()- }-- // Set up streaming response- w.Header().Set("Content-Type", "application/x-ndjson")- w.Header().Set("Transfer-Encoding", "chunked")- flusher, ok := w.(http.Flusher)- if !ok {- http.Error(w, "streaming not supported", http.StatusInternalServerError)- return- }-- ctx := r.Context()- enc := json.NewEncoder(w)-- // Progress callback streams step updates- progress := func(step, total int) {- resp := Response{Step: step, Total: total}- enc.Encode(resp)- w.Write([]byte("\n"))- flusher.Flush()- }-- // Generate image- img, err := s.imageModel.GenerateImage(ctx, req.Prompt, req.Width, req.Height, req.Steps, req.Seed, progress)- if err != nil {- // Don't send error for cancellation- if ctx.Err() != nil {- return- }- resp := Response{Content: fmt.Sprintf("error: %v", err), Done: true}- data, _ := json.Marshal(resp)- w.Write(data)- w.Write([]byte("\n"))- return- }-- // Encode image as base64 PNG- imageData, err := EncodeImageBase64(img)- if err != nil {- resp := Response{Content: fmt.Sprintf("error encoding: %v", err), Done: true}- data, _ := json.Marshal(resp)- w.Write(data)- w.Write([]byte("\n"))- return- }-- // Free the generated image array and clean up MLX state- img.Free()- mlx.ClearCache()- mlx.MetalResetPeakMemory()-- // Send final response with image data- resp := Response{- Image: imageData,- Done: true,- }- data, _ := json.Marshal(resp)- w.Write(data)- w.Write([]byte("\n"))- flusher.Flush()-}diff --git a/x/imagegen/manifest/weights.go b/x/imagegen/manifest/weights.godeleted file mode 100644index fcb30449e..000000000--- a/x/imagegen/manifest/weights.go+++ /dev/null@@ -1,296 +0,0 @@-package manifest--import (- "fmt"- "sort"- "strconv"- "strings"-- "github.com/ollama/ollama/x/imagegen/mlx"-)--// ManifestWeights provides fast weight loading from tensor blobs.-// Uses native mmap loading with synthetic safetensors headers for zero-copy.-type ManifestWeights struct {- manifest *ModelManifest- component string- tensors map[string]ManifestLayer // name -> layer- cache map[string]*mlx.Array // name -> loaded array- nativeCache []*mlx.SafetensorsFile // keep native handles alive- quantType string // quantization type from blob metadata (e.g., "int4", "int8")- groupSize int // quantization group size from blob metadata-}--// LoadWeightsFromManifest creates a weight loader from manifest storage.-// If component is empty, loads all tensors (for LLM models).-// If component is specified, loads only tensors for that component and strips the prefix.-func LoadWeightsFromManifest(manifest *ModelManifest, component string) (*ManifestWeights, error) {- layers := manifest.GetTensorLayers(component)- if len(layers) == 0 {- if component == "" {- return nil, fmt.Errorf("no tensor layers found in manifest")- }- return nil, fmt.Errorf("no tensor layers found for component %q", component)- }-- // Strip component prefix from tensor names for model loading- // e.g., "text_encoder/model.embed_tokens.weight" -> "model.embed_tokens.weight"- tensors := make(map[string]ManifestLayer, len(layers))- for _, layer := range layers {- if component == "" {- tensors[layer.Name] = layer- } else {- tensorName := strings.TrimPrefix(layer.Name, component+"/")- tensors[tensorName] = layer- }- }-- return &ManifestWeights{- manifest: manifest,- component: component,- tensors: tensors,- cache: make(map[string]*mlx.Array),- }, nil-}--// Load loads all tensor blobs using native mmap (zero-copy).-// Blobs are stored in safetensors format for native mlx_load_safetensors mmap.-// Combined quantized blobs contain tensors keyed by name, name+".scale", and optional name+".bias"-// with quantization metadata. Scale and bias are stored in cache as name+"_scale"-// and name+"_qbias" for compatibility with downstream loading code.-// Packed blobs (e.g., for expert groups) contain multiple tensors; the manifest name-// is a group prefix and individual tensors are loaded by their actual names from the blob.-// If dtype is non-zero, non-quantized tensors are converted to the specified dtype.-func (mw *ManifestWeights) Load(dtype mlx.Dtype) error {- // Track native handles to free after batch eval- nativeHandles := make([]*mlx.SafetensorsFile, 0, len(mw.tensors))- arrays := make([]*mlx.Array, 0, len(mw.tensors))-- // Group tensors by digest to avoid loading the same blob multiple times- type blobEntry struct {- name string- layer ManifestLayer- }- blobGroups := make(map[string][]blobEntry)- for name, layer := range mw.tensors {- blobGroups[layer.Digest] = append(blobGroups[layer.Digest], blobEntry{name, layer})- }-- for digest, entries := range blobGroups {- path := mw.manifest.BlobPath(digest)-- // Load blob as safetensors (native mmap, zero-copy)- sf, err := mlx.LoadSafetensorsNative(path)- if err != nil {- for _, h := range nativeHandles {- h.Free()- }- return fmt.Errorf("load %s: %w", entries[0].name, err)- }- nativeHandles = append(nativeHandles, sf)-- // Read quantization metadata from blob- if qt := sf.GetMetadata("quant_type"); qt != "" && mw.quantType == "" {- mw.quantType = qt- if gs := sf.GetMetadata("group_size"); gs != "" {- mw.groupSize, _ = strconv.Atoi(gs)- }- }-- for _, entry := range entries {- name := entry.name-- // Try to get tensor by stripped name first, then with component prefix,- // then fall back to "data" for legacy blobs created by older versions- // that stored all tensors with the generic key "data".- lookupName := name- arr := sf.Get(lookupName)- if arr == nil && mw.component != "" {- lookupName = mw.component + "/" + name- arr = sf.Get(lookupName)- }- if arr == nil {- // Legacy blob format: tensor stored as "data"- lookupName = "data"- arr = sf.Get(lookupName)- }- if arr != nil {- // Single-tensor blob or tensor found by name- if dtype != 0 && arr.Dtype() != dtype {- arr = mlx.AsType(arr, dtype)- }- arr = mlx.Contiguous(arr)- mw.cache[name] = arr- arrays = append(arrays, arr)-- // Check for scale tensor- if scale := sf.Get(lookupName + ".scale"); scale != nil {- scale = mlx.Contiguous(scale)- mw.cache[name+"_scale"] = scale- arrays = append(arrays, scale)- }-- // Check for bias tensor- if bias := sf.Get(lookupName + ".bias"); bias != nil {- bias = mlx.Contiguous(bias)- mw.cache[name+"_qbias"] = bias- arrays = append(arrays, bias)- }- } else {- // Packed blob: manifest name is a group prefix, not a tensor name.- // Load all individual tensors from the blob.- tensorNames, err := ParseBlobTensorNames(path)- if err != nil {- for _, h := range nativeHandles {- h.Free()- }- return fmt.Errorf("parse packed blob for %s: %w", name, err)- }-- for _, tensorName := range tensorNames {- tArr := sf.Get(tensorName)- if tArr == nil {- continue- }-- if dtype != 0 && tArr.Dtype() != dtype {- tArr = mlx.AsType(tArr, dtype)- }- tArr = mlx.Contiguous(tArr)-- // Strip component prefix from blob-internal names so cache keys- // match the stripped names used by LoadModule.- cacheName := tensorName- if mw.component != "" {- cacheName = strings.TrimPrefix(tensorName, mw.component+"/")- }- mw.cache[cacheName] = tArr- arrays = append(arrays, tArr)-- // Check for scale tensor- if scale := sf.Get(tensorName + ".scale"); scale != nil {- scale = mlx.Contiguous(scale)- mw.cache[cacheName+"_scale"] = scale- arrays = append(arrays, scale)- }-- // Check for bias tensor- if bias := sf.Get(tensorName + ".bias"); bias != nil {- bias = mlx.Contiguous(bias)- mw.cache[cacheName+"_qbias"] = bias- arrays = append(arrays, bias)- }- }- }- }- }-- // Batch evaluate all tensors at once (much faster than one at a time)- mlx.Eval(arrays...)-- // Now safe to free all native handles- for _, sf := range nativeHandles {- sf.Free()- }-- return nil-}--// GetTensor returns a tensor from cache. Call Load() first.-func (mw *ManifestWeights) GetTensor(name string) (*mlx.Array, error) {- if mw.cache == nil {- return nil, fmt.Errorf("cache not initialized: call Load() first")- }- arr, ok := mw.cache[name]- if !ok {- return nil, fmt.Errorf("tensor %q not found", name)- }- return arr, nil-}--// ListTensors returns all tensor names in sorted order.-// Includes both manifest tensor names and scale/bias entries from combined blobs.-func (mw *ManifestWeights) ListTensors() []string {- seen := make(map[string]bool, len(mw.tensors)+len(mw.cache))- for name := range mw.tensors {- seen[name] = true- }- // Also include cache entries (scale/bias from combined blobs)- for name := range mw.cache {- seen[name] = true- }- names := make([]string, 0, len(seen))- for name := range seen {- names = append(names, name)- }- sort.Strings(names)- return names-}--// HasTensor checks if a tensor exists in the manifest or cache.-func (mw *ManifestWeights) HasTensor(name string) bool {- if _, ok := mw.tensors[name]; ok {- return true- }- // Also check cache for scale/bias entries from combined blobs- if _, ok := mw.cache[name]; ok {- return true- }- return false-}--// Quantization returns the model's quantization type.-// Returns the quant_type from blob metadata (e.g., "int4", "int8", "nvfp4", "mxfp8").-// Returns empty string if not quantized.-// Falls back to model_index.json for image gen models.-func (mw *ManifestWeights) Quantization() string {- if mw.quantType != "" {- return strings.ToUpper(mw.quantType)- }-- if mw.manifest == nil {- return ""- }-- // Fallback: read from model_index.json (for image gen models)- var index struct {- Quantization string `json:"quantization"`- }- if err := mw.manifest.ReadConfigJSON("model_index.json", &index); err == nil && index.Quantization != "" {- return index.Quantization- }-- return ""-}--// GroupSize returns the quantization group size.-// Returns the group_size from blob metadata.-// Returns 0 if not specified (caller should use default based on quantization type).-func (mw *ManifestWeights) GroupSize() int {- if mw.groupSize > 0 {- return mw.groupSize- }-- if mw.manifest == nil {- return 0- }-- // Fallback: read from model_index.json (for image gen models)- var index struct {- GroupSize int `json:"group_size"`- }- if err := mw.manifest.ReadConfigJSON("model_index.json", &index); err == nil && index.GroupSize > 0 {- return index.GroupSize- }-- return 0-}--// ReleaseAll frees all native handles and clears the tensor cache.-func (mw *ManifestWeights) ReleaseAll() {- for _, sf := range mw.nativeCache {- sf.Free()- }- mw.nativeCache = nil- mw.cache = nil-}diff --git a/x/imagegen/memory.go b/x/imagegen/memory.godeleted file mode 100644index 39a428c69..000000000--- a/x/imagegen/memory.go+++ /dev/null@@ -1,80 +0,0 @@-// Package imagegen provides experimental image generation capabilities for Ollama.-//-// This package is in x/ because the tensor model storage format is under development.-// The goal is to integrate these capabilities into the main Ollama packages once-// the format is stable.-//-// TODO (jmorganca): Integrate into main packages when stable:-// - CLI commands → cmd/-// - API endpoints → api/-// - Model creation → server/-package imagegen--import (- "encoding/json"- "fmt"- "runtime"-- "github.com/ollama/ollama/x/imagegen/manifest"-)--// SupportedBackends lists the backends that support image generation.-var SupportedBackends = []string{"metal", "cuda", "cpu"}--// CheckPlatformSupport validates that image generation is supported on the current platform.-// Returns nil if supported, or an error describing why it's not supported.-func CheckPlatformSupport() error {- switch runtime.GOOS {- case "darwin":- // macOS: Metal is supported via MLX- if runtime.GOARCH != "arm64" {- return fmt.Errorf("image generation on macOS requires Apple Silicon (arm64), got %s", runtime.GOARCH)- }- return nil- case "linux", "windows":- // Linux/Windows: CUDA support (requires mlx or cuda build)- // The actual backend availability is checked at runtime- return nil- default:- return fmt.Errorf("image generation is not supported on %s", runtime.GOOS)- }-}--// ResolveModelName checks if a model name is a known image generation model.-// Returns the normalized model name if found, empty string otherwise.-func ResolveModelName(modelName string) string {- modelManifest, err := manifest.LoadManifest(modelName)- if err == nil && modelManifest.HasTensorLayers() {- return modelName- }- return ""-}--// DetectModelType reads model_index.json and returns the model type.-// Checks both "architecture" (Ollama format) and "_class_name" (diffusers format).-// Returns empty string if detection fails.-func DetectModelType(modelName string) string {- modelManifest, err := manifest.LoadManifest(modelName)- if err != nil {- return ""- }-- data, err := modelManifest.ReadConfig("model_index.json")- if err != nil {- return ""- }-- var index struct {- Architecture string `json:"architecture"`- ClassName string `json:"_class_name"`- }- if err := json.Unmarshal(data, &index); err != nil {- return ""- }-- // Prefer architecture (Ollama format), fall back to _class_name (diffusers)- if index.Architecture != "" {- return index.Architecture- }- return index.ClassName-}diff --git a/x/imagegen/memory_test.go b/x/imagegen/memory_test.godeleted file mode 100644index 531cffda2..000000000--- a/x/imagegen/memory_test.go+++ /dev/null@@ -1,39 +0,0 @@-package imagegen--import (- "runtime"- "testing"-)--func TestCheckPlatformSupport(t *testing.T) {- err := CheckPlatformSupport()-- switch runtime.GOOS {- case "darwin":- if runtime.GOARCH == "arm64" {- if err != nil {- t.Errorf("Expected nil error on darwin/arm64, got: %v", err)- }- } else {- if err == nil {- t.Error("Expected error on darwin/non-arm64")- }- }- case "linux", "windows":- if err != nil {- t.Errorf("Expected nil error on %s, got: %v", runtime.GOOS, err)- }- default:- if err == nil {- t.Errorf("Expected error on unsupported platform %s", runtime.GOOS)- }- }-}--func TestResolveModelName(t *testing.T) {- // Non-existent model should return empty string- result := ResolveModelName("nonexistent-model")- if result != "" {- t.Errorf("ResolveModelName() = %q, want empty string", result)- }-}diff --git a/x/imagegen/mlx/CMakeLists.txt b/x/imagegen/mlx/CMakeLists.txtdeleted file mode 100644index 78e57548c..000000000--- a/x/imagegen/mlx/CMakeLists.txt+++ /dev/null@@ -1,219 +0,0 @@-include(FetchContent)--if(NOT DEFINED OLLAMA_SOURCE_DIR OR "${OLLAMA_SOURCE_DIR}" STREQUAL "")- set(OLLAMA_SOURCE_DIR "${CMAKE_SOURCE_DIR}" CACHE PATH "Ollama repository root")-endif()-get_filename_component(OLLAMA_SOURCE_DIR "${OLLAMA_SOURCE_DIR}" ABSOLUTE BASE_DIR "${CMAKE_SOURCE_DIR}")--# Read MLX-C version from top-level file (shared with Dockerfile)-file(READ "${OLLAMA_SOURCE_DIR}/MLX_C_VERSION" MLX_C_GIT_TAG)-string(STRIP "${MLX_C_GIT_TAG}" MLX_C_GIT_TAG)--# Read MLX version from top-level file-file(READ "${OLLAMA_SOURCE_DIR}/MLX_VERSION" MLX_GIT_TAG)-string(STRIP "${MLX_GIT_TAG}" MLX_GIT_TAG)--set(MLX_C_BUILD_EXAMPLES OFF)--set(MLX_BUILD_GGUF OFF)-set(MLX_BUILD_SAFETENSORS ON)-option(OLLAMA_MLX_GENERATE_WRAPPERS "Regenerate MLX Go wrappers" ON)--function(set_target_output_directory _target)- if(TARGET ${_target})- set_target_properties(${_target} PROPERTIES- RUNTIME_OUTPUT_DIRECTORY ${OLLAMA_BUILD_DIR}- LIBRARY_OUTPUT_DIRECTORY ${OLLAMA_BUILD_DIR}- ARCHIVE_OUTPUT_DIRECTORY ${OLLAMA_BUILD_DIR}- )- endif()-endfunction()--# Check for Metal support (macOS only)-if(CMAKE_SYSTEM_NAME MATCHES "Darwin")- find_program(XCRUN_EXECUTABLE xcrun)- if(NOT XCRUN_EXECUTABLE)- message(FATAL_ERROR- "MLX Metal requires Xcode command line tools. Install Xcode, run "- "`sudo xcode-select -s /Applications/Xcode.app/Contents/Developer`, "- "then install the Metal toolchain with "- "`xcodebuild -downloadComponent MetalToolchain`.")- endif()-- execute_process(- COMMAND- zsh "-c"- "echo \"__METAL_VERSION__\" | \"${XCRUN_EXECUTABLE}\" -sdk macosx metal ${XCRUN_FLAGS} -E -x metal -P - 2>/dev/null | tail -1 | tr -d '\n'"- OUTPUT_VARIABLE MLX_METAL_VERSION- RESULT_VARIABLE MLX_METAL_RESULT)-- if(NOT MLX_METAL_RESULT EQUAL 0 OR NOT MLX_METAL_VERSION MATCHES "^[0-9]+$")- message(FATAL_ERROR- "MLX Metal requires Xcode's Metal toolchain. Install Xcode, run "- "`sudo xcode-select -s /Applications/Xcode.app/Contents/Developer`, "- "then install the Metal toolchain with "- "`xcodebuild -downloadComponent MetalToolchain`.")- endif()-else()- # On Linux, disable Metal backend- message(STATUS "Non-macOS platform detected. Setting MLX_BUILD_METAL=OFF")- set(MLX_BUILD_METAL OFF)-endif()--# Map CMAKE_CUDA_ARCHITECTURES to MLX_CUDA_ARCHITECTURES if not explicitly set-if(NOT MLX_CUDA_ARCHITECTURES AND CMAKE_CUDA_ARCHITECTURES)- set(MLX_CUDA_ARCHITECTURES ${CMAKE_CUDA_ARCHITECTURES})- message(STATUS "Using CMAKE_CUDA_ARCHITECTURES for MLX: ${MLX_CUDA_ARCHITECTURES}")-endif()--# Forward cuDNN environment variables to cmake variables so MLX's FindCUDNN.cmake-# can find them via HINTS ${CUDNN_INCLUDE_PATH} / ${CUDNN_LIBRARY_PATH}.-if(DEFINED ENV{CUDNN_INCLUDE_PATH} AND NOT CUDNN_INCLUDE_PATH)- set(CUDNN_INCLUDE_PATH "$ENV{CUDNN_INCLUDE_PATH}" CACHE PATH "cuDNN include path")- message(STATUS "Using CUDNN_INCLUDE_PATH from environment: ${CUDNN_INCLUDE_PATH}")-endif()-if(DEFINED ENV{CUDNN_LIBRARY_PATH} AND NOT CUDNN_LIBRARY_PATH)- set(CUDNN_LIBRARY_PATH "$ENV{CUDNN_LIBRARY_PATH}" CACHE PATH "cuDNN library path")- message(STATUS "Using CUDNN_LIBRARY_PATH from environment: ${CUDNN_LIBRARY_PATH}")-endif()--# Enable CUDA backend if CUDA architectures are specified and CUDA compiler is available-if(MLX_CUDA_ARCHITECTURES AND CMAKE_CUDA_COMPILER)- set(MLX_BUILD_CUDA ON CACHE BOOL "Build CUDA backend for MLX" FORCE)- message(STATUS "Enabling MLX CUDA backend with architectures: ${MLX_CUDA_ARCHITECTURES}")-elseif(MLX_CUDA_ARCHITECTURES)- message(WARNING "MLX_CUDA_ARCHITECTURES specified but CUDA compiler not found, CUDA backend will be disabled")-endif()--# Allow local source overrides via environment variables-# Resolve to absolute paths so FetchContent doesn't break on relative dirs.-if(DEFINED ENV{OLLAMA_MLX_SOURCE})- get_filename_component(_mlx_src "$ENV{OLLAMA_MLX_SOURCE}" ABSOLUTE BASE_DIR "${OLLAMA_SOURCE_DIR}")- set(FETCHCONTENT_SOURCE_DIR_MLX "${_mlx_src}" CACHE PATH "" FORCE)- message(STATUS "Using local MLX source: ${_mlx_src}")-endif()-if(DEFINED ENV{OLLAMA_MLX_C_SOURCE})- get_filename_component(_mlx_c_src "$ENV{OLLAMA_MLX_C_SOURCE}" ABSOLUTE BASE_DIR "${OLLAMA_SOURCE_DIR}")- set(FETCHCONTENT_SOURCE_DIR_MLX-C "${_mlx_c_src}" CACHE PATH "" FORCE)- message(STATUS "Using local MLX-C source: ${_mlx_c_src}")-endif()--# Pre-declare mlx so our pinned version takes precedence over the one-# hardcoded in mlx-c's CMakeLists.txt (first FetchContent_Declare wins).-FetchContent_Declare(- mlx- GIT_REPOSITORY "https://github.com/ml-explore/mlx.git"- GIT_TAG ${MLX_GIT_TAG}-)--FetchContent_Declare(- mlx-c- GIT_REPOSITORY "https://github.com/ml-explore/mlx-c.git"- GIT_TAG ${MLX_C_GIT_TAG}-)-FetchContent_MakeAvailable(mlx-c)--# To avoid a "long tail" when building MLX with a large set of GPU-# architectures, utilize a higher --threads (-t) setting. At high -t-# every .cu spawns concurrent cicc instances; each cicc can consume several GB-# compiling MLX's CUTLASS-using kernels. This in turn can cause OOMs.-#-# We use a pool to cover all MLX CUDA sources. Pool size is derived from total-# host RAM via a per-file memory budget.-#-# This was calibrated with `-t 6`. Higher -t may require overriding-# MLX_CUDA_RAM_MB-if(CMAKE_GENERATOR STREQUAL "Ninja")- file(GLOB_RECURSE _mlx_cu- "${mlx_SOURCE_DIR}/mlx/backend/cuda/*.cu"- "${mlx_BINARY_DIR}/mlx/backend/cuda/*.cu"- )- if(_mlx_cu)- set(MLX_CUDA_RAM_MB 22000 CACHE STRING- "Per-file memory budget (MB) for the cuda_compile JOB_POOL. Override for higher -t.")- cmake_host_system_information(RESULT _ram_mb QUERY TOTAL_PHYSICAL_MEMORY)- math(EXPR _cuda_pool "${_ram_mb} / ${MLX_CUDA_RAM_MB}")- if(_cuda_pool LESS 2)- set(_cuda_pool 2)- endif()- set_property(GLOBAL APPEND PROPERTY JOB_POOLS cuda_compile=${_cuda_pool})- list(LENGTH _mlx_cu _cu_count)- # SOURCE properties default to directory-scoped, which means a plain- # set_property(SOURCE ...) here would NOT affect the build rules- # generated for the mlx target (defined in mlx_SOURCE_DIR after- # FetchContent). TARGET_DIRECTORY mlx puts the property in the- # directory where mlx was defined, so it actually applies.- foreach(f ${_mlx_cu})- set_property(SOURCE "${f}"- TARGET_DIRECTORY mlx- PROPERTY JOB_POOL_COMPILE cuda_compile)- endforeach()- message(STATUS "MLX cuda_compile JOB_POOL: ${_cu_count} files, pool size ${_cuda_pool} (host RAM ${_ram_mb} MB / ${MLX_CUDA_RAM_MB} MB per file)")- else()- message(WARNING "MLX cuda_compile JOB_POOL: no .cu files found under mlx/backend/cuda/ - check MLX layout")- endif()-endif()--# Sync vendored headers with fetched version.-if(OLLAMA_MLX_GENERATE_WRAPPERS)- file(GLOB _mlx_c_hdrs "${mlx-c_SOURCE_DIR}/mlx/c/*.h")- file(COPY ${_mlx_c_hdrs} DESTINATION "${OLLAMA_SOURCE_DIR}/x/mlxrunner/mlx/include/mlx/c/")-endif()--# Regenerate Go/C shim wrappers from the (possibly updated) headers.-# Skip during cross-compilation — the generated files are arch-independent.-if(OLLAMA_MLX_GENERATE_WRAPPERS AND (CMAKE_SYSTEM_PROCESSOR STREQUAL CMAKE_HOST_SYSTEM_PROCESSOR OR NOT APPLE))- find_program(GO_EXECUTABLE go REQUIRED)- message(STATUS "Regenerating MLX Go wrappers")-- # CGo's probe compilation is sensitive to CGO_CFLAGS/CGO_CXXFLAGS and CC.- # Clear them so go generate uses default compiler settings:- # - On Windows, CC may contain spaces (e.g., "C:/Program Files/.../cl.exe")- # which breaks CGo's CC parsing.- # - On macOS, CGO_CFLAGS with -mmacosx-version-min breaks header search- # when cmake also sets CMAKE_OSX_DEPLOYMENT_TARGET.- set(_SAVE_CC "$ENV{CC}")- set(_SAVE_CGO_CFLAGS "$ENV{CGO_CFLAGS}")- set(_SAVE_CGO_CXXFLAGS "$ENV{CGO_CXXFLAGS}")- set(ENV{CC} "")- set(ENV{CGO_CFLAGS} "")- set(ENV{CGO_CXXFLAGS} "")-- execute_process(- COMMAND ${GO_EXECUTABLE} generate ./x/...- WORKING_DIRECTORY ${OLLAMA_SOURCE_DIR}- COMMAND_ERROR_IS_FATAL ANY- )-- set(ENV{CC} "${_SAVE_CC}")- set(ENV{CGO_CFLAGS} "${_SAVE_CGO_CFLAGS}")- set(ENV{CGO_CXXFLAGS} "${_SAVE_CGO_CXXFLAGS}")-elseif(NOT OLLAMA_MLX_GENERATE_WRAPPERS)- message(STATUS "Skipping MLX Go wrapper generation")-else()- message(STATUS "Skipping MLX Go wrapper generation (cross-compiling)")-endif()--# For local dev builds, override MLX_VERSION with git describe output-if(TARGET mlx_version AND DEFINED FETCHCONTENT_SOURCE_DIR_MLX)- execute_process(- COMMAND git describe --tags --first-parent --abbrev=7 --long --dirty --always- WORKING_DIRECTORY ${mlx_SOURCE_DIR}- OUTPUT_VARIABLE _mlx_git_version- OUTPUT_STRIP_TRAILING_WHITESPACE- ERROR_QUIET- RESULT_VARIABLE _mlx_git_result- )- if(_mlx_git_result EQUAL 0 AND _mlx_git_version)- # Strip leading "v" prefix for consistency- string(REGEX REPLACE "^v" "" _mlx_git_version "${_mlx_git_version}")- get_target_property(_mlx_defs mlx_version COMPILE_DEFINITIONS)- list(FILTER _mlx_defs EXCLUDE REGEX "^MLX_VERSION=")- set_target_properties(mlx_version PROPERTIES COMPILE_DEFINITIONS "${_mlx_defs}")- target_compile_definitions(mlx_version PRIVATE "MLX_VERSION=\"${_mlx_git_version}\"")- message(STATUS "MLX version (local dev): ${_mlx_git_version}")- endif()-endif()--set_target_output_directory(mlx)-set_target_output_directory(mlxc)diff --git a/x/imagegen/mlx/README.md b/x/imagegen/mlx/README.mddeleted file mode 100644index 3a2f7b3d8..000000000--- a/x/imagegen/mlx/README.md+++ /dev/null@@ -1,46 +0,0 @@-# MLX Memory Management--| This package will get consolidated with `x/ml/backend/mlx` in the future.--## Automatic Tracking--All arrays are automatically tracked when created. On `Eval()`, non-kept arrays are freed.--### API--```go-result := mlx.Matmul(x, w) // arrays automatically tracked-mlx.Eval(result) // free non-kept, eval result (auto-kept)-```--### Key Functions--- `mlx.Eval(outputs...)` - free non-kept arrays, then evaluate (outputs auto-kept)-- `mlx.AsyncEval(outputs...)` - async version of Eval (outputs auto-kept)-- `mlx.Keep(arrays...)` - mark arrays to survive cleanup (for weights, caches)-- `array.Free()` - mark array for cleanup on next Eval--### Loop Pattern--```go-for step := 0; step < maxTokens; step++ {- logits := model.Forward(token, caches)- oldToken := token- token = sample(logits)-- // Keep cache state across iterations- for _, c := range caches {- mlx.Keep(c.State()...)- }-- oldToken.Free() // mark for cleanup- mlx.AsyncEval(token) // frees old, evals new-}-```--### Notes--- `Eval()` and `AsyncEval()` auto-keep their outputs-- `Free()` marks for cleanup - actual free happens during next Eval-- Use `Keep()` for weights and cache state that must survive multiple Eval cycles-- Arrays created inside compiled closures are managed by MLX, not trackeddiff --git a/x/imagegen/mlx/compile.go b/x/imagegen/mlx/compile.godeleted file mode 100644index e152c3054..000000000--- a/x/imagegen/mlx/compile.go+++ /dev/null@@ -1,203 +0,0 @@-package mlx--/*-#include "mlx.h"-#include <stdlib.h>--// Forward declaration for Go callback-extern int goClosureCallback(mlx_vector_array* res, mlx_vector_array input, void* payload);--// Destructor for payload (Go handle)-extern void goClosureDestructor(void* payload);-*/-import "C"--import (- "log/slog"- "runtime/cgo"- "sync"- "unsafe"-)--// inClosureCallback is set to true during closure callback execution.-var (- inClosureCallback bool- closureScratch []*Array- closureCallbackMu sync.Mutex-)--// InClosureCallback returns true if we're currently executing inside a closure callback.-func InClosureCallback() bool {- closureCallbackMu.Lock()- defer closureCallbackMu.Unlock()- return inClosureCallback-}--func trackClosureArray(a *Array) {- closureCallbackMu.Lock()- defer closureCallbackMu.Unlock()- if inClosureCallback {- closureScratch = append(closureScratch, a)- }-}--// CompiledFunc is a compiled MLX function that can be called efficiently.-// All intermediate arrays during execution stay inside MLX - only inputs-// and outputs cross the Go boundary.-type CompiledFunc struct {- closure C.mlx_closure- compiled C.mlx_closure-}--// ClosureFunc is the signature for functions that can be compiled.-// It takes a slice of input arrays and returns a slice of output arrays.-type ClosureFunc func(inputs []*Array) []*Array--// Compile compiles a Go function into an optimized MLX closure.-// The function is traced once during compilation, then subsequent calls-// run the optimized graph without creating Go intermediate arrays.-//-// Example:-//-// compiled := mlx.Compile(func(inputs []*mlx.Array) []*mlx.Array {-// a, b := inputs[0], inputs[1]-// c := mlx.Add(a, b)-// d := mlx.Mul(c, c)-// return []*mlx.Array{d}-// })-// defer compiled.Free()-//-// result := compiled.Call(x, y)[0]-func Compile(fn ClosureFunc) *CompiledFunc {- return CompileShapeless(fn, false)-}--// CompileShapeless compiles with optional shapeless mode.-// If shapeless=true, the function works for any input shape after tracing.-func CompileShapeless(fn ClosureFunc, shapeless bool) *CompiledFunc {- // Create a cgo.Handle to prevent the Go function from being GC'd- handle := cgo.NewHandle(fn)-- // Create the closure from the Go callback- closure := C.mlx_closure_new_func_payload(- (*[0]byte)(C.goClosureCallback),- unsafe.Pointer(handle), //nolint:govet // cgo.Handle is passed back unchanged as an MLX C callback payload.- (*[0]byte)(C.goClosureDestructor),- )-- // Compile the closure- compiled := C.mlx_closure_new()- C.mlx_compile(&compiled, closure, C.bool(shapeless))-- return &CompiledFunc{- closure: closure,- compiled: compiled,- }-}--// Call invokes the compiled function with the given inputs.-func (cf *CompiledFunc) Call(inputs ...*Array) []*Array {- // Pack inputs into vector- inputVec := C.mlx_vector_array_new()- for _, arr := range inputs {- C.mlx_vector_array_append_value(inputVec, arr.c)- }-- // Apply compiled closure- outputVec := C.mlx_vector_array_new()- C.mlx_closure_apply(&outputVec, cf.compiled, inputVec)- C.mlx_vector_array_free(inputVec)-- // Unpack outputs- numOutputs := int(C.mlx_vector_array_size(outputVec))- outputs := make([]*Array, numOutputs)- for i := range numOutputs {- var arr C.mlx_array- C.mlx_vector_array_get(&arr, outputVec, C.size_t(i))- outputs[i] = newArray(arr)- }- C.mlx_vector_array_free(outputVec)-- return outputs-}--// CallEval invokes the compiled function and evaluates the results.-func (cf *CompiledFunc) CallEval(inputs ...*Array) []*Array {- outputs := cf.Call(inputs...)- Eval(outputs...)- return outputs-}--// Free releases the compiled function resources.-func (cf *CompiledFunc) Free() {- C.mlx_closure_free(cf.compiled)- C.mlx_closure_free(cf.closure)-}--// borrowArray wraps a C array WITHOUT setting up GC cleanup.-// Use this for arrays we don't own (e.g., borrowed references in callbacks).-func borrowArray(array C.mlx_array) *Array {- return &Array{c: array}-}--//export goClosureCallback-func goClosureCallback(res *C.mlx_vector_array, input C.mlx_vector_array, payload unsafe.Pointer) (rc C.int) {- defer func() {- if r := recover(); r != nil {- slog.Error("mlx closure callback panicked", "panic", r)- rc = 1- }- }()-- closureCallbackMu.Lock()- inClosureCallback = true- closureScratch = nil- closureCallbackMu.Unlock()- defer func() {- closureCallbackMu.Lock()- scratch := closureScratch- closureScratch = nil- inClosureCallback = false- closureCallbackMu.Unlock()-- for _, a := range scratch {- if a != nil && a.Valid() {- C.mlx_array_free(a.c)- a.c.ctx = nil- }- }- }()-- // Recover the Go function from the handle- handle := cgo.Handle(payload)- fn := handle.Value().(ClosureFunc)-- // Convert input vector to Go slice - use borrowArray since MLX owns these- numInputs := int(C.mlx_vector_array_size(input))- inputs := make([]*Array, numInputs)- for i := range numInputs {- var arr C.mlx_array- C.mlx_vector_array_get(&arr, input, C.size_t(i))- inputs[i] = borrowArray(arr) // Don't set up cleanup - MLX owns these- }-- // Call the Go function- outputs := fn(inputs)-- var arrPtr *C.mlx_array- if len(outputs) > 0 {- handles := make([]C.mlx_array, len(outputs))- for i, arr := range outputs {- handles[i] = arr.c- }- arrPtr = &handles[0]- }-- return C.mlx_vector_array_set_data(res, arrPtr, C.size_t(len(outputs)))-}--//export goClosureDestructor-func goClosureDestructor(payload unsafe.Pointer) {- handle := cgo.Handle(payload)- handle.Delete()-}diff --git a/x/imagegen/mlx/doc.go b/x/imagegen/mlx/doc.godeleted file mode 100644index 5410f3b2d..000000000--- a/x/imagegen/mlx/doc.go+++ /dev/null@@ -1,4 +0,0 @@-// Package mlx provides Go bindings for the MLX-C library with dynamic loading support.-//-//go:generate go run generate_wrappers.go ../../mlxrunner/mlx/include/mlx/c mlx.h mlx.c-package mlxdiff --git a/x/imagegen/mlx/generate_wrappers.go b/x/imagegen/mlx/generate_wrappers.godeleted file mode 100644index 114ac2a15..000000000--- a/x/imagegen/mlx/generate_wrappers.go+++ /dev/null@@ -1,451 +0,0 @@-//go:build ignore--// This tool generates MLX-C dynamic loading wrappers.-// Usage: go run generate_wrappers.go <mlx-c-include-dir> <output-header> [output-impl]-package main--import (- "bytes"- "flag"- "fmt"- "io/fs"- "os"- "path/filepath"- "regexp"- "strings"-)--type Function struct {- Name string- ReturnType string- Params string- ParamNames []string- NeedsARM64Guard bool-}--func findHeaders(directory string) ([]string, error) {- var headers []string- err := filepath.WalkDir(directory, func(path string, d fs.DirEntry, err error) error {- if err != nil {- return err- }- // Private headers contain C++ implementation helpers and are not part of- // the C API surface; parsing them can produce invalid wrapper signatures.- if d.IsDir() && d.Name() == "private" {- return fs.SkipDir- }- if !d.IsDir() && strings.HasSuffix(path, ".h") {- headers = append(headers, path)- }- return nil- })- return headers, err-}--func cleanContent(content string) string {- // Remove single-line comments- re := regexp.MustCompile(`//.*?\n`)- content = re.ReplaceAllString(content, "\n")-- // Remove multi-line comments- re = regexp.MustCompile(`/\*.*?\*/`)- content = re.ReplaceAllString(content, "")-- // Remove preprocessor directives (lines starting with #) - use multiline mode- re = regexp.MustCompile(`(?m)^\s*#.*?$`)- content = re.ReplaceAllString(content, "")-- // Remove extern "C" { and } blocks more conservatively- // Only remove the extern "C" { line, not the content inside- re = regexp.MustCompile(`extern\s+"C"\s*\{\s*?\n`)- content = re.ReplaceAllString(content, "\n")- // Remove standalone closing braces that are not part of function declarations- re = regexp.MustCompile(`\n\s*\}\s*\n`)- content = re.ReplaceAllString(content, "\n")-- // Collapse whitespace and newlines- re = regexp.MustCompile(`\s+`)- content = re.ReplaceAllString(content, " ")-- return content-}--func extractParamNames(params string) []string {- if params == "" || strings.TrimSpace(params) == "void" {- return []string{}- }-- var names []string-- // Split by comma, but respect parentheses (for function pointers)- parts := splitParams(params)-- // Remove array brackets- arrayBrackets := regexp.MustCompile(`\[.*?\]`)-- // Function pointer pattern- funcPtrPattern := regexp.MustCompile(`\(\s*\*\s*(\w+)\s*\)`)-- // Type keywords to skip- typeKeywords := map[string]bool{- "const": true,- "struct": true,- "unsigned": true,- "signed": true,- "long": true,- "short": true,- "int": true,- "char": true,- "float": true,- "double": true,- "void": true,- "size_t": true,- "uint8_t": true,- "uint16_t": true,- "uint32_t": true,- "uint64_t": true,- "int8_t": true,- "int16_t": true,- "int32_t": true,- "int64_t": true,- "intptr_t": true,- "uintptr_t": true,- }-- for _, part := range parts {- if part == "" {- continue- }-- // Remove array brackets- part = arrayBrackets.ReplaceAllString(part, "")-- // For function pointers like "void (*callback)(int)"- if matches := funcPtrPattern.FindStringSubmatch(part); len(matches) > 1 {- names = append(names, matches[1])- continue- }-- // Regular parameter: last identifier- tokens := regexp.MustCompile(`\w+`).FindAllString(part, -1)- if len(tokens) > 0 {- // The last token is usually the parameter name- // Skip type keywords- for i := len(tokens) - 1; i >= 0; i-- {- if !typeKeywords[tokens[i]] {- names = append(names, tokens[i])- break- }- }- }- }-- return names-}--func splitParams(params string) []string {- var parts []string- var current bytes.Buffer- depth := 0-- for _, char := range params + "," {- switch char {- case '(':- depth++- current.WriteRune(char)- case ')':- depth--- current.WriteRune(char)- case ',':- if depth == 0 {- parts = append(parts, strings.TrimSpace(current.String()))- current.Reset()- } else {- current.WriteRune(char)- }- default:- current.WriteRune(char)- }- }-- return parts-}--func parseFunctions(content string) []Function {- var functions []Function-- // Match function declarations: return_type function_name(params);- // Matches both mlx_* and _mlx_* functions- pattern := regexp.MustCompile(`\b((?:const\s+)?(?:struct\s+)?[\w\s]+?[\*\s]*)\s+(_?mlx_\w+)\s*\(([^)]*(?:\([^)]*\)[^)]*)*)\)\s*;`)-- matches := pattern.FindAllStringSubmatch(content, -1)- for _, match := range matches {- returnType := strings.TrimSpace(match[1])- funcName := strings.TrimSpace(match[2])- params := strings.TrimSpace(match[3])-- // Skip if this looks like a variable declaration- if params == "" || strings.Contains(params, "{") {- continue- }-- // Clean up return type- returnType = strings.Join(strings.Fields(returnType), " ")-- // Extract parameter names- paramNames := extractParamNames(params)-- // Check if ARM64 guard is needed- needsGuard := needsARM64Guard(funcName, returnType, params)-- functions = append(functions, Function{- Name: funcName,- ReturnType: returnType,- Params: params,- ParamNames: paramNames,- NeedsARM64Guard: needsGuard,- })- }-- return functions-}--func needsARM64Guard(name, retType, params string) bool {- return strings.Contains(name, "float16") ||- strings.Contains(name, "bfloat16") ||- strings.Contains(retType, "float16_t") ||- strings.Contains(retType, "bfloat16_t") ||- strings.Contains(params, "float16_t") ||- strings.Contains(params, "bfloat16_t")-}--func generateWrapperFiles(functions []Function, headerPath, implPath string) error {- // Generate header file- var headerBuf bytes.Buffer-- headerBuf.WriteString("// AUTO-GENERATED by generate_wrappers.go - DO NOT EDIT\n")- headerBuf.WriteString("// This file provides wrapper declarations for MLX-C functions that use dlopen/dlsym\n")- headerBuf.WriteString("//\n")- headerBuf.WriteString("// Strategy: Include MLX-C headers for type definitions, then provide wrapper\n")- headerBuf.WriteString("// functions that shadow the originals, allowing Go code to call them directly (e.g., C.mlx_add).\n")- headerBuf.WriteString("// Function pointers are defined in mlx.c (single compilation unit).\n\n")- headerBuf.WriteString("#ifndef MLX_WRAPPERS_H\n")- headerBuf.WriteString("#define MLX_WRAPPERS_H\n\n")-- headerBuf.WriteString("// Include MLX headers for type definitions and original declarations\n")- headerBuf.WriteString("#include \"mlx/c/mlx.h\"\n")- headerBuf.WriteString("#include \"mlx_dynamic.h\"\n")- headerBuf.WriteString("#include <stdio.h>\n\n")-- // Undef all MLX functions to avoid conflicts- headerBuf.WriteString("// Undefine any existing MLX function macros\n")- for _, fn := range functions {- headerBuf.WriteString(fmt.Sprintf("#undef %s\n", fn.Name))- }- headerBuf.WriteString("\n")-- // Function pointer extern declarations- headerBuf.WriteString("// Function pointer declarations (defined in mlx.c, loaded via dlsym)\n")- for _, fn := range functions {- if fn.NeedsARM64Guard {- headerBuf.WriteString("#if defined(__aarch64__) || defined(_M_ARM64)\n")- }- headerBuf.WriteString(fmt.Sprintf("extern %s (*%s_ptr)(%s);\n", fn.ReturnType, fn.Name, fn.Params))- if fn.NeedsARM64Guard {- headerBuf.WriteString("#endif\n")- }- }- headerBuf.WriteString("\n")-- // Initialization function declaration- headerBuf.WriteString("// Initialize all function pointers via dlsym (defined in mlx.c)\n")- headerBuf.WriteString("int mlx_load_functions(void* handle);\n\n")-- // Wrapper function declarations- headerBuf.WriteString("// Wrapper function declarations that call through function pointers\n")- headerBuf.WriteString("// Go code calls these directly as C.mlx_* (no #define redirection needed)\n")- for _, fn := range functions {- if fn.NeedsARM64Guard {- headerBuf.WriteString("#if defined(__aarch64__) || defined(_M_ARM64)\n")- }- headerBuf.WriteString(fmt.Sprintf("%s %s(%s);\n", fn.ReturnType, fn.Name, fn.Params))- if fn.NeedsARM64Guard {- headerBuf.WriteString("#endif\n")- }- headerBuf.WriteString("\n")- }-- headerBuf.WriteString("#endif // MLX_WRAPPERS_H\n")-- // Write header file- if err := os.WriteFile(headerPath, headerBuf.Bytes(), 0644); err != nil {- return fmt.Errorf("failed to write header file: %w", err)- }-- // Generate implementation file- var implBuf bytes.Buffer-- implBuf.WriteString("// AUTO-GENERATED by generate_wrappers.go - DO NOT EDIT\n")- implBuf.WriteString("// This file contains the function pointer definitions and initialization\n")- implBuf.WriteString("// All function pointers are in a single compilation unit to avoid duplication\n\n")-- implBuf.WriteString("#include \"mlx/c/mlx.h\"\n")- implBuf.WriteString("#include \"mlx_dynamic.h\"\n")- implBuf.WriteString("#include <stdio.h>\n\n")- implBuf.WriteString("// Platform-specific dynamic loading\n")- implBuf.WriteString("#ifdef _WIN32\n")- implBuf.WriteString("#include <windows.h>\n")- implBuf.WriteString("#define GET_SYM(handle, name) (void*)GetProcAddress((HMODULE)(handle), name)\n")- implBuf.WriteString("#else\n")- implBuf.WriteString("#include <dlfcn.h>\n")- implBuf.WriteString("#define GET_SYM(handle, name) dlsym(handle, name)\n")- implBuf.WriteString("#endif\n\n")-- // Function pointer definitions- implBuf.WriteString("// Function pointer definitions\n")- for _, fn := range functions {- if fn.NeedsARM64Guard {- implBuf.WriteString("#if defined(__aarch64__) || defined(_M_ARM64)\n")- }- implBuf.WriteString(fmt.Sprintf("%s (*%s_ptr)(%s) = NULL;\n", fn.ReturnType, fn.Name, fn.Params))- if fn.NeedsARM64Guard {- implBuf.WriteString("#endif\n")- }- }- implBuf.WriteString("\n")-- // Initialization function- implBuf.WriteString("// Initialize all function pointers\n")- implBuf.WriteString("int mlx_load_functions(void* handle) {\n")- implBuf.WriteString(" if (handle == NULL) {\n")- implBuf.WriteString(" fprintf(stderr, \"MLX: Invalid library handle\\n\");\n")- implBuf.WriteString(" return -1;\n")- implBuf.WriteString(" }\n\n")-- for _, fn := range functions {- if fn.NeedsARM64Guard {- implBuf.WriteString("#if defined(__aarch64__) || defined(_M_ARM64)\n")- }- implBuf.WriteString(fmt.Sprintf(" %s_ptr = GET_SYM(handle, \"%s\");\n", fn.Name, fn.Name))- implBuf.WriteString(fmt.Sprintf(" if (%s_ptr == NULL) {\n", fn.Name))- implBuf.WriteString(fmt.Sprintf(" fprintf(stderr, \"MLX: Failed to load symbol: %s\\n\");\n", fn.Name))- implBuf.WriteString(" return -1;\n")- implBuf.WriteString(" }\n")- if fn.NeedsARM64Guard {- implBuf.WriteString("#endif\n")- }- }-- implBuf.WriteString(" return 0;\n")- implBuf.WriteString("}\n\n")-- // Wrapper function implementations- implBuf.WriteString("// Wrapper function implementations that call through function pointers\n")- for _, fn := range functions {- if fn.NeedsARM64Guard {- implBuf.WriteString("#if defined(__aarch64__) || defined(_M_ARM64)\n")- }- implBuf.WriteString(fmt.Sprintf("%s %s(%s) {\n", fn.ReturnType, fn.Name, fn.Params))-- // Call through function pointer- if fn.ReturnType != "void" {- implBuf.WriteString(fmt.Sprintf(" return %s_ptr(", fn.Name))- } else {- implBuf.WriteString(fmt.Sprintf(" %s_ptr(", fn.Name))- }-- // Pass parameters- implBuf.WriteString(strings.Join(fn.ParamNames, ", "))- implBuf.WriteString(");\n")- implBuf.WriteString("}\n")- if fn.NeedsARM64Guard {- implBuf.WriteString("#endif\n")- }- implBuf.WriteString("\n")- }-- // Write implementation file- if err := os.WriteFile(implPath, implBuf.Bytes(), 0644); err != nil {- return fmt.Errorf("failed to write implementation file: %w", err)- }-- return nil-}--func main() {- flag.Usage = func() {- fmt.Fprintf(flag.CommandLine.Output(), "Usage: go run generate_wrappers.go <mlx-c-include-dir> <output-header> [output-impl]\n")- fmt.Fprintf(flag.CommandLine.Output(), "Generate MLX-C dynamic loading wrappers.\n\n")- flag.PrintDefaults()- }- flag.Parse()-- args := flag.Args()- if len(args) < 2 {- fmt.Fprintf(flag.CommandLine.Output(), "ERROR: Missing required arguments\n\n")- flag.Usage()- os.Exit(1)- }-- headerDir := args[0]- outputHeader := args[1]- // Default implementation file is same name with .c extension- outputImpl := outputHeader- if len(args) > 2 {- outputImpl = args[2]- } else if strings.HasSuffix(outputHeader, ".h") {- outputImpl = outputHeader[:len(outputHeader)-2] + ".c"- }-- // Check if header directory exists- if _, err := os.Stat(headerDir); os.IsNotExist(err) {- fmt.Fprintf(os.Stderr, "ERROR: MLX-C headers directory not found at: %s\n\n", headerDir)- fmt.Fprintf(os.Stderr, "Please run CMake first to download MLX-C dependencies:\n")- fmt.Fprintf(os.Stderr, " cmake -B build\n\n")- fmt.Fprintf(os.Stderr, "The CMake build will download and extract MLX-C headers needed for wrapper generation.\n")- os.Exit(1)- }-- fmt.Fprintf(os.Stderr, "Parsing MLX-C headers from: %s\n", headerDir)-- // Find all headers- headers, err := findHeaders(headerDir)- if err != nil {- fmt.Fprintf(os.Stderr, "ERROR: Failed to find header files: %v\n", err)- os.Exit(1)- }- fmt.Fprintf(os.Stderr, "Found %d header files\n", len(headers))-- // Parse all headers- var allFunctions []Function- seen := make(map[string]bool)-- for _, header := range headers {- content, err := os.ReadFile(header)- if err != nil {- fmt.Fprintf(os.Stderr, "Error reading %s: %v\n", header, err)- continue- }-- cleaned := cleanContent(string(content))- functions := parseFunctions(cleaned)-- // Deduplicate- for _, fn := range functions {- if !seen[fn.Name] {- seen[fn.Name] = true- allFunctions = append(allFunctions, fn)- }- }- }-- fmt.Fprintf(os.Stderr, "Found %d unique function declarations\n", len(allFunctions))-- // Generate wrapper files- if err := generateWrapperFiles(allFunctions, outputHeader, outputImpl); err != nil {- fmt.Fprintf(os.Stderr, "ERROR: Failed to generate wrapper files: %v\n", err)- os.Exit(1)- }-- fmt.Fprintf(os.Stderr, "Generated %s and %s successfully\n", outputHeader, outputImpl)-}diff --git a/x/imagegen/mlx/mlx.c b/x/imagegen/mlx/mlx.cdeleted file mode 100644index 6352929cf..000000000--- a/x/imagegen/mlx/mlx.c+++ /dev/null@@ -1,6244 +0,0 @@-// AUTO-GENERATED by generate_wrappers.go - DO NOT EDIT-// This file contains the function pointer definitions and initialization-// All function pointers are in a single compilation unit to avoid duplication--#include "mlx/c/mlx.h"-#include "mlx_dynamic.h"-#include <stdio.h>--// Platform-specific dynamic loading-#ifdef _WIN32-#include <windows.h>-#define GET_SYM(handle, name) (void*)GetProcAddress((HMODULE)(handle), name)-#else-#include <dlfcn.h>-#define GET_SYM(handle, name) dlsym(handle, name)-#endif--// Function pointer definitions-size_t (*mlx_dtype_size_ptr)(mlx_dtype dtype) = NULL;-int (*mlx_array_tostring_ptr)(mlx_string* str, const mlx_array arr) = NULL;-mlx_array (*mlx_array_new_ptr)(void) = NULL;-int (*mlx_array_free_ptr)(mlx_array arr) = NULL;-mlx_array (*mlx_array_new_bool_ptr)(bool val) = NULL;-mlx_array (*mlx_array_new_int_ptr)(int val) = NULL;-mlx_array (*mlx_array_new_float32_ptr)(float val) = NULL;-mlx_array (*mlx_array_new_float_ptr)(float val) = NULL;-mlx_array (*mlx_array_new_float64_ptr)(double val) = NULL;-mlx_array (*mlx_array_new_double_ptr)(double val) = NULL;-mlx_array (*mlx_array_new_complex_ptr)(float real_val, float imag_val) = NULL;-mlx_array (*mlx_array_new_data_ptr)(const void* data, const int* shape, int dim, mlx_dtype dtype) = NULL;-mlx_array (*mlx_array_new_data_managed_ptr)(void* data, const int* shape, int dim, mlx_dtype dtype, void (*dtor)(void*)) = NULL;-mlx_array (*mlx_array_new_data_managed_payload_ptr)(void* data, const int* shape, int dim, mlx_dtype dtype, void* payload, void (*dtor)(void*)) = NULL;-int (*mlx_array_set_ptr)(mlx_array* arr, const mlx_array src) = NULL;-int (*mlx_array_set_bool_ptr)(mlx_array* arr, bool val) = NULL;-int (*mlx_array_set_int_ptr)(mlx_array* arr, int val) = NULL;-int (*mlx_array_set_float32_ptr)(mlx_array* arr, float val) = NULL;-int (*mlx_array_set_float_ptr)(mlx_array* arr, float val) = NULL;-int (*mlx_array_set_float64_ptr)(mlx_array* arr, double val) = NULL;-int (*mlx_array_set_double_ptr)(mlx_array* arr, double val) = NULL;-int (*mlx_array_set_complex_ptr)(mlx_array* arr, float real_val, float imag_val) = NULL;-int (*mlx_array_set_data_ptr)(mlx_array* arr, const void* data, const int* shape, int dim, mlx_dtype dtype) = NULL;-size_t (*mlx_array_itemsize_ptr)(const mlx_array arr) = NULL;-size_t (*mlx_array_size_ptr)(const mlx_array arr) = NULL;-size_t (*mlx_array_nbytes_ptr)(const mlx_array arr) = NULL;-size_t (*mlx_array_ndim_ptr)(const mlx_array arr) = NULL;-const int* (*mlx_array_shape_ptr)(const mlx_array arr) = NULL;-const size_t* (*mlx_array_strides_ptr)(const mlx_array arr) = NULL;-int (*mlx_array_dim_ptr)(const mlx_array arr, int dim) = NULL;-mlx_dtype (*mlx_array_dtype_ptr)(const mlx_array arr) = NULL;-int (*mlx_array_eval_ptr)(mlx_array arr) = NULL;-int (*mlx_array_item_bool_ptr)(bool* res, const mlx_array arr) = NULL;-int (*mlx_array_item_uint8_ptr)(uint8_t* res, const mlx_array arr) = NULL;-int (*mlx_array_item_uint16_ptr)(uint16_t* res, const mlx_array arr) = NULL;-int (*mlx_array_item_uint32_ptr)(uint32_t* res, const mlx_array arr) = NULL;-int (*mlx_array_item_uint64_ptr)(uint64_t* res, const mlx_array arr) = NULL;-int (*mlx_array_item_int8_ptr)(int8_t* res, const mlx_array arr) = NULL;-int (*mlx_array_item_int16_ptr)(int16_t* res, const mlx_array arr) = NULL;-int (*mlx_array_item_int32_ptr)(int32_t* res, const mlx_array arr) = NULL;-int (*mlx_array_item_int64_ptr)(int64_t* res, const mlx_array arr) = NULL;-int (*mlx_array_item_float32_ptr)(float* res, const mlx_array arr) = NULL;-int (*mlx_array_item_float64_ptr)(double* res, const mlx_array arr) = NULL;-int (*mlx_array_item_complex64_ptr)(mlx_complex64_t* res, const mlx_array arr) = NULL;-#if defined(__aarch64__) || defined(_M_ARM64)-int (*mlx_array_item_float16_ptr)(float16_t* res, const mlx_array arr) = NULL;-#endif-#if defined(__aarch64__) || defined(_M_ARM64)-int (*mlx_array_item_bfloat16_ptr)(bfloat16_t* res, const mlx_array arr) = NULL;-#endif-const bool* (*mlx_array_data_bool_ptr)(const mlx_array arr) = NULL;-const uint8_t* (*mlx_array_data_uint8_ptr)(const mlx_array arr) = NULL;-const uint16_t* (*mlx_array_data_uint16_ptr)(const mlx_array arr) = NULL;-const uint32_t* (*mlx_array_data_uint32_ptr)(const mlx_array arr) = NULL;-const uint64_t* (*mlx_array_data_uint64_ptr)(const mlx_array arr) = NULL;-const int8_t* (*mlx_array_data_int8_ptr)(const mlx_array arr) = NULL;-const int16_t* (*mlx_array_data_int16_ptr)(const mlx_array arr) = NULL;-const int32_t* (*mlx_array_data_int32_ptr)(const mlx_array arr) = NULL;-const int64_t* (*mlx_array_data_int64_ptr)(const mlx_array arr) = NULL;-const float* (*mlx_array_data_float32_ptr)(const mlx_array arr) = NULL;-const double* (*mlx_array_data_float64_ptr)(const mlx_array arr) = NULL;-const mlx_complex64_t* (*mlx_array_data_complex64_ptr)(const mlx_array arr) = NULL;-#if defined(__aarch64__) || defined(_M_ARM64)-const float16_t* (*mlx_array_data_float16_ptr)(const mlx_array arr) = NULL;-#endif-#if defined(__aarch64__) || defined(_M_ARM64)-const bfloat16_t* (*mlx_array_data_bfloat16_ptr)(const mlx_array arr) = NULL;-#endif-int (*_mlx_array_is_available_ptr)(bool* res, const mlx_array arr) = NULL;-int (*_mlx_array_wait_ptr)(const mlx_array arr) = NULL;-int (*_mlx_array_is_contiguous_ptr)(bool* res, const mlx_array arr) = NULL;-int (*_mlx_array_is_row_contiguous_ptr)(bool* res, const mlx_array arr) = NULL;-int (*_mlx_array_is_col_contiguous_ptr)(bool* res, const mlx_array arr) = NULL;-mlx_closure (*mlx_closure_new_ptr)(void) = NULL;-int (*mlx_closure_free_ptr)(mlx_closure cls) = NULL;-mlx_closure (*mlx_closure_new_func_ptr)(int (*fun)(mlx_vector_array*, const mlx_vector_array)) = NULL;-mlx_closure (*mlx_closure_new_func_payload_ptr)(int (*fun)(mlx_vector_array*, const mlx_vector_array, void*), void* payload, void (*dtor)(void*)) = NULL;-int (*mlx_closure_set_ptr)(mlx_closure* cls, const mlx_closure src) = NULL;-int (*mlx_closure_apply_ptr)(mlx_vector_array* res, mlx_closure cls, const mlx_vector_array input) = NULL;-mlx_closure (*mlx_closure_new_unary_ptr)(int (*fun)(mlx_array*, const mlx_array)) = NULL;-mlx_closure_kwargs (*mlx_closure_kwargs_new_ptr)(void) = NULL;-int (*mlx_closure_kwargs_free_ptr)(mlx_closure_kwargs cls) = NULL;-mlx_closure_kwargs (*mlx_closure_kwargs_new_func_ptr)(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_map_string_to_array)) = NULL;-mlx_closure_kwargs (*mlx_closure_kwargs_new_func_payload_ptr)(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_map_string_to_array, void*), void* payload, void (*dtor)(void*)) = NULL;-int (*mlx_closure_kwargs_set_ptr)(mlx_closure_kwargs* cls, const mlx_closure_kwargs src) = NULL;-int (*mlx_closure_kwargs_apply_ptr)(mlx_vector_array* res, mlx_closure_kwargs cls, const mlx_vector_array input_0, const mlx_map_string_to_array input_1) = NULL;-mlx_closure_value_and_grad (*mlx_closure_value_and_grad_new_ptr)(void) = NULL;-int (*mlx_closure_value_and_grad_free_ptr)(mlx_closure_value_and_grad cls) = NULL;-mlx_closure_value_and_grad (*mlx_closure_value_and_grad_new_func_ptr)(int (*fun)(mlx_vector_array*, mlx_vector_array*, const mlx_vector_array)) = NULL;-mlx_closure_value_and_grad (*mlx_closure_value_and_grad_new_func_payload_ptr)(int (*fun)( mlx_vector_array*, mlx_vector_array*, const mlx_vector_array, void*), void* payload, void (*dtor)(void*)) = NULL;-int (*mlx_closure_value_and_grad_set_ptr)(mlx_closure_value_and_grad* cls, const mlx_closure_value_and_grad src) = NULL;-int (*mlx_closure_value_and_grad_apply_ptr)(mlx_vector_array* res_0, mlx_vector_array* res_1, mlx_closure_value_and_grad cls, const mlx_vector_array input) = NULL;-mlx_closure_custom (*mlx_closure_custom_new_ptr)(void) = NULL;-int (*mlx_closure_custom_free_ptr)(mlx_closure_custom cls) = NULL;-mlx_closure_custom (*mlx_closure_custom_new_func_ptr)(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_vector_array, const mlx_vector_array)) = NULL;-mlx_closure_custom (*mlx_closure_custom_new_func_payload_ptr)(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_vector_array, const mlx_vector_array, void*), void* payload, void (*dtor)(void*)) = NULL;-int (*mlx_closure_custom_set_ptr)(mlx_closure_custom* cls, const mlx_closure_custom src) = NULL;-int (*mlx_closure_custom_apply_ptr)(mlx_vector_array* res, mlx_closure_custom cls, const mlx_vector_array input_0, const mlx_vector_array input_1, const mlx_vector_array input_2) = NULL;-mlx_closure_custom_jvp (*mlx_closure_custom_jvp_new_ptr)(void) = NULL;-int (*mlx_closure_custom_jvp_free_ptr)(mlx_closure_custom_jvp cls) = NULL;-mlx_closure_custom_jvp (*mlx_closure_custom_jvp_new_func_ptr)(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_vector_array, const int*, size_t _num)) = NULL;-mlx_closure_custom_jvp (*mlx_closure_custom_jvp_new_func_payload_ptr)(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_vector_array, const int*, size_t _num, void*), void* payload, void (*dtor)(void*)) = NULL;-int (*mlx_closure_custom_jvp_set_ptr)(mlx_closure_custom_jvp* cls, const mlx_closure_custom_jvp src) = NULL;-int (*mlx_closure_custom_jvp_apply_ptr)(mlx_vector_array* res, mlx_closure_custom_jvp cls, const mlx_vector_array input_0, const mlx_vector_array input_1, const int* input_2, size_t input_2_num) = NULL;-mlx_closure_custom_vmap (*mlx_closure_custom_vmap_new_ptr)(void) = NULL;-int (*mlx_closure_custom_vmap_free_ptr)(mlx_closure_custom_vmap cls) = NULL;-mlx_closure_custom_vmap (*mlx_closure_custom_vmap_new_func_ptr)(int (*fun)( mlx_vector_array*, mlx_vector_int*, const mlx_vector_array, const int*, size_t _num)) = NULL;-mlx_closure_custom_vmap (*mlx_closure_custom_vmap_new_func_payload_ptr)(int (*fun)( mlx_vector_array*, mlx_vector_int*, const mlx_vector_array, const int*, size_t _num, void*), void* payload, void (*dtor)(void*)) = NULL;-int (*mlx_closure_custom_vmap_set_ptr)(mlx_closure_custom_vmap* cls, const mlx_closure_custom_vmap src) = NULL;-int (*mlx_closure_custom_vmap_apply_ptr)(mlx_vector_array* res_0, mlx_vector_int* res_1, mlx_closure_custom_vmap cls, const mlx_vector_array input_0, const int* input_1, size_t input_1_num) = NULL;-int (*mlx_compile_ptr)(mlx_closure* res, const mlx_closure fun, bool shapeless) = NULL;-int (*mlx_detail_compile_ptr)(mlx_closure* res, const mlx_closure fun, uintptr_t fun_id, bool shapeless, const uint64_t* constants, size_t constants_num) = NULL;-int (*mlx_detail_compile_clear_cache_ptr)(void) = NULL;-int (*mlx_detail_compile_erase_ptr)(uintptr_t fun_id) = NULL;-int (*mlx_disable_compile_ptr)(void) = NULL;-int (*mlx_enable_compile_ptr)(void) = NULL;-int (*mlx_set_compile_mode_ptr)(mlx_compile_mode mode) = NULL;-int (*mlx_cuda_is_available_ptr)(bool* res) = NULL;-mlx_device (*mlx_device_new_ptr)(void) = NULL;-mlx_device (*mlx_device_new_type_ptr)(mlx_device_type type, int index) = NULL;-int (*mlx_device_free_ptr)(mlx_device dev) = NULL;-int (*mlx_device_set_ptr)(mlx_device* dev, const mlx_device src) = NULL;-int (*mlx_device_tostring_ptr)(mlx_string* str, mlx_device dev) = NULL;-bool (*mlx_device_equal_ptr)(mlx_device lhs, mlx_device rhs) = NULL;-int (*mlx_device_get_index_ptr)(int* index, mlx_device dev) = NULL;-int (*mlx_device_get_type_ptr)(mlx_device_type* type, mlx_device dev) = NULL;-int (*mlx_get_default_device_ptr)(mlx_device* dev) = NULL;-int (*mlx_set_default_device_ptr)(mlx_device dev) = NULL;-int (*mlx_device_is_available_ptr)(bool* avail, mlx_device dev) = NULL;-int (*mlx_device_count_ptr)(int* count, mlx_device_type type) = NULL;-mlx_device_info (*mlx_device_info_new_ptr)(void) = NULL;-int (*mlx_device_info_get_ptr)(mlx_device_info* info, mlx_device dev) = NULL;-int (*mlx_device_info_free_ptr)(mlx_device_info info) = NULL;-int (*mlx_device_info_has_key_ptr)(bool* exists, mlx_device_info info, const char* key) = NULL;-int (*mlx_device_info_is_string_ptr)(bool* is_string, mlx_device_info info, const char* key) = NULL;-int (*mlx_device_info_get_string_ptr)(const char** value, mlx_device_info info, const char* key) = NULL;-int (*mlx_device_info_get_size_ptr)(size_t* value, mlx_device_info info, const char* key) = NULL;-int (*mlx_device_info_get_keys_ptr)(mlx_vector_string* keys, mlx_device_info info) = NULL;-int (*mlx_distributed_all_gather_ptr)(mlx_array* res, const mlx_array x, const mlx_distributed_group group , const mlx_stream S) = NULL;-int (*mlx_distributed_all_max_ptr)(mlx_array* res, const mlx_array x, const mlx_distributed_group group , const mlx_stream s) = NULL;-int (*mlx_distributed_all_min_ptr)(mlx_array* res, const mlx_array x, const mlx_distributed_group group , const mlx_stream s) = NULL;-int (*mlx_distributed_all_sum_ptr)(mlx_array* res, const mlx_array x, const mlx_distributed_group group , const mlx_stream s) = NULL;-int (*mlx_distributed_recv_ptr)(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, int src, const mlx_distributed_group group , const mlx_stream s) = NULL;-int (*mlx_distributed_recv_like_ptr)(mlx_array* res, const mlx_array x, int src, const mlx_distributed_group group , const mlx_stream s) = NULL;-int (*mlx_distributed_send_ptr)(mlx_array* res, const mlx_array x, int dst, const mlx_distributed_group group , const mlx_stream s) = NULL;-int (*mlx_distributed_sum_scatter_ptr)(mlx_array* res, const mlx_array x, const mlx_distributed_group group , const mlx_stream s) = NULL;-mlx_distributed_group (*mlx_distributed_group_new_ptr)(void) = NULL;-int (*mlx_distributed_group_free_ptr)(mlx_distributed_group group) = NULL;-int (*mlx_distributed_init_ptr)(mlx_distributed_group* res, bool strict, const char* bk) = NULL;-int (*mlx_distributed_group_rank_ptr)(mlx_distributed_group group) = NULL;-int (*mlx_distributed_group_size_ptr)(mlx_distributed_group group) = NULL;-int (*mlx_distributed_group_split_ptr)(mlx_distributed_group* res, mlx_distributed_group group, int color, int key) = NULL;-bool (*mlx_distributed_is_available_ptr)(const char* bk) = NULL;-void (*mlx_set_error_handler_ptr)(mlx_error_handler_func handler, void* data, void (*dtor)(void*)) = NULL;-void (*_mlx_error_ptr)(const char* file, const int line, const char* fmt, ...) = NULL;-int (*mlx_export_function_ptr)(const char* file, const mlx_closure fun, const mlx_vector_array args, bool shapeless) = NULL;-int (*mlx_export_function_kwargs_ptr)(const char* file, const mlx_closure_kwargs fun, const mlx_vector_array args, const mlx_map_string_to_array kwargs, bool shapeless) = NULL;-mlx_function_exporter (*mlx_function_exporter_new_ptr)(const char* file, const mlx_closure fun, bool shapeless) = NULL;-int (*mlx_function_exporter_free_ptr)(mlx_function_exporter xfunc) = NULL;-int (*mlx_function_exporter_apply_ptr)(const mlx_function_exporter xfunc, const mlx_vector_array args) = NULL;-int (*mlx_function_exporter_apply_kwargs_ptr)(const mlx_function_exporter xfunc, const mlx_vector_array args, const mlx_map_string_to_array kwargs) = NULL;-mlx_imported_function (*mlx_imported_function_new_ptr)(const char* file) = NULL;-int (*mlx_imported_function_free_ptr)(mlx_imported_function xfunc) = NULL;-int (*mlx_imported_function_apply_ptr)(mlx_vector_array* res, const mlx_imported_function xfunc, const mlx_vector_array args) = NULL;-int (*mlx_imported_function_apply_kwargs_ptr)(mlx_vector_array* res, const mlx_imported_function xfunc, const mlx_vector_array args, const mlx_map_string_to_array kwargs) = NULL;-mlx_fast_cuda_kernel_config (*mlx_fast_cuda_kernel_config_new_ptr)(void) = NULL;-void (*mlx_fast_cuda_kernel_config_free_ptr)(mlx_fast_cuda_kernel_config cls) = NULL;-int (*mlx_fast_cuda_kernel_config_add_output_arg_ptr)(mlx_fast_cuda_kernel_config cls, const int* shape, size_t size, mlx_dtype dtype) = NULL;-int (*mlx_fast_cuda_kernel_config_set_grid_ptr)(mlx_fast_cuda_kernel_config cls, int grid1, int grid2, int grid3) = NULL;-int (*mlx_fast_cuda_kernel_config_set_thread_group_ptr)(mlx_fast_cuda_kernel_config cls, int thread1, int thread2, int thread3) = NULL;-int (*mlx_fast_cuda_kernel_config_set_init_value_ptr)(mlx_fast_cuda_kernel_config cls, float value) = NULL;-int (*mlx_fast_cuda_kernel_config_set_verbose_ptr)(mlx_fast_cuda_kernel_config cls, bool verbose) = NULL;-int (*mlx_fast_cuda_kernel_config_add_template_arg_dtype_ptr)(mlx_fast_cuda_kernel_config cls, const char* name, mlx_dtype dtype) = NULL;-int (*mlx_fast_cuda_kernel_config_add_template_arg_int_ptr)(mlx_fast_cuda_kernel_config cls, const char* name, int value) = NULL;-int (*mlx_fast_cuda_kernel_config_add_template_arg_bool_ptr)(mlx_fast_cuda_kernel_config cls, const char* name, bool value) = NULL;-mlx_fast_cuda_kernel (*mlx_fast_cuda_kernel_new_ptr)(const char* name, const mlx_vector_string input_names, const mlx_vector_string output_names, const char* source, const char* header, bool ensure_row_contiguous, int shared_memory) = NULL;-void (*mlx_fast_cuda_kernel_free_ptr)(mlx_fast_cuda_kernel cls) = NULL;-int (*mlx_fast_cuda_kernel_apply_ptr)(mlx_vector_array* outputs, mlx_fast_cuda_kernel cls, const mlx_vector_array inputs, const mlx_fast_cuda_kernel_config config, const mlx_stream stream) = NULL;-int (*mlx_fast_layer_norm_ptr)(mlx_array* res, const mlx_array x, const mlx_array weight , const mlx_array bias , float eps, const mlx_stream s) = NULL;-mlx_fast_metal_kernel_config (*mlx_fast_metal_kernel_config_new_ptr)(void) = NULL;-void (*mlx_fast_metal_kernel_config_free_ptr)(mlx_fast_metal_kernel_config cls) = NULL;-int (*mlx_fast_metal_kernel_config_add_output_arg_ptr)(mlx_fast_metal_kernel_config cls, const int* shape, size_t size, mlx_dtype dtype) = NULL;-int (*mlx_fast_metal_kernel_config_set_grid_ptr)(mlx_fast_metal_kernel_config cls, int grid1, int grid2, int grid3) = NULL;-int (*mlx_fast_metal_kernel_config_set_thread_group_ptr)(mlx_fast_metal_kernel_config cls, int thread1, int thread2, int thread3) = NULL;-int (*mlx_fast_metal_kernel_config_set_init_value_ptr)(mlx_fast_metal_kernel_config cls, float value) = NULL;-int (*mlx_fast_metal_kernel_config_set_verbose_ptr)(mlx_fast_metal_kernel_config cls, bool verbose) = NULL;-int (*mlx_fast_metal_kernel_config_add_template_arg_dtype_ptr)(mlx_fast_metal_kernel_config cls, const char* name, mlx_dtype dtype) = NULL;-int (*mlx_fast_metal_kernel_config_add_template_arg_int_ptr)(mlx_fast_metal_kernel_config cls, const char* name, int value) = NULL;-int (*mlx_fast_metal_kernel_config_add_template_arg_bool_ptr)(mlx_fast_metal_kernel_config cls, const char* name, bool value) = NULL;-mlx_fast_metal_kernel (*mlx_fast_metal_kernel_new_ptr)(const char* name, const mlx_vector_string input_names, const mlx_vector_string output_names, const char* source, const char* header, bool ensure_row_contiguous, bool atomic_outputs) = NULL;-void (*mlx_fast_metal_kernel_free_ptr)(mlx_fast_metal_kernel cls) = NULL;-int (*mlx_fast_metal_kernel_apply_ptr)(mlx_vector_array* outputs, mlx_fast_metal_kernel cls, const mlx_vector_array inputs, const mlx_fast_metal_kernel_config config, const mlx_stream stream) = NULL;-int (*mlx_fast_rms_norm_ptr)(mlx_array* res, const mlx_array x, const mlx_array weight , float eps, const mlx_stream s) = NULL;-int (*mlx_fast_rope_ptr)(mlx_array* res, const mlx_array x, int dims, bool traditional, mlx_optional_float base, float scale, int offset, const mlx_array freqs , const mlx_stream s) = NULL;-int (*mlx_fast_rope_dynamic_ptr)(mlx_array* res, const mlx_array x, int dims, bool traditional, mlx_optional_float base, float scale, const mlx_array offset, const mlx_array freqs , const mlx_stream s) = NULL;-int (*mlx_fast_scaled_dot_product_attention_ptr)(mlx_array* res, const mlx_array queries, const mlx_array keys, const mlx_array values, float scale, const char* mask_mode, const mlx_array mask_arr , const mlx_array sinks , const mlx_stream s) = NULL;-int (*mlx_fft_fft_ptr)(mlx_array* res, const mlx_array a, int n, int axis, mlx_fft_norm norm, const mlx_stream s) = NULL;-int (*mlx_fft_fft2_ptr)(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s) = NULL;-int (*mlx_fft_fftfreq_ptr)(mlx_array* res, int n, double d, const mlx_stream s) = NULL;-int (*mlx_fft_fftn_ptr)(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s) = NULL;-int (*mlx_fft_fftshift_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const mlx_stream s) = NULL;-int (*mlx_fft_ifft_ptr)(mlx_array* res, const mlx_array a, int n, int axis, mlx_fft_norm norm, const mlx_stream s) = NULL;-int (*mlx_fft_ifft2_ptr)(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s) = NULL;-int (*mlx_fft_ifftn_ptr)(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s) = NULL;-int (*mlx_fft_ifftshift_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const mlx_stream s) = NULL;-int (*mlx_fft_irfft_ptr)(mlx_array* res, const mlx_array a, int n, int axis, mlx_fft_norm norm, const mlx_stream s) = NULL;-int (*mlx_fft_irfft2_ptr)(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s) = NULL;-int (*mlx_fft_irfftn_ptr)(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s) = NULL;-int (*mlx_fft_rfft_ptr)(mlx_array* res, const mlx_array a, int n, int axis, mlx_fft_norm norm, const mlx_stream s) = NULL;-int (*mlx_fft_rfft2_ptr)(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s) = NULL;-int (*mlx_fft_rfftfreq_ptr)(mlx_array* res, int n, double d, const mlx_stream s) = NULL;-int (*mlx_fft_rfftn_ptr)(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s) = NULL;-int (*mlx_node_namer_free_ptr)(mlx_node_namer namer) = NULL;-int (*mlx_node_namer_set_name_ptr)(mlx_node_namer namer, const mlx_array arr, const char* name) = NULL;-int (*mlx_node_namer_get_name_ptr)(const char** name, mlx_node_namer namer, const mlx_array arr) = NULL;-int (*mlx_export_to_dot_ptr)(FILE* os, const mlx_node_namer namer, const mlx_vector_array outputs) = NULL;-int (*mlx_print_graph_ptr)(FILE* os, const mlx_node_namer namer, const mlx_vector_array outputs) = NULL;-int (*mlx_load_reader_ptr)(mlx_array* res, mlx_io_reader in_stream, const mlx_stream s) = NULL;-int (*mlx_load_ptr)(mlx_array* res, const char* file, const mlx_stream s) = NULL;-int (*mlx_load_gguf_ptr)(mlx_io_gguf* gguf, const char* file, const mlx_stream s) = NULL;-int (*mlx_load_safetensors_reader_ptr)(mlx_map_string_to_array* res_0, mlx_map_string_to_string* res_1, mlx_io_reader in_stream, const mlx_stream s) = NULL;-int (*mlx_load_safetensors_ptr)(mlx_map_string_to_array* res_0, mlx_map_string_to_string* res_1, const char* file, const mlx_stream s) = NULL;-int (*mlx_save_writer_ptr)(mlx_io_writer out_stream, const mlx_array a) = NULL;-int (*mlx_save_ptr)(const char* file, const mlx_array a) = NULL;-int (*mlx_save_gguf_ptr)(const char* file, mlx_io_gguf gguf) = NULL;-int (*mlx_save_safetensors_writer_ptr)(mlx_io_writer in_stream, const mlx_map_string_to_array param, const mlx_map_string_to_string metadata) = NULL;-int (*mlx_save_safetensors_ptr)(const char* file, const mlx_map_string_to_array param, const mlx_map_string_to_string metadata) = NULL;-mlx_io_reader (*mlx_io_reader_new_ptr)(void* desc, mlx_io_vtable vtable) = NULL;-int (*mlx_io_reader_descriptor_ptr)(void** desc_, mlx_io_reader io) = NULL;-int (*mlx_io_reader_tostring_ptr)(mlx_string* str_, mlx_io_reader io) = NULL;-int (*mlx_io_reader_free_ptr)(mlx_io_reader io) = NULL;-mlx_io_writer (*mlx_io_writer_new_ptr)(void* desc, mlx_io_vtable vtable) = NULL;-int (*mlx_io_writer_descriptor_ptr)(void** desc_, mlx_io_writer io) = NULL;-int (*mlx_io_writer_tostring_ptr)(mlx_string* str_, mlx_io_writer io) = NULL;-int (*mlx_io_writer_free_ptr)(mlx_io_writer io) = NULL;-mlx_io_gguf (*mlx_io_gguf_new_ptr)(void) = NULL;-int (*mlx_io_gguf_free_ptr)(mlx_io_gguf io) = NULL;-int (*mlx_io_gguf_get_keys_ptr)(mlx_vector_string* keys, mlx_io_gguf io) = NULL;-int (*mlx_io_gguf_get_array_ptr)(mlx_array* arr, mlx_io_gguf io, const char* key) = NULL;-int (*mlx_io_gguf_get_metadata_array_ptr)(mlx_array* arr, mlx_io_gguf io, const char* key) = NULL;-int (*mlx_io_gguf_get_metadata_string_ptr)(mlx_string* str, mlx_io_gguf io, const char* key) = NULL;-int (*mlx_io_gguf_get_metadata_vector_string_ptr)(mlx_vector_string* vstr, mlx_io_gguf io, const char* key) = NULL;-int (*mlx_io_gguf_has_metadata_array_ptr)(bool* flag, mlx_io_gguf io, const char* key) = NULL;-int (*mlx_io_gguf_has_metadata_string_ptr)(bool* flag, mlx_io_gguf io, const char* key) = NULL;-int (*mlx_io_gguf_has_metadata_vector_string_ptr)(bool* flag, mlx_io_gguf io, const char* key) = NULL;-int (*mlx_io_gguf_set_array_ptr)(mlx_io_gguf io, const char* key, const mlx_array arr) = NULL;-int (*mlx_io_gguf_set_metadata_array_ptr)(mlx_io_gguf io, const char* key, const mlx_array marr) = NULL;-int (*mlx_io_gguf_set_metadata_string_ptr)(mlx_io_gguf io, const char* key, const char* mstr) = NULL;-int (*mlx_io_gguf_set_metadata_vector_string_ptr)(mlx_io_gguf io, const char* key, const mlx_vector_string mvstr) = NULL;-int (*mlx_linalg_cholesky_ptr)(mlx_array* res, const mlx_array a, bool upper, const mlx_stream s) = NULL;-int (*mlx_linalg_cholesky_inv_ptr)(mlx_array* res, const mlx_array a, bool upper, const mlx_stream s) = NULL;-int (*mlx_linalg_cross_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, int axis, const mlx_stream s) = NULL;-int (*mlx_linalg_eig_ptr)(mlx_array* res_0, mlx_array* res_1, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_linalg_eigh_ptr)(mlx_array* res_0, mlx_array* res_1, const mlx_array a, const char* UPLO, const mlx_stream s) = NULL;-int (*mlx_linalg_eigvals_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_linalg_eigvalsh_ptr)(mlx_array* res, const mlx_array a, const char* UPLO, const mlx_stream s) = NULL;-int (*mlx_linalg_inv_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_linalg_lu_ptr)(mlx_vector_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_linalg_lu_factor_ptr)(mlx_array* res_0, mlx_array* res_1, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_linalg_norm_ptr)(mlx_array* res, const mlx_array a, double ord, const int* axis , size_t axis_num, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_linalg_norm_matrix_ptr)(mlx_array* res, const mlx_array a, const char* ord, const int* axis , size_t axis_num, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_linalg_norm_l2_ptr)(mlx_array* res, const mlx_array a, const int* axis , size_t axis_num, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_linalg_pinv_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_linalg_qr_ptr)(mlx_array* res_0, mlx_array* res_1, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_linalg_solve_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_linalg_solve_triangular_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, bool upper, const mlx_stream s) = NULL;-int (*mlx_linalg_svd_ptr)(mlx_vector_array* res, const mlx_array a, bool compute_uv, const mlx_stream s) = NULL;-int (*mlx_linalg_tri_inv_ptr)(mlx_array* res, const mlx_array a, bool upper, const mlx_stream s) = NULL;-mlx_map_string_to_array (*mlx_map_string_to_array_new_ptr)(void) = NULL;-int (*mlx_map_string_to_array_set_ptr)(mlx_map_string_to_array* map, const mlx_map_string_to_array src) = NULL;-int (*mlx_map_string_to_array_free_ptr)(mlx_map_string_to_array map) = NULL;-int (*mlx_map_string_to_array_insert_ptr)(mlx_map_string_to_array map, const char* key, const mlx_array value) = NULL;-int (*mlx_map_string_to_array_get_ptr)(mlx_array* value, const mlx_map_string_to_array map, const char* key) = NULL;-mlx_map_string_to_array_iterator (*mlx_map_string_to_array_iterator_new_ptr)(mlx_map_string_to_array map) = NULL;-int (*mlx_map_string_to_array_iterator_free_ptr)(mlx_map_string_to_array_iterator it) = NULL;-int (*mlx_map_string_to_array_iterator_next_ptr)(const char** key, mlx_array* value, mlx_map_string_to_array_iterator it) = NULL;-mlx_map_string_to_string (*mlx_map_string_to_string_new_ptr)(void) = NULL;-int (*mlx_map_string_to_string_set_ptr)(mlx_map_string_to_string* map, const mlx_map_string_to_string src) = NULL;-int (*mlx_map_string_to_string_free_ptr)(mlx_map_string_to_string map) = NULL;-int (*mlx_map_string_to_string_insert_ptr)(mlx_map_string_to_string map, const char* key, const char* value) = NULL;-int (*mlx_map_string_to_string_get_ptr)(const char** value, const mlx_map_string_to_string map, const char* key) = NULL;-mlx_map_string_to_string_iterator (*mlx_map_string_to_string_iterator_new_ptr)(mlx_map_string_to_string map) = NULL;-int (*mlx_map_string_to_string_iterator_free_ptr)(mlx_map_string_to_string_iterator it) = NULL;-int (*mlx_map_string_to_string_iterator_next_ptr)(const char** key, const char** value, mlx_map_string_to_string_iterator it) = NULL;-int (*mlx_clear_cache_ptr)(void) = NULL;-int (*mlx_get_active_memory_ptr)(size_t* res) = NULL;-int (*mlx_get_cache_memory_ptr)(size_t* res) = NULL;-int (*mlx_get_memory_limit_ptr)(size_t* res) = NULL;-int (*mlx_get_peak_memory_ptr)(size_t* res) = NULL;-int (*mlx_reset_peak_memory_ptr)(void) = NULL;-int (*mlx_set_cache_limit_ptr)(size_t* res, size_t limit) = NULL;-int (*mlx_set_memory_limit_ptr)(size_t* res, size_t limit) = NULL;-int (*mlx_set_wired_limit_ptr)(size_t* res, size_t limit) = NULL;-int (*mlx_metal_is_available_ptr)(bool* res) = NULL;-int (*mlx_metal_start_capture_ptr)(const char* path) = NULL;-int (*mlx_metal_stop_capture_ptr)(void) = NULL;-int (*mlx_abs_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_add_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_addmm_ptr)(mlx_array* res, const mlx_array c, const mlx_array a, const mlx_array b, float alpha, float beta, const mlx_stream s) = NULL;-int (*mlx_all_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_all_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_all_ptr)(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_allclose_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, double rtol, double atol, bool equal_nan, const mlx_stream s) = NULL;-int (*mlx_any_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_any_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_any_ptr)(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_arange_ptr)(mlx_array* res, double start, double stop, double step, mlx_dtype dtype, const mlx_stream s) = NULL;-int (*mlx_arccos_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_arccosh_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_arcsin_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_arcsinh_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_arctan_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_arctan2_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_arctanh_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_argmax_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_argmax_ptr)(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_argmin_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_argmin_ptr)(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_argpartition_axis_ptr)(mlx_array* res, const mlx_array a, int kth, int axis, const mlx_stream s) = NULL;-int (*mlx_argpartition_ptr)(mlx_array* res, const mlx_array a, int kth, const mlx_stream s) = NULL;-int (*mlx_argsort_axis_ptr)(mlx_array* res, const mlx_array a, int axis, const mlx_stream s) = NULL;-int (*mlx_argsort_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_array_equal_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, bool equal_nan, const mlx_stream s) = NULL;-int (*mlx_as_strided_ptr)(mlx_array* res, const mlx_array a, const int* shape, size_t shape_num, const int64_t* strides, size_t strides_num, size_t offset, const mlx_stream s) = NULL;-int (*mlx_astype_ptr)(mlx_array* res, const mlx_array a, mlx_dtype dtype, const mlx_stream s) = NULL;-int (*mlx_atleast_1d_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_atleast_2d_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_atleast_3d_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_bartlett_ptr)(mlx_array* res, int M, const mlx_stream s) = NULL;-int (*mlx_bitwise_and_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_bitwise_invert_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_bitwise_or_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_bitwise_xor_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_blackman_ptr)(mlx_array* res, int M, const mlx_stream s) = NULL;-int (*mlx_block_masked_mm_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, int block_size, const mlx_array mask_out , const mlx_array mask_lhs , const mlx_array mask_rhs , const mlx_stream s) = NULL;-int (*mlx_broadcast_arrays_ptr)(mlx_vector_array* res, const mlx_vector_array inputs, const mlx_stream s) = NULL;-int (*mlx_broadcast_to_ptr)(mlx_array* res, const mlx_array a, const int* shape, size_t shape_num, const mlx_stream s) = NULL;-int (*mlx_ceil_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_clip_ptr)(mlx_array* res, const mlx_array a, const mlx_array a_min , const mlx_array a_max , const mlx_stream s) = NULL;-int (*mlx_concatenate_axis_ptr)(mlx_array* res, const mlx_vector_array arrays, int axis, const mlx_stream s) = NULL;-int (*mlx_concatenate_ptr)(mlx_array* res, const mlx_vector_array arrays, const mlx_stream s) = NULL;-int (*mlx_conjugate_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_contiguous_ptr)(mlx_array* res, const mlx_array a, bool allow_col_major, const mlx_stream s) = NULL;-int (*mlx_conv1d_ptr)(mlx_array* res, const mlx_array input, const mlx_array weight, int stride, int padding, int dilation, int groups, const mlx_stream s) = NULL;-int (*mlx_conv2d_ptr)(mlx_array* res, const mlx_array input, const mlx_array weight, int stride_0, int stride_1, int padding_0, int padding_1, int dilation_0, int dilation_1, int groups, const mlx_stream s) = NULL;-int (*mlx_conv3d_ptr)(mlx_array* res, const mlx_array input, const mlx_array weight, int stride_0, int stride_1, int stride_2, int padding_0, int padding_1, int padding_2, int dilation_0, int dilation_1, int dilation_2, int groups, const mlx_stream s) = NULL;-int (*mlx_conv_general_ptr)(mlx_array* res, const mlx_array input, const mlx_array weight, const int* stride, size_t stride_num, const int* padding_lo, size_t padding_lo_num, const int* padding_hi, size_t padding_hi_num, const int* kernel_dilation, size_t kernel_dilation_num, const int* input_dilation, size_t input_dilation_num, int groups, bool flip, const mlx_stream s) = NULL;-int (*mlx_conv_transpose1d_ptr)(mlx_array* res, const mlx_array input, const mlx_array weight, int stride, int padding, int dilation, int output_padding, int groups, const mlx_stream s) = NULL;-int (*mlx_conv_transpose2d_ptr)(mlx_array* res, const mlx_array input, const mlx_array weight, int stride_0, int stride_1, int padding_0, int padding_1, int dilation_0, int dilation_1, int output_padding_0, int output_padding_1, int groups, const mlx_stream s) = NULL;-int (*mlx_conv_transpose3d_ptr)(mlx_array* res, const mlx_array input, const mlx_array weight, int stride_0, int stride_1, int stride_2, int padding_0, int padding_1, int padding_2, int dilation_0, int dilation_1, int dilation_2, int output_padding_0, int output_padding_1, int output_padding_2, int groups, const mlx_stream s) = NULL;-int (*mlx_copy_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_cos_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_cosh_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_cummax_ptr)(mlx_array* res, const mlx_array a, int axis, bool reverse, bool inclusive, const mlx_stream s) = NULL;-int (*mlx_cummin_ptr)(mlx_array* res, const mlx_array a, int axis, bool reverse, bool inclusive, const mlx_stream s) = NULL;-int (*mlx_cumprod_ptr)(mlx_array* res, const mlx_array a, int axis, bool reverse, bool inclusive, const mlx_stream s) = NULL;-int (*mlx_cumsum_ptr)(mlx_array* res, const mlx_array a, int axis, bool reverse, bool inclusive, const mlx_stream s) = NULL;-int (*mlx_degrees_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_depends_ptr)(mlx_vector_array* res, const mlx_vector_array inputs, const mlx_vector_array dependencies) = NULL;-int (*mlx_dequantize_ptr)(mlx_array* res, const mlx_array w, const mlx_array scales, const mlx_array biases , mlx_optional_int group_size, mlx_optional_int bits, const char* mode, const mlx_array global_scale , mlx_optional_dtype dtype, const mlx_stream s) = NULL;-int (*mlx_diag_ptr)(mlx_array* res, const mlx_array a, int k, const mlx_stream s) = NULL;-int (*mlx_diagonal_ptr)(mlx_array* res, const mlx_array a, int offset, int axis1, int axis2, const mlx_stream s) = NULL;-int (*mlx_divide_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_divmod_ptr)(mlx_vector_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_einsum_ptr)(mlx_array* res, const char* subscripts, const mlx_vector_array operands, const mlx_stream s) = NULL;-int (*mlx_equal_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_erf_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_erfinv_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_exp_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_expand_dims_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const mlx_stream s) = NULL;-int (*mlx_expand_dims_ptr)(mlx_array* res, const mlx_array a, int axis, const mlx_stream s) = NULL;-int (*mlx_expm1_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_eye_ptr)(mlx_array* res, int n, int m, int k, mlx_dtype dtype, const mlx_stream s) = NULL;-int (*mlx_flatten_ptr)(mlx_array* res, const mlx_array a, int start_axis, int end_axis, const mlx_stream s) = NULL;-int (*mlx_floor_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_floor_divide_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_from_fp8_ptr)(mlx_array* res, const mlx_array x, mlx_dtype dtype, const mlx_stream s) = NULL;-int (*mlx_full_ptr)(mlx_array* res, const int* shape, size_t shape_num, const mlx_array vals, mlx_dtype dtype, const mlx_stream s) = NULL;-int (*mlx_full_like_ptr)(mlx_array* res, const mlx_array a, const mlx_array vals, mlx_dtype dtype, const mlx_stream s) = NULL;-int (*mlx_gather_ptr)(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const int* axes, size_t axes_num, const int* slice_sizes, size_t slice_sizes_num, const mlx_stream s) = NULL;-int (*mlx_gather_single_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, int axis, const int* slice_sizes, size_t slice_sizes_num, const mlx_stream s) = NULL;-int (*mlx_gather_mm_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_array lhs_indices , const mlx_array rhs_indices , bool sorted_indices, const mlx_stream s) = NULL;-int (*mlx_gather_qmm_ptr)(mlx_array* res, const mlx_array x, const mlx_array w, const mlx_array scales, const mlx_array biases , const mlx_array lhs_indices , const mlx_array rhs_indices , bool transpose, mlx_optional_int group_size, mlx_optional_int bits, const char* mode, bool sorted_indices, const mlx_stream s) = NULL;-int (*mlx_greater_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_greater_equal_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_hadamard_transform_ptr)(mlx_array* res, const mlx_array a, mlx_optional_float scale, const mlx_stream s) = NULL;-int (*mlx_hamming_ptr)(mlx_array* res, int M, const mlx_stream s) = NULL;-int (*mlx_hanning_ptr)(mlx_array* res, int M, const mlx_stream s) = NULL;-int (*mlx_identity_ptr)(mlx_array* res, int n, mlx_dtype dtype, const mlx_stream s) = NULL;-int (*mlx_imag_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_inner_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_isclose_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, double rtol, double atol, bool equal_nan, const mlx_stream s) = NULL;-int (*mlx_isfinite_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_isinf_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_isnan_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_isneginf_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_isposinf_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_kron_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_left_shift_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_less_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_less_equal_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_linspace_ptr)(mlx_array* res, double start, double stop, int num, mlx_dtype dtype, const mlx_stream s) = NULL;-int (*mlx_log_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_log10_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_log1p_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_log2_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_logaddexp_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_logcumsumexp_ptr)(mlx_array* res, const mlx_array a, int axis, bool reverse, bool inclusive, const mlx_stream s) = NULL;-int (*mlx_logical_and_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_logical_not_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_logical_or_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_logsumexp_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_logsumexp_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_logsumexp_ptr)(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_masked_scatter_ptr)(mlx_array* res, const mlx_array a, const mlx_array mask, const mlx_array src, const mlx_stream s) = NULL;-int (*mlx_matmul_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_max_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_max_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_max_ptr)(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_maximum_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_mean_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_mean_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_mean_ptr)(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_median_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_meshgrid_ptr)(mlx_vector_array* res, const mlx_vector_array arrays, bool sparse, const char* indexing, const mlx_stream s) = NULL;-int (*mlx_min_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_min_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_min_ptr)(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_minimum_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_moveaxis_ptr)(mlx_array* res, const mlx_array a, int source, int destination, const mlx_stream s) = NULL;-int (*mlx_multiply_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_nan_to_num_ptr)(mlx_array* res, const mlx_array a, float nan, mlx_optional_float posinf, mlx_optional_float neginf, const mlx_stream s) = NULL;-int (*mlx_negative_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_not_equal_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_number_of_elements_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool inverted, mlx_dtype dtype, const mlx_stream s) = NULL;-int (*mlx_ones_ptr)(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_stream s) = NULL;-int (*mlx_ones_like_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_outer_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_pad_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const int* low_pad_size, size_t low_pad_size_num, const int* high_pad_size, size_t high_pad_size_num, const mlx_array pad_value, const char* mode, const mlx_stream s) = NULL;-int (*mlx_pad_symmetric_ptr)(mlx_array* res, const mlx_array a, int pad_width, const mlx_array pad_value, const char* mode, const mlx_stream s) = NULL;-int (*mlx_partition_axis_ptr)(mlx_array* res, const mlx_array a, int kth, int axis, const mlx_stream s) = NULL;-int (*mlx_partition_ptr)(mlx_array* res, const mlx_array a, int kth, const mlx_stream s) = NULL;-int (*mlx_power_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_prod_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_prod_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_prod_ptr)(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_put_along_axis_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array values, int axis, const mlx_stream s) = NULL;-int (*mlx_qqmm_ptr)(mlx_array* res, const mlx_array x, const mlx_array w, const mlx_array w_scales , mlx_optional_int group_size, mlx_optional_int bits, const char* mode, const mlx_array global_scale_x , const mlx_array global_scale_w , const mlx_stream s) = NULL;-int (*mlx_quantize_ptr)(mlx_vector_array* res, const mlx_array w, mlx_optional_int group_size, mlx_optional_int bits, const char* mode, const mlx_array global_scale , const mlx_stream s) = NULL;-int (*mlx_quantized_matmul_ptr)(mlx_array* res, const mlx_array x, const mlx_array w, const mlx_array scales, const mlx_array biases , bool transpose, mlx_optional_int group_size, mlx_optional_int bits, const char* mode, const mlx_stream s) = NULL;-int (*mlx_radians_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_real_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_reciprocal_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_remainder_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_repeat_axis_ptr)(mlx_array* res, const mlx_array arr, int repeats, int axis, const mlx_stream s) = NULL;-int (*mlx_repeat_ptr)(mlx_array* res, const mlx_array arr, int repeats, const mlx_stream s) = NULL;-int (*mlx_reshape_ptr)(mlx_array* res, const mlx_array a, const int* shape, size_t shape_num, const mlx_stream s) = NULL;-int (*mlx_right_shift_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_roll_axis_ptr)(mlx_array* res, const mlx_array a, const int* shift, size_t shift_num, int axis, const mlx_stream s) = NULL;-int (*mlx_roll_axes_ptr)(mlx_array* res, const mlx_array a, const int* shift, size_t shift_num, const int* axes, size_t axes_num, const mlx_stream s) = NULL;-int (*mlx_roll_ptr)(mlx_array* res, const mlx_array a, const int* shift, size_t shift_num, const mlx_stream s) = NULL;-int (*mlx_round_ptr)(mlx_array* res, const mlx_array a, int decimals, const mlx_stream s) = NULL;-int (*mlx_rsqrt_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_scatter_ptr)(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const mlx_array updates, const int* axes, size_t axes_num, const mlx_stream s) = NULL;-int (*mlx_scatter_single_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array updates, int axis, const mlx_stream s) = NULL;-int (*mlx_scatter_add_ptr)(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const mlx_array updates, const int* axes, size_t axes_num, const mlx_stream s) = NULL;-int (*mlx_scatter_add_single_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array updates, int axis, const mlx_stream s) = NULL;-int (*mlx_scatter_add_axis_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array values, int axis, const mlx_stream s) = NULL;-int (*mlx_scatter_max_ptr)(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const mlx_array updates, const int* axes, size_t axes_num, const mlx_stream s) = NULL;-int (*mlx_scatter_max_single_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array updates, int axis, const mlx_stream s) = NULL;-int (*mlx_scatter_min_ptr)(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const mlx_array updates, const int* axes, size_t axes_num, const mlx_stream s) = NULL;-int (*mlx_scatter_min_single_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array updates, int axis, const mlx_stream s) = NULL;-int (*mlx_scatter_prod_ptr)(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const mlx_array updates, const int* axes, size_t axes_num, const mlx_stream s) = NULL;-int (*mlx_scatter_prod_single_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array updates, int axis, const mlx_stream s) = NULL;-int (*mlx_segmented_mm_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_array segments, const mlx_stream s) = NULL;-int (*mlx_sigmoid_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_sign_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_sin_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_sinh_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_slice_ptr)(mlx_array* res, const mlx_array a, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s) = NULL;-int (*mlx_slice_dynamic_ptr)(mlx_array* res, const mlx_array a, const mlx_array start, const int* axes, size_t axes_num, const int* slice_size, size_t slice_size_num, const mlx_stream s) = NULL;-int (*mlx_slice_update_ptr)(mlx_array* res, const mlx_array src, const mlx_array update, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s) = NULL;-int (*mlx_slice_update_dynamic_ptr)(mlx_array* res, const mlx_array src, const mlx_array update, const mlx_array start, const int* axes, size_t axes_num, const mlx_stream s) = NULL;-int (*mlx_slice_update_add_ptr)(mlx_array* res, const mlx_array src, const mlx_array update, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s) = NULL;-int (*mlx_slice_update_max_ptr)(mlx_array* res, const mlx_array src, const mlx_array update, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s) = NULL;-int (*mlx_slice_update_min_ptr)(mlx_array* res, const mlx_array src, const mlx_array update, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s) = NULL;-int (*mlx_slice_update_prod_ptr)(mlx_array* res, const mlx_array src, const mlx_array update, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s) = NULL;-int (*mlx_softmax_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool precise, const mlx_stream s) = NULL;-int (*mlx_softmax_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool precise, const mlx_stream s) = NULL;-int (*mlx_softmax_ptr)(mlx_array* res, const mlx_array a, bool precise, const mlx_stream s) = NULL;-int (*mlx_sort_axis_ptr)(mlx_array* res, const mlx_array a, int axis, const mlx_stream s) = NULL;-int (*mlx_sort_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_split_ptr)(mlx_vector_array* res, const mlx_array a, int num_splits, int axis, const mlx_stream s) = NULL;-int (*mlx_split_sections_ptr)(mlx_vector_array* res, const mlx_array a, const int* indices, size_t indices_num, int axis, const mlx_stream s) = NULL;-int (*mlx_sqrt_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_square_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_squeeze_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const mlx_stream s) = NULL;-int (*mlx_squeeze_axis_ptr)(mlx_array* res, const mlx_array a, int axis, const mlx_stream s) = NULL;-int (*mlx_squeeze_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_stack_axis_ptr)(mlx_array* res, const mlx_vector_array arrays, int axis, const mlx_stream s) = NULL;-int (*mlx_stack_ptr)(mlx_array* res, const mlx_vector_array arrays, const mlx_stream s) = NULL;-int (*mlx_std_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, int ddof, const mlx_stream s) = NULL;-int (*mlx_std_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, int ddof, const mlx_stream s) = NULL;-int (*mlx_std_ptr)(mlx_array* res, const mlx_array a, bool keepdims, int ddof, const mlx_stream s) = NULL;-int (*mlx_stop_gradient_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_subtract_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) = NULL;-int (*mlx_sum_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_sum_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_sum_ptr)(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s) = NULL;-int (*mlx_swapaxes_ptr)(mlx_array* res, const mlx_array a, int axis1, int axis2, const mlx_stream s) = NULL;-int (*mlx_take_axis_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, int axis, const mlx_stream s) = NULL;-int (*mlx_take_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_stream s) = NULL;-int (*mlx_take_along_axis_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, int axis, const mlx_stream s) = NULL;-int (*mlx_tan_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_tanh_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_tensordot_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const int* axes_a, size_t axes_a_num, const int* axes_b, size_t axes_b_num, const mlx_stream s) = NULL;-int (*mlx_tensordot_axis_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, int axis, const mlx_stream s) = NULL;-int (*mlx_tile_ptr)(mlx_array* res, const mlx_array arr, const int* reps, size_t reps_num, const mlx_stream s) = NULL;-int (*mlx_to_fp8_ptr)(mlx_array* res, const mlx_array x, const mlx_stream s) = NULL;-int (*mlx_topk_axis_ptr)(mlx_array* res, const mlx_array a, int k, int axis, const mlx_stream s) = NULL;-int (*mlx_topk_ptr)(mlx_array* res, const mlx_array a, int k, const mlx_stream s) = NULL;-int (*mlx_trace_ptr)(mlx_array* res, const mlx_array a, int offset, int axis1, int axis2, mlx_dtype dtype, const mlx_stream s) = NULL;-int (*mlx_transpose_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const mlx_stream s) = NULL;-int (*mlx_transpose_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_tri_ptr)(mlx_array* res, int n, int m, int k, mlx_dtype type, const mlx_stream s) = NULL;-int (*mlx_tril_ptr)(mlx_array* res, const mlx_array x, int k, const mlx_stream s) = NULL;-int (*mlx_triu_ptr)(mlx_array* res, const mlx_array x, int k, const mlx_stream s) = NULL;-int (*mlx_unflatten_ptr)(mlx_array* res, const mlx_array a, int axis, const int* shape, size_t shape_num, const mlx_stream s) = NULL;-int (*mlx_var_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, int ddof, const mlx_stream s) = NULL;-int (*mlx_var_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, int ddof, const mlx_stream s) = NULL;-int (*mlx_var_ptr)(mlx_array* res, const mlx_array a, bool keepdims, int ddof, const mlx_stream s) = NULL;-int (*mlx_view_ptr)(mlx_array* res, const mlx_array a, mlx_dtype dtype, const mlx_stream s) = NULL;-int (*mlx_where_ptr)(mlx_array* res, const mlx_array condition, const mlx_array x, const mlx_array y, const mlx_stream s) = NULL;-int (*mlx_zeros_ptr)(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_stream s) = NULL;-int (*mlx_zeros_like_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s) = NULL;-int (*mlx_random_bernoulli_ptr)(mlx_array* res, const mlx_array p, const int* shape, size_t shape_num, const mlx_array key , const mlx_stream s) = NULL;-int (*mlx_random_bits_ptr)(mlx_array* res, const int* shape, size_t shape_num, int width, const mlx_array key , const mlx_stream s) = NULL;-int (*mlx_random_categorical_shape_ptr)(mlx_array* res, const mlx_array logits, int axis, const int* shape, size_t shape_num, const mlx_array key , const mlx_stream s) = NULL;-int (*mlx_random_categorical_num_samples_ptr)(mlx_array* res, const mlx_array logits_, int axis, int num_samples, const mlx_array key , const mlx_stream s) = NULL;-int (*mlx_random_categorical_ptr)(mlx_array* res, const mlx_array logits, int axis, const mlx_array key , const mlx_stream s) = NULL;-int (*mlx_random_gumbel_ptr)(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array key , const mlx_stream s) = NULL;-int (*mlx_random_key_ptr)(mlx_array* res, uint64_t seed) = NULL;-int (*mlx_random_laplace_ptr)(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, float loc, float scale, const mlx_array key , const mlx_stream s) = NULL;-int (*mlx_random_multivariate_normal_ptr)(mlx_array* res, const mlx_array mean, const mlx_array cov, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array key , const mlx_stream s) = NULL;-int (*mlx_random_normal_broadcast_ptr)(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array loc , const mlx_array scale , const mlx_array key , const mlx_stream s) = NULL;-int (*mlx_random_normal_ptr)(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, float loc, float scale, const mlx_array key , const mlx_stream s) = NULL;-int (*mlx_random_permutation_ptr)(mlx_array* res, const mlx_array x, int axis, const mlx_array key , const mlx_stream s) = NULL;-int (*mlx_random_permutation_arange_ptr)(mlx_array* res, int x, const mlx_array key , const mlx_stream s) = NULL;-int (*mlx_random_randint_ptr)(mlx_array* res, const mlx_array low, const mlx_array high, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array key , const mlx_stream s) = NULL;-int (*mlx_random_seed_ptr)(uint64_t seed) = NULL;-int (*mlx_random_split_num_ptr)(mlx_array* res, const mlx_array key, int num, const mlx_stream s) = NULL;-int (*mlx_random_split_ptr)(mlx_array* res_0, mlx_array* res_1, const mlx_array key, const mlx_stream s) = NULL;-int (*mlx_random_truncated_normal_ptr)(mlx_array* res, const mlx_array lower, const mlx_array upper, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array key , const mlx_stream s) = NULL;-int (*mlx_random_uniform_ptr)(mlx_array* res, const mlx_array low, const mlx_array high, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array key , const mlx_stream s) = NULL;-mlx_stream (*mlx_stream_new_ptr)(void) = NULL;-mlx_stream (*mlx_stream_new_device_ptr)(mlx_device dev) = NULL;-int (*mlx_stream_set_ptr)(mlx_stream* stream, const mlx_stream src) = NULL;-int (*mlx_stream_free_ptr)(mlx_stream stream) = NULL;-int (*mlx_stream_tostring_ptr)(mlx_string* str, mlx_stream stream) = NULL;-bool (*mlx_stream_equal_ptr)(mlx_stream lhs, mlx_stream rhs) = NULL;-int (*mlx_stream_get_device_ptr)(mlx_device* dev, mlx_stream stream) = NULL;-int (*mlx_stream_get_index_ptr)(int* index, mlx_stream stream) = NULL;-int (*mlx_synchronize_ptr)(mlx_stream stream) = NULL;-int (*mlx_get_default_stream_ptr)(mlx_stream* stream, mlx_device dev) = NULL;-int (*mlx_set_default_stream_ptr)(mlx_stream stream) = NULL;-mlx_stream (*mlx_default_cpu_stream_new_ptr)(void) = NULL;-mlx_stream (*mlx_default_gpu_stream_new_ptr)(void) = NULL;-mlx_string (*mlx_string_new_ptr)(void) = NULL;-mlx_string (*mlx_string_new_data_ptr)(const char* str) = NULL;-int (*mlx_string_set_ptr)(mlx_string* str, const mlx_string src) = NULL;-const char* (*mlx_string_data_ptr)(mlx_string str) = NULL;-int (*mlx_string_free_ptr)(mlx_string str) = NULL;-int (*mlx_async_eval_ptr)(const mlx_vector_array outputs) = NULL;-int (*mlx_checkpoint_ptr)(mlx_closure* res, const mlx_closure fun) = NULL;-int (*mlx_custom_function_ptr)(mlx_closure* res, const mlx_closure fun, const mlx_closure_custom fun_vjp , const mlx_closure_custom_jvp fun_jvp , const mlx_closure_custom_vmap fun_vmap) = NULL;-int (*mlx_custom_vjp_ptr)(mlx_closure* res, const mlx_closure fun, const mlx_closure_custom fun_vjp) = NULL;-int (*mlx_eval_ptr)(const mlx_vector_array outputs) = NULL;-int (*mlx_jvp_ptr)(mlx_vector_array* res_0, mlx_vector_array* res_1, const mlx_closure fun, const mlx_vector_array primals, const mlx_vector_array tangents) = NULL;-int (*mlx_value_and_grad_ptr)(mlx_closure_value_and_grad* res, const mlx_closure fun, const int* argnums, size_t argnums_num) = NULL;-int (*mlx_vjp_ptr)(mlx_vector_array* res_0, mlx_vector_array* res_1, const mlx_closure fun, const mlx_vector_array primals, const mlx_vector_array cotangents) = NULL;-int (*mlx_detail_vmap_replace_ptr)(mlx_vector_array* res, const mlx_vector_array inputs, const mlx_vector_array s_inputs, const mlx_vector_array s_outputs, const int* in_axes, size_t in_axes_num, const int* out_axes, size_t out_axes_num) = NULL;-int (*mlx_detail_vmap_trace_ptr)(mlx_vector_array* res_0, mlx_vector_array* res_1, const mlx_closure fun, const mlx_vector_array inputs, const int* in_axes, size_t in_axes_num) = NULL;-mlx_vector_array (*mlx_vector_array_new_ptr)(void) = NULL;-int (*mlx_vector_array_set_ptr)(mlx_vector_array* vec, const mlx_vector_array src) = NULL;-int (*mlx_vector_array_free_ptr)(mlx_vector_array vec) = NULL;-mlx_vector_array (*mlx_vector_array_new_data_ptr)(const mlx_array* data, size_t size) = NULL;-mlx_vector_array (*mlx_vector_array_new_value_ptr)(const mlx_array val) = NULL;-int (*mlx_vector_array_set_data_ptr)(mlx_vector_array* vec, const mlx_array* data, size_t size) = NULL;-int (*mlx_vector_array_set_value_ptr)(mlx_vector_array* vec, const mlx_array val) = NULL;-int (*mlx_vector_array_append_data_ptr)(mlx_vector_array vec, const mlx_array* data, size_t size) = NULL;-int (*mlx_vector_array_append_value_ptr)(mlx_vector_array vec, const mlx_array val) = NULL;-size_t (*mlx_vector_array_size_ptr)(mlx_vector_array vec) = NULL;-int (*mlx_vector_array_get_ptr)(mlx_array* res, const mlx_vector_array vec, size_t idx) = NULL;-mlx_vector_vector_array (*mlx_vector_vector_array_new_ptr)(void) = NULL;-int (*mlx_vector_vector_array_set_ptr)(mlx_vector_vector_array* vec, const mlx_vector_vector_array src) = NULL;-int (*mlx_vector_vector_array_free_ptr)(mlx_vector_vector_array vec) = NULL;-mlx_vector_vector_array (*mlx_vector_vector_array_new_data_ptr)(const mlx_vector_array* data, size_t size) = NULL;-mlx_vector_vector_array (*mlx_vector_vector_array_new_value_ptr)(const mlx_vector_array val) = NULL;-int (*mlx_vector_vector_array_set_data_ptr)(mlx_vector_vector_array* vec, const mlx_vector_array* data, size_t size) = NULL;-int (*mlx_vector_vector_array_set_value_ptr)(mlx_vector_vector_array* vec, const mlx_vector_array val) = NULL;-int (*mlx_vector_vector_array_append_data_ptr)(mlx_vector_vector_array vec, const mlx_vector_array* data, size_t size) = NULL;-int (*mlx_vector_vector_array_append_value_ptr)(mlx_vector_vector_array vec, const mlx_vector_array val) = NULL;-size_t (*mlx_vector_vector_array_size_ptr)(mlx_vector_vector_array vec) = NULL;-int (*mlx_vector_vector_array_get_ptr)(mlx_vector_array* res, const mlx_vector_vector_array vec, size_t idx) = NULL;-mlx_vector_int (*mlx_vector_int_new_ptr)(void) = NULL;-int (*mlx_vector_int_set_ptr)(mlx_vector_int* vec, const mlx_vector_int src) = NULL;-int (*mlx_vector_int_free_ptr)(mlx_vector_int vec) = NULL;-mlx_vector_int (*mlx_vector_int_new_data_ptr)(int* data, size_t size) = NULL;-mlx_vector_int (*mlx_vector_int_new_value_ptr)(int val) = NULL;-int (*mlx_vector_int_set_data_ptr)(mlx_vector_int* vec, int* data, size_t size) = NULL;-int (*mlx_vector_int_set_value_ptr)(mlx_vector_int* vec, int val) = NULL;-int (*mlx_vector_int_append_data_ptr)(mlx_vector_int vec, int* data, size_t size) = NULL;-int (*mlx_vector_int_append_value_ptr)(mlx_vector_int vec, int val) = NULL;-size_t (*mlx_vector_int_size_ptr)(mlx_vector_int vec) = NULL;-int (*mlx_vector_int_get_ptr)(int* res, const mlx_vector_int vec, size_t idx) = NULL;-mlx_vector_string (*mlx_vector_string_new_ptr)(void) = NULL;-int (*mlx_vector_string_set_ptr)(mlx_vector_string* vec, const mlx_vector_string src) = NULL;-int (*mlx_vector_string_free_ptr)(mlx_vector_string vec) = NULL;-mlx_vector_string (*mlx_vector_string_new_data_ptr)(const char** data, size_t size) = NULL;-mlx_vector_string (*mlx_vector_string_new_value_ptr)(const char* val) = NULL;-int (*mlx_vector_string_set_data_ptr)(mlx_vector_string* vec, const char** data, size_t size) = NULL;-int (*mlx_vector_string_set_value_ptr)(mlx_vector_string* vec, const char* val) = NULL;-int (*mlx_vector_string_append_data_ptr)(mlx_vector_string vec, const char** data, size_t size) = NULL;-int (*mlx_vector_string_append_value_ptr)(mlx_vector_string vec, const char* val) = NULL;-size_t (*mlx_vector_string_size_ptr)(mlx_vector_string vec) = NULL;-int (*mlx_vector_string_get_ptr)(char** res, const mlx_vector_string vec, size_t idx) = NULL;-int (*mlx_version_ptr)(mlx_string* str_) = NULL;--// Initialize all function pointers-int mlx_load_functions(void* handle) {- if (handle == NULL) {- fprintf(stderr, "MLX: Invalid library handle\n");- return -1;- }-- mlx_dtype_size_ptr = GET_SYM(handle, "mlx_dtype_size");- if (mlx_dtype_size_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_dtype_size\n");- return -1;- }- mlx_array_tostring_ptr = GET_SYM(handle, "mlx_array_tostring");- if (mlx_array_tostring_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_tostring\n");- return -1;- }- mlx_array_new_ptr = GET_SYM(handle, "mlx_array_new");- if (mlx_array_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_new\n");- return -1;- }- mlx_array_free_ptr = GET_SYM(handle, "mlx_array_free");- if (mlx_array_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_free\n");- return -1;- }- mlx_array_new_bool_ptr = GET_SYM(handle, "mlx_array_new_bool");- if (mlx_array_new_bool_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_new_bool\n");- return -1;- }- mlx_array_new_int_ptr = GET_SYM(handle, "mlx_array_new_int");- if (mlx_array_new_int_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_new_int\n");- return -1;- }- mlx_array_new_float32_ptr = GET_SYM(handle, "mlx_array_new_float32");- if (mlx_array_new_float32_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_new_float32\n");- return -1;- }- mlx_array_new_float_ptr = GET_SYM(handle, "mlx_array_new_float");- if (mlx_array_new_float_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_new_float\n");- return -1;- }- mlx_array_new_float64_ptr = GET_SYM(handle, "mlx_array_new_float64");- if (mlx_array_new_float64_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_new_float64\n");- return -1;- }- mlx_array_new_double_ptr = GET_SYM(handle, "mlx_array_new_double");- if (mlx_array_new_double_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_new_double\n");- return -1;- }- mlx_array_new_complex_ptr = GET_SYM(handle, "mlx_array_new_complex");- if (mlx_array_new_complex_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_new_complex\n");- return -1;- }- mlx_array_new_data_ptr = GET_SYM(handle, "mlx_array_new_data");- if (mlx_array_new_data_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_new_data\n");- return -1;- }- mlx_array_new_data_managed_ptr = GET_SYM(handle, "mlx_array_new_data_managed");- if (mlx_array_new_data_managed_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_new_data_managed\n");- return -1;- }- mlx_array_new_data_managed_payload_ptr = GET_SYM(handle, "mlx_array_new_data_managed_payload");- if (mlx_array_new_data_managed_payload_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_new_data_managed_payload\n");- return -1;- }- mlx_array_set_ptr = GET_SYM(handle, "mlx_array_set");- if (mlx_array_set_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_set\n");- return -1;- }- mlx_array_set_bool_ptr = GET_SYM(handle, "mlx_array_set_bool");- if (mlx_array_set_bool_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_set_bool\n");- return -1;- }- mlx_array_set_int_ptr = GET_SYM(handle, "mlx_array_set_int");- if (mlx_array_set_int_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_set_int\n");- return -1;- }- mlx_array_set_float32_ptr = GET_SYM(handle, "mlx_array_set_float32");- if (mlx_array_set_float32_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_set_float32\n");- return -1;- }- mlx_array_set_float_ptr = GET_SYM(handle, "mlx_array_set_float");- if (mlx_array_set_float_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_set_float\n");- return -1;- }- mlx_array_set_float64_ptr = GET_SYM(handle, "mlx_array_set_float64");- if (mlx_array_set_float64_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_set_float64\n");- return -1;- }- mlx_array_set_double_ptr = GET_SYM(handle, "mlx_array_set_double");- if (mlx_array_set_double_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_set_double\n");- return -1;- }- mlx_array_set_complex_ptr = GET_SYM(handle, "mlx_array_set_complex");- if (mlx_array_set_complex_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_set_complex\n");- return -1;- }- mlx_array_set_data_ptr = GET_SYM(handle, "mlx_array_set_data");- if (mlx_array_set_data_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_set_data\n");- return -1;- }- mlx_array_itemsize_ptr = GET_SYM(handle, "mlx_array_itemsize");- if (mlx_array_itemsize_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_itemsize\n");- return -1;- }- mlx_array_size_ptr = GET_SYM(handle, "mlx_array_size");- if (mlx_array_size_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_size\n");- return -1;- }- mlx_array_nbytes_ptr = GET_SYM(handle, "mlx_array_nbytes");- if (mlx_array_nbytes_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_nbytes\n");- return -1;- }- mlx_array_ndim_ptr = GET_SYM(handle, "mlx_array_ndim");- if (mlx_array_ndim_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_ndim\n");- return -1;- }- mlx_array_shape_ptr = GET_SYM(handle, "mlx_array_shape");- if (mlx_array_shape_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_shape\n");- return -1;- }- mlx_array_strides_ptr = GET_SYM(handle, "mlx_array_strides");- if (mlx_array_strides_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_strides\n");- return -1;- }- mlx_array_dim_ptr = GET_SYM(handle, "mlx_array_dim");- if (mlx_array_dim_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_dim\n");- return -1;- }- mlx_array_dtype_ptr = GET_SYM(handle, "mlx_array_dtype");- if (mlx_array_dtype_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_dtype\n");- return -1;- }- mlx_array_eval_ptr = GET_SYM(handle, "mlx_array_eval");- if (mlx_array_eval_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_eval\n");- return -1;- }- mlx_array_item_bool_ptr = GET_SYM(handle, "mlx_array_item_bool");- if (mlx_array_item_bool_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_item_bool\n");- return -1;- }- mlx_array_item_uint8_ptr = GET_SYM(handle, "mlx_array_item_uint8");- if (mlx_array_item_uint8_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_item_uint8\n");- return -1;- }- mlx_array_item_uint16_ptr = GET_SYM(handle, "mlx_array_item_uint16");- if (mlx_array_item_uint16_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_item_uint16\n");- return -1;- }- mlx_array_item_uint32_ptr = GET_SYM(handle, "mlx_array_item_uint32");- if (mlx_array_item_uint32_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_item_uint32\n");- return -1;- }- mlx_array_item_uint64_ptr = GET_SYM(handle, "mlx_array_item_uint64");- if (mlx_array_item_uint64_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_item_uint64\n");- return -1;- }- mlx_array_item_int8_ptr = GET_SYM(handle, "mlx_array_item_int8");- if (mlx_array_item_int8_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_item_int8\n");- return -1;- }- mlx_array_item_int16_ptr = GET_SYM(handle, "mlx_array_item_int16");- if (mlx_array_item_int16_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_item_int16\n");- return -1;- }- mlx_array_item_int32_ptr = GET_SYM(handle, "mlx_array_item_int32");- if (mlx_array_item_int32_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_item_int32\n");- return -1;- }- mlx_array_item_int64_ptr = GET_SYM(handle, "mlx_array_item_int64");- if (mlx_array_item_int64_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_item_int64\n");- return -1;- }- mlx_array_item_float32_ptr = GET_SYM(handle, "mlx_array_item_float32");- if (mlx_array_item_float32_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_item_float32\n");- return -1;- }- mlx_array_item_float64_ptr = GET_SYM(handle, "mlx_array_item_float64");- if (mlx_array_item_float64_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_item_float64\n");- return -1;- }- mlx_array_item_complex64_ptr = GET_SYM(handle, "mlx_array_item_complex64");- if (mlx_array_item_complex64_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_item_complex64\n");- return -1;- }-#if defined(__aarch64__) || defined(_M_ARM64)- mlx_array_item_float16_ptr = GET_SYM(handle, "mlx_array_item_float16");- if (mlx_array_item_float16_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_item_float16\n");- return -1;- }-#endif-#if defined(__aarch64__) || defined(_M_ARM64)- mlx_array_item_bfloat16_ptr = GET_SYM(handle, "mlx_array_item_bfloat16");- if (mlx_array_item_bfloat16_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_item_bfloat16\n");- return -1;- }-#endif- mlx_array_data_bool_ptr = GET_SYM(handle, "mlx_array_data_bool");- if (mlx_array_data_bool_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_data_bool\n");- return -1;- }- mlx_array_data_uint8_ptr = GET_SYM(handle, "mlx_array_data_uint8");- if (mlx_array_data_uint8_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_data_uint8\n");- return -1;- }- mlx_array_data_uint16_ptr = GET_SYM(handle, "mlx_array_data_uint16");- if (mlx_array_data_uint16_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_data_uint16\n");- return -1;- }- mlx_array_data_uint32_ptr = GET_SYM(handle, "mlx_array_data_uint32");- if (mlx_array_data_uint32_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_data_uint32\n");- return -1;- }- mlx_array_data_uint64_ptr = GET_SYM(handle, "mlx_array_data_uint64");- if (mlx_array_data_uint64_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_data_uint64\n");- return -1;- }- mlx_array_data_int8_ptr = GET_SYM(handle, "mlx_array_data_int8");- if (mlx_array_data_int8_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_data_int8\n");- return -1;- }- mlx_array_data_int16_ptr = GET_SYM(handle, "mlx_array_data_int16");- if (mlx_array_data_int16_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_data_int16\n");- return -1;- }- mlx_array_data_int32_ptr = GET_SYM(handle, "mlx_array_data_int32");- if (mlx_array_data_int32_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_data_int32\n");- return -1;- }- mlx_array_data_int64_ptr = GET_SYM(handle, "mlx_array_data_int64");- if (mlx_array_data_int64_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_data_int64\n");- return -1;- }- mlx_array_data_float32_ptr = GET_SYM(handle, "mlx_array_data_float32");- if (mlx_array_data_float32_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_data_float32\n");- return -1;- }- mlx_array_data_float64_ptr = GET_SYM(handle, "mlx_array_data_float64");- if (mlx_array_data_float64_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_data_float64\n");- return -1;- }- mlx_array_data_complex64_ptr = GET_SYM(handle, "mlx_array_data_complex64");- if (mlx_array_data_complex64_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_data_complex64\n");- return -1;- }-#if defined(__aarch64__) || defined(_M_ARM64)- mlx_array_data_float16_ptr = GET_SYM(handle, "mlx_array_data_float16");- if (mlx_array_data_float16_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_data_float16\n");- return -1;- }-#endif-#if defined(__aarch64__) || defined(_M_ARM64)- mlx_array_data_bfloat16_ptr = GET_SYM(handle, "mlx_array_data_bfloat16");- if (mlx_array_data_bfloat16_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_data_bfloat16\n");- return -1;- }-#endif- _mlx_array_is_available_ptr = GET_SYM(handle, "_mlx_array_is_available");- if (_mlx_array_is_available_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: _mlx_array_is_available\n");- return -1;- }- _mlx_array_wait_ptr = GET_SYM(handle, "_mlx_array_wait");- if (_mlx_array_wait_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: _mlx_array_wait\n");- return -1;- }- _mlx_array_is_contiguous_ptr = GET_SYM(handle, "_mlx_array_is_contiguous");- if (_mlx_array_is_contiguous_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: _mlx_array_is_contiguous\n");- return -1;- }- _mlx_array_is_row_contiguous_ptr = GET_SYM(handle, "_mlx_array_is_row_contiguous");- if (_mlx_array_is_row_contiguous_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: _mlx_array_is_row_contiguous\n");- return -1;- }- _mlx_array_is_col_contiguous_ptr = GET_SYM(handle, "_mlx_array_is_col_contiguous");- if (_mlx_array_is_col_contiguous_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: _mlx_array_is_col_contiguous\n");- return -1;- }- mlx_closure_new_ptr = GET_SYM(handle, "mlx_closure_new");- if (mlx_closure_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_new\n");- return -1;- }- mlx_closure_free_ptr = GET_SYM(handle, "mlx_closure_free");- if (mlx_closure_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_free\n");- return -1;- }- mlx_closure_new_func_ptr = GET_SYM(handle, "mlx_closure_new_func");- if (mlx_closure_new_func_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_new_func\n");- return -1;- }- mlx_closure_new_func_payload_ptr = GET_SYM(handle, "mlx_closure_new_func_payload");- if (mlx_closure_new_func_payload_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_new_func_payload\n");- return -1;- }- mlx_closure_set_ptr = GET_SYM(handle, "mlx_closure_set");- if (mlx_closure_set_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_set\n");- return -1;- }- mlx_closure_apply_ptr = GET_SYM(handle, "mlx_closure_apply");- if (mlx_closure_apply_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_apply\n");- return -1;- }- mlx_closure_new_unary_ptr = GET_SYM(handle, "mlx_closure_new_unary");- if (mlx_closure_new_unary_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_new_unary\n");- return -1;- }- mlx_closure_kwargs_new_ptr = GET_SYM(handle, "mlx_closure_kwargs_new");- if (mlx_closure_kwargs_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_kwargs_new\n");- return -1;- }- mlx_closure_kwargs_free_ptr = GET_SYM(handle, "mlx_closure_kwargs_free");- if (mlx_closure_kwargs_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_kwargs_free\n");- return -1;- }- mlx_closure_kwargs_new_func_ptr = GET_SYM(handle, "mlx_closure_kwargs_new_func");- if (mlx_closure_kwargs_new_func_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_kwargs_new_func\n");- return -1;- }- mlx_closure_kwargs_new_func_payload_ptr = GET_SYM(handle, "mlx_closure_kwargs_new_func_payload");- if (mlx_closure_kwargs_new_func_payload_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_kwargs_new_func_payload\n");- return -1;- }- mlx_closure_kwargs_set_ptr = GET_SYM(handle, "mlx_closure_kwargs_set");- if (mlx_closure_kwargs_set_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_kwargs_set\n");- return -1;- }- mlx_closure_kwargs_apply_ptr = GET_SYM(handle, "mlx_closure_kwargs_apply");- if (mlx_closure_kwargs_apply_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_kwargs_apply\n");- return -1;- }- mlx_closure_value_and_grad_new_ptr = GET_SYM(handle, "mlx_closure_value_and_grad_new");- if (mlx_closure_value_and_grad_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_value_and_grad_new\n");- return -1;- }- mlx_closure_value_and_grad_free_ptr = GET_SYM(handle, "mlx_closure_value_and_grad_free");- if (mlx_closure_value_and_grad_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_value_and_grad_free\n");- return -1;- }- mlx_closure_value_and_grad_new_func_ptr = GET_SYM(handle, "mlx_closure_value_and_grad_new_func");- if (mlx_closure_value_and_grad_new_func_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_value_and_grad_new_func\n");- return -1;- }- mlx_closure_value_and_grad_new_func_payload_ptr = GET_SYM(handle, "mlx_closure_value_and_grad_new_func_payload");- if (mlx_closure_value_and_grad_new_func_payload_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_value_and_grad_new_func_payload\n");- return -1;- }- mlx_closure_value_and_grad_set_ptr = GET_SYM(handle, "mlx_closure_value_and_grad_set");- if (mlx_closure_value_and_grad_set_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_value_and_grad_set\n");- return -1;- }- mlx_closure_value_and_grad_apply_ptr = GET_SYM(handle, "mlx_closure_value_and_grad_apply");- if (mlx_closure_value_and_grad_apply_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_value_and_grad_apply\n");- return -1;- }- mlx_closure_custom_new_ptr = GET_SYM(handle, "mlx_closure_custom_new");- if (mlx_closure_custom_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_custom_new\n");- return -1;- }- mlx_closure_custom_free_ptr = GET_SYM(handle, "mlx_closure_custom_free");- if (mlx_closure_custom_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_custom_free\n");- return -1;- }- mlx_closure_custom_new_func_ptr = GET_SYM(handle, "mlx_closure_custom_new_func");- if (mlx_closure_custom_new_func_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_custom_new_func\n");- return -1;- }- mlx_closure_custom_new_func_payload_ptr = GET_SYM(handle, "mlx_closure_custom_new_func_payload");- if (mlx_closure_custom_new_func_payload_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_custom_new_func_payload\n");- return -1;- }- mlx_closure_custom_set_ptr = GET_SYM(handle, "mlx_closure_custom_set");- if (mlx_closure_custom_set_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_custom_set\n");- return -1;- }- mlx_closure_custom_apply_ptr = GET_SYM(handle, "mlx_closure_custom_apply");- if (mlx_closure_custom_apply_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_custom_apply\n");- return -1;- }- mlx_closure_custom_jvp_new_ptr = GET_SYM(handle, "mlx_closure_custom_jvp_new");- if (mlx_closure_custom_jvp_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_custom_jvp_new\n");- return -1;- }- mlx_closure_custom_jvp_free_ptr = GET_SYM(handle, "mlx_closure_custom_jvp_free");- if (mlx_closure_custom_jvp_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_custom_jvp_free\n");- return -1;- }- mlx_closure_custom_jvp_new_func_ptr = GET_SYM(handle, "mlx_closure_custom_jvp_new_func");- if (mlx_closure_custom_jvp_new_func_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_custom_jvp_new_func\n");- return -1;- }- mlx_closure_custom_jvp_new_func_payload_ptr = GET_SYM(handle, "mlx_closure_custom_jvp_new_func_payload");- if (mlx_closure_custom_jvp_new_func_payload_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_custom_jvp_new_func_payload\n");- return -1;- }- mlx_closure_custom_jvp_set_ptr = GET_SYM(handle, "mlx_closure_custom_jvp_set");- if (mlx_closure_custom_jvp_set_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_custom_jvp_set\n");- return -1;- }- mlx_closure_custom_jvp_apply_ptr = GET_SYM(handle, "mlx_closure_custom_jvp_apply");- if (mlx_closure_custom_jvp_apply_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_custom_jvp_apply\n");- return -1;- }- mlx_closure_custom_vmap_new_ptr = GET_SYM(handle, "mlx_closure_custom_vmap_new");- if (mlx_closure_custom_vmap_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_custom_vmap_new\n");- return -1;- }- mlx_closure_custom_vmap_free_ptr = GET_SYM(handle, "mlx_closure_custom_vmap_free");- if (mlx_closure_custom_vmap_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_custom_vmap_free\n");- return -1;- }- mlx_closure_custom_vmap_new_func_ptr = GET_SYM(handle, "mlx_closure_custom_vmap_new_func");- if (mlx_closure_custom_vmap_new_func_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_custom_vmap_new_func\n");- return -1;- }- mlx_closure_custom_vmap_new_func_payload_ptr = GET_SYM(handle, "mlx_closure_custom_vmap_new_func_payload");- if (mlx_closure_custom_vmap_new_func_payload_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_custom_vmap_new_func_payload\n");- return -1;- }- mlx_closure_custom_vmap_set_ptr = GET_SYM(handle, "mlx_closure_custom_vmap_set");- if (mlx_closure_custom_vmap_set_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_custom_vmap_set\n");- return -1;- }- mlx_closure_custom_vmap_apply_ptr = GET_SYM(handle, "mlx_closure_custom_vmap_apply");- if (mlx_closure_custom_vmap_apply_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_closure_custom_vmap_apply\n");- return -1;- }- mlx_compile_ptr = GET_SYM(handle, "mlx_compile");- if (mlx_compile_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_compile\n");- return -1;- }- mlx_detail_compile_ptr = GET_SYM(handle, "mlx_detail_compile");- if (mlx_detail_compile_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_detail_compile\n");- return -1;- }- mlx_detail_compile_clear_cache_ptr = GET_SYM(handle, "mlx_detail_compile_clear_cache");- if (mlx_detail_compile_clear_cache_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_detail_compile_clear_cache\n");- return -1;- }- mlx_detail_compile_erase_ptr = GET_SYM(handle, "mlx_detail_compile_erase");- if (mlx_detail_compile_erase_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_detail_compile_erase\n");- return -1;- }- mlx_disable_compile_ptr = GET_SYM(handle, "mlx_disable_compile");- if (mlx_disable_compile_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_disable_compile\n");- return -1;- }- mlx_enable_compile_ptr = GET_SYM(handle, "mlx_enable_compile");- if (mlx_enable_compile_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_enable_compile\n");- return -1;- }- mlx_set_compile_mode_ptr = GET_SYM(handle, "mlx_set_compile_mode");- if (mlx_set_compile_mode_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_set_compile_mode\n");- return -1;- }- mlx_cuda_is_available_ptr = GET_SYM(handle, "mlx_cuda_is_available");- if (mlx_cuda_is_available_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_cuda_is_available\n");- return -1;- }- mlx_device_new_ptr = GET_SYM(handle, "mlx_device_new");- if (mlx_device_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_device_new\n");- return -1;- }- mlx_device_new_type_ptr = GET_SYM(handle, "mlx_device_new_type");- if (mlx_device_new_type_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_device_new_type\n");- return -1;- }- mlx_device_free_ptr = GET_SYM(handle, "mlx_device_free");- if (mlx_device_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_device_free\n");- return -1;- }- mlx_device_set_ptr = GET_SYM(handle, "mlx_device_set");- if (mlx_device_set_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_device_set\n");- return -1;- }- mlx_device_tostring_ptr = GET_SYM(handle, "mlx_device_tostring");- if (mlx_device_tostring_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_device_tostring\n");- return -1;- }- mlx_device_equal_ptr = GET_SYM(handle, "mlx_device_equal");- if (mlx_device_equal_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_device_equal\n");- return -1;- }- mlx_device_get_index_ptr = GET_SYM(handle, "mlx_device_get_index");- if (mlx_device_get_index_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_device_get_index\n");- return -1;- }- mlx_device_get_type_ptr = GET_SYM(handle, "mlx_device_get_type");- if (mlx_device_get_type_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_device_get_type\n");- return -1;- }- mlx_get_default_device_ptr = GET_SYM(handle, "mlx_get_default_device");- if (mlx_get_default_device_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_get_default_device\n");- return -1;- }- mlx_set_default_device_ptr = GET_SYM(handle, "mlx_set_default_device");- if (mlx_set_default_device_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_set_default_device\n");- return -1;- }- mlx_device_is_available_ptr = GET_SYM(handle, "mlx_device_is_available");- if (mlx_device_is_available_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_device_is_available\n");- return -1;- }- mlx_device_count_ptr = GET_SYM(handle, "mlx_device_count");- if (mlx_device_count_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_device_count\n");- return -1;- }- mlx_device_info_new_ptr = GET_SYM(handle, "mlx_device_info_new");- if (mlx_device_info_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_device_info_new\n");- return -1;- }- mlx_device_info_get_ptr = GET_SYM(handle, "mlx_device_info_get");- if (mlx_device_info_get_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_device_info_get\n");- return -1;- }- mlx_device_info_free_ptr = GET_SYM(handle, "mlx_device_info_free");- if (mlx_device_info_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_device_info_free\n");- return -1;- }- mlx_device_info_has_key_ptr = GET_SYM(handle, "mlx_device_info_has_key");- if (mlx_device_info_has_key_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_device_info_has_key\n");- return -1;- }- mlx_device_info_is_string_ptr = GET_SYM(handle, "mlx_device_info_is_string");- if (mlx_device_info_is_string_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_device_info_is_string\n");- return -1;- }- mlx_device_info_get_string_ptr = GET_SYM(handle, "mlx_device_info_get_string");- if (mlx_device_info_get_string_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_device_info_get_string\n");- return -1;- }- mlx_device_info_get_size_ptr = GET_SYM(handle, "mlx_device_info_get_size");- if (mlx_device_info_get_size_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_device_info_get_size\n");- return -1;- }- mlx_device_info_get_keys_ptr = GET_SYM(handle, "mlx_device_info_get_keys");- if (mlx_device_info_get_keys_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_device_info_get_keys\n");- return -1;- }- mlx_distributed_all_gather_ptr = GET_SYM(handle, "mlx_distributed_all_gather");- if (mlx_distributed_all_gather_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_distributed_all_gather\n");- return -1;- }- mlx_distributed_all_max_ptr = GET_SYM(handle, "mlx_distributed_all_max");- if (mlx_distributed_all_max_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_distributed_all_max\n");- return -1;- }- mlx_distributed_all_min_ptr = GET_SYM(handle, "mlx_distributed_all_min");- if (mlx_distributed_all_min_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_distributed_all_min\n");- return -1;- }- mlx_distributed_all_sum_ptr = GET_SYM(handle, "mlx_distributed_all_sum");- if (mlx_distributed_all_sum_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_distributed_all_sum\n");- return -1;- }- mlx_distributed_recv_ptr = GET_SYM(handle, "mlx_distributed_recv");- if (mlx_distributed_recv_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_distributed_recv\n");- return -1;- }- mlx_distributed_recv_like_ptr = GET_SYM(handle, "mlx_distributed_recv_like");- if (mlx_distributed_recv_like_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_distributed_recv_like\n");- return -1;- }- mlx_distributed_send_ptr = GET_SYM(handle, "mlx_distributed_send");- if (mlx_distributed_send_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_distributed_send\n");- return -1;- }- mlx_distributed_sum_scatter_ptr = GET_SYM(handle, "mlx_distributed_sum_scatter");- if (mlx_distributed_sum_scatter_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_distributed_sum_scatter\n");- return -1;- }- mlx_distributed_group_new_ptr = GET_SYM(handle, "mlx_distributed_group_new");- if (mlx_distributed_group_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_distributed_group_new\n");- return -1;- }- mlx_distributed_group_free_ptr = GET_SYM(handle, "mlx_distributed_group_free");- if (mlx_distributed_group_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_distributed_group_free\n");- return -1;- }- mlx_distributed_init_ptr = GET_SYM(handle, "mlx_distributed_init");- if (mlx_distributed_init_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_distributed_init\n");- return -1;- }- mlx_distributed_group_rank_ptr = GET_SYM(handle, "mlx_distributed_group_rank");- if (mlx_distributed_group_rank_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_distributed_group_rank\n");- return -1;- }- mlx_distributed_group_size_ptr = GET_SYM(handle, "mlx_distributed_group_size");- if (mlx_distributed_group_size_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_distributed_group_size\n");- return -1;- }- mlx_distributed_group_split_ptr = GET_SYM(handle, "mlx_distributed_group_split");- if (mlx_distributed_group_split_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_distributed_group_split\n");- return -1;- }- mlx_distributed_is_available_ptr = GET_SYM(handle, "mlx_distributed_is_available");- if (mlx_distributed_is_available_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_distributed_is_available\n");- return -1;- }- mlx_set_error_handler_ptr = GET_SYM(handle, "mlx_set_error_handler");- if (mlx_set_error_handler_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_set_error_handler\n");- return -1;- }- _mlx_error_ptr = GET_SYM(handle, "_mlx_error");- if (_mlx_error_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: _mlx_error\n");- return -1;- }- mlx_export_function_ptr = GET_SYM(handle, "mlx_export_function");- if (mlx_export_function_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_export_function\n");- return -1;- }- mlx_export_function_kwargs_ptr = GET_SYM(handle, "mlx_export_function_kwargs");- if (mlx_export_function_kwargs_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_export_function_kwargs\n");- return -1;- }- mlx_function_exporter_new_ptr = GET_SYM(handle, "mlx_function_exporter_new");- if (mlx_function_exporter_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_function_exporter_new\n");- return -1;- }- mlx_function_exporter_free_ptr = GET_SYM(handle, "mlx_function_exporter_free");- if (mlx_function_exporter_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_function_exporter_free\n");- return -1;- }- mlx_function_exporter_apply_ptr = GET_SYM(handle, "mlx_function_exporter_apply");- if (mlx_function_exporter_apply_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_function_exporter_apply\n");- return -1;- }- mlx_function_exporter_apply_kwargs_ptr = GET_SYM(handle, "mlx_function_exporter_apply_kwargs");- if (mlx_function_exporter_apply_kwargs_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_function_exporter_apply_kwargs\n");- return -1;- }- mlx_imported_function_new_ptr = GET_SYM(handle, "mlx_imported_function_new");- if (mlx_imported_function_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_imported_function_new\n");- return -1;- }- mlx_imported_function_free_ptr = GET_SYM(handle, "mlx_imported_function_free");- if (mlx_imported_function_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_imported_function_free\n");- return -1;- }- mlx_imported_function_apply_ptr = GET_SYM(handle, "mlx_imported_function_apply");- if (mlx_imported_function_apply_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_imported_function_apply\n");- return -1;- }- mlx_imported_function_apply_kwargs_ptr = GET_SYM(handle, "mlx_imported_function_apply_kwargs");- if (mlx_imported_function_apply_kwargs_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_imported_function_apply_kwargs\n");- return -1;- }- mlx_fast_cuda_kernel_config_new_ptr = GET_SYM(handle, "mlx_fast_cuda_kernel_config_new");- if (mlx_fast_cuda_kernel_config_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_cuda_kernel_config_new\n");- return -1;- }- mlx_fast_cuda_kernel_config_free_ptr = GET_SYM(handle, "mlx_fast_cuda_kernel_config_free");- if (mlx_fast_cuda_kernel_config_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_cuda_kernel_config_free\n");- return -1;- }- mlx_fast_cuda_kernel_config_add_output_arg_ptr = GET_SYM(handle, "mlx_fast_cuda_kernel_config_add_output_arg");- if (mlx_fast_cuda_kernel_config_add_output_arg_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_cuda_kernel_config_add_output_arg\n");- return -1;- }- mlx_fast_cuda_kernel_config_set_grid_ptr = GET_SYM(handle, "mlx_fast_cuda_kernel_config_set_grid");- if (mlx_fast_cuda_kernel_config_set_grid_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_cuda_kernel_config_set_grid\n");- return -1;- }- mlx_fast_cuda_kernel_config_set_thread_group_ptr = GET_SYM(handle, "mlx_fast_cuda_kernel_config_set_thread_group");- if (mlx_fast_cuda_kernel_config_set_thread_group_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_cuda_kernel_config_set_thread_group\n");- return -1;- }- mlx_fast_cuda_kernel_config_set_init_value_ptr = GET_SYM(handle, "mlx_fast_cuda_kernel_config_set_init_value");- if (mlx_fast_cuda_kernel_config_set_init_value_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_cuda_kernel_config_set_init_value\n");- return -1;- }- mlx_fast_cuda_kernel_config_set_verbose_ptr = GET_SYM(handle, "mlx_fast_cuda_kernel_config_set_verbose");- if (mlx_fast_cuda_kernel_config_set_verbose_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_cuda_kernel_config_set_verbose\n");- return -1;- }- mlx_fast_cuda_kernel_config_add_template_arg_dtype_ptr = GET_SYM(handle, "mlx_fast_cuda_kernel_config_add_template_arg_dtype");- if (mlx_fast_cuda_kernel_config_add_template_arg_dtype_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_cuda_kernel_config_add_template_arg_dtype\n");- return -1;- }- mlx_fast_cuda_kernel_config_add_template_arg_int_ptr = GET_SYM(handle, "mlx_fast_cuda_kernel_config_add_template_arg_int");- if (mlx_fast_cuda_kernel_config_add_template_arg_int_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_cuda_kernel_config_add_template_arg_int\n");- return -1;- }- mlx_fast_cuda_kernel_config_add_template_arg_bool_ptr = GET_SYM(handle, "mlx_fast_cuda_kernel_config_add_template_arg_bool");- if (mlx_fast_cuda_kernel_config_add_template_arg_bool_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_cuda_kernel_config_add_template_arg_bool\n");- return -1;- }- mlx_fast_cuda_kernel_new_ptr = GET_SYM(handle, "mlx_fast_cuda_kernel_new");- if (mlx_fast_cuda_kernel_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_cuda_kernel_new\n");- return -1;- }- mlx_fast_cuda_kernel_free_ptr = GET_SYM(handle, "mlx_fast_cuda_kernel_free");- if (mlx_fast_cuda_kernel_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_cuda_kernel_free\n");- return -1;- }- mlx_fast_cuda_kernel_apply_ptr = GET_SYM(handle, "mlx_fast_cuda_kernel_apply");- if (mlx_fast_cuda_kernel_apply_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_cuda_kernel_apply\n");- return -1;- }- mlx_fast_layer_norm_ptr = GET_SYM(handle, "mlx_fast_layer_norm");- if (mlx_fast_layer_norm_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_layer_norm\n");- return -1;- }- mlx_fast_metal_kernel_config_new_ptr = GET_SYM(handle, "mlx_fast_metal_kernel_config_new");- if (mlx_fast_metal_kernel_config_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_metal_kernel_config_new\n");- return -1;- }- mlx_fast_metal_kernel_config_free_ptr = GET_SYM(handle, "mlx_fast_metal_kernel_config_free");- if (mlx_fast_metal_kernel_config_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_metal_kernel_config_free\n");- return -1;- }- mlx_fast_metal_kernel_config_add_output_arg_ptr = GET_SYM(handle, "mlx_fast_metal_kernel_config_add_output_arg");- if (mlx_fast_metal_kernel_config_add_output_arg_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_metal_kernel_config_add_output_arg\n");- return -1;- }- mlx_fast_metal_kernel_config_set_grid_ptr = GET_SYM(handle, "mlx_fast_metal_kernel_config_set_grid");- if (mlx_fast_metal_kernel_config_set_grid_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_metal_kernel_config_set_grid\n");- return -1;- }- mlx_fast_metal_kernel_config_set_thread_group_ptr = GET_SYM(handle, "mlx_fast_metal_kernel_config_set_thread_group");- if (mlx_fast_metal_kernel_config_set_thread_group_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_metal_kernel_config_set_thread_group\n");- return -1;- }- mlx_fast_metal_kernel_config_set_init_value_ptr = GET_SYM(handle, "mlx_fast_metal_kernel_config_set_init_value");- if (mlx_fast_metal_kernel_config_set_init_value_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_metal_kernel_config_set_init_value\n");- return -1;- }- mlx_fast_metal_kernel_config_set_verbose_ptr = GET_SYM(handle, "mlx_fast_metal_kernel_config_set_verbose");- if (mlx_fast_metal_kernel_config_set_verbose_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_metal_kernel_config_set_verbose\n");- return -1;- }- mlx_fast_metal_kernel_config_add_template_arg_dtype_ptr = GET_SYM(handle, "mlx_fast_metal_kernel_config_add_template_arg_dtype");- if (mlx_fast_metal_kernel_config_add_template_arg_dtype_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_metal_kernel_config_add_template_arg_dtype\n");- return -1;- }- mlx_fast_metal_kernel_config_add_template_arg_int_ptr = GET_SYM(handle, "mlx_fast_metal_kernel_config_add_template_arg_int");- if (mlx_fast_metal_kernel_config_add_template_arg_int_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_metal_kernel_config_add_template_arg_int\n");- return -1;- }- mlx_fast_metal_kernel_config_add_template_arg_bool_ptr = GET_SYM(handle, "mlx_fast_metal_kernel_config_add_template_arg_bool");- if (mlx_fast_metal_kernel_config_add_template_arg_bool_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_metal_kernel_config_add_template_arg_bool\n");- return -1;- }- mlx_fast_metal_kernel_new_ptr = GET_SYM(handle, "mlx_fast_metal_kernel_new");- if (mlx_fast_metal_kernel_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_metal_kernel_new\n");- return -1;- }- mlx_fast_metal_kernel_free_ptr = GET_SYM(handle, "mlx_fast_metal_kernel_free");- if (mlx_fast_metal_kernel_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_metal_kernel_free\n");- return -1;- }- mlx_fast_metal_kernel_apply_ptr = GET_SYM(handle, "mlx_fast_metal_kernel_apply");- if (mlx_fast_metal_kernel_apply_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_metal_kernel_apply\n");- return -1;- }- mlx_fast_rms_norm_ptr = GET_SYM(handle, "mlx_fast_rms_norm");- if (mlx_fast_rms_norm_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_rms_norm\n");- return -1;- }- mlx_fast_rope_ptr = GET_SYM(handle, "mlx_fast_rope");- if (mlx_fast_rope_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_rope\n");- return -1;- }- mlx_fast_rope_dynamic_ptr = GET_SYM(handle, "mlx_fast_rope_dynamic");- if (mlx_fast_rope_dynamic_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_rope_dynamic\n");- return -1;- }- mlx_fast_scaled_dot_product_attention_ptr = GET_SYM(handle, "mlx_fast_scaled_dot_product_attention");- if (mlx_fast_scaled_dot_product_attention_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fast_scaled_dot_product_attention\n");- return -1;- }- mlx_fft_fft_ptr = GET_SYM(handle, "mlx_fft_fft");- if (mlx_fft_fft_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fft_fft\n");- return -1;- }- mlx_fft_fft2_ptr = GET_SYM(handle, "mlx_fft_fft2");- if (mlx_fft_fft2_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fft_fft2\n");- return -1;- }- mlx_fft_fftfreq_ptr = GET_SYM(handle, "mlx_fft_fftfreq");- if (mlx_fft_fftfreq_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fft_fftfreq\n");- return -1;- }- mlx_fft_fftn_ptr = GET_SYM(handle, "mlx_fft_fftn");- if (mlx_fft_fftn_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fft_fftn\n");- return -1;- }- mlx_fft_fftshift_ptr = GET_SYM(handle, "mlx_fft_fftshift");- if (mlx_fft_fftshift_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fft_fftshift\n");- return -1;- }- mlx_fft_ifft_ptr = GET_SYM(handle, "mlx_fft_ifft");- if (mlx_fft_ifft_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fft_ifft\n");- return -1;- }- mlx_fft_ifft2_ptr = GET_SYM(handle, "mlx_fft_ifft2");- if (mlx_fft_ifft2_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fft_ifft2\n");- return -1;- }- mlx_fft_ifftn_ptr = GET_SYM(handle, "mlx_fft_ifftn");- if (mlx_fft_ifftn_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fft_ifftn\n");- return -1;- }- mlx_fft_ifftshift_ptr = GET_SYM(handle, "mlx_fft_ifftshift");- if (mlx_fft_ifftshift_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fft_ifftshift\n");- return -1;- }- mlx_fft_irfft_ptr = GET_SYM(handle, "mlx_fft_irfft");- if (mlx_fft_irfft_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fft_irfft\n");- return -1;- }- mlx_fft_irfft2_ptr = GET_SYM(handle, "mlx_fft_irfft2");- if (mlx_fft_irfft2_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fft_irfft2\n");- return -1;- }- mlx_fft_irfftn_ptr = GET_SYM(handle, "mlx_fft_irfftn");- if (mlx_fft_irfftn_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fft_irfftn\n");- return -1;- }- mlx_fft_rfft_ptr = GET_SYM(handle, "mlx_fft_rfft");- if (mlx_fft_rfft_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fft_rfft\n");- return -1;- }- mlx_fft_rfft2_ptr = GET_SYM(handle, "mlx_fft_rfft2");- if (mlx_fft_rfft2_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fft_rfft2\n");- return -1;- }- mlx_fft_rfftfreq_ptr = GET_SYM(handle, "mlx_fft_rfftfreq");- if (mlx_fft_rfftfreq_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fft_rfftfreq\n");- return -1;- }- mlx_fft_rfftn_ptr = GET_SYM(handle, "mlx_fft_rfftn");- if (mlx_fft_rfftn_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_fft_rfftn\n");- return -1;- }- mlx_node_namer_free_ptr = GET_SYM(handle, "mlx_node_namer_free");- if (mlx_node_namer_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_node_namer_free\n");- return -1;- }- mlx_node_namer_set_name_ptr = GET_SYM(handle, "mlx_node_namer_set_name");- if (mlx_node_namer_set_name_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_node_namer_set_name\n");- return -1;- }- mlx_node_namer_get_name_ptr = GET_SYM(handle, "mlx_node_namer_get_name");- if (mlx_node_namer_get_name_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_node_namer_get_name\n");- return -1;- }- mlx_export_to_dot_ptr = GET_SYM(handle, "mlx_export_to_dot");- if (mlx_export_to_dot_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_export_to_dot\n");- return -1;- }- mlx_print_graph_ptr = GET_SYM(handle, "mlx_print_graph");- if (mlx_print_graph_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_print_graph\n");- return -1;- }- mlx_load_reader_ptr = GET_SYM(handle, "mlx_load_reader");- if (mlx_load_reader_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_load_reader\n");- return -1;- }- mlx_load_ptr = GET_SYM(handle, "mlx_load");- if (mlx_load_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_load\n");- return -1;- }- mlx_load_gguf_ptr = GET_SYM(handle, "mlx_load_gguf");- if (mlx_load_gguf_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_load_gguf\n");- return -1;- }- mlx_load_safetensors_reader_ptr = GET_SYM(handle, "mlx_load_safetensors_reader");- if (mlx_load_safetensors_reader_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_load_safetensors_reader\n");- return -1;- }- mlx_load_safetensors_ptr = GET_SYM(handle, "mlx_load_safetensors");- if (mlx_load_safetensors_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_load_safetensors\n");- return -1;- }- mlx_save_writer_ptr = GET_SYM(handle, "mlx_save_writer");- if (mlx_save_writer_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_save_writer\n");- return -1;- }- mlx_save_ptr = GET_SYM(handle, "mlx_save");- if (mlx_save_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_save\n");- return -1;- }- mlx_save_gguf_ptr = GET_SYM(handle, "mlx_save_gguf");- if (mlx_save_gguf_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_save_gguf\n");- return -1;- }- mlx_save_safetensors_writer_ptr = GET_SYM(handle, "mlx_save_safetensors_writer");- if (mlx_save_safetensors_writer_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_save_safetensors_writer\n");- return -1;- }- mlx_save_safetensors_ptr = GET_SYM(handle, "mlx_save_safetensors");- if (mlx_save_safetensors_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_save_safetensors\n");- return -1;- }- mlx_io_reader_new_ptr = GET_SYM(handle, "mlx_io_reader_new");- if (mlx_io_reader_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_reader_new\n");- return -1;- }- mlx_io_reader_descriptor_ptr = GET_SYM(handle, "mlx_io_reader_descriptor");- if (mlx_io_reader_descriptor_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_reader_descriptor\n");- return -1;- }- mlx_io_reader_tostring_ptr = GET_SYM(handle, "mlx_io_reader_tostring");- if (mlx_io_reader_tostring_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_reader_tostring\n");- return -1;- }- mlx_io_reader_free_ptr = GET_SYM(handle, "mlx_io_reader_free");- if (mlx_io_reader_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_reader_free\n");- return -1;- }- mlx_io_writer_new_ptr = GET_SYM(handle, "mlx_io_writer_new");- if (mlx_io_writer_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_writer_new\n");- return -1;- }- mlx_io_writer_descriptor_ptr = GET_SYM(handle, "mlx_io_writer_descriptor");- if (mlx_io_writer_descriptor_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_writer_descriptor\n");- return -1;- }- mlx_io_writer_tostring_ptr = GET_SYM(handle, "mlx_io_writer_tostring");- if (mlx_io_writer_tostring_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_writer_tostring\n");- return -1;- }- mlx_io_writer_free_ptr = GET_SYM(handle, "mlx_io_writer_free");- if (mlx_io_writer_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_writer_free\n");- return -1;- }- mlx_io_gguf_new_ptr = GET_SYM(handle, "mlx_io_gguf_new");- if (mlx_io_gguf_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_gguf_new\n");- return -1;- }- mlx_io_gguf_free_ptr = GET_SYM(handle, "mlx_io_gguf_free");- if (mlx_io_gguf_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_gguf_free\n");- return -1;- }- mlx_io_gguf_get_keys_ptr = GET_SYM(handle, "mlx_io_gguf_get_keys");- if (mlx_io_gguf_get_keys_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_gguf_get_keys\n");- return -1;- }- mlx_io_gguf_get_array_ptr = GET_SYM(handle, "mlx_io_gguf_get_array");- if (mlx_io_gguf_get_array_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_gguf_get_array\n");- return -1;- }- mlx_io_gguf_get_metadata_array_ptr = GET_SYM(handle, "mlx_io_gguf_get_metadata_array");- if (mlx_io_gguf_get_metadata_array_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_gguf_get_metadata_array\n");- return -1;- }- mlx_io_gguf_get_metadata_string_ptr = GET_SYM(handle, "mlx_io_gguf_get_metadata_string");- if (mlx_io_gguf_get_metadata_string_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_gguf_get_metadata_string\n");- return -1;- }- mlx_io_gguf_get_metadata_vector_string_ptr = GET_SYM(handle, "mlx_io_gguf_get_metadata_vector_string");- if (mlx_io_gguf_get_metadata_vector_string_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_gguf_get_metadata_vector_string\n");- return -1;- }- mlx_io_gguf_has_metadata_array_ptr = GET_SYM(handle, "mlx_io_gguf_has_metadata_array");- if (mlx_io_gguf_has_metadata_array_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_gguf_has_metadata_array\n");- return -1;- }- mlx_io_gguf_has_metadata_string_ptr = GET_SYM(handle, "mlx_io_gguf_has_metadata_string");- if (mlx_io_gguf_has_metadata_string_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_gguf_has_metadata_string\n");- return -1;- }- mlx_io_gguf_has_metadata_vector_string_ptr = GET_SYM(handle, "mlx_io_gguf_has_metadata_vector_string");- if (mlx_io_gguf_has_metadata_vector_string_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_gguf_has_metadata_vector_string\n");- return -1;- }- mlx_io_gguf_set_array_ptr = GET_SYM(handle, "mlx_io_gguf_set_array");- if (mlx_io_gguf_set_array_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_gguf_set_array\n");- return -1;- }- mlx_io_gguf_set_metadata_array_ptr = GET_SYM(handle, "mlx_io_gguf_set_metadata_array");- if (mlx_io_gguf_set_metadata_array_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_gguf_set_metadata_array\n");- return -1;- }- mlx_io_gguf_set_metadata_string_ptr = GET_SYM(handle, "mlx_io_gguf_set_metadata_string");- if (mlx_io_gguf_set_metadata_string_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_gguf_set_metadata_string\n");- return -1;- }- mlx_io_gguf_set_metadata_vector_string_ptr = GET_SYM(handle, "mlx_io_gguf_set_metadata_vector_string");- if (mlx_io_gguf_set_metadata_vector_string_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_io_gguf_set_metadata_vector_string\n");- return -1;- }- mlx_linalg_cholesky_ptr = GET_SYM(handle, "mlx_linalg_cholesky");- if (mlx_linalg_cholesky_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_linalg_cholesky\n");- return -1;- }- mlx_linalg_cholesky_inv_ptr = GET_SYM(handle, "mlx_linalg_cholesky_inv");- if (mlx_linalg_cholesky_inv_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_linalg_cholesky_inv\n");- return -1;- }- mlx_linalg_cross_ptr = GET_SYM(handle, "mlx_linalg_cross");- if (mlx_linalg_cross_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_linalg_cross\n");- return -1;- }- mlx_linalg_eig_ptr = GET_SYM(handle, "mlx_linalg_eig");- if (mlx_linalg_eig_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_linalg_eig\n");- return -1;- }- mlx_linalg_eigh_ptr = GET_SYM(handle, "mlx_linalg_eigh");- if (mlx_linalg_eigh_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_linalg_eigh\n");- return -1;- }- mlx_linalg_eigvals_ptr = GET_SYM(handle, "mlx_linalg_eigvals");- if (mlx_linalg_eigvals_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_linalg_eigvals\n");- return -1;- }- mlx_linalg_eigvalsh_ptr = GET_SYM(handle, "mlx_linalg_eigvalsh");- if (mlx_linalg_eigvalsh_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_linalg_eigvalsh\n");- return -1;- }- mlx_linalg_inv_ptr = GET_SYM(handle, "mlx_linalg_inv");- if (mlx_linalg_inv_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_linalg_inv\n");- return -1;- }- mlx_linalg_lu_ptr = GET_SYM(handle, "mlx_linalg_lu");- if (mlx_linalg_lu_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_linalg_lu\n");- return -1;- }- mlx_linalg_lu_factor_ptr = GET_SYM(handle, "mlx_linalg_lu_factor");- if (mlx_linalg_lu_factor_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_linalg_lu_factor\n");- return -1;- }- mlx_linalg_norm_ptr = GET_SYM(handle, "mlx_linalg_norm");- if (mlx_linalg_norm_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_linalg_norm\n");- return -1;- }- mlx_linalg_norm_matrix_ptr = GET_SYM(handle, "mlx_linalg_norm_matrix");- if (mlx_linalg_norm_matrix_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_linalg_norm_matrix\n");- return -1;- }- mlx_linalg_norm_l2_ptr = GET_SYM(handle, "mlx_linalg_norm_l2");- if (mlx_linalg_norm_l2_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_linalg_norm_l2\n");- return -1;- }- mlx_linalg_pinv_ptr = GET_SYM(handle, "mlx_linalg_pinv");- if (mlx_linalg_pinv_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_linalg_pinv\n");- return -1;- }- mlx_linalg_qr_ptr = GET_SYM(handle, "mlx_linalg_qr");- if (mlx_linalg_qr_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_linalg_qr\n");- return -1;- }- mlx_linalg_solve_ptr = GET_SYM(handle, "mlx_linalg_solve");- if (mlx_linalg_solve_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_linalg_solve\n");- return -1;- }- mlx_linalg_solve_triangular_ptr = GET_SYM(handle, "mlx_linalg_solve_triangular");- if (mlx_linalg_solve_triangular_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_linalg_solve_triangular\n");- return -1;- }- mlx_linalg_svd_ptr = GET_SYM(handle, "mlx_linalg_svd");- if (mlx_linalg_svd_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_linalg_svd\n");- return -1;- }- mlx_linalg_tri_inv_ptr = GET_SYM(handle, "mlx_linalg_tri_inv");- if (mlx_linalg_tri_inv_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_linalg_tri_inv\n");- return -1;- }- mlx_map_string_to_array_new_ptr = GET_SYM(handle, "mlx_map_string_to_array_new");- if (mlx_map_string_to_array_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_map_string_to_array_new\n");- return -1;- }- mlx_map_string_to_array_set_ptr = GET_SYM(handle, "mlx_map_string_to_array_set");- if (mlx_map_string_to_array_set_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_map_string_to_array_set\n");- return -1;- }- mlx_map_string_to_array_free_ptr = GET_SYM(handle, "mlx_map_string_to_array_free");- if (mlx_map_string_to_array_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_map_string_to_array_free\n");- return -1;- }- mlx_map_string_to_array_insert_ptr = GET_SYM(handle, "mlx_map_string_to_array_insert");- if (mlx_map_string_to_array_insert_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_map_string_to_array_insert\n");- return -1;- }- mlx_map_string_to_array_get_ptr = GET_SYM(handle, "mlx_map_string_to_array_get");- if (mlx_map_string_to_array_get_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_map_string_to_array_get\n");- return -1;- }- mlx_map_string_to_array_iterator_new_ptr = GET_SYM(handle, "mlx_map_string_to_array_iterator_new");- if (mlx_map_string_to_array_iterator_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_map_string_to_array_iterator_new\n");- return -1;- }- mlx_map_string_to_array_iterator_free_ptr = GET_SYM(handle, "mlx_map_string_to_array_iterator_free");- if (mlx_map_string_to_array_iterator_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_map_string_to_array_iterator_free\n");- return -1;- }- mlx_map_string_to_array_iterator_next_ptr = GET_SYM(handle, "mlx_map_string_to_array_iterator_next");- if (mlx_map_string_to_array_iterator_next_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_map_string_to_array_iterator_next\n");- return -1;- }- mlx_map_string_to_string_new_ptr = GET_SYM(handle, "mlx_map_string_to_string_new");- if (mlx_map_string_to_string_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_map_string_to_string_new\n");- return -1;- }- mlx_map_string_to_string_set_ptr = GET_SYM(handle, "mlx_map_string_to_string_set");- if (mlx_map_string_to_string_set_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_map_string_to_string_set\n");- return -1;- }- mlx_map_string_to_string_free_ptr = GET_SYM(handle, "mlx_map_string_to_string_free");- if (mlx_map_string_to_string_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_map_string_to_string_free\n");- return -1;- }- mlx_map_string_to_string_insert_ptr = GET_SYM(handle, "mlx_map_string_to_string_insert");- if (mlx_map_string_to_string_insert_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_map_string_to_string_insert\n");- return -1;- }- mlx_map_string_to_string_get_ptr = GET_SYM(handle, "mlx_map_string_to_string_get");- if (mlx_map_string_to_string_get_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_map_string_to_string_get\n");- return -1;- }- mlx_map_string_to_string_iterator_new_ptr = GET_SYM(handle, "mlx_map_string_to_string_iterator_new");- if (mlx_map_string_to_string_iterator_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_map_string_to_string_iterator_new\n");- return -1;- }- mlx_map_string_to_string_iterator_free_ptr = GET_SYM(handle, "mlx_map_string_to_string_iterator_free");- if (mlx_map_string_to_string_iterator_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_map_string_to_string_iterator_free\n");- return -1;- }- mlx_map_string_to_string_iterator_next_ptr = GET_SYM(handle, "mlx_map_string_to_string_iterator_next");- if (mlx_map_string_to_string_iterator_next_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_map_string_to_string_iterator_next\n");- return -1;- }- mlx_clear_cache_ptr = GET_SYM(handle, "mlx_clear_cache");- if (mlx_clear_cache_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_clear_cache\n");- return -1;- }- mlx_get_active_memory_ptr = GET_SYM(handle, "mlx_get_active_memory");- if (mlx_get_active_memory_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_get_active_memory\n");- return -1;- }- mlx_get_cache_memory_ptr = GET_SYM(handle, "mlx_get_cache_memory");- if (mlx_get_cache_memory_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_get_cache_memory\n");- return -1;- }- mlx_get_memory_limit_ptr = GET_SYM(handle, "mlx_get_memory_limit");- if (mlx_get_memory_limit_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_get_memory_limit\n");- return -1;- }- mlx_get_peak_memory_ptr = GET_SYM(handle, "mlx_get_peak_memory");- if (mlx_get_peak_memory_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_get_peak_memory\n");- return -1;- }- mlx_reset_peak_memory_ptr = GET_SYM(handle, "mlx_reset_peak_memory");- if (mlx_reset_peak_memory_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_reset_peak_memory\n");- return -1;- }- mlx_set_cache_limit_ptr = GET_SYM(handle, "mlx_set_cache_limit");- if (mlx_set_cache_limit_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_set_cache_limit\n");- return -1;- }- mlx_set_memory_limit_ptr = GET_SYM(handle, "mlx_set_memory_limit");- if (mlx_set_memory_limit_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_set_memory_limit\n");- return -1;- }- mlx_set_wired_limit_ptr = GET_SYM(handle, "mlx_set_wired_limit");- if (mlx_set_wired_limit_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_set_wired_limit\n");- return -1;- }- mlx_metal_is_available_ptr = GET_SYM(handle, "mlx_metal_is_available");- if (mlx_metal_is_available_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_metal_is_available\n");- return -1;- }- mlx_metal_start_capture_ptr = GET_SYM(handle, "mlx_metal_start_capture");- if (mlx_metal_start_capture_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_metal_start_capture\n");- return -1;- }- mlx_metal_stop_capture_ptr = GET_SYM(handle, "mlx_metal_stop_capture");- if (mlx_metal_stop_capture_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_metal_stop_capture\n");- return -1;- }- mlx_abs_ptr = GET_SYM(handle, "mlx_abs");- if (mlx_abs_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_abs\n");- return -1;- }- mlx_add_ptr = GET_SYM(handle, "mlx_add");- if (mlx_add_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_add\n");- return -1;- }- mlx_addmm_ptr = GET_SYM(handle, "mlx_addmm");- if (mlx_addmm_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_addmm\n");- return -1;- }- mlx_all_axes_ptr = GET_SYM(handle, "mlx_all_axes");- if (mlx_all_axes_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_all_axes\n");- return -1;- }- mlx_all_axis_ptr = GET_SYM(handle, "mlx_all_axis");- if (mlx_all_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_all_axis\n");- return -1;- }- mlx_all_ptr = GET_SYM(handle, "mlx_all");- if (mlx_all_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_all\n");- return -1;- }- mlx_allclose_ptr = GET_SYM(handle, "mlx_allclose");- if (mlx_allclose_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_allclose\n");- return -1;- }- mlx_any_axes_ptr = GET_SYM(handle, "mlx_any_axes");- if (mlx_any_axes_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_any_axes\n");- return -1;- }- mlx_any_axis_ptr = GET_SYM(handle, "mlx_any_axis");- if (mlx_any_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_any_axis\n");- return -1;- }- mlx_any_ptr = GET_SYM(handle, "mlx_any");- if (mlx_any_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_any\n");- return -1;- }- mlx_arange_ptr = GET_SYM(handle, "mlx_arange");- if (mlx_arange_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_arange\n");- return -1;- }- mlx_arccos_ptr = GET_SYM(handle, "mlx_arccos");- if (mlx_arccos_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_arccos\n");- return -1;- }- mlx_arccosh_ptr = GET_SYM(handle, "mlx_arccosh");- if (mlx_arccosh_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_arccosh\n");- return -1;- }- mlx_arcsin_ptr = GET_SYM(handle, "mlx_arcsin");- if (mlx_arcsin_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_arcsin\n");- return -1;- }- mlx_arcsinh_ptr = GET_SYM(handle, "mlx_arcsinh");- if (mlx_arcsinh_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_arcsinh\n");- return -1;- }- mlx_arctan_ptr = GET_SYM(handle, "mlx_arctan");- if (mlx_arctan_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_arctan\n");- return -1;- }- mlx_arctan2_ptr = GET_SYM(handle, "mlx_arctan2");- if (mlx_arctan2_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_arctan2\n");- return -1;- }- mlx_arctanh_ptr = GET_SYM(handle, "mlx_arctanh");- if (mlx_arctanh_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_arctanh\n");- return -1;- }- mlx_argmax_axis_ptr = GET_SYM(handle, "mlx_argmax_axis");- if (mlx_argmax_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_argmax_axis\n");- return -1;- }- mlx_argmax_ptr = GET_SYM(handle, "mlx_argmax");- if (mlx_argmax_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_argmax\n");- return -1;- }- mlx_argmin_axis_ptr = GET_SYM(handle, "mlx_argmin_axis");- if (mlx_argmin_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_argmin_axis\n");- return -1;- }- mlx_argmin_ptr = GET_SYM(handle, "mlx_argmin");- if (mlx_argmin_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_argmin\n");- return -1;- }- mlx_argpartition_axis_ptr = GET_SYM(handle, "mlx_argpartition_axis");- if (mlx_argpartition_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_argpartition_axis\n");- return -1;- }- mlx_argpartition_ptr = GET_SYM(handle, "mlx_argpartition");- if (mlx_argpartition_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_argpartition\n");- return -1;- }- mlx_argsort_axis_ptr = GET_SYM(handle, "mlx_argsort_axis");- if (mlx_argsort_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_argsort_axis\n");- return -1;- }- mlx_argsort_ptr = GET_SYM(handle, "mlx_argsort");- if (mlx_argsort_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_argsort\n");- return -1;- }- mlx_array_equal_ptr = GET_SYM(handle, "mlx_array_equal");- if (mlx_array_equal_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_array_equal\n");- return -1;- }- mlx_as_strided_ptr = GET_SYM(handle, "mlx_as_strided");- if (mlx_as_strided_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_as_strided\n");- return -1;- }- mlx_astype_ptr = GET_SYM(handle, "mlx_astype");- if (mlx_astype_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_astype\n");- return -1;- }- mlx_atleast_1d_ptr = GET_SYM(handle, "mlx_atleast_1d");- if (mlx_atleast_1d_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_atleast_1d\n");- return -1;- }- mlx_atleast_2d_ptr = GET_SYM(handle, "mlx_atleast_2d");- if (mlx_atleast_2d_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_atleast_2d\n");- return -1;- }- mlx_atleast_3d_ptr = GET_SYM(handle, "mlx_atleast_3d");- if (mlx_atleast_3d_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_atleast_3d\n");- return -1;- }- mlx_bartlett_ptr = GET_SYM(handle, "mlx_bartlett");- if (mlx_bartlett_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_bartlett\n");- return -1;- }- mlx_bitwise_and_ptr = GET_SYM(handle, "mlx_bitwise_and");- if (mlx_bitwise_and_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_bitwise_and\n");- return -1;- }- mlx_bitwise_invert_ptr = GET_SYM(handle, "mlx_bitwise_invert");- if (mlx_bitwise_invert_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_bitwise_invert\n");- return -1;- }- mlx_bitwise_or_ptr = GET_SYM(handle, "mlx_bitwise_or");- if (mlx_bitwise_or_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_bitwise_or\n");- return -1;- }- mlx_bitwise_xor_ptr = GET_SYM(handle, "mlx_bitwise_xor");- if (mlx_bitwise_xor_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_bitwise_xor\n");- return -1;- }- mlx_blackman_ptr = GET_SYM(handle, "mlx_blackman");- if (mlx_blackman_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_blackman\n");- return -1;- }- mlx_block_masked_mm_ptr = GET_SYM(handle, "mlx_block_masked_mm");- if (mlx_block_masked_mm_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_block_masked_mm\n");- return -1;- }- mlx_broadcast_arrays_ptr = GET_SYM(handle, "mlx_broadcast_arrays");- if (mlx_broadcast_arrays_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_broadcast_arrays\n");- return -1;- }- mlx_broadcast_to_ptr = GET_SYM(handle, "mlx_broadcast_to");- if (mlx_broadcast_to_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_broadcast_to\n");- return -1;- }- mlx_ceil_ptr = GET_SYM(handle, "mlx_ceil");- if (mlx_ceil_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_ceil\n");- return -1;- }- mlx_clip_ptr = GET_SYM(handle, "mlx_clip");- if (mlx_clip_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_clip\n");- return -1;- }- mlx_concatenate_axis_ptr = GET_SYM(handle, "mlx_concatenate_axis");- if (mlx_concatenate_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_concatenate_axis\n");- return -1;- }- mlx_concatenate_ptr = GET_SYM(handle, "mlx_concatenate");- if (mlx_concatenate_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_concatenate\n");- return -1;- }- mlx_conjugate_ptr = GET_SYM(handle, "mlx_conjugate");- if (mlx_conjugate_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_conjugate\n");- return -1;- }- mlx_contiguous_ptr = GET_SYM(handle, "mlx_contiguous");- if (mlx_contiguous_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_contiguous\n");- return -1;- }- mlx_conv1d_ptr = GET_SYM(handle, "mlx_conv1d");- if (mlx_conv1d_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_conv1d\n");- return -1;- }- mlx_conv2d_ptr = GET_SYM(handle, "mlx_conv2d");- if (mlx_conv2d_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_conv2d\n");- return -1;- }- mlx_conv3d_ptr = GET_SYM(handle, "mlx_conv3d");- if (mlx_conv3d_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_conv3d\n");- return -1;- }- mlx_conv_general_ptr = GET_SYM(handle, "mlx_conv_general");- if (mlx_conv_general_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_conv_general\n");- return -1;- }- mlx_conv_transpose1d_ptr = GET_SYM(handle, "mlx_conv_transpose1d");- if (mlx_conv_transpose1d_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_conv_transpose1d\n");- return -1;- }- mlx_conv_transpose2d_ptr = GET_SYM(handle, "mlx_conv_transpose2d");- if (mlx_conv_transpose2d_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_conv_transpose2d\n");- return -1;- }- mlx_conv_transpose3d_ptr = GET_SYM(handle, "mlx_conv_transpose3d");- if (mlx_conv_transpose3d_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_conv_transpose3d\n");- return -1;- }- mlx_copy_ptr = GET_SYM(handle, "mlx_copy");- if (mlx_copy_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_copy\n");- return -1;- }- mlx_cos_ptr = GET_SYM(handle, "mlx_cos");- if (mlx_cos_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_cos\n");- return -1;- }- mlx_cosh_ptr = GET_SYM(handle, "mlx_cosh");- if (mlx_cosh_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_cosh\n");- return -1;- }- mlx_cummax_ptr = GET_SYM(handle, "mlx_cummax");- if (mlx_cummax_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_cummax\n");- return -1;- }- mlx_cummin_ptr = GET_SYM(handle, "mlx_cummin");- if (mlx_cummin_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_cummin\n");- return -1;- }- mlx_cumprod_ptr = GET_SYM(handle, "mlx_cumprod");- if (mlx_cumprod_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_cumprod\n");- return -1;- }- mlx_cumsum_ptr = GET_SYM(handle, "mlx_cumsum");- if (mlx_cumsum_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_cumsum\n");- return -1;- }- mlx_degrees_ptr = GET_SYM(handle, "mlx_degrees");- if (mlx_degrees_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_degrees\n");- return -1;- }- mlx_depends_ptr = GET_SYM(handle, "mlx_depends");- if (mlx_depends_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_depends\n");- return -1;- }- mlx_dequantize_ptr = GET_SYM(handle, "mlx_dequantize");- if (mlx_dequantize_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_dequantize\n");- return -1;- }- mlx_diag_ptr = GET_SYM(handle, "mlx_diag");- if (mlx_diag_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_diag\n");- return -1;- }- mlx_diagonal_ptr = GET_SYM(handle, "mlx_diagonal");- if (mlx_diagonal_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_diagonal\n");- return -1;- }- mlx_divide_ptr = GET_SYM(handle, "mlx_divide");- if (mlx_divide_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_divide\n");- return -1;- }- mlx_divmod_ptr = GET_SYM(handle, "mlx_divmod");- if (mlx_divmod_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_divmod\n");- return -1;- }- mlx_einsum_ptr = GET_SYM(handle, "mlx_einsum");- if (mlx_einsum_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_einsum\n");- return -1;- }- mlx_equal_ptr = GET_SYM(handle, "mlx_equal");- if (mlx_equal_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_equal\n");- return -1;- }- mlx_erf_ptr = GET_SYM(handle, "mlx_erf");- if (mlx_erf_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_erf\n");- return -1;- }- mlx_erfinv_ptr = GET_SYM(handle, "mlx_erfinv");- if (mlx_erfinv_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_erfinv\n");- return -1;- }- mlx_exp_ptr = GET_SYM(handle, "mlx_exp");- if (mlx_exp_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_exp\n");- return -1;- }- mlx_expand_dims_axes_ptr = GET_SYM(handle, "mlx_expand_dims_axes");- if (mlx_expand_dims_axes_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_expand_dims_axes\n");- return -1;- }- mlx_expand_dims_ptr = GET_SYM(handle, "mlx_expand_dims");- if (mlx_expand_dims_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_expand_dims\n");- return -1;- }- mlx_expm1_ptr = GET_SYM(handle, "mlx_expm1");- if (mlx_expm1_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_expm1\n");- return -1;- }- mlx_eye_ptr = GET_SYM(handle, "mlx_eye");- if (mlx_eye_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_eye\n");- return -1;- }- mlx_flatten_ptr = GET_SYM(handle, "mlx_flatten");- if (mlx_flatten_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_flatten\n");- return -1;- }- mlx_floor_ptr = GET_SYM(handle, "mlx_floor");- if (mlx_floor_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_floor\n");- return -1;- }- mlx_floor_divide_ptr = GET_SYM(handle, "mlx_floor_divide");- if (mlx_floor_divide_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_floor_divide\n");- return -1;- }- mlx_from_fp8_ptr = GET_SYM(handle, "mlx_from_fp8");- if (mlx_from_fp8_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_from_fp8\n");- return -1;- }- mlx_full_ptr = GET_SYM(handle, "mlx_full");- if (mlx_full_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_full\n");- return -1;- }- mlx_full_like_ptr = GET_SYM(handle, "mlx_full_like");- if (mlx_full_like_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_full_like\n");- return -1;- }- mlx_gather_ptr = GET_SYM(handle, "mlx_gather");- if (mlx_gather_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_gather\n");- return -1;- }- mlx_gather_single_ptr = GET_SYM(handle, "mlx_gather_single");- if (mlx_gather_single_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_gather_single\n");- return -1;- }- mlx_gather_mm_ptr = GET_SYM(handle, "mlx_gather_mm");- if (mlx_gather_mm_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_gather_mm\n");- return -1;- }- mlx_gather_qmm_ptr = GET_SYM(handle, "mlx_gather_qmm");- if (mlx_gather_qmm_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_gather_qmm\n");- return -1;- }- mlx_greater_ptr = GET_SYM(handle, "mlx_greater");- if (mlx_greater_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_greater\n");- return -1;- }- mlx_greater_equal_ptr = GET_SYM(handle, "mlx_greater_equal");- if (mlx_greater_equal_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_greater_equal\n");- return -1;- }- mlx_hadamard_transform_ptr = GET_SYM(handle, "mlx_hadamard_transform");- if (mlx_hadamard_transform_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_hadamard_transform\n");- return -1;- }- mlx_hamming_ptr = GET_SYM(handle, "mlx_hamming");- if (mlx_hamming_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_hamming\n");- return -1;- }- mlx_hanning_ptr = GET_SYM(handle, "mlx_hanning");- if (mlx_hanning_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_hanning\n");- return -1;- }- mlx_identity_ptr = GET_SYM(handle, "mlx_identity");- if (mlx_identity_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_identity\n");- return -1;- }- mlx_imag_ptr = GET_SYM(handle, "mlx_imag");- if (mlx_imag_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_imag\n");- return -1;- }- mlx_inner_ptr = GET_SYM(handle, "mlx_inner");- if (mlx_inner_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_inner\n");- return -1;- }- mlx_isclose_ptr = GET_SYM(handle, "mlx_isclose");- if (mlx_isclose_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_isclose\n");- return -1;- }- mlx_isfinite_ptr = GET_SYM(handle, "mlx_isfinite");- if (mlx_isfinite_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_isfinite\n");- return -1;- }- mlx_isinf_ptr = GET_SYM(handle, "mlx_isinf");- if (mlx_isinf_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_isinf\n");- return -1;- }- mlx_isnan_ptr = GET_SYM(handle, "mlx_isnan");- if (mlx_isnan_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_isnan\n");- return -1;- }- mlx_isneginf_ptr = GET_SYM(handle, "mlx_isneginf");- if (mlx_isneginf_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_isneginf\n");- return -1;- }- mlx_isposinf_ptr = GET_SYM(handle, "mlx_isposinf");- if (mlx_isposinf_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_isposinf\n");- return -1;- }- mlx_kron_ptr = GET_SYM(handle, "mlx_kron");- if (mlx_kron_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_kron\n");- return -1;- }- mlx_left_shift_ptr = GET_SYM(handle, "mlx_left_shift");- if (mlx_left_shift_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_left_shift\n");- return -1;- }- mlx_less_ptr = GET_SYM(handle, "mlx_less");- if (mlx_less_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_less\n");- return -1;- }- mlx_less_equal_ptr = GET_SYM(handle, "mlx_less_equal");- if (mlx_less_equal_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_less_equal\n");- return -1;- }- mlx_linspace_ptr = GET_SYM(handle, "mlx_linspace");- if (mlx_linspace_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_linspace\n");- return -1;- }- mlx_log_ptr = GET_SYM(handle, "mlx_log");- if (mlx_log_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_log\n");- return -1;- }- mlx_log10_ptr = GET_SYM(handle, "mlx_log10");- if (mlx_log10_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_log10\n");- return -1;- }- mlx_log1p_ptr = GET_SYM(handle, "mlx_log1p");- if (mlx_log1p_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_log1p\n");- return -1;- }- mlx_log2_ptr = GET_SYM(handle, "mlx_log2");- if (mlx_log2_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_log2\n");- return -1;- }- mlx_logaddexp_ptr = GET_SYM(handle, "mlx_logaddexp");- if (mlx_logaddexp_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_logaddexp\n");- return -1;- }- mlx_logcumsumexp_ptr = GET_SYM(handle, "mlx_logcumsumexp");- if (mlx_logcumsumexp_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_logcumsumexp\n");- return -1;- }- mlx_logical_and_ptr = GET_SYM(handle, "mlx_logical_and");- if (mlx_logical_and_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_logical_and\n");- return -1;- }- mlx_logical_not_ptr = GET_SYM(handle, "mlx_logical_not");- if (mlx_logical_not_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_logical_not\n");- return -1;- }- mlx_logical_or_ptr = GET_SYM(handle, "mlx_logical_or");- if (mlx_logical_or_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_logical_or\n");- return -1;- }- mlx_logsumexp_axes_ptr = GET_SYM(handle, "mlx_logsumexp_axes");- if (mlx_logsumexp_axes_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_logsumexp_axes\n");- return -1;- }- mlx_logsumexp_axis_ptr = GET_SYM(handle, "mlx_logsumexp_axis");- if (mlx_logsumexp_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_logsumexp_axis\n");- return -1;- }- mlx_logsumexp_ptr = GET_SYM(handle, "mlx_logsumexp");- if (mlx_logsumexp_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_logsumexp\n");- return -1;- }- mlx_masked_scatter_ptr = GET_SYM(handle, "mlx_masked_scatter");- if (mlx_masked_scatter_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_masked_scatter\n");- return -1;- }- mlx_matmul_ptr = GET_SYM(handle, "mlx_matmul");- if (mlx_matmul_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_matmul\n");- return -1;- }- mlx_max_axes_ptr = GET_SYM(handle, "mlx_max_axes");- if (mlx_max_axes_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_max_axes\n");- return -1;- }- mlx_max_axis_ptr = GET_SYM(handle, "mlx_max_axis");- if (mlx_max_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_max_axis\n");- return -1;- }- mlx_max_ptr = GET_SYM(handle, "mlx_max");- if (mlx_max_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_max\n");- return -1;- }- mlx_maximum_ptr = GET_SYM(handle, "mlx_maximum");- if (mlx_maximum_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_maximum\n");- return -1;- }- mlx_mean_axes_ptr = GET_SYM(handle, "mlx_mean_axes");- if (mlx_mean_axes_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_mean_axes\n");- return -1;- }- mlx_mean_axis_ptr = GET_SYM(handle, "mlx_mean_axis");- if (mlx_mean_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_mean_axis\n");- return -1;- }- mlx_mean_ptr = GET_SYM(handle, "mlx_mean");- if (mlx_mean_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_mean\n");- return -1;- }- mlx_median_ptr = GET_SYM(handle, "mlx_median");- if (mlx_median_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_median\n");- return -1;- }- mlx_meshgrid_ptr = GET_SYM(handle, "mlx_meshgrid");- if (mlx_meshgrid_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_meshgrid\n");- return -1;- }- mlx_min_axes_ptr = GET_SYM(handle, "mlx_min_axes");- if (mlx_min_axes_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_min_axes\n");- return -1;- }- mlx_min_axis_ptr = GET_SYM(handle, "mlx_min_axis");- if (mlx_min_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_min_axis\n");- return -1;- }- mlx_min_ptr = GET_SYM(handle, "mlx_min");- if (mlx_min_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_min\n");- return -1;- }- mlx_minimum_ptr = GET_SYM(handle, "mlx_minimum");- if (mlx_minimum_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_minimum\n");- return -1;- }- mlx_moveaxis_ptr = GET_SYM(handle, "mlx_moveaxis");- if (mlx_moveaxis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_moveaxis\n");- return -1;- }- mlx_multiply_ptr = GET_SYM(handle, "mlx_multiply");- if (mlx_multiply_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_multiply\n");- return -1;- }- mlx_nan_to_num_ptr = GET_SYM(handle, "mlx_nan_to_num");- if (mlx_nan_to_num_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_nan_to_num\n");- return -1;- }- mlx_negative_ptr = GET_SYM(handle, "mlx_negative");- if (mlx_negative_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_negative\n");- return -1;- }- mlx_not_equal_ptr = GET_SYM(handle, "mlx_not_equal");- if (mlx_not_equal_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_not_equal\n");- return -1;- }- mlx_number_of_elements_ptr = GET_SYM(handle, "mlx_number_of_elements");- if (mlx_number_of_elements_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_number_of_elements\n");- return -1;- }- mlx_ones_ptr = GET_SYM(handle, "mlx_ones");- if (mlx_ones_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_ones\n");- return -1;- }- mlx_ones_like_ptr = GET_SYM(handle, "mlx_ones_like");- if (mlx_ones_like_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_ones_like\n");- return -1;- }- mlx_outer_ptr = GET_SYM(handle, "mlx_outer");- if (mlx_outer_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_outer\n");- return -1;- }- mlx_pad_ptr = GET_SYM(handle, "mlx_pad");- if (mlx_pad_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_pad\n");- return -1;- }- mlx_pad_symmetric_ptr = GET_SYM(handle, "mlx_pad_symmetric");- if (mlx_pad_symmetric_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_pad_symmetric\n");- return -1;- }- mlx_partition_axis_ptr = GET_SYM(handle, "mlx_partition_axis");- if (mlx_partition_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_partition_axis\n");- return -1;- }- mlx_partition_ptr = GET_SYM(handle, "mlx_partition");- if (mlx_partition_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_partition\n");- return -1;- }- mlx_power_ptr = GET_SYM(handle, "mlx_power");- if (mlx_power_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_power\n");- return -1;- }- mlx_prod_axes_ptr = GET_SYM(handle, "mlx_prod_axes");- if (mlx_prod_axes_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_prod_axes\n");- return -1;- }- mlx_prod_axis_ptr = GET_SYM(handle, "mlx_prod_axis");- if (mlx_prod_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_prod_axis\n");- return -1;- }- mlx_prod_ptr = GET_SYM(handle, "mlx_prod");- if (mlx_prod_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_prod\n");- return -1;- }- mlx_put_along_axis_ptr = GET_SYM(handle, "mlx_put_along_axis");- if (mlx_put_along_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_put_along_axis\n");- return -1;- }- mlx_qqmm_ptr = GET_SYM(handle, "mlx_qqmm");- if (mlx_qqmm_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_qqmm\n");- return -1;- }- mlx_quantize_ptr = GET_SYM(handle, "mlx_quantize");- if (mlx_quantize_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_quantize\n");- return -1;- }- mlx_quantized_matmul_ptr = GET_SYM(handle, "mlx_quantized_matmul");- if (mlx_quantized_matmul_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_quantized_matmul\n");- return -1;- }- mlx_radians_ptr = GET_SYM(handle, "mlx_radians");- if (mlx_radians_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_radians\n");- return -1;- }- mlx_real_ptr = GET_SYM(handle, "mlx_real");- if (mlx_real_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_real\n");- return -1;- }- mlx_reciprocal_ptr = GET_SYM(handle, "mlx_reciprocal");- if (mlx_reciprocal_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_reciprocal\n");- return -1;- }- mlx_remainder_ptr = GET_SYM(handle, "mlx_remainder");- if (mlx_remainder_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_remainder\n");- return -1;- }- mlx_repeat_axis_ptr = GET_SYM(handle, "mlx_repeat_axis");- if (mlx_repeat_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_repeat_axis\n");- return -1;- }- mlx_repeat_ptr = GET_SYM(handle, "mlx_repeat");- if (mlx_repeat_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_repeat\n");- return -1;- }- mlx_reshape_ptr = GET_SYM(handle, "mlx_reshape");- if (mlx_reshape_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_reshape\n");- return -1;- }- mlx_right_shift_ptr = GET_SYM(handle, "mlx_right_shift");- if (mlx_right_shift_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_right_shift\n");- return -1;- }- mlx_roll_axis_ptr = GET_SYM(handle, "mlx_roll_axis");- if (mlx_roll_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_roll_axis\n");- return -1;- }- mlx_roll_axes_ptr = GET_SYM(handle, "mlx_roll_axes");- if (mlx_roll_axes_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_roll_axes\n");- return -1;- }- mlx_roll_ptr = GET_SYM(handle, "mlx_roll");- if (mlx_roll_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_roll\n");- return -1;- }- mlx_round_ptr = GET_SYM(handle, "mlx_round");- if (mlx_round_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_round\n");- return -1;- }- mlx_rsqrt_ptr = GET_SYM(handle, "mlx_rsqrt");- if (mlx_rsqrt_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_rsqrt\n");- return -1;- }- mlx_scatter_ptr = GET_SYM(handle, "mlx_scatter");- if (mlx_scatter_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_scatter\n");- return -1;- }- mlx_scatter_single_ptr = GET_SYM(handle, "mlx_scatter_single");- if (mlx_scatter_single_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_scatter_single\n");- return -1;- }- mlx_scatter_add_ptr = GET_SYM(handle, "mlx_scatter_add");- if (mlx_scatter_add_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_scatter_add\n");- return -1;- }- mlx_scatter_add_single_ptr = GET_SYM(handle, "mlx_scatter_add_single");- if (mlx_scatter_add_single_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_scatter_add_single\n");- return -1;- }- mlx_scatter_add_axis_ptr = GET_SYM(handle, "mlx_scatter_add_axis");- if (mlx_scatter_add_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_scatter_add_axis\n");- return -1;- }- mlx_scatter_max_ptr = GET_SYM(handle, "mlx_scatter_max");- if (mlx_scatter_max_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_scatter_max\n");- return -1;- }- mlx_scatter_max_single_ptr = GET_SYM(handle, "mlx_scatter_max_single");- if (mlx_scatter_max_single_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_scatter_max_single\n");- return -1;- }- mlx_scatter_min_ptr = GET_SYM(handle, "mlx_scatter_min");- if (mlx_scatter_min_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_scatter_min\n");- return -1;- }- mlx_scatter_min_single_ptr = GET_SYM(handle, "mlx_scatter_min_single");- if (mlx_scatter_min_single_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_scatter_min_single\n");- return -1;- }- mlx_scatter_prod_ptr = GET_SYM(handle, "mlx_scatter_prod");- if (mlx_scatter_prod_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_scatter_prod\n");- return -1;- }- mlx_scatter_prod_single_ptr = GET_SYM(handle, "mlx_scatter_prod_single");- if (mlx_scatter_prod_single_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_scatter_prod_single\n");- return -1;- }- mlx_segmented_mm_ptr = GET_SYM(handle, "mlx_segmented_mm");- if (mlx_segmented_mm_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_segmented_mm\n");- return -1;- }- mlx_sigmoid_ptr = GET_SYM(handle, "mlx_sigmoid");- if (mlx_sigmoid_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_sigmoid\n");- return -1;- }- mlx_sign_ptr = GET_SYM(handle, "mlx_sign");- if (mlx_sign_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_sign\n");- return -1;- }- mlx_sin_ptr = GET_SYM(handle, "mlx_sin");- if (mlx_sin_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_sin\n");- return -1;- }- mlx_sinh_ptr = GET_SYM(handle, "mlx_sinh");- if (mlx_sinh_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_sinh\n");- return -1;- }- mlx_slice_ptr = GET_SYM(handle, "mlx_slice");- if (mlx_slice_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_slice\n");- return -1;- }- mlx_slice_dynamic_ptr = GET_SYM(handle, "mlx_slice_dynamic");- if (mlx_slice_dynamic_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_slice_dynamic\n");- return -1;- }- mlx_slice_update_ptr = GET_SYM(handle, "mlx_slice_update");- if (mlx_slice_update_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_slice_update\n");- return -1;- }- mlx_slice_update_dynamic_ptr = GET_SYM(handle, "mlx_slice_update_dynamic");- if (mlx_slice_update_dynamic_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_slice_update_dynamic\n");- return -1;- }- mlx_slice_update_add_ptr = GET_SYM(handle, "mlx_slice_update_add");- if (mlx_slice_update_add_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_slice_update_add\n");- return -1;- }- mlx_slice_update_max_ptr = GET_SYM(handle, "mlx_slice_update_max");- if (mlx_slice_update_max_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_slice_update_max\n");- return -1;- }- mlx_slice_update_min_ptr = GET_SYM(handle, "mlx_slice_update_min");- if (mlx_slice_update_min_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_slice_update_min\n");- return -1;- }- mlx_slice_update_prod_ptr = GET_SYM(handle, "mlx_slice_update_prod");- if (mlx_slice_update_prod_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_slice_update_prod\n");- return -1;- }- mlx_softmax_axes_ptr = GET_SYM(handle, "mlx_softmax_axes");- if (mlx_softmax_axes_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_softmax_axes\n");- return -1;- }- mlx_softmax_axis_ptr = GET_SYM(handle, "mlx_softmax_axis");- if (mlx_softmax_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_softmax_axis\n");- return -1;- }- mlx_softmax_ptr = GET_SYM(handle, "mlx_softmax");- if (mlx_softmax_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_softmax\n");- return -1;- }- mlx_sort_axis_ptr = GET_SYM(handle, "mlx_sort_axis");- if (mlx_sort_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_sort_axis\n");- return -1;- }- mlx_sort_ptr = GET_SYM(handle, "mlx_sort");- if (mlx_sort_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_sort\n");- return -1;- }- mlx_split_ptr = GET_SYM(handle, "mlx_split");- if (mlx_split_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_split\n");- return -1;- }- mlx_split_sections_ptr = GET_SYM(handle, "mlx_split_sections");- if (mlx_split_sections_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_split_sections\n");- return -1;- }- mlx_sqrt_ptr = GET_SYM(handle, "mlx_sqrt");- if (mlx_sqrt_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_sqrt\n");- return -1;- }- mlx_square_ptr = GET_SYM(handle, "mlx_square");- if (mlx_square_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_square\n");- return -1;- }- mlx_squeeze_axes_ptr = GET_SYM(handle, "mlx_squeeze_axes");- if (mlx_squeeze_axes_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_squeeze_axes\n");- return -1;- }- mlx_squeeze_axis_ptr = GET_SYM(handle, "mlx_squeeze_axis");- if (mlx_squeeze_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_squeeze_axis\n");- return -1;- }- mlx_squeeze_ptr = GET_SYM(handle, "mlx_squeeze");- if (mlx_squeeze_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_squeeze\n");- return -1;- }- mlx_stack_axis_ptr = GET_SYM(handle, "mlx_stack_axis");- if (mlx_stack_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_stack_axis\n");- return -1;- }- mlx_stack_ptr = GET_SYM(handle, "mlx_stack");- if (mlx_stack_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_stack\n");- return -1;- }- mlx_std_axes_ptr = GET_SYM(handle, "mlx_std_axes");- if (mlx_std_axes_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_std_axes\n");- return -1;- }- mlx_std_axis_ptr = GET_SYM(handle, "mlx_std_axis");- if (mlx_std_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_std_axis\n");- return -1;- }- mlx_std_ptr = GET_SYM(handle, "mlx_std");- if (mlx_std_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_std\n");- return -1;- }- mlx_stop_gradient_ptr = GET_SYM(handle, "mlx_stop_gradient");- if (mlx_stop_gradient_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_stop_gradient\n");- return -1;- }- mlx_subtract_ptr = GET_SYM(handle, "mlx_subtract");- if (mlx_subtract_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_subtract\n");- return -1;- }- mlx_sum_axes_ptr = GET_SYM(handle, "mlx_sum_axes");- if (mlx_sum_axes_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_sum_axes\n");- return -1;- }- mlx_sum_axis_ptr = GET_SYM(handle, "mlx_sum_axis");- if (mlx_sum_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_sum_axis\n");- return -1;- }- mlx_sum_ptr = GET_SYM(handle, "mlx_sum");- if (mlx_sum_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_sum\n");- return -1;- }- mlx_swapaxes_ptr = GET_SYM(handle, "mlx_swapaxes");- if (mlx_swapaxes_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_swapaxes\n");- return -1;- }- mlx_take_axis_ptr = GET_SYM(handle, "mlx_take_axis");- if (mlx_take_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_take_axis\n");- return -1;- }- mlx_take_ptr = GET_SYM(handle, "mlx_take");- if (mlx_take_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_take\n");- return -1;- }- mlx_take_along_axis_ptr = GET_SYM(handle, "mlx_take_along_axis");- if (mlx_take_along_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_take_along_axis\n");- return -1;- }- mlx_tan_ptr = GET_SYM(handle, "mlx_tan");- if (mlx_tan_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_tan\n");- return -1;- }- mlx_tanh_ptr = GET_SYM(handle, "mlx_tanh");- if (mlx_tanh_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_tanh\n");- return -1;- }- mlx_tensordot_ptr = GET_SYM(handle, "mlx_tensordot");- if (mlx_tensordot_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_tensordot\n");- return -1;- }- mlx_tensordot_axis_ptr = GET_SYM(handle, "mlx_tensordot_axis");- if (mlx_tensordot_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_tensordot_axis\n");- return -1;- }- mlx_tile_ptr = GET_SYM(handle, "mlx_tile");- if (mlx_tile_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_tile\n");- return -1;- }- mlx_to_fp8_ptr = GET_SYM(handle, "mlx_to_fp8");- if (mlx_to_fp8_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_to_fp8\n");- return -1;- }- mlx_topk_axis_ptr = GET_SYM(handle, "mlx_topk_axis");- if (mlx_topk_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_topk_axis\n");- return -1;- }- mlx_topk_ptr = GET_SYM(handle, "mlx_topk");- if (mlx_topk_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_topk\n");- return -1;- }- mlx_trace_ptr = GET_SYM(handle, "mlx_trace");- if (mlx_trace_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_trace\n");- return -1;- }- mlx_transpose_axes_ptr = GET_SYM(handle, "mlx_transpose_axes");- if (mlx_transpose_axes_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_transpose_axes\n");- return -1;- }- mlx_transpose_ptr = GET_SYM(handle, "mlx_transpose");- if (mlx_transpose_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_transpose\n");- return -1;- }- mlx_tri_ptr = GET_SYM(handle, "mlx_tri");- if (mlx_tri_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_tri\n");- return -1;- }- mlx_tril_ptr = GET_SYM(handle, "mlx_tril");- if (mlx_tril_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_tril\n");- return -1;- }- mlx_triu_ptr = GET_SYM(handle, "mlx_triu");- if (mlx_triu_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_triu\n");- return -1;- }- mlx_unflatten_ptr = GET_SYM(handle, "mlx_unflatten");- if (mlx_unflatten_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_unflatten\n");- return -1;- }- mlx_var_axes_ptr = GET_SYM(handle, "mlx_var_axes");- if (mlx_var_axes_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_var_axes\n");- return -1;- }- mlx_var_axis_ptr = GET_SYM(handle, "mlx_var_axis");- if (mlx_var_axis_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_var_axis\n");- return -1;- }- mlx_var_ptr = GET_SYM(handle, "mlx_var");- if (mlx_var_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_var\n");- return -1;- }- mlx_view_ptr = GET_SYM(handle, "mlx_view");- if (mlx_view_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_view\n");- return -1;- }- mlx_where_ptr = GET_SYM(handle, "mlx_where");- if (mlx_where_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_where\n");- return -1;- }- mlx_zeros_ptr = GET_SYM(handle, "mlx_zeros");- if (mlx_zeros_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_zeros\n");- return -1;- }- mlx_zeros_like_ptr = GET_SYM(handle, "mlx_zeros_like");- if (mlx_zeros_like_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_zeros_like\n");- return -1;- }- mlx_random_bernoulli_ptr = GET_SYM(handle, "mlx_random_bernoulli");- if (mlx_random_bernoulli_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_random_bernoulli\n");- return -1;- }- mlx_random_bits_ptr = GET_SYM(handle, "mlx_random_bits");- if (mlx_random_bits_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_random_bits\n");- return -1;- }- mlx_random_categorical_shape_ptr = GET_SYM(handle, "mlx_random_categorical_shape");- if (mlx_random_categorical_shape_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_random_categorical_shape\n");- return -1;- }- mlx_random_categorical_num_samples_ptr = GET_SYM(handle, "mlx_random_categorical_num_samples");- if (mlx_random_categorical_num_samples_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_random_categorical_num_samples\n");- return -1;- }- mlx_random_categorical_ptr = GET_SYM(handle, "mlx_random_categorical");- if (mlx_random_categorical_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_random_categorical\n");- return -1;- }- mlx_random_gumbel_ptr = GET_SYM(handle, "mlx_random_gumbel");- if (mlx_random_gumbel_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_random_gumbel\n");- return -1;- }- mlx_random_key_ptr = GET_SYM(handle, "mlx_random_key");- if (mlx_random_key_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_random_key\n");- return -1;- }- mlx_random_laplace_ptr = GET_SYM(handle, "mlx_random_laplace");- if (mlx_random_laplace_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_random_laplace\n");- return -1;- }- mlx_random_multivariate_normal_ptr = GET_SYM(handle, "mlx_random_multivariate_normal");- if (mlx_random_multivariate_normal_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_random_multivariate_normal\n");- return -1;- }- mlx_random_normal_broadcast_ptr = GET_SYM(handle, "mlx_random_normal_broadcast");- if (mlx_random_normal_broadcast_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_random_normal_broadcast\n");- return -1;- }- mlx_random_normal_ptr = GET_SYM(handle, "mlx_random_normal");- if (mlx_random_normal_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_random_normal\n");- return -1;- }- mlx_random_permutation_ptr = GET_SYM(handle, "mlx_random_permutation");- if (mlx_random_permutation_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_random_permutation\n");- return -1;- }- mlx_random_permutation_arange_ptr = GET_SYM(handle, "mlx_random_permutation_arange");- if (mlx_random_permutation_arange_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_random_permutation_arange\n");- return -1;- }- mlx_random_randint_ptr = GET_SYM(handle, "mlx_random_randint");- if (mlx_random_randint_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_random_randint\n");- return -1;- }- mlx_random_seed_ptr = GET_SYM(handle, "mlx_random_seed");- if (mlx_random_seed_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_random_seed\n");- return -1;- }- mlx_random_split_num_ptr = GET_SYM(handle, "mlx_random_split_num");- if (mlx_random_split_num_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_random_split_num\n");- return -1;- }- mlx_random_split_ptr = GET_SYM(handle, "mlx_random_split");- if (mlx_random_split_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_random_split\n");- return -1;- }- mlx_random_truncated_normal_ptr = GET_SYM(handle, "mlx_random_truncated_normal");- if (mlx_random_truncated_normal_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_random_truncated_normal\n");- return -1;- }- mlx_random_uniform_ptr = GET_SYM(handle, "mlx_random_uniform");- if (mlx_random_uniform_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_random_uniform\n");- return -1;- }- mlx_stream_new_ptr = GET_SYM(handle, "mlx_stream_new");- if (mlx_stream_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_stream_new\n");- return -1;- }- mlx_stream_new_device_ptr = GET_SYM(handle, "mlx_stream_new_device");- if (mlx_stream_new_device_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_stream_new_device\n");- return -1;- }- mlx_stream_set_ptr = GET_SYM(handle, "mlx_stream_set");- if (mlx_stream_set_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_stream_set\n");- return -1;- }- mlx_stream_free_ptr = GET_SYM(handle, "mlx_stream_free");- if (mlx_stream_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_stream_free\n");- return -1;- }- mlx_stream_tostring_ptr = GET_SYM(handle, "mlx_stream_tostring");- if (mlx_stream_tostring_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_stream_tostring\n");- return -1;- }- mlx_stream_equal_ptr = GET_SYM(handle, "mlx_stream_equal");- if (mlx_stream_equal_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_stream_equal\n");- return -1;- }- mlx_stream_get_device_ptr = GET_SYM(handle, "mlx_stream_get_device");- if (mlx_stream_get_device_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_stream_get_device\n");- return -1;- }- mlx_stream_get_index_ptr = GET_SYM(handle, "mlx_stream_get_index");- if (mlx_stream_get_index_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_stream_get_index\n");- return -1;- }- mlx_synchronize_ptr = GET_SYM(handle, "mlx_synchronize");- if (mlx_synchronize_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_synchronize\n");- return -1;- }- mlx_get_default_stream_ptr = GET_SYM(handle, "mlx_get_default_stream");- if (mlx_get_default_stream_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_get_default_stream\n");- return -1;- }- mlx_set_default_stream_ptr = GET_SYM(handle, "mlx_set_default_stream");- if (mlx_set_default_stream_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_set_default_stream\n");- return -1;- }- mlx_default_cpu_stream_new_ptr = GET_SYM(handle, "mlx_default_cpu_stream_new");- if (mlx_default_cpu_stream_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_default_cpu_stream_new\n");- return -1;- }- mlx_default_gpu_stream_new_ptr = GET_SYM(handle, "mlx_default_gpu_stream_new");- if (mlx_default_gpu_stream_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_default_gpu_stream_new\n");- return -1;- }- mlx_string_new_ptr = GET_SYM(handle, "mlx_string_new");- if (mlx_string_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_string_new\n");- return -1;- }- mlx_string_new_data_ptr = GET_SYM(handle, "mlx_string_new_data");- if (mlx_string_new_data_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_string_new_data\n");- return -1;- }- mlx_string_set_ptr = GET_SYM(handle, "mlx_string_set");- if (mlx_string_set_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_string_set\n");- return -1;- }- mlx_string_data_ptr = GET_SYM(handle, "mlx_string_data");- if (mlx_string_data_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_string_data\n");- return -1;- }- mlx_string_free_ptr = GET_SYM(handle, "mlx_string_free");- if (mlx_string_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_string_free\n");- return -1;- }- mlx_async_eval_ptr = GET_SYM(handle, "mlx_async_eval");- if (mlx_async_eval_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_async_eval\n");- return -1;- }- mlx_checkpoint_ptr = GET_SYM(handle, "mlx_checkpoint");- if (mlx_checkpoint_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_checkpoint\n");- return -1;- }- mlx_custom_function_ptr = GET_SYM(handle, "mlx_custom_function");- if (mlx_custom_function_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_custom_function\n");- return -1;- }- mlx_custom_vjp_ptr = GET_SYM(handle, "mlx_custom_vjp");- if (mlx_custom_vjp_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_custom_vjp\n");- return -1;- }- mlx_eval_ptr = GET_SYM(handle, "mlx_eval");- if (mlx_eval_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_eval\n");- return -1;- }- mlx_jvp_ptr = GET_SYM(handle, "mlx_jvp");- if (mlx_jvp_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_jvp\n");- return -1;- }- mlx_value_and_grad_ptr = GET_SYM(handle, "mlx_value_and_grad");- if (mlx_value_and_grad_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_value_and_grad\n");- return -1;- }- mlx_vjp_ptr = GET_SYM(handle, "mlx_vjp");- if (mlx_vjp_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vjp\n");- return -1;- }- mlx_detail_vmap_replace_ptr = GET_SYM(handle, "mlx_detail_vmap_replace");- if (mlx_detail_vmap_replace_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_detail_vmap_replace\n");- return -1;- }- mlx_detail_vmap_trace_ptr = GET_SYM(handle, "mlx_detail_vmap_trace");- if (mlx_detail_vmap_trace_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_detail_vmap_trace\n");- return -1;- }- mlx_vector_array_new_ptr = GET_SYM(handle, "mlx_vector_array_new");- if (mlx_vector_array_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_array_new\n");- return -1;- }- mlx_vector_array_set_ptr = GET_SYM(handle, "mlx_vector_array_set");- if (mlx_vector_array_set_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_array_set\n");- return -1;- }- mlx_vector_array_free_ptr = GET_SYM(handle, "mlx_vector_array_free");- if (mlx_vector_array_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_array_free\n");- return -1;- }- mlx_vector_array_new_data_ptr = GET_SYM(handle, "mlx_vector_array_new_data");- if (mlx_vector_array_new_data_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_array_new_data\n");- return -1;- }- mlx_vector_array_new_value_ptr = GET_SYM(handle, "mlx_vector_array_new_value");- if (mlx_vector_array_new_value_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_array_new_value\n");- return -1;- }- mlx_vector_array_set_data_ptr = GET_SYM(handle, "mlx_vector_array_set_data");- if (mlx_vector_array_set_data_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_array_set_data\n");- return -1;- }- mlx_vector_array_set_value_ptr = GET_SYM(handle, "mlx_vector_array_set_value");- if (mlx_vector_array_set_value_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_array_set_value\n");- return -1;- }- mlx_vector_array_append_data_ptr = GET_SYM(handle, "mlx_vector_array_append_data");- if (mlx_vector_array_append_data_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_array_append_data\n");- return -1;- }- mlx_vector_array_append_value_ptr = GET_SYM(handle, "mlx_vector_array_append_value");- if (mlx_vector_array_append_value_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_array_append_value\n");- return -1;- }- mlx_vector_array_size_ptr = GET_SYM(handle, "mlx_vector_array_size");- if (mlx_vector_array_size_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_array_size\n");- return -1;- }- mlx_vector_array_get_ptr = GET_SYM(handle, "mlx_vector_array_get");- if (mlx_vector_array_get_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_array_get\n");- return -1;- }- mlx_vector_vector_array_new_ptr = GET_SYM(handle, "mlx_vector_vector_array_new");- if (mlx_vector_vector_array_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_vector_array_new\n");- return -1;- }- mlx_vector_vector_array_set_ptr = GET_SYM(handle, "mlx_vector_vector_array_set");- if (mlx_vector_vector_array_set_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_vector_array_set\n");- return -1;- }- mlx_vector_vector_array_free_ptr = GET_SYM(handle, "mlx_vector_vector_array_free");- if (mlx_vector_vector_array_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_vector_array_free\n");- return -1;- }- mlx_vector_vector_array_new_data_ptr = GET_SYM(handle, "mlx_vector_vector_array_new_data");- if (mlx_vector_vector_array_new_data_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_vector_array_new_data\n");- return -1;- }- mlx_vector_vector_array_new_value_ptr = GET_SYM(handle, "mlx_vector_vector_array_new_value");- if (mlx_vector_vector_array_new_value_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_vector_array_new_value\n");- return -1;- }- mlx_vector_vector_array_set_data_ptr = GET_SYM(handle, "mlx_vector_vector_array_set_data");- if (mlx_vector_vector_array_set_data_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_vector_array_set_data\n");- return -1;- }- mlx_vector_vector_array_set_value_ptr = GET_SYM(handle, "mlx_vector_vector_array_set_value");- if (mlx_vector_vector_array_set_value_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_vector_array_set_value\n");- return -1;- }- mlx_vector_vector_array_append_data_ptr = GET_SYM(handle, "mlx_vector_vector_array_append_data");- if (mlx_vector_vector_array_append_data_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_vector_array_append_data\n");- return -1;- }- mlx_vector_vector_array_append_value_ptr = GET_SYM(handle, "mlx_vector_vector_array_append_value");- if (mlx_vector_vector_array_append_value_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_vector_array_append_value\n");- return -1;- }- mlx_vector_vector_array_size_ptr = GET_SYM(handle, "mlx_vector_vector_array_size");- if (mlx_vector_vector_array_size_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_vector_array_size\n");- return -1;- }- mlx_vector_vector_array_get_ptr = GET_SYM(handle, "mlx_vector_vector_array_get");- if (mlx_vector_vector_array_get_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_vector_array_get\n");- return -1;- }- mlx_vector_int_new_ptr = GET_SYM(handle, "mlx_vector_int_new");- if (mlx_vector_int_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_int_new\n");- return -1;- }- mlx_vector_int_set_ptr = GET_SYM(handle, "mlx_vector_int_set");- if (mlx_vector_int_set_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_int_set\n");- return -1;- }- mlx_vector_int_free_ptr = GET_SYM(handle, "mlx_vector_int_free");- if (mlx_vector_int_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_int_free\n");- return -1;- }- mlx_vector_int_new_data_ptr = GET_SYM(handle, "mlx_vector_int_new_data");- if (mlx_vector_int_new_data_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_int_new_data\n");- return -1;- }- mlx_vector_int_new_value_ptr = GET_SYM(handle, "mlx_vector_int_new_value");- if (mlx_vector_int_new_value_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_int_new_value\n");- return -1;- }- mlx_vector_int_set_data_ptr = GET_SYM(handle, "mlx_vector_int_set_data");- if (mlx_vector_int_set_data_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_int_set_data\n");- return -1;- }- mlx_vector_int_set_value_ptr = GET_SYM(handle, "mlx_vector_int_set_value");- if (mlx_vector_int_set_value_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_int_set_value\n");- return -1;- }- mlx_vector_int_append_data_ptr = GET_SYM(handle, "mlx_vector_int_append_data");- if (mlx_vector_int_append_data_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_int_append_data\n");- return -1;- }- mlx_vector_int_append_value_ptr = GET_SYM(handle, "mlx_vector_int_append_value");- if (mlx_vector_int_append_value_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_int_append_value\n");- return -1;- }- mlx_vector_int_size_ptr = GET_SYM(handle, "mlx_vector_int_size");- if (mlx_vector_int_size_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_int_size\n");- return -1;- }- mlx_vector_int_get_ptr = GET_SYM(handle, "mlx_vector_int_get");- if (mlx_vector_int_get_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_int_get\n");- return -1;- }- mlx_vector_string_new_ptr = GET_SYM(handle, "mlx_vector_string_new");- if (mlx_vector_string_new_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_string_new\n");- return -1;- }- mlx_vector_string_set_ptr = GET_SYM(handle, "mlx_vector_string_set");- if (mlx_vector_string_set_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_string_set\n");- return -1;- }- mlx_vector_string_free_ptr = GET_SYM(handle, "mlx_vector_string_free");- if (mlx_vector_string_free_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_string_free\n");- return -1;- }- mlx_vector_string_new_data_ptr = GET_SYM(handle, "mlx_vector_string_new_data");- if (mlx_vector_string_new_data_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_string_new_data\n");- return -1;- }- mlx_vector_string_new_value_ptr = GET_SYM(handle, "mlx_vector_string_new_value");- if (mlx_vector_string_new_value_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_string_new_value\n");- return -1;- }- mlx_vector_string_set_data_ptr = GET_SYM(handle, "mlx_vector_string_set_data");- if (mlx_vector_string_set_data_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_string_set_data\n");- return -1;- }- mlx_vector_string_set_value_ptr = GET_SYM(handle, "mlx_vector_string_set_value");- if (mlx_vector_string_set_value_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_string_set_value\n");- return -1;- }- mlx_vector_string_append_data_ptr = GET_SYM(handle, "mlx_vector_string_append_data");- if (mlx_vector_string_append_data_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_string_append_data\n");- return -1;- }- mlx_vector_string_append_value_ptr = GET_SYM(handle, "mlx_vector_string_append_value");- if (mlx_vector_string_append_value_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_string_append_value\n");- return -1;- }- mlx_vector_string_size_ptr = GET_SYM(handle, "mlx_vector_string_size");- if (mlx_vector_string_size_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_string_size\n");- return -1;- }- mlx_vector_string_get_ptr = GET_SYM(handle, "mlx_vector_string_get");- if (mlx_vector_string_get_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_vector_string_get\n");- return -1;- }- mlx_version_ptr = GET_SYM(handle, "mlx_version");- if (mlx_version_ptr == NULL) {- fprintf(stderr, "MLX: Failed to load symbol: mlx_version\n");- return -1;- }- return 0;-}--// Wrapper function implementations that call through function pointers-size_t mlx_dtype_size(mlx_dtype dtype) {- return mlx_dtype_size_ptr(dtype);-}--int mlx_array_tostring(mlx_string* str, const mlx_array arr) {- return mlx_array_tostring_ptr(str, arr);-}--mlx_array mlx_array_new(void) {- return mlx_array_new_ptr();-}--int mlx_array_free(mlx_array arr) {- return mlx_array_free_ptr(arr);-}--mlx_array mlx_array_new_bool(bool val) {- return mlx_array_new_bool_ptr(val);-}--mlx_array mlx_array_new_int(int val) {- return mlx_array_new_int_ptr(val);-}--mlx_array mlx_array_new_float32(float val) {- return mlx_array_new_float32_ptr(val);-}--mlx_array mlx_array_new_float(float val) {- return mlx_array_new_float_ptr(val);-}--mlx_array mlx_array_new_float64(double val) {- return mlx_array_new_float64_ptr(val);-}--mlx_array mlx_array_new_double(double val) {- return mlx_array_new_double_ptr(val);-}--mlx_array mlx_array_new_complex(float real_val, float imag_val) {- return mlx_array_new_complex_ptr(real_val, imag_val);-}--mlx_array mlx_array_new_data(const void* data, const int* shape, int dim, mlx_dtype dtype) {- return mlx_array_new_data_ptr(data, shape, dim, dtype);-}--mlx_array mlx_array_new_data_managed(void* data, const int* shape, int dim, mlx_dtype dtype, void (*dtor)(void*)) {- return mlx_array_new_data_managed_ptr(data, shape, dim, dtype, dtor);-}--mlx_array mlx_array_new_data_managed_payload(void* data, const int* shape, int dim, mlx_dtype dtype, void* payload, void (*dtor)(void*)) {- return mlx_array_new_data_managed_payload_ptr(data, shape, dim, dtype, payload, dtor);-}--int mlx_array_set(mlx_array* arr, const mlx_array src) {- return mlx_array_set_ptr(arr, src);-}--int mlx_array_set_bool(mlx_array* arr, bool val) {- return mlx_array_set_bool_ptr(arr, val);-}--int mlx_array_set_int(mlx_array* arr, int val) {- return mlx_array_set_int_ptr(arr, val);-}--int mlx_array_set_float32(mlx_array* arr, float val) {- return mlx_array_set_float32_ptr(arr, val);-}--int mlx_array_set_float(mlx_array* arr, float val) {- return mlx_array_set_float_ptr(arr, val);-}--int mlx_array_set_float64(mlx_array* arr, double val) {- return mlx_array_set_float64_ptr(arr, val);-}--int mlx_array_set_double(mlx_array* arr, double val) {- return mlx_array_set_double_ptr(arr, val);-}--int mlx_array_set_complex(mlx_array* arr, float real_val, float imag_val) {- return mlx_array_set_complex_ptr(arr, real_val, imag_val);-}--int mlx_array_set_data(mlx_array* arr, const void* data, const int* shape, int dim, mlx_dtype dtype) {- return mlx_array_set_data_ptr(arr, data, shape, dim, dtype);-}--size_t mlx_array_itemsize(const mlx_array arr) {- return mlx_array_itemsize_ptr(arr);-}--size_t mlx_array_size(const mlx_array arr) {- return mlx_array_size_ptr(arr);-}--size_t mlx_array_nbytes(const mlx_array arr) {- return mlx_array_nbytes_ptr(arr);-}--size_t mlx_array_ndim(const mlx_array arr) {- return mlx_array_ndim_ptr(arr);-}--const int* mlx_array_shape(const mlx_array arr) {- return mlx_array_shape_ptr(arr);-}--const size_t* mlx_array_strides(const mlx_array arr) {- return mlx_array_strides_ptr(arr);-}--int mlx_array_dim(const mlx_array arr, int dim) {- return mlx_array_dim_ptr(arr, dim);-}--mlx_dtype mlx_array_dtype(const mlx_array arr) {- return mlx_array_dtype_ptr(arr);-}--int mlx_array_eval(mlx_array arr) {- return mlx_array_eval_ptr(arr);-}--int mlx_array_item_bool(bool* res, const mlx_array arr) {- return mlx_array_item_bool_ptr(res, arr);-}--int mlx_array_item_uint8(uint8_t* res, const mlx_array arr) {- return mlx_array_item_uint8_ptr(res, arr);-}--int mlx_array_item_uint16(uint16_t* res, const mlx_array arr) {- return mlx_array_item_uint16_ptr(res, arr);-}--int mlx_array_item_uint32(uint32_t* res, const mlx_array arr) {- return mlx_array_item_uint32_ptr(res, arr);-}--int mlx_array_item_uint64(uint64_t* res, const mlx_array arr) {- return mlx_array_item_uint64_ptr(res, arr);-}--int mlx_array_item_int8(int8_t* res, const mlx_array arr) {- return mlx_array_item_int8_ptr(res, arr);-}--int mlx_array_item_int16(int16_t* res, const mlx_array arr) {- return mlx_array_item_int16_ptr(res, arr);-}--int mlx_array_item_int32(int32_t* res, const mlx_array arr) {- return mlx_array_item_int32_ptr(res, arr);-}--int mlx_array_item_int64(int64_t* res, const mlx_array arr) {- return mlx_array_item_int64_ptr(res, arr);-}--int mlx_array_item_float32(float* res, const mlx_array arr) {- return mlx_array_item_float32_ptr(res, arr);-}--int mlx_array_item_float64(double* res, const mlx_array arr) {- return mlx_array_item_float64_ptr(res, arr);-}--int mlx_array_item_complex64(mlx_complex64_t* res, const mlx_array arr) {- return mlx_array_item_complex64_ptr(res, arr);-}--#if defined(__aarch64__) || defined(_M_ARM64)-int mlx_array_item_float16(float16_t* res, const mlx_array arr) {- return mlx_array_item_float16_ptr(res, arr);-}-#endif--#if defined(__aarch64__) || defined(_M_ARM64)-int mlx_array_item_bfloat16(bfloat16_t* res, const mlx_array arr) {- return mlx_array_item_bfloat16_ptr(res, arr);-}-#endif--const bool* mlx_array_data_bool(const mlx_array arr) {- return mlx_array_data_bool_ptr(arr);-}--const uint8_t* mlx_array_data_uint8(const mlx_array arr) {- return mlx_array_data_uint8_ptr(arr);-}--const uint16_t* mlx_array_data_uint16(const mlx_array arr) {- return mlx_array_data_uint16_ptr(arr);-}--const uint32_t* mlx_array_data_uint32(const mlx_array arr) {- return mlx_array_data_uint32_ptr(arr);-}--const uint64_t* mlx_array_data_uint64(const mlx_array arr) {- return mlx_array_data_uint64_ptr(arr);-}--const int8_t* mlx_array_data_int8(const mlx_array arr) {- return mlx_array_data_int8_ptr(arr);-}--const int16_t* mlx_array_data_int16(const mlx_array arr) {- return mlx_array_data_int16_ptr(arr);-}--const int32_t* mlx_array_data_int32(const mlx_array arr) {- return mlx_array_data_int32_ptr(arr);-}--const int64_t* mlx_array_data_int64(const mlx_array arr) {- return mlx_array_data_int64_ptr(arr);-}--const float* mlx_array_data_float32(const mlx_array arr) {- return mlx_array_data_float32_ptr(arr);-}--const double* mlx_array_data_float64(const mlx_array arr) {- return mlx_array_data_float64_ptr(arr);-}--const mlx_complex64_t* mlx_array_data_complex64(const mlx_array arr) {- return mlx_array_data_complex64_ptr(arr);-}--#if defined(__aarch64__) || defined(_M_ARM64)-const float16_t* mlx_array_data_float16(const mlx_array arr) {- return mlx_array_data_float16_ptr(arr);-}-#endif--#if defined(__aarch64__) || defined(_M_ARM64)-const bfloat16_t* mlx_array_data_bfloat16(const mlx_array arr) {- return mlx_array_data_bfloat16_ptr(arr);-}-#endif--int _mlx_array_is_available(bool* res, const mlx_array arr) {- return _mlx_array_is_available_ptr(res, arr);-}--int _mlx_array_wait(const mlx_array arr) {- return _mlx_array_wait_ptr(arr);-}--int _mlx_array_is_contiguous(bool* res, const mlx_array arr) {- return _mlx_array_is_contiguous_ptr(res, arr);-}--int _mlx_array_is_row_contiguous(bool* res, const mlx_array arr) {- return _mlx_array_is_row_contiguous_ptr(res, arr);-}--int _mlx_array_is_col_contiguous(bool* res, const mlx_array arr) {- return _mlx_array_is_col_contiguous_ptr(res, arr);-}--mlx_closure mlx_closure_new(void) {- return mlx_closure_new_ptr();-}--int mlx_closure_free(mlx_closure cls) {- return mlx_closure_free_ptr(cls);-}--mlx_closure mlx_closure_new_func(int (*fun)(mlx_vector_array*, const mlx_vector_array)) {- return mlx_closure_new_func_ptr(fun);-}--mlx_closure mlx_closure_new_func_payload(int (*fun)(mlx_vector_array*, const mlx_vector_array, void*), void* payload, void (*dtor)(void*)) {- return mlx_closure_new_func_payload_ptr(fun, payload, dtor);-}--int mlx_closure_set(mlx_closure* cls, const mlx_closure src) {- return mlx_closure_set_ptr(cls, src);-}--int mlx_closure_apply(mlx_vector_array* res, mlx_closure cls, const mlx_vector_array input) {- return mlx_closure_apply_ptr(res, cls, input);-}--mlx_closure mlx_closure_new_unary(int (*fun)(mlx_array*, const mlx_array)) {- return mlx_closure_new_unary_ptr(fun);-}--mlx_closure_kwargs mlx_closure_kwargs_new(void) {- return mlx_closure_kwargs_new_ptr();-}--int mlx_closure_kwargs_free(mlx_closure_kwargs cls) {- return mlx_closure_kwargs_free_ptr(cls);-}--mlx_closure_kwargs mlx_closure_kwargs_new_func(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_map_string_to_array)) {- return mlx_closure_kwargs_new_func_ptr(fun);-}--mlx_closure_kwargs mlx_closure_kwargs_new_func_payload(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_map_string_to_array, void*), void* payload, void (*dtor)(void*)) {- return mlx_closure_kwargs_new_func_payload_ptr(fun, payload, dtor);-}--int mlx_closure_kwargs_set(mlx_closure_kwargs* cls, const mlx_closure_kwargs src) {- return mlx_closure_kwargs_set_ptr(cls, src);-}--int mlx_closure_kwargs_apply(mlx_vector_array* res, mlx_closure_kwargs cls, const mlx_vector_array input_0, const mlx_map_string_to_array input_1) {- return mlx_closure_kwargs_apply_ptr(res, cls, input_0, input_1);-}--mlx_closure_value_and_grad mlx_closure_value_and_grad_new(void) {- return mlx_closure_value_and_grad_new_ptr();-}--int mlx_closure_value_and_grad_free(mlx_closure_value_and_grad cls) {- return mlx_closure_value_and_grad_free_ptr(cls);-}--mlx_closure_value_and_grad mlx_closure_value_and_grad_new_func(int (*fun)(mlx_vector_array*, mlx_vector_array*, const mlx_vector_array)) {- return mlx_closure_value_and_grad_new_func_ptr(fun);-}--mlx_closure_value_and_grad mlx_closure_value_and_grad_new_func_payload(int (*fun)( mlx_vector_array*, mlx_vector_array*, const mlx_vector_array, void*), void* payload, void (*dtor)(void*)) {- return mlx_closure_value_and_grad_new_func_payload_ptr(fun, payload, dtor);-}--int mlx_closure_value_and_grad_set(mlx_closure_value_and_grad* cls, const mlx_closure_value_and_grad src) {- return mlx_closure_value_and_grad_set_ptr(cls, src);-}--int mlx_closure_value_and_grad_apply(mlx_vector_array* res_0, mlx_vector_array* res_1, mlx_closure_value_and_grad cls, const mlx_vector_array input) {- return mlx_closure_value_and_grad_apply_ptr(res_0, res_1, cls, input);-}--mlx_closure_custom mlx_closure_custom_new(void) {- return mlx_closure_custom_new_ptr();-}--int mlx_closure_custom_free(mlx_closure_custom cls) {- return mlx_closure_custom_free_ptr(cls);-}--mlx_closure_custom mlx_closure_custom_new_func(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_vector_array, const mlx_vector_array)) {- return mlx_closure_custom_new_func_ptr(fun);-}--mlx_closure_custom mlx_closure_custom_new_func_payload(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_vector_array, const mlx_vector_array, void*), void* payload, void (*dtor)(void*)) {- return mlx_closure_custom_new_func_payload_ptr(fun, payload, dtor);-}--int mlx_closure_custom_set(mlx_closure_custom* cls, const mlx_closure_custom src) {- return mlx_closure_custom_set_ptr(cls, src);-}--int mlx_closure_custom_apply(mlx_vector_array* res, mlx_closure_custom cls, const mlx_vector_array input_0, const mlx_vector_array input_1, const mlx_vector_array input_2) {- return mlx_closure_custom_apply_ptr(res, cls, input_0, input_1, input_2);-}--mlx_closure_custom_jvp mlx_closure_custom_jvp_new(void) {- return mlx_closure_custom_jvp_new_ptr();-}--int mlx_closure_custom_jvp_free(mlx_closure_custom_jvp cls) {- return mlx_closure_custom_jvp_free_ptr(cls);-}--mlx_closure_custom_jvp mlx_closure_custom_jvp_new_func(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_vector_array, const int*, size_t _num)) {- return mlx_closure_custom_jvp_new_func_ptr(fun);-}--mlx_closure_custom_jvp mlx_closure_custom_jvp_new_func_payload(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_vector_array, const int*, size_t _num, void*), void* payload, void (*dtor)(void*)) {- return mlx_closure_custom_jvp_new_func_payload_ptr(fun, payload, dtor);-}--int mlx_closure_custom_jvp_set(mlx_closure_custom_jvp* cls, const mlx_closure_custom_jvp src) {- return mlx_closure_custom_jvp_set_ptr(cls, src);-}--int mlx_closure_custom_jvp_apply(mlx_vector_array* res, mlx_closure_custom_jvp cls, const mlx_vector_array input_0, const mlx_vector_array input_1, const int* input_2, size_t input_2_num) {- return mlx_closure_custom_jvp_apply_ptr(res, cls, input_0, input_1, input_2, input_2_num);-}--mlx_closure_custom_vmap mlx_closure_custom_vmap_new(void) {- return mlx_closure_custom_vmap_new_ptr();-}--int mlx_closure_custom_vmap_free(mlx_closure_custom_vmap cls) {- return mlx_closure_custom_vmap_free_ptr(cls);-}--mlx_closure_custom_vmap mlx_closure_custom_vmap_new_func(int (*fun)( mlx_vector_array*, mlx_vector_int*, const mlx_vector_array, const int*, size_t _num)) {- return mlx_closure_custom_vmap_new_func_ptr(fun);-}--mlx_closure_custom_vmap mlx_closure_custom_vmap_new_func_payload(int (*fun)( mlx_vector_array*, mlx_vector_int*, const mlx_vector_array, const int*, size_t _num, void*), void* payload, void (*dtor)(void*)) {- return mlx_closure_custom_vmap_new_func_payload_ptr(fun, payload, dtor);-}--int mlx_closure_custom_vmap_set(mlx_closure_custom_vmap* cls, const mlx_closure_custom_vmap src) {- return mlx_closure_custom_vmap_set_ptr(cls, src);-}--int mlx_closure_custom_vmap_apply(mlx_vector_array* res_0, mlx_vector_int* res_1, mlx_closure_custom_vmap cls, const mlx_vector_array input_0, const int* input_1, size_t input_1_num) {- return mlx_closure_custom_vmap_apply_ptr(res_0, res_1, cls, input_0, input_1, input_1_num);-}--int mlx_compile(mlx_closure* res, const mlx_closure fun, bool shapeless) {- return mlx_compile_ptr(res, fun, shapeless);-}--int mlx_detail_compile(mlx_closure* res, const mlx_closure fun, uintptr_t fun_id, bool shapeless, const uint64_t* constants, size_t constants_num) {- return mlx_detail_compile_ptr(res, fun, fun_id, shapeless, constants, constants_num);-}--int mlx_detail_compile_clear_cache(void) {- return mlx_detail_compile_clear_cache_ptr();-}--int mlx_detail_compile_erase(uintptr_t fun_id) {- return mlx_detail_compile_erase_ptr(fun_id);-}--int mlx_disable_compile(void) {- return mlx_disable_compile_ptr();-}--int mlx_enable_compile(void) {- return mlx_enable_compile_ptr();-}--int mlx_set_compile_mode(mlx_compile_mode mode) {- return mlx_set_compile_mode_ptr(mode);-}--int mlx_cuda_is_available(bool* res) {- return mlx_cuda_is_available_ptr(res);-}--mlx_device mlx_device_new(void) {- return mlx_device_new_ptr();-}--mlx_device mlx_device_new_type(mlx_device_type type, int index) {- return mlx_device_new_type_ptr(type, index);-}--int mlx_device_free(mlx_device dev) {- return mlx_device_free_ptr(dev);-}--int mlx_device_set(mlx_device* dev, const mlx_device src) {- return mlx_device_set_ptr(dev, src);-}--int mlx_device_tostring(mlx_string* str, mlx_device dev) {- return mlx_device_tostring_ptr(str, dev);-}--bool mlx_device_equal(mlx_device lhs, mlx_device rhs) {- return mlx_device_equal_ptr(lhs, rhs);-}--int mlx_device_get_index(int* index, mlx_device dev) {- return mlx_device_get_index_ptr(index, dev);-}--int mlx_device_get_type(mlx_device_type* type, mlx_device dev) {- return mlx_device_get_type_ptr(type, dev);-}--int mlx_get_default_device(mlx_device* dev) {- return mlx_get_default_device_ptr(dev);-}--int mlx_set_default_device(mlx_device dev) {- return mlx_set_default_device_ptr(dev);-}--int mlx_device_is_available(bool* avail, mlx_device dev) {- return mlx_device_is_available_ptr(avail, dev);-}--int mlx_device_count(int* count, mlx_device_type type) {- return mlx_device_count_ptr(count, type);-}--mlx_device_info mlx_device_info_new(void) {- return mlx_device_info_new_ptr();-}--int mlx_device_info_get(mlx_device_info* info, mlx_device dev) {- return mlx_device_info_get_ptr(info, dev);-}--int mlx_device_info_free(mlx_device_info info) {- return mlx_device_info_free_ptr(info);-}--int mlx_device_info_has_key(bool* exists, mlx_device_info info, const char* key) {- return mlx_device_info_has_key_ptr(exists, info, key);-}--int mlx_device_info_is_string(bool* is_string, mlx_device_info info, const char* key) {- return mlx_device_info_is_string_ptr(is_string, info, key);-}--int mlx_device_info_get_string(const char** value, mlx_device_info info, const char* key) {- return mlx_device_info_get_string_ptr(value, info, key);-}--int mlx_device_info_get_size(size_t* value, mlx_device_info info, const char* key) {- return mlx_device_info_get_size_ptr(value, info, key);-}--int mlx_device_info_get_keys(mlx_vector_string* keys, mlx_device_info info) {- return mlx_device_info_get_keys_ptr(keys, info);-}--int mlx_distributed_all_gather(mlx_array* res, const mlx_array x, const mlx_distributed_group group , const mlx_stream S) {- return mlx_distributed_all_gather_ptr(res, x, group, S);-}--int mlx_distributed_all_max(mlx_array* res, const mlx_array x, const mlx_distributed_group group , const mlx_stream s) {- return mlx_distributed_all_max_ptr(res, x, group, s);-}--int mlx_distributed_all_min(mlx_array* res, const mlx_array x, const mlx_distributed_group group , const mlx_stream s) {- return mlx_distributed_all_min_ptr(res, x, group, s);-}--int mlx_distributed_all_sum(mlx_array* res, const mlx_array x, const mlx_distributed_group group , const mlx_stream s) {- return mlx_distributed_all_sum_ptr(res, x, group, s);-}--int mlx_distributed_recv(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, int src, const mlx_distributed_group group , const mlx_stream s) {- return mlx_distributed_recv_ptr(res, shape, shape_num, dtype, src, group, s);-}--int mlx_distributed_recv_like(mlx_array* res, const mlx_array x, int src, const mlx_distributed_group group , const mlx_stream s) {- return mlx_distributed_recv_like_ptr(res, x, src, group, s);-}--int mlx_distributed_send(mlx_array* res, const mlx_array x, int dst, const mlx_distributed_group group , const mlx_stream s) {- return mlx_distributed_send_ptr(res, x, dst, group, s);-}--int mlx_distributed_sum_scatter(mlx_array* res, const mlx_array x, const mlx_distributed_group group , const mlx_stream s) {- return mlx_distributed_sum_scatter_ptr(res, x, group, s);-}--mlx_distributed_group mlx_distributed_group_new(void) {- return mlx_distributed_group_new_ptr();-}--int mlx_distributed_group_free(mlx_distributed_group group) {- return mlx_distributed_group_free_ptr(group);-}--int mlx_distributed_init(mlx_distributed_group* res, bool strict, const char* bk) {- return mlx_distributed_init_ptr(res, strict, bk);-}--int mlx_distributed_group_rank(mlx_distributed_group group) {- return mlx_distributed_group_rank_ptr(group);-}--int mlx_distributed_group_size(mlx_distributed_group group) {- return mlx_distributed_group_size_ptr(group);-}--int mlx_distributed_group_split(mlx_distributed_group* res, mlx_distributed_group group, int color, int key) {- return mlx_distributed_group_split_ptr(res, group, color, key);-}--bool mlx_distributed_is_available(const char* bk) {- return mlx_distributed_is_available_ptr(bk);-}--void mlx_set_error_handler(mlx_error_handler_func handler, void* data, void (*dtor)(void*)) {- mlx_set_error_handler_ptr(handler, data, dtor);-}--void _mlx_error(const char* file, const int line, const char* fmt, ...) {- _mlx_error_ptr(file, line, fmt);-}--int mlx_export_function(const char* file, const mlx_closure fun, const mlx_vector_array args, bool shapeless) {- return mlx_export_function_ptr(file, fun, args, shapeless);-}--int mlx_export_function_kwargs(const char* file, const mlx_closure_kwargs fun, const mlx_vector_array args, const mlx_map_string_to_array kwargs, bool shapeless) {- return mlx_export_function_kwargs_ptr(file, fun, args, kwargs, shapeless);-}--mlx_function_exporter mlx_function_exporter_new(const char* file, const mlx_closure fun, bool shapeless) {- return mlx_function_exporter_new_ptr(file, fun, shapeless);-}--int mlx_function_exporter_free(mlx_function_exporter xfunc) {- return mlx_function_exporter_free_ptr(xfunc);-}--int mlx_function_exporter_apply(const mlx_function_exporter xfunc, const mlx_vector_array args) {- return mlx_function_exporter_apply_ptr(xfunc, args);-}--int mlx_function_exporter_apply_kwargs(const mlx_function_exporter xfunc, const mlx_vector_array args, const mlx_map_string_to_array kwargs) {- return mlx_function_exporter_apply_kwargs_ptr(xfunc, args, kwargs);-}--mlx_imported_function mlx_imported_function_new(const char* file) {- return mlx_imported_function_new_ptr(file);-}--int mlx_imported_function_free(mlx_imported_function xfunc) {- return mlx_imported_function_free_ptr(xfunc);-}--int mlx_imported_function_apply(mlx_vector_array* res, const mlx_imported_function xfunc, const mlx_vector_array args) {- return mlx_imported_function_apply_ptr(res, xfunc, args);-}--int mlx_imported_function_apply_kwargs(mlx_vector_array* res, const mlx_imported_function xfunc, const mlx_vector_array args, const mlx_map_string_to_array kwargs) {- return mlx_imported_function_apply_kwargs_ptr(res, xfunc, args, kwargs);-}--mlx_fast_cuda_kernel_config mlx_fast_cuda_kernel_config_new(void) {- return mlx_fast_cuda_kernel_config_new_ptr();-}--void mlx_fast_cuda_kernel_config_free(mlx_fast_cuda_kernel_config cls) {- mlx_fast_cuda_kernel_config_free_ptr(cls);-}--int mlx_fast_cuda_kernel_config_add_output_arg(mlx_fast_cuda_kernel_config cls, const int* shape, size_t size, mlx_dtype dtype) {- return mlx_fast_cuda_kernel_config_add_output_arg_ptr(cls, shape, size, dtype);-}--int mlx_fast_cuda_kernel_config_set_grid(mlx_fast_cuda_kernel_config cls, int grid1, int grid2, int grid3) {- return mlx_fast_cuda_kernel_config_set_grid_ptr(cls, grid1, grid2, grid3);-}--int mlx_fast_cuda_kernel_config_set_thread_group(mlx_fast_cuda_kernel_config cls, int thread1, int thread2, int thread3) {- return mlx_fast_cuda_kernel_config_set_thread_group_ptr(cls, thread1, thread2, thread3);-}--int mlx_fast_cuda_kernel_config_set_init_value(mlx_fast_cuda_kernel_config cls, float value) {- return mlx_fast_cuda_kernel_config_set_init_value_ptr(cls, value);-}--int mlx_fast_cuda_kernel_config_set_verbose(mlx_fast_cuda_kernel_config cls, bool verbose) {- return mlx_fast_cuda_kernel_config_set_verbose_ptr(cls, verbose);-}--int mlx_fast_cuda_kernel_config_add_template_arg_dtype(mlx_fast_cuda_kernel_config cls, const char* name, mlx_dtype dtype) {- return mlx_fast_cuda_kernel_config_add_template_arg_dtype_ptr(cls, name, dtype);-}--int mlx_fast_cuda_kernel_config_add_template_arg_int(mlx_fast_cuda_kernel_config cls, const char* name, int value) {- return mlx_fast_cuda_kernel_config_add_template_arg_int_ptr(cls, name, value);-}--int mlx_fast_cuda_kernel_config_add_template_arg_bool(mlx_fast_cuda_kernel_config cls, const char* name, bool value) {- return mlx_fast_cuda_kernel_config_add_template_arg_bool_ptr(cls, name, value);-}--mlx_fast_cuda_kernel mlx_fast_cuda_kernel_new(const char* name, const mlx_vector_string input_names, const mlx_vector_string output_names, const char* source, const char* header, bool ensure_row_contiguous, int shared_memory) {- return mlx_fast_cuda_kernel_new_ptr(name, input_names, output_names, source, header, ensure_row_contiguous, shared_memory);-}--void mlx_fast_cuda_kernel_free(mlx_fast_cuda_kernel cls) {- mlx_fast_cuda_kernel_free_ptr(cls);-}--int mlx_fast_cuda_kernel_apply(mlx_vector_array* outputs, mlx_fast_cuda_kernel cls, const mlx_vector_array inputs, const mlx_fast_cuda_kernel_config config, const mlx_stream stream) {- return mlx_fast_cuda_kernel_apply_ptr(outputs, cls, inputs, config, stream);-}--int mlx_fast_layer_norm(mlx_array* res, const mlx_array x, const mlx_array weight , const mlx_array bias , float eps, const mlx_stream s) {- return mlx_fast_layer_norm_ptr(res, x, weight, bias, eps, s);-}--mlx_fast_metal_kernel_config mlx_fast_metal_kernel_config_new(void) {- return mlx_fast_metal_kernel_config_new_ptr();-}--void mlx_fast_metal_kernel_config_free(mlx_fast_metal_kernel_config cls) {- mlx_fast_metal_kernel_config_free_ptr(cls);-}--int mlx_fast_metal_kernel_config_add_output_arg(mlx_fast_metal_kernel_config cls, const int* shape, size_t size, mlx_dtype dtype) {- return mlx_fast_metal_kernel_config_add_output_arg_ptr(cls, shape, size, dtype);-}--int mlx_fast_metal_kernel_config_set_grid(mlx_fast_metal_kernel_config cls, int grid1, int grid2, int grid3) {- return mlx_fast_metal_kernel_config_set_grid_ptr(cls, grid1, grid2, grid3);-}--int mlx_fast_metal_kernel_config_set_thread_group(mlx_fast_metal_kernel_config cls, int thread1, int thread2, int thread3) {- return mlx_fast_metal_kernel_config_set_thread_group_ptr(cls, thread1, thread2, thread3);-}--int mlx_fast_metal_kernel_config_set_init_value(mlx_fast_metal_kernel_config cls, float value) {- return mlx_fast_metal_kernel_config_set_init_value_ptr(cls, value);-}--int mlx_fast_metal_kernel_config_set_verbose(mlx_fast_metal_kernel_config cls, bool verbose) {- return mlx_fast_metal_kernel_config_set_verbose_ptr(cls, verbose);-}--int mlx_fast_metal_kernel_config_add_template_arg_dtype(mlx_fast_metal_kernel_config cls, const char* name, mlx_dtype dtype) {- return mlx_fast_metal_kernel_config_add_template_arg_dtype_ptr(cls, name, dtype);-}--int mlx_fast_metal_kernel_config_add_template_arg_int(mlx_fast_metal_kernel_config cls, const char* name, int value) {- return mlx_fast_metal_kernel_config_add_template_arg_int_ptr(cls, name, value);-}--int mlx_fast_metal_kernel_config_add_template_arg_bool(mlx_fast_metal_kernel_config cls, const char* name, bool value) {- return mlx_fast_metal_kernel_config_add_template_arg_bool_ptr(cls, name, value);-}--mlx_fast_metal_kernel mlx_fast_metal_kernel_new(const char* name, const mlx_vector_string input_names, const mlx_vector_string output_names, const char* source, const char* header, bool ensure_row_contiguous, bool atomic_outputs) {- return mlx_fast_metal_kernel_new_ptr(name, input_names, output_names, source, header, ensure_row_contiguous, atomic_outputs);-}--void mlx_fast_metal_kernel_free(mlx_fast_metal_kernel cls) {- mlx_fast_metal_kernel_free_ptr(cls);-}--int mlx_fast_metal_kernel_apply(mlx_vector_array* outputs, mlx_fast_metal_kernel cls, const mlx_vector_array inputs, const mlx_fast_metal_kernel_config config, const mlx_stream stream) {- return mlx_fast_metal_kernel_apply_ptr(outputs, cls, inputs, config, stream);-}--int mlx_fast_rms_norm(mlx_array* res, const mlx_array x, const mlx_array weight , float eps, const mlx_stream s) {- return mlx_fast_rms_norm_ptr(res, x, weight, eps, s);-}--int mlx_fast_rope(mlx_array* res, const mlx_array x, int dims, bool traditional, mlx_optional_float base, float scale, int offset, const mlx_array freqs , const mlx_stream s) {- return mlx_fast_rope_ptr(res, x, dims, traditional, base, scale, offset, freqs, s);-}--int mlx_fast_rope_dynamic(mlx_array* res, const mlx_array x, int dims, bool traditional, mlx_optional_float base, float scale, const mlx_array offset, const mlx_array freqs , const mlx_stream s) {- return mlx_fast_rope_dynamic_ptr(res, x, dims, traditional, base, scale, offset, freqs, s);-}--int mlx_fast_scaled_dot_product_attention(mlx_array* res, const mlx_array queries, const mlx_array keys, const mlx_array values, float scale, const char* mask_mode, const mlx_array mask_arr , const mlx_array sinks , const mlx_stream s) {- return mlx_fast_scaled_dot_product_attention_ptr(res, queries, keys, values, scale, mask_mode, mask_arr, sinks, s);-}--int mlx_fft_fft(mlx_array* res, const mlx_array a, int n, int axis, mlx_fft_norm norm, const mlx_stream s) {- return mlx_fft_fft_ptr(res, a, n, axis, norm, s);-}--int mlx_fft_fft2(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s) {- return mlx_fft_fft2_ptr(res, a, n, n_num, axes, axes_num, norm, s);-}--int mlx_fft_fftfreq(mlx_array* res, int n, double d, const mlx_stream s) {- return mlx_fft_fftfreq_ptr(res, n, d, s);-}--int mlx_fft_fftn(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s) {- return mlx_fft_fftn_ptr(res, a, n, n_num, axes, axes_num, norm, s);-}--int mlx_fft_fftshift(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const mlx_stream s) {- return mlx_fft_fftshift_ptr(res, a, axes, axes_num, s);-}--int mlx_fft_ifft(mlx_array* res, const mlx_array a, int n, int axis, mlx_fft_norm norm, const mlx_stream s) {- return mlx_fft_ifft_ptr(res, a, n, axis, norm, s);-}--int mlx_fft_ifft2(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s) {- return mlx_fft_ifft2_ptr(res, a, n, n_num, axes, axes_num, norm, s);-}--int mlx_fft_ifftn(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s) {- return mlx_fft_ifftn_ptr(res, a, n, n_num, axes, axes_num, norm, s);-}--int mlx_fft_ifftshift(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const mlx_stream s) {- return mlx_fft_ifftshift_ptr(res, a, axes, axes_num, s);-}--int mlx_fft_irfft(mlx_array* res, const mlx_array a, int n, int axis, mlx_fft_norm norm, const mlx_stream s) {- return mlx_fft_irfft_ptr(res, a, n, axis, norm, s);-}--int mlx_fft_irfft2(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s) {- return mlx_fft_irfft2_ptr(res, a, n, n_num, axes, axes_num, norm, s);-}--int mlx_fft_irfftn(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s) {- return mlx_fft_irfftn_ptr(res, a, n, n_num, axes, axes_num, norm, s);-}--int mlx_fft_rfft(mlx_array* res, const mlx_array a, int n, int axis, mlx_fft_norm norm, const mlx_stream s) {- return mlx_fft_rfft_ptr(res, a, n, axis, norm, s);-}--int mlx_fft_rfft2(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s) {- return mlx_fft_rfft2_ptr(res, a, n, n_num, axes, axes_num, norm, s);-}--int mlx_fft_rfftfreq(mlx_array* res, int n, double d, const mlx_stream s) {- return mlx_fft_rfftfreq_ptr(res, n, d, s);-}--int mlx_fft_rfftn(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s) {- return mlx_fft_rfftn_ptr(res, a, n, n_num, axes, axes_num, norm, s);-}--int mlx_node_namer_free(mlx_node_namer namer) {- return mlx_node_namer_free_ptr(namer);-}--int mlx_node_namer_set_name(mlx_node_namer namer, const mlx_array arr, const char* name) {- return mlx_node_namer_set_name_ptr(namer, arr, name);-}--int mlx_node_namer_get_name(const char** name, mlx_node_namer namer, const mlx_array arr) {- return mlx_node_namer_get_name_ptr(name, namer, arr);-}--int mlx_export_to_dot(FILE* os, const mlx_node_namer namer, const mlx_vector_array outputs) {- return mlx_export_to_dot_ptr(os, namer, outputs);-}--int mlx_print_graph(FILE* os, const mlx_node_namer namer, const mlx_vector_array outputs) {- return mlx_print_graph_ptr(os, namer, outputs);-}--int mlx_load_reader(mlx_array* res, mlx_io_reader in_stream, const mlx_stream s) {- return mlx_load_reader_ptr(res, in_stream, s);-}--int mlx_load(mlx_array* res, const char* file, const mlx_stream s) {- return mlx_load_ptr(res, file, s);-}--int mlx_load_gguf(mlx_io_gguf* gguf, const char* file, const mlx_stream s) {- return mlx_load_gguf_ptr(gguf, file, s);-}--int mlx_load_safetensors_reader(mlx_map_string_to_array* res_0, mlx_map_string_to_string* res_1, mlx_io_reader in_stream, const mlx_stream s) {- return mlx_load_safetensors_reader_ptr(res_0, res_1, in_stream, s);-}--int mlx_load_safetensors(mlx_map_string_to_array* res_0, mlx_map_string_to_string* res_1, const char* file, const mlx_stream s) {- return mlx_load_safetensors_ptr(res_0, res_1, file, s);-}--int mlx_save_writer(mlx_io_writer out_stream, const mlx_array a) {- return mlx_save_writer_ptr(out_stream, a);-}--int mlx_save(const char* file, const mlx_array a) {- return mlx_save_ptr(file, a);-}--int mlx_save_gguf(const char* file, mlx_io_gguf gguf) {- return mlx_save_gguf_ptr(file, gguf);-}--int mlx_save_safetensors_writer(mlx_io_writer in_stream, const mlx_map_string_to_array param, const mlx_map_string_to_string metadata) {- return mlx_save_safetensors_writer_ptr(in_stream, param, metadata);-}--int mlx_save_safetensors(const char* file, const mlx_map_string_to_array param, const mlx_map_string_to_string metadata) {- return mlx_save_safetensors_ptr(file, param, metadata);-}--mlx_io_reader mlx_io_reader_new(void* desc, mlx_io_vtable vtable) {- return mlx_io_reader_new_ptr(desc, vtable);-}--int mlx_io_reader_descriptor(void** desc_, mlx_io_reader io) {- return mlx_io_reader_descriptor_ptr(desc_, io);-}--int mlx_io_reader_tostring(mlx_string* str_, mlx_io_reader io) {- return mlx_io_reader_tostring_ptr(str_, io);-}--int mlx_io_reader_free(mlx_io_reader io) {- return mlx_io_reader_free_ptr(io);-}--mlx_io_writer mlx_io_writer_new(void* desc, mlx_io_vtable vtable) {- return mlx_io_writer_new_ptr(desc, vtable);-}--int mlx_io_writer_descriptor(void** desc_, mlx_io_writer io) {- return mlx_io_writer_descriptor_ptr(desc_, io);-}--int mlx_io_writer_tostring(mlx_string* str_, mlx_io_writer io) {- return mlx_io_writer_tostring_ptr(str_, io);-}--int mlx_io_writer_free(mlx_io_writer io) {- return mlx_io_writer_free_ptr(io);-}--mlx_io_gguf mlx_io_gguf_new(void) {- return mlx_io_gguf_new_ptr();-}--int mlx_io_gguf_free(mlx_io_gguf io) {- return mlx_io_gguf_free_ptr(io);-}--int mlx_io_gguf_get_keys(mlx_vector_string* keys, mlx_io_gguf io) {- return mlx_io_gguf_get_keys_ptr(keys, io);-}--int mlx_io_gguf_get_array(mlx_array* arr, mlx_io_gguf io, const char* key) {- return mlx_io_gguf_get_array_ptr(arr, io, key);-}--int mlx_io_gguf_get_metadata_array(mlx_array* arr, mlx_io_gguf io, const char* key) {- return mlx_io_gguf_get_metadata_array_ptr(arr, io, key);-}--int mlx_io_gguf_get_metadata_string(mlx_string* str, mlx_io_gguf io, const char* key) {- return mlx_io_gguf_get_metadata_string_ptr(str, io, key);-}--int mlx_io_gguf_get_metadata_vector_string(mlx_vector_string* vstr, mlx_io_gguf io, const char* key) {- return mlx_io_gguf_get_metadata_vector_string_ptr(vstr, io, key);-}--int mlx_io_gguf_has_metadata_array(bool* flag, mlx_io_gguf io, const char* key) {- return mlx_io_gguf_has_metadata_array_ptr(flag, io, key);-}--int mlx_io_gguf_has_metadata_string(bool* flag, mlx_io_gguf io, const char* key) {- return mlx_io_gguf_has_metadata_string_ptr(flag, io, key);-}--int mlx_io_gguf_has_metadata_vector_string(bool* flag, mlx_io_gguf io, const char* key) {- return mlx_io_gguf_has_metadata_vector_string_ptr(flag, io, key);-}--int mlx_io_gguf_set_array(mlx_io_gguf io, const char* key, const mlx_array arr) {- return mlx_io_gguf_set_array_ptr(io, key, arr);-}--int mlx_io_gguf_set_metadata_array(mlx_io_gguf io, const char* key, const mlx_array marr) {- return mlx_io_gguf_set_metadata_array_ptr(io, key, marr);-}--int mlx_io_gguf_set_metadata_string(mlx_io_gguf io, const char* key, const char* mstr) {- return mlx_io_gguf_set_metadata_string_ptr(io, key, mstr);-}--int mlx_io_gguf_set_metadata_vector_string(mlx_io_gguf io, const char* key, const mlx_vector_string mvstr) {- return mlx_io_gguf_set_metadata_vector_string_ptr(io, key, mvstr);-}--int mlx_linalg_cholesky(mlx_array* res, const mlx_array a, bool upper, const mlx_stream s) {- return mlx_linalg_cholesky_ptr(res, a, upper, s);-}--int mlx_linalg_cholesky_inv(mlx_array* res, const mlx_array a, bool upper, const mlx_stream s) {- return mlx_linalg_cholesky_inv_ptr(res, a, upper, s);-}--int mlx_linalg_cross(mlx_array* res, const mlx_array a, const mlx_array b, int axis, const mlx_stream s) {- return mlx_linalg_cross_ptr(res, a, b, axis, s);-}--int mlx_linalg_eig(mlx_array* res_0, mlx_array* res_1, const mlx_array a, const mlx_stream s) {- return mlx_linalg_eig_ptr(res_0, res_1, a, s);-}--int mlx_linalg_eigh(mlx_array* res_0, mlx_array* res_1, const mlx_array a, const char* UPLO, const mlx_stream s) {- return mlx_linalg_eigh_ptr(res_0, res_1, a, UPLO, s);-}--int mlx_linalg_eigvals(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_linalg_eigvals_ptr(res, a, s);-}--int mlx_linalg_eigvalsh(mlx_array* res, const mlx_array a, const char* UPLO, const mlx_stream s) {- return mlx_linalg_eigvalsh_ptr(res, a, UPLO, s);-}--int mlx_linalg_inv(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_linalg_inv_ptr(res, a, s);-}--int mlx_linalg_lu(mlx_vector_array* res, const mlx_array a, const mlx_stream s) {- return mlx_linalg_lu_ptr(res, a, s);-}--int mlx_linalg_lu_factor(mlx_array* res_0, mlx_array* res_1, const mlx_array a, const mlx_stream s) {- return mlx_linalg_lu_factor_ptr(res_0, res_1, a, s);-}--int mlx_linalg_norm(mlx_array* res, const mlx_array a, double ord, const int* axis , size_t axis_num, bool keepdims, const mlx_stream s) {- return mlx_linalg_norm_ptr(res, a, ord, axis, axis_num, keepdims, s);-}--int mlx_linalg_norm_matrix(mlx_array* res, const mlx_array a, const char* ord, const int* axis , size_t axis_num, bool keepdims, const mlx_stream s) {- return mlx_linalg_norm_matrix_ptr(res, a, ord, axis, axis_num, keepdims, s);-}--int mlx_linalg_norm_l2(mlx_array* res, const mlx_array a, const int* axis , size_t axis_num, bool keepdims, const mlx_stream s) {- return mlx_linalg_norm_l2_ptr(res, a, axis, axis_num, keepdims, s);-}--int mlx_linalg_pinv(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_linalg_pinv_ptr(res, a, s);-}--int mlx_linalg_qr(mlx_array* res_0, mlx_array* res_1, const mlx_array a, const mlx_stream s) {- return mlx_linalg_qr_ptr(res_0, res_1, a, s);-}--int mlx_linalg_solve(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_linalg_solve_ptr(res, a, b, s);-}--int mlx_linalg_solve_triangular(mlx_array* res, const mlx_array a, const mlx_array b, bool upper, const mlx_stream s) {- return mlx_linalg_solve_triangular_ptr(res, a, b, upper, s);-}--int mlx_linalg_svd(mlx_vector_array* res, const mlx_array a, bool compute_uv, const mlx_stream s) {- return mlx_linalg_svd_ptr(res, a, compute_uv, s);-}--int mlx_linalg_tri_inv(mlx_array* res, const mlx_array a, bool upper, const mlx_stream s) {- return mlx_linalg_tri_inv_ptr(res, a, upper, s);-}--mlx_map_string_to_array mlx_map_string_to_array_new(void) {- return mlx_map_string_to_array_new_ptr();-}--int mlx_map_string_to_array_set(mlx_map_string_to_array* map, const mlx_map_string_to_array src) {- return mlx_map_string_to_array_set_ptr(map, src);-}--int mlx_map_string_to_array_free(mlx_map_string_to_array map) {- return mlx_map_string_to_array_free_ptr(map);-}--int mlx_map_string_to_array_insert(mlx_map_string_to_array map, const char* key, const mlx_array value) {- return mlx_map_string_to_array_insert_ptr(map, key, value);-}--int mlx_map_string_to_array_get(mlx_array* value, const mlx_map_string_to_array map, const char* key) {- return mlx_map_string_to_array_get_ptr(value, map, key);-}--mlx_map_string_to_array_iterator mlx_map_string_to_array_iterator_new(mlx_map_string_to_array map) {- return mlx_map_string_to_array_iterator_new_ptr(map);-}--int mlx_map_string_to_array_iterator_free(mlx_map_string_to_array_iterator it) {- return mlx_map_string_to_array_iterator_free_ptr(it);-}--int mlx_map_string_to_array_iterator_next(const char** key, mlx_array* value, mlx_map_string_to_array_iterator it) {- return mlx_map_string_to_array_iterator_next_ptr(key, value, it);-}--mlx_map_string_to_string mlx_map_string_to_string_new(void) {- return mlx_map_string_to_string_new_ptr();-}--int mlx_map_string_to_string_set(mlx_map_string_to_string* map, const mlx_map_string_to_string src) {- return mlx_map_string_to_string_set_ptr(map, src);-}--int mlx_map_string_to_string_free(mlx_map_string_to_string map) {- return mlx_map_string_to_string_free_ptr(map);-}--int mlx_map_string_to_string_insert(mlx_map_string_to_string map, const char* key, const char* value) {- return mlx_map_string_to_string_insert_ptr(map, key, value);-}--int mlx_map_string_to_string_get(const char** value, const mlx_map_string_to_string map, const char* key) {- return mlx_map_string_to_string_get_ptr(value, map, key);-}--mlx_map_string_to_string_iterator mlx_map_string_to_string_iterator_new(mlx_map_string_to_string map) {- return mlx_map_string_to_string_iterator_new_ptr(map);-}--int mlx_map_string_to_string_iterator_free(mlx_map_string_to_string_iterator it) {- return mlx_map_string_to_string_iterator_free_ptr(it);-}--int mlx_map_string_to_string_iterator_next(const char** key, const char** value, mlx_map_string_to_string_iterator it) {- return mlx_map_string_to_string_iterator_next_ptr(key, value, it);-}--int mlx_clear_cache(void) {- return mlx_clear_cache_ptr();-}--int mlx_get_active_memory(size_t* res) {- return mlx_get_active_memory_ptr(res);-}--int mlx_get_cache_memory(size_t* res) {- return mlx_get_cache_memory_ptr(res);-}--int mlx_get_memory_limit(size_t* res) {- return mlx_get_memory_limit_ptr(res);-}--int mlx_get_peak_memory(size_t* res) {- return mlx_get_peak_memory_ptr(res);-}--int mlx_reset_peak_memory(void) {- return mlx_reset_peak_memory_ptr();-}--int mlx_set_cache_limit(size_t* res, size_t limit) {- return mlx_set_cache_limit_ptr(res, limit);-}--int mlx_set_memory_limit(size_t* res, size_t limit) {- return mlx_set_memory_limit_ptr(res, limit);-}--int mlx_set_wired_limit(size_t* res, size_t limit) {- return mlx_set_wired_limit_ptr(res, limit);-}--int mlx_metal_is_available(bool* res) {- return mlx_metal_is_available_ptr(res);-}--int mlx_metal_start_capture(const char* path) {- return mlx_metal_start_capture_ptr(path);-}--int mlx_metal_stop_capture(void) {- return mlx_metal_stop_capture_ptr();-}--int mlx_abs(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_abs_ptr(res, a, s);-}--int mlx_add(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_add_ptr(res, a, b, s);-}--int mlx_addmm(mlx_array* res, const mlx_array c, const mlx_array a, const mlx_array b, float alpha, float beta, const mlx_stream s) {- return mlx_addmm_ptr(res, c, a, b, alpha, beta, s);-}--int mlx_all_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s) {- return mlx_all_axes_ptr(res, a, axes, axes_num, keepdims, s);-}--int mlx_all_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s) {- return mlx_all_axis_ptr(res, a, axis, keepdims, s);-}--int mlx_all(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s) {- return mlx_all_ptr(res, a, keepdims, s);-}--int mlx_allclose(mlx_array* res, const mlx_array a, const mlx_array b, double rtol, double atol, bool equal_nan, const mlx_stream s) {- return mlx_allclose_ptr(res, a, b, rtol, atol, equal_nan, s);-}--int mlx_any_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s) {- return mlx_any_axes_ptr(res, a, axes, axes_num, keepdims, s);-}--int mlx_any_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s) {- return mlx_any_axis_ptr(res, a, axis, keepdims, s);-}--int mlx_any(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s) {- return mlx_any_ptr(res, a, keepdims, s);-}--int mlx_arange(mlx_array* res, double start, double stop, double step, mlx_dtype dtype, const mlx_stream s) {- return mlx_arange_ptr(res, start, stop, step, dtype, s);-}--int mlx_arccos(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_arccos_ptr(res, a, s);-}--int mlx_arccosh(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_arccosh_ptr(res, a, s);-}--int mlx_arcsin(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_arcsin_ptr(res, a, s);-}--int mlx_arcsinh(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_arcsinh_ptr(res, a, s);-}--int mlx_arctan(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_arctan_ptr(res, a, s);-}--int mlx_arctan2(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_arctan2_ptr(res, a, b, s);-}--int mlx_arctanh(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_arctanh_ptr(res, a, s);-}--int mlx_argmax_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s) {- return mlx_argmax_axis_ptr(res, a, axis, keepdims, s);-}--int mlx_argmax(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s) {- return mlx_argmax_ptr(res, a, keepdims, s);-}--int mlx_argmin_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s) {- return mlx_argmin_axis_ptr(res, a, axis, keepdims, s);-}--int mlx_argmin(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s) {- return mlx_argmin_ptr(res, a, keepdims, s);-}--int mlx_argpartition_axis(mlx_array* res, const mlx_array a, int kth, int axis, const mlx_stream s) {- return mlx_argpartition_axis_ptr(res, a, kth, axis, s);-}--int mlx_argpartition(mlx_array* res, const mlx_array a, int kth, const mlx_stream s) {- return mlx_argpartition_ptr(res, a, kth, s);-}--int mlx_argsort_axis(mlx_array* res, const mlx_array a, int axis, const mlx_stream s) {- return mlx_argsort_axis_ptr(res, a, axis, s);-}--int mlx_argsort(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_argsort_ptr(res, a, s);-}--int mlx_array_equal(mlx_array* res, const mlx_array a, const mlx_array b, bool equal_nan, const mlx_stream s) {- return mlx_array_equal_ptr(res, a, b, equal_nan, s);-}--int mlx_as_strided(mlx_array* res, const mlx_array a, const int* shape, size_t shape_num, const int64_t* strides, size_t strides_num, size_t offset, const mlx_stream s) {- return mlx_as_strided_ptr(res, a, shape, shape_num, strides, strides_num, offset, s);-}--int mlx_astype(mlx_array* res, const mlx_array a, mlx_dtype dtype, const mlx_stream s) {- return mlx_astype_ptr(res, a, dtype, s);-}--int mlx_atleast_1d(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_atleast_1d_ptr(res, a, s);-}--int mlx_atleast_2d(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_atleast_2d_ptr(res, a, s);-}--int mlx_atleast_3d(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_atleast_3d_ptr(res, a, s);-}--int mlx_bartlett(mlx_array* res, int M, const mlx_stream s) {- return mlx_bartlett_ptr(res, M, s);-}--int mlx_bitwise_and(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_bitwise_and_ptr(res, a, b, s);-}--int mlx_bitwise_invert(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_bitwise_invert_ptr(res, a, s);-}--int mlx_bitwise_or(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_bitwise_or_ptr(res, a, b, s);-}--int mlx_bitwise_xor(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_bitwise_xor_ptr(res, a, b, s);-}--int mlx_blackman(mlx_array* res, int M, const mlx_stream s) {- return mlx_blackman_ptr(res, M, s);-}--int mlx_block_masked_mm(mlx_array* res, const mlx_array a, const mlx_array b, int block_size, const mlx_array mask_out , const mlx_array mask_lhs , const mlx_array mask_rhs , const mlx_stream s) {- return mlx_block_masked_mm_ptr(res, a, b, block_size, mask_out, mask_lhs, mask_rhs, s);-}--int mlx_broadcast_arrays(mlx_vector_array* res, const mlx_vector_array inputs, const mlx_stream s) {- return mlx_broadcast_arrays_ptr(res, inputs, s);-}--int mlx_broadcast_to(mlx_array* res, const mlx_array a, const int* shape, size_t shape_num, const mlx_stream s) {- return mlx_broadcast_to_ptr(res, a, shape, shape_num, s);-}--int mlx_ceil(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_ceil_ptr(res, a, s);-}--int mlx_clip(mlx_array* res, const mlx_array a, const mlx_array a_min , const mlx_array a_max , const mlx_stream s) {- return mlx_clip_ptr(res, a, a_min, a_max, s);-}--int mlx_concatenate_axis(mlx_array* res, const mlx_vector_array arrays, int axis, const mlx_stream s) {- return mlx_concatenate_axis_ptr(res, arrays, axis, s);-}--int mlx_concatenate(mlx_array* res, const mlx_vector_array arrays, const mlx_stream s) {- return mlx_concatenate_ptr(res, arrays, s);-}--int mlx_conjugate(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_conjugate_ptr(res, a, s);-}--int mlx_contiguous(mlx_array* res, const mlx_array a, bool allow_col_major, const mlx_stream s) {- return mlx_contiguous_ptr(res, a, allow_col_major, s);-}--int mlx_conv1d(mlx_array* res, const mlx_array input, const mlx_array weight, int stride, int padding, int dilation, int groups, const mlx_stream s) {- return mlx_conv1d_ptr(res, input, weight, stride, padding, dilation, groups, s);-}--int mlx_conv2d(mlx_array* res, const mlx_array input, const mlx_array weight, int stride_0, int stride_1, int padding_0, int padding_1, int dilation_0, int dilation_1, int groups, const mlx_stream s) {- return mlx_conv2d_ptr(res, input, weight, stride_0, stride_1, padding_0, padding_1, dilation_0, dilation_1, groups, s);-}--int mlx_conv3d(mlx_array* res, const mlx_array input, const mlx_array weight, int stride_0, int stride_1, int stride_2, int padding_0, int padding_1, int padding_2, int dilation_0, int dilation_1, int dilation_2, int groups, const mlx_stream s) {- return mlx_conv3d_ptr(res, input, weight, stride_0, stride_1, stride_2, padding_0, padding_1, padding_2, dilation_0, dilation_1, dilation_2, groups, s);-}--int mlx_conv_general(mlx_array* res, const mlx_array input, const mlx_array weight, const int* stride, size_t stride_num, const int* padding_lo, size_t padding_lo_num, const int* padding_hi, size_t padding_hi_num, const int* kernel_dilation, size_t kernel_dilation_num, const int* input_dilation, size_t input_dilation_num, int groups, bool flip, const mlx_stream s) {- return mlx_conv_general_ptr(res, input, weight, stride, stride_num, padding_lo, padding_lo_num, padding_hi, padding_hi_num, kernel_dilation, kernel_dilation_num, input_dilation, input_dilation_num, groups, flip, s);-}--int mlx_conv_transpose1d(mlx_array* res, const mlx_array input, const mlx_array weight, int stride, int padding, int dilation, int output_padding, int groups, const mlx_stream s) {- return mlx_conv_transpose1d_ptr(res, input, weight, stride, padding, dilation, output_padding, groups, s);-}--int mlx_conv_transpose2d(mlx_array* res, const mlx_array input, const mlx_array weight, int stride_0, int stride_1, int padding_0, int padding_1, int dilation_0, int dilation_1, int output_padding_0, int output_padding_1, int groups, const mlx_stream s) {- return mlx_conv_transpose2d_ptr(res, input, weight, stride_0, stride_1, padding_0, padding_1, dilation_0, dilation_1, output_padding_0, output_padding_1, groups, s);-}--int mlx_conv_transpose3d(mlx_array* res, const mlx_array input, const mlx_array weight, int stride_0, int stride_1, int stride_2, int padding_0, int padding_1, int padding_2, int dilation_0, int dilation_1, int dilation_2, int output_padding_0, int output_padding_1, int output_padding_2, int groups, const mlx_stream s) {- return mlx_conv_transpose3d_ptr(res, input, weight, stride_0, stride_1, stride_2, padding_0, padding_1, padding_2, dilation_0, dilation_1, dilation_2, output_padding_0, output_padding_1, output_padding_2, groups, s);-}--int mlx_copy(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_copy_ptr(res, a, s);-}--int mlx_cos(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_cos_ptr(res, a, s);-}--int mlx_cosh(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_cosh_ptr(res, a, s);-}--int mlx_cummax(mlx_array* res, const mlx_array a, int axis, bool reverse, bool inclusive, const mlx_stream s) {- return mlx_cummax_ptr(res, a, axis, reverse, inclusive, s);-}--int mlx_cummin(mlx_array* res, const mlx_array a, int axis, bool reverse, bool inclusive, const mlx_stream s) {- return mlx_cummin_ptr(res, a, axis, reverse, inclusive, s);-}--int mlx_cumprod(mlx_array* res, const mlx_array a, int axis, bool reverse, bool inclusive, const mlx_stream s) {- return mlx_cumprod_ptr(res, a, axis, reverse, inclusive, s);-}--int mlx_cumsum(mlx_array* res, const mlx_array a, int axis, bool reverse, bool inclusive, const mlx_stream s) {- return mlx_cumsum_ptr(res, a, axis, reverse, inclusive, s);-}--int mlx_degrees(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_degrees_ptr(res, a, s);-}--int mlx_depends(mlx_vector_array* res, const mlx_vector_array inputs, const mlx_vector_array dependencies) {- return mlx_depends_ptr(res, inputs, dependencies);-}--int mlx_dequantize(mlx_array* res, const mlx_array w, const mlx_array scales, const mlx_array biases , mlx_optional_int group_size, mlx_optional_int bits, const char* mode, const mlx_array global_scale , mlx_optional_dtype dtype, const mlx_stream s) {- return mlx_dequantize_ptr(res, w, scales, biases, group_size, bits, mode, global_scale, dtype, s);-}--int mlx_diag(mlx_array* res, const mlx_array a, int k, const mlx_stream s) {- return mlx_diag_ptr(res, a, k, s);-}--int mlx_diagonal(mlx_array* res, const mlx_array a, int offset, int axis1, int axis2, const mlx_stream s) {- return mlx_diagonal_ptr(res, a, offset, axis1, axis2, s);-}--int mlx_divide(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_divide_ptr(res, a, b, s);-}--int mlx_divmod(mlx_vector_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_divmod_ptr(res, a, b, s);-}--int mlx_einsum(mlx_array* res, const char* subscripts, const mlx_vector_array operands, const mlx_stream s) {- return mlx_einsum_ptr(res, subscripts, operands, s);-}--int mlx_equal(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_equal_ptr(res, a, b, s);-}--int mlx_erf(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_erf_ptr(res, a, s);-}--int mlx_erfinv(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_erfinv_ptr(res, a, s);-}--int mlx_exp(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_exp_ptr(res, a, s);-}--int mlx_expand_dims_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const mlx_stream s) {- return mlx_expand_dims_axes_ptr(res, a, axes, axes_num, s);-}--int mlx_expand_dims(mlx_array* res, const mlx_array a, int axis, const mlx_stream s) {- return mlx_expand_dims_ptr(res, a, axis, s);-}--int mlx_expm1(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_expm1_ptr(res, a, s);-}--int mlx_eye(mlx_array* res, int n, int m, int k, mlx_dtype dtype, const mlx_stream s) {- return mlx_eye_ptr(res, n, m, k, dtype, s);-}--int mlx_flatten(mlx_array* res, const mlx_array a, int start_axis, int end_axis, const mlx_stream s) {- return mlx_flatten_ptr(res, a, start_axis, end_axis, s);-}--int mlx_floor(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_floor_ptr(res, a, s);-}--int mlx_floor_divide(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_floor_divide_ptr(res, a, b, s);-}--int mlx_from_fp8(mlx_array* res, const mlx_array x, mlx_dtype dtype, const mlx_stream s) {- return mlx_from_fp8_ptr(res, x, dtype, s);-}--int mlx_full(mlx_array* res, const int* shape, size_t shape_num, const mlx_array vals, mlx_dtype dtype, const mlx_stream s) {- return mlx_full_ptr(res, shape, shape_num, vals, dtype, s);-}--int mlx_full_like(mlx_array* res, const mlx_array a, const mlx_array vals, mlx_dtype dtype, const mlx_stream s) {- return mlx_full_like_ptr(res, a, vals, dtype, s);-}--int mlx_gather(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const int* axes, size_t axes_num, const int* slice_sizes, size_t slice_sizes_num, const mlx_stream s) {- return mlx_gather_ptr(res, a, indices, axes, axes_num, slice_sizes, slice_sizes_num, s);-}--int mlx_gather_single(mlx_array* res, const mlx_array a, const mlx_array indices, int axis, const int* slice_sizes, size_t slice_sizes_num, const mlx_stream s) {- return mlx_gather_single_ptr(res, a, indices, axis, slice_sizes, slice_sizes_num, s);-}--int mlx_gather_mm(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_array lhs_indices , const mlx_array rhs_indices , bool sorted_indices, const mlx_stream s) {- return mlx_gather_mm_ptr(res, a, b, lhs_indices, rhs_indices, sorted_indices, s);-}--int mlx_gather_qmm(mlx_array* res, const mlx_array x, const mlx_array w, const mlx_array scales, const mlx_array biases , const mlx_array lhs_indices , const mlx_array rhs_indices , bool transpose, mlx_optional_int group_size, mlx_optional_int bits, const char* mode, bool sorted_indices, const mlx_stream s) {- return mlx_gather_qmm_ptr(res, x, w, scales, biases, lhs_indices, rhs_indices, transpose, group_size, bits, mode, sorted_indices, s);-}--int mlx_greater(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_greater_ptr(res, a, b, s);-}--int mlx_greater_equal(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_greater_equal_ptr(res, a, b, s);-}--int mlx_hadamard_transform(mlx_array* res, const mlx_array a, mlx_optional_float scale, const mlx_stream s) {- return mlx_hadamard_transform_ptr(res, a, scale, s);-}--int mlx_hamming(mlx_array* res, int M, const mlx_stream s) {- return mlx_hamming_ptr(res, M, s);-}--int mlx_hanning(mlx_array* res, int M, const mlx_stream s) {- return mlx_hanning_ptr(res, M, s);-}--int mlx_identity(mlx_array* res, int n, mlx_dtype dtype, const mlx_stream s) {- return mlx_identity_ptr(res, n, dtype, s);-}--int mlx_imag(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_imag_ptr(res, a, s);-}--int mlx_inner(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_inner_ptr(res, a, b, s);-}--int mlx_isclose(mlx_array* res, const mlx_array a, const mlx_array b, double rtol, double atol, bool equal_nan, const mlx_stream s) {- return mlx_isclose_ptr(res, a, b, rtol, atol, equal_nan, s);-}--int mlx_isfinite(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_isfinite_ptr(res, a, s);-}--int mlx_isinf(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_isinf_ptr(res, a, s);-}--int mlx_isnan(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_isnan_ptr(res, a, s);-}--int mlx_isneginf(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_isneginf_ptr(res, a, s);-}--int mlx_isposinf(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_isposinf_ptr(res, a, s);-}--int mlx_kron(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_kron_ptr(res, a, b, s);-}--int mlx_left_shift(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_left_shift_ptr(res, a, b, s);-}--int mlx_less(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_less_ptr(res, a, b, s);-}--int mlx_less_equal(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_less_equal_ptr(res, a, b, s);-}--int mlx_linspace(mlx_array* res, double start, double stop, int num, mlx_dtype dtype, const mlx_stream s) {- return mlx_linspace_ptr(res, start, stop, num, dtype, s);-}--int mlx_log(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_log_ptr(res, a, s);-}--int mlx_log10(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_log10_ptr(res, a, s);-}--int mlx_log1p(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_log1p_ptr(res, a, s);-}--int mlx_log2(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_log2_ptr(res, a, s);-}--int mlx_logaddexp(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_logaddexp_ptr(res, a, b, s);-}--int mlx_logcumsumexp(mlx_array* res, const mlx_array a, int axis, bool reverse, bool inclusive, const mlx_stream s) {- return mlx_logcumsumexp_ptr(res, a, axis, reverse, inclusive, s);-}--int mlx_logical_and(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_logical_and_ptr(res, a, b, s);-}--int mlx_logical_not(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_logical_not_ptr(res, a, s);-}--int mlx_logical_or(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_logical_or_ptr(res, a, b, s);-}--int mlx_logsumexp_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s) {- return mlx_logsumexp_axes_ptr(res, a, axes, axes_num, keepdims, s);-}--int mlx_logsumexp_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s) {- return mlx_logsumexp_axis_ptr(res, a, axis, keepdims, s);-}--int mlx_logsumexp(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s) {- return mlx_logsumexp_ptr(res, a, keepdims, s);-}--int mlx_masked_scatter(mlx_array* res, const mlx_array a, const mlx_array mask, const mlx_array src, const mlx_stream s) {- return mlx_masked_scatter_ptr(res, a, mask, src, s);-}--int mlx_matmul(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_matmul_ptr(res, a, b, s);-}--int mlx_max_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s) {- return mlx_max_axes_ptr(res, a, axes, axes_num, keepdims, s);-}--int mlx_max_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s) {- return mlx_max_axis_ptr(res, a, axis, keepdims, s);-}--int mlx_max(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s) {- return mlx_max_ptr(res, a, keepdims, s);-}--int mlx_maximum(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_maximum_ptr(res, a, b, s);-}--int mlx_mean_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s) {- return mlx_mean_axes_ptr(res, a, axes, axes_num, keepdims, s);-}--int mlx_mean_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s) {- return mlx_mean_axis_ptr(res, a, axis, keepdims, s);-}--int mlx_mean(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s) {- return mlx_mean_ptr(res, a, keepdims, s);-}--int mlx_median(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s) {- return mlx_median_ptr(res, a, axes, axes_num, keepdims, s);-}--int mlx_meshgrid(mlx_vector_array* res, const mlx_vector_array arrays, bool sparse, const char* indexing, const mlx_stream s) {- return mlx_meshgrid_ptr(res, arrays, sparse, indexing, s);-}--int mlx_min_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s) {- return mlx_min_axes_ptr(res, a, axes, axes_num, keepdims, s);-}--int mlx_min_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s) {- return mlx_min_axis_ptr(res, a, axis, keepdims, s);-}--int mlx_min(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s) {- return mlx_min_ptr(res, a, keepdims, s);-}--int mlx_minimum(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_minimum_ptr(res, a, b, s);-}--int mlx_moveaxis(mlx_array* res, const mlx_array a, int source, int destination, const mlx_stream s) {- return mlx_moveaxis_ptr(res, a, source, destination, s);-}--int mlx_multiply(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_multiply_ptr(res, a, b, s);-}--int mlx_nan_to_num(mlx_array* res, const mlx_array a, float nan, mlx_optional_float posinf, mlx_optional_float neginf, const mlx_stream s) {- return mlx_nan_to_num_ptr(res, a, nan, posinf, neginf, s);-}--int mlx_negative(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_negative_ptr(res, a, s);-}--int mlx_not_equal(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_not_equal_ptr(res, a, b, s);-}--int mlx_number_of_elements(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool inverted, mlx_dtype dtype, const mlx_stream s) {- return mlx_number_of_elements_ptr(res, a, axes, axes_num, inverted, dtype, s);-}--int mlx_ones(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_stream s) {- return mlx_ones_ptr(res, shape, shape_num, dtype, s);-}--int mlx_ones_like(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_ones_like_ptr(res, a, s);-}--int mlx_outer(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_outer_ptr(res, a, b, s);-}--int mlx_pad(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const int* low_pad_size, size_t low_pad_size_num, const int* high_pad_size, size_t high_pad_size_num, const mlx_array pad_value, const char* mode, const mlx_stream s) {- return mlx_pad_ptr(res, a, axes, axes_num, low_pad_size, low_pad_size_num, high_pad_size, high_pad_size_num, pad_value, mode, s);-}--int mlx_pad_symmetric(mlx_array* res, const mlx_array a, int pad_width, const mlx_array pad_value, const char* mode, const mlx_stream s) {- return mlx_pad_symmetric_ptr(res, a, pad_width, pad_value, mode, s);-}--int mlx_partition_axis(mlx_array* res, const mlx_array a, int kth, int axis, const mlx_stream s) {- return mlx_partition_axis_ptr(res, a, kth, axis, s);-}--int mlx_partition(mlx_array* res, const mlx_array a, int kth, const mlx_stream s) {- return mlx_partition_ptr(res, a, kth, s);-}--int mlx_power(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_power_ptr(res, a, b, s);-}--int mlx_prod_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s) {- return mlx_prod_axes_ptr(res, a, axes, axes_num, keepdims, s);-}--int mlx_prod_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s) {- return mlx_prod_axis_ptr(res, a, axis, keepdims, s);-}--int mlx_prod(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s) {- return mlx_prod_ptr(res, a, keepdims, s);-}--int mlx_put_along_axis(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array values, int axis, const mlx_stream s) {- return mlx_put_along_axis_ptr(res, a, indices, values, axis, s);-}--int mlx_qqmm(mlx_array* res, const mlx_array x, const mlx_array w, const mlx_array w_scales , mlx_optional_int group_size, mlx_optional_int bits, const char* mode, const mlx_array global_scale_x , const mlx_array global_scale_w , const mlx_stream s) {- return mlx_qqmm_ptr(res, x, w, w_scales, group_size, bits, mode, global_scale_x, global_scale_w, s);-}--int mlx_quantize(mlx_vector_array* res, const mlx_array w, mlx_optional_int group_size, mlx_optional_int bits, const char* mode, const mlx_array global_scale , const mlx_stream s) {- return mlx_quantize_ptr(res, w, group_size, bits, mode, global_scale, s);-}--int mlx_quantized_matmul(mlx_array* res, const mlx_array x, const mlx_array w, const mlx_array scales, const mlx_array biases , bool transpose, mlx_optional_int group_size, mlx_optional_int bits, const char* mode, const mlx_stream s) {- return mlx_quantized_matmul_ptr(res, x, w, scales, biases, transpose, group_size, bits, mode, s);-}--int mlx_radians(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_radians_ptr(res, a, s);-}--int mlx_real(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_real_ptr(res, a, s);-}--int mlx_reciprocal(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_reciprocal_ptr(res, a, s);-}--int mlx_remainder(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_remainder_ptr(res, a, b, s);-}--int mlx_repeat_axis(mlx_array* res, const mlx_array arr, int repeats, int axis, const mlx_stream s) {- return mlx_repeat_axis_ptr(res, arr, repeats, axis, s);-}--int mlx_repeat(mlx_array* res, const mlx_array arr, int repeats, const mlx_stream s) {- return mlx_repeat_ptr(res, arr, repeats, s);-}--int mlx_reshape(mlx_array* res, const mlx_array a, const int* shape, size_t shape_num, const mlx_stream s) {- return mlx_reshape_ptr(res, a, shape, shape_num, s);-}--int mlx_right_shift(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_right_shift_ptr(res, a, b, s);-}--int mlx_roll_axis(mlx_array* res, const mlx_array a, const int* shift, size_t shift_num, int axis, const mlx_stream s) {- return mlx_roll_axis_ptr(res, a, shift, shift_num, axis, s);-}--int mlx_roll_axes(mlx_array* res, const mlx_array a, const int* shift, size_t shift_num, const int* axes, size_t axes_num, const mlx_stream s) {- return mlx_roll_axes_ptr(res, a, shift, shift_num, axes, axes_num, s);-}--int mlx_roll(mlx_array* res, const mlx_array a, const int* shift, size_t shift_num, const mlx_stream s) {- return mlx_roll_ptr(res, a, shift, shift_num, s);-}--int mlx_round(mlx_array* res, const mlx_array a, int decimals, const mlx_stream s) {- return mlx_round_ptr(res, a, decimals, s);-}--int mlx_rsqrt(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_rsqrt_ptr(res, a, s);-}--int mlx_scatter(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const mlx_array updates, const int* axes, size_t axes_num, const mlx_stream s) {- return mlx_scatter_ptr(res, a, indices, updates, axes, axes_num, s);-}--int mlx_scatter_single(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array updates, int axis, const mlx_stream s) {- return mlx_scatter_single_ptr(res, a, indices, updates, axis, s);-}--int mlx_scatter_add(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const mlx_array updates, const int* axes, size_t axes_num, const mlx_stream s) {- return mlx_scatter_add_ptr(res, a, indices, updates, axes, axes_num, s);-}--int mlx_scatter_add_single(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array updates, int axis, const mlx_stream s) {- return mlx_scatter_add_single_ptr(res, a, indices, updates, axis, s);-}--int mlx_scatter_add_axis(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array values, int axis, const mlx_stream s) {- return mlx_scatter_add_axis_ptr(res, a, indices, values, axis, s);-}--int mlx_scatter_max(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const mlx_array updates, const int* axes, size_t axes_num, const mlx_stream s) {- return mlx_scatter_max_ptr(res, a, indices, updates, axes, axes_num, s);-}--int mlx_scatter_max_single(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array updates, int axis, const mlx_stream s) {- return mlx_scatter_max_single_ptr(res, a, indices, updates, axis, s);-}--int mlx_scatter_min(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const mlx_array updates, const int* axes, size_t axes_num, const mlx_stream s) {- return mlx_scatter_min_ptr(res, a, indices, updates, axes, axes_num, s);-}--int mlx_scatter_min_single(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array updates, int axis, const mlx_stream s) {- return mlx_scatter_min_single_ptr(res, a, indices, updates, axis, s);-}--int mlx_scatter_prod(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const mlx_array updates, const int* axes, size_t axes_num, const mlx_stream s) {- return mlx_scatter_prod_ptr(res, a, indices, updates, axes, axes_num, s);-}--int mlx_scatter_prod_single(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array updates, int axis, const mlx_stream s) {- return mlx_scatter_prod_single_ptr(res, a, indices, updates, axis, s);-}--int mlx_segmented_mm(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_array segments, const mlx_stream s) {- return mlx_segmented_mm_ptr(res, a, b, segments, s);-}--int mlx_sigmoid(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_sigmoid_ptr(res, a, s);-}--int mlx_sign(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_sign_ptr(res, a, s);-}--int mlx_sin(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_sin_ptr(res, a, s);-}--int mlx_sinh(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_sinh_ptr(res, a, s);-}--int mlx_slice(mlx_array* res, const mlx_array a, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s) {- return mlx_slice_ptr(res, a, start, start_num, stop, stop_num, strides, strides_num, s);-}--int mlx_slice_dynamic(mlx_array* res, const mlx_array a, const mlx_array start, const int* axes, size_t axes_num, const int* slice_size, size_t slice_size_num, const mlx_stream s) {- return mlx_slice_dynamic_ptr(res, a, start, axes, axes_num, slice_size, slice_size_num, s);-}--int mlx_slice_update(mlx_array* res, const mlx_array src, const mlx_array update, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s) {- return mlx_slice_update_ptr(res, src, update, start, start_num, stop, stop_num, strides, strides_num, s);-}--int mlx_slice_update_dynamic(mlx_array* res, const mlx_array src, const mlx_array update, const mlx_array start, const int* axes, size_t axes_num, const mlx_stream s) {- return mlx_slice_update_dynamic_ptr(res, src, update, start, axes, axes_num, s);-}--int mlx_slice_update_add(mlx_array* res, const mlx_array src, const mlx_array update, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s) {- return mlx_slice_update_add_ptr(res, src, update, start, start_num, stop, stop_num, strides, strides_num, s);-}--int mlx_slice_update_max(mlx_array* res, const mlx_array src, const mlx_array update, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s) {- return mlx_slice_update_max_ptr(res, src, update, start, start_num, stop, stop_num, strides, strides_num, s);-}--int mlx_slice_update_min(mlx_array* res, const mlx_array src, const mlx_array update, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s) {- return mlx_slice_update_min_ptr(res, src, update, start, start_num, stop, stop_num, strides, strides_num, s);-}--int mlx_slice_update_prod(mlx_array* res, const mlx_array src, const mlx_array update, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s) {- return mlx_slice_update_prod_ptr(res, src, update, start, start_num, stop, stop_num, strides, strides_num, s);-}--int mlx_softmax_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool precise, const mlx_stream s) {- return mlx_softmax_axes_ptr(res, a, axes, axes_num, precise, s);-}--int mlx_softmax_axis(mlx_array* res, const mlx_array a, int axis, bool precise, const mlx_stream s) {- return mlx_softmax_axis_ptr(res, a, axis, precise, s);-}--int mlx_softmax(mlx_array* res, const mlx_array a, bool precise, const mlx_stream s) {- return mlx_softmax_ptr(res, a, precise, s);-}--int mlx_sort_axis(mlx_array* res, const mlx_array a, int axis, const mlx_stream s) {- return mlx_sort_axis_ptr(res, a, axis, s);-}--int mlx_sort(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_sort_ptr(res, a, s);-}--int mlx_split(mlx_vector_array* res, const mlx_array a, int num_splits, int axis, const mlx_stream s) {- return mlx_split_ptr(res, a, num_splits, axis, s);-}--int mlx_split_sections(mlx_vector_array* res, const mlx_array a, const int* indices, size_t indices_num, int axis, const mlx_stream s) {- return mlx_split_sections_ptr(res, a, indices, indices_num, axis, s);-}--int mlx_sqrt(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_sqrt_ptr(res, a, s);-}--int mlx_square(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_square_ptr(res, a, s);-}--int mlx_squeeze_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const mlx_stream s) {- return mlx_squeeze_axes_ptr(res, a, axes, axes_num, s);-}--int mlx_squeeze_axis(mlx_array* res, const mlx_array a, int axis, const mlx_stream s) {- return mlx_squeeze_axis_ptr(res, a, axis, s);-}--int mlx_squeeze(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_squeeze_ptr(res, a, s);-}--int mlx_stack_axis(mlx_array* res, const mlx_vector_array arrays, int axis, const mlx_stream s) {- return mlx_stack_axis_ptr(res, arrays, axis, s);-}--int mlx_stack(mlx_array* res, const mlx_vector_array arrays, const mlx_stream s) {- return mlx_stack_ptr(res, arrays, s);-}--int mlx_std_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, int ddof, const mlx_stream s) {- return mlx_std_axes_ptr(res, a, axes, axes_num, keepdims, ddof, s);-}--int mlx_std_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, int ddof, const mlx_stream s) {- return mlx_std_axis_ptr(res, a, axis, keepdims, ddof, s);-}--int mlx_std(mlx_array* res, const mlx_array a, bool keepdims, int ddof, const mlx_stream s) {- return mlx_std_ptr(res, a, keepdims, ddof, s);-}--int mlx_stop_gradient(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_stop_gradient_ptr(res, a, s);-}--int mlx_subtract(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s) {- return mlx_subtract_ptr(res, a, b, s);-}--int mlx_sum_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s) {- return mlx_sum_axes_ptr(res, a, axes, axes_num, keepdims, s);-}--int mlx_sum_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s) {- return mlx_sum_axis_ptr(res, a, axis, keepdims, s);-}--int mlx_sum(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s) {- return mlx_sum_ptr(res, a, keepdims, s);-}--int mlx_swapaxes(mlx_array* res, const mlx_array a, int axis1, int axis2, const mlx_stream s) {- return mlx_swapaxes_ptr(res, a, axis1, axis2, s);-}--int mlx_take_axis(mlx_array* res, const mlx_array a, const mlx_array indices, int axis, const mlx_stream s) {- return mlx_take_axis_ptr(res, a, indices, axis, s);-}--int mlx_take(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_stream s) {- return mlx_take_ptr(res, a, indices, s);-}--int mlx_take_along_axis(mlx_array* res, const mlx_array a, const mlx_array indices, int axis, const mlx_stream s) {- return mlx_take_along_axis_ptr(res, a, indices, axis, s);-}--int mlx_tan(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_tan_ptr(res, a, s);-}--int mlx_tanh(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_tanh_ptr(res, a, s);-}--int mlx_tensordot(mlx_array* res, const mlx_array a, const mlx_array b, const int* axes_a, size_t axes_a_num, const int* axes_b, size_t axes_b_num, const mlx_stream s) {- return mlx_tensordot_ptr(res, a, b, axes_a, axes_a_num, axes_b, axes_b_num, s);-}--int mlx_tensordot_axis(mlx_array* res, const mlx_array a, const mlx_array b, int axis, const mlx_stream s) {- return mlx_tensordot_axis_ptr(res, a, b, axis, s);-}--int mlx_tile(mlx_array* res, const mlx_array arr, const int* reps, size_t reps_num, const mlx_stream s) {- return mlx_tile_ptr(res, arr, reps, reps_num, s);-}--int mlx_to_fp8(mlx_array* res, const mlx_array x, const mlx_stream s) {- return mlx_to_fp8_ptr(res, x, s);-}--int mlx_topk_axis(mlx_array* res, const mlx_array a, int k, int axis, const mlx_stream s) {- return mlx_topk_axis_ptr(res, a, k, axis, s);-}--int mlx_topk(mlx_array* res, const mlx_array a, int k, const mlx_stream s) {- return mlx_topk_ptr(res, a, k, s);-}--int mlx_trace(mlx_array* res, const mlx_array a, int offset, int axis1, int axis2, mlx_dtype dtype, const mlx_stream s) {- return mlx_trace_ptr(res, a, offset, axis1, axis2, dtype, s);-}--int mlx_transpose_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const mlx_stream s) {- return mlx_transpose_axes_ptr(res, a, axes, axes_num, s);-}--int mlx_transpose(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_transpose_ptr(res, a, s);-}--int mlx_tri(mlx_array* res, int n, int m, int k, mlx_dtype type, const mlx_stream s) {- return mlx_tri_ptr(res, n, m, k, type, s);-}--int mlx_tril(mlx_array* res, const mlx_array x, int k, const mlx_stream s) {- return mlx_tril_ptr(res, x, k, s);-}--int mlx_triu(mlx_array* res, const mlx_array x, int k, const mlx_stream s) {- return mlx_triu_ptr(res, x, k, s);-}--int mlx_unflatten(mlx_array* res, const mlx_array a, int axis, const int* shape, size_t shape_num, const mlx_stream s) {- return mlx_unflatten_ptr(res, a, axis, shape, shape_num, s);-}--int mlx_var_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, int ddof, const mlx_stream s) {- return mlx_var_axes_ptr(res, a, axes, axes_num, keepdims, ddof, s);-}--int mlx_var_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, int ddof, const mlx_stream s) {- return mlx_var_axis_ptr(res, a, axis, keepdims, ddof, s);-}--int mlx_var(mlx_array* res, const mlx_array a, bool keepdims, int ddof, const mlx_stream s) {- return mlx_var_ptr(res, a, keepdims, ddof, s);-}--int mlx_view(mlx_array* res, const mlx_array a, mlx_dtype dtype, const mlx_stream s) {- return mlx_view_ptr(res, a, dtype, s);-}--int mlx_where(mlx_array* res, const mlx_array condition, const mlx_array x, const mlx_array y, const mlx_stream s) {- return mlx_where_ptr(res, condition, x, y, s);-}--int mlx_zeros(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_stream s) {- return mlx_zeros_ptr(res, shape, shape_num, dtype, s);-}--int mlx_zeros_like(mlx_array* res, const mlx_array a, const mlx_stream s) {- return mlx_zeros_like_ptr(res, a, s);-}--int mlx_random_bernoulli(mlx_array* res, const mlx_array p, const int* shape, size_t shape_num, const mlx_array key , const mlx_stream s) {- return mlx_random_bernoulli_ptr(res, p, shape, shape_num, key, s);-}--int mlx_random_bits(mlx_array* res, const int* shape, size_t shape_num, int width, const mlx_array key , const mlx_stream s) {- return mlx_random_bits_ptr(res, shape, shape_num, width, key, s);-}--int mlx_random_categorical_shape(mlx_array* res, const mlx_array logits, int axis, const int* shape, size_t shape_num, const mlx_array key , const mlx_stream s) {- return mlx_random_categorical_shape_ptr(res, logits, axis, shape, shape_num, key, s);-}--int mlx_random_categorical_num_samples(mlx_array* res, const mlx_array logits_, int axis, int num_samples, const mlx_array key , const mlx_stream s) {- return mlx_random_categorical_num_samples_ptr(res, logits_, axis, num_samples, key, s);-}--int mlx_random_categorical(mlx_array* res, const mlx_array logits, int axis, const mlx_array key , const mlx_stream s) {- return mlx_random_categorical_ptr(res, logits, axis, key, s);-}--int mlx_random_gumbel(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array key , const mlx_stream s) {- return mlx_random_gumbel_ptr(res, shape, shape_num, dtype, key, s);-}--int mlx_random_key(mlx_array* res, uint64_t seed) {- return mlx_random_key_ptr(res, seed);-}--int mlx_random_laplace(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, float loc, float scale, const mlx_array key , const mlx_stream s) {- return mlx_random_laplace_ptr(res, shape, shape_num, dtype, loc, scale, key, s);-}--int mlx_random_multivariate_normal(mlx_array* res, const mlx_array mean, const mlx_array cov, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array key , const mlx_stream s) {- return mlx_random_multivariate_normal_ptr(res, mean, cov, shape, shape_num, dtype, key, s);-}--int mlx_random_normal_broadcast(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array loc , const mlx_array scale , const mlx_array key , const mlx_stream s) {- return mlx_random_normal_broadcast_ptr(res, shape, shape_num, dtype, loc, scale, key, s);-}--int mlx_random_normal(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, float loc, float scale, const mlx_array key , const mlx_stream s) {- return mlx_random_normal_ptr(res, shape, shape_num, dtype, loc, scale, key, s);-}--int mlx_random_permutation(mlx_array* res, const mlx_array x, int axis, const mlx_array key , const mlx_stream s) {- return mlx_random_permutation_ptr(res, x, axis, key, s);-}--int mlx_random_permutation_arange(mlx_array* res, int x, const mlx_array key , const mlx_stream s) {- return mlx_random_permutation_arange_ptr(res, x, key, s);-}--int mlx_random_randint(mlx_array* res, const mlx_array low, const mlx_array high, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array key , const mlx_stream s) {- return mlx_random_randint_ptr(res, low, high, shape, shape_num, dtype, key, s);-}--int mlx_random_seed(uint64_t seed) {- return mlx_random_seed_ptr(seed);-}--int mlx_random_split_num(mlx_array* res, const mlx_array key, int num, const mlx_stream s) {- return mlx_random_split_num_ptr(res, key, num, s);-}--int mlx_random_split(mlx_array* res_0, mlx_array* res_1, const mlx_array key, const mlx_stream s) {- return mlx_random_split_ptr(res_0, res_1, key, s);-}--int mlx_random_truncated_normal(mlx_array* res, const mlx_array lower, const mlx_array upper, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array key , const mlx_stream s) {- return mlx_random_truncated_normal_ptr(res, lower, upper, shape, shape_num, dtype, key, s);-}--int mlx_random_uniform(mlx_array* res, const mlx_array low, const mlx_array high, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array key , const mlx_stream s) {- return mlx_random_uniform_ptr(res, low, high, shape, shape_num, dtype, key, s);-}--mlx_stream mlx_stream_new(void) {- return mlx_stream_new_ptr();-}--mlx_stream mlx_stream_new_device(mlx_device dev) {- return mlx_stream_new_device_ptr(dev);-}--int mlx_stream_set(mlx_stream* stream, const mlx_stream src) {- return mlx_stream_set_ptr(stream, src);-}--int mlx_stream_free(mlx_stream stream) {- return mlx_stream_free_ptr(stream);-}--int mlx_stream_tostring(mlx_string* str, mlx_stream stream) {- return mlx_stream_tostring_ptr(str, stream);-}--bool mlx_stream_equal(mlx_stream lhs, mlx_stream rhs) {- return mlx_stream_equal_ptr(lhs, rhs);-}--int mlx_stream_get_device(mlx_device* dev, mlx_stream stream) {- return mlx_stream_get_device_ptr(dev, stream);-}--int mlx_stream_get_index(int* index, mlx_stream stream) {- return mlx_stream_get_index_ptr(index, stream);-}--int mlx_synchronize(mlx_stream stream) {- return mlx_synchronize_ptr(stream);-}--int mlx_get_default_stream(mlx_stream* stream, mlx_device dev) {- return mlx_get_default_stream_ptr(stream, dev);-}--int mlx_set_default_stream(mlx_stream stream) {- return mlx_set_default_stream_ptr(stream);-}--mlx_stream mlx_default_cpu_stream_new(void) {- return mlx_default_cpu_stream_new_ptr();-}--mlx_stream mlx_default_gpu_stream_new(void) {- return mlx_default_gpu_stream_new_ptr();-}--mlx_string mlx_string_new(void) {- return mlx_string_new_ptr();-}--mlx_string mlx_string_new_data(const char* str) {- return mlx_string_new_data_ptr(str);-}--int mlx_string_set(mlx_string* str, const mlx_string src) {- return mlx_string_set_ptr(str, src);-}--const char* mlx_string_data(mlx_string str) {- return mlx_string_data_ptr(str);-}--int mlx_string_free(mlx_string str) {- return mlx_string_free_ptr(str);-}--int mlx_async_eval(const mlx_vector_array outputs) {- return mlx_async_eval_ptr(outputs);-}--int mlx_checkpoint(mlx_closure* res, const mlx_closure fun) {- return mlx_checkpoint_ptr(res, fun);-}--int mlx_custom_function(mlx_closure* res, const mlx_closure fun, const mlx_closure_custom fun_vjp , const mlx_closure_custom_jvp fun_jvp , const mlx_closure_custom_vmap fun_vmap) {- return mlx_custom_function_ptr(res, fun, fun_vjp, fun_jvp, fun_vmap);-}--int mlx_custom_vjp(mlx_closure* res, const mlx_closure fun, const mlx_closure_custom fun_vjp) {- return mlx_custom_vjp_ptr(res, fun, fun_vjp);-}--int mlx_eval(const mlx_vector_array outputs) {- return mlx_eval_ptr(outputs);-}--int mlx_jvp(mlx_vector_array* res_0, mlx_vector_array* res_1, const mlx_closure fun, const mlx_vector_array primals, const mlx_vector_array tangents) {- return mlx_jvp_ptr(res_0, res_1, fun, primals, tangents);-}--int mlx_value_and_grad(mlx_closure_value_and_grad* res, const mlx_closure fun, const int* argnums, size_t argnums_num) {- return mlx_value_and_grad_ptr(res, fun, argnums, argnums_num);-}--int mlx_vjp(mlx_vector_array* res_0, mlx_vector_array* res_1, const mlx_closure fun, const mlx_vector_array primals, const mlx_vector_array cotangents) {- return mlx_vjp_ptr(res_0, res_1, fun, primals, cotangents);-}--int mlx_detail_vmap_replace(mlx_vector_array* res, const mlx_vector_array inputs, const mlx_vector_array s_inputs, const mlx_vector_array s_outputs, const int* in_axes, size_t in_axes_num, const int* out_axes, size_t out_axes_num) {- return mlx_detail_vmap_replace_ptr(res, inputs, s_inputs, s_outputs, in_axes, in_axes_num, out_axes, out_axes_num);-}--int mlx_detail_vmap_trace(mlx_vector_array* res_0, mlx_vector_array* res_1, const mlx_closure fun, const mlx_vector_array inputs, const int* in_axes, size_t in_axes_num) {- return mlx_detail_vmap_trace_ptr(res_0, res_1, fun, inputs, in_axes, in_axes_num);-}--mlx_vector_array mlx_vector_array_new(void) {- return mlx_vector_array_new_ptr();-}--int mlx_vector_array_set(mlx_vector_array* vec, const mlx_vector_array src) {- return mlx_vector_array_set_ptr(vec, src);-}--int mlx_vector_array_free(mlx_vector_array vec) {- return mlx_vector_array_free_ptr(vec);-}--mlx_vector_array mlx_vector_array_new_data(const mlx_array* data, size_t size) {- return mlx_vector_array_new_data_ptr(data, size);-}--mlx_vector_array mlx_vector_array_new_value(const mlx_array val) {- return mlx_vector_array_new_value_ptr(val);-}--int mlx_vector_array_set_data(mlx_vector_array* vec, const mlx_array* data, size_t size) {- return mlx_vector_array_set_data_ptr(vec, data, size);-}--int mlx_vector_array_set_value(mlx_vector_array* vec, const mlx_array val) {- return mlx_vector_array_set_value_ptr(vec, val);-}--int mlx_vector_array_append_data(mlx_vector_array vec, const mlx_array* data, size_t size) {- return mlx_vector_array_append_data_ptr(vec, data, size);-}--int mlx_vector_array_append_value(mlx_vector_array vec, const mlx_array val) {- return mlx_vector_array_append_value_ptr(vec, val);-}--size_t mlx_vector_array_size(mlx_vector_array vec) {- return mlx_vector_array_size_ptr(vec);-}--int mlx_vector_array_get(mlx_array* res, const mlx_vector_array vec, size_t idx) {- return mlx_vector_array_get_ptr(res, vec, idx);-}--mlx_vector_vector_array mlx_vector_vector_array_new(void) {- return mlx_vector_vector_array_new_ptr();-}--int mlx_vector_vector_array_set(mlx_vector_vector_array* vec, const mlx_vector_vector_array src) {- return mlx_vector_vector_array_set_ptr(vec, src);-}--int mlx_vector_vector_array_free(mlx_vector_vector_array vec) {- return mlx_vector_vector_array_free_ptr(vec);-}--mlx_vector_vector_array mlx_vector_vector_array_new_data(const mlx_vector_array* data, size_t size) {- return mlx_vector_vector_array_new_data_ptr(data, size);-}--mlx_vector_vector_array mlx_vector_vector_array_new_value(const mlx_vector_array val) {- return mlx_vector_vector_array_new_value_ptr(val);-}--int mlx_vector_vector_array_set_data(mlx_vector_vector_array* vec, const mlx_vector_array* data, size_t size) {- return mlx_vector_vector_array_set_data_ptr(vec, data, size);-}--int mlx_vector_vector_array_set_value(mlx_vector_vector_array* vec, const mlx_vector_array val) {- return mlx_vector_vector_array_set_value_ptr(vec, val);-}--int mlx_vector_vector_array_append_data(mlx_vector_vector_array vec, const mlx_vector_array* data, size_t size) {- return mlx_vector_vector_array_append_data_ptr(vec, data, size);-}--int mlx_vector_vector_array_append_value(mlx_vector_vector_array vec, const mlx_vector_array val) {- return mlx_vector_vector_array_append_value_ptr(vec, val);-}--size_t mlx_vector_vector_array_size(mlx_vector_vector_array vec) {- return mlx_vector_vector_array_size_ptr(vec);-}--int mlx_vector_vector_array_get(mlx_vector_array* res, const mlx_vector_vector_array vec, size_t idx) {- return mlx_vector_vector_array_get_ptr(res, vec, idx);-}--mlx_vector_int mlx_vector_int_new(void) {- return mlx_vector_int_new_ptr();-}--int mlx_vector_int_set(mlx_vector_int* vec, const mlx_vector_int src) {- return mlx_vector_int_set_ptr(vec, src);-}--int mlx_vector_int_free(mlx_vector_int vec) {- return mlx_vector_int_free_ptr(vec);-}--mlx_vector_int mlx_vector_int_new_data(int* data, size_t size) {- return mlx_vector_int_new_data_ptr(data, size);-}--mlx_vector_int mlx_vector_int_new_value(int val) {- return mlx_vector_int_new_value_ptr(val);-}--int mlx_vector_int_set_data(mlx_vector_int* vec, int* data, size_t size) {- return mlx_vector_int_set_data_ptr(vec, data, size);-}--int mlx_vector_int_set_value(mlx_vector_int* vec, int val) {- return mlx_vector_int_set_value_ptr(vec, val);-}--int mlx_vector_int_append_data(mlx_vector_int vec, int* data, size_t size) {- return mlx_vector_int_append_data_ptr(vec, data, size);-}--int mlx_vector_int_append_value(mlx_vector_int vec, int val) {- return mlx_vector_int_append_value_ptr(vec, val);-}--size_t mlx_vector_int_size(mlx_vector_int vec) {- return mlx_vector_int_size_ptr(vec);-}--int mlx_vector_int_get(int* res, const mlx_vector_int vec, size_t idx) {- return mlx_vector_int_get_ptr(res, vec, idx);-}--mlx_vector_string mlx_vector_string_new(void) {- return mlx_vector_string_new_ptr();-}--int mlx_vector_string_set(mlx_vector_string* vec, const mlx_vector_string src) {- return mlx_vector_string_set_ptr(vec, src);-}--int mlx_vector_string_free(mlx_vector_string vec) {- return mlx_vector_string_free_ptr(vec);-}--mlx_vector_string mlx_vector_string_new_data(const char** data, size_t size) {- return mlx_vector_string_new_data_ptr(data, size);-}--mlx_vector_string mlx_vector_string_new_value(const char* val) {- return mlx_vector_string_new_value_ptr(val);-}--int mlx_vector_string_set_data(mlx_vector_string* vec, const char** data, size_t size) {- return mlx_vector_string_set_data_ptr(vec, data, size);-}--int mlx_vector_string_set_value(mlx_vector_string* vec, const char* val) {- return mlx_vector_string_set_value_ptr(vec, val);-}--int mlx_vector_string_append_data(mlx_vector_string vec, const char** data, size_t size) {- return mlx_vector_string_append_data_ptr(vec, data, size);-}--int mlx_vector_string_append_value(mlx_vector_string vec, const char* val) {- return mlx_vector_string_append_value_ptr(vec, val);-}--size_t mlx_vector_string_size(mlx_vector_string vec) {- return mlx_vector_string_size_ptr(vec);-}--int mlx_vector_string_get(char** res, const mlx_vector_string vec, size_t idx) {- return mlx_vector_string_get_ptr(res, vec, idx);-}--int mlx_version(mlx_string* str_) {- return mlx_version_ptr(str_);-}-diff --git a/x/imagegen/mlx/mlx.go b/x/imagegen/mlx/mlx.godeleted file mode 100644index 3c3d354d8..000000000--- a/x/imagegen/mlx/mlx.go+++ /dev/null@@ -1,2385 +0,0 @@-package mlx--/*-#cgo CFLAGS: -O3 -I${SRCDIR}/../../mlxrunner/mlx/include -I${SRCDIR}-#cgo darwin LDFLAGS: -lc++ -framework Metal -framework Foundation -framework Accelerate-#cgo linux LDFLAGS: -lstdc++ -ldl-#cgo windows LDFLAGS: -lstdc++--// Use generated wrappers instead of direct MLX headers-#include "mlx.h"-#include "mlx_error_handler.h"-#include <stdlib.h>-#include <stdint.h>-#include <string.h>--// Forward declare cpu_stream-static mlx_stream cpu_stream();--// Cached default GPU stream for all ops-static mlx_stream _default_stream = {0};-static mlx_stream _cpu_stream = {0};--static inline mlx_stream default_stream() {- if (_default_stream.ctx == NULL) {- _default_stream = mlx_default_gpu_stream_new();- }- return _default_stream;-}--static inline void set_default_stream(mlx_stream s) {- _default_stream = s;-}--// CPU stream for operations that only support CPU evaluation-static inline mlx_stream cpu_stream() {- if (_cpu_stream.ctx == NULL) {- _cpu_stream = mlx_default_cpu_stream_new();- }- return _cpu_stream;-}--// CGO noescape/nocallback hints to reduce CGO overhead-// noescape: pointers won't escape, no heap allocation needed-// nocallback: function won't call back into Go-*/-import "C"--import (- "fmt"- "reflect"- "runtime"- "sync"- "sync/atomic"- "time"- "unsafe"-- mlxrunnermlx "github.com/ollama/ollama/x/mlxrunner/mlx"-)--// Dtype represents MLX data types-type Dtype int--const (- DtypeBool Dtype = C.MLX_BOOL- DtypeUint8 Dtype = C.MLX_UINT8- DtypeUint16 Dtype = C.MLX_UINT16- DtypeUint32 Dtype = C.MLX_UINT32- DtypeUint64 Dtype = C.MLX_UINT64- DtypeInt8 Dtype = C.MLX_INT8- DtypeInt16 Dtype = C.MLX_INT16- DtypeInt32 Dtype = C.MLX_INT32- DtypeInt64 Dtype = C.MLX_INT64- DtypeFloat16 Dtype = C.MLX_FLOAT16- DtypeFloat32 Dtype = C.MLX_FLOAT32- DtypeFloat64 Dtype = C.MLX_FLOAT64- DtypeBFloat16 Dtype = C.MLX_BFLOAT16- DtypeComplex64 Dtype = C.MLX_COMPLEX64-)--// String implements fmt.Stringer for Dtype-func (d Dtype) String() string {- switch d {- case DtypeBool:- return "bool"- case DtypeUint8:- return "u8"- case DtypeUint16:- return "u16"- case DtypeUint32:- return "u32"- case DtypeUint64:- return "u64"- case DtypeInt8:- return "i8"- case DtypeInt16:- return "i16"- case DtypeInt32:- return "i32"- case DtypeInt64:- return "i64"- case DtypeFloat16:- return "f16"- case DtypeFloat32:- return "f32"- case DtypeFloat64:- return "f64"- case DtypeBFloat16:- return "bf16"- case DtypeComplex64:- return "c64"- default:- return "unknown"- }-}--// Memory Management:-//-// All arrays are automatically tracked for cleanup. On Eval(), non-kept arrays are freed.-//-// x := mlx.Matmul(input, weight) // x is tracked for cleanup-// mlx.Keep(x) // mark x as persistent-// mlx.Eval(x) // eval + free non-kept arrays-//-// Use Keep() for arrays that should persist (weights, caches).-// Use Free() to mark a kept array for cleanup on next Eval().-//-// Note: Not goroutine-safe. Use from a single goroutine.--// Array wraps an MLX array handle.-// Arrays are freed via Eval() cleanup (deterministic) or GC (fallback).-type Array struct {- c C.mlx_array- freed bool // Prevents double-free- kept bool // If true, survives Eval() cleanup-}--// arrays tracks all live arrays. On Eval(), non-kept arrays are freed.-// Not goroutine-safe.-var arrays = make([]*Array, 0, 4096)--// evalHandles is a pre-allocated slice for passing arrays to MLX eval.-var evalHandles = make([]C.mlx_array, 0, 64)--// arrayPool reduces allocations for intermediate arrays-var arrayPool = sync.Pool{- New: func() any { return &Array{} },-}--func newArray(array C.mlx_array) *Array {- // In compiled closures, MLX manages memory - skip Go tracking- if InClosureCallback() {- a := &Array{c: array}- trackClosureArray(a)- return a- }-- // Use pooled Array struct for efficiency- a := arrayPool.Get().(*Array)- a.c = array- a.freed = false- a.kept = false-- // Track in global list- arrays = append(arrays, a)-- return a-}--// Collect uses reflection to find all *Array fields in a struct (recursively).-// Use this to automatically gather model weights, cache state, etc.-func Collect(v any) []*Array {- var arrays []*Array- seen := make(map[uintptr]bool)- collect(reflect.ValueOf(v), &arrays, seen)- return arrays-}--func collect(v reflect.Value, arrays *[]*Array, seen map[uintptr]bool) {- if !v.IsValid() {- return- }-- // Handle pointers- if v.Kind() == reflect.Pointer {- if v.IsNil() {- return- }- // Avoid infinite loops- ptr := v.Pointer()- if seen[ptr] {- return- }- seen[ptr] = true-- // Check if it's *Array- if arr, ok := v.Interface().(*Array); ok {- if arr != nil && arr.c.ctx != nil {- *arrays = append(*arrays, arr)- }- return- }- collect(v.Elem(), arrays, seen)- return- }-- // Handle structs- if v.Kind() == reflect.Struct {- for i := range v.NumField() {- field := v.Field(i)- if field.CanInterface() {- collect(field, arrays, seen)- }- }- return- }-- // Handle slices- if v.Kind() == reflect.Slice {- for i := range v.Len() {- collect(v.Index(i), arrays, seen)- }- return- }-- // Handle maps- if v.Kind() == reflect.Map {- for _, key := range v.MapKeys() {- collect(v.MapIndex(key), arrays, seen)- }- return- }-- // Handle interfaces- if v.Kind() == reflect.Interface {- if !v.IsNil() {- collect(v.Elem(), arrays, seen)- }- return- }-}--// FreeStruct releases all *Array fields in a struct (recursively).-// Use this to free model weights when unloading a model.-func FreeStruct(v any) {- for _, arr := range Collect(v) {- arr.Free()- }-}--// ReleaseAll releases all arrays tracked by this package.-// Use this when tearing down a whole MLX context; normal model code should-// prefer FreeStruct or explicit Array.Free calls for owned state.-func ReleaseAll() {- for _, a := range arrays {- if a != nil {- a.kept = false- }- }- cleanup()-}--// Keep marks arrays to persist across Eval() cleanup.-// Kept arrays will NOT be freed when Eval() runs cleanup.-func Keep(arrays ...*Array) {- for _, a := range arrays {- if a != nil {- a.kept = true- }- }-}--// cleanup frees non-kept arrays and compacts the live array list.-// Returns number of arrays freed.-func cleanup() int {- freed := 0- n := 0- for _, a := range arrays {- if a.kept {- arrays[n] = a- n++- } else if a.c.ctx != nil && !a.freed {- C.mlx_array_free(a.c)- a.c.ctx = nil- arrayPool.Put(a)- freed++- }- }- arrays = arrays[:n]- return freed-}--func keepDuringRead(readArrays ...*Array) func() {- type state struct {- array *Array- kept bool- }-- states := make([]state, 0, len(readArrays))- for _, a := range readArrays {- if a != nil {- states = append(states, state{array: a, kept: a.kept})- a.kept = true- }- }-- return func() {- for _, s := range states {- s.array.kept = s.kept- }- }-}--// DebugArrays prints summary info about all tracked arrays.-func DebugArrays() {- var totalBytes int64- var keptCount, unkeptCount int- for _, a := range arrays {- if a.kept {- keptCount++- } else {- unkeptCount++- }- totalBytes += a.Nbytes()- }- fmt.Printf("[DEBUG] Arrays: %d kept, %d unkept, %.2f GB total\n",- keptCount, unkeptCount, float64(totalBytes)/(1024*1024*1024))-}--// DebugArraysVerbose prints detailed info about all tracked arrays, sorted by size.-func DebugArraysVerbose(topN int) {- type arrayInfo struct {- shape []int32- dtype Dtype- bytes int64- kept bool- }-- var infos []arrayInfo- var totalBytes int64- for _, a := range arrays {- bytes := a.Nbytes()- infos = append(infos, arrayInfo{- shape: a.Shape(),- dtype: a.Dtype(),- bytes: bytes,- kept: a.kept,- })- totalBytes += bytes- }-- // Sort by size descending- for i := range len(infos) - 1 {- for j := i + 1; j < len(infos); j++ {- if infos[j].bytes > infos[i].bytes {- infos[i], infos[j] = infos[j], infos[i]- }- }- }-- fmt.Printf("[DEBUG] %d arrays, %.2f GB total:\n", len(infos), float64(totalBytes)/(1024*1024*1024))- for i, info := range infos {- if i >= topN {- break- }- keptStr := ""- if info.kept {- keptStr = " [kept]"- }- fmt.Printf(" %3d. %8.2f MB %v %v%s\n",- i+1, float64(info.bytes)/(1024*1024), info.shape, info.dtype, keptStr)- }-}--// Eval synchronously evaluates arrays and cleans up non-kept arrays.-// Outputs are automatically kept (survive cleanup). Returns them for chaining.-func Eval(outputs ...*Array) []*Array {- // Keep outputs so cleanup doesn't free them- for _, o := range outputs {- if o != nil {- o.kept = true- }- }-- // Cleanup non-kept arrays- cleanup()-- // Then evaluate- if len(outputs) > 0 {- evalHandles = evalHandles[:0]- for _, o := range outputs {- if o != nil {- evalHandles = append(evalHandles, o.c)- }- }- if len(evalHandles) > 0 {- vec := C.mlx_vector_array_new_data(&evalHandles[0], C.size_t(len(evalHandles)))- C.mlx_eval(vec)- C.mlx_vector_array_free(vec)- }- }- return outputs-}--// AsyncEval dispatches async evaluation and cleans up non-kept arrays.-// Outputs are automatically kept (survive cleanup).-func AsyncEval(outputs ...*Array) {- // Keep outputs so cleanup doesn't free them- for _, o := range outputs {- if o != nil {- o.kept = true- }- }-- // Cleanup non-kept arrays- cleanup()-- // Then dispatch async eval- if len(outputs) > 0 {- evalHandles = evalHandles[:0]- for _, o := range outputs {- if o != nil {- evalHandles = append(evalHandles, o.c)- }- }- if len(evalHandles) > 0 {- vec := C.mlx_vector_array_new_data(&evalHandles[0], C.size_t(len(evalHandles)))- C.mlx_async_eval(vec)- C.mlx_vector_array_free(vec)- }- }-}--// Sync waits for all async operations to complete (no cleanup).-func Sync() {- C.mlx_synchronize(C.default_stream())-}--// Free marks this array for cleanup on the next Eval().-// The array is not immediately freed - cleanup happens during Eval().-//-// Pattern for loops:-//-// oldLatents.Free() // mark for cleanup-// mlx.Eval(newLatents) // frees old, evals new-func (a *Array) Free() {- if a != nil {- a.kept = false- }-}--// Eval evaluates this single array and runs cleanup.-func (a *Array) Eval() *Array {- Eval(a)- return a-}--// Valid returns true if the array hasn't been freed.-func (a *Array) Valid() bool {- return a != nil && a.c.ctx != nil-}--// Kept returns true if the array is marked to survive Eval() cleanup.-func (a *Array) Kept() bool {- return a != nil && a.kept-}--func int32ToCInt(s []int32) *C.int {- if len(s) == 0 {- return nil- }- return (*C.int)(unsafe.Pointer(&s[0]))-}--// NewArray creates a new MLX array from float32 data-func NewArray(data []float32, shape []int32) *Array {- handle := C.mlx_array_new_data(- unsafe.Pointer(&data[0]),- int32ToCInt(shape),- C.int(len(shape)),- C.MLX_FLOAT32,- )- return newArray(handle)-}--// NewArrayInt32 creates a new MLX array from int32 data-func NewArrayInt32(data []int32, shape []int32) *Array {- handle := C.mlx_array_new_data(- unsafe.Pointer(&data[0]),- int32ToCInt(shape),- C.int(len(shape)),- C.MLX_INT32,- )- return newArray(handle)-}--// NewArrayFloat32 creates a new float32 array from data-func NewArrayFloat32(data []float32, shape []int32) *Array {- return NewArray(data, shape)-}--// Zeros creates an array of zeros with optional dtype (default float32)-func Zeros(shape []int32, dtype ...Dtype) *Array {- res := C.mlx_array_new()- dt := DtypeFloat32- if len(dtype) > 0 {- dt = dtype[0]- }- C.mlx_zeros(&res, int32ToCInt(shape), C.size_t(len(shape)), C.mlx_dtype(dt), C.default_stream())- return newArray(res)-}--// ZerosLike creates a zeros array with the same dtype as a.-// If shape is provided, uses that shape; otherwise uses a's shape.-func ZerosLike(a *Array, shape ...int32) *Array {- res := C.mlx_array_new()- if len(shape) == 0 {- C.mlx_zeros_like(&res, a.c, C.default_stream())- } else {- dtype := a.Dtype()- C.mlx_zeros(&res, int32ToCInt(shape), C.size_t(len(shape)), C.mlx_dtype(dtype), C.default_stream())- }- return newArray(res)-}--// Ones creates an array of ones-func Ones(shape ...int32) *Array {- res := C.mlx_array_new()- C.mlx_ones(&res, int32ToCInt(shape), C.size_t(len(shape)), C.MLX_FLOAT32, C.default_stream())- return newArray(res)-}--// Full creates an array filled with a value-func Full(value float32, shape ...int32) *Array {- vals := C.mlx_array_new_float(C.float(value))- res := C.mlx_array_new()- C.mlx_full(&res, int32ToCInt(shape), C.size_t(len(shape)), vals, C.MLX_FLOAT32, C.default_stream())- C.mlx_array_free(vals)- return newArray(res)-}--// Arange creates a range of values-func Arange(start, stop, step float32) *Array {- res := C.mlx_array_new()- C.mlx_arange(&res, C.double(start), C.double(stop), C.double(step), C.MLX_FLOAT32, C.default_stream())- return newArray(res)-}--// Linspace creates evenly spaced values-func Linspace(start, stop float32, steps int32) *Array {- res := C.mlx_array_new()- C.mlx_linspace(&res, C.double(start), C.double(stop), C.int(steps), C.MLX_FLOAT32, C.default_stream())- return newArray(res)-}--// ============ Math Operations ============--// Add adds two arrays element-wise-func Add(a, b *Array) *Array {- res := C.mlx_array_new()- C.mlx_add(&res, a.c, b.c, C.default_stream())- return newArray(res)-}--// AddRaw is like Add - kept for API compatibility (now identical to Add)-func AddRaw(a, b *Array) *Array {- return Add(a, b)-}--// Sub subtracts two arrays element-wise-func Sub(a, b *Array) *Array {- res := C.mlx_array_new()- C.mlx_subtract(&res, a.c, b.c, C.default_stream())- return newArray(res)-}--// Mul multiplies two arrays element-wise-func Mul(a, b *Array) *Array {- res := C.mlx_array_new()- C.mlx_multiply(&res, a.c, b.c, C.default_stream())- return newArray(res)-}--// Div divides two arrays element-wise-func Div(a, b *Array) *Array {- res := C.mlx_array_new()- C.mlx_divide(&res, a.c, b.c, C.default_stream())- return newArray(res)-}--// Matmul performs matrix multiplication-func Matmul(a, b *Array) *Array {- res := C.mlx_array_new()- C.mlx_matmul(&res, a.c, b.c, C.default_stream())- return newArray(res)-}--// AddMM computes: result = beta*c + alpha*(a @ b)-// This fuses bias addition with matmul into a single op.-func AddMM(c, a, b *Array, alpha, beta float32) *Array {- res := C.mlx_array_new()- C.mlx_addmm(&res, c.c, a.c, b.c, C.float(alpha), C.float(beta), C.default_stream())- return newArray(res)-}--// Linear performs matrix multiplication: a @ weight-func Linear(a, weight *Array) *Array {- return Matmul(a, weight)-}--// Sqrt computes element-wise square root-func Sqrt(a *Array) *Array {- res := C.mlx_array_new()- C.mlx_sqrt(&res, a.c, C.default_stream())- return newArray(res)-}--// RSqrt computes element-wise reciprocal square root-func RSqrt(a *Array) *Array {- res := C.mlx_array_new()- C.mlx_rsqrt(&res, a.c, C.default_stream())- return newArray(res)-}--// Erf computes element-wise error function-func Erf(a *Array) *Array {- res := C.mlx_array_new()- C.mlx_erf(&res, a.c, C.default_stream())- return newArray(res)-}--// Exp computes element-wise exponential-func Exp(a *Array) *Array {- res := C.mlx_array_new()- C.mlx_exp(&res, a.c, C.default_stream())- return newArray(res)-}--// Log computes element-wise natural logarithm-func Log(a *Array) *Array {- res := C.mlx_array_new()- C.mlx_log(&res, a.c, C.default_stream())- return newArray(res)-}--// Sin computes element-wise sine-func Sin(a *Array) *Array {- res := C.mlx_array_new()- C.mlx_sin(&res, a.c, C.default_stream())- return newArray(res)-}--// Cos computes element-wise cosine-func Cos(a *Array) *Array {- res := C.mlx_array_new()- C.mlx_cos(&res, a.c, C.default_stream())- return newArray(res)-}--// Neg negates the array-func Neg(a *Array) *Array {- res := C.mlx_array_new()- C.mlx_negative(&res, a.c, C.default_stream())- return newArray(res)-}--// Abs computes element-wise absolute value-func Abs(a *Array) *Array {- res := C.mlx_array_new()- C.mlx_abs(&res, a.c, C.default_stream())- return newArray(res)-}--// Square computes element-wise square-func Square(a *Array) *Array {- res := C.mlx_array_new()- C.mlx_square(&res, a.c, C.default_stream())- return newArray(res)-}--// Pow raises a to the power of b element-wise-func Pow(a, b *Array) *Array {- res := C.mlx_array_new()- C.mlx_power(&res, a.c, b.c, C.default_stream())- return newArray(res)-}--// Max computes element-wise maximum-func Max(a, b *Array) *Array {- res := C.mlx_array_new()- C.mlx_maximum(&res, a.c, b.c, C.default_stream())- return newArray(res)-}--// Min computes element-wise minimum-func Min(a, b *Array) *Array {- res := C.mlx_array_new()- C.mlx_minimum(&res, a.c, b.c, C.default_stream())- return newArray(res)-}--// scalarWithDtype creates a scalar array matching the dtype of a (critical for graph fusion!)-func scalarWithDtype(s float32, a *Array) C.mlx_array {- // Create float32 scalar, then cast to match input dtype- f32 := C.mlx_array_new_float(C.float(s))- dtype := a.Dtype()- if dtype == DtypeFloat32 {- return f32 // No cast needed- }- // Cast to match input dtype- casted := C.mlx_array_new()- C.mlx_astype(&casted, f32, C.mlx_dtype(dtype), C.default_stream())- C.mlx_array_free(f32)- return casted-}--// AddScalar adds a scalar to an array (matches dtype for graph fusion)-func AddScalar(a *Array, s float32) *Array {- scalar := scalarWithDtype(s, a)- res := C.mlx_array_new()- C.mlx_add(&res, a.c, scalar, C.default_stream())- C.mlx_array_free(scalar)- return newArray(res)-}--// MulScalar multiplies an array by a scalar (matches dtype for graph fusion)-func MulScalar(a *Array, s float32) *Array {- scalar := scalarWithDtype(s, a)- res := C.mlx_array_new()- C.mlx_multiply(&res, a.c, scalar, C.default_stream())- C.mlx_array_free(scalar)- return newArray(res)-}--// DivScalar divides an array by a scalar (matches dtype for graph fusion)-func DivScalar(a *Array, s float32) *Array {- scalar := scalarWithDtype(s, a)- res := C.mlx_array_new()- C.mlx_divide(&res, a.c, scalar, C.default_stream())- C.mlx_array_free(scalar)- return newArray(res)-}--// DivScalarInt divides an int array by an int scalar (regular division, may return float)-func DivScalarInt(a *Array, s int32) *Array {- scalar := C.mlx_array_new_int(C.int(s))- res := C.mlx_array_new()- C.mlx_divide(&res, a.c, scalar, C.default_stream())- C.mlx_array_free(scalar)- return newArray(res)-}--// FloorDivideScalar performs integer floor division (a // s), preserving int dtype-func FloorDivideScalar(a *Array, s int32) *Array {- scalar := C.mlx_array_new_int(C.int(s))- res := C.mlx_array_new()- C.mlx_floor_divide(&res, a.c, scalar, C.default_stream())- C.mlx_array_free(scalar)- return newArray(res)-}--// ============ Reduction Operations ============--// Sum reduces along an axis-func Sum(a *Array, axis int, keepdims bool) *Array {- res := C.mlx_array_new()- C.mlx_sum_axis(&res, a.c, C.int(axis), C._Bool(keepdims), C.default_stream())- return newArray(res)-}--// SumAll reduces the entire array to a scalar-func SumAll(a *Array) *Array {- res := C.mlx_array_new()- C.mlx_sum(&res, a.c, false, C.default_stream())- return newArray(res)-}--// Mean reduces along an axis-func Mean(a *Array, axis int, keepdims bool) *Array {- res := C.mlx_array_new()- C.mlx_mean_axis(&res, a.c, C.int(axis), C._Bool(keepdims), C.default_stream())- return newArray(res)-}--// MeanAll reduces the entire array to a scalar-func MeanAll(a *Array) *Array {- res := C.mlx_array_new()- C.mlx_mean(&res, a.c, false, C.default_stream())- return newArray(res)-}--// Var computes variance along an axis-func Var(a *Array, axis int, keepdims bool) *Array {- res := C.mlx_array_new()- C.mlx_var_axis(&res, a.c, C.int(axis), C._Bool(keepdims), 0, C.default_stream())- return newArray(res)-}--// Argmax returns indices of maximum values along an axis-func Argmax(a *Array, axis int, keepdims bool) *Array {- res := C.mlx_array_new()- C.mlx_argmax_axis(&res, a.c, C.int(axis), C._Bool(keepdims), C.default_stream())- return newArray(res)-}--// ArgmaxAll returns the index of the maximum element (flattened).-// Triggers cleanup of non-kept arrays.-func ArgmaxAll(a *Array) int32 {- cleanup()- // Flatten, then argmax with keepdims=false- flat := C.mlx_array_new()- C.mlx_flatten(&flat, a.c, 0, -1, C.default_stream())- res := C.mlx_array_new()- C.mlx_argmax(&res, flat, false, C.default_stream())- C.mlx_array_eval(res)- var val C.int32_t- C.mlx_array_item_int32(&val, res)- C.mlx_array_free(flat)- C.mlx_array_free(res)- return int32(val)-}--// Reshape reshapes the array-func Reshape(a *Array, shape ...int32) *Array {- res := C.mlx_array_new()- C.mlx_reshape(&res, a.c, int32ToCInt(shape), C.size_t(len(shape)), C.default_stream())- return newArray(res)-}--// Transpose permutes the dimensions-func Transpose(a *Array, axes ...int) *Array {- cAxes := make([]C.int, len(axes))- for i, ax := range axes {- cAxes[i] = C.int(ax)- }- res := C.mlx_array_new()- C.mlx_transpose_axes(&res, a.c, &cAxes[0], C.size_t(len(axes)), C.default_stream())- return newArray(res)-}--// AsStrided creates a view with custom strides. Useful for fusing reshape+transpose.-func AsStrided(a *Array, shape []int32, strides []int64, offset int64) *Array {- cShape := make([]C.int, len(shape))- for i, s := range shape {- cShape[i] = C.int(s)- }- cStrides := make([]C.int64_t, len(strides))- for i, s := range strides {- cStrides[i] = C.int64_t(s)- }- res := C.mlx_array_new()- C.mlx_as_strided(&res, a.c, &cShape[0], C.size_t(len(shape)), &cStrides[0], C.size_t(len(strides)), C.size_t(offset), C.default_stream())- return newArray(res)-}--// ExpandDims adds a dimension at the specified axis-func ExpandDims(a *Array, axis int) *Array {- res := C.mlx_array_new()- C.mlx_expand_dims(&res, a.c, C.int(axis), C.default_stream())- return newArray(res)-}--// Squeeze removes a dimension at the specified axis-func Squeeze(a *Array, axis int) *Array {- res := C.mlx_array_new()- C.mlx_squeeze_axis(&res, a.c, C.int(axis), C.default_stream())- return newArray(res)-}--// Flatten flattens the array to 1D-func Flatten(a *Array) *Array {- res := C.mlx_array_new()- C.mlx_flatten(&res, a.c, 0, -1, C.default_stream())- return newArray(res)-}--// FlattenRange flattens consecutive axes from start_axis to end_axis (intermediates)-func FlattenRange(a *Array, startAxis, endAxis int) *Array {- res := C.mlx_array_new()- C.mlx_flatten(&res, a.c, C.int(startAxis), C.int(endAxis), C.default_stream())- return newArray(res)-}--// View reinterprets the array with a new dtype (no data copy)-func View(a *Array, dtype int) *Array {- res := C.mlx_array_new()- C.mlx_view(&res, a.c, C.mlx_dtype(dtype), C.default_stream())- return newArray(res)-}--// Contiguous returns a contiguous copy of the array (row-major)-func Contiguous(a *Array) *Array {- res := C.mlx_array_new()- // Use allow_col=false to force row-major contiguous layout- C.mlx_contiguous(&res, a.c, false, C.default_stream())- return newArray(res)-}--// Clip clips values to [min, max]. Pass nil for no bound on that side.-func Clip(a *Array, aMin, aMax *Array) *Array {- res := C.mlx_array_new()- var minH, maxH C.mlx_array- if aMin != nil {- minH = aMin.c- }- if aMax != nil {- maxH = aMax.c- }- C.mlx_clip(&res, a.c, minH, maxH, C.default_stream())- return newArray(res)-}--// ClipScalar clips array values using scalar bounds (matches dtype for graph fusion)-// Pass math.NaN() or set hasMin/hasMax to false for unbounded-func ClipScalar(a *Array, minVal, maxVal float32, hasMin, hasMax bool) *Array {- var minArr, maxArr C.mlx_array- if hasMin {- minArr = scalarWithDtype(minVal, a)- }- if hasMax {- maxArr = scalarWithDtype(maxVal, a)- }- res := C.mlx_array_new()- C.mlx_clip(&res, a.c, minArr, maxArr, C.default_stream())- if hasMin {- C.mlx_array_free(minArr)- }- if hasMax {- C.mlx_array_free(maxArr)- }- return newArray(res)-}--// GreaterEqual returns element-wise a >= b-func GreaterEqual(a, b *Array) *Array {- res := C.mlx_array_new()- C.mlx_greater_equal(&res, a.c, b.c, C.default_stream())- return newArray(res)-}--// LessArray returns element-wise a < b-func LessArray(a, b *Array) *Array {- res := C.mlx_array_new()- C.mlx_less(&res, a.c, b.c, C.default_stream())- return newArray(res)-}--// LogicalAnd returns element-wise a && b-func LogicalAnd(a, b *Array) *Array {- res := C.mlx_array_new()- C.mlx_logical_and(&res, a.c, b.c, C.default_stream())- return newArray(res)-}--// AllClose returns true if all elements of a and b are within tolerance.-// Uses rtol (relative tolerance) and atol (absolute tolerance):-// |a - b| <= atol + rtol * |b|-func AllClose(a, b *Array, rtol, atol float64) *Array {- res := C.mlx_array_new()- C.mlx_allclose(&res, a.c, b.c, C.double(rtol), C.double(atol), C.bool(false), C.default_stream())- return newArray(res)-}--// AllCloseEqualNaN is like AllClose but treats NaN as equal to NaN.-func AllCloseEqualNaN(a, b *Array, rtol, atol float64) *Array {- res := C.mlx_array_new()- C.mlx_allclose(&res, a.c, b.c, C.double(rtol), C.double(atol), C.bool(true), C.default_stream())- return newArray(res)-}--// ArrayEqual returns true if arrays have same shape and all elements are equal.-func ArrayEqual(a, b *Array) *Array {- res := C.mlx_array_new()- C.mlx_array_equal(&res, a.c, b.c, C.bool(false), C.default_stream())- return newArray(res)-}--// ArrayEqualNaN is like ArrayEqual but treats NaN as equal to NaN.-func ArrayEqualNaN(a, b *Array) *Array {- res := C.mlx_array_new()- C.mlx_array_equal(&res, a.c, b.c, C.bool(true), C.default_stream())- return newArray(res)-}--// IsClose returns element-wise bool array indicating if values are within tolerance.-// |a - b| <= atol + rtol * |b|-func IsClose(a, b *Array, rtol, atol float64) *Array {- res := C.mlx_array_new()- C.mlx_isclose(&res, a.c, b.c, C.double(rtol), C.double(atol), C.bool(false), C.default_stream())- return newArray(res)-}--// IsCloseEqualNaN is like IsClose but treats NaN as equal to NaN.-func IsCloseEqualNaN(a, b *Array, rtol, atol float64) *Array {- res := C.mlx_array_new()- C.mlx_isclose(&res, a.c, b.c, C.double(rtol), C.double(atol), C.bool(true), C.default_stream())- return newArray(res)-}--// ReduceMax reduces array to max value over all dimensions.-func ReduceMax(a *Array) *Array {- res := C.mlx_array_new()- C.mlx_max(&res, a.c, C.bool(false), C.default_stream())- return newArray(res)-}--// ArangeInt creates an array with values from start to stop with step and specified dtype-func ArangeInt(start, stop, step int32, dtype Dtype) *Array {- res := C.mlx_array_new()- C.mlx_arange(&res, C.double(start), C.double(stop), C.double(step), C.mlx_dtype(dtype), C.default_stream())- return newArray(res)-}--// Concatenate concatenates arrays along an axis-func Concatenate(arrays []*Array, axis int) *Array {- handles := make([]C.mlx_array, len(arrays))- for i, arr := range arrays {- handles[i] = arr.c- }- vec := C.mlx_vector_array_new_data(&handles[0], C.size_t(len(handles)))- res := C.mlx_array_new()- C.mlx_concatenate_axis(&res, vec, C.int(axis), C.default_stream())- C.mlx_vector_array_free(vec)- return newArray(res)-}--// Concat is a convenience function to concatenate two arrays-func Concat(a, b *Array, axis int) *Array {- return Concatenate([]*Array{a, b}, axis)-}--// Stack stacks arrays along a new axis (axis 0 by default)-func Stack(arrays []*Array, axis int) *Array {- handles := make([]C.mlx_array, len(arrays))- for i, arr := range arrays {- handles[i] = arr.c- }- vec := C.mlx_vector_array_new_data(&handles[0], C.size_t(len(handles)))- res := C.mlx_array_new()- C.mlx_stack_axis(&res, vec, C.int(axis), C.default_stream())- C.mlx_vector_array_free(vec)- return newArray(res)-}--// Slice slices the array-func Slice(a *Array, start, stop []int32) *Array {- n := len(start)- cStart := make([]C.int, n)- cStop := make([]C.int, n)- cStrides := make([]C.int, n)- for i := range n {- cStart[i] = C.int(start[i])- cStop[i] = C.int(stop[i])- cStrides[i] = 1 // Default stride of 1- }- res := C.mlx_array_new()- C.mlx_slice(&res, a.c, &cStart[0], C.size_t(n), &cStop[0], C.size_t(n), &cStrides[0], C.size_t(n), C.default_stream())- return newArray(res)-}--// SliceStride slices with start:stop:stride like Python a[start:stop:stride]-func SliceStride(a *Array, start, stop, strides []int32) *Array {- cStart := make([]C.int, len(start))- cStop := make([]C.int, len(stop))- cStrides := make([]C.int, len(strides))- for i := range start {- cStart[i] = C.int(start[i])- cStop[i] = C.int(stop[i])- cStrides[i] = C.int(strides[i])- }- res := C.mlx_array_new()- C.mlx_slice(&res, a.c, &cStart[0], C.size_t(len(start)), &cStop[0], C.size_t(len(stop)), &cStrides[0], C.size_t(len(strides)), C.default_stream())- return newArray(res)-}--// Tile repeats the array along each dimension-func Tile(a *Array, reps []int32) *Array {- res := C.mlx_array_new()- C.mlx_tile(&res, a.c, int32ToCInt(reps), C.size_t(len(reps)), C.default_stream())- return newArray(res)-}--// BroadcastTo broadcasts an array to a given shape-func BroadcastTo(a *Array, shape []int32) *Array {- res := C.mlx_array_new()- C.mlx_broadcast_to(&res, a.c, int32ToCInt(shape), C.size_t(len(shape)), C.default_stream())- return newArray(res)-}--// ============ Neural Network Operations ============--// Softmax computes softmax along an axis-func Softmax(a *Array, axis int) *Array {- res := C.mlx_array_new()- C.mlx_softmax_axis(&res, a.c, C.int(axis), false, C.default_stream())- return newArray(res)-}--// Take gathers elements along an axis using indices-func Take(a *Array, indices *Array, axis int) *Array {- res := C.mlx_array_new()- C.mlx_take_axis(&res, a.c, indices.c, C.int(axis), C.default_stream())- return newArray(res)-}--// Argsort returns indices that would sort the array along an axis-func Argsort(a *Array, axis int) *Array {- res := C.mlx_array_new()- C.mlx_argsort_axis(&res, a.c, C.int(axis), C.default_stream())- return newArray(res)-}--// Sigmoid computes element-wise sigmoid-func Sigmoid(a *Array) *Array {- res := C.mlx_array_new()- C.mlx_sigmoid(&res, a.c, C.default_stream())- return newArray(res)-}--// ReLU computes element-wise ReLU: max(0, x)-func ReLU(a *Array) *Array {- // ReLU = maximum(x, 0) - mlx-c doesn't have mlx_relu, but we can use maximum- zero := C.mlx_array_new_float(0.0)- res := C.mlx_array_new()- C.mlx_maximum(&res, a.c, zero, C.default_stream())- C.mlx_array_free(zero)- return newArray(res)-}--// SiLU computes element-wise SiLU (Swish): x * sigmoid(x)-func SiLU(a *Array) *Array {- // SiLU = x * sigmoid(x)- sig := C.mlx_array_new()- C.mlx_sigmoid(&sig, a.c, C.default_stream())- res := C.mlx_array_new()- C.mlx_multiply(&res, a.c, sig, C.default_stream())- C.mlx_array_free(sig)- return newArray(res)-}--// GELU computes element-wise GELU (Gaussian Error Linear Unit)-// GELU(x) = x * 0.5 * (1 + erf(x / sqrt(2)))-func GELU(a *Array) *Array {- sqrt2 := C.mlx_array_new_float(1.4142135623730951)- scaled := C.mlx_array_new()- C.mlx_divide(&scaled, a.c, sqrt2, C.default_stream())- erfd := C.mlx_array_new()- C.mlx_erf(&erfd, scaled, C.default_stream())- one := C.mlx_array_new_float(1.0)- erfdPlusOne := C.mlx_array_new()- C.mlx_add(&erfdPlusOne, erfd, one, C.default_stream())- half := C.mlx_array_new_float(0.5)- halfErfdPlusOne := C.mlx_array_new()- C.mlx_multiply(&halfErfdPlusOne, half, erfdPlusOne, C.default_stream())- res := C.mlx_array_new()- C.mlx_multiply(&res, a.c, halfErfdPlusOne, C.default_stream())- C.mlx_array_free(sqrt2)- C.mlx_array_free(scaled)- C.mlx_array_free(erfd)- C.mlx_array_free(one)- C.mlx_array_free(erfdPlusOne)- C.mlx_array_free(half)- C.mlx_array_free(halfErfdPlusOne)- return newArray(res)-}--// Tanh computes element-wise tanh-func Tanh(a *Array) *Array {- res := C.mlx_array_new()- C.mlx_tanh(&res, a.c, C.default_stream())- return newArray(res)-}--// RMSNorm computes RMS normalization using mlx.fast-func RMSNorm(x, weight *Array, eps float32) *Array {- res := C.mlx_array_new()- C.mlx_fast_rms_norm(&res, x.c, weight.c, C.float(eps), C.default_stream())- return newArray(res)-}--// RMSNormNoWeight applies RMS normalization without a weight-// x * rsqrt(mean(x^2) + eps)-// Uses mlx_fast_rms_norm with ones weight for f32 accumulation precision-func RMSNormNoWeight(x *Array, eps float32) *Array {- // Create weight of ones matching last dimension- lastDim := x.Shape()[len(x.Shape())-1]- ones := AsType(Full(1.0, lastDim), x.Dtype())- return RMSNorm(x, ones, eps)-}--// LayerNorm applies layer normalization without learnable params-// (x - mean) / sqrt(var + eps)-func LayerNorm(x *Array, eps float32) *Array {- return LayerNormWithWeightBias(x, nil, nil, eps)-}--// LayerNormWithWeightBias computes layer normalization using mlx.fast-// weight and bias can be nil for elementwise_affine=False-func LayerNormWithWeightBias(x, weight, bias *Array, eps float32) *Array {- res := C.mlx_array_new()- var wc, bc C.mlx_array- if weight != nil {- wc = weight.c- }- if bias != nil {- bc = bias.c- }- C.mlx_fast_layer_norm(&res, x.c, wc, bc, C.float(eps), C.default_stream())- return newArray(res)-}--// RoPE applies rotary position embeddings using mlx.fast-func RoPE(x *Array, dims int, traditional bool, base, scale float32, offset int) *Array {- res := C.mlx_array_new()- optBase := C.mlx_optional_float{value: C.float(base), has_value: true}- C.mlx_fast_rope(&res, x.c, C.int(dims), C._Bool(traditional), optBase, C.float(scale), C.int(offset), C.mlx_array{}, C.default_stream())- return newArray(res)-}--// RoPEWithFreqs applies rotary position embeddings with custom frequencies (for YaRN)-// freqs is required - use RoPE() if you don't have custom frequencies-func RoPEWithFreqs(x, freqs *Array, dims int, traditional bool, scale float32, offset int) *Array {- res := C.mlx_array_new()- optBase := C.mlx_optional_float{has_value: false} // No base when using freqs- C.mlx_fast_rope(&res, x.c, C.int(dims), C._Bool(traditional), optBase, C.float(scale), C.int(offset), freqs.c, C.default_stream())- return newArray(res)-}--// ============ Indexing ============--// EmbeddingLookup performs embedding lookup (gathers from table)-// table: [vocab_size, hidden_size], indices: [batch, seq_len]-// returns: [batch, seq_len, hidden_size]-func EmbeddingLookup(table, indices *Array) *Array {- return Take(table, indices, 0)-}--// Gather gathers elements using indices - simplified to use take axis 0-func Gather(a, indices *Array) *Array {- return Take(a, indices, 0)-}--// ============ Array Properties ============--// Ndim returns the number of dimensions-func (a *Array) Ndim() int {- return int(C.mlx_array_ndim(a.c))-}--// Size returns the total number of elements-func (a *Array) Size() int {- return int(C.mlx_array_size(a.c))-}--// IsContiguous returns whether the array's data is contiguous in memory.-// Non-contiguous arrays (e.g., from SliceStride) must call Contiguous() before Data().-func (a *Array) IsContiguous() bool {- var res C.bool- C._mlx_array_is_contiguous(&res, a.c)- return bool(res)-}--// Dim returns the size of a dimension-func (a *Array) Dim(axis int) int32 {- return int32(C.mlx_array_dim(a.c, C.int(axis)))-}--// Shape returns the shape as a slice-func (a *Array) Shape() []int32 {- ndim := a.Ndim()- shape := make([]int32, ndim)- for i := range ndim {- shape[i] = a.Dim(i)- }- return shape-}--// IsValid returns true if the array hasn't been freed-func (a *Array) IsValid() bool {- return a != nil && a.c.ctx != nil-}--// Dtype returns the data type-func (a *Array) Dtype() Dtype {- return Dtype(C.mlx_array_dtype(a.c))-}--// Nbytes returns the total size in bytes-func (a *Array) Nbytes() int64 {- return int64(a.Size()) * a.Dtype().ItemSize()-}--// ItemSize returns the size in bytes of one element for this dtype-func (d Dtype) ItemSize() int64 {- switch d {- case DtypeBool, DtypeUint8, DtypeInt8:- return 1- case DtypeUint16, DtypeInt16, DtypeFloat16, DtypeBFloat16:- return 2- case DtypeUint32, DtypeInt32, DtypeFloat32:- return 4- case DtypeUint64, DtypeInt64, DtypeFloat64, DtypeComplex64:- return 8- default:- return 4- }-}--// ============ Data Access ============--// Data copies the float32 data out of the array.-// Note: For non-contiguous arrays (e.g., from SliceStride), call Contiguous() first.-// Note: Arrays of other dtypes (bf16, f16, etc) are automatically converted to float32.-// Note: Triggers cleanup of non-kept arrays.-func (a *Array) Data() []float32 {- if a == nil || !a.Valid() {- return nil- }- restore := keepDuringRead(a)- defer func() {- restore()- cleanup()- }()-- size := a.Size()- if size == 0 {- return nil- }-- arr := a- var restoreCast func()- if a.Dtype() != DtypeFloat32 {- arr = AsType(a, DtypeFloat32)- restoreCast = keepDuringRead(arr)- arr.Eval()- defer func() {- restoreCast()- }()- }- var restoreContiguous func()- if !arr.IsContiguous() {- arr = Contiguous(arr)- restoreContiguous = keepDuringRead(arr)- arr.Eval()- defer func() {- restoreContiguous()- }()- }-- ptr := C.mlx_array_data_float32(arr.c)- if ptr == nil {- return nil- }- data := make([]float32, size)- copy(data, unsafe.Slice((*float32)(unsafe.Pointer(ptr)), size))- return data-}--// Item returns the scalar value from a 0-dimensional array.-// Converts to float32 if necessary. Triggers cleanup.-func (a *Array) Item() float32 {- data := a.Data() // Data() calls cleanup()- if len(data) == 0 {- return 0- }- return data[0]-}--// DataInt32 copies the int32 data out of the array.-// Note: For non-contiguous arrays (e.g., from SliceStride), call Contiguous() first.-// Note: Triggers cleanup of non-kept arrays.-func (a *Array) DataInt32() []int32 {- if a == nil || !a.Valid() {- return nil- }- restore := keepDuringRead(a)- defer func() {- restore()- cleanup()- }()-- size := a.Size()- if size == 0 {- return nil- }- ptr := C.mlx_array_data_int32(a.c)- if ptr == nil {- return nil- }- data := make([]int32, size)- copy(data, unsafe.Slice((*int32)(unsafe.Pointer(ptr)), size))- return data-}--// ItemInt32 gets a single scalar value efficiently (no array copy).-// Note: Triggers cleanup of non-kept arrays.-func (a *Array) ItemInt32() int32 {- if a == nil || !a.Valid() {- return 0- }- restore := keepDuringRead(a)- defer func() {- restore()- cleanup()- }()-- var val C.int32_t- C.mlx_array_item_int32(&val, a.c)- return int32(val)-}--// Bytes copies the raw bytes out of the array without type conversion.-// Works with common dtypes (float32, int32, uint32, uint8).-// For non-contiguous arrays, call Contiguous() first.-// Note: Triggers cleanup of non-kept arrays.-func (a *Array) Bytes() []byte {- if a == nil || !a.Valid() {- return nil- }- restore := keepDuringRead(a)- defer func() {- restore()- cleanup()- }()-- nbytes := a.Nbytes()- if nbytes == 0 {- return nil- }-- // Get raw pointer based on dtype- var ptr unsafe.Pointer- switch a.Dtype() {- case DtypeFloat32:- ptr = unsafe.Pointer(C.mlx_array_data_float32(a.c))- case DtypeInt32:- ptr = unsafe.Pointer(C.mlx_array_data_int32(a.c))- case DtypeUint32:- ptr = unsafe.Pointer(C.mlx_array_data_uint32(a.c))- case DtypeUint8:- ptr = unsafe.Pointer(C.mlx_array_data_uint8(a.c))- default:- // For other types (bf16, f16, etc), convert to float32- arr := AsType(a, DtypeFloat32)- restoreCast := keepDuringRead(arr)- arr.Eval()- defer restoreCast()- ptr = unsafe.Pointer(C.mlx_array_data_float32(arr.c))- nbytes = arr.Nbytes()- }-- if ptr == nil {- return nil- }- data := make([]byte, nbytes)- copy(data, unsafe.Slice((*byte)(ptr), nbytes))- return data-}--// ============ Utility ============--// String returns a string representation-func (a *Array) String() string {- shape := a.Shape()- size := a.Size()- if size <= 20 {- data := a.Data()- return fmt.Sprintf("Array(shape=%v, data=%v)", shape, data)- }- return fmt.Sprintf("Array(shape=%v, size=%d)", shape, size)-}--// ============ Safetensors Support ============--// NewArrayFromBytes creates an array from raw bytes (for safetensors)-func NewArrayFromBytes(data []byte, shape []int32, dtype Dtype) *Array {- cData := unsafe.Pointer(&data[0])- intShape := make([]C.int, len(shape))- for i, s := range shape {- intShape[i] = C.int(s)- }- handle := C.mlx_array_new_data(cData, &intShape[0], C.int(len(shape)), C.mlx_dtype(dtype))- return newArray(handle)-}--// ============ Device Control ============--// SetDefaultDeviceGPU sets the default device to GPU (Metal)-func SetDefaultDeviceGPU() {- dev := C.mlx_device_new_type(C.MLX_GPU, 0)- C.mlx_set_default_device(dev)- C.mlx_device_free(dev)-}--// SetDefaultDeviceCPU sets the default device to CPU-func SetDefaultDeviceCPU() {- dev := C.mlx_device_new_type(C.MLX_CPU, 0)- C.mlx_set_default_device(dev)- C.mlx_device_free(dev)-}--// MetalIsAvailable returns true if Metal GPU is available-func MetalIsAvailable() bool {- var available C._Bool- C.mlx_metal_is_available(&available)- return bool(available)-}--// MetalStartCapture starts a GPU trace capture to the given file path.-// The path must not already exist. Run with MTL_CAPTURE_ENABLED=1 env var.-// Open the resulting .gputrace file in Xcode for analysis.-func MetalStartCapture(path string) {- cPath := C.CString(path)- defer C.free(unsafe.Pointer(cPath))- C.mlx_metal_start_capture(cPath)-}--// MetalStopCapture stops the current GPU trace capture.-func MetalStopCapture() {- C.mlx_metal_stop_capture()-}--// GPUIsAvailable returns true if any GPU (Metal or CUDA) is available-func GPUIsAvailable() bool {- // On Linux with CUDA build, GPU is available- // On macOS, check Metal availability- if MetalIsAvailable() {- return true- }- // CUDA is available if we compiled with CUDA support (Linux)- return runtime.GOOS == "linux"-}--// GetDefaultDeviceType returns the current default device (0=CPU, 1=GPU)-func GetDefaultDeviceType() int {- var dev C.mlx_device- C.mlx_get_default_device(&dev)- var devType C.mlx_device_type- C.mlx_device_get_type(&devType, dev)- C.mlx_device_free(dev)- return int(devType)-}--// Synchronize waits for all GPU operations to complete-func Synchronize() {- C.mlx_synchronize(C.default_stream())-}--// ScaledDotProductAttention computes optimized attention using GPU kernel-// Q, K, V should be [batch, heads, seq, head_dim]-func ScaledDotProductAttention(q, k, v *Array, scale float32, causalMask bool) *Array {- res := C.mlx_array_new()- maskMode := "" // empty string for no mask- if causalMask {- maskMode = "causal"- }- cMaskMode := C.CString(maskMode)- defer C.free(unsafe.Pointer(cMaskMode))- C.mlx_fast_scaled_dot_product_attention(&res, q.c, k.c, v.c, C.float(scale), cMaskMode, C.mlx_array{}, C.mlx_array{}, C.default_stream())- return newArray(res)-}--// ScaledDotProductAttentionWithSinks computes attention with sinks support-// maskMode: "causal", "sliding_window", or "" for none-// mask: optional attention mask array (nil for none)-// sinks: attention sinks array (nil for none)-func ScaledDotProductAttentionWithSinks(q, k, v *Array, scale float32, maskMode string, mask, sinks *Array) *Array {- res := C.mlx_array_new()- cMaskMode := C.CString(maskMode)- defer C.free(unsafe.Pointer(cMaskMode))- var maskH, sinksH C.mlx_array- if mask != nil {- maskH = mask.c- }- if sinks != nil {- sinksH = sinks.c- }- C.mlx_fast_scaled_dot_product_attention(&res, q.c, k.c, v.c, C.float(scale), cMaskMode, maskH, sinksH, C.default_stream())- return newArray(res)-}--// ============ Native Safetensors Loading ============--// SafetensorsFile represents a loaded safetensors file-type SafetensorsFile struct {- arrays C.mlx_map_string_to_array- metadata C.mlx_map_string_to_string-}--// LoadSafetensorsNative loads a safetensors file using MLX's optimized loader.-// On CUDA, Load::eval_gpu is implemented so we use the default (GPU) stream.-// On Metal, Load::eval_gpu is not implemented so we must use the CPU stream.-func LoadSafetensorsNative(path string) (*SafetensorsFile, error) {- cPath := C.CString(path)- defer C.free(unsafe.Pointer(cPath))-- stream := C.default_stream()- if runtime.GOOS == "darwin" {- stream = C.cpu_stream()- }-- var arrays C.mlx_map_string_to_array- var metadata C.mlx_map_string_to_string- if C.mlx_load_safetensors(&arrays, &metadata, cPath, stream) != 0 {- return nil, fmt.Errorf("failed to load safetensors: %s", path)- }- return &SafetensorsFile{arrays: arrays, metadata: metadata}, nil-}--// Get retrieves a tensor by name-func (s *SafetensorsFile) Get(name string) *Array {- cName := C.CString(name)- defer C.free(unsafe.Pointer(cName))-- var arr C.mlx_array- if C.mlx_map_string_to_array_get(&arr, s.arrays, cName) != 0 {- return nil- }- if arr.ctx == nil {- return nil- }- return newArray(arr)-}--// Set replaces a tensor in the map (like Python's weights[k] = v)-func (s *SafetensorsFile) Set(name string, arr *Array) {- cName := C.CString(name)- defer C.free(unsafe.Pointer(cName))- C.mlx_map_string_to_array_insert(s.arrays, cName, arr.c)-}--// Count returns the number of tensors (not directly available, would need iterator)-func (s *SafetensorsFile) Count() int {- // mlx-c doesn't have a direct count - would need to iterate- return 0-}--// GetMetadata retrieves a metadata value by key from the safetensors file-func (s *SafetensorsFile) GetMetadata(key string) string {- cKey := C.CString(key)- defer C.free(unsafe.Pointer(cKey))-- var cValue *C.char- if C.mlx_map_string_to_string_get(&cValue, s.metadata, cKey) != 0 {- return ""- }- return C.GoString(cValue)-}--// Free releases the safetensors file-func (s *SafetensorsFile) Free() {- C.mlx_map_string_to_array_free(s.arrays)- C.mlx_map_string_to_string_free(s.metadata)-}--// SaveSafetensors saves arrays to a safetensors file using MLX's native implementation.-// This correctly handles all dtypes including uint32 for quantized weights.-func SaveSafetensors(path string, arrays map[string]*Array) error {- cPath := C.CString(path)- defer C.free(unsafe.Pointer(cPath))-- // Create the map- cArrays := C.mlx_map_string_to_array_new()- defer C.mlx_map_string_to_array_free(cArrays)-- // Add each array to the map- for name, arr := range arrays {- cName := C.CString(name)- C.mlx_map_string_to_array_insert(cArrays, cName, arr.c)- C.free(unsafe.Pointer(cName))- }-- // Create empty metadata (optional)- cMeta := C.mlx_map_string_to_string_new()- defer C.mlx_map_string_to_string_free(cMeta)-- // Save- if C.mlx_save_safetensors(cPath, cArrays, cMeta) != 0 {- return fmt.Errorf("failed to save safetensors: %s", path)- }- return nil-}--// SaveSafetensorsWithMetadata saves arrays to a safetensors file with metadata key/value pairs.-// This is like SaveSafetensors but inserts metadata into the __metadata__ section.-func SaveSafetensorsWithMetadata(path string, arrays map[string]*Array, metadata map[string]string) error {- cPath := C.CString(path)- defer C.free(unsafe.Pointer(cPath))-- // Create the array map- cArrays := C.mlx_map_string_to_array_new()- defer C.mlx_map_string_to_array_free(cArrays)-- for name, arr := range arrays {- cName := C.CString(name)- C.mlx_map_string_to_array_insert(cArrays, cName, arr.c)- C.free(unsafe.Pointer(cName))- }-- // Create metadata map- cMeta := C.mlx_map_string_to_string_new()- defer C.mlx_map_string_to_string_free(cMeta)-- for key, value := range metadata {- cKey := C.CString(key)- cValue := C.CString(value)- C.mlx_map_string_to_string_insert(cMeta, cKey, cValue)- C.free(unsafe.Pointer(cKey))- C.free(unsafe.Pointer(cValue))- }-- // Save- if C.mlx_save_safetensors(cPath, cArrays, cMeta) != 0 {- return fmt.Errorf("failed to save safetensors: %s", path)- }- return nil-}--// ============ NPY Loading ============--// LoadNpy loads a numpy array from an npy file-// Note: Uses CPU stream because Load primitive only runs on CPU-func LoadNpy(path string) (*Array, error) {- cPath := C.CString(path)- defer C.free(unsafe.Pointer(cPath))-- var arr C.mlx_array- if C.mlx_load(&arr, cPath, C.cpu_stream()) != 0 {- return nil, fmt.Errorf("failed to load npy: %s", path)- }- if arr.ctx == nil {- return nil, fmt.Errorf("failed to load npy: %s", path)- }- return newArray(arr), nil-}--// ============ Slice Update ============--// SliceUpdate updates a slice of the array with new values-func SliceUpdate(a, update *Array, start, stop []int32) *Array {- n := len(start)- cStart := make([]C.int, n)- cStop := make([]C.int, n)- cStrides := make([]C.int, n)- for i := range n {- cStart[i] = C.int(start[i])- cStop[i] = C.int(stop[i])- cStrides[i] = 1 // Default stride of 1- }- res := C.mlx_array_new()- C.mlx_slice_update(&res, a.c, update.c, &cStart[0], C.size_t(n), &cStop[0], C.size_t(n), &cStrides[0], C.size_t(n), C.default_stream())- return newArray(res)-}--// SliceUpdateInplace updates a slice and returns a new array.-// Note: Despite the name, this is NOT in-place - MLX arrays are immutable.-// The caller must use the returned value.-func SliceUpdateInplace(a, update *Array, start, stop []int32) *Array {- return SliceUpdate(a, update, start, stop)-}--// ============ Optimized Operations ============--// SampleArgmax gets the last logit position and returns argmax (fused operation)-func SampleArgmax(logits *Array) int32 {- result := Argmax(logits, -1, false)- return result.ItemInt32()-}--// ArgmaxKeepArray returns argmax as an Array (for pipelining, no sync)-// This is like mlx-lm's sampler that returns y as an array, not .item()-func ArgmaxKeepArray(logits *Array) *Array {- // For greedy decoding: logits shape is [1, 1, vocab]- // We want argmax over vocab dimension, return shape []- return Argmax(logits, -1, false)-}--// RandomState is the global PRNG state, analogous to mx.random.state in Python.-// It's a slice containing a single key array. Random functions use and update this state.-//-// Thread safety: Protected by randomStateMu, mimicking Python's GIL behavior.-// All random functions that use global state acquire this lock.-var (- RandomState = []*Array{nil}- randomStateMu sync.Mutex-)--var (- mlxInitialized bool- mlxInitError error-)--// InitMLX initializes the MLX library by dynamically loading libmlxc.-// This must be called before using any MLX functions.-// Returns an error if the library cannot be loaded.-func InitMLX() error {- if mlxInitialized {- return mlxInitError- }-- libPath, err := mlxrunnermlx.LoadedLibraryPath()- if err != nil {- mlxInitError = fmt.Errorf("failed to initialize MLX: %w", err)- return mlxInitError- }-- cPath := C.CString(libPath)- defer C.free(unsafe.Pointer(cPath))- if C.mlx_dynamic_init_path(cPath) != 0 {- errMsg := C.GoString(C.mlx_dynamic_error())- mlxInitError = fmt.Errorf("failed to initialize MLX: %s", errMsg)- return mlxInitError- }-- // Initialize all function pointers via dlsym- handle := C.mlx_get_handle()- if C.mlx_load_functions(handle) != 0 {- mlxInitError = fmt.Errorf("failed to load MLX function symbols")- return mlxInitError- }-- mlxInitialized = true- mlxInitError = nil-- // Enter safe mode: replace the default exit(-1) error handler with one- // that logs and stores errors. This prevents a GPU init failure from- // killing the entire process during startup.- C.mlx_set_safe_init_mode()-- // Lock main goroutine to OS thread for CUDA context stability.- // CUDA contexts are bound to threads; Go can migrate goroutines between threads.- runtime.LockOSThread()- RandomState[0] = RandomKey(uint64(time.Now().UnixMilli()))- Keep(RandomState[0]) // Global state should persist-- // Check if the RandomKey call silently failed under safe mode- if C.mlx_had_init_error() != 0 {- msg := C.GoString(C.mlx_get_init_error())- mlxInitError = fmt.Errorf("MLX GPU init failed: %s", msg)- mlxInitialized = false- return mlxInitError- }-- return nil-}--// IsMLXAvailable returns whether MLX was successfully initialized-func IsMLXAvailable() bool {- return mlxInitialized && mlxInitError == nil-}--// GetMLXInitError returns any error that occurred during MLX initialization-func GetMLXInitError() error {- return mlxInitError-}--// RestoreDefaultErrorHandler restores the default MLX error handler (exit on error).-// Call this from runner entry points after confirming MLX is available,-// to get the original strict error behavior during actual MLX work.-func RestoreDefaultErrorHandler() {- C.mlx_set_default_error_mode()-}--// RandomKey creates a PRNG key from a seed-func RandomKey(seed uint64) *Array {- var res C.mlx_array- C.mlx_random_key(&res, C.uint64_t(seed))- return newArray(res)-}--// RandomSplit splits a PRNG key into two new keys-func RandomSplit(key *Array) (*Array, *Array) {- var key1, key2 C.mlx_array- C.mlx_random_split(&key1, &key2, key.c, C.default_stream())- return newArray(key1), newArray(key2)-}--// RandomCategoricalWithKey samples from categorical distribution using provided key.-func RandomCategoricalWithKey(logits, key *Array, axis int, numSamples int) *Array {- res := C.mlx_array_new()- C.mlx_random_categorical_num_samples(&res, logits.c, C.int(axis), C.int(numSamples), key.c, C.default_stream())- return newArray(res)-}--// RandomCategorical samples using global RandomState.-// For simple scripts - production code should use RandomCategoricalWithKey with explicit key management.-func RandomCategorical(logits *Array, axis int, numSamples int) *Array {- randomStateMu.Lock()- oldKey := RandomState[0]- key1, key2 := RandomSplit(oldKey)- Keep(key1) // key1 becomes the new global state- oldKey.Free()- RandomState[0] = key1- randomStateMu.Unlock()- return RandomCategoricalWithKey(logits, key2, axis, numSamples)-}--// RandomNormal creates a random normal (Gaussian) tensor in float32-func RandomNormal(shape []int32, seed uint64) *Array {- return RandomNormalWithDtype(shape, seed, DtypeFloat32)-}--// RandomNormalWithDtype creates a random normal (Gaussian) tensor with specified dtype-func RandomNormalWithDtype(shape []int32, seed uint64, dtype Dtype) *Array {- key := RandomKey(seed)- res := C.mlx_array_new()- C.mlx_random_normal(&res, int32ToCInt(shape), C.size_t(len(shape)), C.mlx_dtype(dtype), 0.0, 1.0, key.c, C.default_stream())- return newArray(res)-}--// RandomUniform generates uniform random values in [0, 1) with the given shape-func RandomUniform(shape []int32, seed uint64) *Array {- key := RandomKey(seed)- low := C.mlx_array_new_float(0.0)- high := C.mlx_array_new_float(1.0)- res := C.mlx_array_new()- C.mlx_random_uniform(&res, low, high, int32ToCInt(shape), C.size_t(len(shape)), C.MLX_FLOAT32, key.c, C.default_stream())- C.mlx_array_free(low)- C.mlx_array_free(high)- return newArray(res)-}--// Conv2d performs 2D convolution-// input: [N, H, W, C], weight: [O, kH, kW, C] (MLX uses NHWC layout)-// Returns: [N, H', W', O]-func Conv2d(input, weight *Array, stride, padding int32) *Array {- res := C.mlx_array_new()- C.mlx_conv2d(&res, input.c, weight.c, C.int(stride), C.int(stride), C.int(padding), C.int(padding), 1, 1, 1, C.default_stream())- return newArray(res)-}--// Conv3d performs 3D convolution-// input: [N, D, H, W, C], weight: [O, kD, kH, kW, C] (MLX uses NDHWC layout)-// Returns: [N, D', H', W', O]-func Conv3d(input, weight *Array, strideD, strideH, strideW, padD, padH, padW int32) *Array {- res := C.mlx_array_new()- C.mlx_conv3d(&res, input.c, weight.c, C.int(strideD), C.int(strideH), C.int(strideW), C.int(padD), C.int(padH), C.int(padW), 1, 1, 1, 1, C.default_stream())- return newArray(res)-}--// ============ Compilation Control ============--// EnableCompile enables global compilation/graph fusion-func EnableCompile() {- C.mlx_enable_compile()-}--// DisableCompile disables global compilation-func DisableCompile() {- C.mlx_disable_compile()-}--// SetCompileMode sets the compile mode-// 0=disabled, 1=no_simplify, 2=no_fuse, 3=enabled-func SetCompileMode(mode int) {- C.mlx_set_compile_mode(C.mlx_compile_mode(mode))-}--// ============ Stream Control ============--// Stream represents an MLX execution stream-type Stream struct {- c C.mlx_stream-}--// NewStream creates a new execution stream on the default device-func NewStream() *Stream {- var dev C.mlx_device- C.mlx_get_default_device(&dev)- stream := C.mlx_stream_new_device(dev)- C.mlx_device_free(dev)- return &Stream{c: stream}-}--// Free releases the stream-func (s *Stream) Free() {- if s.c.ctx != nil {- C.mlx_stream_free(s.c)- s.c.ctx = nil- }-}--// SetDefaultStream sets the default stream for operations-func SetDefaultStream(s *Stream) {- C.mlx_set_default_stream(s.c)- C.set_default_stream(s.c) // Also update our cached stream-}--// GetDefaultStream returns the current default stream-func GetDefaultStream() *Stream {- var stream C.mlx_stream- var dev C.mlx_device- C.mlx_get_default_device(&dev)- C.mlx_get_default_stream(&stream, dev)- C.mlx_device_free(dev)- return &Stream{c: stream}-}--// SynchronizeStream waits for all operations on the stream to complete-func SynchronizeStream(s *Stream) {- C.mlx_synchronize(s.c)-}--// ============ Metal Memory Control ============--// MetalGetCacheMemory returns the current cache memory usage in bytes-func MetalGetCacheMemory() uint64 {- var size C.size_t- C.mlx_get_cache_memory(&size)- return uint64(size)-}--// MetalGetPeakMemory returns the peak memory usage in bytes-func MetalGetPeakMemory() uint64 {- var size C.size_t- C.mlx_get_peak_memory(&size)- return uint64(size)-}--// MetalResetPeakMemory resets the peak memory counter-func MetalResetPeakMemory() {- C.mlx_reset_peak_memory()-}--// MetalSetWiredLimit sets the wired memory limit and returns the previous limit-// This keeps tensors pinned in GPU memory for faster access-func MetalSetWiredLimit(limit uint64) uint64 {- var prev C.size_t- C.mlx_set_wired_limit(&prev, C.size_t(limit))- return uint64(prev)-}--// MetalGetActiveMemory returns the current active memory usage in bytes-func MetalGetActiveMemory() uint64 {- var size C.size_t- C.mlx_get_active_memory(&size)- return uint64(size)-}--// ClearCache clears the MLX memory cache-func ClearCache() {- C.mlx_clear_cache()-}--// SetCacheLimit sets the free cache limit in bytes-// Setting to 0 disables caching (useful for memory-constrained generation)-// Returns the previous cache limit-func SetCacheLimit(limit uint64) uint64 {- var prev C.size_t- C.mlx_set_cache_limit(&prev, C.size_t(limit))- return uint64(prev)-}--// SetMemoryLimit sets the overall memory limit in bytes-// This is a guideline for maximum memory during graph evaluation.-// When Metal is available, defaults to 1.5x the max recommended working set.-// Returns the previous memory limit-func SetMemoryLimit(limit uint64) uint64 {- var prev C.size_t- C.mlx_set_memory_limit(&prev, C.size_t(limit))- return uint64(prev)-}--// GetMemoryLimit returns the current memory limit in bytes-func GetMemoryLimit() uint64 {- var size C.size_t- C.mlx_get_memory_limit(&size)- return uint64(size)-}--// ============ MoE Operations ============--// GatherMM performs gather matrix multiplication for MoE-// a: input, b: weight matrices-// lhsIndices, rhsIndices: optional expert selection indices (nil for none)-func GatherMM(a, b *Array, lhsIndices, rhsIndices *Array, sortedIndices bool) *Array {- var lhs, rhs C.mlx_array- if lhsIndices != nil {- lhs = lhsIndices.c- }- if rhsIndices != nil {- rhs = rhsIndices.c- }- res := C.mlx_array_new()- C.mlx_gather_mm(&res, a.c, b.c, lhs, rhs, C._Bool(sortedIndices), C.default_stream())- return newArray(res)-}--// GatherQMM performs quantized gather matrix multiplication for MoE-// Used for MXFP4 and other quantized MoE inference-func GatherQMM(x, w, scales *Array, biases, lhsIndices, rhsIndices *Array, transpose bool, groupSize, bits int, mode string, sortedIndices bool) *Array {- var b, lhs, rhs C.mlx_array- if biases != nil {- b = biases.c- }- if lhsIndices != nil {- lhs = lhsIndices.c- }- if rhsIndices != nil {- rhs = rhsIndices.c- }- cMode := C.CString(mode)- defer C.free(unsafe.Pointer(cMode))- optGroupSize := C.mlx_optional_int{value: C.int(groupSize), has_value: true}- optBits := C.mlx_optional_int{value: C.int(bits), has_value: true}- res := C.mlx_array_new()- C.mlx_gather_qmm(&res, x.c, w.c, scales.c, b, lhs, rhs, C._Bool(transpose), optGroupSize, optBits, cMode, C._Bool(sortedIndices), C.default_stream())- return newArray(res)-}--// ============ Quantization ============--// Quantize quantizes weights to specified bits per element.-// Returns (quantized_weights, scales, biases).-// groupSize: number of elements quantized together (default 64)-// bits: bits per element, 2, 4, or 8 (default 4)-// mode: "affine" (default), "mxfp4", or "mxfp8"-// Note: mxfp8 mode returns nil biases (only weights and scales)-func Quantize(w *Array, groupSize, bits int, mode string) (weights, scales, biases *Array) {- cMode := C.CString(mode)- defer C.free(unsafe.Pointer(cMode))- optGroupSize := C.mlx_optional_int{value: C.int(groupSize), has_value: true}- optBits := C.mlx_optional_int{value: C.int(bits), has_value: true}- res := C.mlx_vector_array_new()- var globalScale C.mlx_array- C.mlx_quantize(&res, w.c, optGroupSize, optBits, cMode, globalScale, C.default_stream())-- // Result is a vector of arrays: [weights, scales, biases?]- // mxfp8 mode returns only 2 elements (no biases)- vecSize := int(C.mlx_vector_array_size(res))- var w0, w1, w2 C.mlx_array- C.mlx_vector_array_get(&w0, res, 0)- C.mlx_vector_array_get(&w1, res, 1)- if vecSize >= 3 {- C.mlx_vector_array_get(&w2, res, 2)- }- C.mlx_vector_array_free(res)-- if vecSize >= 3 {- return newArray(w0), newArray(w1), newArray(w2)- }- return newArray(w0), newArray(w1), nil-}--// Dequantize reconstructs weights from quantized form.-// groupSize: number of elements quantized together (default 64)-// bits: bits per element, 2, 4, or 8 (default 4)-// mode: "affine" (default) or "mxfp4"-func Dequantize(w, scales, biases *Array, groupSize, bits int, mode string) *Array {- cMode := C.CString(mode)- defer C.free(unsafe.Pointer(cMode))- optGroupSize := C.mlx_optional_int{value: C.int(groupSize), has_value: true}- optBits := C.mlx_optional_int{value: C.int(bits), has_value: true}- optDtype := C.mlx_optional_dtype{has_value: false}-- var b C.mlx_array- if biases != nil {- b = biases.c- }-- res := C.mlx_array_new()- var globalScale C.mlx_array- C.mlx_dequantize(&res, w.c, scales.c, b, optGroupSize, optBits, cMode, globalScale, optDtype, C.default_stream())- return newArray(res)-}--// QuantizedMatmul performs matrix multiplication with quantized weights.-// x: input tensor [batch..., in_features]-// w: quantized weights-// scales, biases: from Quantize-// transpose: if true, compute x @ w.T (typical for Linear layers)-// groupSize, bits, mode: must match what was used in Quantize-func QuantizedMatmul(x, w, scales, biases *Array, transpose bool, groupSize, bits int, mode string) *Array {- cMode := C.CString(mode)- defer C.free(unsafe.Pointer(cMode))- optGroupSize := C.mlx_optional_int{value: C.int(groupSize), has_value: true}- optBits := C.mlx_optional_int{value: C.int(bits), has_value: true}-- var b C.mlx_array- if biases != nil {- b = biases.c- }-- res := C.mlx_array_new()- C.mlx_quantized_matmul(&res, x.c, w.c, scales.c, b, C._Bool(transpose), optGroupSize, optBits, cMode, C.default_stream())- return newArray(res)-}--// ============ Sorting and Top-K ============--// TopK returns the k largest elements along an axis-func TopK(a *Array, k int, axis int) *Array {- res := C.mlx_array_new()- C.mlx_topk_axis(&res, a.c, C.int(k), C.int(axis), C.default_stream())- return newArray(res)-}--// Argpartition returns indices for partial sort (k-th smallest first)-func Argpartition(a *Array, kth int, axis int) *Array {- res := C.mlx_array_new()- C.mlx_argpartition_axis(&res, a.c, C.int(kth), C.int(axis), C.default_stream())- return newArray(res)-}--// TakeAlongAxis takes elements from array using indices along axis-func TakeAlongAxis(a, indices *Array, axis int) *Array {- res := C.mlx_array_new()- C.mlx_take_along_axis(&res, a.c, indices.c, C.int(axis), C.default_stream())- return newArray(res)-}--// PutAlongAxis puts values into array at indices along axis-func PutAlongAxis(a, indices, values *Array, axis int) *Array {- res := C.mlx_array_new()- C.mlx_put_along_axis(&res, a.c, indices.c, values.c, C.int(axis), C.default_stream())- return newArray(res)-}--// Cumsum computes cumulative sum along an axis-func Cumsum(a *Array, axis int) *Array {- res := C.mlx_array_new()- C.mlx_cumsum(&res, a.c, C.int(axis), false, false, C.default_stream())- return newArray(res)-}--// Where selects elements: condition ? a : b-func Where(condition, a, b *Array) *Array {- res := C.mlx_array_new()- C.mlx_where(&res, condition.c, a.c, b.c, C.default_stream())- return newArray(res)-}--// LessScalar returns element-wise a < scalar-func LessScalar(a *Array, s float32) *Array {- scalar := C.mlx_array_new_float(C.float(s))- res := C.mlx_array_new()- C.mlx_less(&res, a.c, scalar, C.default_stream())- C.mlx_array_free(scalar)- return newArray(res)-}--// FullDtype creates an array filled with a value with specific dtype-func FullDtype(value float32, dtype Dtype, shape ...int32) *Array {- intShape := make([]C.int, len(shape))- for i, s := range shape {- intShape[i] = C.int(s)- }- vals := C.mlx_array_new_float(C.float(value))- res := C.mlx_array_new()- C.mlx_full(&res, &intShape[0], C.size_t(len(shape)), vals, C.mlx_dtype(dtype), C.default_stream())- C.mlx_array_free(vals)- return newArray(res)-}--// AsType casts an array to a different dtype-func AsType(a *Array, dtype Dtype) *Array {- res := C.mlx_array_new()- C.mlx_astype(&res, a.c, C.mlx_dtype(dtype), C.default_stream())- return newArray(res)-}--// ToBFloat16 casts an array to bfloat16-func ToBFloat16(a *Array) *Array {- return AsType(a, DtypeBFloat16)-}--// ============ VibeVoice Helper Functions ============--// NewScalarArray creates a true 0-dimensional scalar array from a float32 value-func NewScalarArray(value float32) *Array {- return newArray(C.mlx_array_new_float(C.float(value)))-}--// Global random seed counter for RandN-var randnSeedCounter uint64 = uint64(time.Now().UnixNano())--// RandN creates an array of random samples from a standard normal distribution-func RandN(shape []int32) *Array {- // Use incrementing seed for unique random values each call- seed := atomic.AddUint64(&randnSeedCounter, 1)- return RandomNormal(shape, seed)-}--// Pad pads an array with zeros-// paddings: [before_0, after_0, before_1, after_1, ...] for each dimension-func Pad(a *Array, paddings []int32) *Array {- numAxes := len(paddings) / 2- // Convert to low/high pairs- lowPad := make([]C.int, numAxes)- highPad := make([]C.int, numAxes)- for i := range numAxes {- lowPad[i] = C.int(paddings[i*2])- highPad[i] = C.int(paddings[i*2+1])- }- zero := C.mlx_array_new_float(0.0)- res := C.mlx_array_new()- // mlx_pad takes axes, low, high arrays- axes := make([]C.int, numAxes)- for i := range numAxes {- axes[i] = C.int(i)- }- cMode := C.CString("constant")- defer C.free(unsafe.Pointer(cMode))- C.mlx_pad(&res, a.c, &axes[0], C.size_t(numAxes), &lowPad[0], C.size_t(numAxes), &highPad[0], C.size_t(numAxes), zero, cMode, C.default_stream())- C.mlx_array_free(zero)- return newArray(res)-}--// Conv1d performs 1D convolution-// x: [B, L, Cin], weight: [Cout, K, Cin] (MLX uses NLC layout)-// bias: optional (nil for no bias)-func Conv1d(x, weight *Array, bias *Array, stride int32) *Array {- res := C.mlx_array_new()- C.mlx_conv1d(&res, x.c, weight.c, C.int(stride), C.int(0), C.int(1), 1, C.default_stream())- // Apply bias if provided- if bias != nil {- biased := C.mlx_array_new()- C.mlx_add(&biased, res, bias.c, C.default_stream())- C.mlx_array_free(res)- return newArray(biased)- }- return newArray(res)-}--// ConvTranspose1d performs transposed 1D convolution-// x: [B, L, Cin], weight: [Cout, K, Cin] (MLX uses NLC layout)-// bias: optional (nil for no bias)-func ConvTranspose1d(x, weight *Array, bias *Array, stride int32) *Array {- res := C.mlx_array_new()- // stride, padding, dilation, output_padding, groups- C.mlx_conv_transpose1d(&res, x.c, weight.c, C.int(stride), 0, 1, 0, 1, C.default_stream())- // Apply bias if provided- if bias != nil {- biased := C.mlx_array_new()- C.mlx_add(&biased, res, bias.c, C.default_stream())- C.mlx_array_free(res)- return newArray(biased)- }- return newArray(res)-}--// DepthwiseConv1d performs depthwise 1D convolution (groups=Cin)-// x: [B, L, C], weight: [1, K, C] (groups = C)-// bias: optional (nil for no bias)-func DepthwiseConv1d(x, weight *Array, bias *Array) *Array {- // Get number of input channels for groups- shape := x.Shape()- groups := int(shape[len(shape)-1])- res := C.mlx_array_new()- C.mlx_conv1d(&res, x.c, weight.c, 1, 0, 1, C.int(groups), C.default_stream())- // Apply bias if provided- if bias != nil {- biased := C.mlx_array_new()- C.mlx_add(&biased, res, bias.c, C.default_stream())- C.mlx_array_free(res)- return newArray(biased)- }- return newArray(res)-}--// SliceAxis extracts a slice along a specific axis-func SliceAxis(a *Array, axis int, start, stop int32) *Array {- shape := a.Shape()-- // Build start and stop indices for all dimensions- starts := make([]int32, len(shape))- stops := make([]int32, len(shape))- for i := range shape {- if i == axis {- starts[i] = start- stops[i] = stop- } else {- starts[i] = 0- stops[i] = shape[i]- }- }-- return Slice(a, starts, stops)-}--// Tri creates a lower triangular matrix-func Tri(n, m int32, k int) *Array {- res := C.mlx_array_new()- C.mlx_tri(&res, C.int(n), C.int(m), C.int(k), C.MLX_FLOAT32, C.default_stream())- return newArray(res)-}diff --git a/x/imagegen/mlx/mlx.h b/x/imagegen/mlx/mlx.hdeleted file mode 100644index 3f7e12a95..000000000--- a/x/imagegen/mlx/mlx.h+++ /dev/null@@ -1,2517 +0,0 @@-// AUTO-GENERATED by generate_wrappers.go - DO NOT EDIT-// This file provides wrapper declarations for MLX-C functions that use dlopen/dlsym-//-// Strategy: Include MLX-C headers for type definitions, then provide wrapper-// functions that shadow the originals, allowing Go code to call them directly (e.g., C.mlx_add).-// Function pointers are defined in mlx.c (single compilation unit).--#ifndef MLX_WRAPPERS_H-#define MLX_WRAPPERS_H--// Include MLX headers for type definitions and original declarations-#include "mlx/c/mlx.h"-#include "mlx_dynamic.h"-#include <stdio.h>--// Undefine any existing MLX function macros-#undef mlx_dtype_size-#undef mlx_array_tostring-#undef mlx_array_new-#undef mlx_array_free-#undef mlx_array_new_bool-#undef mlx_array_new_int-#undef mlx_array_new_float32-#undef mlx_array_new_float-#undef mlx_array_new_float64-#undef mlx_array_new_double-#undef mlx_array_new_complex-#undef mlx_array_new_data-#undef mlx_array_new_data_managed-#undef mlx_array_new_data_managed_payload-#undef mlx_array_set-#undef mlx_array_set_bool-#undef mlx_array_set_int-#undef mlx_array_set_float32-#undef mlx_array_set_float-#undef mlx_array_set_float64-#undef mlx_array_set_double-#undef mlx_array_set_complex-#undef mlx_array_set_data-#undef mlx_array_itemsize-#undef mlx_array_size-#undef mlx_array_nbytes-#undef mlx_array_ndim-#undef mlx_array_shape-#undef mlx_array_strides-#undef mlx_array_dim-#undef mlx_array_dtype-#undef mlx_array_eval-#undef mlx_array_item_bool-#undef mlx_array_item_uint8-#undef mlx_array_item_uint16-#undef mlx_array_item_uint32-#undef mlx_array_item_uint64-#undef mlx_array_item_int8-#undef mlx_array_item_int16-#undef mlx_array_item_int32-#undef mlx_array_item_int64-#undef mlx_array_item_float32-#undef mlx_array_item_float64-#undef mlx_array_item_complex64-#undef mlx_array_item_float16-#undef mlx_array_item_bfloat16-#undef mlx_array_data_bool-#undef mlx_array_data_uint8-#undef mlx_array_data_uint16-#undef mlx_array_data_uint32-#undef mlx_array_data_uint64-#undef mlx_array_data_int8-#undef mlx_array_data_int16-#undef mlx_array_data_int32-#undef mlx_array_data_int64-#undef mlx_array_data_float32-#undef mlx_array_data_float64-#undef mlx_array_data_complex64-#undef mlx_array_data_float16-#undef mlx_array_data_bfloat16-#undef _mlx_array_is_available-#undef _mlx_array_wait-#undef _mlx_array_is_contiguous-#undef _mlx_array_is_row_contiguous-#undef _mlx_array_is_col_contiguous-#undef mlx_closure_new-#undef mlx_closure_free-#undef mlx_closure_new_func-#undef mlx_closure_new_func_payload-#undef mlx_closure_set-#undef mlx_closure_apply-#undef mlx_closure_new_unary-#undef mlx_closure_kwargs_new-#undef mlx_closure_kwargs_free-#undef mlx_closure_kwargs_new_func-#undef mlx_closure_kwargs_new_func_payload-#undef mlx_closure_kwargs_set-#undef mlx_closure_kwargs_apply-#undef mlx_closure_value_and_grad_new-#undef mlx_closure_value_and_grad_free-#undef mlx_closure_value_and_grad_new_func-#undef mlx_closure_value_and_grad_new_func_payload-#undef mlx_closure_value_and_grad_set-#undef mlx_closure_value_and_grad_apply-#undef mlx_closure_custom_new-#undef mlx_closure_custom_free-#undef mlx_closure_custom_new_func-#undef mlx_closure_custom_new_func_payload-#undef mlx_closure_custom_set-#undef mlx_closure_custom_apply-#undef mlx_closure_custom_jvp_new-#undef mlx_closure_custom_jvp_free-#undef mlx_closure_custom_jvp_new_func-#undef mlx_closure_custom_jvp_new_func_payload-#undef mlx_closure_custom_jvp_set-#undef mlx_closure_custom_jvp_apply-#undef mlx_closure_custom_vmap_new-#undef mlx_closure_custom_vmap_free-#undef mlx_closure_custom_vmap_new_func-#undef mlx_closure_custom_vmap_new_func_payload-#undef mlx_closure_custom_vmap_set-#undef mlx_closure_custom_vmap_apply-#undef mlx_compile-#undef mlx_detail_compile-#undef mlx_detail_compile_clear_cache-#undef mlx_detail_compile_erase-#undef mlx_disable_compile-#undef mlx_enable_compile-#undef mlx_set_compile_mode-#undef mlx_cuda_is_available-#undef mlx_device_new-#undef mlx_device_new_type-#undef mlx_device_free-#undef mlx_device_set-#undef mlx_device_tostring-#undef mlx_device_equal-#undef mlx_device_get_index-#undef mlx_device_get_type-#undef mlx_get_default_device-#undef mlx_set_default_device-#undef mlx_device_is_available-#undef mlx_device_count-#undef mlx_device_info_new-#undef mlx_device_info_get-#undef mlx_device_info_free-#undef mlx_device_info_has_key-#undef mlx_device_info_is_string-#undef mlx_device_info_get_string-#undef mlx_device_info_get_size-#undef mlx_device_info_get_keys-#undef mlx_distributed_all_gather-#undef mlx_distributed_all_max-#undef mlx_distributed_all_min-#undef mlx_distributed_all_sum-#undef mlx_distributed_recv-#undef mlx_distributed_recv_like-#undef mlx_distributed_send-#undef mlx_distributed_sum_scatter-#undef mlx_distributed_group_new-#undef mlx_distributed_group_free-#undef mlx_distributed_init-#undef mlx_distributed_group_rank-#undef mlx_distributed_group_size-#undef mlx_distributed_group_split-#undef mlx_distributed_is_available-#undef mlx_set_error_handler-#undef _mlx_error-#undef mlx_export_function-#undef mlx_export_function_kwargs-#undef mlx_function_exporter_new-#undef mlx_function_exporter_free-#undef mlx_function_exporter_apply-#undef mlx_function_exporter_apply_kwargs-#undef mlx_imported_function_new-#undef mlx_imported_function_free-#undef mlx_imported_function_apply-#undef mlx_imported_function_apply_kwargs-#undef mlx_fast_cuda_kernel_config_new-#undef mlx_fast_cuda_kernel_config_free-#undef mlx_fast_cuda_kernel_config_add_output_arg-#undef mlx_fast_cuda_kernel_config_set_grid-#undef mlx_fast_cuda_kernel_config_set_thread_group-#undef mlx_fast_cuda_kernel_config_set_init_value-#undef mlx_fast_cuda_kernel_config_set_verbose-#undef mlx_fast_cuda_kernel_config_add_template_arg_dtype-#undef mlx_fast_cuda_kernel_config_add_template_arg_int-#undef mlx_fast_cuda_kernel_config_add_template_arg_bool-#undef mlx_fast_cuda_kernel_new-#undef mlx_fast_cuda_kernel_free-#undef mlx_fast_cuda_kernel_apply-#undef mlx_fast_layer_norm-#undef mlx_fast_metal_kernel_config_new-#undef mlx_fast_metal_kernel_config_free-#undef mlx_fast_metal_kernel_config_add_output_arg-#undef mlx_fast_metal_kernel_config_set_grid-#undef mlx_fast_metal_kernel_config_set_thread_group-#undef mlx_fast_metal_kernel_config_set_init_value-#undef mlx_fast_metal_kernel_config_set_verbose-#undef mlx_fast_metal_kernel_config_add_template_arg_dtype-#undef mlx_fast_metal_kernel_config_add_template_arg_int-#undef mlx_fast_metal_kernel_config_add_template_arg_bool-#undef mlx_fast_metal_kernel_new-#undef mlx_fast_metal_kernel_free-#undef mlx_fast_metal_kernel_apply-#undef mlx_fast_rms_norm-#undef mlx_fast_rope-#undef mlx_fast_rope_dynamic-#undef mlx_fast_scaled_dot_product_attention-#undef mlx_fft_fft-#undef mlx_fft_fft2-#undef mlx_fft_fftfreq-#undef mlx_fft_fftn-#undef mlx_fft_fftshift-#undef mlx_fft_ifft-#undef mlx_fft_ifft2-#undef mlx_fft_ifftn-#undef mlx_fft_ifftshift-#undef mlx_fft_irfft-#undef mlx_fft_irfft2-#undef mlx_fft_irfftn-#undef mlx_fft_rfft-#undef mlx_fft_rfft2-#undef mlx_fft_rfftfreq-#undef mlx_fft_rfftn-#undef mlx_node_namer_free-#undef mlx_node_namer_set_name-#undef mlx_node_namer_get_name-#undef mlx_export_to_dot-#undef mlx_print_graph-#undef mlx_load_reader-#undef mlx_load-#undef mlx_load_gguf-#undef mlx_load_safetensors_reader-#undef mlx_load_safetensors-#undef mlx_save_writer-#undef mlx_save-#undef mlx_save_gguf-#undef mlx_save_safetensors_writer-#undef mlx_save_safetensors-#undef mlx_io_reader_new-#undef mlx_io_reader_descriptor-#undef mlx_io_reader_tostring-#undef mlx_io_reader_free-#undef mlx_io_writer_new-#undef mlx_io_writer_descriptor-#undef mlx_io_writer_tostring-#undef mlx_io_writer_free-#undef mlx_io_gguf_new-#undef mlx_io_gguf_free-#undef mlx_io_gguf_get_keys-#undef mlx_io_gguf_get_array-#undef mlx_io_gguf_get_metadata_array-#undef mlx_io_gguf_get_metadata_string-#undef mlx_io_gguf_get_metadata_vector_string-#undef mlx_io_gguf_has_metadata_array-#undef mlx_io_gguf_has_metadata_string-#undef mlx_io_gguf_has_metadata_vector_string-#undef mlx_io_gguf_set_array-#undef mlx_io_gguf_set_metadata_array-#undef mlx_io_gguf_set_metadata_string-#undef mlx_io_gguf_set_metadata_vector_string-#undef mlx_linalg_cholesky-#undef mlx_linalg_cholesky_inv-#undef mlx_linalg_cross-#undef mlx_linalg_eig-#undef mlx_linalg_eigh-#undef mlx_linalg_eigvals-#undef mlx_linalg_eigvalsh-#undef mlx_linalg_inv-#undef mlx_linalg_lu-#undef mlx_linalg_lu_factor-#undef mlx_linalg_norm-#undef mlx_linalg_norm_matrix-#undef mlx_linalg_norm_l2-#undef mlx_linalg_pinv-#undef mlx_linalg_qr-#undef mlx_linalg_solve-#undef mlx_linalg_solve_triangular-#undef mlx_linalg_svd-#undef mlx_linalg_tri_inv-#undef mlx_map_string_to_array_new-#undef mlx_map_string_to_array_set-#undef mlx_map_string_to_array_free-#undef mlx_map_string_to_array_insert-#undef mlx_map_string_to_array_get-#undef mlx_map_string_to_array_iterator_new-#undef mlx_map_string_to_array_iterator_free-#undef mlx_map_string_to_array_iterator_next-#undef mlx_map_string_to_string_new-#undef mlx_map_string_to_string_set-#undef mlx_map_string_to_string_free-#undef mlx_map_string_to_string_insert-#undef mlx_map_string_to_string_get-#undef mlx_map_string_to_string_iterator_new-#undef mlx_map_string_to_string_iterator_free-#undef mlx_map_string_to_string_iterator_next-#undef mlx_clear_cache-#undef mlx_get_active_memory-#undef mlx_get_cache_memory-#undef mlx_get_memory_limit-#undef mlx_get_peak_memory-#undef mlx_reset_peak_memory-#undef mlx_set_cache_limit-#undef mlx_set_memory_limit-#undef mlx_set_wired_limit-#undef mlx_metal_is_available-#undef mlx_metal_start_capture-#undef mlx_metal_stop_capture-#undef mlx_abs-#undef mlx_add-#undef mlx_addmm-#undef mlx_all_axes-#undef mlx_all_axis-#undef mlx_all-#undef mlx_allclose-#undef mlx_any_axes-#undef mlx_any_axis-#undef mlx_any-#undef mlx_arange-#undef mlx_arccos-#undef mlx_arccosh-#undef mlx_arcsin-#undef mlx_arcsinh-#undef mlx_arctan-#undef mlx_arctan2-#undef mlx_arctanh-#undef mlx_argmax_axis-#undef mlx_argmax-#undef mlx_argmin_axis-#undef mlx_argmin-#undef mlx_argpartition_axis-#undef mlx_argpartition-#undef mlx_argsort_axis-#undef mlx_argsort-#undef mlx_array_equal-#undef mlx_as_strided-#undef mlx_astype-#undef mlx_atleast_1d-#undef mlx_atleast_2d-#undef mlx_atleast_3d-#undef mlx_bartlett-#undef mlx_bitwise_and-#undef mlx_bitwise_invert-#undef mlx_bitwise_or-#undef mlx_bitwise_xor-#undef mlx_blackman-#undef mlx_block_masked_mm-#undef mlx_broadcast_arrays-#undef mlx_broadcast_to-#undef mlx_ceil-#undef mlx_clip-#undef mlx_concatenate_axis-#undef mlx_concatenate-#undef mlx_conjugate-#undef mlx_contiguous-#undef mlx_conv1d-#undef mlx_conv2d-#undef mlx_conv3d-#undef mlx_conv_general-#undef mlx_conv_transpose1d-#undef mlx_conv_transpose2d-#undef mlx_conv_transpose3d-#undef mlx_copy-#undef mlx_cos-#undef mlx_cosh-#undef mlx_cummax-#undef mlx_cummin-#undef mlx_cumprod-#undef mlx_cumsum-#undef mlx_degrees-#undef mlx_depends-#undef mlx_dequantize-#undef mlx_diag-#undef mlx_diagonal-#undef mlx_divide-#undef mlx_divmod-#undef mlx_einsum-#undef mlx_equal-#undef mlx_erf-#undef mlx_erfinv-#undef mlx_exp-#undef mlx_expand_dims_axes-#undef mlx_expand_dims-#undef mlx_expm1-#undef mlx_eye-#undef mlx_flatten-#undef mlx_floor-#undef mlx_floor_divide-#undef mlx_from_fp8-#undef mlx_full-#undef mlx_full_like-#undef mlx_gather-#undef mlx_gather_single-#undef mlx_gather_mm-#undef mlx_gather_qmm-#undef mlx_greater-#undef mlx_greater_equal-#undef mlx_hadamard_transform-#undef mlx_hamming-#undef mlx_hanning-#undef mlx_identity-#undef mlx_imag-#undef mlx_inner-#undef mlx_isclose-#undef mlx_isfinite-#undef mlx_isinf-#undef mlx_isnan-#undef mlx_isneginf-#undef mlx_isposinf-#undef mlx_kron-#undef mlx_left_shift-#undef mlx_less-#undef mlx_less_equal-#undef mlx_linspace-#undef mlx_log-#undef mlx_log10-#undef mlx_log1p-#undef mlx_log2-#undef mlx_logaddexp-#undef mlx_logcumsumexp-#undef mlx_logical_and-#undef mlx_logical_not-#undef mlx_logical_or-#undef mlx_logsumexp_axes-#undef mlx_logsumexp_axis-#undef mlx_logsumexp-#undef mlx_masked_scatter-#undef mlx_matmul-#undef mlx_max_axes-#undef mlx_max_axis-#undef mlx_max-#undef mlx_maximum-#undef mlx_mean_axes-#undef mlx_mean_axis-#undef mlx_mean-#undef mlx_median-#undef mlx_meshgrid-#undef mlx_min_axes-#undef mlx_min_axis-#undef mlx_min-#undef mlx_minimum-#undef mlx_moveaxis-#undef mlx_multiply-#undef mlx_nan_to_num-#undef mlx_negative-#undef mlx_not_equal-#undef mlx_number_of_elements-#undef mlx_ones-#undef mlx_ones_like-#undef mlx_outer-#undef mlx_pad-#undef mlx_pad_symmetric-#undef mlx_partition_axis-#undef mlx_partition-#undef mlx_power-#undef mlx_prod_axes-#undef mlx_prod_axis-#undef mlx_prod-#undef mlx_put_along_axis-#undef mlx_qqmm-#undef mlx_quantize-#undef mlx_quantized_matmul-#undef mlx_radians-#undef mlx_real-#undef mlx_reciprocal-#undef mlx_remainder-#undef mlx_repeat_axis-#undef mlx_repeat-#undef mlx_reshape-#undef mlx_right_shift-#undef mlx_roll_axis-#undef mlx_roll_axes-#undef mlx_roll-#undef mlx_round-#undef mlx_rsqrt-#undef mlx_scatter-#undef mlx_scatter_single-#undef mlx_scatter_add-#undef mlx_scatter_add_single-#undef mlx_scatter_add_axis-#undef mlx_scatter_max-#undef mlx_scatter_max_single-#undef mlx_scatter_min-#undef mlx_scatter_min_single-#undef mlx_scatter_prod-#undef mlx_scatter_prod_single-#undef mlx_segmented_mm-#undef mlx_sigmoid-#undef mlx_sign-#undef mlx_sin-#undef mlx_sinh-#undef mlx_slice-#undef mlx_slice_dynamic-#undef mlx_slice_update-#undef mlx_slice_update_dynamic-#undef mlx_slice_update_add-#undef mlx_slice_update_max-#undef mlx_slice_update_min-#undef mlx_slice_update_prod-#undef mlx_softmax_axes-#undef mlx_softmax_axis-#undef mlx_softmax-#undef mlx_sort_axis-#undef mlx_sort-#undef mlx_split-#undef mlx_split_sections-#undef mlx_sqrt-#undef mlx_square-#undef mlx_squeeze_axes-#undef mlx_squeeze_axis-#undef mlx_squeeze-#undef mlx_stack_axis-#undef mlx_stack-#undef mlx_std_axes-#undef mlx_std_axis-#undef mlx_std-#undef mlx_stop_gradient-#undef mlx_subtract-#undef mlx_sum_axes-#undef mlx_sum_axis-#undef mlx_sum-#undef mlx_swapaxes-#undef mlx_take_axis-#undef mlx_take-#undef mlx_take_along_axis-#undef mlx_tan-#undef mlx_tanh-#undef mlx_tensordot-#undef mlx_tensordot_axis-#undef mlx_tile-#undef mlx_to_fp8-#undef mlx_topk_axis-#undef mlx_topk-#undef mlx_trace-#undef mlx_transpose_axes-#undef mlx_transpose-#undef mlx_tri-#undef mlx_tril-#undef mlx_triu-#undef mlx_unflatten-#undef mlx_var_axes-#undef mlx_var_axis-#undef mlx_var-#undef mlx_view-#undef mlx_where-#undef mlx_zeros-#undef mlx_zeros_like-#undef mlx_random_bernoulli-#undef mlx_random_bits-#undef mlx_random_categorical_shape-#undef mlx_random_categorical_num_samples-#undef mlx_random_categorical-#undef mlx_random_gumbel-#undef mlx_random_key-#undef mlx_random_laplace-#undef mlx_random_multivariate_normal-#undef mlx_random_normal_broadcast-#undef mlx_random_normal-#undef mlx_random_permutation-#undef mlx_random_permutation_arange-#undef mlx_random_randint-#undef mlx_random_seed-#undef mlx_random_split_num-#undef mlx_random_split-#undef mlx_random_truncated_normal-#undef mlx_random_uniform-#undef mlx_stream_new-#undef mlx_stream_new_device-#undef mlx_stream_set-#undef mlx_stream_free-#undef mlx_stream_tostring-#undef mlx_stream_equal-#undef mlx_stream_get_device-#undef mlx_stream_get_index-#undef mlx_synchronize-#undef mlx_get_default_stream-#undef mlx_set_default_stream-#undef mlx_default_cpu_stream_new-#undef mlx_default_gpu_stream_new-#undef mlx_string_new-#undef mlx_string_new_data-#undef mlx_string_set-#undef mlx_string_data-#undef mlx_string_free-#undef mlx_async_eval-#undef mlx_checkpoint-#undef mlx_custom_function-#undef mlx_custom_vjp-#undef mlx_eval-#undef mlx_jvp-#undef mlx_value_and_grad-#undef mlx_vjp-#undef mlx_detail_vmap_replace-#undef mlx_detail_vmap_trace-#undef mlx_vector_array_new-#undef mlx_vector_array_set-#undef mlx_vector_array_free-#undef mlx_vector_array_new_data-#undef mlx_vector_array_new_value-#undef mlx_vector_array_set_data-#undef mlx_vector_array_set_value-#undef mlx_vector_array_append_data-#undef mlx_vector_array_append_value-#undef mlx_vector_array_size-#undef mlx_vector_array_get-#undef mlx_vector_vector_array_new-#undef mlx_vector_vector_array_set-#undef mlx_vector_vector_array_free-#undef mlx_vector_vector_array_new_data-#undef mlx_vector_vector_array_new_value-#undef mlx_vector_vector_array_set_data-#undef mlx_vector_vector_array_set_value-#undef mlx_vector_vector_array_append_data-#undef mlx_vector_vector_array_append_value-#undef mlx_vector_vector_array_size-#undef mlx_vector_vector_array_get-#undef mlx_vector_int_new-#undef mlx_vector_int_set-#undef mlx_vector_int_free-#undef mlx_vector_int_new_data-#undef mlx_vector_int_new_value-#undef mlx_vector_int_set_data-#undef mlx_vector_int_set_value-#undef mlx_vector_int_append_data-#undef mlx_vector_int_append_value-#undef mlx_vector_int_size-#undef mlx_vector_int_get-#undef mlx_vector_string_new-#undef mlx_vector_string_set-#undef mlx_vector_string_free-#undef mlx_vector_string_new_data-#undef mlx_vector_string_new_value-#undef mlx_vector_string_set_data-#undef mlx_vector_string_set_value-#undef mlx_vector_string_append_data-#undef mlx_vector_string_append_value-#undef mlx_vector_string_size-#undef mlx_vector_string_get-#undef mlx_version--// Function pointer declarations (defined in mlx.c, loaded via dlsym)-extern size_t (*mlx_dtype_size_ptr)(mlx_dtype dtype);-extern int (*mlx_array_tostring_ptr)(mlx_string* str, const mlx_array arr);-extern mlx_array (*mlx_array_new_ptr)(void);-extern int (*mlx_array_free_ptr)(mlx_array arr);-extern mlx_array (*mlx_array_new_bool_ptr)(bool val);-extern mlx_array (*mlx_array_new_int_ptr)(int val);-extern mlx_array (*mlx_array_new_float32_ptr)(float val);-extern mlx_array (*mlx_array_new_float_ptr)(float val);-extern mlx_array (*mlx_array_new_float64_ptr)(double val);-extern mlx_array (*mlx_array_new_double_ptr)(double val);-extern mlx_array (*mlx_array_new_complex_ptr)(float real_val, float imag_val);-extern mlx_array (*mlx_array_new_data_ptr)(const void* data, const int* shape, int dim, mlx_dtype dtype);-extern mlx_array (*mlx_array_new_data_managed_ptr)(void* data, const int* shape, int dim, mlx_dtype dtype, void (*dtor)(void*));-extern mlx_array (*mlx_array_new_data_managed_payload_ptr)(void* data, const int* shape, int dim, mlx_dtype dtype, void* payload, void (*dtor)(void*));-extern int (*mlx_array_set_ptr)(mlx_array* arr, const mlx_array src);-extern int (*mlx_array_set_bool_ptr)(mlx_array* arr, bool val);-extern int (*mlx_array_set_int_ptr)(mlx_array* arr, int val);-extern int (*mlx_array_set_float32_ptr)(mlx_array* arr, float val);-extern int (*mlx_array_set_float_ptr)(mlx_array* arr, float val);-extern int (*mlx_array_set_float64_ptr)(mlx_array* arr, double val);-extern int (*mlx_array_set_double_ptr)(mlx_array* arr, double val);-extern int (*mlx_array_set_complex_ptr)(mlx_array* arr, float real_val, float imag_val);-extern int (*mlx_array_set_data_ptr)(mlx_array* arr, const void* data, const int* shape, int dim, mlx_dtype dtype);-extern size_t (*mlx_array_itemsize_ptr)(const mlx_array arr);-extern size_t (*mlx_array_size_ptr)(const mlx_array arr);-extern size_t (*mlx_array_nbytes_ptr)(const mlx_array arr);-extern size_t (*mlx_array_ndim_ptr)(const mlx_array arr);-extern const int* (*mlx_array_shape_ptr)(const mlx_array arr);-extern const size_t* (*mlx_array_strides_ptr)(const mlx_array arr);-extern int (*mlx_array_dim_ptr)(const mlx_array arr, int dim);-extern mlx_dtype (*mlx_array_dtype_ptr)(const mlx_array arr);-extern int (*mlx_array_eval_ptr)(mlx_array arr);-extern int (*mlx_array_item_bool_ptr)(bool* res, const mlx_array arr);-extern int (*mlx_array_item_uint8_ptr)(uint8_t* res, const mlx_array arr);-extern int (*mlx_array_item_uint16_ptr)(uint16_t* res, const mlx_array arr);-extern int (*mlx_array_item_uint32_ptr)(uint32_t* res, const mlx_array arr);-extern int (*mlx_array_item_uint64_ptr)(uint64_t* res, const mlx_array arr);-extern int (*mlx_array_item_int8_ptr)(int8_t* res, const mlx_array arr);-extern int (*mlx_array_item_int16_ptr)(int16_t* res, const mlx_array arr);-extern int (*mlx_array_item_int32_ptr)(int32_t* res, const mlx_array arr);-extern int (*mlx_array_item_int64_ptr)(int64_t* res, const mlx_array arr);-extern int (*mlx_array_item_float32_ptr)(float* res, const mlx_array arr);-extern int (*mlx_array_item_float64_ptr)(double* res, const mlx_array arr);-extern int (*mlx_array_item_complex64_ptr)(mlx_complex64_t* res, const mlx_array arr);-#if defined(__aarch64__) || defined(_M_ARM64)-extern int (*mlx_array_item_float16_ptr)(float16_t* res, const mlx_array arr);-#endif-#if defined(__aarch64__) || defined(_M_ARM64)-extern int (*mlx_array_item_bfloat16_ptr)(bfloat16_t* res, const mlx_array arr);-#endif-extern const bool* (*mlx_array_data_bool_ptr)(const mlx_array arr);-extern const uint8_t* (*mlx_array_data_uint8_ptr)(const mlx_array arr);-extern const uint16_t* (*mlx_array_data_uint16_ptr)(const mlx_array arr);-extern const uint32_t* (*mlx_array_data_uint32_ptr)(const mlx_array arr);-extern const uint64_t* (*mlx_array_data_uint64_ptr)(const mlx_array arr);-extern const int8_t* (*mlx_array_data_int8_ptr)(const mlx_array arr);-extern const int16_t* (*mlx_array_data_int16_ptr)(const mlx_array arr);-extern const int32_t* (*mlx_array_data_int32_ptr)(const mlx_array arr);-extern const int64_t* (*mlx_array_data_int64_ptr)(const mlx_array arr);-extern const float* (*mlx_array_data_float32_ptr)(const mlx_array arr);-extern const double* (*mlx_array_data_float64_ptr)(const mlx_array arr);-extern const mlx_complex64_t* (*mlx_array_data_complex64_ptr)(const mlx_array arr);-#if defined(__aarch64__) || defined(_M_ARM64)-extern const float16_t* (*mlx_array_data_float16_ptr)(const mlx_array arr);-#endif-#if defined(__aarch64__) || defined(_M_ARM64)-extern const bfloat16_t* (*mlx_array_data_bfloat16_ptr)(const mlx_array arr);-#endif-extern int (*_mlx_array_is_available_ptr)(bool* res, const mlx_array arr);-extern int (*_mlx_array_wait_ptr)(const mlx_array arr);-extern int (*_mlx_array_is_contiguous_ptr)(bool* res, const mlx_array arr);-extern int (*_mlx_array_is_row_contiguous_ptr)(bool* res, const mlx_array arr);-extern int (*_mlx_array_is_col_contiguous_ptr)(bool* res, const mlx_array arr);-extern mlx_closure (*mlx_closure_new_ptr)(void);-extern int (*mlx_closure_free_ptr)(mlx_closure cls);-extern mlx_closure (*mlx_closure_new_func_ptr)(int (*fun)(mlx_vector_array*, const mlx_vector_array));-extern mlx_closure (*mlx_closure_new_func_payload_ptr)(int (*fun)(mlx_vector_array*, const mlx_vector_array, void*), void* payload, void (*dtor)(void*));-extern int (*mlx_closure_set_ptr)(mlx_closure* cls, const mlx_closure src);-extern int (*mlx_closure_apply_ptr)(mlx_vector_array* res, mlx_closure cls, const mlx_vector_array input);-extern mlx_closure (*mlx_closure_new_unary_ptr)(int (*fun)(mlx_array*, const mlx_array));-extern mlx_closure_kwargs (*mlx_closure_kwargs_new_ptr)(void);-extern int (*mlx_closure_kwargs_free_ptr)(mlx_closure_kwargs cls);-extern mlx_closure_kwargs (*mlx_closure_kwargs_new_func_ptr)(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_map_string_to_array));-extern mlx_closure_kwargs (*mlx_closure_kwargs_new_func_payload_ptr)(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_map_string_to_array, void*), void* payload, void (*dtor)(void*));-extern int (*mlx_closure_kwargs_set_ptr)(mlx_closure_kwargs* cls, const mlx_closure_kwargs src);-extern int (*mlx_closure_kwargs_apply_ptr)(mlx_vector_array* res, mlx_closure_kwargs cls, const mlx_vector_array input_0, const mlx_map_string_to_array input_1);-extern mlx_closure_value_and_grad (*mlx_closure_value_and_grad_new_ptr)(void);-extern int (*mlx_closure_value_and_grad_free_ptr)(mlx_closure_value_and_grad cls);-extern mlx_closure_value_and_grad (*mlx_closure_value_and_grad_new_func_ptr)(int (*fun)(mlx_vector_array*, mlx_vector_array*, const mlx_vector_array));-extern mlx_closure_value_and_grad (*mlx_closure_value_and_grad_new_func_payload_ptr)(int (*fun)( mlx_vector_array*, mlx_vector_array*, const mlx_vector_array, void*), void* payload, void (*dtor)(void*));-extern int (*mlx_closure_value_and_grad_set_ptr)(mlx_closure_value_and_grad* cls, const mlx_closure_value_and_grad src);-extern int (*mlx_closure_value_and_grad_apply_ptr)(mlx_vector_array* res_0, mlx_vector_array* res_1, mlx_closure_value_and_grad cls, const mlx_vector_array input);-extern mlx_closure_custom (*mlx_closure_custom_new_ptr)(void);-extern int (*mlx_closure_custom_free_ptr)(mlx_closure_custom cls);-extern mlx_closure_custom (*mlx_closure_custom_new_func_ptr)(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_vector_array, const mlx_vector_array));-extern mlx_closure_custom (*mlx_closure_custom_new_func_payload_ptr)(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_vector_array, const mlx_vector_array, void*), void* payload, void (*dtor)(void*));-extern int (*mlx_closure_custom_set_ptr)(mlx_closure_custom* cls, const mlx_closure_custom src);-extern int (*mlx_closure_custom_apply_ptr)(mlx_vector_array* res, mlx_closure_custom cls, const mlx_vector_array input_0, const mlx_vector_array input_1, const mlx_vector_array input_2);-extern mlx_closure_custom_jvp (*mlx_closure_custom_jvp_new_ptr)(void);-extern int (*mlx_closure_custom_jvp_free_ptr)(mlx_closure_custom_jvp cls);-extern mlx_closure_custom_jvp (*mlx_closure_custom_jvp_new_func_ptr)(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_vector_array, const int*, size_t _num));-extern mlx_closure_custom_jvp (*mlx_closure_custom_jvp_new_func_payload_ptr)(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_vector_array, const int*, size_t _num, void*), void* payload, void (*dtor)(void*));-extern int (*mlx_closure_custom_jvp_set_ptr)(mlx_closure_custom_jvp* cls, const mlx_closure_custom_jvp src);-extern int (*mlx_closure_custom_jvp_apply_ptr)(mlx_vector_array* res, mlx_closure_custom_jvp cls, const mlx_vector_array input_0, const mlx_vector_array input_1, const int* input_2, size_t input_2_num);-extern mlx_closure_custom_vmap (*mlx_closure_custom_vmap_new_ptr)(void);-extern int (*mlx_closure_custom_vmap_free_ptr)(mlx_closure_custom_vmap cls);-extern mlx_closure_custom_vmap (*mlx_closure_custom_vmap_new_func_ptr)(int (*fun)( mlx_vector_array*, mlx_vector_int*, const mlx_vector_array, const int*, size_t _num));-extern mlx_closure_custom_vmap (*mlx_closure_custom_vmap_new_func_payload_ptr)(int (*fun)( mlx_vector_array*, mlx_vector_int*, const mlx_vector_array, const int*, size_t _num, void*), void* payload, void (*dtor)(void*));-extern int (*mlx_closure_custom_vmap_set_ptr)(mlx_closure_custom_vmap* cls, const mlx_closure_custom_vmap src);-extern int (*mlx_closure_custom_vmap_apply_ptr)(mlx_vector_array* res_0, mlx_vector_int* res_1, mlx_closure_custom_vmap cls, const mlx_vector_array input_0, const int* input_1, size_t input_1_num);-extern int (*mlx_compile_ptr)(mlx_closure* res, const mlx_closure fun, bool shapeless);-extern int (*mlx_detail_compile_ptr)(mlx_closure* res, const mlx_closure fun, uintptr_t fun_id, bool shapeless, const uint64_t* constants, size_t constants_num);-extern int (*mlx_detail_compile_clear_cache_ptr)(void);-extern int (*mlx_detail_compile_erase_ptr)(uintptr_t fun_id);-extern int (*mlx_disable_compile_ptr)(void);-extern int (*mlx_enable_compile_ptr)(void);-extern int (*mlx_set_compile_mode_ptr)(mlx_compile_mode mode);-extern int (*mlx_cuda_is_available_ptr)(bool* res);-extern mlx_device (*mlx_device_new_ptr)(void);-extern mlx_device (*mlx_device_new_type_ptr)(mlx_device_type type, int index);-extern int (*mlx_device_free_ptr)(mlx_device dev);-extern int (*mlx_device_set_ptr)(mlx_device* dev, const mlx_device src);-extern int (*mlx_device_tostring_ptr)(mlx_string* str, mlx_device dev);-extern bool (*mlx_device_equal_ptr)(mlx_device lhs, mlx_device rhs);-extern int (*mlx_device_get_index_ptr)(int* index, mlx_device dev);-extern int (*mlx_device_get_type_ptr)(mlx_device_type* type, mlx_device dev);-extern int (*mlx_get_default_device_ptr)(mlx_device* dev);-extern int (*mlx_set_default_device_ptr)(mlx_device dev);-extern int (*mlx_device_is_available_ptr)(bool* avail, mlx_device dev);-extern int (*mlx_device_count_ptr)(int* count, mlx_device_type type);-extern mlx_device_info (*mlx_device_info_new_ptr)(void);-extern int (*mlx_device_info_get_ptr)(mlx_device_info* info, mlx_device dev);-extern int (*mlx_device_info_free_ptr)(mlx_device_info info);-extern int (*mlx_device_info_has_key_ptr)(bool* exists, mlx_device_info info, const char* key);-extern int (*mlx_device_info_is_string_ptr)(bool* is_string, mlx_device_info info, const char* key);-extern int (*mlx_device_info_get_string_ptr)(const char** value, mlx_device_info info, const char* key);-extern int (*mlx_device_info_get_size_ptr)(size_t* value, mlx_device_info info, const char* key);-extern int (*mlx_device_info_get_keys_ptr)(mlx_vector_string* keys, mlx_device_info info);-extern int (*mlx_distributed_all_gather_ptr)(mlx_array* res, const mlx_array x, const mlx_distributed_group group , const mlx_stream S);-extern int (*mlx_distributed_all_max_ptr)(mlx_array* res, const mlx_array x, const mlx_distributed_group group , const mlx_stream s);-extern int (*mlx_distributed_all_min_ptr)(mlx_array* res, const mlx_array x, const mlx_distributed_group group , const mlx_stream s);-extern int (*mlx_distributed_all_sum_ptr)(mlx_array* res, const mlx_array x, const mlx_distributed_group group , const mlx_stream s);-extern int (*mlx_distributed_recv_ptr)(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, int src, const mlx_distributed_group group , const mlx_stream s);-extern int (*mlx_distributed_recv_like_ptr)(mlx_array* res, const mlx_array x, int src, const mlx_distributed_group group , const mlx_stream s);-extern int (*mlx_distributed_send_ptr)(mlx_array* res, const mlx_array x, int dst, const mlx_distributed_group group , const mlx_stream s);-extern int (*mlx_distributed_sum_scatter_ptr)(mlx_array* res, const mlx_array x, const mlx_distributed_group group , const mlx_stream s);-extern mlx_distributed_group (*mlx_distributed_group_new_ptr)(void);-extern int (*mlx_distributed_group_free_ptr)(mlx_distributed_group group);-extern int (*mlx_distributed_init_ptr)(mlx_distributed_group* res, bool strict, const char* bk);-extern int (*mlx_distributed_group_rank_ptr)(mlx_distributed_group group);-extern int (*mlx_distributed_group_size_ptr)(mlx_distributed_group group);-extern int (*mlx_distributed_group_split_ptr)(mlx_distributed_group* res, mlx_distributed_group group, int color, int key);-extern bool (*mlx_distributed_is_available_ptr)(const char* bk);-extern void (*mlx_set_error_handler_ptr)(mlx_error_handler_func handler, void* data, void (*dtor)(void*));-extern void (*_mlx_error_ptr)(const char* file, const int line, const char* fmt, ...);-extern int (*mlx_export_function_ptr)(const char* file, const mlx_closure fun, const mlx_vector_array args, bool shapeless);-extern int (*mlx_export_function_kwargs_ptr)(const char* file, const mlx_closure_kwargs fun, const mlx_vector_array args, const mlx_map_string_to_array kwargs, bool shapeless);-extern mlx_function_exporter (*mlx_function_exporter_new_ptr)(const char* file, const mlx_closure fun, bool shapeless);-extern int (*mlx_function_exporter_free_ptr)(mlx_function_exporter xfunc);-extern int (*mlx_function_exporter_apply_ptr)(const mlx_function_exporter xfunc, const mlx_vector_array args);-extern int (*mlx_function_exporter_apply_kwargs_ptr)(const mlx_function_exporter xfunc, const mlx_vector_array args, const mlx_map_string_to_array kwargs);-extern mlx_imported_function (*mlx_imported_function_new_ptr)(const char* file);-extern int (*mlx_imported_function_free_ptr)(mlx_imported_function xfunc);-extern int (*mlx_imported_function_apply_ptr)(mlx_vector_array* res, const mlx_imported_function xfunc, const mlx_vector_array args);-extern int (*mlx_imported_function_apply_kwargs_ptr)(mlx_vector_array* res, const mlx_imported_function xfunc, const mlx_vector_array args, const mlx_map_string_to_array kwargs);-extern mlx_fast_cuda_kernel_config (*mlx_fast_cuda_kernel_config_new_ptr)(void);-extern void (*mlx_fast_cuda_kernel_config_free_ptr)(mlx_fast_cuda_kernel_config cls);-extern int (*mlx_fast_cuda_kernel_config_add_output_arg_ptr)(mlx_fast_cuda_kernel_config cls, const int* shape, size_t size, mlx_dtype dtype);-extern int (*mlx_fast_cuda_kernel_config_set_grid_ptr)(mlx_fast_cuda_kernel_config cls, int grid1, int grid2, int grid3);-extern int (*mlx_fast_cuda_kernel_config_set_thread_group_ptr)(mlx_fast_cuda_kernel_config cls, int thread1, int thread2, int thread3);-extern int (*mlx_fast_cuda_kernel_config_set_init_value_ptr)(mlx_fast_cuda_kernel_config cls, float value);-extern int (*mlx_fast_cuda_kernel_config_set_verbose_ptr)(mlx_fast_cuda_kernel_config cls, bool verbose);-extern int (*mlx_fast_cuda_kernel_config_add_template_arg_dtype_ptr)(mlx_fast_cuda_kernel_config cls, const char* name, mlx_dtype dtype);-extern int (*mlx_fast_cuda_kernel_config_add_template_arg_int_ptr)(mlx_fast_cuda_kernel_config cls, const char* name, int value);-extern int (*mlx_fast_cuda_kernel_config_add_template_arg_bool_ptr)(mlx_fast_cuda_kernel_config cls, const char* name, bool value);-extern mlx_fast_cuda_kernel (*mlx_fast_cuda_kernel_new_ptr)(const char* name, const mlx_vector_string input_names, const mlx_vector_string output_names, const char* source, const char* header, bool ensure_row_contiguous, int shared_memory);-extern void (*mlx_fast_cuda_kernel_free_ptr)(mlx_fast_cuda_kernel cls);-extern int (*mlx_fast_cuda_kernel_apply_ptr)(mlx_vector_array* outputs, mlx_fast_cuda_kernel cls, const mlx_vector_array inputs, const mlx_fast_cuda_kernel_config config, const mlx_stream stream);-extern int (*mlx_fast_layer_norm_ptr)(mlx_array* res, const mlx_array x, const mlx_array weight , const mlx_array bias , float eps, const mlx_stream s);-extern mlx_fast_metal_kernel_config (*mlx_fast_metal_kernel_config_new_ptr)(void);-extern void (*mlx_fast_metal_kernel_config_free_ptr)(mlx_fast_metal_kernel_config cls);-extern int (*mlx_fast_metal_kernel_config_add_output_arg_ptr)(mlx_fast_metal_kernel_config cls, const int* shape, size_t size, mlx_dtype dtype);-extern int (*mlx_fast_metal_kernel_config_set_grid_ptr)(mlx_fast_metal_kernel_config cls, int grid1, int grid2, int grid3);-extern int (*mlx_fast_metal_kernel_config_set_thread_group_ptr)(mlx_fast_metal_kernel_config cls, int thread1, int thread2, int thread3);-extern int (*mlx_fast_metal_kernel_config_set_init_value_ptr)(mlx_fast_metal_kernel_config cls, float value);-extern int (*mlx_fast_metal_kernel_config_set_verbose_ptr)(mlx_fast_metal_kernel_config cls, bool verbose);-extern int (*mlx_fast_metal_kernel_config_add_template_arg_dtype_ptr)(mlx_fast_metal_kernel_config cls, const char* name, mlx_dtype dtype);-extern int (*mlx_fast_metal_kernel_config_add_template_arg_int_ptr)(mlx_fast_metal_kernel_config cls, const char* name, int value);-extern int (*mlx_fast_metal_kernel_config_add_template_arg_bool_ptr)(mlx_fast_metal_kernel_config cls, const char* name, bool value);-extern mlx_fast_metal_kernel (*mlx_fast_metal_kernel_new_ptr)(const char* name, const mlx_vector_string input_names, const mlx_vector_string output_names, const char* source, const char* header, bool ensure_row_contiguous, bool atomic_outputs);-extern void (*mlx_fast_metal_kernel_free_ptr)(mlx_fast_metal_kernel cls);-extern int (*mlx_fast_metal_kernel_apply_ptr)(mlx_vector_array* outputs, mlx_fast_metal_kernel cls, const mlx_vector_array inputs, const mlx_fast_metal_kernel_config config, const mlx_stream stream);-extern int (*mlx_fast_rms_norm_ptr)(mlx_array* res, const mlx_array x, const mlx_array weight , float eps, const mlx_stream s);-extern int (*mlx_fast_rope_ptr)(mlx_array* res, const mlx_array x, int dims, bool traditional, mlx_optional_float base, float scale, int offset, const mlx_array freqs , const mlx_stream s);-extern int (*mlx_fast_rope_dynamic_ptr)(mlx_array* res, const mlx_array x, int dims, bool traditional, mlx_optional_float base, float scale, const mlx_array offset, const mlx_array freqs , const mlx_stream s);-extern int (*mlx_fast_scaled_dot_product_attention_ptr)(mlx_array* res, const mlx_array queries, const mlx_array keys, const mlx_array values, float scale, const char* mask_mode, const mlx_array mask_arr , const mlx_array sinks , const mlx_stream s);-extern int (*mlx_fft_fft_ptr)(mlx_array* res, const mlx_array a, int n, int axis, mlx_fft_norm norm, const mlx_stream s);-extern int (*mlx_fft_fft2_ptr)(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s);-extern int (*mlx_fft_fftfreq_ptr)(mlx_array* res, int n, double d, const mlx_stream s);-extern int (*mlx_fft_fftn_ptr)(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s);-extern int (*mlx_fft_fftshift_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const mlx_stream s);-extern int (*mlx_fft_ifft_ptr)(mlx_array* res, const mlx_array a, int n, int axis, mlx_fft_norm norm, const mlx_stream s);-extern int (*mlx_fft_ifft2_ptr)(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s);-extern int (*mlx_fft_ifftn_ptr)(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s);-extern int (*mlx_fft_ifftshift_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const mlx_stream s);-extern int (*mlx_fft_irfft_ptr)(mlx_array* res, const mlx_array a, int n, int axis, mlx_fft_norm norm, const mlx_stream s);-extern int (*mlx_fft_irfft2_ptr)(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s);-extern int (*mlx_fft_irfftn_ptr)(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s);-extern int (*mlx_fft_rfft_ptr)(mlx_array* res, const mlx_array a, int n, int axis, mlx_fft_norm norm, const mlx_stream s);-extern int (*mlx_fft_rfft2_ptr)(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s);-extern int (*mlx_fft_rfftfreq_ptr)(mlx_array* res, int n, double d, const mlx_stream s);-extern int (*mlx_fft_rfftn_ptr)(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s);-extern int (*mlx_node_namer_free_ptr)(mlx_node_namer namer);-extern int (*mlx_node_namer_set_name_ptr)(mlx_node_namer namer, const mlx_array arr, const char* name);-extern int (*mlx_node_namer_get_name_ptr)(const char** name, mlx_node_namer namer, const mlx_array arr);-extern int (*mlx_export_to_dot_ptr)(FILE* os, const mlx_node_namer namer, const mlx_vector_array outputs);-extern int (*mlx_print_graph_ptr)(FILE* os, const mlx_node_namer namer, const mlx_vector_array outputs);-extern int (*mlx_load_reader_ptr)(mlx_array* res, mlx_io_reader in_stream, const mlx_stream s);-extern int (*mlx_load_ptr)(mlx_array* res, const char* file, const mlx_stream s);-extern int (*mlx_load_gguf_ptr)(mlx_io_gguf* gguf, const char* file, const mlx_stream s);-extern int (*mlx_load_safetensors_reader_ptr)(mlx_map_string_to_array* res_0, mlx_map_string_to_string* res_1, mlx_io_reader in_stream, const mlx_stream s);-extern int (*mlx_load_safetensors_ptr)(mlx_map_string_to_array* res_0, mlx_map_string_to_string* res_1, const char* file, const mlx_stream s);-extern int (*mlx_save_writer_ptr)(mlx_io_writer out_stream, const mlx_array a);-extern int (*mlx_save_ptr)(const char* file, const mlx_array a);-extern int (*mlx_save_gguf_ptr)(const char* file, mlx_io_gguf gguf);-extern int (*mlx_save_safetensors_writer_ptr)(mlx_io_writer in_stream, const mlx_map_string_to_array param, const mlx_map_string_to_string metadata);-extern int (*mlx_save_safetensors_ptr)(const char* file, const mlx_map_string_to_array param, const mlx_map_string_to_string metadata);-extern mlx_io_reader (*mlx_io_reader_new_ptr)(void* desc, mlx_io_vtable vtable);-extern int (*mlx_io_reader_descriptor_ptr)(void** desc_, mlx_io_reader io);-extern int (*mlx_io_reader_tostring_ptr)(mlx_string* str_, mlx_io_reader io);-extern int (*mlx_io_reader_free_ptr)(mlx_io_reader io);-extern mlx_io_writer (*mlx_io_writer_new_ptr)(void* desc, mlx_io_vtable vtable);-extern int (*mlx_io_writer_descriptor_ptr)(void** desc_, mlx_io_writer io);-extern int (*mlx_io_writer_tostring_ptr)(mlx_string* str_, mlx_io_writer io);-extern int (*mlx_io_writer_free_ptr)(mlx_io_writer io);-extern mlx_io_gguf (*mlx_io_gguf_new_ptr)(void);-extern int (*mlx_io_gguf_free_ptr)(mlx_io_gguf io);-extern int (*mlx_io_gguf_get_keys_ptr)(mlx_vector_string* keys, mlx_io_gguf io);-extern int (*mlx_io_gguf_get_array_ptr)(mlx_array* arr, mlx_io_gguf io, const char* key);-extern int (*mlx_io_gguf_get_metadata_array_ptr)(mlx_array* arr, mlx_io_gguf io, const char* key);-extern int (*mlx_io_gguf_get_metadata_string_ptr)(mlx_string* str, mlx_io_gguf io, const char* key);-extern int (*mlx_io_gguf_get_metadata_vector_string_ptr)(mlx_vector_string* vstr, mlx_io_gguf io, const char* key);-extern int (*mlx_io_gguf_has_metadata_array_ptr)(bool* flag, mlx_io_gguf io, const char* key);-extern int (*mlx_io_gguf_has_metadata_string_ptr)(bool* flag, mlx_io_gguf io, const char* key);-extern int (*mlx_io_gguf_has_metadata_vector_string_ptr)(bool* flag, mlx_io_gguf io, const char* key);-extern int (*mlx_io_gguf_set_array_ptr)(mlx_io_gguf io, const char* key, const mlx_array arr);-extern int (*mlx_io_gguf_set_metadata_array_ptr)(mlx_io_gguf io, const char* key, const mlx_array marr);-extern int (*mlx_io_gguf_set_metadata_string_ptr)(mlx_io_gguf io, const char* key, const char* mstr);-extern int (*mlx_io_gguf_set_metadata_vector_string_ptr)(mlx_io_gguf io, const char* key, const mlx_vector_string mvstr);-extern int (*mlx_linalg_cholesky_ptr)(mlx_array* res, const mlx_array a, bool upper, const mlx_stream s);-extern int (*mlx_linalg_cholesky_inv_ptr)(mlx_array* res, const mlx_array a, bool upper, const mlx_stream s);-extern int (*mlx_linalg_cross_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, int axis, const mlx_stream s);-extern int (*mlx_linalg_eig_ptr)(mlx_array* res_0, mlx_array* res_1, const mlx_array a, const mlx_stream s);-extern int (*mlx_linalg_eigh_ptr)(mlx_array* res_0, mlx_array* res_1, const mlx_array a, const char* UPLO, const mlx_stream s);-extern int (*mlx_linalg_eigvals_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_linalg_eigvalsh_ptr)(mlx_array* res, const mlx_array a, const char* UPLO, const mlx_stream s);-extern int (*mlx_linalg_inv_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_linalg_lu_ptr)(mlx_vector_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_linalg_lu_factor_ptr)(mlx_array* res_0, mlx_array* res_1, const mlx_array a, const mlx_stream s);-extern int (*mlx_linalg_norm_ptr)(mlx_array* res, const mlx_array a, double ord, const int* axis , size_t axis_num, bool keepdims, const mlx_stream s);-extern int (*mlx_linalg_norm_matrix_ptr)(mlx_array* res, const mlx_array a, const char* ord, const int* axis , size_t axis_num, bool keepdims, const mlx_stream s);-extern int (*mlx_linalg_norm_l2_ptr)(mlx_array* res, const mlx_array a, const int* axis , size_t axis_num, bool keepdims, const mlx_stream s);-extern int (*mlx_linalg_pinv_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_linalg_qr_ptr)(mlx_array* res_0, mlx_array* res_1, const mlx_array a, const mlx_stream s);-extern int (*mlx_linalg_solve_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_linalg_solve_triangular_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, bool upper, const mlx_stream s);-extern int (*mlx_linalg_svd_ptr)(mlx_vector_array* res, const mlx_array a, bool compute_uv, const mlx_stream s);-extern int (*mlx_linalg_tri_inv_ptr)(mlx_array* res, const mlx_array a, bool upper, const mlx_stream s);-extern mlx_map_string_to_array (*mlx_map_string_to_array_new_ptr)(void);-extern int (*mlx_map_string_to_array_set_ptr)(mlx_map_string_to_array* map, const mlx_map_string_to_array src);-extern int (*mlx_map_string_to_array_free_ptr)(mlx_map_string_to_array map);-extern int (*mlx_map_string_to_array_insert_ptr)(mlx_map_string_to_array map, const char* key, const mlx_array value);-extern int (*mlx_map_string_to_array_get_ptr)(mlx_array* value, const mlx_map_string_to_array map, const char* key);-extern mlx_map_string_to_array_iterator (*mlx_map_string_to_array_iterator_new_ptr)(mlx_map_string_to_array map);-extern int (*mlx_map_string_to_array_iterator_free_ptr)(mlx_map_string_to_array_iterator it);-extern int (*mlx_map_string_to_array_iterator_next_ptr)(const char** key, mlx_array* value, mlx_map_string_to_array_iterator it);-extern mlx_map_string_to_string (*mlx_map_string_to_string_new_ptr)(void);-extern int (*mlx_map_string_to_string_set_ptr)(mlx_map_string_to_string* map, const mlx_map_string_to_string src);-extern int (*mlx_map_string_to_string_free_ptr)(mlx_map_string_to_string map);-extern int (*mlx_map_string_to_string_insert_ptr)(mlx_map_string_to_string map, const char* key, const char* value);-extern int (*mlx_map_string_to_string_get_ptr)(const char** value, const mlx_map_string_to_string map, const char* key);-extern mlx_map_string_to_string_iterator (*mlx_map_string_to_string_iterator_new_ptr)(mlx_map_string_to_string map);-extern int (*mlx_map_string_to_string_iterator_free_ptr)(mlx_map_string_to_string_iterator it);-extern int (*mlx_map_string_to_string_iterator_next_ptr)(const char** key, const char** value, mlx_map_string_to_string_iterator it);-extern int (*mlx_clear_cache_ptr)(void);-extern int (*mlx_get_active_memory_ptr)(size_t* res);-extern int (*mlx_get_cache_memory_ptr)(size_t* res);-extern int (*mlx_get_memory_limit_ptr)(size_t* res);-extern int (*mlx_get_peak_memory_ptr)(size_t* res);-extern int (*mlx_reset_peak_memory_ptr)(void);-extern int (*mlx_set_cache_limit_ptr)(size_t* res, size_t limit);-extern int (*mlx_set_memory_limit_ptr)(size_t* res, size_t limit);-extern int (*mlx_set_wired_limit_ptr)(size_t* res, size_t limit);-extern int (*mlx_metal_is_available_ptr)(bool* res);-extern int (*mlx_metal_start_capture_ptr)(const char* path);-extern int (*mlx_metal_stop_capture_ptr)(void);-extern int (*mlx_abs_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_add_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_addmm_ptr)(mlx_array* res, const mlx_array c, const mlx_array a, const mlx_array b, float alpha, float beta, const mlx_stream s);-extern int (*mlx_all_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s);-extern int (*mlx_all_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s);-extern int (*mlx_all_ptr)(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s);-extern int (*mlx_allclose_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, double rtol, double atol, bool equal_nan, const mlx_stream s);-extern int (*mlx_any_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s);-extern int (*mlx_any_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s);-extern int (*mlx_any_ptr)(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s);-extern int (*mlx_arange_ptr)(mlx_array* res, double start, double stop, double step, mlx_dtype dtype, const mlx_stream s);-extern int (*mlx_arccos_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_arccosh_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_arcsin_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_arcsinh_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_arctan_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_arctan2_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_arctanh_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_argmax_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s);-extern int (*mlx_argmax_ptr)(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s);-extern int (*mlx_argmin_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s);-extern int (*mlx_argmin_ptr)(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s);-extern int (*mlx_argpartition_axis_ptr)(mlx_array* res, const mlx_array a, int kth, int axis, const mlx_stream s);-extern int (*mlx_argpartition_ptr)(mlx_array* res, const mlx_array a, int kth, const mlx_stream s);-extern int (*mlx_argsort_axis_ptr)(mlx_array* res, const mlx_array a, int axis, const mlx_stream s);-extern int (*mlx_argsort_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_array_equal_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, bool equal_nan, const mlx_stream s);-extern int (*mlx_as_strided_ptr)(mlx_array* res, const mlx_array a, const int* shape, size_t shape_num, const int64_t* strides, size_t strides_num, size_t offset, const mlx_stream s);-extern int (*mlx_astype_ptr)(mlx_array* res, const mlx_array a, mlx_dtype dtype, const mlx_stream s);-extern int (*mlx_atleast_1d_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_atleast_2d_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_atleast_3d_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_bartlett_ptr)(mlx_array* res, int M, const mlx_stream s);-extern int (*mlx_bitwise_and_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_bitwise_invert_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_bitwise_or_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_bitwise_xor_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_blackman_ptr)(mlx_array* res, int M, const mlx_stream s);-extern int (*mlx_block_masked_mm_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, int block_size, const mlx_array mask_out , const mlx_array mask_lhs , const mlx_array mask_rhs , const mlx_stream s);-extern int (*mlx_broadcast_arrays_ptr)(mlx_vector_array* res, const mlx_vector_array inputs, const mlx_stream s);-extern int (*mlx_broadcast_to_ptr)(mlx_array* res, const mlx_array a, const int* shape, size_t shape_num, const mlx_stream s);-extern int (*mlx_ceil_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_clip_ptr)(mlx_array* res, const mlx_array a, const mlx_array a_min , const mlx_array a_max , const mlx_stream s);-extern int (*mlx_concatenate_axis_ptr)(mlx_array* res, const mlx_vector_array arrays, int axis, const mlx_stream s);-extern int (*mlx_concatenate_ptr)(mlx_array* res, const mlx_vector_array arrays, const mlx_stream s);-extern int (*mlx_conjugate_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_contiguous_ptr)(mlx_array* res, const mlx_array a, bool allow_col_major, const mlx_stream s);-extern int (*mlx_conv1d_ptr)(mlx_array* res, const mlx_array input, const mlx_array weight, int stride, int padding, int dilation, int groups, const mlx_stream s);-extern int (*mlx_conv2d_ptr)(mlx_array* res, const mlx_array input, const mlx_array weight, int stride_0, int stride_1, int padding_0, int padding_1, int dilation_0, int dilation_1, int groups, const mlx_stream s);-extern int (*mlx_conv3d_ptr)(mlx_array* res, const mlx_array input, const mlx_array weight, int stride_0, int stride_1, int stride_2, int padding_0, int padding_1, int padding_2, int dilation_0, int dilation_1, int dilation_2, int groups, const mlx_stream s);-extern int (*mlx_conv_general_ptr)(mlx_array* res, const mlx_array input, const mlx_array weight, const int* stride, size_t stride_num, const int* padding_lo, size_t padding_lo_num, const int* padding_hi, size_t padding_hi_num, const int* kernel_dilation, size_t kernel_dilation_num, const int* input_dilation, size_t input_dilation_num, int groups, bool flip, const mlx_stream s);-extern int (*mlx_conv_transpose1d_ptr)(mlx_array* res, const mlx_array input, const mlx_array weight, int stride, int padding, int dilation, int output_padding, int groups, const mlx_stream s);-extern int (*mlx_conv_transpose2d_ptr)(mlx_array* res, const mlx_array input, const mlx_array weight, int stride_0, int stride_1, int padding_0, int padding_1, int dilation_0, int dilation_1, int output_padding_0, int output_padding_1, int groups, const mlx_stream s);-extern int (*mlx_conv_transpose3d_ptr)(mlx_array* res, const mlx_array input, const mlx_array weight, int stride_0, int stride_1, int stride_2, int padding_0, int padding_1, int padding_2, int dilation_0, int dilation_1, int dilation_2, int output_padding_0, int output_padding_1, int output_padding_2, int groups, const mlx_stream s);-extern int (*mlx_copy_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_cos_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_cosh_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_cummax_ptr)(mlx_array* res, const mlx_array a, int axis, bool reverse, bool inclusive, const mlx_stream s);-extern int (*mlx_cummin_ptr)(mlx_array* res, const mlx_array a, int axis, bool reverse, bool inclusive, const mlx_stream s);-extern int (*mlx_cumprod_ptr)(mlx_array* res, const mlx_array a, int axis, bool reverse, bool inclusive, const mlx_stream s);-extern int (*mlx_cumsum_ptr)(mlx_array* res, const mlx_array a, int axis, bool reverse, bool inclusive, const mlx_stream s);-extern int (*mlx_degrees_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_depends_ptr)(mlx_vector_array* res, const mlx_vector_array inputs, const mlx_vector_array dependencies);-extern int (*mlx_dequantize_ptr)(mlx_array* res, const mlx_array w, const mlx_array scales, const mlx_array biases , mlx_optional_int group_size, mlx_optional_int bits, const char* mode, const mlx_array global_scale , mlx_optional_dtype dtype, const mlx_stream s);-extern int (*mlx_diag_ptr)(mlx_array* res, const mlx_array a, int k, const mlx_stream s);-extern int (*mlx_diagonal_ptr)(mlx_array* res, const mlx_array a, int offset, int axis1, int axis2, const mlx_stream s);-extern int (*mlx_divide_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_divmod_ptr)(mlx_vector_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_einsum_ptr)(mlx_array* res, const char* subscripts, const mlx_vector_array operands, const mlx_stream s);-extern int (*mlx_equal_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_erf_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_erfinv_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_exp_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_expand_dims_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const mlx_stream s);-extern int (*mlx_expand_dims_ptr)(mlx_array* res, const mlx_array a, int axis, const mlx_stream s);-extern int (*mlx_expm1_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_eye_ptr)(mlx_array* res, int n, int m, int k, mlx_dtype dtype, const mlx_stream s);-extern int (*mlx_flatten_ptr)(mlx_array* res, const mlx_array a, int start_axis, int end_axis, const mlx_stream s);-extern int (*mlx_floor_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_floor_divide_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_from_fp8_ptr)(mlx_array* res, const mlx_array x, mlx_dtype dtype, const mlx_stream s);-extern int (*mlx_full_ptr)(mlx_array* res, const int* shape, size_t shape_num, const mlx_array vals, mlx_dtype dtype, const mlx_stream s);-extern int (*mlx_full_like_ptr)(mlx_array* res, const mlx_array a, const mlx_array vals, mlx_dtype dtype, const mlx_stream s);-extern int (*mlx_gather_ptr)(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const int* axes, size_t axes_num, const int* slice_sizes, size_t slice_sizes_num, const mlx_stream s);-extern int (*mlx_gather_single_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, int axis, const int* slice_sizes, size_t slice_sizes_num, const mlx_stream s);-extern int (*mlx_gather_mm_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_array lhs_indices , const mlx_array rhs_indices , bool sorted_indices, const mlx_stream s);-extern int (*mlx_gather_qmm_ptr)(mlx_array* res, const mlx_array x, const mlx_array w, const mlx_array scales, const mlx_array biases , const mlx_array lhs_indices , const mlx_array rhs_indices , bool transpose, mlx_optional_int group_size, mlx_optional_int bits, const char* mode, bool sorted_indices, const mlx_stream s);-extern int (*mlx_greater_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_greater_equal_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_hadamard_transform_ptr)(mlx_array* res, const mlx_array a, mlx_optional_float scale, const mlx_stream s);-extern int (*mlx_hamming_ptr)(mlx_array* res, int M, const mlx_stream s);-extern int (*mlx_hanning_ptr)(mlx_array* res, int M, const mlx_stream s);-extern int (*mlx_identity_ptr)(mlx_array* res, int n, mlx_dtype dtype, const mlx_stream s);-extern int (*mlx_imag_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_inner_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_isclose_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, double rtol, double atol, bool equal_nan, const mlx_stream s);-extern int (*mlx_isfinite_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_isinf_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_isnan_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_isneginf_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_isposinf_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_kron_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_left_shift_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_less_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_less_equal_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_linspace_ptr)(mlx_array* res, double start, double stop, int num, mlx_dtype dtype, const mlx_stream s);-extern int (*mlx_log_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_log10_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_log1p_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_log2_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_logaddexp_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_logcumsumexp_ptr)(mlx_array* res, const mlx_array a, int axis, bool reverse, bool inclusive, const mlx_stream s);-extern int (*mlx_logical_and_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_logical_not_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_logical_or_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_logsumexp_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s);-extern int (*mlx_logsumexp_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s);-extern int (*mlx_logsumexp_ptr)(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s);-extern int (*mlx_masked_scatter_ptr)(mlx_array* res, const mlx_array a, const mlx_array mask, const mlx_array src, const mlx_stream s);-extern int (*mlx_matmul_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_max_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s);-extern int (*mlx_max_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s);-extern int (*mlx_max_ptr)(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s);-extern int (*mlx_maximum_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_mean_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s);-extern int (*mlx_mean_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s);-extern int (*mlx_mean_ptr)(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s);-extern int (*mlx_median_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s);-extern int (*mlx_meshgrid_ptr)(mlx_vector_array* res, const mlx_vector_array arrays, bool sparse, const char* indexing, const mlx_stream s);-extern int (*mlx_min_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s);-extern int (*mlx_min_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s);-extern int (*mlx_min_ptr)(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s);-extern int (*mlx_minimum_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_moveaxis_ptr)(mlx_array* res, const mlx_array a, int source, int destination, const mlx_stream s);-extern int (*mlx_multiply_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_nan_to_num_ptr)(mlx_array* res, const mlx_array a, float nan, mlx_optional_float posinf, mlx_optional_float neginf, const mlx_stream s);-extern int (*mlx_negative_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_not_equal_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_number_of_elements_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool inverted, mlx_dtype dtype, const mlx_stream s);-extern int (*mlx_ones_ptr)(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_stream s);-extern int (*mlx_ones_like_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_outer_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_pad_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const int* low_pad_size, size_t low_pad_size_num, const int* high_pad_size, size_t high_pad_size_num, const mlx_array pad_value, const char* mode, const mlx_stream s);-extern int (*mlx_pad_symmetric_ptr)(mlx_array* res, const mlx_array a, int pad_width, const mlx_array pad_value, const char* mode, const mlx_stream s);-extern int (*mlx_partition_axis_ptr)(mlx_array* res, const mlx_array a, int kth, int axis, const mlx_stream s);-extern int (*mlx_partition_ptr)(mlx_array* res, const mlx_array a, int kth, const mlx_stream s);-extern int (*mlx_power_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_prod_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s);-extern int (*mlx_prod_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s);-extern int (*mlx_prod_ptr)(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s);-extern int (*mlx_put_along_axis_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array values, int axis, const mlx_stream s);-extern int (*mlx_qqmm_ptr)(mlx_array* res, const mlx_array x, const mlx_array w, const mlx_array w_scales , mlx_optional_int group_size, mlx_optional_int bits, const char* mode, const mlx_array global_scale_x , const mlx_array global_scale_w , const mlx_stream s);-extern int (*mlx_quantize_ptr)(mlx_vector_array* res, const mlx_array w, mlx_optional_int group_size, mlx_optional_int bits, const char* mode, const mlx_array global_scale , const mlx_stream s);-extern int (*mlx_quantized_matmul_ptr)(mlx_array* res, const mlx_array x, const mlx_array w, const mlx_array scales, const mlx_array biases , bool transpose, mlx_optional_int group_size, mlx_optional_int bits, const char* mode, const mlx_stream s);-extern int (*mlx_radians_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_real_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_reciprocal_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_remainder_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_repeat_axis_ptr)(mlx_array* res, const mlx_array arr, int repeats, int axis, const mlx_stream s);-extern int (*mlx_repeat_ptr)(mlx_array* res, const mlx_array arr, int repeats, const mlx_stream s);-extern int (*mlx_reshape_ptr)(mlx_array* res, const mlx_array a, const int* shape, size_t shape_num, const mlx_stream s);-extern int (*mlx_right_shift_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_roll_axis_ptr)(mlx_array* res, const mlx_array a, const int* shift, size_t shift_num, int axis, const mlx_stream s);-extern int (*mlx_roll_axes_ptr)(mlx_array* res, const mlx_array a, const int* shift, size_t shift_num, const int* axes, size_t axes_num, const mlx_stream s);-extern int (*mlx_roll_ptr)(mlx_array* res, const mlx_array a, const int* shift, size_t shift_num, const mlx_stream s);-extern int (*mlx_round_ptr)(mlx_array* res, const mlx_array a, int decimals, const mlx_stream s);-extern int (*mlx_rsqrt_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_scatter_ptr)(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const mlx_array updates, const int* axes, size_t axes_num, const mlx_stream s);-extern int (*mlx_scatter_single_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array updates, int axis, const mlx_stream s);-extern int (*mlx_scatter_add_ptr)(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const mlx_array updates, const int* axes, size_t axes_num, const mlx_stream s);-extern int (*mlx_scatter_add_single_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array updates, int axis, const mlx_stream s);-extern int (*mlx_scatter_add_axis_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array values, int axis, const mlx_stream s);-extern int (*mlx_scatter_max_ptr)(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const mlx_array updates, const int* axes, size_t axes_num, const mlx_stream s);-extern int (*mlx_scatter_max_single_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array updates, int axis, const mlx_stream s);-extern int (*mlx_scatter_min_ptr)(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const mlx_array updates, const int* axes, size_t axes_num, const mlx_stream s);-extern int (*mlx_scatter_min_single_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array updates, int axis, const mlx_stream s);-extern int (*mlx_scatter_prod_ptr)(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const mlx_array updates, const int* axes, size_t axes_num, const mlx_stream s);-extern int (*mlx_scatter_prod_single_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array updates, int axis, const mlx_stream s);-extern int (*mlx_segmented_mm_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_array segments, const mlx_stream s);-extern int (*mlx_sigmoid_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_sign_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_sin_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_sinh_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_slice_ptr)(mlx_array* res, const mlx_array a, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s);-extern int (*mlx_slice_dynamic_ptr)(mlx_array* res, const mlx_array a, const mlx_array start, const int* axes, size_t axes_num, const int* slice_size, size_t slice_size_num, const mlx_stream s);-extern int (*mlx_slice_update_ptr)(mlx_array* res, const mlx_array src, const mlx_array update, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s);-extern int (*mlx_slice_update_dynamic_ptr)(mlx_array* res, const mlx_array src, const mlx_array update, const mlx_array start, const int* axes, size_t axes_num, const mlx_stream s);-extern int (*mlx_slice_update_add_ptr)(mlx_array* res, const mlx_array src, const mlx_array update, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s);-extern int (*mlx_slice_update_max_ptr)(mlx_array* res, const mlx_array src, const mlx_array update, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s);-extern int (*mlx_slice_update_min_ptr)(mlx_array* res, const mlx_array src, const mlx_array update, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s);-extern int (*mlx_slice_update_prod_ptr)(mlx_array* res, const mlx_array src, const mlx_array update, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s);-extern int (*mlx_softmax_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool precise, const mlx_stream s);-extern int (*mlx_softmax_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool precise, const mlx_stream s);-extern int (*mlx_softmax_ptr)(mlx_array* res, const mlx_array a, bool precise, const mlx_stream s);-extern int (*mlx_sort_axis_ptr)(mlx_array* res, const mlx_array a, int axis, const mlx_stream s);-extern int (*mlx_sort_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_split_ptr)(mlx_vector_array* res, const mlx_array a, int num_splits, int axis, const mlx_stream s);-extern int (*mlx_split_sections_ptr)(mlx_vector_array* res, const mlx_array a, const int* indices, size_t indices_num, int axis, const mlx_stream s);-extern int (*mlx_sqrt_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_square_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_squeeze_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const mlx_stream s);-extern int (*mlx_squeeze_axis_ptr)(mlx_array* res, const mlx_array a, int axis, const mlx_stream s);-extern int (*mlx_squeeze_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_stack_axis_ptr)(mlx_array* res, const mlx_vector_array arrays, int axis, const mlx_stream s);-extern int (*mlx_stack_ptr)(mlx_array* res, const mlx_vector_array arrays, const mlx_stream s);-extern int (*mlx_std_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, int ddof, const mlx_stream s);-extern int (*mlx_std_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, int ddof, const mlx_stream s);-extern int (*mlx_std_ptr)(mlx_array* res, const mlx_array a, bool keepdims, int ddof, const mlx_stream s);-extern int (*mlx_stop_gradient_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_subtract_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);-extern int (*mlx_sum_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s);-extern int (*mlx_sum_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s);-extern int (*mlx_sum_ptr)(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s);-extern int (*mlx_swapaxes_ptr)(mlx_array* res, const mlx_array a, int axis1, int axis2, const mlx_stream s);-extern int (*mlx_take_axis_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, int axis, const mlx_stream s);-extern int (*mlx_take_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_stream s);-extern int (*mlx_take_along_axis_ptr)(mlx_array* res, const mlx_array a, const mlx_array indices, int axis, const mlx_stream s);-extern int (*mlx_tan_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_tanh_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_tensordot_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, const int* axes_a, size_t axes_a_num, const int* axes_b, size_t axes_b_num, const mlx_stream s);-extern int (*mlx_tensordot_axis_ptr)(mlx_array* res, const mlx_array a, const mlx_array b, int axis, const mlx_stream s);-extern int (*mlx_tile_ptr)(mlx_array* res, const mlx_array arr, const int* reps, size_t reps_num, const mlx_stream s);-extern int (*mlx_to_fp8_ptr)(mlx_array* res, const mlx_array x, const mlx_stream s);-extern int (*mlx_topk_axis_ptr)(mlx_array* res, const mlx_array a, int k, int axis, const mlx_stream s);-extern int (*mlx_topk_ptr)(mlx_array* res, const mlx_array a, int k, const mlx_stream s);-extern int (*mlx_trace_ptr)(mlx_array* res, const mlx_array a, int offset, int axis1, int axis2, mlx_dtype dtype, const mlx_stream s);-extern int (*mlx_transpose_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const mlx_stream s);-extern int (*mlx_transpose_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_tri_ptr)(mlx_array* res, int n, int m, int k, mlx_dtype type, const mlx_stream s);-extern int (*mlx_tril_ptr)(mlx_array* res, const mlx_array x, int k, const mlx_stream s);-extern int (*mlx_triu_ptr)(mlx_array* res, const mlx_array x, int k, const mlx_stream s);-extern int (*mlx_unflatten_ptr)(mlx_array* res, const mlx_array a, int axis, const int* shape, size_t shape_num, const mlx_stream s);-extern int (*mlx_var_axes_ptr)(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, int ddof, const mlx_stream s);-extern int (*mlx_var_axis_ptr)(mlx_array* res, const mlx_array a, int axis, bool keepdims, int ddof, const mlx_stream s);-extern int (*mlx_var_ptr)(mlx_array* res, const mlx_array a, bool keepdims, int ddof, const mlx_stream s);-extern int (*mlx_view_ptr)(mlx_array* res, const mlx_array a, mlx_dtype dtype, const mlx_stream s);-extern int (*mlx_where_ptr)(mlx_array* res, const mlx_array condition, const mlx_array x, const mlx_array y, const mlx_stream s);-extern int (*mlx_zeros_ptr)(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_stream s);-extern int (*mlx_zeros_like_ptr)(mlx_array* res, const mlx_array a, const mlx_stream s);-extern int (*mlx_random_bernoulli_ptr)(mlx_array* res, const mlx_array p, const int* shape, size_t shape_num, const mlx_array key , const mlx_stream s);-extern int (*mlx_random_bits_ptr)(mlx_array* res, const int* shape, size_t shape_num, int width, const mlx_array key , const mlx_stream s);-extern int (*mlx_random_categorical_shape_ptr)(mlx_array* res, const mlx_array logits, int axis, const int* shape, size_t shape_num, const mlx_array key , const mlx_stream s);-extern int (*mlx_random_categorical_num_samples_ptr)(mlx_array* res, const mlx_array logits_, int axis, int num_samples, const mlx_array key , const mlx_stream s);-extern int (*mlx_random_categorical_ptr)(mlx_array* res, const mlx_array logits, int axis, const mlx_array key , const mlx_stream s);-extern int (*mlx_random_gumbel_ptr)(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array key , const mlx_stream s);-extern int (*mlx_random_key_ptr)(mlx_array* res, uint64_t seed);-extern int (*mlx_random_laplace_ptr)(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, float loc, float scale, const mlx_array key , const mlx_stream s);-extern int (*mlx_random_multivariate_normal_ptr)(mlx_array* res, const mlx_array mean, const mlx_array cov, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array key , const mlx_stream s);-extern int (*mlx_random_normal_broadcast_ptr)(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array loc , const mlx_array scale , const mlx_array key , const mlx_stream s);-extern int (*mlx_random_normal_ptr)(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, float loc, float scale, const mlx_array key , const mlx_stream s);-extern int (*mlx_random_permutation_ptr)(mlx_array* res, const mlx_array x, int axis, const mlx_array key , const mlx_stream s);-extern int (*mlx_random_permutation_arange_ptr)(mlx_array* res, int x, const mlx_array key , const mlx_stream s);-extern int (*mlx_random_randint_ptr)(mlx_array* res, const mlx_array low, const mlx_array high, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array key , const mlx_stream s);-extern int (*mlx_random_seed_ptr)(uint64_t seed);-extern int (*mlx_random_split_num_ptr)(mlx_array* res, const mlx_array key, int num, const mlx_stream s);-extern int (*mlx_random_split_ptr)(mlx_array* res_0, mlx_array* res_1, const mlx_array key, const mlx_stream s);-extern int (*mlx_random_truncated_normal_ptr)(mlx_array* res, const mlx_array lower, const mlx_array upper, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array key , const mlx_stream s);-extern int (*mlx_random_uniform_ptr)(mlx_array* res, const mlx_array low, const mlx_array high, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array key , const mlx_stream s);-extern mlx_stream (*mlx_stream_new_ptr)(void);-extern mlx_stream (*mlx_stream_new_device_ptr)(mlx_device dev);-extern int (*mlx_stream_set_ptr)(mlx_stream* stream, const mlx_stream src);-extern int (*mlx_stream_free_ptr)(mlx_stream stream);-extern int (*mlx_stream_tostring_ptr)(mlx_string* str, mlx_stream stream);-extern bool (*mlx_stream_equal_ptr)(mlx_stream lhs, mlx_stream rhs);-extern int (*mlx_stream_get_device_ptr)(mlx_device* dev, mlx_stream stream);-extern int (*mlx_stream_get_index_ptr)(int* index, mlx_stream stream);-extern int (*mlx_synchronize_ptr)(mlx_stream stream);-extern int (*mlx_get_default_stream_ptr)(mlx_stream* stream, mlx_device dev);-extern int (*mlx_set_default_stream_ptr)(mlx_stream stream);-extern mlx_stream (*mlx_default_cpu_stream_new_ptr)(void);-extern mlx_stream (*mlx_default_gpu_stream_new_ptr)(void);-extern mlx_string (*mlx_string_new_ptr)(void);-extern mlx_string (*mlx_string_new_data_ptr)(const char* str);-extern int (*mlx_string_set_ptr)(mlx_string* str, const mlx_string src);-extern const char* (*mlx_string_data_ptr)(mlx_string str);-extern int (*mlx_string_free_ptr)(mlx_string str);-extern int (*mlx_async_eval_ptr)(const mlx_vector_array outputs);-extern int (*mlx_checkpoint_ptr)(mlx_closure* res, const mlx_closure fun);-extern int (*mlx_custom_function_ptr)(mlx_closure* res, const mlx_closure fun, const mlx_closure_custom fun_vjp , const mlx_closure_custom_jvp fun_jvp , const mlx_closure_custom_vmap fun_vmap);-extern int (*mlx_custom_vjp_ptr)(mlx_closure* res, const mlx_closure fun, const mlx_closure_custom fun_vjp);-extern int (*mlx_eval_ptr)(const mlx_vector_array outputs);-extern int (*mlx_jvp_ptr)(mlx_vector_array* res_0, mlx_vector_array* res_1, const mlx_closure fun, const mlx_vector_array primals, const mlx_vector_array tangents);-extern int (*mlx_value_and_grad_ptr)(mlx_closure_value_and_grad* res, const mlx_closure fun, const int* argnums, size_t argnums_num);-extern int (*mlx_vjp_ptr)(mlx_vector_array* res_0, mlx_vector_array* res_1, const mlx_closure fun, const mlx_vector_array primals, const mlx_vector_array cotangents);-extern int (*mlx_detail_vmap_replace_ptr)(mlx_vector_array* res, const mlx_vector_array inputs, const mlx_vector_array s_inputs, const mlx_vector_array s_outputs, const int* in_axes, size_t in_axes_num, const int* out_axes, size_t out_axes_num);-extern int (*mlx_detail_vmap_trace_ptr)(mlx_vector_array* res_0, mlx_vector_array* res_1, const mlx_closure fun, const mlx_vector_array inputs, const int* in_axes, size_t in_axes_num);-extern mlx_vector_array (*mlx_vector_array_new_ptr)(void);-extern int (*mlx_vector_array_set_ptr)(mlx_vector_array* vec, const mlx_vector_array src);-extern int (*mlx_vector_array_free_ptr)(mlx_vector_array vec);-extern mlx_vector_array (*mlx_vector_array_new_data_ptr)(const mlx_array* data, size_t size);-extern mlx_vector_array (*mlx_vector_array_new_value_ptr)(const mlx_array val);-extern int (*mlx_vector_array_set_data_ptr)(mlx_vector_array* vec, const mlx_array* data, size_t size);-extern int (*mlx_vector_array_set_value_ptr)(mlx_vector_array* vec, const mlx_array val);-extern int (*mlx_vector_array_append_data_ptr)(mlx_vector_array vec, const mlx_array* data, size_t size);-extern int (*mlx_vector_array_append_value_ptr)(mlx_vector_array vec, const mlx_array val);-extern size_t (*mlx_vector_array_size_ptr)(mlx_vector_array vec);-extern int (*mlx_vector_array_get_ptr)(mlx_array* res, const mlx_vector_array vec, size_t idx);-extern mlx_vector_vector_array (*mlx_vector_vector_array_new_ptr)(void);-extern int (*mlx_vector_vector_array_set_ptr)(mlx_vector_vector_array* vec, const mlx_vector_vector_array src);-extern int (*mlx_vector_vector_array_free_ptr)(mlx_vector_vector_array vec);-extern mlx_vector_vector_array (*mlx_vector_vector_array_new_data_ptr)(const mlx_vector_array* data, size_t size);-extern mlx_vector_vector_array (*mlx_vector_vector_array_new_value_ptr)(const mlx_vector_array val);-extern int (*mlx_vector_vector_array_set_data_ptr)(mlx_vector_vector_array* vec, const mlx_vector_array* data, size_t size);-extern int (*mlx_vector_vector_array_set_value_ptr)(mlx_vector_vector_array* vec, const mlx_vector_array val);-extern int (*mlx_vector_vector_array_append_data_ptr)(mlx_vector_vector_array vec, const mlx_vector_array* data, size_t size);-extern int (*mlx_vector_vector_array_append_value_ptr)(mlx_vector_vector_array vec, const mlx_vector_array val);-extern size_t (*mlx_vector_vector_array_size_ptr)(mlx_vector_vector_array vec);-extern int (*mlx_vector_vector_array_get_ptr)(mlx_vector_array* res, const mlx_vector_vector_array vec, size_t idx);-extern mlx_vector_int (*mlx_vector_int_new_ptr)(void);-extern int (*mlx_vector_int_set_ptr)(mlx_vector_int* vec, const mlx_vector_int src);-extern int (*mlx_vector_int_free_ptr)(mlx_vector_int vec);-extern mlx_vector_int (*mlx_vector_int_new_data_ptr)(int* data, size_t size);-extern mlx_vector_int (*mlx_vector_int_new_value_ptr)(int val);-extern int (*mlx_vector_int_set_data_ptr)(mlx_vector_int* vec, int* data, size_t size);-extern int (*mlx_vector_int_set_value_ptr)(mlx_vector_int* vec, int val);-extern int (*mlx_vector_int_append_data_ptr)(mlx_vector_int vec, int* data, size_t size);-extern int (*mlx_vector_int_append_value_ptr)(mlx_vector_int vec, int val);-extern size_t (*mlx_vector_int_size_ptr)(mlx_vector_int vec);-extern int (*mlx_vector_int_get_ptr)(int* res, const mlx_vector_int vec, size_t idx);-extern mlx_vector_string (*mlx_vector_string_new_ptr)(void);-extern int (*mlx_vector_string_set_ptr)(mlx_vector_string* vec, const mlx_vector_string src);-extern int (*mlx_vector_string_free_ptr)(mlx_vector_string vec);-extern mlx_vector_string (*mlx_vector_string_new_data_ptr)(const char** data, size_t size);-extern mlx_vector_string (*mlx_vector_string_new_value_ptr)(const char* val);-extern int (*mlx_vector_string_set_data_ptr)(mlx_vector_string* vec, const char** data, size_t size);-extern int (*mlx_vector_string_set_value_ptr)(mlx_vector_string* vec, const char* val);-extern int (*mlx_vector_string_append_data_ptr)(mlx_vector_string vec, const char** data, size_t size);-extern int (*mlx_vector_string_append_value_ptr)(mlx_vector_string vec, const char* val);-extern size_t (*mlx_vector_string_size_ptr)(mlx_vector_string vec);-extern int (*mlx_vector_string_get_ptr)(char** res, const mlx_vector_string vec, size_t idx);-extern int (*mlx_version_ptr)(mlx_string* str_);--// Initialize all function pointers via dlsym (defined in mlx.c)-int mlx_load_functions(void* handle);--// Wrapper function declarations that call through function pointers-// Go code calls these directly as C.mlx_* (no #define redirection needed)-size_t mlx_dtype_size(mlx_dtype dtype);--int mlx_array_tostring(mlx_string* str, const mlx_array arr);--mlx_array mlx_array_new(void);--int mlx_array_free(mlx_array arr);--mlx_array mlx_array_new_bool(bool val);--mlx_array mlx_array_new_int(int val);--mlx_array mlx_array_new_float32(float val);--mlx_array mlx_array_new_float(float val);--mlx_array mlx_array_new_float64(double val);--mlx_array mlx_array_new_double(double val);--mlx_array mlx_array_new_complex(float real_val, float imag_val);--mlx_array mlx_array_new_data(const void* data, const int* shape, int dim, mlx_dtype dtype);--mlx_array mlx_array_new_data_managed(void* data, const int* shape, int dim, mlx_dtype dtype, void (*dtor)(void*));--mlx_array mlx_array_new_data_managed_payload(void* data, const int* shape, int dim, mlx_dtype dtype, void* payload, void (*dtor)(void*));--int mlx_array_set(mlx_array* arr, const mlx_array src);--int mlx_array_set_bool(mlx_array* arr, bool val);--int mlx_array_set_int(mlx_array* arr, int val);--int mlx_array_set_float32(mlx_array* arr, float val);--int mlx_array_set_float(mlx_array* arr, float val);--int mlx_array_set_float64(mlx_array* arr, double val);--int mlx_array_set_double(mlx_array* arr, double val);--int mlx_array_set_complex(mlx_array* arr, float real_val, float imag_val);--int mlx_array_set_data(mlx_array* arr, const void* data, const int* shape, int dim, mlx_dtype dtype);--size_t mlx_array_itemsize(const mlx_array arr);--size_t mlx_array_size(const mlx_array arr);--size_t mlx_array_nbytes(const mlx_array arr);--size_t mlx_array_ndim(const mlx_array arr);--const int* mlx_array_shape(const mlx_array arr);--const size_t* mlx_array_strides(const mlx_array arr);--int mlx_array_dim(const mlx_array arr, int dim);--mlx_dtype mlx_array_dtype(const mlx_array arr);--int mlx_array_eval(mlx_array arr);--int mlx_array_item_bool(bool* res, const mlx_array arr);--int mlx_array_item_uint8(uint8_t* res, const mlx_array arr);--int mlx_array_item_uint16(uint16_t* res, const mlx_array arr);--int mlx_array_item_uint32(uint32_t* res, const mlx_array arr);--int mlx_array_item_uint64(uint64_t* res, const mlx_array arr);--int mlx_array_item_int8(int8_t* res, const mlx_array arr);--int mlx_array_item_int16(int16_t* res, const mlx_array arr);--int mlx_array_item_int32(int32_t* res, const mlx_array arr);--int mlx_array_item_int64(int64_t* res, const mlx_array arr);--int mlx_array_item_float32(float* res, const mlx_array arr);--int mlx_array_item_float64(double* res, const mlx_array arr);--int mlx_array_item_complex64(mlx_complex64_t* res, const mlx_array arr);--#if defined(__aarch64__) || defined(_M_ARM64)-int mlx_array_item_float16(float16_t* res, const mlx_array arr);-#endif--#if defined(__aarch64__) || defined(_M_ARM64)-int mlx_array_item_bfloat16(bfloat16_t* res, const mlx_array arr);-#endif--const bool* mlx_array_data_bool(const mlx_array arr);--const uint8_t* mlx_array_data_uint8(const mlx_array arr);--const uint16_t* mlx_array_data_uint16(const mlx_array arr);--const uint32_t* mlx_array_data_uint32(const mlx_array arr);--const uint64_t* mlx_array_data_uint64(const mlx_array arr);--const int8_t* mlx_array_data_int8(const mlx_array arr);--const int16_t* mlx_array_data_int16(const mlx_array arr);--const int32_t* mlx_array_data_int32(const mlx_array arr);--const int64_t* mlx_array_data_int64(const mlx_array arr);--const float* mlx_array_data_float32(const mlx_array arr);--const double* mlx_array_data_float64(const mlx_array arr);--const mlx_complex64_t* mlx_array_data_complex64(const mlx_array arr);--#if defined(__aarch64__) || defined(_M_ARM64)-const float16_t* mlx_array_data_float16(const mlx_array arr);-#endif--#if defined(__aarch64__) || defined(_M_ARM64)-const bfloat16_t* mlx_array_data_bfloat16(const mlx_array arr);-#endif--int _mlx_array_is_available(bool* res, const mlx_array arr);--int _mlx_array_wait(const mlx_array arr);--int _mlx_array_is_contiguous(bool* res, const mlx_array arr);--int _mlx_array_is_row_contiguous(bool* res, const mlx_array arr);--int _mlx_array_is_col_contiguous(bool* res, const mlx_array arr);--mlx_closure mlx_closure_new(void);--int mlx_closure_free(mlx_closure cls);--mlx_closure mlx_closure_new_func(int (*fun)(mlx_vector_array*, const mlx_vector_array));--mlx_closure mlx_closure_new_func_payload(int (*fun)(mlx_vector_array*, const mlx_vector_array, void*), void* payload, void (*dtor)(void*));--int mlx_closure_set(mlx_closure* cls, const mlx_closure src);--int mlx_closure_apply(mlx_vector_array* res, mlx_closure cls, const mlx_vector_array input);--mlx_closure mlx_closure_new_unary(int (*fun)(mlx_array*, const mlx_array));--mlx_closure_kwargs mlx_closure_kwargs_new(void);--int mlx_closure_kwargs_free(mlx_closure_kwargs cls);--mlx_closure_kwargs mlx_closure_kwargs_new_func(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_map_string_to_array));--mlx_closure_kwargs mlx_closure_kwargs_new_func_payload(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_map_string_to_array, void*), void* payload, void (*dtor)(void*));--int mlx_closure_kwargs_set(mlx_closure_kwargs* cls, const mlx_closure_kwargs src);--int mlx_closure_kwargs_apply(mlx_vector_array* res, mlx_closure_kwargs cls, const mlx_vector_array input_0, const mlx_map_string_to_array input_1);--mlx_closure_value_and_grad mlx_closure_value_and_grad_new(void);--int mlx_closure_value_and_grad_free(mlx_closure_value_and_grad cls);--mlx_closure_value_and_grad mlx_closure_value_and_grad_new_func(int (*fun)(mlx_vector_array*, mlx_vector_array*, const mlx_vector_array));--mlx_closure_value_and_grad mlx_closure_value_and_grad_new_func_payload(int (*fun)( mlx_vector_array*, mlx_vector_array*, const mlx_vector_array, void*), void* payload, void (*dtor)(void*));--int mlx_closure_value_and_grad_set(mlx_closure_value_and_grad* cls, const mlx_closure_value_and_grad src);--int mlx_closure_value_and_grad_apply(mlx_vector_array* res_0, mlx_vector_array* res_1, mlx_closure_value_and_grad cls, const mlx_vector_array input);--mlx_closure_custom mlx_closure_custom_new(void);--int mlx_closure_custom_free(mlx_closure_custom cls);--mlx_closure_custom mlx_closure_custom_new_func(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_vector_array, const mlx_vector_array));--mlx_closure_custom mlx_closure_custom_new_func_payload(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_vector_array, const mlx_vector_array, void*), void* payload, void (*dtor)(void*));--int mlx_closure_custom_set(mlx_closure_custom* cls, const mlx_closure_custom src);--int mlx_closure_custom_apply(mlx_vector_array* res, mlx_closure_custom cls, const mlx_vector_array input_0, const mlx_vector_array input_1, const mlx_vector_array input_2);--mlx_closure_custom_jvp mlx_closure_custom_jvp_new(void);--int mlx_closure_custom_jvp_free(mlx_closure_custom_jvp cls);--mlx_closure_custom_jvp mlx_closure_custom_jvp_new_func(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_vector_array, const int*, size_t _num));--mlx_closure_custom_jvp mlx_closure_custom_jvp_new_func_payload(int (*fun)( mlx_vector_array*, const mlx_vector_array, const mlx_vector_array, const int*, size_t _num, void*), void* payload, void (*dtor)(void*));--int mlx_closure_custom_jvp_set(mlx_closure_custom_jvp* cls, const mlx_closure_custom_jvp src);--int mlx_closure_custom_jvp_apply(mlx_vector_array* res, mlx_closure_custom_jvp cls, const mlx_vector_array input_0, const mlx_vector_array input_1, const int* input_2, size_t input_2_num);--mlx_closure_custom_vmap mlx_closure_custom_vmap_new(void);--int mlx_closure_custom_vmap_free(mlx_closure_custom_vmap cls);--mlx_closure_custom_vmap mlx_closure_custom_vmap_new_func(int (*fun)( mlx_vector_array*, mlx_vector_int*, const mlx_vector_array, const int*, size_t _num));--mlx_closure_custom_vmap mlx_closure_custom_vmap_new_func_payload(int (*fun)( mlx_vector_array*, mlx_vector_int*, const mlx_vector_array, const int*, size_t _num, void*), void* payload, void (*dtor)(void*));--int mlx_closure_custom_vmap_set(mlx_closure_custom_vmap* cls, const mlx_closure_custom_vmap src);--int mlx_closure_custom_vmap_apply(mlx_vector_array* res_0, mlx_vector_int* res_1, mlx_closure_custom_vmap cls, const mlx_vector_array input_0, const int* input_1, size_t input_1_num);--int mlx_compile(mlx_closure* res, const mlx_closure fun, bool shapeless);--int mlx_detail_compile(mlx_closure* res, const mlx_closure fun, uintptr_t fun_id, bool shapeless, const uint64_t* constants, size_t constants_num);--int mlx_detail_compile_clear_cache(void);--int mlx_detail_compile_erase(uintptr_t fun_id);--int mlx_disable_compile(void);--int mlx_enable_compile(void);--int mlx_set_compile_mode(mlx_compile_mode mode);--int mlx_cuda_is_available(bool* res);--mlx_device mlx_device_new(void);--mlx_device mlx_device_new_type(mlx_device_type type, int index);--int mlx_device_free(mlx_device dev);--int mlx_device_set(mlx_device* dev, const mlx_device src);--int mlx_device_tostring(mlx_string* str, mlx_device dev);--bool mlx_device_equal(mlx_device lhs, mlx_device rhs);--int mlx_device_get_index(int* index, mlx_device dev);--int mlx_device_get_type(mlx_device_type* type, mlx_device dev);--int mlx_get_default_device(mlx_device* dev);--int mlx_set_default_device(mlx_device dev);--int mlx_device_is_available(bool* avail, mlx_device dev);--int mlx_device_count(int* count, mlx_device_type type);--mlx_device_info mlx_device_info_new(void);--int mlx_device_info_get(mlx_device_info* info, mlx_device dev);--int mlx_device_info_free(mlx_device_info info);--int mlx_device_info_has_key(bool* exists, mlx_device_info info, const char* key);--int mlx_device_info_is_string(bool* is_string, mlx_device_info info, const char* key);--int mlx_device_info_get_string(const char** value, mlx_device_info info, const char* key);--int mlx_device_info_get_size(size_t* value, mlx_device_info info, const char* key);--int mlx_device_info_get_keys(mlx_vector_string* keys, mlx_device_info info);--int mlx_distributed_all_gather(mlx_array* res, const mlx_array x, const mlx_distributed_group group , const mlx_stream S);--int mlx_distributed_all_max(mlx_array* res, const mlx_array x, const mlx_distributed_group group , const mlx_stream s);--int mlx_distributed_all_min(mlx_array* res, const mlx_array x, const mlx_distributed_group group , const mlx_stream s);--int mlx_distributed_all_sum(mlx_array* res, const mlx_array x, const mlx_distributed_group group , const mlx_stream s);--int mlx_distributed_recv(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, int src, const mlx_distributed_group group , const mlx_stream s);--int mlx_distributed_recv_like(mlx_array* res, const mlx_array x, int src, const mlx_distributed_group group , const mlx_stream s);--int mlx_distributed_send(mlx_array* res, const mlx_array x, int dst, const mlx_distributed_group group , const mlx_stream s);--int mlx_distributed_sum_scatter(mlx_array* res, const mlx_array x, const mlx_distributed_group group , const mlx_stream s);--mlx_distributed_group mlx_distributed_group_new(void);--int mlx_distributed_group_free(mlx_distributed_group group);--int mlx_distributed_init(mlx_distributed_group* res, bool strict, const char* bk);--int mlx_distributed_group_rank(mlx_distributed_group group);--int mlx_distributed_group_size(mlx_distributed_group group);--int mlx_distributed_group_split(mlx_distributed_group* res, mlx_distributed_group group, int color, int key);--bool mlx_distributed_is_available(const char* bk);--void mlx_set_error_handler(mlx_error_handler_func handler, void* data, void (*dtor)(void*));--void _mlx_error(const char* file, const int line, const char* fmt, ...);--int mlx_export_function(const char* file, const mlx_closure fun, const mlx_vector_array args, bool shapeless);--int mlx_export_function_kwargs(const char* file, const mlx_closure_kwargs fun, const mlx_vector_array args, const mlx_map_string_to_array kwargs, bool shapeless);--mlx_function_exporter mlx_function_exporter_new(const char* file, const mlx_closure fun, bool shapeless);--int mlx_function_exporter_free(mlx_function_exporter xfunc);--int mlx_function_exporter_apply(const mlx_function_exporter xfunc, const mlx_vector_array args);--int mlx_function_exporter_apply_kwargs(const mlx_function_exporter xfunc, const mlx_vector_array args, const mlx_map_string_to_array kwargs);--mlx_imported_function mlx_imported_function_new(const char* file);--int mlx_imported_function_free(mlx_imported_function xfunc);--int mlx_imported_function_apply(mlx_vector_array* res, const mlx_imported_function xfunc, const mlx_vector_array args);--int mlx_imported_function_apply_kwargs(mlx_vector_array* res, const mlx_imported_function xfunc, const mlx_vector_array args, const mlx_map_string_to_array kwargs);--mlx_fast_cuda_kernel_config mlx_fast_cuda_kernel_config_new(void);--void mlx_fast_cuda_kernel_config_free(mlx_fast_cuda_kernel_config cls);--int mlx_fast_cuda_kernel_config_add_output_arg(mlx_fast_cuda_kernel_config cls, const int* shape, size_t size, mlx_dtype dtype);--int mlx_fast_cuda_kernel_config_set_grid(mlx_fast_cuda_kernel_config cls, int grid1, int grid2, int grid3);--int mlx_fast_cuda_kernel_config_set_thread_group(mlx_fast_cuda_kernel_config cls, int thread1, int thread2, int thread3);--int mlx_fast_cuda_kernel_config_set_init_value(mlx_fast_cuda_kernel_config cls, float value);--int mlx_fast_cuda_kernel_config_set_verbose(mlx_fast_cuda_kernel_config cls, bool verbose);--int mlx_fast_cuda_kernel_config_add_template_arg_dtype(mlx_fast_cuda_kernel_config cls, const char* name, mlx_dtype dtype);--int mlx_fast_cuda_kernel_config_add_template_arg_int(mlx_fast_cuda_kernel_config cls, const char* name, int value);--int mlx_fast_cuda_kernel_config_add_template_arg_bool(mlx_fast_cuda_kernel_config cls, const char* name, bool value);--mlx_fast_cuda_kernel mlx_fast_cuda_kernel_new(const char* name, const mlx_vector_string input_names, const mlx_vector_string output_names, const char* source, const char* header, bool ensure_row_contiguous, int shared_memory);--void mlx_fast_cuda_kernel_free(mlx_fast_cuda_kernel cls);--int mlx_fast_cuda_kernel_apply(mlx_vector_array* outputs, mlx_fast_cuda_kernel cls, const mlx_vector_array inputs, const mlx_fast_cuda_kernel_config config, const mlx_stream stream);--int mlx_fast_layer_norm(mlx_array* res, const mlx_array x, const mlx_array weight , const mlx_array bias , float eps, const mlx_stream s);--mlx_fast_metal_kernel_config mlx_fast_metal_kernel_config_new(void);--void mlx_fast_metal_kernel_config_free(mlx_fast_metal_kernel_config cls);--int mlx_fast_metal_kernel_config_add_output_arg(mlx_fast_metal_kernel_config cls, const int* shape, size_t size, mlx_dtype dtype);--int mlx_fast_metal_kernel_config_set_grid(mlx_fast_metal_kernel_config cls, int grid1, int grid2, int grid3);--int mlx_fast_metal_kernel_config_set_thread_group(mlx_fast_metal_kernel_config cls, int thread1, int thread2, int thread3);--int mlx_fast_metal_kernel_config_set_init_value(mlx_fast_metal_kernel_config cls, float value);--int mlx_fast_metal_kernel_config_set_verbose(mlx_fast_metal_kernel_config cls, bool verbose);--int mlx_fast_metal_kernel_config_add_template_arg_dtype(mlx_fast_metal_kernel_config cls, const char* name, mlx_dtype dtype);--int mlx_fast_metal_kernel_config_add_template_arg_int(mlx_fast_metal_kernel_config cls, const char* name, int value);--int mlx_fast_metal_kernel_config_add_template_arg_bool(mlx_fast_metal_kernel_config cls, const char* name, bool value);--mlx_fast_metal_kernel mlx_fast_metal_kernel_new(const char* name, const mlx_vector_string input_names, const mlx_vector_string output_names, const char* source, const char* header, bool ensure_row_contiguous, bool atomic_outputs);--void mlx_fast_metal_kernel_free(mlx_fast_metal_kernel cls);--int mlx_fast_metal_kernel_apply(mlx_vector_array* outputs, mlx_fast_metal_kernel cls, const mlx_vector_array inputs, const mlx_fast_metal_kernel_config config, const mlx_stream stream);--int mlx_fast_rms_norm(mlx_array* res, const mlx_array x, const mlx_array weight , float eps, const mlx_stream s);--int mlx_fast_rope(mlx_array* res, const mlx_array x, int dims, bool traditional, mlx_optional_float base, float scale, int offset, const mlx_array freqs , const mlx_stream s);--int mlx_fast_rope_dynamic(mlx_array* res, const mlx_array x, int dims, bool traditional, mlx_optional_float base, float scale, const mlx_array offset, const mlx_array freqs , const mlx_stream s);--int mlx_fast_scaled_dot_product_attention(mlx_array* res, const mlx_array queries, const mlx_array keys, const mlx_array values, float scale, const char* mask_mode, const mlx_array mask_arr , const mlx_array sinks , const mlx_stream s);--int mlx_fft_fft(mlx_array* res, const mlx_array a, int n, int axis, mlx_fft_norm norm, const mlx_stream s);--int mlx_fft_fft2(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s);--int mlx_fft_fftfreq(mlx_array* res, int n, double d, const mlx_stream s);--int mlx_fft_fftn(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s);--int mlx_fft_fftshift(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const mlx_stream s);--int mlx_fft_ifft(mlx_array* res, const mlx_array a, int n, int axis, mlx_fft_norm norm, const mlx_stream s);--int mlx_fft_ifft2(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s);--int mlx_fft_ifftn(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s);--int mlx_fft_ifftshift(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const mlx_stream s);--int mlx_fft_irfft(mlx_array* res, const mlx_array a, int n, int axis, mlx_fft_norm norm, const mlx_stream s);--int mlx_fft_irfft2(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s);--int mlx_fft_irfftn(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s);--int mlx_fft_rfft(mlx_array* res, const mlx_array a, int n, int axis, mlx_fft_norm norm, const mlx_stream s);--int mlx_fft_rfft2(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s);--int mlx_fft_rfftfreq(mlx_array* res, int n, double d, const mlx_stream s);--int mlx_fft_rfftn(mlx_array* res, const mlx_array a, const int* n, size_t n_num, const int* axes, size_t axes_num, mlx_fft_norm norm, const mlx_stream s);--int mlx_node_namer_free(mlx_node_namer namer);--int mlx_node_namer_set_name(mlx_node_namer namer, const mlx_array arr, const char* name);--int mlx_node_namer_get_name(const char** name, mlx_node_namer namer, const mlx_array arr);--int mlx_export_to_dot(FILE* os, const mlx_node_namer namer, const mlx_vector_array outputs);--int mlx_print_graph(FILE* os, const mlx_node_namer namer, const mlx_vector_array outputs);--int mlx_load_reader(mlx_array* res, mlx_io_reader in_stream, const mlx_stream s);--int mlx_load(mlx_array* res, const char* file, const mlx_stream s);--int mlx_load_gguf(mlx_io_gguf* gguf, const char* file, const mlx_stream s);--int mlx_load_safetensors_reader(mlx_map_string_to_array* res_0, mlx_map_string_to_string* res_1, mlx_io_reader in_stream, const mlx_stream s);--int mlx_load_safetensors(mlx_map_string_to_array* res_0, mlx_map_string_to_string* res_1, const char* file, const mlx_stream s);--int mlx_save_writer(mlx_io_writer out_stream, const mlx_array a);--int mlx_save(const char* file, const mlx_array a);--int mlx_save_gguf(const char* file, mlx_io_gguf gguf);--int mlx_save_safetensors_writer(mlx_io_writer in_stream, const mlx_map_string_to_array param, const mlx_map_string_to_string metadata);--int mlx_save_safetensors(const char* file, const mlx_map_string_to_array param, const mlx_map_string_to_string metadata);--mlx_io_reader mlx_io_reader_new(void* desc, mlx_io_vtable vtable);--int mlx_io_reader_descriptor(void** desc_, mlx_io_reader io);--int mlx_io_reader_tostring(mlx_string* str_, mlx_io_reader io);--int mlx_io_reader_free(mlx_io_reader io);--mlx_io_writer mlx_io_writer_new(void* desc, mlx_io_vtable vtable);--int mlx_io_writer_descriptor(void** desc_, mlx_io_writer io);--int mlx_io_writer_tostring(mlx_string* str_, mlx_io_writer io);--int mlx_io_writer_free(mlx_io_writer io);--mlx_io_gguf mlx_io_gguf_new(void);--int mlx_io_gguf_free(mlx_io_gguf io);--int mlx_io_gguf_get_keys(mlx_vector_string* keys, mlx_io_gguf io);--int mlx_io_gguf_get_array(mlx_array* arr, mlx_io_gguf io, const char* key);--int mlx_io_gguf_get_metadata_array(mlx_array* arr, mlx_io_gguf io, const char* key);--int mlx_io_gguf_get_metadata_string(mlx_string* str, mlx_io_gguf io, const char* key);--int mlx_io_gguf_get_metadata_vector_string(mlx_vector_string* vstr, mlx_io_gguf io, const char* key);--int mlx_io_gguf_has_metadata_array(bool* flag, mlx_io_gguf io, const char* key);--int mlx_io_gguf_has_metadata_string(bool* flag, mlx_io_gguf io, const char* key);--int mlx_io_gguf_has_metadata_vector_string(bool* flag, mlx_io_gguf io, const char* key);--int mlx_io_gguf_set_array(mlx_io_gguf io, const char* key, const mlx_array arr);--int mlx_io_gguf_set_metadata_array(mlx_io_gguf io, const char* key, const mlx_array marr);--int mlx_io_gguf_set_metadata_string(mlx_io_gguf io, const char* key, const char* mstr);--int mlx_io_gguf_set_metadata_vector_string(mlx_io_gguf io, const char* key, const mlx_vector_string mvstr);--int mlx_linalg_cholesky(mlx_array* res, const mlx_array a, bool upper, const mlx_stream s);--int mlx_linalg_cholesky_inv(mlx_array* res, const mlx_array a, bool upper, const mlx_stream s);--int mlx_linalg_cross(mlx_array* res, const mlx_array a, const mlx_array b, int axis, const mlx_stream s);--int mlx_linalg_eig(mlx_array* res_0, mlx_array* res_1, const mlx_array a, const mlx_stream s);--int mlx_linalg_eigh(mlx_array* res_0, mlx_array* res_1, const mlx_array a, const char* UPLO, const mlx_stream s);--int mlx_linalg_eigvals(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_linalg_eigvalsh(mlx_array* res, const mlx_array a, const char* UPLO, const mlx_stream s);--int mlx_linalg_inv(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_linalg_lu(mlx_vector_array* res, const mlx_array a, const mlx_stream s);--int mlx_linalg_lu_factor(mlx_array* res_0, mlx_array* res_1, const mlx_array a, const mlx_stream s);--int mlx_linalg_norm(mlx_array* res, const mlx_array a, double ord, const int* axis , size_t axis_num, bool keepdims, const mlx_stream s);--int mlx_linalg_norm_matrix(mlx_array* res, const mlx_array a, const char* ord, const int* axis , size_t axis_num, bool keepdims, const mlx_stream s);--int mlx_linalg_norm_l2(mlx_array* res, const mlx_array a, const int* axis , size_t axis_num, bool keepdims, const mlx_stream s);--int mlx_linalg_pinv(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_linalg_qr(mlx_array* res_0, mlx_array* res_1, const mlx_array a, const mlx_stream s);--int mlx_linalg_solve(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_linalg_solve_triangular(mlx_array* res, const mlx_array a, const mlx_array b, bool upper, const mlx_stream s);--int mlx_linalg_svd(mlx_vector_array* res, const mlx_array a, bool compute_uv, const mlx_stream s);--int mlx_linalg_tri_inv(mlx_array* res, const mlx_array a, bool upper, const mlx_stream s);--mlx_map_string_to_array mlx_map_string_to_array_new(void);--int mlx_map_string_to_array_set(mlx_map_string_to_array* map, const mlx_map_string_to_array src);--int mlx_map_string_to_array_free(mlx_map_string_to_array map);--int mlx_map_string_to_array_insert(mlx_map_string_to_array map, const char* key, const mlx_array value);--int mlx_map_string_to_array_get(mlx_array* value, const mlx_map_string_to_array map, const char* key);--mlx_map_string_to_array_iterator mlx_map_string_to_array_iterator_new(mlx_map_string_to_array map);--int mlx_map_string_to_array_iterator_free(mlx_map_string_to_array_iterator it);--int mlx_map_string_to_array_iterator_next(const char** key, mlx_array* value, mlx_map_string_to_array_iterator it);--mlx_map_string_to_string mlx_map_string_to_string_new(void);--int mlx_map_string_to_string_set(mlx_map_string_to_string* map, const mlx_map_string_to_string src);--int mlx_map_string_to_string_free(mlx_map_string_to_string map);--int mlx_map_string_to_string_insert(mlx_map_string_to_string map, const char* key, const char* value);--int mlx_map_string_to_string_get(const char** value, const mlx_map_string_to_string map, const char* key);--mlx_map_string_to_string_iterator mlx_map_string_to_string_iterator_new(mlx_map_string_to_string map);--int mlx_map_string_to_string_iterator_free(mlx_map_string_to_string_iterator it);--int mlx_map_string_to_string_iterator_next(const char** key, const char** value, mlx_map_string_to_string_iterator it);--int mlx_clear_cache(void);--int mlx_get_active_memory(size_t* res);--int mlx_get_cache_memory(size_t* res);--int mlx_get_memory_limit(size_t* res);--int mlx_get_peak_memory(size_t* res);--int mlx_reset_peak_memory(void);--int mlx_set_cache_limit(size_t* res, size_t limit);--int mlx_set_memory_limit(size_t* res, size_t limit);--int mlx_set_wired_limit(size_t* res, size_t limit);--int mlx_metal_is_available(bool* res);--int mlx_metal_start_capture(const char* path);--int mlx_metal_stop_capture(void);--int mlx_abs(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_add(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_addmm(mlx_array* res, const mlx_array c, const mlx_array a, const mlx_array b, float alpha, float beta, const mlx_stream s);--int mlx_all_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s);--int mlx_all_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s);--int mlx_all(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s);--int mlx_allclose(mlx_array* res, const mlx_array a, const mlx_array b, double rtol, double atol, bool equal_nan, const mlx_stream s);--int mlx_any_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s);--int mlx_any_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s);--int mlx_any(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s);--int mlx_arange(mlx_array* res, double start, double stop, double step, mlx_dtype dtype, const mlx_stream s);--int mlx_arccos(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_arccosh(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_arcsin(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_arcsinh(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_arctan(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_arctan2(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_arctanh(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_argmax_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s);--int mlx_argmax(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s);--int mlx_argmin_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s);--int mlx_argmin(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s);--int mlx_argpartition_axis(mlx_array* res, const mlx_array a, int kth, int axis, const mlx_stream s);--int mlx_argpartition(mlx_array* res, const mlx_array a, int kth, const mlx_stream s);--int mlx_argsort_axis(mlx_array* res, const mlx_array a, int axis, const mlx_stream s);--int mlx_argsort(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_array_equal(mlx_array* res, const mlx_array a, const mlx_array b, bool equal_nan, const mlx_stream s);--int mlx_as_strided(mlx_array* res, const mlx_array a, const int* shape, size_t shape_num, const int64_t* strides, size_t strides_num, size_t offset, const mlx_stream s);--int mlx_astype(mlx_array* res, const mlx_array a, mlx_dtype dtype, const mlx_stream s);--int mlx_atleast_1d(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_atleast_2d(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_atleast_3d(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_bartlett(mlx_array* res, int M, const mlx_stream s);--int mlx_bitwise_and(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_bitwise_invert(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_bitwise_or(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_bitwise_xor(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_blackman(mlx_array* res, int M, const mlx_stream s);--int mlx_block_masked_mm(mlx_array* res, const mlx_array a, const mlx_array b, int block_size, const mlx_array mask_out , const mlx_array mask_lhs , const mlx_array mask_rhs , const mlx_stream s);--int mlx_broadcast_arrays(mlx_vector_array* res, const mlx_vector_array inputs, const mlx_stream s);--int mlx_broadcast_to(mlx_array* res, const mlx_array a, const int* shape, size_t shape_num, const mlx_stream s);--int mlx_ceil(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_clip(mlx_array* res, const mlx_array a, const mlx_array a_min , const mlx_array a_max , const mlx_stream s);--int mlx_concatenate_axis(mlx_array* res, const mlx_vector_array arrays, int axis, const mlx_stream s);--int mlx_concatenate(mlx_array* res, const mlx_vector_array arrays, const mlx_stream s);--int mlx_conjugate(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_contiguous(mlx_array* res, const mlx_array a, bool allow_col_major, const mlx_stream s);--int mlx_conv1d(mlx_array* res, const mlx_array input, const mlx_array weight, int stride, int padding, int dilation, int groups, const mlx_stream s);--int mlx_conv2d(mlx_array* res, const mlx_array input, const mlx_array weight, int stride_0, int stride_1, int padding_0, int padding_1, int dilation_0, int dilation_1, int groups, const mlx_stream s);--int mlx_conv3d(mlx_array* res, const mlx_array input, const mlx_array weight, int stride_0, int stride_1, int stride_2, int padding_0, int padding_1, int padding_2, int dilation_0, int dilation_1, int dilation_2, int groups, const mlx_stream s);--int mlx_conv_general(mlx_array* res, const mlx_array input, const mlx_array weight, const int* stride, size_t stride_num, const int* padding_lo, size_t padding_lo_num, const int* padding_hi, size_t padding_hi_num, const int* kernel_dilation, size_t kernel_dilation_num, const int* input_dilation, size_t input_dilation_num, int groups, bool flip, const mlx_stream s);--int mlx_conv_transpose1d(mlx_array* res, const mlx_array input, const mlx_array weight, int stride, int padding, int dilation, int output_padding, int groups, const mlx_stream s);--int mlx_conv_transpose2d(mlx_array* res, const mlx_array input, const mlx_array weight, int stride_0, int stride_1, int padding_0, int padding_1, int dilation_0, int dilation_1, int output_padding_0, int output_padding_1, int groups, const mlx_stream s);--int mlx_conv_transpose3d(mlx_array* res, const mlx_array input, const mlx_array weight, int stride_0, int stride_1, int stride_2, int padding_0, int padding_1, int padding_2, int dilation_0, int dilation_1, int dilation_2, int output_padding_0, int output_padding_1, int output_padding_2, int groups, const mlx_stream s);--int mlx_copy(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_cos(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_cosh(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_cummax(mlx_array* res, const mlx_array a, int axis, bool reverse, bool inclusive, const mlx_stream s);--int mlx_cummin(mlx_array* res, const mlx_array a, int axis, bool reverse, bool inclusive, const mlx_stream s);--int mlx_cumprod(mlx_array* res, const mlx_array a, int axis, bool reverse, bool inclusive, const mlx_stream s);--int mlx_cumsum(mlx_array* res, const mlx_array a, int axis, bool reverse, bool inclusive, const mlx_stream s);--int mlx_degrees(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_depends(mlx_vector_array* res, const mlx_vector_array inputs, const mlx_vector_array dependencies);--int mlx_dequantize(mlx_array* res, const mlx_array w, const mlx_array scales, const mlx_array biases , mlx_optional_int group_size, mlx_optional_int bits, const char* mode, const mlx_array global_scale , mlx_optional_dtype dtype, const mlx_stream s);--int mlx_diag(mlx_array* res, const mlx_array a, int k, const mlx_stream s);--int mlx_diagonal(mlx_array* res, const mlx_array a, int offset, int axis1, int axis2, const mlx_stream s);--int mlx_divide(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_divmod(mlx_vector_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_einsum(mlx_array* res, const char* subscripts, const mlx_vector_array operands, const mlx_stream s);--int mlx_equal(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_erf(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_erfinv(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_exp(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_expand_dims_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const mlx_stream s);--int mlx_expand_dims(mlx_array* res, const mlx_array a, int axis, const mlx_stream s);--int mlx_expm1(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_eye(mlx_array* res, int n, int m, int k, mlx_dtype dtype, const mlx_stream s);--int mlx_flatten(mlx_array* res, const mlx_array a, int start_axis, int end_axis, const mlx_stream s);--int mlx_floor(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_floor_divide(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_from_fp8(mlx_array* res, const mlx_array x, mlx_dtype dtype, const mlx_stream s);--int mlx_full(mlx_array* res, const int* shape, size_t shape_num, const mlx_array vals, mlx_dtype dtype, const mlx_stream s);--int mlx_full_like(mlx_array* res, const mlx_array a, const mlx_array vals, mlx_dtype dtype, const mlx_stream s);--int mlx_gather(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const int* axes, size_t axes_num, const int* slice_sizes, size_t slice_sizes_num, const mlx_stream s);--int mlx_gather_single(mlx_array* res, const mlx_array a, const mlx_array indices, int axis, const int* slice_sizes, size_t slice_sizes_num, const mlx_stream s);--int mlx_gather_mm(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_array lhs_indices , const mlx_array rhs_indices , bool sorted_indices, const mlx_stream s);--int mlx_gather_qmm(mlx_array* res, const mlx_array x, const mlx_array w, const mlx_array scales, const mlx_array biases , const mlx_array lhs_indices , const mlx_array rhs_indices , bool transpose, mlx_optional_int group_size, mlx_optional_int bits, const char* mode, bool sorted_indices, const mlx_stream s);--int mlx_greater(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_greater_equal(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_hadamard_transform(mlx_array* res, const mlx_array a, mlx_optional_float scale, const mlx_stream s);--int mlx_hamming(mlx_array* res, int M, const mlx_stream s);--int mlx_hanning(mlx_array* res, int M, const mlx_stream s);--int mlx_identity(mlx_array* res, int n, mlx_dtype dtype, const mlx_stream s);--int mlx_imag(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_inner(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_isclose(mlx_array* res, const mlx_array a, const mlx_array b, double rtol, double atol, bool equal_nan, const mlx_stream s);--int mlx_isfinite(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_isinf(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_isnan(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_isneginf(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_isposinf(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_kron(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_left_shift(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_less(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_less_equal(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_linspace(mlx_array* res, double start, double stop, int num, mlx_dtype dtype, const mlx_stream s);--int mlx_log(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_log10(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_log1p(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_log2(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_logaddexp(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_logcumsumexp(mlx_array* res, const mlx_array a, int axis, bool reverse, bool inclusive, const mlx_stream s);--int mlx_logical_and(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_logical_not(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_logical_or(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_logsumexp_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s);--int mlx_logsumexp_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s);--int mlx_logsumexp(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s);--int mlx_masked_scatter(mlx_array* res, const mlx_array a, const mlx_array mask, const mlx_array src, const mlx_stream s);--int mlx_matmul(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_max_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s);--int mlx_max_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s);--int mlx_max(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s);--int mlx_maximum(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_mean_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s);--int mlx_mean_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s);--int mlx_mean(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s);--int mlx_median(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s);--int mlx_meshgrid(mlx_vector_array* res, const mlx_vector_array arrays, bool sparse, const char* indexing, const mlx_stream s);--int mlx_min_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s);--int mlx_min_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s);--int mlx_min(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s);--int mlx_minimum(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_moveaxis(mlx_array* res, const mlx_array a, int source, int destination, const mlx_stream s);--int mlx_multiply(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_nan_to_num(mlx_array* res, const mlx_array a, float nan, mlx_optional_float posinf, mlx_optional_float neginf, const mlx_stream s);--int mlx_negative(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_not_equal(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_number_of_elements(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool inverted, mlx_dtype dtype, const mlx_stream s);--int mlx_ones(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_stream s);--int mlx_ones_like(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_outer(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_pad(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const int* low_pad_size, size_t low_pad_size_num, const int* high_pad_size, size_t high_pad_size_num, const mlx_array pad_value, const char* mode, const mlx_stream s);--int mlx_pad_symmetric(mlx_array* res, const mlx_array a, int pad_width, const mlx_array pad_value, const char* mode, const mlx_stream s);--int mlx_partition_axis(mlx_array* res, const mlx_array a, int kth, int axis, const mlx_stream s);--int mlx_partition(mlx_array* res, const mlx_array a, int kth, const mlx_stream s);--int mlx_power(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_prod_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s);--int mlx_prod_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s);--int mlx_prod(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s);--int mlx_put_along_axis(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array values, int axis, const mlx_stream s);--int mlx_qqmm(mlx_array* res, const mlx_array x, const mlx_array w, const mlx_array w_scales , mlx_optional_int group_size, mlx_optional_int bits, const char* mode, const mlx_array global_scale_x , const mlx_array global_scale_w , const mlx_stream s);--int mlx_quantize(mlx_vector_array* res, const mlx_array w, mlx_optional_int group_size, mlx_optional_int bits, const char* mode, const mlx_array global_scale , const mlx_stream s);--int mlx_quantized_matmul(mlx_array* res, const mlx_array x, const mlx_array w, const mlx_array scales, const mlx_array biases , bool transpose, mlx_optional_int group_size, mlx_optional_int bits, const char* mode, const mlx_stream s);--int mlx_radians(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_real(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_reciprocal(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_remainder(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_repeat_axis(mlx_array* res, const mlx_array arr, int repeats, int axis, const mlx_stream s);--int mlx_repeat(mlx_array* res, const mlx_array arr, int repeats, const mlx_stream s);--int mlx_reshape(mlx_array* res, const mlx_array a, const int* shape, size_t shape_num, const mlx_stream s);--int mlx_right_shift(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_roll_axis(mlx_array* res, const mlx_array a, const int* shift, size_t shift_num, int axis, const mlx_stream s);--int mlx_roll_axes(mlx_array* res, const mlx_array a, const int* shift, size_t shift_num, const int* axes, size_t axes_num, const mlx_stream s);--int mlx_roll(mlx_array* res, const mlx_array a, const int* shift, size_t shift_num, const mlx_stream s);--int mlx_round(mlx_array* res, const mlx_array a, int decimals, const mlx_stream s);--int mlx_rsqrt(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_scatter(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const mlx_array updates, const int* axes, size_t axes_num, const mlx_stream s);--int mlx_scatter_single(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array updates, int axis, const mlx_stream s);--int mlx_scatter_add(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const mlx_array updates, const int* axes, size_t axes_num, const mlx_stream s);--int mlx_scatter_add_single(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array updates, int axis, const mlx_stream s);--int mlx_scatter_add_axis(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array values, int axis, const mlx_stream s);--int mlx_scatter_max(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const mlx_array updates, const int* axes, size_t axes_num, const mlx_stream s);--int mlx_scatter_max_single(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array updates, int axis, const mlx_stream s);--int mlx_scatter_min(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const mlx_array updates, const int* axes, size_t axes_num, const mlx_stream s);--int mlx_scatter_min_single(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array updates, int axis, const mlx_stream s);--int mlx_scatter_prod(mlx_array* res, const mlx_array a, const mlx_vector_array indices, const mlx_array updates, const int* axes, size_t axes_num, const mlx_stream s);--int mlx_scatter_prod_single(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_array updates, int axis, const mlx_stream s);--int mlx_segmented_mm(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_array segments, const mlx_stream s);--int mlx_sigmoid(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_sign(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_sin(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_sinh(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_slice(mlx_array* res, const mlx_array a, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s);--int mlx_slice_dynamic(mlx_array* res, const mlx_array a, const mlx_array start, const int* axes, size_t axes_num, const int* slice_size, size_t slice_size_num, const mlx_stream s);--int mlx_slice_update(mlx_array* res, const mlx_array src, const mlx_array update, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s);--int mlx_slice_update_dynamic(mlx_array* res, const mlx_array src, const mlx_array update, const mlx_array start, const int* axes, size_t axes_num, const mlx_stream s);--int mlx_slice_update_add(mlx_array* res, const mlx_array src, const mlx_array update, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s);--int mlx_slice_update_max(mlx_array* res, const mlx_array src, const mlx_array update, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s);--int mlx_slice_update_min(mlx_array* res, const mlx_array src, const mlx_array update, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s);--int mlx_slice_update_prod(mlx_array* res, const mlx_array src, const mlx_array update, const int* start, size_t start_num, const int* stop, size_t stop_num, const int* strides, size_t strides_num, const mlx_stream s);--int mlx_softmax_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool precise, const mlx_stream s);--int mlx_softmax_axis(mlx_array* res, const mlx_array a, int axis, bool precise, const mlx_stream s);--int mlx_softmax(mlx_array* res, const mlx_array a, bool precise, const mlx_stream s);--int mlx_sort_axis(mlx_array* res, const mlx_array a, int axis, const mlx_stream s);--int mlx_sort(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_split(mlx_vector_array* res, const mlx_array a, int num_splits, int axis, const mlx_stream s);--int mlx_split_sections(mlx_vector_array* res, const mlx_array a, const int* indices, size_t indices_num, int axis, const mlx_stream s);--int mlx_sqrt(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_square(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_squeeze_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const mlx_stream s);--int mlx_squeeze_axis(mlx_array* res, const mlx_array a, int axis, const mlx_stream s);--int mlx_squeeze(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_stack_axis(mlx_array* res, const mlx_vector_array arrays, int axis, const mlx_stream s);--int mlx_stack(mlx_array* res, const mlx_vector_array arrays, const mlx_stream s);--int mlx_std_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, int ddof, const mlx_stream s);--int mlx_std_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, int ddof, const mlx_stream s);--int mlx_std(mlx_array* res, const mlx_array a, bool keepdims, int ddof, const mlx_stream s);--int mlx_stop_gradient(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_subtract(mlx_array* res, const mlx_array a, const mlx_array b, const mlx_stream s);--int mlx_sum_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, const mlx_stream s);--int mlx_sum_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, const mlx_stream s);--int mlx_sum(mlx_array* res, const mlx_array a, bool keepdims, const mlx_stream s);--int mlx_swapaxes(mlx_array* res, const mlx_array a, int axis1, int axis2, const mlx_stream s);--int mlx_take_axis(mlx_array* res, const mlx_array a, const mlx_array indices, int axis, const mlx_stream s);--int mlx_take(mlx_array* res, const mlx_array a, const mlx_array indices, const mlx_stream s);--int mlx_take_along_axis(mlx_array* res, const mlx_array a, const mlx_array indices, int axis, const mlx_stream s);--int mlx_tan(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_tanh(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_tensordot(mlx_array* res, const mlx_array a, const mlx_array b, const int* axes_a, size_t axes_a_num, const int* axes_b, size_t axes_b_num, const mlx_stream s);--int mlx_tensordot_axis(mlx_array* res, const mlx_array a, const mlx_array b, int axis, const mlx_stream s);--int mlx_tile(mlx_array* res, const mlx_array arr, const int* reps, size_t reps_num, const mlx_stream s);--int mlx_to_fp8(mlx_array* res, const mlx_array x, const mlx_stream s);--int mlx_topk_axis(mlx_array* res, const mlx_array a, int k, int axis, const mlx_stream s);--int mlx_topk(mlx_array* res, const mlx_array a, int k, const mlx_stream s);--int mlx_trace(mlx_array* res, const mlx_array a, int offset, int axis1, int axis2, mlx_dtype dtype, const mlx_stream s);--int mlx_transpose_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, const mlx_stream s);--int mlx_transpose(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_tri(mlx_array* res, int n, int m, int k, mlx_dtype type, const mlx_stream s);--int mlx_tril(mlx_array* res, const mlx_array x, int k, const mlx_stream s);--int mlx_triu(mlx_array* res, const mlx_array x, int k, const mlx_stream s);--int mlx_unflatten(mlx_array* res, const mlx_array a, int axis, const int* shape, size_t shape_num, const mlx_stream s);--int mlx_var_axes(mlx_array* res, const mlx_array a, const int* axes, size_t axes_num, bool keepdims, int ddof, const mlx_stream s);--int mlx_var_axis(mlx_array* res, const mlx_array a, int axis, bool keepdims, int ddof, const mlx_stream s);--int mlx_var(mlx_array* res, const mlx_array a, bool keepdims, int ddof, const mlx_stream s);--int mlx_view(mlx_array* res, const mlx_array a, mlx_dtype dtype, const mlx_stream s);--int mlx_where(mlx_array* res, const mlx_array condition, const mlx_array x, const mlx_array y, const mlx_stream s);--int mlx_zeros(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_stream s);--int mlx_zeros_like(mlx_array* res, const mlx_array a, const mlx_stream s);--int mlx_random_bernoulli(mlx_array* res, const mlx_array p, const int* shape, size_t shape_num, const mlx_array key , const mlx_stream s);--int mlx_random_bits(mlx_array* res, const int* shape, size_t shape_num, int width, const mlx_array key , const mlx_stream s);--int mlx_random_categorical_shape(mlx_array* res, const mlx_array logits, int axis, const int* shape, size_t shape_num, const mlx_array key , const mlx_stream s);--int mlx_random_categorical_num_samples(mlx_array* res, const mlx_array logits_, int axis, int num_samples, const mlx_array key , const mlx_stream s);--int mlx_random_categorical(mlx_array* res, const mlx_array logits, int axis, const mlx_array key , const mlx_stream s);--int mlx_random_gumbel(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array key , const mlx_stream s);--int mlx_random_key(mlx_array* res, uint64_t seed);--int mlx_random_laplace(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, float loc, float scale, const mlx_array key , const mlx_stream s);--int mlx_random_multivariate_normal(mlx_array* res, const mlx_array mean, const mlx_array cov, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array key , const mlx_stream s);--int mlx_random_normal_broadcast(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array loc , const mlx_array scale , const mlx_array key , const mlx_stream s);--int mlx_random_normal(mlx_array* res, const int* shape, size_t shape_num, mlx_dtype dtype, float loc, float scale, const mlx_array key , const mlx_stream s);--int mlx_random_permutation(mlx_array* res, const mlx_array x, int axis, const mlx_array key , const mlx_stream s);--int mlx_random_permutation_arange(mlx_array* res, int x, const mlx_array key , const mlx_stream s);--int mlx_random_randint(mlx_array* res, const mlx_array low, const mlx_array high, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array key , const mlx_stream s);--int mlx_random_seed(uint64_t seed);--int mlx_random_split_num(mlx_array* res, const mlx_array key, int num, const mlx_stream s);--int mlx_random_split(mlx_array* res_0, mlx_array* res_1, const mlx_array key, const mlx_stream s);--int mlx_random_truncated_normal(mlx_array* res, const mlx_array lower, const mlx_array upper, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array key , const mlx_stream s);--int mlx_random_uniform(mlx_array* res, const mlx_array low, const mlx_array high, const int* shape, size_t shape_num, mlx_dtype dtype, const mlx_array key , const mlx_stream s);--mlx_stream mlx_stream_new(void);--mlx_stream mlx_stream_new_device(mlx_device dev);--int mlx_stream_set(mlx_stream* stream, const mlx_stream src);--int mlx_stream_free(mlx_stream stream);--int mlx_stream_tostring(mlx_string* str, mlx_stream stream);--bool mlx_stream_equal(mlx_stream lhs, mlx_stream rhs);--int mlx_stream_get_device(mlx_device* dev, mlx_stream stream);--int mlx_stream_get_index(int* index, mlx_stream stream);--int mlx_synchronize(mlx_stream stream);--int mlx_get_default_stream(mlx_stream* stream, mlx_device dev);--int mlx_set_default_stream(mlx_stream stream);--mlx_stream mlx_default_cpu_stream_new(void);--mlx_stream mlx_default_gpu_stream_new(void);--mlx_string mlx_string_new(void);--mlx_string mlx_string_new_data(const char* str);--int mlx_string_set(mlx_string* str, const mlx_string src);--const char* mlx_string_data(mlx_string str);--int mlx_string_free(mlx_string str);--int mlx_async_eval(const mlx_vector_array outputs);--int mlx_checkpoint(mlx_closure* res, const mlx_closure fun);--int mlx_custom_function(mlx_closure* res, const mlx_closure fun, const mlx_closure_custom fun_vjp , const mlx_closure_custom_jvp fun_jvp , const mlx_closure_custom_vmap fun_vmap);--int mlx_custom_vjp(mlx_closure* res, const mlx_closure fun, const mlx_closure_custom fun_vjp);--int mlx_eval(const mlx_vector_array outputs);--int mlx_jvp(mlx_vector_array* res_0, mlx_vector_array* res_1, const mlx_closure fun, const mlx_vector_array primals, const mlx_vector_array tangents);--int mlx_value_and_grad(mlx_closure_value_and_grad* res, const mlx_closure fun, const int* argnums, size_t argnums_num);--int mlx_vjp(mlx_vector_array* res_0, mlx_vector_array* res_1, const mlx_closure fun, const mlx_vector_array primals, const mlx_vector_array cotangents);--int mlx_detail_vmap_replace(mlx_vector_array* res, const mlx_vector_array inputs, const mlx_vector_array s_inputs, const mlx_vector_array s_outputs, const int* in_axes, size_t in_axes_num, const int* out_axes, size_t out_axes_num);--int mlx_detail_vmap_trace(mlx_vector_array* res_0, mlx_vector_array* res_1, const mlx_closure fun, const mlx_vector_array inputs, const int* in_axes, size_t in_axes_num);--mlx_vector_array mlx_vector_array_new(void);--int mlx_vector_array_set(mlx_vector_array* vec, const mlx_vector_array src);--int mlx_vector_array_free(mlx_vector_array vec);--mlx_vector_array mlx_vector_array_new_data(const mlx_array* data, size_t size);--mlx_vector_array mlx_vector_array_new_value(const mlx_array val);--int mlx_vector_array_set_data(mlx_vector_array* vec, const mlx_array* data, size_t size);--int mlx_vector_array_set_value(mlx_vector_array* vec, const mlx_array val);--int mlx_vector_array_append_data(mlx_vector_array vec, const mlx_array* data, size_t size);--int mlx_vector_array_append_value(mlx_vector_array vec, const mlx_array val);--size_t mlx_vector_array_size(mlx_vector_array vec);--int mlx_vector_array_get(mlx_array* res, const mlx_vector_array vec, size_t idx);--mlx_vector_vector_array mlx_vector_vector_array_new(void);--int mlx_vector_vector_array_set(mlx_vector_vector_array* vec, const mlx_vector_vector_array src);--int mlx_vector_vector_array_free(mlx_vector_vector_array vec);--mlx_vector_vector_array mlx_vector_vector_array_new_data(const mlx_vector_array* data, size_t size);--mlx_vector_vector_array mlx_vector_vector_array_new_value(const mlx_vector_array val);--int mlx_vector_vector_array_set_data(mlx_vector_vector_array* vec, const mlx_vector_array* data, size_t size);--int mlx_vector_vector_array_set_value(mlx_vector_vector_array* vec, const mlx_vector_array val);--int mlx_vector_vector_array_append_data(mlx_vector_vector_array vec, const mlx_vector_array* data, size_t size);--int mlx_vector_vector_array_append_value(mlx_vector_vector_array vec, const mlx_vector_array val);--size_t mlx_vector_vector_array_size(mlx_vector_vector_array vec);--int mlx_vector_vector_array_get(mlx_vector_array* res, const mlx_vector_vector_array vec, size_t idx);--mlx_vector_int mlx_vector_int_new(void);--int mlx_vector_int_set(mlx_vector_int* vec, const mlx_vector_int src);--int mlx_vector_int_free(mlx_vector_int vec);--mlx_vector_int mlx_vector_int_new_data(int* data, size_t size);--mlx_vector_int mlx_vector_int_new_value(int val);--int mlx_vector_int_set_data(mlx_vector_int* vec, int* data, size_t size);--int mlx_vector_int_set_value(mlx_vector_int* vec, int val);--int mlx_vector_int_append_data(mlx_vector_int vec, int* data, size_t size);--int mlx_vector_int_append_value(mlx_vector_int vec, int val);--size_t mlx_vector_int_size(mlx_vector_int vec);--int mlx_vector_int_get(int* res, const mlx_vector_int vec, size_t idx);--mlx_vector_string mlx_vector_string_new(void);--int mlx_vector_string_set(mlx_vector_string* vec, const mlx_vector_string src);--int mlx_vector_string_free(mlx_vector_string vec);--mlx_vector_string mlx_vector_string_new_data(const char** data, size_t size);--mlx_vector_string mlx_vector_string_new_value(const char* val);--int mlx_vector_string_set_data(mlx_vector_string* vec, const char** data, size_t size);--int mlx_vector_string_set_value(mlx_vector_string* vec, const char* val);--int mlx_vector_string_append_data(mlx_vector_string vec, const char** data, size_t size);--int mlx_vector_string_append_value(mlx_vector_string vec, const char* val);--size_t mlx_vector_string_size(mlx_vector_string vec);--int mlx_vector_string_get(char** res, const mlx_vector_string vec, size_t idx);--int mlx_version(mlx_string* str_);--#endif // MLX_WRAPPERS_Hdiff --git a/x/imagegen/mlx/mlx_dynamic.c b/x/imagegen/mlx/mlx_dynamic.cdeleted file mode 100644index 1281ec0e3..000000000--- a/x/imagegen/mlx/mlx_dynamic.c+++ /dev/null@@ -1,93 +0,0 @@-// mlx_dynamic.c - Dynamic loading wrapper for MLX-C library-// This file provides runtime dynamic loading of libmlxc instead of link-time binding--#include "mlx_dynamic.h"-#include <stdio.h>-#include <stdlib.h>-#include <string.h>--#ifdef _WIN32-#include <windows.h>-typedef HMODULE lib_handle_t;-static char win_error_buffer[256] = {0};-static const char* get_win_error(void) {- DWORD err = GetLastError();- snprintf(win_error_buffer, sizeof(win_error_buffer), "error code %lu", err);- return win_error_buffer;-}-#define LIB_ERROR() get_win_error()-#else-#include <dlfcn.h>-typedef void* lib_handle_t;-#define LIB_ERROR() dlerror()-#endif--static lib_handle_t mlx_handle = NULL;-static int mlx_initialized = 0;-static char mlx_error_buffer[512] = {0};--#ifdef _WIN32-// Windows: Load library from a path with dependency resolution.-// Temporarily adds the library's directory to the DLL search path-// so that dependencies (like mlx.dll) in the same directory are found.-static int try_load_win(const char* path) {- if (!path) return 0;-- // Extract directory and add to DLL search path for dependency resolution- char dir_path[MAX_PATH];- strncpy(dir_path, path, MAX_PATH - 1);- dir_path[MAX_PATH - 1] = '\0';- char* last_slash = strrchr(dir_path, '\\');- if (!last_slash) last_slash = strrchr(dir_path, '/');- if (last_slash) {- *last_slash = '\0';- SetDllDirectoryA(dir_path);- }-- mlx_handle = LoadLibraryA(path);- SetDllDirectoryA(NULL);- return mlx_handle != NULL;-}-#endif--// Try to load library from a specific path-static int try_load_lib(const char* path) {- if (!path) return 0;-#ifdef _WIN32- return try_load_win(path);-#else- mlx_handle = dlopen(path, RTLD_LAZY | RTLD_GLOBAL);- return mlx_handle != NULL;-#endif-}--// Initialize the MLX dynamic library from a specific path.-// Returns 0 on success, -1 on failure.-int mlx_dynamic_init_path(const char* path) {- if (mlx_initialized) {- return 0;- }-- if (try_load_lib(path)) {- mlx_initialized = 1;- snprintf(mlx_error_buffer, sizeof(mlx_error_buffer),- "MLX: Successfully loaded %s", path ? path : "library");- return 0;- }-- const char* err = LIB_ERROR();- snprintf(mlx_error_buffer, sizeof(mlx_error_buffer),- "MLX: Failed to load %s: %s", path ? path : "(null)", err ? err : "unknown error");- return -1;-}--// Get the last error message-const char* mlx_dynamic_error(void) {- return mlx_error_buffer;-}--// Get the library handle (for use by generated wrappers)-void* mlx_get_handle(void) {- return mlx_handle;-}-diff --git a/x/imagegen/mlx/mlx_dynamic.h b/x/imagegen/mlx/mlx_dynamic.hdeleted file mode 100644index 3f4d0fd74..000000000--- a/x/imagegen/mlx/mlx_dynamic.h+++ /dev/null@@ -1,23 +0,0 @@-// mlx_dynamic.h - Dynamic loading interface for MLX-C library-#ifndef MLX_DYNAMIC_H-#define MLX_DYNAMIC_H--#ifdef __cplusplus-extern "C" {-#endif--// Initialize the MLX dynamic library from a specific path-// Returns 0 on success, -1 on failure-int mlx_dynamic_init_path(const char* path);--// Get the last error message from dynamic loading-const char* mlx_dynamic_error(void);--// Get the library handle (for use by generated wrappers)-void* mlx_get_handle(void);--#ifdef __cplusplus-}-#endif--#endif // MLX_DYNAMIC_Hdiff --git a/x/imagegen/mlx/mlx_error_handler.c b/x/imagegen/mlx/mlx_error_handler.cdeleted file mode 100644index 56635464b..000000000--- a/x/imagegen/mlx/mlx_error_handler.c+++ /dev/null@@ -1,38 +0,0 @@-// mlx_error_handler.c - Safe error handling for MLX initialization-// Provides a non-fatal error handler for use during init(), so that-// GPU failures are captured instead of calling exit(-1).--#include "mlx_error_handler.h"-#include "mlx.h"-#include <string.h>--static char mlx_init_error_msg[1024] = {0};-static int mlx_init_error_flag = 0;--// Error handler that silently stores the error message.-// The error is surfaced on the Go side via mlxInitError / GetMLXInitError()-// only when MLX is actually needed.-static void mlx_silent_error_handler(const char* msg, void* data) {- (void)data;- strncpy(mlx_init_error_msg, msg, sizeof(mlx_init_error_msg) - 1);- mlx_init_error_msg[sizeof(mlx_init_error_msg) - 1] = '\0';- mlx_init_error_flag = 1;-}--void mlx_set_safe_init_mode(void) {- mlx_init_error_flag = 0;- mlx_init_error_msg[0] = '\0';- mlx_set_error_handler(mlx_silent_error_handler, NULL, NULL);-}--void mlx_set_default_error_mode(void) {- mlx_set_error_handler(NULL, NULL, NULL);-}--int mlx_had_init_error(void) {- return mlx_init_error_flag;-}--const char* mlx_get_init_error(void) {- return mlx_init_error_flag ? mlx_init_error_msg : NULL;-}diff --git a/x/imagegen/mlx/mlx_error_handler.h b/x/imagegen/mlx/mlx_error_handler.hdeleted file mode 100644index 851768106..000000000--- a/x/imagegen/mlx/mlx_error_handler.h+++ /dev/null@@ -1,22 +0,0 @@-// mlx_error_handler.h - Safe error handling for MLX initialization-// This replaces the default exit(-1) MLX error handler during init()-// so that GPU failures don't kill the process.--#ifndef MLX_ERROR_HANDLER_H-#define MLX_ERROR_HANDLER_H--// Enter safe mode before any MLX compute calls during init().-// Replaces the default exit(-1) handler with one that silently stores errors.-void mlx_set_safe_init_mode(void);--// Restore the default MLX error handler (exit on error).-// Call from runner entry points after confirming MLX is available.-void mlx_set_default_error_mode(void);--// Check whether an error occurred while in safe init mode.-int mlx_had_init_error(void);--// Get the error message from the last init error, or NULL if none.-const char* mlx_get_init_error(void);--#endif // MLX_ERROR_HANDLER_Hdiff --git a/x/imagegen/mlx/mlx_test.go b/x/imagegen/mlx/mlx_test.godeleted file mode 100644index 06855e416..000000000--- a/x/imagegen/mlx/mlx_test.go+++ /dev/null@@ -1,1206 +0,0 @@-package mlx--import (- "fmt"- "os"- "path/filepath"- "runtime"- "testing"-)--// TestMain initializes MLX before running tests.-// If MLX libraries are not available, tests are skipped.-func TestMain(m *testing.M) {- // Change to repo root so ./build/lib/ollama/ path works- _, thisFile, _, _ := runtime.Caller(0)- repoRoot := filepath.Join(filepath.Dir(thisFile), "..", "..", "..")- if err := os.Chdir(repoRoot); err != nil {- fmt.Printf("Failed to change to repo root: %v\n", err)- os.Exit(1)- }-- if err := InitMLX(); err != nil {- fmt.Printf("Skipping MLX tests: %v\n", err)- os.Exit(0)- }- os.Exit(m.Run())-}--func useMLXTestThread(t *testing.T) {- t.Helper()- runtime.LockOSThread()- t.Cleanup(func() {- ReleaseAll()- ClearCache()- runtime.UnlockOSThread()- })-}--// TestBasicCleanup verifies non-kept arrays are freed and kept arrays survive.-func TestBasicCleanup(t *testing.T) {- useMLXTestThread(t)-- weight := NewArrayFloat32([]float32{1, 2, 3, 4}, []int32{2, 2})- Keep(weight)- weight.Eval()-- intermediate := NewArrayFloat32([]float32{1, 1}, []int32{1, 2})- result := Matmul(intermediate, weight)- Keep(result)-- // Before eval: intermediate should be valid- if !intermediate.Valid() {- t.Fatal("intermediate should be valid before Eval")- }-- Eval(result)-- // After eval: intermediate should be freed- if intermediate.Valid() {- t.Fatal("intermediate should be freed after Eval")- }-- // Result should have correct values- data := result.Data()- if data[0] != 4 || data[1] != 6 {- t.Errorf("expected [4, 6], got %v", data)- }-- // Weight should survive- if !weight.Valid() {- t.Error("weight was freed")- }-}--// TestKeptSurvives verifies kept arrays are not freed.-func TestKeptSurvives(t *testing.T) {- useMLXTestThread(t)-- a := NewArrayFloat32([]float32{1, 2}, []int32{2})- b := NewArrayFloat32([]float32{3, 4}, []int32{2})- result := Add(a, b)- Keep(result)-- Eval(result)-- if !result.Valid() {- t.Error("kept result was freed")- }-- data := result.Data()- if data[0] != 4 || data[1] != 6 {- t.Errorf("expected [4, 6], got %v", data)- }-}--// TestEvalAutoKeeps verifies Eval automatically keeps its outputs.-func TestEvalAutoKeeps(t *testing.T) {- useMLXTestThread(t)-- a := NewArrayFloat32([]float32{1, 2}, []int32{2})- b := NewArrayFloat32([]float32{3, 4}, []int32{2})- result := Add(a, b)-- // Don't call Keep(result) - Eval should auto-keep it- Eval(result)-- // Result should survive (auto-kept by Eval)- if !result.Valid() {- t.Error("Eval output was freed - should be auto-kept")- }-- // Inputs should be freed (not kept)- if a.Valid() {- t.Error("input 'a' should be freed")- }- if b.Valid() {- t.Error("input 'b' should be freed")- }-- // Verify data is correct- data := result.Data()- if data[0] != 4 || data[1] != 6 {- t.Errorf("expected [4, 6], got %v", data)- }-}--// TestWeightsSurvive verifies kept arrays survive multiple Eval cycles.-func TestWeightsSurvive(t *testing.T) {- useMLXTestThread(t)-- weight := NewArrayFloat32([]float32{1, 2, 3, 4}, []int32{2, 2})- Keep(weight)- weight.Eval()-- for range 5 {- x := NewArrayFloat32([]float32{1, 1}, []int32{1, 2})- result := Matmul(x, weight)- Keep(result)- Eval(result)- }-- if !weight.Valid() {- t.Error("weight was freed after multiple iterations")- }-}--// TestAsyncEvalCleanup verifies AsyncEval cleans up and dispatches.-func TestAsyncEvalCleanup(t *testing.T) {- useMLXTestThread(t)-- weight := NewArrayFloat32([]float32{1, 0, 0, 1}, []int32{2, 2}) // Identity matrix- Keep(weight)- weight.Eval()-- // First async step- x1 := NewArrayFloat32([]float32{1, 2}, []int32{1, 2})- result1 := Matmul(x1, weight)- Keep(result1)- AsyncEval(result1)-- // Second async step- x2 := NewArrayFloat32([]float32{3, 4}, []int32{1, 2})- result2 := Matmul(x2, weight)- Keep(result2)- AsyncEval(result2)-- // Sync and verify results- result1.Eval()- d1 := result1.Data()- if d1[0] != 1 || d1[1] != 2 {- t.Errorf("result1: expected [1, 2], got %v", d1)- }-- result2.Eval()- d2 := result2.Data()- if d2[0] != 3 || d2[1] != 4 {- t.Errorf("result2: expected [3, 4], got %v", d2)- }-- if !weight.Valid() {- t.Error("weight was freed during async")- }-}--// TestMultiOutput verifies multiple kept arrays survive.-func TestMultiOutput(t *testing.T) {- useMLXTestThread(t)-- a := NewArrayFloat32([]float32{1, 2, 3, 4}, []int32{2, 2})- sum := Add(a, a)- prod := Mul(a, a)- Keep(sum, prod)-- Eval(sum, prod)-- // Both kept arrays should be valid- if !sum.Valid() || !prod.Valid() {- t.Error("kept arrays should survive cleanup")- }-- // Verify values- sumData := sum.Data()- prodData := prod.Data()- if sumData[0] != 2 || prodData[0] != 1 {- t.Errorf("unexpected results: sum=%v prod=%v", sumData, prodData)- }-}--// TestChaining verifies output from one step can be used in next.-func TestChaining(t *testing.T) {- useMLXTestThread(t)-- weight := NewArrayFloat32([]float32{1, 0, 0, 1}, []int32{2, 2})- Keep(weight)- weight.Eval()-- // First step- x := NewArrayFloat32([]float32{1, 2}, []int32{1, 2})- out1 := Matmul(x, weight)- Keep(out1)- AsyncEval(out1)-- // Second step uses output of first- out2 := Add(out1, out1)- Keep(out2)- Eval(out2)-- // out1 should survive (was kept)- if !out1.Valid() {- t.Error("out1 was freed but used by second step")- }-- // Final result should be correct- data := out2.Data()- if data[0] != 2 || data[1] != 4 {- t.Errorf("expected [2, 4], got %v", data)- }-}--// TestGenerationLoop simulates the LLM generation pattern with cache.-func TestGenerationLoop(t *testing.T) {- useMLXTestThread(t)-- weight := NewArrayFloat32([]float32{1, 0, 0, 1}, []int32{2, 2})- Keep(weight)- weight.Eval()-- // Simulate cache - starts as zeros- cache := NewArrayFloat32([]float32{0, 0}, []int32{1, 2})- Keep(cache)- cache.Eval()-- var lastToken *Array-- // Simulate 5 generation steps- for step := range 5 {- oldCache := cache-- // Simulate forward pass- input := NewArrayFloat32([]float32{float32(step + 1), float32(step + 2)}, []int32{1, 2})- output := Matmul(input, weight)-- // Simulate cache update- newCache := Add(output, cache)-- // Mark what survives- Keep(output, newCache)-- if step < 4 {- AsyncEval(output, newCache)- } else {- Eval(output, newCache)- }-- // Free old cache, update references- oldCache.Free()- lastToken = output- cache = newCache- }-- // Token output should be valid- if !lastToken.Valid() {- t.Error("token output was freed")- }-- // Cache should be valid- if !cache.Valid() {- t.Error("cache was freed")- }-- // Weight should survive all iterations- if !weight.Valid() {- t.Error("weight was freed")- }-}--// BenchmarkCleanupOnly isolates cleanup cost without MLX ops.-func BenchmarkCleanupOnly(b *testing.B) {- // Pre-create weight- weight := NewArrayFloat32([]float32{1, 0, 0, 1}, []int32{2, 2})- Keep(weight)- weight.Eval()-- b.ResetTimer()- for range b.N {- // Create 100 arrays - minimal ops- arrays := make([]*Array, 100)- for j := range arrays {- arrays[j] = NewArrayFloat32([]float32{1, 2}, []int32{1, 2})- }- Keep(arrays[0])- Eval() // Just cleanup- }-}--// BenchmarkNewArrayOnly measures array creation overhead.-func BenchmarkNewArrayOnly(b *testing.B) {- b.ResetTimer()- for range b.N {- _ = NewArrayFloat32([]float32{1, 2, 3, 4}, []int32{2, 2})- }-}--// BenchmarkCGOCallOverhead measures raw CGO call cost.-func BenchmarkCGOCallOverhead(b *testing.B) {- arr := NewArrayFloat32([]float32{1, 2, 3, 4}, []int32{2, 2})- Keep(arr)- arr.Eval()- b.ResetTimer()- for range b.N {- _ = arr.Ndim() // Simple CGO call- }-}--// BenchmarkCleanup_50 measures cleanup with 50 arrays.-func BenchmarkCleanup_50(b *testing.B) {- benchCleanup(b, 50)-}--// BenchmarkCleanup_500 measures cleanup with 500 arrays (LLM scale).-func BenchmarkCleanup_500(b *testing.B) {- benchCleanup(b, 500)-}--// BenchmarkCleanup_1000 measures cleanup with 1000 arrays.-func BenchmarkCleanup_1000(b *testing.B) {- benchCleanup(b, 1000)-}--func benchCleanup(b *testing.B, numArrays int) {- weight := NewArrayFloat32([]float32{1, 0, 0, 1}, []int32{2, 2})- Keep(weight)- weight.Eval()-- b.ResetTimer()- for range b.N {- x := NewArrayFloat32([]float32{1, 2}, []int32{1, 2})- for range numArrays {- x = Add(x, x)- }- result := Matmul(x, weight)- Keep(result)- Eval(result)- }-}--// BenchmarkGenerationLoop_10 simulates 10 token generation steps.-func BenchmarkGenerationLoop_10(b *testing.B) {- benchGenerationLoop(b, 10)-}--// BenchmarkGenerationLoop_100 simulates 100 token generation steps.-func BenchmarkGenerationLoop_100(b *testing.B) {- benchGenerationLoop(b, 100)-}--func benchGenerationLoop(b *testing.B, steps int) {- weight := NewArrayFloat32([]float32{1, 0, 0, 1}, []int32{2, 2})- Keep(weight)- weight.Eval()-- b.ResetTimer()- for range b.N {- cache := NewArrayFloat32([]float32{0, 0}, []int32{1, 2})- Keep(cache)- cache.Eval()-- for step := range steps {- oldCache := cache- input := NewArrayFloat32([]float32{1, 2}, []int32{1, 2})- output := Matmul(input, weight)- newCache := Add(output, cache)- Keep(output, newCache)-- if step < steps-1 {- AsyncEval(output, newCache)- } else {- Eval(output, newCache)- }- oldCache.Free()- cache = newCache- }- }-}--// BenchmarkLLMForward simulates a realistic LLM forward pass with ~500 ops.-func BenchmarkLLMForward(b *testing.B) {- // Simulate weights for 32 layers- numLayers := 32- weights := make([]*Array, numLayers*4) // q, k, v, o per layer- for i := range weights {- weights[i] = NewArrayFloat32([]float32{1, 0, 0, 1}, []int32{2, 2})- }- Keep(weights...)- Eval(weights...)-- b.ResetTimer()- for range b.N {- x := NewArrayFloat32([]float32{1, 2}, []int32{1, 2})-- // Simulate 32 transformer layers- for layer := range numLayers {- // Attention block (simplified)- q := Matmul(x, weights[layer*4])- k := Matmul(x, weights[layer*4+1])- v := Matmul(x, weights[layer*4+2])- attn := Matmul(Softmax(Matmul(q, Transpose(k, 1, 0)), -1), v)- attnOut := Matmul(attn, weights[layer*4+3])-- // Residual + layernorm (simplified)- x = Add(x, attnOut)- x = RMSNormNoWeight(x, 1e-5)-- // FFN (simplified as single matmul)- ffn := Matmul(x, weights[layer*4])- ffn = SiLU(ffn)- x = Add(x, ffn)- }- Keep(x)- Eval(x)- }-}--// ============ Compile Tests ============--// gelu implements GELU activation: x * 0.5 * (1 + erf(x / sqrt(2)))-func gelu(x *Array) *Array {- sqrt2 := NewScalarArray(1.4142135623730951)- half := NewScalarArray(0.5)- one := NewScalarArray(1.0)- scaled := Div(x, sqrt2)- erfd := Erf(scaled)- return Mul(Mul(x, half), Add(one, erfd))-}--// TestCompileBasic verifies compiled function produces correct output.-func TestCompileBasic(t *testing.T) {- useMLXTestThread(t)-- x := NewArrayFloat32([]float32{-1, 0, 1, 2}, []int32{4})- Keep(x)- x.Eval()-- // Uncompiled- expected := gelu(x)- Keep(expected)- Eval(expected)-- // Compiled- compiled := Compile(func(inputs []*Array) []*Array {- return []*Array{gelu(inputs[0])}- })- defer compiled.Free()-- result := compiled.Call(x)[0]- Keep(result)- Eval(result)-- // Compare with tolerance- expData := expected.Data()- resData := result.Data()- for i := range expData {- diff := expData[i] - resData[i]- if diff < 0 {- diff = -diff- }- if diff > 1e-5 {- t.Errorf("mismatch at %d: expected %f, got %f (diff=%e)", i, expData[i], resData[i], diff)- }- }-}--// TestCompileMultipleInputs verifies compiled function with multiple inputs.-func TestCompileMultipleInputs(t *testing.T) {- useMLXTestThread(t)-- a := NewArrayFloat32([]float32{1, 2, 3, 4}, []int32{4})- b := NewArrayFloat32([]float32{5, 6, 7, 8}, []int32{4})- Keep(a, b)- Eval(a, b)-- compiled := Compile(func(inputs []*Array) []*Array {- sum := Add(inputs[0], inputs[1])- prod := Mul(inputs[0], inputs[1])- return []*Array{sum, prod}- })- defer compiled.Free()-- outputs := compiled.Call(a, b)- Keep(outputs...)- Eval(outputs...)-- sumData := outputs[0].Data()- prodData := outputs[1].Data()- if sumData[0] != 6 || prodData[0] != 5 {- t.Errorf("unexpected: sum[0]=%f, prod[0]=%f", sumData[0], prodData[0])- }-}--// TestCompileReuse verifies compiled function can be called multiple times.-func TestCompileReuse(t *testing.T) {- useMLXTestThread(t)-- compiled := Compile(func(inputs []*Array) []*Array {- return []*Array{Add(inputs[0], inputs[0])}- })- defer compiled.Free()-- for i := range 5 {- x := NewArrayFloat32([]float32{float32(i)}, []int32{1})- Keep(x)- x.Eval()- result := compiled.Call(x)[0]- Keep(result)- Eval(result)- data := result.Data()- expected := float32(i * 2)- if data[0] != expected {- t.Errorf("iteration %d: expected %f, got %f", i, expected, data[0])- }- }-}--// BenchmarkGELUUncompiled benchmarks uncompiled GELU.-func BenchmarkGELUUncompiled(b *testing.B) {- x := RandomNormal([]int32{1000, 1024}, 42)- Keep(x)- x.Eval()-- b.ResetTimer()- for range b.N {- y := x- for range 10 {- y = gelu(y)- }- Keep(y)- Eval(y)- }-}--// BenchmarkGELUCompiled benchmarks compiled GELU.-func BenchmarkGELUCompiled(b *testing.B) {- x := RandomNormal([]int32{1000, 1024}, 42)- Keep(x)- x.Eval()-- compiled := Compile(func(inputs []*Array) []*Array {- y := inputs[0]- for range 10 {- y = gelu(y)- }- return []*Array{y}- })- defer compiled.Free()-- b.ResetTimer()- for range b.N {- result := compiled.Call(x)- Keep(result[0])- Eval(result[0])- }-}--// TestCompileNoMemoryLeak verifies compiled functions don't leak memory.-func TestCompileNoMemoryLeak(t *testing.T) {- useMLXTestThread(t)-- x := RandomNormal([]int32{100, 100}, 42)- Keep(x)- x.Eval()-- compiled := Compile(func(inputs []*Array) []*Array {- y := inputs[0]- for range 5 {- y = gelu(y)- }- return []*Array{y}- })- defer compiled.Free()-- // Warmup to establish baseline- for range 10 {- result := compiled.Call(x)- Keep(result[0])- Eval(result[0])- result[0].Free()- }-- MetalResetPeakMemory()- initialMem := MetalGetActiveMemory()-- for range 100 {- result := compiled.Call(x)- Keep(result[0])- Eval(result[0])- result[0].Free()- }-- Eval() // Final cleanup-- finalMem := MetalGetActiveMemory()- peakMem := MetalGetPeakMemory()-- // Memory should not grow significantly (allow 10MB slack for caching)- growth := int64(finalMem) - int64(initialMem)- if growth > 10*1024*1024 {- t.Errorf("memory grew by %d bytes over 100 iterations", growth)- }- t.Logf("memory: initial=%dMB, final=%dMB, peak=%dMB, growth=%dKB",- initialMem/(1<<20), finalMem/(1<<20), peakMem/(1<<20), growth/1024)-}--// TestCompileWithRandomState verifies compiled function can capture and update random state.-func TestCompileWithRandomState(t *testing.T) {- useMLXTestThread(t)-- // Simulate logits for sampling- logits := NewArrayFloat32([]float32{0.1, 0.2, 0.3, 0.4}, []int32{1, 4})- Keep(logits)- logits.Eval()-- // Initial random key- key := RandomKey(42)- Keep(key)-- // Compile a sampling function that splits the key- compiled := Compile(func(inputs []*Array) []*Array {- logits := inputs[0]- keyIn := inputs[1]-- // Split key: one for sampling, one for next iteration- key1, key2 := RandomSplit(keyIn)-- // Sample from logits- sample := RandomCategoricalWithKey(logits, key2, -1, 1)-- return []*Array{sample, key1}- })- defer compiled.Free()-- // Run multiple sampling steps- samples := make([]int32, 10)- for i := range 10 {- outputs := compiled.Call(logits, key)- Keep(outputs...)- Eval(outputs...)- samples[i] = outputs[0].ItemInt32()- key.Free()- key = outputs[1]- }-- // Verify we got valid samples (0-3)- for i, s := range samples {- if s < 0 || s > 3 {- t.Errorf("sample %d out of range: %d", i, s)- }- }- t.Logf("samples: %v", samples)-- // Verify samples aren't all the same (randomness works)- allSame := true- for i := 1; i < len(samples); i++ {- if samples[i] != samples[0] {- allSame = false- break- }- }- if allSame {- t.Error("all samples are the same - random state may not be updating")- }-}--// swiGLU implements the GPT-OSS custom SwiGLU activation.-func swiGLU(gate, up *Array, alpha, limit float32) *Array {- gateClipped := ClipScalar(gate, 0, limit, false, true)- upClipped := ClipScalar(up, -limit, limit, true, true)- gluScaled := MulScalar(gateClipped, alpha)- sig := Sigmoid(gluScaled)- outGlu := Mul(gateClipped, sig)- return Mul(outGlu, AddScalar(upClipped, 1.0))-}--// TestCompileSwiGLU verifies compiled SwiGLU produces correct output.-func TestCompileSwiGLU(t *testing.T) {- useMLXTestThread(t)-- gate := NewArrayFloat32([]float32{-1, 0, 1, 2, 5, 10}, []int32{6})- up := NewArrayFloat32([]float32{-5, -1, 0, 1, 5, 10}, []int32{6})- Keep(gate, up)- Eval(gate, up)-- const alpha float32 = 1.702- const limit float32 = 7.0-- // Uncompiled- expected := swiGLU(gate, up, alpha, limit)- Keep(expected)- Eval(expected)-- // Compiled- compiled := Compile(func(inputs []*Array) []*Array {- return []*Array{swiGLU(inputs[0], inputs[1], alpha, limit)}- })- defer compiled.Free()-- result := compiled.Call(gate, up)[0]- Keep(result)- Eval(result)-- // Compare- expData := expected.Data()- resData := result.Data()- for i := range expData {- diff := expData[i] - resData[i]- if diff < 0 {- diff = -diff- }- if diff > 1e-5 {- t.Errorf("mismatch at %d: expected %f, got %f", i, expData[i], resData[i])- }- }- t.Logf("SwiGLU results: %v", resData)-}--// BenchmarkSwiGLUUncompiled benchmarks uncompiled SwiGLU.-func BenchmarkSwiGLUUncompiled(b *testing.B) {- gate := RandomNormal([]int32{1, 2880}, 42)- up := RandomNormal([]int32{1, 2880}, 43)- Keep(gate, up)- Eval(gate, up)-- const alpha float32 = 1.702- const limit float32 = 7.0-- b.ResetTimer()- for range b.N {- result := swiGLU(gate, up, alpha, limit)- Keep(result)- Eval(result)- }-}--// BenchmarkSwiGLUCompiled benchmarks compiled SwiGLU.-func BenchmarkSwiGLUCompiled(b *testing.B) {- gate := RandomNormal([]int32{1, 2880}, 42)- up := RandomNormal([]int32{1, 2880}, 43)- Keep(gate, up)- Eval(gate, up)-- const alpha float32 = 1.702- const limit float32 = 7.0-- compiled := Compile(func(inputs []*Array) []*Array {- return []*Array{swiGLU(inputs[0], inputs[1], alpha, limit)}- })- defer compiled.Free()-- b.ResetTimer()- for range b.N {- result := compiled.Call(gate, up)- Keep(result[0])- Eval(result[0])- }-}--// BenchmarkSwiGLU10xUncompiled benchmarks 10 chained SwiGLU ops uncompiled.-func BenchmarkSwiGLU10xUncompiled(b *testing.B) {- x := RandomNormal([]int32{1, 2880}, 42)- Keep(x)- x.Eval()-- const alpha float32 = 1.702- const limit float32 = 7.0-- b.ResetTimer()- for range b.N {- y := x- for range 10 {- y = swiGLU(y, y, alpha, limit)- }- Keep(y)- Eval(y)- }-}--// BenchmarkSwiGLU10xCompiled benchmarks 10 chained SwiGLU ops compiled.-func BenchmarkSwiGLU10xCompiled(b *testing.B) {- x := RandomNormal([]int32{1, 2880}, 42)- Keep(x)- x.Eval()-- const alpha float32 = 1.702- const limit float32 = 7.0-- compiled := Compile(func(inputs []*Array) []*Array {- y := inputs[0]- for range 10 {- y = swiGLU(y, y, alpha, limit)- }- return []*Array{y}- })- defer compiled.Free()-- b.ResetTimer()- for range b.N {- result := compiled.Call(x)- Keep(result[0])- Eval(result[0])- }-}--// ============ Sampler Benchmarks ============--// sampleTopK implements top-k sampling-func sampleTopK(logits, key *Array, k int) (*Array, *Array) {- neg := Neg(logits)- indices := Argpartition(neg, k-1, -1)- topK := Slice(indices, []int32{0}, []int32{int32(k)})- values := TakeAlongAxis(logits, topK, -1)- key1, key2 := RandomSplit(key)- sampled := RandomCategoricalWithKey(values, key2, -1, 1)- return Take(topK, sampled, -1), key1-}--// sampleTopP implements top-p (nucleus) sampling-func sampleTopP(logits, key *Array, p float32, vocabSize int32) (*Array, *Array) {- sorted := Argsort(Neg(logits), -1)- sortedLogits := TakeAlongAxis(logits, sorted, -1)- probs := Softmax(sortedLogits, -1)- cumProbs := Cumsum(probs, -1)- mask := LessScalar(cumProbs, p)- negInf := FullDtype(float32(-1e9), logits.Dtype(), vocabSize)- masked := Where(mask, sortedLogits, negInf)- key1, key2 := RandomSplit(key)- sampled := RandomCategoricalWithKey(masked, key2, -1, 1)- return Take(sorted, sampled, -1), key1-}--// BenchmarkSampleTopKUncompiled benchmarks uncompiled top-k sampling.-func BenchmarkSampleTopKUncompiled(b *testing.B) {- vocabSize := int32(32000)- logits := RandomNormal([]int32{vocabSize}, 42)- key := RandomKey(42)- Keep(logits, key)- Eval(logits, key)-- b.ResetTimer()- for range b.N {- var token *Array- token, key = sampleTopK(logits, key, 40)- Keep(token, key)- Eval(token)- }-}--// BenchmarkSampleTopKCompiled benchmarks compiled top-k sampling.-func BenchmarkSampleTopKCompiled(b *testing.B) {- vocabSize := int32(32000)- logits := RandomNormal([]int32{vocabSize}, 42)- key := RandomKey(42)- Keep(logits, key)- Eval(logits, key)-- compiled := Compile(func(inputs []*Array) []*Array {- token, newKey := sampleTopK(inputs[0], inputs[1], 40)- return []*Array{token, newKey}- })- defer compiled.Free()-- b.ResetTimer()- for range b.N {- outputs := compiled.Call(logits, key)- Keep(outputs...)- Eval(outputs[0])- key = outputs[1]- }-}--// BenchmarkSampleTopPUncompiled benchmarks uncompiled top-p sampling.-func BenchmarkSampleTopPUncompiled(b *testing.B) {- vocabSize := int32(32000)- logits := RandomNormal([]int32{vocabSize}, 42)- key := RandomKey(42)- Keep(logits, key)- Eval(logits, key)-- b.ResetTimer()- for range b.N {- var token *Array- token, key = sampleTopP(logits, key, 0.9, vocabSize)- Keep(token, key)- Eval(token)- }-}--// BenchmarkSampleTopPCompiled benchmarks compiled top-p sampling.-func BenchmarkSampleTopPCompiled(b *testing.B) {- vocabSize := int32(32000)- logits := RandomNormal([]int32{vocabSize}, 42)- key := RandomKey(42)- Keep(logits, key)- Eval(logits, key)-- compiled := Compile(func(inputs []*Array) []*Array {- token, newKey := sampleTopP(inputs[0], inputs[1], 0.9, vocabSize)- return []*Array{token, newKey}- })- defer compiled.Free()-- b.ResetTimer()- for range b.N {- outputs := compiled.Call(logits, key)- Keep(outputs...)- Eval(outputs[0])- key = outputs[1]- }-}--// TestCompiledSamplerMemoryStable verifies compiled samplers don't leak memory.-func TestCompiledSamplerMemoryStable(t *testing.T) {- useMLXTestThread(t)-- vocabSize := int32(32000)- logits := RandomNormal([]int32{vocabSize}, 42)- key := RandomKey(42)- Keep(logits, key)- Eval(logits, key)-- compiledTopK := Compile(func(inputs []*Array) []*Array {- token, newKey := sampleTopK(inputs[0], inputs[1], 40)- return []*Array{token, newKey}- })- defer compiledTopK.Free()-- compiledTopP := Compile(func(inputs []*Array) []*Array {- token, newKey := sampleTopP(inputs[0], inputs[1], 0.9, vocabSize)- return []*Array{token, newKey}- })- defer compiledTopP.Free()-- // Warmup- for range 10 {- out := compiledTopK.Call(logits, key)- Keep(out...)- Eval(out[0])- out[0].Free()- key = out[1]- }-- MetalResetPeakMemory()- initialMem := MetalGetActiveMemory()-- // Run 500 iterations of each sampler- for range 500 {- // TopK- out := compiledTopK.Call(logits, key)- Keep(out...)- Eval(out[0])- out[0].Free()- key = out[1]-- // TopP- out = compiledTopP.Call(logits, key)- Keep(out...)- Eval(out[0])- out[0].Free()- key = out[1]- }-- Eval() // Final cleanup-- finalMem := MetalGetActiveMemory()- peakMem := MetalGetPeakMemory()-- growth := int64(finalMem) - int64(initialMem)- t.Logf("memory: initial=%dMB, final=%dMB, peak=%dMB, growth=%dKB",- initialMem/(1<<20), finalMem/(1<<20), peakMem/(1<<20), growth/1024)-- // Memory should stay bounded (allow 20MB for caching overhead)- if growth > 20*1024*1024 {- t.Errorf("memory grew by %d bytes over 1000 sampler calls - possible leak!", growth)- }-}--// BenchmarkSimpleOps measures simple ops with cleanup-func BenchmarkSimpleOps(b *testing.B) {- weight := NewArrayFloat32([]float32{1, 0, 0, 1}, []int32{2, 2})- Keep(weight)- weight.Eval()-- b.ResetTimer()- for range b.N {- x := NewArrayFloat32([]float32{1, 2}, []int32{1, 2})- result := Matmul(x, weight)- Keep(result)- AsyncEval(result)- result.Eval()- }-}--// BenchmarkLayerLike measures layer-like ops (~15 ops)-func BenchmarkLayerLike(b *testing.B) {- hidden := int32(256)- w := Ones(hidden, hidden)- Keep(w)- w.Eval()-- b.ResetTimer()- for range b.N {- x := Ones(1, hidden)- // Simulate attention-like ops with proper shapes- h := Matmul(x, w) // [1, 256] @ [256, 256] = [1, 256]- h = Add(h, Matmul(h, w)) // residual- h = Mul(h, Sigmoid(Matmul(h, w))) // gating- h = Matmul(h, w) // output projection- h = Add(x, RMSNormNoWeight(h, 1e-5)) // residual + norm- Keep(h)- AsyncEval(h)- Eval(h)- }-}--// BenchmarkManyOps measures with increasing op counts-func BenchmarkManyOps(b *testing.B) {- w := Ones(64, 64)- Keep(w)- w.Eval()-- for _, numOps := range []int{10, 50, 100, 500, 1000} {- b.Run(fmt.Sprintf("ops_%d", numOps), func(b *testing.B) {- for range b.N {- x := Ones(1, 64)- for range numOps {- x = Add(x, Matmul(x, w))- }- Keep(x)- AsyncEval(x)- Eval(x)- }- })- }-}--// BenchmarkLLMScale measures at LLM-realistic scale (~1348 arrays)-func BenchmarkLLMScale(b *testing.B) {- // Simulate Qwen-like model: 24 layers, each with ~56 ops = 1344 arrays- numLayers := 24- opsPerLayer := 56-- // Create weights- hidden := int32(64)- weights := make([]*Array, numLayers*4)- for i := range weights {- weights[i] = Ones(hidden, hidden)- }- Keep(weights...)- Eval(weights...)-- b.ResetTimer()- for range b.N {- x := Ones(1, hidden)-- for layer := range numLayers {- for range opsPerLayer / 4 {- x = Add(x, Matmul(x, weights[layer*4]))- x = Mul(x, Sigmoid(x))- }- }- Keep(x)- AsyncEval(x)- Eval(x)- }-}--// BenchmarkArrayFreeLoop measures the cost of freeing N arrays-func BenchmarkArrayFreeLoop(b *testing.B) {- for _, count := range []int{100, 500, 1000, 1500} {- b.Run(fmt.Sprintf("arrays_%d", count), func(b *testing.B) {- for range b.N {- b.StopTimer()- arrays := make([]*Array, count)- for j := range count {- arrays[j] = NewArrayFloat32([]float32{1, 2, 3, 4}, []int32{2, 2})- }- b.StartTimer()-- // Cleanup all arrays- Eval()- }- })- }-}--// BenchmarkCleanupIsolated measures just cleanup time-func BenchmarkCleanupIsolated(b *testing.B) {- w := NewArrayFloat32([]float32{1}, []int32{1, 1})- Keep(w)- w.Eval()-- for _, count := range []int{100, 500, 1000, 1500} {- b.Run(fmt.Sprintf("arrays_%d", count), func(b *testing.B) {- b.ResetTimer()- for range b.N {- b.StopTimer()- x := NewArrayFloat32([]float32{1}, []int32{1})- for range count {- x = Add(x, x)- }- Keep(x)- b.StartTimer()- Eval() // Just cleanup- }- })- }-}--// TestMemoryStable verifies that cleanup doesn't cause unbounded memory growth.-func TestMemoryStable(t *testing.T) {- useMLXTestThread(t)-- if testing.Short() {- t.Skip("skipping memory test in short mode")- }-- // Create realistic-sized arrays (like KV cache)- batchSize := int32(1)- numHeads := int32(8)- seqLen := int32(256)- headDim := int32(64)- cacheShape := []int32{batchSize, numHeads, seqLen, headDim}- cacheSize := batchSize * numHeads * seqLen * headDim * 4 // float32 = 4 bytes-- // Initial cache- keys := Zeros(cacheShape, DtypeFloat32)- values := Zeros(cacheShape, DtypeFloat32)- Keep(keys, values)- Eval(keys, values)-- // Warmup- for range 5 {- oldKeys, oldValues := keys, values-- newKeys := Add(keys, keys)- newValues := Add(values, values)- Keep(newKeys, newValues)- Eval(newKeys, newValues)-- oldKeys.Free()- oldValues.Free()- keys, values = newKeys, newValues- }-- MetalResetPeakMemory()- initialMem := MetalGetActiveMemory()-- // Run 100 steps- for range 100 {- oldKeys, oldValues := keys, values-- newKeys := Add(keys, keys)- newValues := Add(values, values)- Keep(newKeys, newValues)- Eval(newKeys, newValues)-- oldKeys.Free()- oldValues.Free()- keys, values = newKeys, newValues- }-- Eval() // Final cleanup-- finalMem := MetalGetActiveMemory()- peakMem := MetalGetPeakMemory()-- growth := int64(finalMem) - int64(initialMem)- expectedMaxGrowth := int64(cacheSize * 4 * 10)-- t.Logf("cache size: %d bytes", cacheSize*2)- t.Logf("memory: initial=%dMB, final=%dMB, peak=%dMB, growth=%dKB",- initialMem/(1<<20), finalMem/(1<<20), peakMem/(1<<20), growth/1024)-- if growth > expectedMaxGrowth {- t.Errorf("memory grew by %d bytes over 100 steps (expected max %d) - possible leak",- growth, expectedMaxGrowth)- }-}diff --git a/x/imagegen/models/flux2/flux2.go b/x/imagegen/models/flux2/flux2.godeleted file mode 100644index 4efaf3ec9..000000000--- a/x/imagegen/models/flux2/flux2.go+++ /dev/null@@ -1,551 +0,0 @@-// Package flux2 implements the FLUX.2 Klein diffusion transformer model.-// Klein is a 4B parameter distilled model that supports sub-second inference.-package flux2--import (- "context"- "encoding/json"- "fmt"- "image"- "math"- "time"-- "github.com/ollama/ollama/x/imagegen/manifest"- "github.com/ollama/ollama/x/imagegen/mlx"- "github.com/ollama/ollama/x/imagegen/models/qwen3"- "github.com/ollama/ollama/x/imagegen/tokenizer"- "golang.org/x/image/draw"-)--// GenerateConfig holds all options for image generation.-type GenerateConfig struct {- Prompt string- Width int32 // Image width (default: 1024)- Height int32 // Image height (default: 1024)- Steps int // Denoising steps (default: 4 for Klein)- GuidanceScale float32 // Guidance scale (default: 1.0, Klein doesn't need CFG)- Seed int64 // Random seed- Progress func(step, totalSteps int) // Optional progress callback- CapturePath string // GPU capture path (debug)- InputImages []image.Image // Reference images for image conditioning (already loaded)-}--// Model represents a FLUX.2 Klein model.-type Model struct {- ModelName string- Tokenizer *tokenizer.Tokenizer- TextEncoder *qwen3.TextEncoder- Transformer *Flux2Transformer2DModel- VAE *AutoencoderKLFlux2- SchedulerConfig *SchedulerConfig-}--// TextEncoderLayerIndices are the layers from which to extract text embeddings.-// Diffusers uses hidden_states[9, 18, 27]. In Python, hidden_states[0] is the embedding-// output before any layers, so hidden_states[9] = after layer 8 (0-indexed).-// Go's ForwardWithLayerOutputs captures after layer i runs, so we use [8, 17, 26].-var TextEncoderLayerIndices = []int{8, 17, 26}--// Load loads the FLUX.2 Klein model from ollama blob storage.-func (m *Model) Load(modelName string) error {- fmt.Printf("Loading FLUX.2 Klein model from manifest: %s...\n", modelName)- start := time.Now()-- if mlx.GPUIsAvailable() {- mlx.SetDefaultDeviceGPU()- mlx.EnableCompile()- }-- m.ModelName = modelName-- // Load manifest- manifest, err := manifest.LoadManifest(modelName)- if err != nil {- return fmt.Errorf("load manifest: %w", err)- }-- // Load tokenizer- fmt.Print(" Loading tokenizer... ")- tokData, err := manifest.ReadConfig("tokenizer/tokenizer.json")- if err != nil {- return fmt.Errorf("tokenizer: %w", err)- }-- tokConfig := &tokenizer.TokenizerConfig{}- if data, err := manifest.ReadConfig("tokenizer/tokenizer_config.json"); err == nil {- tokConfig.TokenizerConfigJSON = data- }- if data, err := manifest.ReadConfig("tokenizer/generation_config.json"); err == nil {- tokConfig.GenerationConfigJSON = data- }- if data, err := manifest.ReadConfig("tokenizer/special_tokens_map.json"); err == nil {- tokConfig.SpecialTokensMapJSON = data- }-- tok, err := tokenizer.LoadFromBytesWithConfig(tokData, tokConfig)- if err != nil {- return fmt.Errorf("tokenizer: %w", err)- }- m.Tokenizer = tok- fmt.Println("✓")-- // Load text encoder- m.TextEncoder = &qwen3.TextEncoder{}- if err := m.TextEncoder.Load(manifest, "text_encoder/config.json"); err != nil {- return fmt.Errorf("text encoder: %w", err)- }-- // Load transformer- m.Transformer = &Flux2Transformer2DModel{}- if err := m.Transformer.Load(manifest); err != nil {- return fmt.Errorf("transformer: %w", err)- }-- // Load VAE- m.VAE = &AutoencoderKLFlux2{}- if err := m.VAE.Load(manifest); err != nil {- return fmt.Errorf("VAE: %w", err)- }-- // Evaluate all weights in a single batch (reduces GPU sync overhead)- fmt.Print(" Evaluating weights... ")- allWeights := mlx.Collect(m.TextEncoder)- allWeights = append(allWeights, mlx.Collect(m.Transformer)...)- allWeights = append(allWeights, mlx.Collect(m.VAE)...)- mlx.Eval(allWeights...)- fmt.Println("✓")-- // Load scheduler config- m.SchedulerConfig = DefaultSchedulerConfig()- if schedData, err := manifest.ReadConfig("scheduler/scheduler_config.json"); err == nil {- if err := json.Unmarshal(schedData, m.SchedulerConfig); err != nil {- fmt.Printf(" Warning: failed to parse scheduler config: %v\n", err)- }- }-- mem := mlx.MetalGetActiveMemory()- fmt.Printf(" Loaded in %.2fs (%.1f GB VRAM)\n", time.Since(start).Seconds(), float64(mem)/(1024*1024*1024))-- return nil-}--// Generate creates an image from a prompt.-func (m *Model) Generate(prompt string, width, height int32, steps int, seed int64) (*mlx.Array, error) {- return m.GenerateFromConfig(context.Background(), &GenerateConfig{- Prompt: prompt,- Width: width,- Height: height,- Steps: steps,- Seed: seed,- })-}--// GenerateWithProgress creates an image with progress callback.-func (m *Model) GenerateWithProgress(prompt string, width, height int32, steps int, seed int64, progress func(step, totalSteps int)) (*mlx.Array, error) {- return m.GenerateFromConfig(context.Background(), &GenerateConfig{- Prompt: prompt,- Width: width,- Height: height,- Steps: steps,- Seed: seed,- Progress: progress,- })-}--// GenerateFromConfig generates an image using the unified config struct.-func (m *Model) GenerateFromConfig(ctx context.Context, cfg *GenerateConfig) (*mlx.Array, error) {- start := time.Now()- result, err := m.generate(ctx, cfg)- if err != nil {- return nil, err- }- fmt.Printf("Generated in %.2fs (%d steps)\n", time.Since(start).Seconds(), cfg.Steps)- return result, nil-}--// GenerateImage implements runner.ImageModel interface.-func (m *Model) GenerateImage(ctx context.Context, prompt string, width, height int32, steps int, seed int64, progress func(step, total int)) (*mlx.Array, error) {- return m.GenerateFromConfig(ctx, &GenerateConfig{- Prompt: prompt,- Width: width,- Height: height,- Steps: steps,- Seed: seed,- Progress: progress,- })-}--// GenerateImageWithInputs implements runner.ImageEditModel interface.-// It generates an image conditioned on the provided input images for image editing.-func (m *Model) GenerateImageWithInputs(ctx context.Context, prompt string, width, height int32, steps int, seed int64, inputImages []image.Image, progress func(step, total int)) (*mlx.Array, error) {- return m.GenerateFromConfig(ctx, &GenerateConfig{- Prompt: prompt,- Width: width,- Height: height,- Steps: steps,- Seed: seed,- InputImages: inputImages,- Progress: progress,- })-}--// MaxOutputPixels is the maximum output resolution (4 megapixels, ~2048x2048)-const MaxOutputPixels = 2048 * 2048--// MaxRefPixels is the maximum resolution for reference images (smaller to reduce attention memory)-const MaxRefPixels = 728 * 728--// generate is the internal denoising pipeline.-func (m *Model) generate(ctx context.Context, cfg *GenerateConfig) (*mlx.Array, error) {- // Enable MLX compilation for fused kernels- mlx.EnableCompile()-- // Apply defaults- if cfg.Steps <= 0 {- cfg.Steps = 4 // Klein default: 4 steps for distilled model- }- if cfg.GuidanceScale <= 0 {- cfg.GuidanceScale = 1.0 // Klein doesn't need guidance- }-- // Determine output dimensions- if len(cfg.InputImages) > 0 {- // With input images, compute missing dimension from aspect ratio- // Images are already EXIF-rotated by the caller- bounds := cfg.InputImages[0].Bounds()- imgW, imgH := bounds.Dx(), bounds.Dy()- aspectRatio := float64(imgH) / float64(imgW)- if cfg.Width > 0 && cfg.Height <= 0 {- // Width specified, compute height- cfg.Height = int32(math.Round(float64(cfg.Width)*aspectRatio/16) * 16)- } else if cfg.Height > 0 && cfg.Width <= 0 {- // Height specified, compute width- cfg.Width = int32(math.Round(float64(cfg.Height)/aspectRatio/16) * 16)- } else if cfg.Width <= 0 && cfg.Height <= 0 {- // Neither specified, use input dimensions- cfg.Width = int32(imgW)- cfg.Height = int32(imgH)- }- }- if cfg.Width <= 0 {- cfg.Width = 1024- }- if cfg.Height <= 0 {- cfg.Height = 1024- }-- // Cap to max pixels, preserve aspect ratio, round to multiple of 16- pixels := int(cfg.Width) * int(cfg.Height)- if pixels > MaxOutputPixels {- scale := math.Sqrt(float64(MaxOutputPixels) / float64(pixels))- cfg.Width = int32(math.Round(float64(cfg.Width)*scale/16) * 16)- cfg.Height = int32(math.Round(float64(cfg.Height)*scale/16) * 16)- }- cfg.Height = (cfg.Height + 8) / 16 * 16 // round to nearest 16- cfg.Width = (cfg.Width + 8) / 16 * 16- fmt.Printf(" Output: %dx%d\n", cfg.Width, cfg.Height)-- tcfg := m.Transformer.TransformerConfig- patchSize := m.VAE.Config.PatchSize-- // Latent dimensions: image / 8 (VAE downscale) / patch_size- latentH := cfg.Height / 8- latentW := cfg.Width / 8- patchH := latentH / patchSize[0]- patchW := latentW / patchSize[1]- imgSeqLen := patchH * patchW-- // Text encoding with multi-layer extraction (no padding, use true sequence length)- fmt.Print(" Encoding prompt... ")- promptEmbeds, textLen := m.TextEncoder.EncodePromptWithLayers(m.Tokenizer, cfg.Prompt, 512, TextEncoderLayerIndices, false)- fmt.Println("✓")-- // Encode reference images if provided- var refTokens *ImageCondTokens- var refHeights, refWidths []int32- if len(cfg.InputImages) > 0 {- fmt.Printf(" Encoding %d reference image(s):\n", len(cfg.InputImages))-- var err error- refTokens, err = m.EncodeImageRefs(cfg.InputImages)- if err != nil {- return nil, fmt.Errorf("encode reference images: %w", err)- }-- // Extract heights/widths for RoPE computation (same limits as EncodeImageRefs)- limitPixels := MaxRefPixels- if len(cfg.InputImages) > 1 {- limitPixels = MaxRefPixels / 2- }- for _, img := range cfg.InputImages {- _, w, h := PrepareImage(img, limitPixels)- refHeights = append(refHeights, int32(h/16))- refWidths = append(refWidths, int32(w/16))- }- }-- // Scheduler- scheduler := NewFlowMatchScheduler(m.SchedulerConfig)- scheduler.SetTimestepsWithMu(cfg.Steps, CalculateShift(imgSeqLen, cfg.Steps))-- // Init latents in packed form [B, C*4, H/2, W/2] like diffusers- // diffusers creates noise in [B, 128, 64, 64] and packs to [B, 4096, 128]- latentChannels := m.VAE.Config.LatentChannels- packedChannels := latentChannels * 4 // 32 * 4 = 128- latents := scheduler.InitNoise([]int32{1, packedChannels, patchH, patchW}, cfg.Seed)-- // Pack latents (transpose): [B, C, H, W] -> [B, H*W, C]- // This matches diffusers' _pack_latents- patches := packLatents(latents)- noiseSeqLen := patches.Shape()[1]-- // RoPE cache - includes reference images if present- rope := PrepareRoPECache(textLen, patchH, patchW, tcfg.AxesDimsRoPE, tcfg.RopeTheta, refHeights, refWidths, ImageRefScale)-- // Cleanup setup arrays when done- defer func() {- rope.Cos.Free()- rope.Sin.Free()- promptEmbeds.Free()- if refTokens != nil {- refTokens.Tokens.Free()- }- }()-- // Pre-compute all timesteps before the loop to avoid per-step tensor creation- timesteps := make([]*mlx.Array, cfg.Steps)- for i := range cfg.Steps {- tCurr := scheduler.Timesteps[i] / float32(m.SchedulerConfig.NumTrainTimesteps)- timesteps[i] = mlx.ToBFloat16(mlx.NewArray([]float32{tCurr}, []int32{1}))- }-- // Evaluate setup arrays- fmt.Print(" Evaluating setup... ")- setupStart := time.Now()- toEval := []*mlx.Array{promptEmbeds, patches, rope.Cos, rope.Sin}- toEval = append(toEval, timesteps...)- if refTokens != nil {- toEval = append(toEval, refTokens.Tokens)- }- mlx.Eval(toEval...)- mlx.MetalResetPeakMemory() // Reset peak to measure generation separately- fmt.Printf("✓ (%.2fs, %.1f GB)\n", time.Since(setupStart).Seconds(),- float64(mlx.MetalGetActiveMemory())/(1024*1024*1024))-- if cfg.Progress != nil {- cfg.Progress(0, cfg.Steps)- }-- loopStart := time.Now()- stepStart := time.Now()-- // Denoising loop- for i := range cfg.Steps {- // Check for cancellation- if ctx != nil {- select {- case <-ctx.Done():- return nil, ctx.Err()- default:- }- }-- // GPU capture on step 2 if requested- if cfg.CapturePath != "" && i == 1 {- mlx.MetalStartCapture(cfg.CapturePath)- }-- timestep := timesteps[i]-- // Prepare input - concatenate noise patches with reference tokens if present- imgInput := patches- if refTokens != nil {- imgInput = mlx.Concatenate([]*mlx.Array{patches, refTokens.Tokens}, 1)- }-- // Transformer forward pass- output := m.Transformer.Forward(imgInput, promptEmbeds, timestep, rope)-- // If we concatenated reference tokens, slice to only get noise portion- if refTokens != nil {- output = mlx.Slice(output, []int32{0, 0, 0}, []int32{1, noiseSeqLen, output.Shape()[2]})- }-- // Scheduler step (keep reference to old patches for the computation graph)- newPatches := scheduler.Step(output, patches, i)-- if cfg.CapturePath != "" && i == 1 {- mlx.MetalStopCapture()- }-- mlx.Eval(newPatches)- patches = newPatches-- elapsed := time.Since(stepStart).Seconds()- peakGB := float64(mlx.MetalGetPeakMemory()) / (1024 * 1024 * 1024)- if i == 0 {- fmt.Printf(" step %d: %.2fs (JIT warmup), peak %.1f GB\n", i+1, elapsed, peakGB)- } else {- fmt.Printf(" step %d: %.2fs, peak %.1f GB\n", i+1, elapsed, peakGB)- }- stepStart = time.Now()- if cfg.Progress != nil {- cfg.Progress(i+1, cfg.Steps)- }- }-- loopTime := time.Since(loopStart).Seconds()- peakMem := float64(mlx.MetalGetPeakMemory()) / (1024 * 1024 * 1024)- fmt.Printf(" Denoised %d steps in %.2fs (%.2fs/step), peak %.1f GB\n",- cfg.Steps, loopTime, loopTime/float64(cfg.Steps), peakMem)-- // Free timesteps now that denoising is done- for _, ts := range timesteps {- ts.Free()- }-- // VAE decode with tiling for larger images- fmt.Print(" Decoding VAE... ")- vaeStart := time.Now()- // Enable tiling for images > 512x512 (latent > 64x64)- // VAE attention is O(n²) on latent pixels, tiling reduces memory significantly- if patchH*2 > 64 || patchW*2 > 64 {- m.VAE.Tiling = DefaultTilingConfig()- }- decoded := m.VAE.Decode(patches, patchH, patchW)- mlx.Eval(decoded)-- // Free patches now that decode is done- patches.Free()-- fmt.Printf("✓ (%.2fs, peak %.1f GB)\n", time.Since(vaeStart).Seconds(),- float64(mlx.MetalGetPeakMemory())/(1024*1024*1024))-- return decoded, nil-}--// packLatents converts [B, C, H, W] to [B, H*W, C] (matches diffusers _pack_latents)-func packLatents(x *mlx.Array) *mlx.Array {- shape := x.Shape()- B := shape[0]- C := shape[1]- H := shape[2]- W := shape[3]- // [B, C, H, W] -> [B, C, H*W] -> [B, H*W, C]- x = mlx.Reshape(x, B, C, H*W)- return mlx.Transpose(x, 0, 2, 1)-}--// LoadPersistent loads the model and keeps it in memory for repeated use.-func LoadPersistent(modelName string) (*Model, error) {- m := &Model{}- if err := m.Load(modelName); err != nil {- return nil, err- }- return m, nil-}--// ImageRefScale is the time coordinate offset between reference images (matches diffusers scale=10)-const ImageRefScale = 10--// PrepareImage resizes and crops an image to be a multiple of 16, with optional pixel limit.-// Returns the processed image and its dimensions.-func PrepareImage(img image.Image, limitPixels int) (image.Image, int, int) {- bounds := img.Bounds()- w, h := bounds.Dx(), bounds.Dy()-- // Cap pixels if needed (like diffusers cap_pixels)- if limitPixels > 0 && w*h > limitPixels {- scale := math.Sqrt(float64(limitPixels) / float64(w*h))- w = int(float64(w) * scale)- h = int(float64(h) * scale)- }-- // Round down to multiple of 16- w = (w / 16) * 16- h = (h / 16) * 16-- if w < 16 {- w = 16- }- if h < 16 {- h = 16- }-- // Resize using high-quality bicubic interpolation (matches diffusers' default lanczos)- resized := image.NewRGBA(image.Rect(0, 0, w, h))- draw.CatmullRom.Scale(resized, resized.Bounds(), img, img.Bounds(), draw.Over, nil)-- return resized, w, h-}--// ImageToTensor converts an image to a tensor in [-1, 1] range with shape [1, C, H, W].-func ImageToTensor(img image.Image) *mlx.Array {- bounds := img.Bounds()- w, h := bounds.Dx(), bounds.Dy()-- // Convert to float32 array in NCHW format [1, 3, H, W] with values in [-1, 1]- data := make([]float32, 3*h*w)-- for y := range h {- for x := range w {- r, g, b, _ := img.At(x+bounds.Min.X, y+bounds.Min.Y).RGBA()- // RGBA returns 16-bit values, convert to [-1, 1]- data[0*h*w+y*w+x] = float32(r>>8)/127.5 - 1.0- data[1*h*w+y*w+x] = float32(g>>8)/127.5 - 1.0- data[2*h*w+y*w+x] = float32(b>>8)/127.5 - 1.0- }- }-- arr := mlx.NewArrayFloat32(data, []int32{1, 3, int32(h), int32(w)})- return arr-}--// ImageCondTokens holds encoded reference image tokens.-type ImageCondTokens struct {- Tokens *mlx.Array // [1, total_tokens, C] - concatenated reference tokens-}--// EncodeImageRefs encodes reference images using the VAE.-func (m *Model) EncodeImageRefs(images []image.Image) (*ImageCondTokens, error) {- if len(images) == 0 {- return nil, nil- }-- // Limit reference images to reduce attention memory- limitPixels := MaxRefPixels- if len(images) > 1 {- limitPixels = MaxRefPixels / 2- }-- var allTokens []*mlx.Array-- for _, img := range images {- // Prepare image (resize, crop to multiple of 16)- prepared, prepW, prepH := PrepareImage(img, limitPixels)- fmt.Printf(" Encoding %dx%d image... ", prepW, prepH)-- // Convert to tensor [-1, 1]- tensor := ImageToTensor(prepared)-- // Encode with VAE - returns [1, L, 128]- encoded := m.VAE.EncodeImage(tensor)- squeezed := mlx.Squeeze(encoded, 0) // [L, C]-- // Defer eval - will be done with other setup arrays- allTokens = append(allTokens, squeezed)- fmt.Println("✓")- }-- // For single image, just add batch dimension directly- // For multiple images, concatenate first- var tokens *mlx.Array- if len(allTokens) == 1 {- tokens = mlx.ExpandDims(allTokens[0], 0) // [1, L, C]- } else {- tokens = mlx.Concatenate(allTokens, 0) // [total_L, C]- tokens = mlx.ExpandDims(tokens, 0) // [1, total_L, C]- }-- return &ImageCondTokens{Tokens: tokens}, nil-}diff --git a/x/imagegen/models/flux2/rope.go b/x/imagegen/models/flux2/rope.godeleted file mode 100644index 5ed009b81..000000000--- a/x/imagegen/models/flux2/rope.go+++ /dev/null@@ -1,222 +0,0 @@-package flux2--import (- "math"-- "github.com/ollama/ollama/x/imagegen/mlx"-)--// RoPEConfig holds 4D RoPE configuration for Flux2-type RoPEConfig struct {- Theta int32 // 2000 for Klein- AxesDims []int32 // [32, 32, 32, 32] - dimensions for T, H, W, L axes-}--// RoPECache holds precomputed RoPE cos/sin values-type RoPECache struct {- Cos *mlx.Array // [1, TotalSeqLen, 1, head_dim/2]- Sin *mlx.Array // [1, TotalSeqLen, 1, head_dim/2]- TextLen int32 // Length of text sequence- ImageLen int32 // Length of image sequence-}--// PrepareTextIDs creates position IDs for text tokens.-// Text tokens use: T=0, H=0, W=0, L=0..seqLen-1-// Returns: [seqLen, 4]-func PrepareTextIDs(seqLen int32) *mlx.Array {- ids := make([]float32, seqLen*4)- for i := range seqLen {- idx := i * 4- ids[idx+0] = 0 // T = 0- ids[idx+1] = 0 // H = 0- ids[idx+2] = 0 // W = 0- ids[idx+3] = float32(i) // L = sequence position- }- return mlx.NewArray(ids, []int32{seqLen, 4})-}--// PrepareLatentIDs creates position IDs for image latent tokens.-// Latent tokens use: T=0, H=0..height-1, W=0..width-1, L=0-// The latents are in row-major order (H then W).-// Returns: [height*width, 4]-func PrepareLatentIDs(height, width int32) *mlx.Array {- seqLen := height * width- ids := make([]float32, seqLen*4)- idx := 0- for h := range height {- for w := range width {- ids[idx*4+0] = 0 // T = 0- ids[idx*4+1] = float32(h) // H = row- ids[idx*4+2] = float32(w) // W = column- ids[idx*4+3] = 0 // L = 0- idx++- }- }- return mlx.NewArray(ids, []int32{seqLen, 4})-}--// PrepareImageIDs creates position IDs for reference image tokens (used in editing).-// Reference images use: T=scale*(i+1), H=0..h-1, W=0..w-1, L=0-// where i is the image index (0, 1, 2, ...) and scale separates images in T dimension.-// Returns: [total_tokens, 4]-func PrepareImageIDs(imageHeights, imageWidths []int32, scale int32) *mlx.Array {- // Calculate total tokens- totalTokens := int32(0)- for i := range imageHeights {- totalTokens += imageHeights[i] * imageWidths[i]- }-- ids := make([]float32, totalTokens*4)- idx := int32(0)- for imgIdx, h := range imageHeights {- w := imageWidths[imgIdx]- tValue := float32(scale * int32(imgIdx+1))- for hi := range h {- for wi := range w {- ids[idx*4+0] = tValue // T = scale * (imgIdx + 1)- ids[idx*4+1] = float32(hi) // H = row- ids[idx*4+2] = float32(wi) // W = column- ids[idx*4+3] = 0 // L = 0- idx++- }- }- }- return mlx.NewArray(ids, []int32{totalTokens, 4})-}--// ComputeRoPE computes cos and sin for 4D rotary position embeddings.-// ids: [L, 4] with (T, H, W, L) coordinates-// axesDims: [32, 32, 32, 32] - each axis has this many dimensions (total = head_dim = 128)-// theta: base frequency (2000 for Klein)-// Returns: cos, sin each [1, L, 1, head_dim] with repeat_interleave applied-func ComputeRoPE(ids *mlx.Array, axesDims []int32, theta int32) (*mlx.Array, *mlx.Array) {- shape := ids.Shape()- seqLen := shape[0]-- // Compute total head dim (sum of all axes dims)- headDim := int32(0)- for _, d := range axesDims {- headDim += d- }-- // Extract each coordinate dimension- // ids[:, 0] = T, ids[:, 1] = H, ids[:, 2] = W, ids[:, 3] = L- posT := mlx.Slice(ids, []int32{0, 0}, []int32{seqLen, 1}) // [L, 1]- posH := mlx.Slice(ids, []int32{0, 1}, []int32{seqLen, 2}) // [L, 1]- posW := mlx.Slice(ids, []int32{0, 2}, []int32{seqLen, 3}) // [L, 1]- posL := mlx.Slice(ids, []int32{0, 3}, []int32{seqLen, 4}) // [L, 1]-- // Compute frequencies for each axis- logTheta := float32(math.Log(float64(theta)))- cosArrs := make([]*mlx.Array, 4)- sinArrs := make([]*mlx.Array, 4)- positions := []*mlx.Array{posT, posH, posW, posL}-- for i, axisDim := range axesDims {- half := axisDim / 2-- // Create frequency array for this axis: theta^(-2j/dim) for j=0..half-1- // This matches diffusers: 1.0 / (theta ** (torch.arange(0, dim, 2) / dim))- freqs := make([]float32, half)- for j := range half {- freqs[j] = float32(math.Exp(float64(-logTheta * float32(2*j) / float32(axisDim))))- }- freqArr := mlx.NewArray(freqs, []int32{1, half})-- // Compute pos * freq -> [L, half]- posExpanded := positions[i] // [L, 1]- args := mlx.Mul(posExpanded, freqArr) // [L, half]-- // Compute cos and sin for this axis- cosAxis := mlx.Cos(args) // [L, half]- sinAxis := mlx.Sin(args) // [L, half]-- // repeat_interleave(2): [c0, c1, ...] -> [c0, c0, c1, c1, ...]- // Reshape [L, half] -> [L, half, 1], tile to [L, half, 2], reshape to [L, axisDim]- cosAxis = mlx.ExpandDims(cosAxis, 2) // [L, half, 1]- cosAxis = mlx.Tile(cosAxis, []int32{1, 1, 2}) // [L, half, 2]- cosAxis = mlx.Reshape(cosAxis, seqLen, axisDim) // [L, axisDim]-- sinAxis = mlx.ExpandDims(sinAxis, 2)- sinAxis = mlx.Tile(sinAxis, []int32{1, 1, 2})- sinAxis = mlx.Reshape(sinAxis, seqLen, axisDim)-- cosArrs[i] = cosAxis- sinArrs[i] = sinAxis- }-- // Concatenate all axes: [L, headDim]- cos := mlx.Concatenate(cosArrs, 1)- sin := mlx.Concatenate(sinArrs, 1)-- // Reshape to [1, L, 1, headDim] for broadcasting with attention- cos = mlx.Reshape(cos, 1, seqLen, 1, headDim)- sin = mlx.Reshape(sin, 1, seqLen, 1, headDim)-- return cos, sin-}--// ApplyRoPE4D applies 4D rotary position embeddings to queries and keys.-// x: [B, L, nheads, head_dim]-// cos, sin: [1, L, 1, head_dim] (with repeat_interleave applied)-// Returns: x with RoPE applied-// Matches diffusers apply_rotary_emb with use_real=True, use_real_unbind_dim=-1-func ApplyRoPE4D(x *mlx.Array, cos, sin *mlx.Array) *mlx.Array {- shape := x.Shape()- B := shape[0]- L := shape[1]- nheads := shape[2]- headDim := shape[3]- half := headDim / 2-- // Reshape x to [B, L, nheads, half, 2] and split into real/imag- xReshaped := mlx.Reshape(x, B, L, nheads, half, 2)-- // Extract real (index 0) and imag (index 1) parts- xReal := mlx.Slice(xReshaped, []int32{0, 0, 0, 0, 0}, []int32{B, L, nheads, half, 1})- xImag := mlx.Slice(xReshaped, []int32{0, 0, 0, 0, 1}, []int32{B, L, nheads, half, 2})- xReal = mlx.Squeeze(xReal, 4) // [B, L, nheads, half]- xImag = mlx.Squeeze(xImag, 4) // [B, L, nheads, half]-- // x_rotated = stack([-x_imag, x_real], dim=-1).flatten(-2)- // This creates [-x_imag[0], x_real[0], -x_imag[1], x_real[1], ...]- negXImag := mlx.Neg(xImag)- negXImag = mlx.ExpandDims(negXImag, 4) // [B, L, nheads, half, 1]- xReal = mlx.ExpandDims(xReal, 4) // [B, L, nheads, half, 1]- xRotated := mlx.Concatenate([]*mlx.Array{negXImag, xReal}, 4) // [B, L, nheads, half, 2]- xRotated = mlx.Reshape(xRotated, B, L, nheads, headDim) // [B, L, nheads, headDim]-- // out = x * cos + x_rotated * sin- return mlx.Add(mlx.Mul(x, cos), mlx.Mul(xRotated, sin))-}--// PrepareRoPECache creates RoPE cache for text + noise, optionally with reference images.-// textLen: number of text tokens-// noiseH, noiseW: dimensions of the noise latent in patch tokens-// axesDims: [32, 32, 32, 32]-// theta: 2000-// refHeights, refWidths: optional reference image dimensions (pass nil/empty for no images)-// scale: time coordinate offset between reference images (e.g., 10)-func PrepareRoPECache(textLen, noiseH, noiseW int32, axesDims []int32, theta int32, refHeights, refWidths []int32, scale int32) *RoPECache {- textIDs := PrepareTextIDs(textLen)- noiseIDs := PrepareLatentIDs(noiseH, noiseW)-- var allIDs *mlx.Array- imageLen := noiseH * noiseW-- if len(refHeights) > 0 {- refIDs := PrepareImageIDs(refHeights, refWidths, scale)- allIDs = mlx.Concatenate([]*mlx.Array{textIDs, noiseIDs, refIDs}, 0)- for i := range refHeights {- imageLen += refHeights[i] * refWidths[i]- }- } else {- allIDs = mlx.Concatenate([]*mlx.Array{textIDs, noiseIDs}, 0)- }-- cos, sin := ComputeRoPE(allIDs, axesDims, theta)- cos = mlx.ToBFloat16(cos)- sin = mlx.ToBFloat16(sin)-- return &RoPECache{Cos: cos, Sin: sin, TextLen: textLen, ImageLen: imageLen}-}diff --git a/x/imagegen/models/flux2/scheduler.go b/x/imagegen/models/flux2/scheduler.godeleted file mode 100644index f4e66113c..000000000--- a/x/imagegen/models/flux2/scheduler.go+++ /dev/null@@ -1,147 +0,0 @@-package flux2--import (- "math"-- "github.com/ollama/ollama/x/imagegen/mlx"-)--// SchedulerConfig holds Flow-Match scheduler configuration-type SchedulerConfig struct {- NumTrainTimesteps int32 `json:"num_train_timesteps"` // 1000- Shift float32 `json:"shift"` // 3.0 for Klein- UseDynamicShifting bool `json:"use_dynamic_shifting"` // true- TimeShiftType string `json:"time_shift_type"` // "exponential" or "linear"-}--// DefaultSchedulerConfig returns default config for Klein-func DefaultSchedulerConfig() *SchedulerConfig {- return &SchedulerConfig{- NumTrainTimesteps: 1000,- Shift: 3.0, // Klein uses 3.0- UseDynamicShifting: true,- TimeShiftType: "exponential",- }-}--// FlowMatchScheduler implements the Flow-Match Euler discrete scheduler-type FlowMatchScheduler struct {- Config *SchedulerConfig- Timesteps []float32 // Discretized timesteps (t from 1 to 0)- Sigmas []float32 // Noise levels at each timestep- NumSteps int // Number of inference steps-}--// NewFlowMatchScheduler creates a new scheduler-func NewFlowMatchScheduler(cfg *SchedulerConfig) *FlowMatchScheduler {- return &FlowMatchScheduler{- Config: cfg,- }-}--// SetTimesteps sets up the scheduler for the given number of inference steps-func (s *FlowMatchScheduler) SetTimesteps(numSteps int) {- s.SetTimestepsWithMu(numSteps, 0)-}--// SetTimestepsWithMu sets up scheduler matching diffusers set_timesteps(sigmas=..., mu=...)-func (s *FlowMatchScheduler) SetTimestepsWithMu(numSteps int, mu float32) {- s.NumSteps = numSteps-- // diffusers: sigmas = linspace(1, 1/num_steps, num_steps)- // Then applies time shift, appends 0.0 at end- s.Sigmas = make([]float32, numSteps+1)-- for i := range numSteps {- // linspace(1, 1/num_steps, num_steps)- var sigma float32- if numSteps == 1 {- sigma = 1.0- } else {- sigma = 1.0 - float32(i)/float32(numSteps-1)*(1.0-1.0/float32(numSteps))- }-- // Apply time shift if using dynamic shifting- if s.Config.UseDynamicShifting && mu != 0 {- sigma = s.timeShift(mu, sigma)- } else {- // If not dynamic shifting, apply fixed shift scaling like diffusers- shift := s.Config.Shift- sigma = shift * sigma / (1 + (shift-1)*sigma)- }- s.Sigmas[i] = sigma- }- // Append terminal zero- s.Sigmas[numSteps] = 0.0-- // Timesteps scaled to training range (matches diffusers: timesteps = sigmas * num_train_timesteps)- s.Timesteps = make([]float32, numSteps+1)- for i, v := range s.Sigmas {- s.Timesteps[i] = v * float32(s.Config.NumTrainTimesteps)- }-}--// timeShift applies the dynamic time shift-func (s *FlowMatchScheduler) timeShift(mu float32, t float32) float32 {- if t <= 0 {- return 0- }- if s.Config.TimeShiftType == "linear" {- return mu / (mu + (1.0/t - 1.0))- }- // Default: exponential- expMu := float32(math.Exp(float64(mu)))- return expMu / (expMu + (1.0/t - 1.0))-}--// Step performs one denoising step-func (s *FlowMatchScheduler) Step(modelOutput, sample *mlx.Array, timestepIdx int) *mlx.Array {- sigma := s.Sigmas[timestepIdx]- sigmaNext := s.Sigmas[timestepIdx+1]-- // Euler step: x_{t-dt} = x_t + (sigma_next - sigma) * v_t- dt := sigmaNext - sigma-- // Upcast to float32 for precision (matches diffusers)- sampleF32 := mlx.AsType(sample, mlx.DtypeFloat32)- outputF32 := mlx.AsType(modelOutput, mlx.DtypeFloat32)-- scaledOutput := mlx.MulScalar(outputF32, dt)- result := mlx.Add(sampleF32, scaledOutput)-- // Cast back to bfloat16- return mlx.ToBFloat16(result)-}--// GetTimestep returns the timestep value at the given index-func (s *FlowMatchScheduler) GetTimestep(idx int) float32 {- if idx < len(s.Timesteps) {- return s.Timesteps[idx]- }- return 0.0-}--// InitNoise creates initial noise for sampling-func (s *FlowMatchScheduler) InitNoise(shape []int32, seed int64) *mlx.Array {- return mlx.RandomNormalWithDtype(shape, uint64(seed), mlx.DtypeBFloat16)-}--// CalculateShift computes the mu shift value for dynamic scheduling-// Matches diffusers compute_empirical_mu function-func CalculateShift(imgSeqLen int32, numSteps int) float32 {- a1, b1 := float32(8.73809524e-05), float32(1.89833333)- a2, b2 := float32(0.00016927), float32(0.45666666)-- seqLen := float32(imgSeqLen)-- if imgSeqLen > 4300 {- return a2*seqLen + b2- }-- m200 := a2*seqLen + b2- m10 := a1*seqLen + b1-- a := (m200 - m10) / 190.0- b := m200 - 200.0*a- return a*float32(numSteps) + b-}diff --git a/x/imagegen/models/flux2/transformer.go b/x/imagegen/models/flux2/transformer.godeleted file mode 100644index ed1a233ba..000000000--- a/x/imagegen/models/flux2/transformer.go+++ /dev/null@@ -1,546 +0,0 @@-package flux2--import (- "fmt"- "math"-- "github.com/ollama/ollama/x/imagegen/manifest"- "github.com/ollama/ollama/x/imagegen/mlx"- "github.com/ollama/ollama/x/imagegen/nn"- "github.com/ollama/ollama/x/imagegen/safetensors"-)--// TransformerConfig holds Flux2 transformer configuration-type TransformerConfig struct {- AttentionHeadDim int32 `json:"attention_head_dim"` // 128- AxesDimsRoPE []int32 `json:"axes_dims_rope"` // [32, 32, 32, 32]- Eps float32 `json:"eps"` // 1e-6- GuidanceEmbeds bool `json:"guidance_embeds"` // false for Klein- InChannels int32 `json:"in_channels"` // 128- JointAttentionDim int32 `json:"joint_attention_dim"` // 7680- MLPRatio float32 `json:"mlp_ratio"` // 3.0- NumAttentionHeads int32 `json:"num_attention_heads"` // 24- NumLayers int32 `json:"num_layers"` // 5- NumSingleLayers int32 `json:"num_single_layers"` // 20- PatchSize int32 `json:"patch_size"` // 1- RopeTheta int32 `json:"rope_theta"` // 2000- TimestepGuidanceChannels int32 `json:"timestep_guidance_channels"` // 256-}--// Computed dimensions-func (c *TransformerConfig) InnerDim() int32 {- return c.NumAttentionHeads * c.AttentionHeadDim // 24 * 128 = 3072-}--func (c *TransformerConfig) MLPHiddenDim() int32 {- return int32(float32(c.InnerDim()) * c.MLPRatio) // 3072 * 3.0 = 9216-}--// TimestepEmbedder creates timestep embeddings-// Weight names: time_guidance_embed.timestep_embedder.linear_1.weight, linear_2.weight-type TimestepEmbedder struct {- Linear1 nn.LinearLayer `weight:"linear_1"`- Linear2 nn.LinearLayer `weight:"linear_2"`- EmbedDim int32 // 256-}--// Forward creates sinusoidal embeddings and projects them-func (t *TimestepEmbedder) Forward(timesteps *mlx.Array) *mlx.Array {- half := t.EmbedDim / 2- freqs := make([]float32, half)- for i := range half {- freqs[i] = float32(math.Exp(-math.Log(10000.0) * float64(i) / float64(half)))- }- freqsArr := mlx.NewArray(freqs, []int32{1, half})-- // timesteps: [B] -> [B, 1]- tExpanded := mlx.ExpandDims(timesteps, 1)- // args: [B, half]- args := mlx.Mul(tExpanded, freqsArr)-- // [cos(args), sin(args)] -> [B, embed_dim]- sinEmbed := mlx.Concatenate([]*mlx.Array{mlx.Cos(args), mlx.Sin(args)}, 1)-- // MLP: linear_1 -> silu -> linear_2- h := t.Linear1.Forward(sinEmbed)- h = mlx.SiLU(h)- return t.Linear2.Forward(h)-}--// TimeGuidanceEmbed wraps the timestep embedder-// Weight names: time_guidance_embed.timestep_embedder.*-type TimeGuidanceEmbed struct {- TimestepEmbedder *TimestepEmbedder `weight:"timestep_embedder"`-}--// Forward computes timestep embeddings-func (t *TimeGuidanceEmbed) Forward(timesteps *mlx.Array) *mlx.Array {- return t.TimestepEmbedder.Forward(timesteps)-}--// Modulation computes adaptive modulation parameters-// Weight names: double_stream_modulation_img.linear.weight, etc.-type Modulation struct {- Linear nn.LinearLayer `weight:"linear"`-}--// Forward computes modulation parameters-func (m *Modulation) Forward(temb *mlx.Array) *mlx.Array {- h := mlx.SiLU(temb)- return m.Linear.Forward(h)-}--// TransformerBlockAttn implements dual-stream attention-// Weight names: transformer_blocks.N.attn.*-type TransformerBlockAttn struct {- // Image stream (separate Q, K, V projections)- ToQ nn.LinearLayer `weight:"to_q"`- ToK nn.LinearLayer `weight:"to_k"`- ToV nn.LinearLayer `weight:"to_v"`- // Note: to_out has .0 suffix in weights, handled specially- ToOut0 nn.LinearLayer `weight:"to_out.0"`-- // Text stream (add_ projections)- AddQProj nn.LinearLayer `weight:"add_q_proj"`- AddKProj nn.LinearLayer `weight:"add_k_proj"`- AddVProj nn.LinearLayer `weight:"add_v_proj"`- ToAddOut nn.LinearLayer `weight:"to_add_out"`-- // QK norms for image stream- NormQ *mlx.Array `weight:"norm_q.weight"`- NormK *mlx.Array `weight:"norm_k.weight"`-- // QK norms for text stream (added)- NormAddedQ *mlx.Array `weight:"norm_added_q.weight"`- NormAddedK *mlx.Array `weight:"norm_added_k.weight"`-}--// FeedForward implements SwiGLU MLP-// Weight names: transformer_blocks.N.ff.linear_in.weight, linear_out.weight-type FeedForward struct {- LinearIn nn.LinearLayer `weight:"linear_in"`- LinearOut nn.LinearLayer `weight:"linear_out"`-}--// Forward applies SwiGLU MLP-func (ff *FeedForward) Forward(x *mlx.Array) *mlx.Array {- // LinearIn outputs 2x hidden dim for SwiGLU- h := ff.LinearIn.Forward(x)- shape := h.Shape()- half := shape[len(shape)-1] / 2-- // Split into gate and up- gate := mlx.Slice(h, []int32{0, 0, 0}, []int32{shape[0], shape[1], half})- up := mlx.Slice(h, []int32{0, 0, half}, []int32{shape[0], shape[1], shape[2]})-- // SwiGLU: silu(gate) * up- h = mlx.Mul(mlx.SiLU(gate), up)- return ff.LinearOut.Forward(h)-}--// TransformerBlock implements a dual-stream transformer block-// Weight names: transformer_blocks.N.*-type TransformerBlock struct {- Attn *TransformerBlockAttn `weight:"attn"`- FF *FeedForward `weight:"ff"`- FFContext *FeedForward `weight:"ff_context"`-- // Config (set after loading)- NHeads int32- HeadDim int32- Scale float32-}--// Forward applies the dual-stream block-// imgHidden: [B, imgLen, dim]-// txtHidden: [B, txtLen, dim]-// imgMod, txtMod: modulation params [B, 6*dim] each-// cos, sin: RoPE values-func (block *TransformerBlock) Forward(imgHidden, txtHidden *mlx.Array, imgMod, txtMod *mlx.Array, cos, sin *mlx.Array) (*mlx.Array, *mlx.Array) {- imgShape := imgHidden.Shape()- B := imgShape[0]- imgLen := imgShape[1]- dim := imgShape[2]- txtLen := txtHidden.Shape()[1]-- // Parse modulation: 6 params each (shift1, scale1, gate1, shift2, scale2, gate2)- imgShift1, imgScale1, imgGate1 := parseModulation3(imgMod, dim, 0)- imgShift2, imgScale2, imgGate2 := parseModulation3(imgMod, dim, 3)- txtShift1, txtScale1, txtGate1 := parseModulation3(txtMod, dim, 0)- txtShift2, txtScale2, txtGate2 := parseModulation3(txtMod, dim, 3)-- // === Attention branch ===- // Modulate inputs- imgNorm := modulateLayerNorm(imgHidden, imgShift1, imgScale1)- txtNorm := modulateLayerNorm(txtHidden, txtShift1, txtScale1)-- // Compute Q, K, V for image stream (separate projections)- imgQ := block.Attn.ToQ.Forward(imgNorm)- imgK := block.Attn.ToK.Forward(imgNorm)- imgV := block.Attn.ToV.Forward(imgNorm)-- // Compute Q, K, V for text stream (add_ projections)- txtQ := block.Attn.AddQProj.Forward(txtNorm)- txtK := block.Attn.AddKProj.Forward(txtNorm)- txtV := block.Attn.AddVProj.Forward(txtNorm)-- // Reshape for attention: [B, L, dim] -> [B, L, nheads, headDim]- imgQ = mlx.Reshape(imgQ, B, imgLen, block.NHeads, block.HeadDim)- imgK = mlx.Reshape(imgK, B, imgLen, block.NHeads, block.HeadDim)- imgV = mlx.Reshape(imgV, B, imgLen, block.NHeads, block.HeadDim)- txtQ = mlx.Reshape(txtQ, B, txtLen, block.NHeads, block.HeadDim)- txtK = mlx.Reshape(txtK, B, txtLen, block.NHeads, block.HeadDim)- txtV = mlx.Reshape(txtV, B, txtLen, block.NHeads, block.HeadDim)-- // Apply QK norm (RMSNorm with learned scale)- imgQ = applyQKNorm(imgQ, block.Attn.NormQ)- imgK = applyQKNorm(imgK, block.Attn.NormK)- txtQ = applyQKNorm(txtQ, block.Attn.NormAddedQ)- txtK = applyQKNorm(txtK, block.Attn.NormAddedK)-- // Concatenate for joint attention: text first, then image- q := mlx.Concatenate([]*mlx.Array{txtQ, imgQ}, 1)- k := mlx.Concatenate([]*mlx.Array{txtK, imgK}, 1)- v := mlx.Concatenate([]*mlx.Array{txtV, imgV}, 1)-- // Apply RoPE- q = ApplyRoPE4D(q, cos, sin)- k = ApplyRoPE4D(k, cos, sin)-- // Transpose for SDPA: [B, nheads, L, headDim]- q = mlx.Transpose(q, 0, 2, 1, 3)- k = mlx.Transpose(k, 0, 2, 1, 3)- v = mlx.Transpose(v, 0, 2, 1, 3)-- // Scaled dot-product attention- out := mlx.ScaledDotProductAttention(q, k, v, block.Scale, false)-- // Transpose back: [B, L, nheads, headDim]- out = mlx.Transpose(out, 0, 2, 1, 3)-- // Split back into txt and img- totalLen := txtLen + imgLen- txtOut := mlx.Slice(out, []int32{0, 0, 0, 0}, []int32{B, txtLen, block.NHeads, block.HeadDim})- imgOut := mlx.Slice(out, []int32{0, txtLen, 0, 0}, []int32{B, totalLen, block.NHeads, block.HeadDim})-- // Reshape and project- txtOut = mlx.Reshape(txtOut, B, txtLen, dim)- imgOut = mlx.Reshape(imgOut, B, imgLen, dim)- txtOut = block.Attn.ToAddOut.Forward(txtOut)- imgOut = block.Attn.ToOut0.Forward(imgOut)-- // Apply gates and residual- imgHidden = mlx.Add(imgHidden, mlx.Mul(imgGate1, imgOut))- txtHidden = mlx.Add(txtHidden, mlx.Mul(txtGate1, txtOut))-- // === MLP branch ===- imgNorm = modulateLayerNorm(imgHidden, imgShift2, imgScale2)- txtNorm = modulateLayerNorm(txtHidden, txtShift2, txtScale2)-- imgFFOut := block.FF.Forward(imgNorm)- txtFFOut := block.FFContext.Forward(txtNorm)-- imgHidden = mlx.Add(imgHidden, mlx.Mul(imgGate2, imgFFOut))- txtHidden = mlx.Add(txtHidden, mlx.Mul(txtGate2, txtFFOut))-- return imgHidden, txtHidden-}--// SingleTransformerBlockAttn implements attention for single-stream blocks-// Weight names: single_transformer_blocks.N.attn.*-type SingleTransformerBlockAttn struct {- ToQKVMlpProj nn.LinearLayer `weight:"to_qkv_mlp_proj"` // Fused QKV + MLP input- ToOut nn.LinearLayer `weight:"to_out"` // Fused attn_out + MLP out- NormQ *mlx.Array `weight:"norm_q.weight"`- NormK *mlx.Array `weight:"norm_k.weight"`-}--// SingleTransformerBlock implements a single-stream transformer block-// Weight names: single_transformer_blocks.N.*-type SingleTransformerBlock struct {- Attn *SingleTransformerBlockAttn `weight:"attn"`-- // Config- NHeads int32- HeadDim int32- InnerDim int32- MLPHidDim int32- Scale float32-}--// Forward applies the single-stream block-// x: [B, L, dim] concatenated text+image-// mod: modulation [B, 3*dim]-func (block *SingleTransformerBlock) Forward(x *mlx.Array, mod *mlx.Array, cos, sin *mlx.Array) *mlx.Array {- shape := x.Shape()- B := shape[0]- L := shape[1]- dim := shape[2]-- // Parse modulation: (shift, scale, gate)- shift, scale, gate := parseModulation3(mod, dim, 0)-- // Modulate input- h := modulateLayerNorm(x, shift, scale)-- // Fused projection: QKV + MLP gate/up- // linear1 outputs: [q, k, v, mlp_gate, mlp_up] = [dim, dim, dim, mlpHid, mlpHid]- qkvMlp := block.Attn.ToQKVMlpProj.Forward(h)-- // Split: first 3*dim is QKV, rest is MLP- qkvDim := 3 * block.InnerDim- qkv := mlx.Slice(qkvMlp, []int32{0, 0, 0}, []int32{B, L, qkvDim})- mlpIn := mlx.Slice(qkvMlp, []int32{0, 0, qkvDim}, []int32{B, L, qkvMlp.Shape()[2]})-- // Split QKV- q, k, v := splitQKV(qkv, B, L, block.InnerDim)-- // Reshape for attention- q = mlx.Reshape(q, B, L, block.NHeads, block.HeadDim)- k = mlx.Reshape(k, B, L, block.NHeads, block.HeadDim)- v = mlx.Reshape(v, B, L, block.NHeads, block.HeadDim)-- // QK norm- q = applyQKNorm(q, block.Attn.NormQ)- k = applyQKNorm(k, block.Attn.NormK)-- // Apply RoPE- q = ApplyRoPE4D(q, cos, sin)- k = ApplyRoPE4D(k, cos, sin)-- // Transpose for SDPA- q = mlx.Transpose(q, 0, 2, 1, 3)- k = mlx.Transpose(k, 0, 2, 1, 3)- v = mlx.Transpose(v, 0, 2, 1, 3)-- // SDPA- attnOut := mlx.ScaledDotProductAttention(q, k, v, block.Scale, false)-- // Transpose back and reshape- attnOut = mlx.Transpose(attnOut, 0, 2, 1, 3)- attnOut = mlx.Reshape(attnOut, B, L, block.InnerDim)-- // MLP: SwiGLU- mlpShape := mlpIn.Shape()- half := mlpShape[2] / 2- mlpGate := mlx.Slice(mlpIn, []int32{0, 0, 0}, []int32{B, L, half})- mlpUp := mlx.Slice(mlpIn, []int32{0, 0, half}, []int32{B, L, mlpShape[2]})- mlpOut := mlx.Mul(mlx.SiLU(mlpGate), mlpUp)-- // Concatenate attention and MLP for fused output- combined := mlx.Concatenate([]*mlx.Array{attnOut, mlpOut}, 2)-- // Output projection- out := block.Attn.ToOut.Forward(combined)-- // Apply gate and residual- return mlx.Add(x, mlx.Mul(gate, out))-}--// NormOut implements the output normalization with modulation-// Weight names: norm_out.linear.weight-type NormOut struct {- Linear nn.LinearLayer `weight:"linear"`-}--// Forward computes final modulated output-func (n *NormOut) Forward(x *mlx.Array, temb *mlx.Array) *mlx.Array {- shape := x.Shape()- B := shape[0]- dim := shape[2]-- // Modulation: temb -> silu -> linear -> [shift, scale]- mod := mlx.SiLU(temb)- mod = n.Linear.Forward(mod)-- // Split into scale and shift (diffusers order: scale first, shift second)- scale := mlx.Slice(mod, []int32{0, 0}, []int32{B, dim})- shift := mlx.Slice(mod, []int32{0, dim}, []int32{B, 2 * dim})- shift = mlx.ExpandDims(shift, 1)- scale = mlx.ExpandDims(scale, 1)-- // Modulate with RMSNorm- return modulateLayerNorm(x, shift, scale)-}--// Flux2Transformer2DModel is the main Flux2 transformer-// Weight names at top level: time_guidance_embed.*, double_stream_modulation_*.*, etc.-type Flux2Transformer2DModel struct {- // Timestep embedding- TimeGuidanceEmbed *TimeGuidanceEmbed `weight:"time_guidance_embed"`-- // Shared modulation- DoubleStreamModulationImg *Modulation `weight:"double_stream_modulation_img"`- DoubleStreamModulationTxt *Modulation `weight:"double_stream_modulation_txt"`- SingleStreamModulation *Modulation `weight:"single_stream_modulation"`-- // Embedders- XEmbedder nn.LinearLayer `weight:"x_embedder"`- ContextEmbedder nn.LinearLayer `weight:"context_embedder"`-- // Transformer blocks- TransformerBlocks []*TransformerBlock `weight:"transformer_blocks"`- SingleTransformerBlocks []*SingleTransformerBlock `weight:"single_transformer_blocks"`-- // Output- NormOut *NormOut `weight:"norm_out"`- ProjOut nn.LinearLayer `weight:"proj_out"`-- *TransformerConfig-}--// Load loads the Flux2 transformer from ollama blob storage.-func (m *Flux2Transformer2DModel) Load(modelManifest *manifest.ModelManifest) error {- fmt.Print(" Loading transformer... ")-- // Load config from blob- var cfg TransformerConfig- if err := modelManifest.ReadConfigJSON("transformer/config.json", &cfg); err != nil {- return fmt.Errorf("config: %w", err)- }- m.TransformerConfig = &cfg-- // Initialize slices- m.TransformerBlocks = make([]*TransformerBlock, cfg.NumLayers)- m.SingleTransformerBlocks = make([]*SingleTransformerBlock, cfg.NumSingleLayers)-- // Initialize TimeGuidanceEmbed with embed dim- m.TimeGuidanceEmbed = &TimeGuidanceEmbed{- TimestepEmbedder: &TimestepEmbedder{EmbedDim: cfg.TimestepGuidanceChannels},- }-- // Load weights from tensor blobs- weights, err := manifest.LoadWeightsFromManifest(modelManifest, "transformer")- if err != nil {- return fmt.Errorf("weights: %w", err)- }- if err := weights.Load(0); err != nil {- return fmt.Errorf("load weights: %w", err)- }- defer weights.ReleaseAll()-- return m.loadWeights(weights)-}--// loadWeights loads weights from any WeightSource into the model-func (m *Flux2Transformer2DModel) loadWeights(weights safetensors.WeightSource) error {- if err := safetensors.LoadModule(m, weights, ""); err != nil {- return fmt.Errorf("load module: %w", err)- }- m.initComputedFields()- fmt.Println("✓")- return nil-}--// initComputedFields initializes computed fields after loading weights-func (m *Flux2Transformer2DModel) initComputedFields() {- cfg := m.TransformerConfig- innerDim := cfg.InnerDim()- scale := float32(1.0 / math.Sqrt(float64(cfg.AttentionHeadDim)))-- // Initialize transformer blocks- for _, block := range m.TransformerBlocks {- block.NHeads = cfg.NumAttentionHeads- block.HeadDim = cfg.AttentionHeadDim- block.Scale = scale- }-- // Initialize single transformer blocks- for _, block := range m.SingleTransformerBlocks {- block.NHeads = cfg.NumAttentionHeads- block.HeadDim = cfg.AttentionHeadDim- block.InnerDim = innerDim- block.MLPHidDim = cfg.MLPHiddenDim()- block.Scale = scale- }-}--// Forward runs the Flux2 transformer-func (m *Flux2Transformer2DModel) Forward(patches, txtEmbeds *mlx.Array, timesteps *mlx.Array, rope *RoPECache) *mlx.Array {- patchShape := patches.Shape()- B := patchShape[0]- imgLen := patchShape[1]- txtLen := txtEmbeds.Shape()[1]-- // Scale timestep to 0-1000 range (diffusers multiplies by 1000)- scaledTimesteps := mlx.MulScalar(timesteps, 1000.0)-- // Compute timestep embedding- temb := m.TimeGuidanceEmbed.Forward(scaledTimesteps)-- // Embed patches and text- imgHidden := m.XEmbedder.Forward(patches)- txtHidden := m.ContextEmbedder.Forward(txtEmbeds)-- // Compute shared modulation- imgMod := m.DoubleStreamModulationImg.Forward(temb)- txtMod := m.DoubleStreamModulationTxt.Forward(temb)- singleMod := m.SingleStreamModulation.Forward(temb)-- // Double (dual-stream) blocks- for _, block := range m.TransformerBlocks {- imgHidden, txtHidden = block.Forward(imgHidden, txtHidden, imgMod, txtMod, rope.Cos, rope.Sin)- }-- // Concatenate for single-stream: text first, then image- hidden := mlx.Concatenate([]*mlx.Array{txtHidden, imgHidden}, 1)-- // Single-stream blocks- for _, block := range m.SingleTransformerBlocks {- hidden = block.Forward(hidden, singleMod, rope.Cos, rope.Sin)- }-- // Extract image portion- totalLen := txtLen + imgLen- imgOut := mlx.Slice(hidden, []int32{0, txtLen, 0}, []int32{B, totalLen, hidden.Shape()[2]})-- // Final norm and projection- imgOut = m.NormOut.Forward(imgOut, temb)- return m.ProjOut.Forward(imgOut)-}--// Note: QK normalization uses mlx.RMSNorm (the fast version) directly-// See applyQKNorm function below--// Helper functions--// parseModulation3 extracts 3 modulation params (shift, scale, gate) starting at offset-func parseModulation3(mod *mlx.Array, dim int32, offset int32) (*mlx.Array, *mlx.Array, *mlx.Array) {- B := mod.Shape()[0]- start := offset * dim- shift := mlx.Slice(mod, []int32{0, start}, []int32{B, start + dim})- scale := mlx.Slice(mod, []int32{0, start + dim}, []int32{B, start + 2*dim})- gate := mlx.Slice(mod, []int32{0, start + 2*dim}, []int32{B, start + 3*dim})-- // Expand for broadcasting [B, dim] -> [B, 1, dim]- shift = mlx.ExpandDims(shift, 1)- scale = mlx.ExpandDims(scale, 1)- gate = mlx.ExpandDims(gate, 1)-- return shift, scale, gate-}--// modulateLayerNorm applies LayerNorm then shift/scale modulation-// Diffusers uses LayerNorm(elementwise_affine=False) which centers the data-func modulateLayerNorm(x *mlx.Array, shift, scale *mlx.Array) *mlx.Array {- // Fast LayerNorm without learnable params- x = mlx.LayerNorm(x, 1e-6)-- // Modulate: x * (1 + scale) + shift- x = mlx.Mul(x, mlx.AddScalar(scale, 1.0))- return mlx.Add(x, shift)-}--// splitQKV splits a fused QKV tensor into Q, K, V-func splitQKV(qkv *mlx.Array, B, L, dim int32) (*mlx.Array, *mlx.Array, *mlx.Array) {- q := mlx.Slice(qkv, []int32{0, 0, 0}, []int32{B, L, dim})- k := mlx.Slice(qkv, []int32{0, 0, dim}, []int32{B, L, 2 * dim})- v := mlx.Slice(qkv, []int32{0, 0, 2 * dim}, []int32{B, L, 3 * dim})- return q, k, v-}--// applyQKNorm applies RMSNorm with learned scale (no bias)-// Uses the optimized mlx_fast_rms_norm-func applyQKNorm(x *mlx.Array, scale *mlx.Array) *mlx.Array {- return mlx.RMSNorm(x, scale, 1e-6)-}diff --git a/x/imagegen/models/flux2/vae.go b/x/imagegen/models/flux2/vae.godeleted file mode 100644index c29788af9..000000000--- a/x/imagegen/models/flux2/vae.go+++ /dev/null@@ -1,802 +0,0 @@-package flux2--import (- "fmt"- "math"-- "github.com/ollama/ollama/x/imagegen/manifest"- "github.com/ollama/ollama/x/imagegen/mlx"- "github.com/ollama/ollama/x/imagegen/nn"- "github.com/ollama/ollama/x/imagegen/safetensors"- "github.com/ollama/ollama/x/imagegen/vae"-)--// VAEConfig holds AutoencoderKLFlux2 configuration-type VAEConfig struct {- ActFn string `json:"act_fn"` // "silu"- BatchNormEps float32 `json:"batch_norm_eps"` // 0.0001- BatchNormMomentum float32 `json:"batch_norm_momentum"` // 0.1- BlockOutChannels []int32 `json:"block_out_channels"` // [128, 256, 512, 512]- ForceUpcast bool `json:"force_upcast"` // true- InChannels int32 `json:"in_channels"` // 3- LatentChannels int32 `json:"latent_channels"` // 32- LayersPerBlock int32 `json:"layers_per_block"` // 2- MidBlockAddAttn bool `json:"mid_block_add_attention"` // true- NormNumGroups int32 `json:"norm_num_groups"` // 32- OutChannels int32 `json:"out_channels"` // 3- PatchSize []int32 `json:"patch_size"` // [2, 2]- SampleSize int32 `json:"sample_size"` // 1024- UsePostQuantConv bool `json:"use_post_quant_conv"` // true- UseQuantConv bool `json:"use_quant_conv"` // true-}--// BatchNorm2D implements 2D batch normalization with running statistics-type BatchNorm2D struct {- RunningMean *mlx.Array // [C]- RunningVar *mlx.Array // [C]- Weight *mlx.Array // [C] gamma- Bias *mlx.Array // [C] beta- Eps float32- Momentum float32-}--// Forward applies batch normalization (inference mode - uses running stats)-// Input and output are in NHWC format [B, H, W, C]-func (bn *BatchNorm2D) Forward(x *mlx.Array) *mlx.Array {- shape := x.Shape()- C := shape[3]-- // Reshape stats for broadcasting [1, 1, 1, C]- mean := mlx.Reshape(bn.RunningMean, 1, 1, 1, C)- variance := mlx.Reshape(bn.RunningVar, 1, 1, 1, C)-- // Normalize: (x - mean) / sqrt(var + eps)- xNorm := mlx.Sub(x, mean)- xNorm = mlx.Div(xNorm, mlx.Sqrt(mlx.AddScalar(variance, bn.Eps)))-- // Scale and shift (only if affine=True)- if bn.Weight != nil {- weight := mlx.Reshape(bn.Weight, 1, 1, 1, C)- xNorm = mlx.Mul(xNorm, weight)- }- if bn.Bias != nil {- bias := mlx.Reshape(bn.Bias, 1, 1, 1, C)- xNorm = mlx.Add(xNorm, bias)- }-- return xNorm-}--// Denormalize inverts the batch normalization-// Used when decoding latents-func (bn *BatchNorm2D) Denormalize(x *mlx.Array) *mlx.Array {- shape := x.Shape()- C := shape[3]-- // Reshape stats for broadcasting [1, 1, 1, C]- mean := mlx.Reshape(bn.RunningMean, 1, 1, 1, C)- variance := mlx.Reshape(bn.RunningVar, 1, 1, 1, C)-- // Inverse: first undo affine, then undo normalization- // For affine=False: x_denorm = x * sqrt(var + eps) + mean- if bn.Bias != nil {- bias := mlx.Reshape(bn.Bias, 1, 1, 1, C)- x = mlx.Sub(x, bias)- }- if bn.Weight != nil {- weight := mlx.Reshape(bn.Weight, 1, 1, 1, C)- x = mlx.Div(x, weight)- }- x = mlx.Mul(x, mlx.Sqrt(mlx.AddScalar(variance, bn.Eps)))- x = mlx.Add(x, mean)-- return x-}--// GroupNormLayer implements group normalization-// Reused from zimage package pattern-type GroupNormLayer struct {- Weight *mlx.Array `weight:"weight"`- Bias *mlx.Array `weight:"bias"`- NumGroups int32- Eps float32-}--// Forward applies group normalization-// Input and output are in NHWC format [B, H, W, C]-func (gn *GroupNormLayer) Forward(x *mlx.Array) *mlx.Array {- shape := x.Shape()- B := shape[0]- H := shape[1]- W := shape[2]- C := shape[3]-- // Reshape to [B, H, W, groups, C/groups]- groupSize := C / gn.NumGroups- x = mlx.Reshape(x, B, H, W, gn.NumGroups, groupSize)-- // Compute mean and variance per group- mean := mlx.Mean(x, 1, true)- mean = mlx.Mean(mean, 2, true)- mean = mlx.Mean(mean, 4, true)-- xCentered := mlx.Sub(x, mean)-- sq := mlx.Square(xCentered)- variance := mlx.Mean(sq, 1, true)- variance = mlx.Mean(variance, 2, true)- variance = mlx.Mean(variance, 4, true)-- // Normalize- xNorm := mlx.Div(xCentered, mlx.Sqrt(mlx.AddScalar(variance, gn.Eps)))-- // Reshape back to [B, H, W, C]- xNorm = mlx.Reshape(xNorm, B, H, W, C)-- // Scale and shift- if gn.Weight != nil {- weight := mlx.Reshape(gn.Weight, 1, 1, 1, C)- xNorm = mlx.Mul(xNorm, weight)- }- if gn.Bias != nil {- bias := mlx.Reshape(gn.Bias, 1, 1, 1, C)- xNorm = mlx.Add(xNorm, bias)- }-- return xNorm-}--// Conv2D represents a 2D convolution layer (reused pattern)-type Conv2D struct {- Weight *mlx.Array `weight:"weight"`- Bias *mlx.Array `weight:"bias,optional"`- Stride int32- Padding int32-}--// Transform implements safetensors.Transformer to transpose weights from PyTorch's OIHW to MLX's OHWI.-func (conv *Conv2D) Transform(field string, arr *mlx.Array) *mlx.Array {- if field == "Weight" {- return mlx.Transpose(arr, 0, 2, 3, 1)- }- return arr-}--// Forward applies convolution (NHWC format)-func (conv *Conv2D) Forward(x *mlx.Array) *mlx.Array {- out := mlx.Conv2d(x, conv.Weight, conv.Stride, conv.Padding)-- if conv.Bias != nil {- bias := mlx.Reshape(conv.Bias, 1, 1, 1, conv.Bias.Dim(0))- out = mlx.Add(out, bias)- }-- return out-}--// ResnetBlock2D implements a ResNet block for VAE-type ResnetBlock2D struct {- Norm1 *GroupNormLayer `weight:"norm1"`- Conv1 *Conv2D `weight:"conv1"`- Norm2 *GroupNormLayer `weight:"norm2"`- Conv2 *Conv2D `weight:"conv2"`- ConvShortcut *Conv2D `weight:"conv_shortcut,optional"`-}--// Forward applies the ResNet block-func (rb *ResnetBlock2D) Forward(x *mlx.Array) *mlx.Array {- h := rb.Norm1.Forward(x)- h = mlx.SiLU(h)- h = rb.Conv1.Forward(h)-- h = rb.Norm2.Forward(h)- h = mlx.SiLU(h)- h = rb.Conv2.Forward(h)-- if rb.ConvShortcut != nil {- x = rb.ConvShortcut.Forward(x)- }-- return mlx.Add(h, x)-}--// VAEAttentionBlock implements self-attention for VAE-type VAEAttentionBlock struct {- GroupNorm *GroupNormLayer `weight:"group_norm"`- ToQ nn.LinearLayer `weight:"to_q"`- ToK nn.LinearLayer `weight:"to_k"`- ToV nn.LinearLayer `weight:"to_v"`- ToOut nn.LinearLayer `weight:"to_out.0"`-}--// Forward applies attention (NHWC format)-func (ab *VAEAttentionBlock) Forward(x *mlx.Array) *mlx.Array {- residual := x- shape := x.Shape()- B := shape[0]- H := shape[1]- W := shape[2]- C := shape[3]-- h := ab.GroupNorm.Forward(x)- h = mlx.Reshape(h, B, H*W, C)-- q := ab.ToQ.Forward(h)- k := ab.ToK.Forward(h)- v := ab.ToV.Forward(h)-- q = mlx.ExpandDims(q, 1)- k = mlx.ExpandDims(k, 1)- v = mlx.ExpandDims(v, 1)-- scale := float32(1.0 / math.Sqrt(float64(C)))- out := mlx.ScaledDotProductAttention(q, k, v, scale, false)- out = mlx.Squeeze(out, 1)-- out = ab.ToOut.Forward(out)- out = mlx.Reshape(out, B, H, W, C)- out = mlx.Add(out, residual)-- return out-}--// UpDecoderBlock2D implements an upsampling decoder block-type UpDecoderBlock2D struct {- ResnetBlocks []*ResnetBlock2D- Upsample *Conv2D-}--// Forward applies the up decoder block-func (ub *UpDecoderBlock2D) Forward(x *mlx.Array) *mlx.Array {- for _, resnet := range ub.ResnetBlocks {- x = resnet.Forward(x)- }-- if ub.Upsample != nil {- x = upsample2x(x)- x = ub.Upsample.Forward(x)- }-- return x-}--// upsample2x performs 2x nearest neighbor upsampling-func upsample2x(x *mlx.Array) *mlx.Array {- shape := x.Shape()- H := shape[1]- W := shape[2]-- hIdx := mlx.ArangeInt(0, H, 1, mlx.DtypeInt32)- hIdx = mlx.Reshape(hIdx, H, 1)- hIdx = mlx.BroadcastTo(hIdx, []int32{H, 2})- hIdx = mlx.Reshape(hIdx, H*2)-- wIdx := mlx.ArangeInt(0, W, 1, mlx.DtypeInt32)- wIdx = mlx.Reshape(wIdx, W, 1)- wIdx = mlx.BroadcastTo(wIdx, []int32{W, 2})- wIdx = mlx.Reshape(wIdx, W*2)-- x = mlx.Take(x, hIdx, 1)- x = mlx.Take(x, wIdx, 2)-- return x-}--// VAEMidBlock is the middle block with attention-type VAEMidBlock struct {- Resnet1 *ResnetBlock2D- Attention *VAEAttentionBlock- Resnet2 *ResnetBlock2D-}--// Forward applies the mid block-func (mb *VAEMidBlock) Forward(x *mlx.Array) *mlx.Array {- x = mb.Resnet1.Forward(x)- x = mb.Attention.Forward(x)- x = mb.Resnet2.Forward(x)- return x-}--// DefaultTilingConfig returns reasonable defaults for tiled decoding-// Matches diffusers: tile_latent_min_size=64, tile_overlap_factor=0.25-func DefaultTilingConfig() *vae.TilingConfig {- return vae.DefaultTilingConfig()-}--// AutoencoderKLFlux2 is the Flux2 VAE with BatchNorm-type AutoencoderKLFlux2 struct {- Config *VAEConfig-- // Encoder components (for image editing)- EncoderConvIn *Conv2D- EncoderMid *VAEMidBlock- EncoderDown []*DownEncoderBlock2D- EncoderNormOut *GroupNormLayer- EncoderConvOut *Conv2D-- // Decoder components- DecoderConvIn *Conv2D- DecoderMid *VAEMidBlock- DecoderUp []*UpDecoderBlock2D- DecoderNormOut *GroupNormLayer- DecoderConvOut *Conv2D-- // Quant conv layers- QuantConv *Conv2D- PostQuantConv *Conv2D-- // BatchNorm for latent normalization- LatentBN *BatchNorm2D-- // Tiling configuration (nil = no tiling)- Tiling *vae.TilingConfig-}--// DownEncoderBlock2D implements a downsampling encoder block-type DownEncoderBlock2D struct {- ResnetBlocks []*ResnetBlock2D- Downsample *Conv2D-}--// Forward applies the down encoder block-func (db *DownEncoderBlock2D) Forward(x *mlx.Array) *mlx.Array {- for _, resnet := range db.ResnetBlocks {- x = resnet.Forward(x)- }-- if db.Downsample != nil {- // Pad then conv with stride 2- x = mlx.Pad(x, []int32{0, 0, 0, 1, 0, 1, 0, 0})- x = db.Downsample.Forward(x)- }-- return x-}--// Load loads the Flux2 VAE from ollama blob storage.-func (m *AutoencoderKLFlux2) Load(modelManifest *manifest.ModelManifest) error {- fmt.Print(" Loading VAE... ")-- // Load config from blob- var cfg VAEConfig- if err := modelManifest.ReadConfigJSON("vae/config.json", &cfg); err != nil {- return fmt.Errorf("config: %w", err)- }- m.Config = &cfg-- // Load weights from tensor blobs- weights, err := manifest.LoadWeightsFromManifest(modelManifest, "vae")- if err != nil {- return fmt.Errorf("weights: %w", err)- }- if err := weights.Load(0); err != nil {- return fmt.Errorf("load weights: %w", err)- }- defer weights.ReleaseAll()-- return m.loadWeights(weights, &cfg)-}--// loadWeights loads VAE weights from any WeightSource-func (m *AutoencoderKLFlux2) loadWeights(weights safetensors.WeightSource, cfg *VAEConfig) error {- var err error-- // Load encoder components (for image conditioning)- if err := m.loadEncoderWeights(weights, cfg); err != nil {- return fmt.Errorf("encoder: %w", err)- }-- // Load decoder conv_in- m.DecoderConvIn = &Conv2D{Stride: 1, Padding: 1}- if err := safetensors.LoadModule(m.DecoderConvIn, weights, "decoder.conv_in"); err != nil {- return fmt.Errorf("decoder.conv_in: %w", err)- }-- // Load mid block- m.DecoderMid, err = loadVAEMidBlock(weights, "decoder.mid_block", cfg.NormNumGroups)- if err != nil {- return fmt.Errorf("decoder.mid_block: %w", err)- }-- // Load up blocks- numBlocks := len(cfg.BlockOutChannels)- m.DecoderUp = make([]*UpDecoderBlock2D, numBlocks)- for i := range numBlocks {- prefix := fmt.Sprintf("decoder.up_blocks.%d", i)- hasUpsample := i < numBlocks-1- m.DecoderUp[i], err = loadUpDecoderBlock2D(weights, prefix, cfg.LayersPerBlock+1, cfg.NormNumGroups, hasUpsample)- if err != nil {- return fmt.Errorf("%s: %w", prefix, err)- }- }-- // Load decoder conv_norm_out and conv_out- m.DecoderNormOut = &GroupNormLayer{NumGroups: cfg.NormNumGroups, Eps: 1e-5}- if err := safetensors.LoadModule(m.DecoderNormOut, weights, "decoder.conv_norm_out"); err != nil {- return fmt.Errorf("decoder.conv_norm_out: %w", err)- }-- m.DecoderConvOut = &Conv2D{Stride: 1, Padding: 1}- if err := safetensors.LoadModule(m.DecoderConvOut, weights, "decoder.conv_out"); err != nil {- return fmt.Errorf("decoder.conv_out: %w", err)- }-- // Load post_quant_conv- if cfg.UsePostQuantConv {- m.PostQuantConv = &Conv2D{Stride: 1, Padding: 0}- if err := safetensors.LoadModule(m.PostQuantConv, weights, "post_quant_conv"); err != nil {- return fmt.Errorf("post_quant_conv: %w", err)- }- }-- // Load latent BatchNorm (affine=False, so no weight/bias)- bnMean, err := weights.GetTensor("bn.running_mean")- if err != nil {- return fmt.Errorf("bn.running_mean: %w", err)- }- bnVar, err := weights.GetTensor("bn.running_var")- if err != nil {- return fmt.Errorf("bn.running_var: %w", err)- }- m.LatentBN = &BatchNorm2D{- RunningMean: bnMean,- RunningVar: bnVar,- Weight: nil, // affine=False- Bias: nil, // affine=False- Eps: cfg.BatchNormEps,- Momentum: cfg.BatchNormMomentum,- }-- fmt.Println("✓")- return nil-}--// loadVAEMidBlock loads the mid block.-func loadVAEMidBlock(weights safetensors.WeightSource, prefix string, numGroups int32) (*VAEMidBlock, error) {- resnet1, err := loadResnetBlock2D(weights, prefix+".resnets.0", numGroups)- if err != nil {- return nil, err- }-- attention, err := loadVAEAttentionBlock(weights, prefix+".attentions.0", numGroups)- if err != nil {- return nil, err- }-- resnet2, err := loadResnetBlock2D(weights, prefix+".resnets.1", numGroups)- if err != nil {- return nil, err- }-- return &VAEMidBlock{- Resnet1: resnet1,- Attention: attention,- Resnet2: resnet2,- }, nil-}--// loadResnetBlock2D loads a ResNet block.-func loadResnetBlock2D(weights safetensors.WeightSource, prefix string, numGroups int32) (*ResnetBlock2D, error) {- block := &ResnetBlock2D{- Norm1: &GroupNormLayer{NumGroups: numGroups, Eps: 1e-5},- Conv1: &Conv2D{Stride: 1, Padding: 1},- Norm2: &GroupNormLayer{NumGroups: numGroups, Eps: 1e-5},- Conv2: &Conv2D{Stride: 1, Padding: 1},- ConvShortcut: &Conv2D{Stride: 1, Padding: 0}, // Pre-allocate for optional loading- }- if err := safetensors.LoadModule(block, weights, prefix); err != nil {- return nil, err- }- // If ConvShortcut wasn't loaded (no weights found), nil it out- if block.ConvShortcut.Weight == nil {- block.ConvShortcut = nil- }- return block, nil-}--// loadVAEAttentionBlock loads an attention block using LoadModule.-func loadVAEAttentionBlock(weights safetensors.WeightSource, prefix string, numGroups int32) (*VAEAttentionBlock, error) {- ab := &VAEAttentionBlock{- GroupNorm: &GroupNormLayer{NumGroups: numGroups, Eps: 1e-5},- }- if err := safetensors.LoadModule(ab, weights, prefix); err != nil {- return nil, err- }- return ab, nil-}--// loadUpDecoderBlock2D loads an up decoder block.-func loadUpDecoderBlock2D(weights safetensors.WeightSource, prefix string, numLayers, numGroups int32, hasUpsample bool) (*UpDecoderBlock2D, error) {- resnets := make([]*ResnetBlock2D, numLayers)- for i := range numLayers {- resPrefix := fmt.Sprintf("%s.resnets.%d", prefix, i)- resnet, err := loadResnetBlock2D(weights, resPrefix, numGroups)- if err != nil {- return nil, err- }- resnets[i] = resnet- }-- var upsample *Conv2D- if hasUpsample {- upsample = &Conv2D{Stride: 1, Padding: 1}- if err := safetensors.LoadModule(upsample, weights, prefix+".upsamplers.0.conv"); err != nil {- return nil, err- }- }-- return &UpDecoderBlock2D{- ResnetBlocks: resnets,- Upsample: upsample,- }, nil-}--// Patchify converts latents [B, C, H, W] to patches [B, H*W/4, C*4] using 2x2 patches-// This is the inverse of the VAE's patchify for feeding to transformer-func (vae *AutoencoderKLFlux2) Patchify(latents *mlx.Array) *mlx.Array {- shape := latents.Shape()- B := shape[0]- C := shape[1]- H := shape[2]- W := shape[3]-- patchH := vae.Config.PatchSize[0]- patchW := vae.Config.PatchSize[1]-- pH := H / patchH- pW := W / patchW-- // [B, C, H, W] -> [B, C, pH, patchH, pW, patchW]- x := mlx.Reshape(latents, B, C, pH, patchH, pW, patchW)- // [B, C, pH, patchH, pW, patchW] -> [B, pH, pW, C, patchH, patchW]- x = mlx.Transpose(x, 0, 2, 4, 1, 3, 5)- // [B, pH, pW, C, patchH, patchW] -> [B, pH*pW, C*patchH*patchW]- return mlx.Reshape(x, B, pH*pW, C*patchH*patchW)-}--// Unpatchify converts patches [B, L, C*4] back to [B, C, H, W]-func (vae *AutoencoderKLFlux2) Unpatchify(patches *mlx.Array, pH, pW, C int32) *mlx.Array {- shape := patches.Shape()- B := shape[0]-- patchH := vae.Config.PatchSize[0]- patchW := vae.Config.PatchSize[1]-- // [B, pH*pW, C*patchH*patchW] -> [B, pH, pW, C, patchH, patchW]- x := mlx.Reshape(patches, B, pH, pW, C, patchH, patchW)- // [B, pH, pW, C, patchH, patchW] -> [B, C, pH, patchH, pW, patchW]- x = mlx.Transpose(x, 0, 3, 1, 4, 2, 5)- // [B, C, pH, patchH, pW, patchW] -> [B, C, H, W]- H := pH * patchH- W := pW * patchW- return mlx.Reshape(x, B, C, H, W)-}--// denormalizePatchified applies inverse batch normalization to patchified latents.-// Input: [B, L, 128] where 128 = 32 latent channels * 4 (2x2 patch)-// Output: [B, L, 128] denormalized-func (vae *AutoencoderKLFlux2) denormalizePatchified(x *mlx.Array) *mlx.Array {- shape := x.Shape()- C := shape[2] // 128-- // Reshape stats for broadcasting [1, 1, C]- mean := mlx.Reshape(vae.LatentBN.RunningMean, 1, 1, C)- variance := mlx.Reshape(vae.LatentBN.RunningVar, 1, 1, C)-- // Inverse BN (affine=False): x_denorm = x * sqrt(var + eps) + mean- if vae.LatentBN.Bias != nil {- bias := mlx.Reshape(vae.LatentBN.Bias, 1, 1, C)- x = mlx.Sub(x, bias)- }- if vae.LatentBN.Weight != nil {- weight := mlx.Reshape(vae.LatentBN.Weight, 1, 1, C)- x = mlx.Div(x, weight)- }- x = mlx.Mul(x, mlx.Sqrt(mlx.AddScalar(variance, vae.LatentBN.Eps)))- x = mlx.Add(x, mean)-- return x-}--// Decode decodes latent patches to images.-// If Tiling is set, uses tiled decoding to reduce memory for large images.-// latents: [B, L, C*4] patchified latents from transformer-// pH, pW: patch grid dimensions-// Returns: [B, 3, H, W] image tensor-func (v *AutoencoderKLFlux2) Decode(latents *mlx.Array, pH, pW int32) *mlx.Array {- // Denormalize patchified latents- z := v.denormalizePatchified(latents)-- // Unpatchify: [B, L, C*4] -> [B, C, H, W]- z = v.Unpatchify(z, pH, pW, v.Config.LatentChannels)-- // Convert NCHW -> NHWC for processing- z = mlx.Transpose(z, 0, 2, 3, 1)-- // Use tiled decoding if enabled- if v.Tiling != nil {- mlx.Eval(z)- return vae.DecodeTiled(z, v.Tiling, v.decodeTile)- }-- // Direct decode (no tiling)- h := v.decodeTile(z)- h = mlx.ClipScalar(h, 0.0, 1.0, true, true)- h = mlx.Transpose(h, 0, 3, 1, 2)- return h-}--// decodeTile decodes a single latent tile to pixels (internal helper)-// z: [B, H, W, C] latent tile in NHWC format-// Returns: [B, H*8, W*8, 3] pixel tile in NHWC format (before clipping)-func (vae *AutoencoderKLFlux2) decodeTile(z *mlx.Array) *mlx.Array {- // Post-quant conv- if vae.PostQuantConv != nil {- z = vae.PostQuantConv.Forward(z)- }-- // Decoder- h := vae.DecoderConvIn.Forward(z)- h = vae.DecoderMid.Forward(h)-- for _, upBlock := range vae.DecoderUp {- h = upBlock.Forward(h)- }-- h = vae.DecoderNormOut.Forward(h)- h = mlx.SiLU(h)- h = vae.DecoderConvOut.Forward(h)-- // VAE outputs [-1, 1], convert to [0, 1]- h = mlx.MulScalar(h, 0.5)- h = mlx.AddScalar(h, 0.5)-- return h-}--// loadEncoderWeights loads the encoder components for image conditioning-func (m *AutoencoderKLFlux2) loadEncoderWeights(weights safetensors.WeightSource, cfg *VAEConfig) error {- var err error-- // Load encoder conv_in- m.EncoderConvIn = &Conv2D{Stride: 1, Padding: 1}- if err := safetensors.LoadModule(m.EncoderConvIn, weights, "encoder.conv_in"); err != nil {- return fmt.Errorf("encoder.conv_in: %w", err)- }-- // Load encoder down blocks- numBlocks := len(cfg.BlockOutChannels)- m.EncoderDown = make([]*DownEncoderBlock2D, numBlocks)- for i := range numBlocks {- prefix := fmt.Sprintf("encoder.down_blocks.%d", i)- hasDownsample := i < numBlocks-1- m.EncoderDown[i], err = loadDownEncoderBlock2D(weights, prefix, cfg.LayersPerBlock, cfg.NormNumGroups, hasDownsample)- if err != nil {- return fmt.Errorf("%s: %w", prefix, err)- }- }-- // Load encoder mid block- m.EncoderMid, err = loadVAEMidBlock(weights, "encoder.mid_block", cfg.NormNumGroups)- if err != nil {- return fmt.Errorf("encoder.mid_block: %w", err)- }-- // Load encoder conv_norm_out and conv_out- m.EncoderNormOut = &GroupNormLayer{NumGroups: cfg.NormNumGroups, Eps: 1e-5}- if err := safetensors.LoadModule(m.EncoderNormOut, weights, "encoder.conv_norm_out"); err != nil {- return fmt.Errorf("encoder.conv_norm_out: %w", err)- }-- m.EncoderConvOut = &Conv2D{Stride: 1, Padding: 1}- if err := safetensors.LoadModule(m.EncoderConvOut, weights, "encoder.conv_out"); err != nil {- return fmt.Errorf("encoder.conv_out: %w", err)- }-- // Load quant_conv (for encoding)- if cfg.UseQuantConv {- m.QuantConv = &Conv2D{Stride: 1, Padding: 0}- if err := safetensors.LoadModule(m.QuantConv, weights, "quant_conv"); err != nil {- return fmt.Errorf("quant_conv: %w", err)- }- }-- return nil-}--// loadDownEncoderBlock2D loads a down encoder block.-func loadDownEncoderBlock2D(weights safetensors.WeightSource, prefix string, numLayers, numGroups int32, hasDownsample bool) (*DownEncoderBlock2D, error) {- resnets := make([]*ResnetBlock2D, numLayers)- for i := range numLayers {- resPrefix := fmt.Sprintf("%s.resnets.%d", prefix, i)- resnet, err := loadResnetBlock2D(weights, resPrefix, numGroups)- if err != nil {- return nil, err- }- resnets[i] = resnet- }-- var downsample *Conv2D- if hasDownsample {- downsample = &Conv2D{Stride: 2, Padding: 0}- if err := safetensors.LoadModule(downsample, weights, prefix+".downsamplers.0.conv"); err != nil {- return nil, err- }- }-- return &DownEncoderBlock2D{- ResnetBlocks: resnets,- Downsample: downsample,- }, nil-}--// EncodeImage encodes an image to normalized latents.-// image: [B, 3, H, W] image tensor in [-1, 1]-// Returns: [B, L, C*4] patchified normalized latents-func (vae *AutoencoderKLFlux2) EncodeImage(image *mlx.Array) *mlx.Array {- // Convert NCHW -> NHWC- x := mlx.Transpose(image, 0, 2, 3, 1)-- // Encoder- h := vae.EncoderConvIn.Forward(x)-- for _, downBlock := range vae.EncoderDown {- h = downBlock.Forward(h)- }-- h = vae.EncoderMid.Forward(h)- h = vae.EncoderNormOut.Forward(h)- h = mlx.SiLU(h)- h = vae.EncoderConvOut.Forward(h)-- // Quant conv outputs [B, H, W, 2*latent_channels] (mean + logvar)- if vae.QuantConv != nil {- h = vae.QuantConv.Forward(h)- }-- // Take only the mean (first latent_channels) - deterministic encoding- // h is [B, H, W, 64] -> take first 32 channels for mean- shape := h.Shape()- latentChannels := vae.Config.LatentChannels // 32- h = mlx.Slice(h, []int32{0, 0, 0, 0}, []int32{shape[0], shape[1], shape[2], latentChannels})-- // Convert NHWC -> NCHW for patchifying- h = mlx.Transpose(h, 0, 3, 1, 2)-- // Patchify: [B, C, H, W] -> [B, L, C*4]- h = vae.Patchify(h)-- // Apply BatchNorm on patchified latents [B, L, 128]- // The BatchNorm has 128 channels matching the patchified dimension- h = vae.normalizePatchified(h)-- return h-}--// normalizePatchified applies batch normalization to patchified latents.-// Input: [B, L, 128] where 128 = 32 latent channels * 4 (2x2 patch)-// Output: [B, L, 128] normalized-func (vae *AutoencoderKLFlux2) normalizePatchified(x *mlx.Array) *mlx.Array {- shape := x.Shape()- C := shape[2] // 128-- // Reshape stats for broadcasting [1, 1, C]- mean := mlx.Reshape(vae.LatentBN.RunningMean, 1, 1, C)- variance := mlx.Reshape(vae.LatentBN.RunningVar, 1, 1, C)-- // Normalize: (x - mean) / sqrt(var + eps)- xNorm := mlx.Sub(x, mean)- xNorm = mlx.Div(xNorm, mlx.Sqrt(mlx.AddScalar(variance, vae.LatentBN.Eps)))-- // Scale and shift (only if affine=True)- if vae.LatentBN.Weight != nil {- weight := mlx.Reshape(vae.LatentBN.Weight, 1, 1, C)- xNorm = mlx.Mul(xNorm, weight)- }- if vae.LatentBN.Bias != nil {- bias := mlx.Reshape(vae.LatentBN.Bias, 1, 1, C)- xNorm = mlx.Add(xNorm, bias)- }-- return xNorm-}diff --git a/x/imagegen/models/qwen3/text_encoder.go b/x/imagegen/models/qwen3/text_encoder.godeleted file mode 100644index b828fe880..000000000--- a/x/imagegen/models/qwen3/text_encoder.go+++ /dev/null@@ -1,388 +0,0 @@-// Package qwen3 provides a shared Qwen3 text encoder used by multiple image generation models.-package qwen3--import (- "fmt"- "math"-- "github.com/ollama/ollama/x/imagegen/manifest"- "github.com/ollama/ollama/x/imagegen/mlx"- "github.com/ollama/ollama/x/imagegen/nn"- "github.com/ollama/ollama/x/imagegen/safetensors"- "github.com/ollama/ollama/x/imagegen/tokenizer"-)--// Config holds Qwen3 text encoder configuration-type Config struct {- HiddenSize int32 `json:"hidden_size"`- NumHiddenLayers int32 `json:"num_hidden_layers"`- IntermediateSize int32 `json:"intermediate_size"`- NumAttentionHeads int32 `json:"num_attention_heads"`- NumKeyValueHeads int32 `json:"num_key_value_heads"`- VocabSize int32 `json:"vocab_size"`- RMSNormEps float32 `json:"rms_norm_eps"`- RopeTheta float32 `json:"rope_theta"`- HeadDim int32 `json:"head_dim"`-}--// Attention implements Qwen3 attention with QK norms-type Attention struct {- QProj nn.LinearLayer `weight:"q_proj"`- KProj nn.LinearLayer `weight:"k_proj"`- VProj nn.LinearLayer `weight:"v_proj"`- OProj nn.LinearLayer `weight:"o_proj"`- QNorm *nn.RMSNorm `weight:"q_norm"`- KNorm *nn.RMSNorm `weight:"k_norm"`- // Computed fields- NHeads int32- NKVHeads int32- HeadDim int32- Scale float32- RopeTheta float32-}--// applyRoPEQwen3 applies the custom RoPE for Qwen3 text encoder-func applyRoPEQwen3(x *mlx.Array, seqLen int32, theta float32) *mlx.Array {- shape := x.Shape()- B := shape[0]- L := shape[1]- H := shape[2]- D := shape[3]- half := D / 2-- freqsArr := make([]float32, half)- logTheta := float32(math.Log(float64(theta)))- for i := range half {- freqsArr[i] = float32(math.Exp(float64(-logTheta * float32(i) / float32(half))))- }- freqs := mlx.NewArray(freqsArr, []int32{half})-- posArr := make([]float32, seqLen)- for i := range seqLen {- posArr[i] = float32(i)- }- pos := mlx.NewArray(posArr, []int32{seqLen})-- posExpanded := mlx.Reshape(pos, seqLen, 1)- freqsExpanded := mlx.Reshape(freqs, 1, half)- args := mlx.Mul(posExpanded, freqsExpanded)-- cosVals := mlx.Cos(args)- sinVals := mlx.Sin(args)- cosVals = mlx.Reshape(cosVals, seqLen, 1, half)- sinVals = mlx.Reshape(sinVals, seqLen, 1, half)-- x1 := mlx.Slice(x, []int32{0, 0, 0, 0}, []int32{B, L, H, half})- x2 := mlx.Slice(x, []int32{0, 0, 0, half}, []int32{B, L, H, D})-- part1 := mlx.Sub(mlx.Mul(x1, cosVals), mlx.Mul(x2, sinVals))- part2 := mlx.Add(mlx.Mul(x1, sinVals), mlx.Mul(x2, cosVals))-- return mlx.Concatenate([]*mlx.Array{part1, part2}, 3)-}--// Forward computes attention with causal masking and optional padding mask-func (attn *Attention) Forward(x *mlx.Array, mask *mlx.Array, maskMode string) *mlx.Array {- shape := x.Shape()- B := shape[0]- L := shape[1]-- q := attn.QProj.Forward(x)- k := attn.KProj.Forward(x)- v := attn.VProj.Forward(x)-- q = mlx.Reshape(q, B, L, attn.NHeads, attn.HeadDim)- k = mlx.Reshape(k, B, L, attn.NKVHeads, attn.HeadDim)- v = mlx.Reshape(v, B, L, attn.NKVHeads, attn.HeadDim)-- // QK norm uses 1e-6 hardcoded (Qwen3 specific)- q = attn.QNorm.Forward(q, 1e-6)- k = attn.KNorm.Forward(k, 1e-6)-- q = applyRoPEQwen3(q, L, attn.RopeTheta)- k = applyRoPEQwen3(k, L, attn.RopeTheta)-- q = mlx.Transpose(q, 0, 2, 1, 3)- k = mlx.Transpose(k, 0, 2, 1, 3)- v = mlx.Transpose(v, 0, 2, 1, 3)-- if attn.NKVHeads < attn.NHeads {- repeats := attn.NHeads / attn.NKVHeads- k = repeatKV(k, repeats)- v = repeatKV(v, repeats)- }-- out := mlx.ScaledDotProductAttentionWithSinks(q, k, v, attn.Scale, maskMode, mask, nil)-- out = mlx.Transpose(out, 0, 2, 1, 3)- out = mlx.Reshape(out, B, L, attn.NHeads*attn.HeadDim)-- out = attn.OProj.Forward(out)-- return out-}--// repeatKV repeats key/value heads for GQA-func repeatKV(x *mlx.Array, repeats int32) *mlx.Array {- if repeats == 1 {- return x- }- shape := x.Shape()- x = mlx.ExpandDims(x, 2)- x = mlx.Tile(x, []int32{1, 1, repeats, 1, 1})- return mlx.Reshape(x, shape[0], shape[1]*repeats, shape[2], shape[3])-}--// MLP implements Qwen3 SwiGLU MLP-type MLP struct {- GateProj nn.LinearLayer `weight:"gate_proj"`- UpProj nn.LinearLayer `weight:"up_proj"`- DownProj nn.LinearLayer `weight:"down_proj"`-}--// Forward applies the MLP-func (m *MLP) Forward(x *mlx.Array) *mlx.Array {- gate := m.GateProj.Forward(x)- gate = mlx.SiLU(gate)- up := m.UpProj.Forward(x)- h := mlx.Mul(gate, up)- return m.DownProj.Forward(h)-}--// Block represents a single Qwen3 transformer block-type Block struct {- Attention *Attention `weight:"self_attn"`- MLP *MLP `weight:"mlp"`- InputLayerNorm *nn.RMSNorm `weight:"input_layernorm"`- PostAttnLayerNorm *nn.RMSNorm `weight:"post_attention_layernorm"`-}--// Forward applies the Qwen3 block-func (qb *Block) Forward(x *mlx.Array, eps float32, mask *mlx.Array, maskMode string) *mlx.Array {- h := qb.InputLayerNorm.Forward(x, eps)- attnOut := qb.Attention.Forward(h, mask, maskMode)- x = mlx.Add(x, attnOut)-- h = qb.PostAttnLayerNorm.Forward(x, eps)- mlpOut := qb.MLP.Forward(h)- x = mlx.Add(x, mlpOut)-- return x-}--// TextEncoder is the full Qwen3 encoder-type TextEncoder struct {- EmbedTokens *nn.Embedding `weight:"model.embed_tokens"`- Layers []*Block `weight:"model.layers"`- FinalNorm *nn.RMSNorm `weight:"model.norm"`- *Config-}--// Load loads the Qwen3 text encoder from ollama blob storage.-func (m *TextEncoder) Load(modelManifest *manifest.ModelManifest, configPath string) error {- fmt.Print(" Loading text encoder... ")-- // Load config from blob- var cfg Config- if err := modelManifest.ReadConfigJSON(configPath, &cfg); err != nil {- return fmt.Errorf("config: %w", err)- }- m.Config = &cfg- m.Layers = make([]*Block, cfg.NumHiddenLayers)-- // Load weights from tensor blobs- weights, err := manifest.LoadWeightsFromManifest(modelManifest, "text_encoder")- if err != nil {- return fmt.Errorf("weights: %w", err)- }- if err := weights.Load(0); err != nil {- return fmt.Errorf("load weights: %w", err)- }- defer weights.ReleaseAll()-- return m.loadWeights(weights)-}--// loadWeights loads weights from any WeightSource into the model-func (m *TextEncoder) loadWeights(weights safetensors.WeightSource) error {- if err := safetensors.LoadModule(m, weights, ""); err != nil {- return fmt.Errorf("load module: %w", err)- }- m.initComputedFields()- fmt.Println("✓")- return nil-}--// initComputedFields initializes computed fields after loading weights-func (m *TextEncoder) initComputedFields() {- cfg := m.Config- m.FinalNorm.Eps = cfg.RMSNormEps- for _, block := range m.Layers {- // Attention- block.Attention.NHeads = cfg.NumAttentionHeads- block.Attention.NKVHeads = cfg.NumKeyValueHeads- block.Attention.HeadDim = cfg.HeadDim- block.Attention.Scale = float32(1.0 / math.Sqrt(float64(cfg.HeadDim)))- block.Attention.RopeTheta = cfg.RopeTheta- block.Attention.QNorm.Eps = cfg.RMSNormEps- block.Attention.KNorm.Eps = cfg.RMSNormEps- // Block norms- block.InputLayerNorm.Eps = cfg.RMSNormEps- block.PostAttnLayerNorm.Eps = cfg.RMSNormEps- }-}--// Forward encodes text tokens with provided attention mask (LxL) and mask mode.-func (te *TextEncoder) Forward(tokens *mlx.Array, attnMask *mlx.Array, maskMode string) *mlx.Array {- h := te.EmbedTokens.Forward(tokens)- eps := te.RMSNormEps-- for _, layer := range te.Layers {- h = layer.Forward(h, eps, attnMask, maskMode)- }-- // Apply final RMS norm- h = te.FinalNorm.Forward(h, eps)-- return h-}--// ForwardWithLayerOutputs encodes text tokens and returns hidden states from specified layers.-// This is used by Flux2 which needs embeddings from specific intermediate layers.-func (te *TextEncoder) ForwardWithLayerOutputs(tokens *mlx.Array, layerIndices []int, attnMask *mlx.Array, maskMode string) []*mlx.Array {- h := te.EmbedTokens.Forward(tokens)- eps := te.RMSNormEps-- outputs := make([]*mlx.Array, len(layerIndices))- layerSet := make(map[int]int)- for i, idx := range layerIndices {- layerSet[idx] = i- }-- for i, layer := range te.Layers {- h = layer.Forward(h, eps, attnMask, maskMode)- if outIdx, ok := layerSet[i]; ok {- outputs[outIdx] = h- }- }-- return outputs-}--// ApplyChatTemplate wraps prompt in Qwen3 chat format.-// If think is true, adds the <think></think> block after the assistant tag-// (matches tokenizer.apply_chat_template with enable_thinking=False in Python).-func ApplyChatTemplate(prompt string, think bool) string {- base := "<|im_start|>user\n" + prompt + "<|im_end|>\n<|im_start|>assistant\n"- if think {- return base + "<think>\n\n</think>\n\n"- }- return base-}--// EncodePrompt encodes a text prompt using the tokenizer and encoder.-// If think is true, includes the <think></think> block in the chat template.-func (te *TextEncoder) EncodePrompt(tok *tokenizer.Tokenizer, prompt string, maxLen int, think bool) (*mlx.Array, *mlx.Array) {- formattedPrompt := ApplyChatTemplate(prompt, think)-- tokens := tok.Encode(formattedPrompt, false)-- if len(tokens) > maxLen {- tokens = tokens[:maxLen]- }-- maskData := make([]float32, maxLen)- for i := range tokens {- maskData[i] = 1.0- }-- // Get PAD token (different from EOS for Qwen3)- padToken := tok.PAD()- if padToken < 0 {- padToken = tok.EOS() // fallback- }-- paddedTokens := make([]int32, maxLen)- copy(paddedTokens, tokens)- for i := len(tokens); i < maxLen; i++ {- paddedTokens[i] = padToken- }-- tokensArr := mlx.NewArrayInt32(paddedTokens, []int32{1, int32(maxLen)})- maskArr := mlx.NewArray(maskData, []int32{1, int32(maxLen)})-- // Build combined causal + PAD mask [L, L]- // mask[i,j] = 0 if (j <= i AND valid[j]) else -inf- L := int32(maxLen)- validLen := int32(len(tokens))- combinedMaskData := make([]float32, L*L)- negInf := float32(-1e9)- for i := range L {- for j := range L {- idx := i*L + j- if j <= i && j < validLen {- combinedMaskData[idx] = 0- } else {- combinedMaskData[idx] = negInf- }- }- }- maskMat := mlx.NewArray(combinedMaskData, []int32{L, L})-- embeddings := te.Forward(tokensArr, maskMat, "")-- return embeddings, maskArr-}--// EncodePromptWithLayers encodes a text prompt and returns embeddings from specified layers.-// Used by Flux2 which concatenates embeddings from multiple intermediate layers.-// If think is true, includes the <think></think> block in the chat template.-// Returns embeddings and padded sequence length.-func (te *TextEncoder) EncodePromptWithLayers(tok *tokenizer.Tokenizer, prompt string, maxLen int, layerIndices []int, think bool) (*mlx.Array, int32) {- formattedPrompt := ApplyChatTemplate(prompt, think)- tokens := tok.Encode(formattedPrompt, false)-- if len(tokens) > maxLen {- tokens = tokens[:maxLen]- }-- // Pad to maxLen- padToken := tok.PAD()- if padToken < 0 {- padToken = tok.EOS() // fallback- }- padded := make([]int32, maxLen)- copy(padded, tokens)- for i := len(tokens); i < maxLen; i++ {- padded[i] = padToken- }- tokensArr := mlx.NewArrayInt32(padded, []int32{1, int32(maxLen)})-- // Build combined causal + PAD mask [L, L]- // mask[i,j] = 0 if (j <= i AND valid[j]) else -inf- // This combines causal masking with PAD token masking- L := int32(maxLen)- validLen := int32(len(tokens))- maskData := make([]float32, L*L)- negInf := float32(-1e9)- for i := range L {- for j := range L {- idx := i*L + j- if j <= i && j < validLen {- maskData[idx] = 0 // allowed: causal OK and not PAD- } else {- maskData[idx] = negInf // blocked: future or PAD- }- }- }- maskMat := mlx.NewArray(maskData, []int32{L, L})-- layerOutputs := te.ForwardWithLayerOutputs(tokensArr, layerIndices, maskMat, "")-- // Concatenate layer outputs along the hidden dimension- // Each output is [B, L, hidden_dim], result is [B, L, num_layers * hidden_dim]- embeddings := mlx.Concatenate(layerOutputs, 2)-- // Return embeddings and padded length- return embeddings, int32(maxLen)-}diff --git a/x/imagegen/models/zimage/scheduler.go b/x/imagegen/models/zimage/scheduler.godeleted file mode 100644index f5e1ccc46..000000000--- a/x/imagegen/models/zimage/scheduler.go+++ /dev/null@@ -1,141 +0,0 @@-package zimage--import (- "math"-- "github.com/ollama/ollama/x/imagegen/mlx"-)--// FlowMatchSchedulerConfig holds scheduler configuration-type FlowMatchSchedulerConfig struct {- NumTrainTimesteps int32 `json:"num_train_timesteps"` // 1000- Shift float32 `json:"shift"` // 3.0- UseDynamicShifting bool `json:"use_dynamic_shifting"` // false-}--// DefaultFlowMatchSchedulerConfig returns default config-func DefaultFlowMatchSchedulerConfig() *FlowMatchSchedulerConfig {- return &FlowMatchSchedulerConfig{- NumTrainTimesteps: 1000,- Shift: 3.0,- UseDynamicShifting: true, // Z-Image-Turbo uses dynamic shifting- }-}--// FlowMatchEulerScheduler implements the Flow Match Euler discrete scheduler-// This is used in Z-Image-Turbo for fast sampling-type FlowMatchEulerScheduler struct {- Config *FlowMatchSchedulerConfig- Timesteps []float32 // Discretized timesteps- Sigmas []float32 // Noise levels at each timestep- NumSteps int // Number of inference steps-}--// NewFlowMatchEulerScheduler creates a new scheduler-func NewFlowMatchEulerScheduler(cfg *FlowMatchSchedulerConfig) *FlowMatchEulerScheduler {- return &FlowMatchEulerScheduler{- Config: cfg,- }-}--// SetTimesteps sets up the scheduler for the given number of inference steps-func (s *FlowMatchEulerScheduler) SetTimesteps(numSteps int) {- s.SetTimestepsWithMu(numSteps, 0)-}--// SetTimestepsWithMu sets up the scheduler with dynamic mu shift-func (s *FlowMatchEulerScheduler) SetTimestepsWithMu(numSteps int, mu float32) {- s.NumSteps = numSteps-- // Create evenly spaced timesteps from 1.0 to 0.0 (flow matching goes t=1 to t=0)- // Match Python: np.linspace(1.0, 0.0, num_inference_steps + 1)- s.Timesteps = make([]float32, numSteps+1)- s.Sigmas = make([]float32, numSteps+1)-- for i := 0; i <= numSteps; i++ {- t := 1.0 - float32(i)/float32(numSteps)-- // Apply time shift if using dynamic shifting- if s.Config.UseDynamicShifting && mu != 0 {- t = s.timeShift(mu, t)- }-- s.Timesteps[i] = t- s.Sigmas[i] = t- }-}--// timeShift applies the dynamic time shift (match Python)-func (s *FlowMatchEulerScheduler) timeShift(mu float32, t float32) float32 {- if t <= 0 {- return 0- }- // exp(mu) / (exp(mu) + (1/t - 1))- expMu := float32(math.Exp(float64(mu)))- return expMu / (expMu + (1.0/t - 1.0))-}--// Step performs one denoising step-// modelOutput: predicted velocity/noise from the model-// timestepIdx: current timestep index-// sample: current noisy sample-// Returns: denoised sample for next step-func (s *FlowMatchEulerScheduler) Step(modelOutput, sample *mlx.Array, timestepIdx int) *mlx.Array {- // Get current and next sigma- sigma := s.Sigmas[timestepIdx]- sigmaNext := s.Sigmas[timestepIdx+1]-- // Euler step: x_{t-dt} = x_t + (sigma_next - sigma) * v_t- // where v_t is the velocity predicted by the model- dt := sigmaNext - sigma // This is negative (going from noise to clean)-- // x_next = x + dt * velocity- scaledOutput := mlx.MulScalar(modelOutput, dt)- return mlx.Add(sample, scaledOutput)-}--// ScaleSample scales the sample for model input (identity for flow matching)-func (s *FlowMatchEulerScheduler) ScaleSample(sample *mlx.Array, timestepIdx int) *mlx.Array {- // Flow matching doesn't need scaling- return sample-}--// GetTimestep returns the timestep value at the given index-func (s *FlowMatchEulerScheduler) GetTimestep(idx int) float32 {- if idx < len(s.Timesteps) {- return s.Timesteps[idx]- }- return 0.0-}--// GetTimesteps returns all timesteps (implements Scheduler interface)-func (s *FlowMatchEulerScheduler) GetTimesteps() []float32 {- return s.Timesteps-}--// AddNoise adds noise to clean samples for a given timestep-// Used for img2img or inpainting-func (s *FlowMatchEulerScheduler) AddNoise(cleanSample, noise *mlx.Array, timestepIdx int) *mlx.Array {- // In flow matching: x_t = (1-t) * x_0 + t * noise- t := s.Timesteps[timestepIdx]- oneMinusT := 1.0 - t-- scaledClean := mlx.MulScalar(cleanSample, oneMinusT)- scaledNoise := mlx.MulScalar(noise, t)-- return mlx.Add(scaledClean, scaledNoise)-}--// InitNoise creates initial noise for sampling (BFloat16 for GPU efficiency)-func (s *FlowMatchEulerScheduler) InitNoise(shape []int32, seed int64) *mlx.Array {- return mlx.RandomNormalWithDtype(shape, uint64(seed), mlx.DtypeBFloat16)-}--// GetLatentShape returns the latent shape for a given image size-func GetLatentShape(batchSize, height, width, latentChannels int32, patchSize int32) []int32 {- // Latent is 8x smaller than image (VAE downscale)- latentH := height / 8- latentW := width / 8-- return []int32{batchSize, latentChannels, latentH, latentW}-}diff --git a/x/imagegen/models/zimage/text_encoder.go b/x/imagegen/models/zimage/text_encoder.godeleted file mode 100644index 65d9ab596..000000000--- a/x/imagegen/models/zimage/text_encoder.go+++ /dev/null@@ -1,17 +0,0 @@-package zimage--import (- "github.com/ollama/ollama/x/imagegen/models/qwen3"-)--// Re-export types from shared qwen3 package for backwards compatibility-type (- Qwen3Config = qwen3.Config- Qwen3Attention = qwen3.Attention- Qwen3MLP = qwen3.MLP- Qwen3Block = qwen3.Block- Qwen3TextEncoder = qwen3.TextEncoder-)--// ApplyChatTemplate wraps prompt in Qwen3 chat format-var ApplyChatTemplate = qwen3.ApplyChatTemplatediff --git a/x/imagegen/models/zimage/transformer.go b/x/imagegen/models/zimage/transformer.godeleted file mode 100644index 4f8d67b6a..000000000--- a/x/imagegen/models/zimage/transformer.go+++ /dev/null@@ -1,759 +0,0 @@-// Package zimage implements the Z-Image diffusion transformer model.-package zimage--import (- "fmt"- "math"-- "github.com/ollama/ollama/x/imagegen/cache"- "github.com/ollama/ollama/x/imagegen/manifest"- "github.com/ollama/ollama/x/imagegen/mlx"- "github.com/ollama/ollama/x/imagegen/nn"- "github.com/ollama/ollama/x/imagegen/safetensors"-)--// TransformerConfig holds Z-Image transformer configuration-type TransformerConfig struct {- Dim int32 `json:"dim"`- NHeads int32 `json:"n_heads"`- NKVHeads int32 `json:"n_kv_heads"`- NLayers int32 `json:"n_layers"`- NRefinerLayers int32 `json:"n_refiner_layers"`- InChannels int32 `json:"in_channels"`- PatchSize int32 `json:"-"` // Computed from AllPatchSize- CapFeatDim int32 `json:"cap_feat_dim"`- NormEps float32 `json:"norm_eps"`- RopeTheta float32 `json:"rope_theta"`- TScale float32 `json:"t_scale"`- QKNorm bool `json:"qk_norm"`- AxesDims []int32 `json:"axes_dims"`- AxesLens []int32 `json:"axes_lens"`- AllPatchSize []int32 `json:"all_patch_size"` // JSON array, PatchSize = first element-}--// TimestepEmbedder creates sinusoidal timestep embeddings-// Output dimension is 256 (fixed), used for AdaLN modulation-type TimestepEmbedder struct {- Linear1 nn.LinearLayer `weight:"mlp.0"`- Linear2 nn.LinearLayer `weight:"mlp.2"`- FreqEmbedSize int32 // 256 (computed)-}--// Forward computes timestep embeddings -> [B, 256]-func (te *TimestepEmbedder) Forward(t *mlx.Array) *mlx.Array {- // t: [B] timesteps-- // Create sinusoidal embedding- half := te.FreqEmbedSize / 2-- // freqs = exp(-log(10000) * arange(half) / half)- freqs := make([]float32, half)- for i := range half {- freqs[i] = float32(math.Exp(-math.Log(10000.0) * float64(i) / float64(half)))- }- freqsArr := mlx.NewArray(freqs, []int32{1, half})-- // t[:, None] * freqs[None, :] -> [B, half]- tExpanded := mlx.ExpandDims(t, 1) // [B, 1]- args := mlx.Mul(tExpanded, freqsArr)-- // embedding = [cos(args), sin(args)] -> [B, 256]- cosArgs := mlx.Cos(args)- sinArgs := mlx.Sin(args)- embedding := mlx.Concatenate([]*mlx.Array{cosArgs, sinArgs}, 1)-- // MLP: linear1 -> silu -> linear2- h := te.Linear1.Forward(embedding)- h = mlx.SiLU(h)- h = te.Linear2.Forward(h)-- return h-}--// XEmbedder embeds image patches to model dimension-type XEmbedder struct {- Linear nn.LinearLayer `weight:"2-1"`-}--// Forward embeds patchified image latents-func (xe *XEmbedder) Forward(x *mlx.Array) *mlx.Array {- // x: [B, L, in_channels * 4] -> [B, L, dim]- return xe.Linear.Forward(x)-}--// CapEmbedder projects caption features to model dimension-type CapEmbedder struct {- Norm *nn.RMSNorm `weight:"0"`- Linear nn.LinearLayer `weight:"1"`- PadToken *mlx.Array // loaded separately at root level-}--// Forward projects caption embeddings: [B, L, cap_feat_dim] -> [B, L, dim]-func (ce *CapEmbedder) Forward(capFeats *mlx.Array) *mlx.Array {- // RMSNorm on last axis (uses 1e-6)- h := ce.Norm.Forward(capFeats, 1e-6)- // Linear projection- return ce.Linear.Forward(h)-}--// FeedForward implements SwiGLU FFN-type FeedForward struct {- W1 nn.LinearLayer `weight:"w1"` // gate projection- W2 nn.LinearLayer `weight:"w2"` // down projection- W3 nn.LinearLayer `weight:"w3"` // up projection- OutDim int32 // computed from W2-}--// Forward applies SwiGLU: silu(W1(x)) * W3(x), then W2-func (ff *FeedForward) Forward(x *mlx.Array) *mlx.Array {- shape := x.Shape()- B := shape[0]- L := shape[1]- D := shape[2]-- // Reshape for matmul- x = mlx.Reshape(x, B*L, D)-- gate := ff.W1.Forward(x)- gate = mlx.SiLU(gate)- up := ff.W3.Forward(x)- h := mlx.Mul(gate, up)- out := ff.W2.Forward(h)-- return mlx.Reshape(out, B, L, ff.OutDim)-}--// Attention implements multi-head attention with QK norm-type Attention struct {- ToQ nn.LinearLayer `weight:"to_q"`- ToK nn.LinearLayer `weight:"to_k"`- ToV nn.LinearLayer `weight:"to_v"`- ToOut nn.LinearLayer `weight:"to_out.0"`- NormQ *mlx.Array `weight:"norm_q.weight"` // [head_dim] for per-head RMSNorm- NormK *mlx.Array `weight:"norm_k.weight"`- // Fused QKV (computed at init time for efficiency, not loaded from weights)- ToQKV nn.LinearLayer `weight:"-"` // Fused Q+K+V projection (created by FuseQKV)- Fused bool `weight:"-"` // Whether to use fused QKV path- // Computed fields (not loaded from weights)- NHeads int32 `weight:"-"`- HeadDim int32 `weight:"-"`- Dim int32 `weight:"-"`- Scale float32 `weight:"-"`-}--// FuseQKV creates a fused QKV projection by concatenating weights.-// This reduces 3 matmuls to 1 for a ~5-10% speedup.-// Note: Fusion is skipped for quantized weights as it would require complex-// dequant-concat-requant operations. The FP8 memory bandwidth savings outweigh-// the ~5% fusion benefit.-func (attn *Attention) FuseQKV() {- if attn.ToQ == nil || attn.ToK == nil || attn.ToV == nil {- return- }-- // Skip fusion for quantized weights - type assert to check- toQ, qOk := attn.ToQ.(*nn.Linear)- toK, kOk := attn.ToK.(*nn.Linear)- toV, vOk := attn.ToV.(*nn.Linear)- if !qOk || !kOk || !vOk {- // One or more are QuantizedLinear, skip fusion- return- }-- if toQ.Weight == nil || toK.Weight == nil || toV.Weight == nil {- return- }-- // Concatenate weights: [dim, dim] x 3 -> [3*dim, dim]- // Weight shapes: ToQ.Weight [out_dim, in_dim], etc.- qWeight := toQ.Weight- kWeight := toK.Weight- vWeight := toV.Weight-- // Concatenate along output dimension (axis 0)- fusedWeight := mlx.Concatenate([]*mlx.Array{qWeight, kWeight, vWeight}, 0)-- // Evaluate fused weight to ensure it's materialized- mlx.Eval(fusedWeight)-- // Create fused linear layer- fusedLinear := &nn.Linear{Weight: fusedWeight}-- // Handle bias if present- if toQ.Bias != nil && toK.Bias != nil && toV.Bias != nil {- fusedBias := mlx.Concatenate([]*mlx.Array{toQ.Bias, toK.Bias, toV.Bias}, 0)- mlx.Eval(fusedBias)- fusedLinear.Bias = fusedBias- }-- attn.ToQKV = fusedLinear- attn.Fused = true-}--// Forward computes attention-func (attn *Attention) Forward(x *mlx.Array, cos, sin *mlx.Array) *mlx.Array {- shape := x.Shape()- B := shape[0]- L := shape[1]- D := shape[2]-- xFlat := mlx.Reshape(x, B*L, D)-- var q, k, v *mlx.Array- if attn.Fused && attn.ToQKV != nil {- // Fused QKV path: single matmul then split- qkv := attn.ToQKV.Forward(xFlat) // [B*L, 3*dim]-- // Split into Q, K, V along last dimension- // Each has shape [B*L, dim]- q = mlx.Slice(qkv, []int32{0, 0}, []int32{B * L, attn.Dim})- k = mlx.Slice(qkv, []int32{0, attn.Dim}, []int32{B * L, 2 * attn.Dim})- v = mlx.Slice(qkv, []int32{0, 2 * attn.Dim}, []int32{B * L, 3 * attn.Dim})- } else {- // Separate Q, K, V projections- q = attn.ToQ.Forward(xFlat)- k = attn.ToK.Forward(xFlat)- v = attn.ToV.Forward(xFlat)- }-- // Reshape to [B, L, nheads, head_dim]- q = mlx.Reshape(q, B, L, attn.NHeads, attn.HeadDim)- k = mlx.Reshape(k, B, L, attn.NHeads, attn.HeadDim)- v = mlx.Reshape(v, B, L, attn.NHeads, attn.HeadDim)-- // QK norm- q = mlx.RMSNorm(q, attn.NormQ, 1e-5)- k = mlx.RMSNorm(k, attn.NormK, 1e-5)-- // Apply RoPE if provided- if cos != nil && sin != nil {- q = applyRoPE3D(q, cos, sin)- k = applyRoPE3D(k, cos, sin)- }-- // Transpose to [B, nheads, L, head_dim]- q = mlx.Transpose(q, 0, 2, 1, 3)- k = mlx.Transpose(k, 0, 2, 1, 3)- v = mlx.Transpose(v, 0, 2, 1, 3)-- // SDPA- out := mlx.ScaledDotProductAttention(q, k, v, attn.Scale, false)-- // Transpose back and reshape- out = mlx.Transpose(out, 0, 2, 1, 3)- out = mlx.Reshape(out, B*L, attn.Dim)- out = attn.ToOut.Forward(out)-- return mlx.Reshape(out, B, L, attn.Dim)-}--// applyRoPE3D applies 3-axis rotary position embeddings-// x: [B, L, nheads, head_dim]-// cos, sin: [B, L, 1, head_dim/2]-func applyRoPE3D(x *mlx.Array, cos, sin *mlx.Array) *mlx.Array {- shape := x.Shape()- B := shape[0]- L := shape[1]- nheads := shape[2]- headDim := shape[3]- half := headDim / 2-- // Create even/odd index arrays- evenIdx := make([]int32, half)- oddIdx := make([]int32, half)- for i := range half {- evenIdx[i] = i * 2- oddIdx[i] = i*2 + 1- }- evenIndices := mlx.NewArrayInt32(evenIdx, []int32{half})- oddIndices := mlx.NewArrayInt32(oddIdx, []int32{half})-- // Extract x1 (even indices) and x2 (odd indices) along last axis- x1 := mlx.Take(x, evenIndices, 3) // [B, L, nheads, half]- x2 := mlx.Take(x, oddIndices, 3) // [B, L, nheads, half]-- // Apply rotation: [x1*cos - x2*sin, x1*sin + x2*cos]- r1 := mlx.Sub(mlx.Mul(x1, cos), mlx.Mul(x2, sin))- r2 := mlx.Add(mlx.Mul(x1, sin), mlx.Mul(x2, cos))-- // Stack and reshape to interleave: [r1_0, r2_0, r1_1, r2_1, ...]- r1 = mlx.ExpandDims(r1, 4) // [B, L, nheads, half, 1]- r2 = mlx.ExpandDims(r2, 4) // [B, L, nheads, half, 1]- stacked := mlx.Concatenate([]*mlx.Array{r1, r2}, 4) // [B, L, nheads, half, 2]- return mlx.Reshape(stacked, B, L, nheads, headDim)-}--// TransformerBlock is a single transformer block with optional AdaLN modulation-type TransformerBlock struct {- Attention *Attention `weight:"attention"`- FeedForward *FeedForward `weight:"feed_forward"`- AttentionNorm1 *nn.RMSNorm `weight:"attention_norm1"`- AttentionNorm2 *nn.RMSNorm `weight:"attention_norm2"`- FFNNorm1 *nn.RMSNorm `weight:"ffn_norm1"`- FFNNorm2 *nn.RMSNorm `weight:"ffn_norm2"`- AdaLN nn.LinearLayer `weight:"adaLN_modulation.0,optional"` // only if modulation- // Computed fields- HasModulation bool- Dim int32-}--// Forward applies the transformer block-func (tb *TransformerBlock) Forward(x *mlx.Array, adaln *mlx.Array, cos, sin *mlx.Array, eps float32) *mlx.Array {- if tb.AdaLN != nil && adaln != nil {- // Compute modulation: [B, 256] -> [B, 4*dim]- chunks := tb.AdaLN.Forward(adaln)-- // Split into 4 parts: scale_msa, gate_msa, scale_mlp, gate_mlp- chunkShape := chunks.Shape()- chunkDim := chunkShape[1] / 4-- scaleMSA := mlx.Slice(chunks, []int32{0, 0}, []int32{chunkShape[0], chunkDim})- gateMSA := mlx.Slice(chunks, []int32{0, chunkDim}, []int32{chunkShape[0], chunkDim * 2})- scaleMLP := mlx.Slice(chunks, []int32{0, chunkDim * 2}, []int32{chunkShape[0], chunkDim * 3})- gateMLP := mlx.Slice(chunks, []int32{0, chunkDim * 3}, []int32{chunkShape[0], chunkDim * 4})-- // Expand for broadcasting: [B, 1, dim]- scaleMSA = mlx.ExpandDims(scaleMSA, 1)- gateMSA = mlx.ExpandDims(gateMSA, 1)- scaleMLP = mlx.ExpandDims(scaleMLP, 1)- gateMLP = mlx.ExpandDims(gateMLP, 1)-- // Attention with modulation- normX := tb.AttentionNorm1.Forward(x, eps)- normX = mlx.Mul(normX, mlx.AddScalar(scaleMSA, 1.0))- attnOut := tb.Attention.Forward(normX, cos, sin)- attnOut = tb.AttentionNorm2.Forward(attnOut, eps)- x = mlx.Add(x, mlx.Mul(mlx.Tanh(gateMSA), attnOut))-- // FFN with modulation- normFFN := tb.FFNNorm1.Forward(x, eps)- normFFN = mlx.Mul(normFFN, mlx.AddScalar(scaleMLP, 1.0))- ffnOut := tb.FeedForward.Forward(normFFN)- ffnOut = tb.FFNNorm2.Forward(ffnOut, eps)- x = mlx.Add(x, mlx.Mul(mlx.Tanh(gateMLP), ffnOut))- } else {- // No modulation (context refiner)- attnOut := tb.Attention.Forward(tb.AttentionNorm1.Forward(x, eps), cos, sin)- x = mlx.Add(x, tb.AttentionNorm2.Forward(attnOut, eps))-- ffnOut := tb.FeedForward.Forward(tb.FFNNorm1.Forward(x, eps))- x = mlx.Add(x, tb.FFNNorm2.Forward(ffnOut, eps))- }-- return x-}--// FinalLayer outputs the denoised patches-type FinalLayer struct {- AdaLN nn.LinearLayer `weight:"adaLN_modulation.1"` // [256] -> [dim]- Output nn.LinearLayer `weight:"linear"` // [dim] -> [out_channels]- OutDim int32 // computed from Output-}--// Forward computes final output-func (fl *FinalLayer) Forward(x *mlx.Array, c *mlx.Array) *mlx.Array {- // c: [B, 256] -> scale: [B, dim]- scale := mlx.SiLU(c)- scale = fl.AdaLN.Forward(scale)- scale = mlx.ExpandDims(scale, 1) // [B, 1, dim]-- // LayerNorm (affine=False) then scale- x = layerNormNoAffine(x, 1e-6)- x = mlx.Mul(x, mlx.AddScalar(scale, 1.0))-- // Output projection- shape := x.Shape()- B := shape[0]- L := shape[1]- D := shape[2]- x = mlx.Reshape(x, B*L, D)- x = fl.Output.Forward(x)-- return mlx.Reshape(x, B, L, fl.OutDim)-}--// layerNormNoAffine applies layer norm without learnable parameters-func layerNormNoAffine(x *mlx.Array, eps float32) *mlx.Array {- ndim := x.Ndim()- lastAxis := ndim - 1-- mean := mlx.Mean(x, lastAxis, true)- xCentered := mlx.Sub(x, mean)- variance := mlx.Mean(mlx.Square(xCentered), lastAxis, true)- return mlx.Div(xCentered, mlx.Sqrt(mlx.AddScalar(variance, eps)))-}--// Transformer is the full Z-Image DiT model-type Transformer struct {- TEmbed *TimestepEmbedder `weight:"t_embedder"`- XEmbed *XEmbedder `weight:"all_x_embedder"`- CapEmbed *CapEmbedder `weight:"cap_embedder"`- NoiseRefiners []*TransformerBlock `weight:"noise_refiner"`- ContextRefiners []*TransformerBlock `weight:"context_refiner"`- Layers []*TransformerBlock `weight:"layers"`- FinalLayer *FinalLayer `weight:"all_final_layer.2-1"`- XPadToken *mlx.Array `weight:"x_pad_token"`- CapPadToken *mlx.Array `weight:"cap_pad_token"`- *TransformerConfig-}--// Load loads the Z-Image transformer from ollama blob storage.-func (m *Transformer) Load(modelManifest *manifest.ModelManifest) error {- fmt.Print(" Loading transformer... ")-- // Load config from blob- var cfg TransformerConfig- if err := modelManifest.ReadConfigJSON("transformer/config.json", &cfg); err != nil {- return fmt.Errorf("config: %w", err)- }- if len(cfg.AllPatchSize) > 0 {- cfg.PatchSize = cfg.AllPatchSize[0]- }- m.TransformerConfig = &cfg- m.NoiseRefiners = make([]*TransformerBlock, cfg.NRefinerLayers)- m.ContextRefiners = make([]*TransformerBlock, cfg.NRefinerLayers)- m.Layers = make([]*TransformerBlock, cfg.NLayers)-- weights, err := manifest.LoadWeightsFromManifest(modelManifest, "transformer")- if err != nil {- return fmt.Errorf("weights: %w", err)- }- if err := weights.Load(0); err != nil {- return fmt.Errorf("load weights: %w", err)- }- defer weights.ReleaseAll()-- return m.loadWeights(weights)-}--// loadWeights loads weights from any WeightSource into the model-func (m *Transformer) loadWeights(weights safetensors.WeightSource) error {- if err := safetensors.LoadModule(m, weights, ""); err != nil {- return fmt.Errorf("load module: %w", err)- }- m.initComputedFields()- fmt.Println("✓")- return nil-}--// initComputedFields initializes computed fields after loading weights-func (m *Transformer) initComputedFields() {- cfg := m.TransformerConfig- m.TEmbed.FreqEmbedSize = 256- m.FinalLayer.OutDim = m.FinalLayer.Output.OutputDim()- m.CapEmbed.Norm.Eps = 1e-6-- for _, block := range m.NoiseRefiners {- initTransformerBlock(block, cfg)- }- for _, block := range m.ContextRefiners {- initTransformerBlock(block, cfg)- }- for _, block := range m.Layers {- initTransformerBlock(block, cfg)- }-}--// FuseAllQKV fuses QKV projections in all attention layers for efficiency.-// This reduces 3 matmuls to 1 per attention layer, providing ~5-10% speedup.-func (m *Transformer) FuseAllQKV() {- for _, block := range m.NoiseRefiners {- block.Attention.FuseQKV()- }- for _, block := range m.ContextRefiners {- block.Attention.FuseQKV()- }- for _, block := range m.Layers {- block.Attention.FuseQKV()- }-}--// initTransformerBlock sets computed fields on a transformer block-func initTransformerBlock(block *TransformerBlock, cfg *TransformerConfig) {- block.Dim = cfg.Dim- block.HasModulation = block.AdaLN != nil-- // Init attention computed fields- attn := block.Attention- attn.NHeads = cfg.NHeads- attn.HeadDim = cfg.Dim / cfg.NHeads- attn.Dim = cfg.Dim- attn.Scale = float32(1.0 / math.Sqrt(float64(attn.HeadDim)))-- // Init feedforward OutDim- block.FeedForward.OutDim = block.FeedForward.W2.OutputDim()-- // Set eps on all RMSNorm layers- block.AttentionNorm1.Eps = cfg.NormEps- block.AttentionNorm2.Eps = cfg.NormEps- block.FFNNorm1.Eps = cfg.NormEps- block.FFNNorm2.Eps = cfg.NormEps-}--// RoPECache holds precomputed RoPE values-type RoPECache struct {- ImgCos *mlx.Array- ImgSin *mlx.Array- CapCos *mlx.Array- CapSin *mlx.Array- UnifiedCos *mlx.Array- UnifiedSin *mlx.Array- ImgLen int32- CapLen int32- GridH int32 // Image token grid height- GridW int32 // Image token grid width-}--// PrepareRoPECache precomputes RoPE values for the given image and caption lengths.-// hTok and wTok are the number of tokens in each dimension (latentH/patchSize, latentW/patchSize).-func (m *Transformer) PrepareRoPECache(hTok, wTok, capLen int32) *RoPECache {- imgLen := hTok * wTok-- // Image positions: grid over (1, H, W) starting at (capLen+1, 0, 0)- imgPos := createCoordinateGrid(1, hTok, wTok, capLen+1, 0, 0)- imgPos = mlx.ToBFloat16(imgPos)- // Caption positions: grid over (capLen, 1, 1) starting at (1, 0, 0)- capPos := createCoordinateGrid(capLen, 1, 1, 1, 0, 0)- capPos = mlx.ToBFloat16(capPos)-- // Compute RoPE from UNIFIED positions- unifiedPos := mlx.Concatenate([]*mlx.Array{imgPos, capPos}, 1)- unifiedCos, unifiedSin := prepareRoPE3D(unifiedPos, m.TransformerConfig.AxesDims)-- // Slice RoPE for image and caption parts- imgCos := mlx.Slice(unifiedCos, []int32{0, 0, 0, 0}, []int32{1, imgLen, 1, 64})- imgSin := mlx.Slice(unifiedSin, []int32{0, 0, 0, 0}, []int32{1, imgLen, 1, 64})- capCos := mlx.Slice(unifiedCos, []int32{0, imgLen, 0, 0}, []int32{1, imgLen + capLen, 1, 64})- capSin := mlx.Slice(unifiedSin, []int32{0, imgLen, 0, 0}, []int32{1, imgLen + capLen, 1, 64})-- return &RoPECache{- ImgCos: imgCos,- ImgSin: imgSin,- CapCos: capCos,- CapSin: capSin,- UnifiedCos: unifiedCos,- UnifiedSin: unifiedSin,- ImgLen: imgLen,- CapLen: capLen,- GridH: hTok,- GridW: wTok,- }-}--// Forward runs the Z-Image transformer with precomputed RoPE-func (m *Transformer) Forward(x *mlx.Array, t *mlx.Array, capFeats *mlx.Array, rope *RoPECache) *mlx.Array {- imgLen := rope.ImgLen-- // Timestep embedding -> [B, 256]- temb := m.TEmbed.Forward(mlx.MulScalar(t, m.TransformerConfig.TScale))-- // Embed image patches -> [B, L_img, dim]- x = m.XEmbed.Forward(x)-- // Embed caption features -> [B, L_cap, dim]- capEmb := m.CapEmbed.Forward(capFeats)-- eps := m.NormEps-- // Noise refiner: refine image patches with modulation- for _, refiner := range m.NoiseRefiners {- x = refiner.Forward(x, temb, rope.ImgCos, rope.ImgSin, eps)- }-- // Context refiner: refine caption (no modulation)- for _, refiner := range m.ContextRefiners {- capEmb = refiner.Forward(capEmb, nil, rope.CapCos, rope.CapSin, eps)- }-- // Concatenate image and caption for joint attention- unified := mlx.Concatenate([]*mlx.Array{x, capEmb}, 1)-- // Main transformer layers use full unified RoPE- for _, layer := range m.Layers {- unified = layer.Forward(unified, temb, rope.UnifiedCos, rope.UnifiedSin, eps)- }-- // Extract image tokens only- unifiedShape := unified.Shape()- B := unifiedShape[0]- imgOut := mlx.Slice(unified, []int32{0, 0, 0}, []int32{B, imgLen, unifiedShape[2]})-- // Final layer- return m.FinalLayer.Forward(imgOut, temb)-}--// ForwardWithCache runs the transformer with layer caching for faster inference.-// On refresh steps (step % cacheInterval == 0), all layers are computed and cached.-// On other steps, shallow layers (0 to cacheLayers-1) reuse cached outputs.-func (m *Transformer) ForwardWithCache(- x *mlx.Array,- t *mlx.Array,- capFeats *mlx.Array,- rope *RoPECache,- stepCache *cache.StepCache,- step int,- cacheInterval int,-) *mlx.Array {- imgLen := rope.ImgLen- cacheLayers := stepCache.NumLayers()- eps := m.NormEps-- // Timestep embedding -> [B, 256]- temb := m.TEmbed.Forward(mlx.MulScalar(t, m.TransformerConfig.TScale))-- // Embed image patches -> [B, L_img, dim]- x = m.XEmbed.Forward(x)-- // Context refiners: compute once on step 0, reuse forever- // (caption embedding doesn't depend on timestep or latents)- var capEmb *mlx.Array- if stepCache.GetConstant() != nil {- capEmb = stepCache.GetConstant()- } else {- capEmb = m.CapEmbed.Forward(capFeats)- for _, refiner := range m.ContextRefiners {- capEmb = refiner.Forward(capEmb, nil, rope.CapCos, rope.CapSin, eps)- }- stepCache.SetConstant(capEmb)- }-- // Noise refiners: always compute (depend on x which changes each step)- for _, refiner := range m.NoiseRefiners {- x = refiner.Forward(x, temb, rope.ImgCos, rope.ImgSin, eps)- }-- // Concatenate image and caption for joint attention- unified := mlx.Concatenate([]*mlx.Array{x, capEmb}, 1)-- // Determine if this is a cache refresh step- refreshCache := stepCache.ShouldRefresh(step, cacheInterval)-- // Main transformer layers with caching- for i, layer := range m.Layers {- if i < cacheLayers && !refreshCache && stepCache.Get(i) != nil {- // Use cached output for shallow layers- unified = stepCache.Get(i)- } else {- // Compute layer- unified = layer.Forward(unified, temb, rope.UnifiedCos, rope.UnifiedSin, eps)- // Cache shallow layer outputs on refresh steps- if i < cacheLayers && refreshCache {- stepCache.Set(i, unified)- }- }- }-- // Extract image tokens only- unifiedShape := unified.Shape()- B := unifiedShape[0]- imgOut := mlx.Slice(unified, []int32{0, 0, 0}, []int32{B, imgLen, unifiedShape[2]})-- // Final layer- return m.FinalLayer.Forward(imgOut, temb)-}--// createCoordinateGrid creates 3D position grid [1, d0*d1*d2, 3]-func createCoordinateGrid(d0, d1, d2, s0, s1, s2 int32) *mlx.Array {- // Create meshgrid and stack- total := d0 * d1 * d2- coords := make([]float32, total*3)-- idx := 0- for i := range d0 {- for j := range d1 {- for k := range d2 {- coords[idx*3+0] = float32(s0 + i)- coords[idx*3+1] = float32(s1 + j)- coords[idx*3+2] = float32(s2 + k)- idx++- }- }- }-- return mlx.NewArray(coords, []int32{1, total, 3})-}--// prepareRoPE3D computes cos/sin for 3-axis RoPE-// positions: [B, L, 3] with (h, w, t) coordinates-// axesDims: [32, 48, 48] - dimensions for each axis-// Returns: cos, sin each [B, L, 1, head_dim/2]-func prepareRoPE3D(positions *mlx.Array, axesDims []int32) (*mlx.Array, *mlx.Array) {- // Compute frequencies for each axis- // dims = [32, 48, 48], so halves = [16, 24, 24]- ropeTheta := float32(256.0)-- freqs := make([]*mlx.Array, 3)- for axis := range 3 {- half := axesDims[axis] / 2- f := make([]float32, half)- for i := range half {- f[i] = float32(math.Exp(-math.Log(float64(ropeTheta)) * float64(i) / float64(half)))- }- freqs[axis] = mlx.NewArray(f, []int32{1, 1, 1, half})- }-- // Extract position coordinates- shape := positions.Shape()- B := shape[0]- L := shape[1]-- // positions[:, :, 0] -> h positions- posH := mlx.Slice(positions, []int32{0, 0, 0}, []int32{B, L, 1})- posW := mlx.Slice(positions, []int32{0, 0, 1}, []int32{B, L, 2})- posT := mlx.Slice(positions, []int32{0, 0, 2}, []int32{B, L, 3})-- // Compute args: pos * freqs for each axis- posH = mlx.ExpandDims(posH, 3) // [B, L, 1, 1]- posW = mlx.ExpandDims(posW, 3)- posT = mlx.ExpandDims(posT, 3)-- argsH := mlx.Mul(posH, freqs[0]) // [B, L, 1, 16]- argsW := mlx.Mul(posW, freqs[1]) // [B, L, 1, 24]- argsT := mlx.Mul(posT, freqs[2]) // [B, L, 1, 24]-- // Concatenate: [B, L, 1, 16+24+24=64]- args := mlx.Concatenate([]*mlx.Array{argsH, argsW, argsT}, 3)-- // Compute cos and sin- return mlx.Cos(args), mlx.Sin(args)-}--// PatchifyLatents converts latents [B, C, H, W] to patches [B, L, C*patch^2]-// Matches Python: x.reshape(C, 1, 1, H_tok, 2, W_tok, 2).transpose(1,2,3,5,4,6,0).reshape(1,-1,C*4)-func PatchifyLatents(latents *mlx.Array, patchSize int32) *mlx.Array {- shape := latents.Shape()- C := shape[1]- H := shape[2]- W := shape[3]-- pH := H / patchSize // H_tok- pW := W / patchSize // W_tok-- // Match Python exactly: reshape treating B=1 as part of contiguous data- // [1, C, H, W] -> [C, 1, 1, pH, 2, pW, 2]- x := mlx.Reshape(latents, C, 1, 1, pH, patchSize, pW, patchSize)-- // Python: transpose(1, 2, 3, 5, 4, 6, 0)- // [C, 1, 1, pH, 2, pW, 2] -> [1, 1, pH, pW, 2, 2, C]- x = mlx.Transpose(x, 1, 2, 3, 5, 4, 6, 0)-- // [1, 1, pH, pW, 2, 2, C] -> [1, pH*pW, C*4]- return mlx.Reshape(x, 1, pH*pW, C*patchSize*patchSize)-}--// UnpatchifyLatents converts patches [B, L, C*patch^2] back to [B, C, H, W]-// Matches Python: out.reshape(1,1,H_tok,W_tok,2,2,C).transpose(6,0,1,2,4,3,5).reshape(1,C,H,W)-func UnpatchifyLatents(patches *mlx.Array, patchSize, H, W, C int32) *mlx.Array {- pH := H / patchSize- pW := W / patchSize-- // [1, L, C*4] -> [1, 1, pH, pW, 2, 2, C]- x := mlx.Reshape(patches, 1, 1, pH, pW, patchSize, patchSize, C)-- // Python: transpose(6, 0, 1, 2, 4, 3, 5)- // [1, 1, pH, pW, 2, 2, C] -> [C, 1, 1, pH, 2, pW, 2]- x = mlx.Transpose(x, 6, 0, 1, 2, 4, 3, 5)-- // [C, 1, 1, pH, 2, pW, 2] -> [1, C, H, W]- return mlx.Reshape(x, 1, C, H, W)-}diff --git a/x/imagegen/models/zimage/vae.go b/x/imagegen/models/zimage/vae.godeleted file mode 100644index 74633b594..000000000--- a/x/imagegen/models/zimage/vae.go+++ /dev/null@@ -1,820 +0,0 @@-package zimage--import (- "fmt"- "math"-- "github.com/ollama/ollama/x/imagegen/manifest"- "github.com/ollama/ollama/x/imagegen/mlx"- "github.com/ollama/ollama/x/imagegen/safetensors"- "github.com/ollama/ollama/x/imagegen/vae"-)--// VAEConfig holds VAE decoder configuration-type VAEConfig struct {- InChannels int32 `json:"in_channels"`- OutChannels int32 `json:"out_channels"`- LatentChannels int32 `json:"latent_channels"`- BlockOutChannels []int32 `json:"block_out_channels"`- LayersPerBlock int32 `json:"layers_per_block"`- NormNumGroups int32 `json:"norm_num_groups"`- ScalingFactor float32 `json:"scaling_factor"`- ShiftFactor float32 `json:"shift_factor"`-}--// GroupNormLayer implements group normalization-type GroupNormLayer struct {- Weight *mlx.Array- Bias *mlx.Array- NumGroups int32- Eps float32-}--// NewGroupNorm creates a group norm layer-func NewGroupNorm(weight, bias *mlx.Array, numGroups int32) *GroupNormLayer {- return &GroupNormLayer{- Weight: weight,- Bias: bias,- NumGroups: numGroups,- Eps: 1e-5,- }-}--// Forward applies group normalization-// Input and output are in NHWC format [B, H, W, C]-func (gn *GroupNormLayer) Forward(x *mlx.Array) *mlx.Array {- // x: [B, H, W, C] (NHWC format)- shape := x.Shape()- B := shape[0]- H := shape[1]- W := shape[2]- C := shape[3]-- // For large spatial sizes, use tiled computation to avoid CUDA grid limits- // CUDA grid.y max is 65535, so H*W/16 must be <= 65535, meaning H*W <= ~1M- // To be safe, tile when H*W > 512*512 = 262144- if H*W > 512*512 {- return gn.forwardTiled(x, B, H, W, C)- }-- return gn.forwardSmall(x, B, H, W, C)-}--// forwardSmall is the standard GroupNorm for tensors that fit within CUDA grid limits-func (gn *GroupNormLayer) forwardSmall(x *mlx.Array, B, H, W, C int32) *mlx.Array {- // Reshape to [B, H, W, groups, C/groups]- groupSize := C / gn.NumGroups- x = mlx.Reshape(x, B, H, W, gn.NumGroups, groupSize)-- // Compute mean and variance per group (over H, W, and C/groups dimensions)- mean := mlx.Mean(x, 1, true)- mean = mlx.Mean(mean, 2, true)- mean = mlx.Mean(mean, 4, true)-- xCentered := mlx.Sub(x, mean)-- // Variance over same axes- sq := mlx.Square(xCentered)- variance := mlx.Mean(sq, 1, true)- variance = mlx.Mean(variance, 2, true)- variance = mlx.Mean(variance, 4, true)-- // Normalize- xNorm := mlx.Div(xCentered, mlx.Sqrt(mlx.AddScalar(variance, gn.Eps)))-- // Reshape back to [B, H, W, C]- xNorm = mlx.Reshape(xNorm, B, H, W, C)-- // Scale and shift (weight and bias are [C])- if gn.Weight != nil {- weight := mlx.Reshape(gn.Weight, 1, 1, 1, C)- xNorm = mlx.Mul(xNorm, weight)- }- if gn.Bias != nil {- bias := mlx.Reshape(gn.Bias, 1, 1, 1, C)- xNorm = mlx.Add(xNorm, bias)- }-- return xNorm-}--// forwardTiled handles large tensors by processing in H-tiles to avoid CUDA grid limits-func (gn *GroupNormLayer) forwardTiled(x *mlx.Array, B, H, W, C int32) *mlx.Array {- groupSize := C / gn.NumGroups-- // Keep the input - we need it for slicing tiles later- // Track if we were the ones who kept it, so we can restore state after- wasKept := x.Kept()- mlx.Keep(x)-- // Compute per-group mean and variance using flattened spatial dimensions- // Build the entire compute graph first, then eval once- // Reshape to [B, H*W, groups, groupSize]- xFlat := mlx.Reshape(x, B, H*W, gn.NumGroups, groupSize)-- // Mean over spatial (axis 1) and groupSize (axis 3) dimensions- // Result shape: [B, 1, groups, 1]- mean1 := mlx.Mean(xFlat, 1, true)- mean := mlx.Mean(mean1, 3, true)-- // Variance using E[X^2] - E[X]^2- xSq := mlx.Square(xFlat)- meanSq1 := mlx.Mean(xSq, 1, true)- meanSq := mlx.Mean(meanSq1, 3, true)- meanSquared := mlx.Square(mean)- variance := mlx.Sub(meanSq, meanSquared)-- // invStd = 1/sqrt(var + eps)- varPlusEps := mlx.AddScalar(variance, gn.Eps)- stdDev := mlx.Sqrt(varPlusEps)- one := mlx.Full(1.0, 1)- invStd := mlx.Div(one, stdDev)-- // Eval mean and invStd together - these are what we need for the tile loop- mlx.Keep(mean, invStd)- mlx.Eval(mean, invStd)-- // Tile along H dimension- tileH := 512 * 512 / W- if tileH < 1 {- tileH = 1- }- if tileH > H {- tileH = H- }-- // Prepare weight and bias reshaped for 4D broadcast [1, 1, groups, groupSize]- var weightGN, biasGN *mlx.Array- if gn.Weight != nil {- weightGN = mlx.Reshape(gn.Weight, 1, 1, gn.NumGroups, groupSize)- mlx.Keep(weightGN)- mlx.Eval(weightGN)- }- if gn.Bias != nil {- biasGN = mlx.Reshape(gn.Bias, 1, 1, gn.NumGroups, groupSize)- mlx.Keep(biasGN)- mlx.Eval(biasGN)- }-- var tiles []*mlx.Array- for hStart := int32(0); hStart < H; hStart += tileH {- hEnd := hStart + tileH- if hEnd > H {- hEnd = H- }- tileHeight := hEnd - hStart- spatialSize := tileHeight * W-- // Build the compute graph for this tile (no intermediate Evals)- // Extract tile and flatten spatial dims: [B, tileH*W, groups, groupSize]- tile := mlx.Slice(x, []int32{0, hStart, 0, 0}, []int32{B, hEnd, W, C})- tileFlat := mlx.Reshape(tile, B, spatialSize, gn.NumGroups, groupSize)-- // Normalize: (x - mean) * invStd- tileCentered := mlx.Sub(tileFlat, mean)- tileNorm := mlx.Mul(tileCentered, invStd)-- // Apply scale and shift in 4D space- if weightGN != nil {- tileNorm = mlx.Mul(tileNorm, weightGN)- }- if biasGN != nil {- tileNorm = mlx.Add(tileNorm, biasGN)- }-- // Reshape back to [B, tileH, W, C]- tileOut := mlx.Reshape(tileNorm, B, tileHeight, W, C)-- // Now eval and keep this tile- mlx.Keep(tileOut)- mlx.Eval(tileOut)-- tiles = append(tiles, tileOut)- }-- // Concatenate tiles along H axis- var result *mlx.Array- if len(tiles) == 1 {- result = tiles[0]- } else {- result = mlx.Concatenate(tiles, 1)- mlx.Eval(result)- // Free the individual tiles now that they're concatenated- for _, t := range tiles {- t.Free()- }- }-- // Clean up kept arrays- // Restore x's kept state - only free if we were the ones who kept it- if !wasKept {- x.Free()- }- mean.Free()- invStd.Free()- if weightGN != nil {- weightGN.Free()- }- if biasGN != nil {- biasGN.Free()- }-- return result-}--// Conv2D represents a 2D convolution layer-// Works natively in NHWC format (MLX's native format)-type Conv2D struct {- Weight *mlx.Array // [out_channels, kH, kW, in_channels] (OHWI for MLX)- Bias *mlx.Array // [out_channels]- Stride int32- Padding int32-}--// NewConv2D creates a Conv2D layer-// weight comes in as [out_channels, in_channels, kH, kW] (OIHW from PyTorch)-// we transpose to [out_channels, kH, kW, in_channels] (OHWI for MLX)-func NewConv2D(weight, bias *mlx.Array, stride, padding int32) *Conv2D {- // Transpose weight from OIHW to OHWI- // [O, I, H, W] -> [O, H, W, I]- weightOHWI := mlx.Transpose(weight, 0, 2, 3, 1)- return &Conv2D{- Weight: weightOHWI,- Bias: bias,- Stride: stride,- Padding: padding,- }-}--// Forward applies convolution-// Input and output are in NHWC format [N, H, W, C]-func (conv *Conv2D) Forward(x *mlx.Array) *mlx.Array {- // Conv in NHWC format (MLX native)- out := mlx.Conv2d(x, conv.Weight, conv.Stride, conv.Padding)-- if conv.Bias != nil {- // Bias is [C], reshape to [1, 1, 1, C] for NHWC broadcast- bias := mlx.Reshape(conv.Bias, 1, 1, 1, conv.Bias.Dim(0))- out = mlx.Add(out, bias)- }-- return out-}--// ResnetBlock2D implements a ResNet block for VAE-type ResnetBlock2D struct {- Norm1 *GroupNormLayer- Conv1 *Conv2D- Norm2 *GroupNormLayer- Conv2 *Conv2D- ConvShortcut *Conv2D // nil if in_channels == out_channels-}--// NewResnetBlock2D creates a ResNet block-func NewResnetBlock2D(weights safetensors.WeightSource, prefix string, numGroups int32) (*ResnetBlock2D, error) {- norm1Weight, err := weights.GetTensor(prefix + ".norm1.weight")- if err != nil {- return nil, err- }- norm1Bias, err := weights.GetTensor(prefix + ".norm1.bias")- if err != nil {- return nil, err- }-- conv1Weight, err := weights.GetTensor(prefix + ".conv1.weight")- if err != nil {- return nil, err- }- conv1Bias, err := weights.GetTensor(prefix + ".conv1.bias")- if err != nil {- return nil, err- }-- norm2Weight, err := weights.GetTensor(prefix + ".norm2.weight")- if err != nil {- return nil, err- }- norm2Bias, err := weights.GetTensor(prefix + ".norm2.bias")- if err != nil {- return nil, err- }-- conv2Weight, err := weights.GetTensor(prefix + ".conv2.weight")- if err != nil {- return nil, err- }- conv2Bias, err := weights.GetTensor(prefix + ".conv2.bias")- if err != nil {- return nil, err- }-- block := &ResnetBlock2D{- Norm1: NewGroupNorm(norm1Weight, norm1Bias, numGroups),- Conv1: NewConv2D(conv1Weight, conv1Bias, 1, 1),- Norm2: NewGroupNorm(norm2Weight, norm2Bias, numGroups),- Conv2: NewConv2D(conv2Weight, conv2Bias, 1, 1),- }-- if weights.HasTensor(prefix + ".conv_shortcut.weight") {- shortcutWeight, err := weights.GetTensor(prefix + ".conv_shortcut.weight")- if err != nil {- return nil, err- }- shortcutBias, err := weights.GetTensor(prefix + ".conv_shortcut.bias")- if err != nil {- return nil, err- }- block.ConvShortcut = NewConv2D(shortcutWeight, shortcutBias, 1, 0)- }-- return block, nil-}--// Forward applies the ResNet block with staged evaluation-func (rb *ResnetBlock2D) Forward(x *mlx.Array) *mlx.Array {- var h *mlx.Array-- // Stage 1: norm1- {- h = rb.Norm1.Forward(x)- mlx.Eval(h)- }-- // Stage 2: silu + conv1- {- prev := h- h = mlx.SiLU(h)- h = rb.Conv1.Forward(h)- prev.Free()- mlx.Eval(h)- }-- // Stage 3: norm2- {- prev := h- h = rb.Norm2.Forward(h)- prev.Free()- mlx.Eval(h)- }-- // Stage 4: silu + conv2- {- prev := h- h = mlx.SiLU(h)- h = rb.Conv2.Forward(h)- prev.Free()- mlx.Eval(h)- }-- // Residual connection- {- prev := h- if rb.ConvShortcut != nil {- shortcut := rb.ConvShortcut.Forward(x)- h = mlx.Add(h, shortcut)- } else {- h = mlx.Add(h, x)- }- prev.Free()- mlx.Eval(h)- }-- return h-}--// VAEAttentionBlock implements self-attention for VAE-type VAEAttentionBlock struct {- GroupNorm *GroupNormLayer- ToQWeight *mlx.Array- ToQBias *mlx.Array- ToKWeight *mlx.Array- ToKBias *mlx.Array- ToVWeight *mlx.Array- ToVBias *mlx.Array- ToOutWeight *mlx.Array- ToOutBias *mlx.Array- NumHeads int32-}--// NewVAEAttentionBlock creates an attention block-func NewVAEAttentionBlock(weights safetensors.WeightSource, prefix string, numGroups int32) (*VAEAttentionBlock, error) {- normWeight, err := weights.GetTensor(prefix + ".group_norm.weight")- if err != nil {- return nil, err- }- normBias, err := weights.GetTensor(prefix + ".group_norm.bias")- if err != nil {- return nil, err- }-- toQWeight, err := weights.GetTensor(prefix + ".to_q.weight")- if err != nil {- return nil, err- }- toQBias, err := weights.GetTensor(prefix + ".to_q.bias")- if err != nil {- return nil, err- }-- toKWeight, err := weights.GetTensor(prefix + ".to_k.weight")- if err != nil {- return nil, err- }- toKBias, err := weights.GetTensor(prefix + ".to_k.bias")- if err != nil {- return nil, err- }-- toVWeight, err := weights.GetTensor(prefix + ".to_v.weight")- if err != nil {- return nil, err- }- toVBias, err := weights.GetTensor(prefix + ".to_v.bias")- if err != nil {- return nil, err- }-- toOutWeight, err := weights.GetTensor(prefix + ".to_out.0.weight")- if err != nil {- return nil, err- }- toOutBias, err := weights.GetTensor(prefix + ".to_out.0.bias")- if err != nil {- return nil, err- }-- return &VAEAttentionBlock{- GroupNorm: NewGroupNorm(normWeight, normBias, numGroups),- ToQWeight: mlx.Transpose(toQWeight, 1, 0),- ToQBias: toQBias,- ToKWeight: mlx.Transpose(toKWeight, 1, 0),- ToKBias: toKBias,- ToVWeight: mlx.Transpose(toVWeight, 1, 0),- ToVBias: toVBias,- ToOutWeight: mlx.Transpose(toOutWeight, 1, 0),- ToOutBias: toOutBias,- NumHeads: 1,- }, nil-}--// Forward applies attention with staged evaluation-// Input and output are in NHWC format [B, H, W, C]-func (ab *VAEAttentionBlock) Forward(x *mlx.Array) *mlx.Array {- residual := x- shape := x.Shape()- B := shape[0]- H := shape[1]- W := shape[2]- C := shape[3]-- var h *mlx.Array-- // Stage 1: GroupNorm + reshape to [B, H*W, C]- {- h = ab.GroupNorm.Forward(x)- h = mlx.Reshape(h, B, H*W, C)- mlx.Eval(h)- }-- var out *mlx.Array-- // Stage 2: Q, K, V projections + attention- {- q := mlx.Linear(h, ab.ToQWeight)- q = mlx.Add(q, ab.ToQBias)- k := mlx.Linear(h, ab.ToKWeight)- k = mlx.Add(k, ab.ToKBias)- v := mlx.Linear(h, ab.ToVWeight)- v = mlx.Add(v, ab.ToVBias)- h.Free()-- q = mlx.ExpandDims(q, 1)- k = mlx.ExpandDims(k, 1)- v = mlx.ExpandDims(v, 1)-- scale := float32(1.0 / math.Sqrt(float64(C)))- out = mlx.ScaledDotProductAttention(q, k, v, scale, false)- out = mlx.Squeeze(out, 1)- mlx.Eval(out)- }-- // Stage 3: Output projection + reshape + residual- {- prev := out- out = mlx.Linear(out, ab.ToOutWeight)- out = mlx.Add(out, ab.ToOutBias)- out = mlx.Reshape(out, B, H, W, C)- out = mlx.Add(out, residual)- prev.Free()- mlx.Eval(out)- }-- return out-}--// UpDecoderBlock2D implements an upsampling decoder block-type UpDecoderBlock2D struct {- ResnetBlocks []*ResnetBlock2D- Upsample *Conv2D-}--// NewUpDecoderBlock2D creates an up decoder block-func NewUpDecoderBlock2D(weights safetensors.WeightSource, prefix string, numLayers, numGroups int32, hasUpsample bool) (*UpDecoderBlock2D, error) {- resnets := make([]*ResnetBlock2D, numLayers)- for i := range numLayers {- resPrefix := fmt.Sprintf("%s.resnets.%d", prefix, i)- resnet, err := NewResnetBlock2D(weights, resPrefix, numGroups)- if err != nil {- return nil, err- }- resnets[i] = resnet- }-- var upsample *Conv2D- if hasUpsample {- upWeight, err := weights.GetTensor(prefix + ".upsamplers.0.conv.weight")- if err != nil {- return nil, err- }- upBias, err := weights.GetTensor(prefix + ".upsamplers.0.conv.bias")- if err != nil {- return nil, err- }- upsample = NewConv2D(upWeight, upBias, 1, 1)- }-- return &UpDecoderBlock2D{- ResnetBlocks: resnets,- Upsample: upsample,- }, nil-}--// Forward applies the up decoder block with staged evaluation to reduce peak memory-func (ub *UpDecoderBlock2D) Forward(x *mlx.Array) *mlx.Array {- for _, resnet := range ub.ResnetBlocks {- prev := x- x = resnet.Forward(x) // ResNet handles its own pools- prev.Free()- }-- if ub.Upsample != nil {- // Stage 1: Upsample2x (nearest neighbor)- {- prev := x- x = Upsample2x(x)- prev.Free()- mlx.Eval(x)- }-- // Stage 2: Upsample conv- {- prev := x- x = ub.Upsample.Forward(x)- prev.Free()- mlx.Eval(x)- }- }-- return x-}--// VAEMidBlock is the middle block with attention-type VAEMidBlock struct {- Resnet1 *ResnetBlock2D- Attention *VAEAttentionBlock- Resnet2 *ResnetBlock2D-}--// NewVAEMidBlock creates the mid block-func NewVAEMidBlock(weights safetensors.WeightSource, prefix string, numGroups int32) (*VAEMidBlock, error) {- resnet1, err := NewResnetBlock2D(weights, prefix+".resnets.0", numGroups)- if err != nil {- return nil, err- }-- attention, err := NewVAEAttentionBlock(weights, prefix+".attentions.0", numGroups)- if err != nil {- return nil, err- }-- resnet2, err := NewResnetBlock2D(weights, prefix+".resnets.1", numGroups)- if err != nil {- return nil, err- }-- return &VAEMidBlock{- Resnet1: resnet1,- Attention: attention,- Resnet2: resnet2,- }, nil-}--// Forward applies the mid block with staged evaluation-func (mb *VAEMidBlock) Forward(x *mlx.Array) *mlx.Array {- prev := x- x = mb.Resnet1.Forward(x) // ResNet handles its own pools- prev.Free()-- // Attention handles its own pools- prev = x- x = mb.Attention.Forward(x)- prev.Free()-- prev = x- x = mb.Resnet2.Forward(x) // ResNet handles its own pools- prev.Free()-- return x-}--// VAEDecoder is the full VAE decoder-type VAEDecoder struct {- Config *VAEConfig- ConvIn *Conv2D- MidBlock *VAEMidBlock- UpBlocks []*UpDecoderBlock2D- ConvNormOut *GroupNormLayer- ConvOut *Conv2D-- // Tiling configuration (nil = no tiling)- Tiling *vae.TilingConfig-}--// Load loads the VAE decoder from ollama blob storage.-func (m *VAEDecoder) Load(modelManifest *manifest.ModelManifest) error {- // Load config from blob- var cfg VAEConfig- if err := modelManifest.ReadConfigJSON("vae/config.json", &cfg); err != nil {- return fmt.Errorf("config: %w", err)- }- m.Config = &cfg-- // Load weights from tensor blobs- weights, err := manifest.LoadWeightsFromManifest(modelManifest, "vae")- if err != nil {- return fmt.Errorf("weights: %w", err)- }- if err := weights.Load(0); err != nil {- return fmt.Errorf("load weights: %w", err)- }- defer weights.ReleaseAll()-- return m.loadWeights(weights, &cfg)-}--// loadWeights loads VAE weights from any WeightSource-func (m *VAEDecoder) loadWeights(weights safetensors.WeightSource, cfg *VAEConfig) error {- var err error-- // Load conv_in- fmt.Print(" Loading conv_in... ")- convInWeight, err := weights.GetTensor("decoder.conv_in.weight")- if err != nil {- return err- }- convInBias, err := weights.GetTensor("decoder.conv_in.bias")- if err != nil {- return err- }- m.ConvIn = NewConv2D(convInWeight, convInBias, 1, 1)- fmt.Println("✓")-- // Load mid block- fmt.Print(" Loading mid block... ")- m.MidBlock, err = NewVAEMidBlock(weights, "decoder.mid_block", cfg.NormNumGroups)- if err != nil {- return err- }- fmt.Println("✓")-- // Load up blocks- fmt.Print(" Loading up blocks... ")- numBlocks := len(cfg.BlockOutChannels)- m.UpBlocks = make([]*UpDecoderBlock2D, numBlocks)- for i := range numBlocks {- prefix := fmt.Sprintf("decoder.up_blocks.%d", i)- hasUpsample := i < numBlocks-1- m.UpBlocks[i], err = NewUpDecoderBlock2D(weights, prefix, cfg.LayersPerBlock+1, cfg.NormNumGroups, hasUpsample)- if err != nil {- return err- }- }- fmt.Printf("✓ [%d blocks]\n", numBlocks)-- // Load conv_norm_out- fmt.Print(" Loading conv_norm_out... ")- normWeight, err := weights.GetTensor("decoder.conv_norm_out.weight")- if err != nil {- return err- }- normBias, err := weights.GetTensor("decoder.conv_norm_out.bias")- if err != nil {- return err- }- m.ConvNormOut = NewGroupNorm(normWeight, normBias, cfg.NormNumGroups)- fmt.Println("✓")-- // Load conv_out- fmt.Print(" Loading conv_out... ")- convOutWeight, err := weights.GetTensor("decoder.conv_out.weight")- if err != nil {- return err- }- convOutBias, err := weights.GetTensor("decoder.conv_out.bias")- if err != nil {- return err- }- m.ConvOut = NewConv2D(convOutWeight, convOutBias, 1, 1)- fmt.Println("✓")-- return nil-}--// Decode decodes latents to images.-// Input latents are in NCHW format, output is in NCHW format.-// If Tiling is set, uses tiled decoding to reduce memory for large images.-func (v *VAEDecoder) Decode(latents *mlx.Array) *mlx.Array {- // Scale latents- z := mlx.DivScalar(latents, v.Config.ScalingFactor)- z = mlx.AddScalar(z, v.Config.ShiftFactor)- // Convert NCHW -> NHWC for internal processing- z = mlx.Transpose(z, 0, 2, 3, 1)-- // Use tiled decoding if enabled- if v.Tiling != nil {- mlx.Eval(z)- return vae.DecodeTiled(z, v.Tiling, v.decodeTile)- }-- // Direct decode- h := v.decodeTile(z)- h = mlx.ClipScalar(h, 0.0, 1.0, true, true)- // Convert NHWC -> NCHW for output- h = mlx.Transpose(h, 0, 3, 1, 2)- mlx.Eval(h)- return h-}--// decodeTile decodes a single latent tile to pixels.-// Input: [B, H, W, C] latent tile in NHWC format (already scaled)-// Output: [B, H*8, W*8, 3] pixel tile in NHWC format-func (v *VAEDecoder) decodeTile(z *mlx.Array) *mlx.Array {- h := v.ConvIn.Forward(z)- mlx.Eval(h)-- prev := h- h = v.MidBlock.Forward(h)- prev.Free()-- for _, upBlock := range v.UpBlocks {- prev = h- h = upBlock.Forward(h)- prev.Free()- }-- prev = h- h = v.ConvNormOut.Forward(h)- mlx.Eval(h) // Eval after GroupNorm to avoid grid dimension issues- prev.Free()-- prev = h- h = mlx.SiLU(h)- h = v.ConvOut.Forward(h)- mlx.Eval(h)- prev.Free()-- // VAE outputs [-1, 1], convert to [0, 1]- h = mlx.MulScalar(h, 0.5)- h = mlx.AddScalar(h, 0.5)-- return h-}--// Upsample2x performs 2x nearest neighbor upsampling using Take.-// Input and output are in NHWC format: [B, H, W, C] -> [B, H*2, W*2, C]-// Uses Take with repeated indices to produce contiguous output.-func Upsample2x(x *mlx.Array) *mlx.Array {- shape := x.Shape()- H := shape[1]- W := shape[2]-- // Create indices [0, 0, 1, 1, 2, 2, ...] for nearest neighbor- // For H dimension- hIdx := mlx.ArangeInt(0, H, 1, mlx.DtypeInt32)- hIdx = mlx.Reshape(hIdx, H, 1)- hIdx = mlx.BroadcastTo(hIdx, []int32{H, 2})- hIdx = mlx.Reshape(hIdx, H*2)-- // For W dimension- wIdx := mlx.ArangeInt(0, W, 1, mlx.DtypeInt32)- wIdx = mlx.Reshape(wIdx, W, 1)- wIdx = mlx.BroadcastTo(wIdx, []int32{W, 2})- wIdx = mlx.Reshape(wIdx, W*2)-- // Take along H axis (axis 1 in NHWC)- x = mlx.Take(x, hIdx, 1)- // Take along W axis (axis 2 in NHWC)- x = mlx.Take(x, wIdx, 2)-- return x-}diff --git a/x/imagegen/models/zimage/zimage.go b/x/imagegen/models/zimage/zimage.godeleted file mode 100644index 06e5a4091..000000000--- a/x/imagegen/models/zimage/zimage.go+++ /dev/null@@ -1,488 +0,0 @@-// Package zimage implements the Z-Image diffusion transformer model.-package zimage--import (- "context"- "fmt"- "time"-- "github.com/ollama/ollama/x/imagegen/cache"- "github.com/ollama/ollama/x/imagegen/manifest"- "github.com/ollama/ollama/x/imagegen/mlx"- "github.com/ollama/ollama/x/imagegen/tokenizer"- "github.com/ollama/ollama/x/imagegen/vae"-)--// GenerateConfig holds all options for image generation.-type GenerateConfig struct {- Prompt string- NegativePrompt string // Empty = no CFG- CFGScale float32 // Only used if NegativePrompt is set (default: 4.0)- Width int32 // Image width (default: 1024)- Height int32 // Image height (default: 1024)- Steps int // Denoising steps (default: 9 for turbo)- Seed int64 // Random seed- Progress func(step, totalSteps int) // Optional progress callback- CapturePath string // GPU capture path (debug)-- // TeaCache options (timestep embedding aware caching)- TeaCache bool // TeaCache is always enabled for faster inference- TeaCacheThreshold float32 // Threshold for cache reuse (default: 0.1, lower = more aggressive)-- // Fused QKV (fuse Q/K/V projections into single matmul)- FusedQKV bool // Enable fused QKV projection (default: false)-}--// Model represents a Z-Image diffusion model.-type Model struct {- ModelName string- Tokenizer *tokenizer.Tokenizer- TextEncoder *Qwen3TextEncoder- Transformer *Transformer- VAEDecoder *VAEDecoder- qkvFused bool // Track if QKV has been fused (do only once)-}--// Load loads the Z-Image model from ollama blob storage.-func (m *Model) Load(modelName string) error {- fmt.Printf("Loading Z-Image model from manifest: %s...\n", modelName)- start := time.Now()-- if mlx.GPUIsAvailable() {- mlx.SetDefaultDeviceGPU()- mlx.EnableCompile()- }-- m.ModelName = modelName-- // Load manifest- manifest, err := manifest.LoadManifest(modelName)- if err != nil {- return fmt.Errorf("load manifest: %w", err)- }-- // Load tokenizer from manifest with config- fmt.Print(" Loading tokenizer... ")- tokData, err := manifest.ReadConfig("tokenizer/tokenizer.json")- if err != nil {- return fmt.Errorf("tokenizer: %w", err)- }-- // Try to read tokenizer config files from manifest- tokConfig := &tokenizer.TokenizerConfig{}- if data, err := manifest.ReadConfig("tokenizer/tokenizer_config.json"); err == nil {- tokConfig.TokenizerConfigJSON = data- }- if data, err := manifest.ReadConfig("tokenizer/generation_config.json"); err == nil {- tokConfig.GenerationConfigJSON = data- }- if data, err := manifest.ReadConfig("tokenizer/special_tokens_map.json"); err == nil {- tokConfig.SpecialTokensMapJSON = data- }-- tok, err := tokenizer.LoadFromBytesWithConfig(tokData, tokConfig)- if err != nil {- return fmt.Errorf("tokenizer: %w", err)- }- m.Tokenizer = tok- fmt.Println("✓")-- // Load text encoder- m.TextEncoder = &Qwen3TextEncoder{}- if err := m.TextEncoder.Load(manifest, "text_encoder/config.json"); err != nil {- return fmt.Errorf("text encoder: %w", err)- }- mlx.Eval(mlx.Collect(m.TextEncoder)...)- fmt.Printf(" (%.1f GB, peak %.1f GB)\n",- float64(mlx.MetalGetActiveMemory())/(1024*1024*1024),- float64(mlx.MetalGetPeakMemory())/(1024*1024*1024))-- // Load transformer- m.Transformer = &Transformer{}- if err := m.Transformer.Load(manifest); err != nil {- return fmt.Errorf("transformer: %w", err)- }- mlx.Eval(mlx.Collect(m.Transformer)...)- fmt.Printf(" (%.1f GB, peak %.1f GB)\n",- float64(mlx.MetalGetActiveMemory())/(1024*1024*1024),- float64(mlx.MetalGetPeakMemory())/(1024*1024*1024))-- // Load VAE decoder- m.VAEDecoder = &VAEDecoder{}- if err := m.VAEDecoder.Load(manifest); err != nil {- return fmt.Errorf("VAE decoder: %w", err)- }- mlx.Eval(mlx.Collect(m.VAEDecoder)...)- fmt.Printf(" (%.1f GB, peak %.1f GB)\n",- float64(mlx.MetalGetActiveMemory())/(1024*1024*1024),- float64(mlx.MetalGetPeakMemory())/(1024*1024*1024))-- mem := mlx.MetalGetActiveMemory()- fmt.Printf(" Loaded in %.2fs (%.1f GB VRAM)\n", time.Since(start).Seconds(), float64(mem)/(1024*1024*1024))-- return nil-}--// Generate creates an image from a prompt.-func (m *Model) Generate(prompt string, width, height int32, steps int, seed int64) (*mlx.Array, error) {- return m.GenerateFromConfig(context.Background(), &GenerateConfig{- Prompt: prompt,- Width: width,- Height: height,- Steps: steps,- Seed: seed,- })-}--// GenerateWithProgress creates an image with progress callback.-func (m *Model) GenerateWithProgress(prompt string, width, height int32, steps int, seed int64, progress func(step, totalSteps int)) (*mlx.Array, error) {- return m.GenerateFromConfig(context.Background(), &GenerateConfig{- Prompt: prompt,- Width: width,- Height: height,- Steps: steps,- Seed: seed,- Progress: progress,- })-}--// GenerateWithCFG creates an image with classifier-free guidance.-func (m *Model) GenerateWithCFG(prompt, negativePrompt string, width, height int32, steps int, seed int64, cfgScale float32, progress func(step, totalSteps int)) (*mlx.Array, error) {- return m.GenerateFromConfig(context.Background(), &GenerateConfig{- Prompt: prompt,- NegativePrompt: negativePrompt,- CFGScale: cfgScale,- Width: width,- Height: height,- Steps: steps,- Seed: seed,- Progress: progress,- })-}--// GenerateFromConfig generates an image using the unified config struct.-func (m *Model) GenerateFromConfig(ctx context.Context, cfg *GenerateConfig) (*mlx.Array, error) {- start := time.Now()- result, err := m.generate(ctx, cfg)- if err != nil {- return nil, err- }- if cfg.NegativePrompt != "" {- fmt.Printf("Generated with CFG (scale=%.1f) in %.2fs (%d steps)\n", cfg.CFGScale, time.Since(start).Seconds(), cfg.Steps)- } else {- fmt.Printf("Generated in %.2fs (%d steps)\n", time.Since(start).Seconds(), cfg.Steps)- }- return result, nil-}--// GenerateImage implements runner.ImageModel interface.-func (m *Model) GenerateImage(ctx context.Context, prompt string, width, height int32, steps int, seed int64, progress func(step, total int)) (*mlx.Array, error) {- return m.GenerateFromConfig(ctx, &GenerateConfig{- Prompt: prompt,- Width: width,- Height: height,- Steps: steps,- Seed: seed,- Progress: progress,- })-}--// generate is the internal denoising pipeline.-func (m *Model) generate(ctx context.Context, cfg *GenerateConfig) (*mlx.Array, error) {- // Apply defaults- if cfg.Width <= 0 {- cfg.Width = 1024- }- if cfg.Height <= 0 {- cfg.Height = 1024- }- if cfg.Steps <= 0 {- cfg.Steps = 9 // Z-Image turbo default- }- if cfg.CFGScale <= 0 {- cfg.CFGScale = 4.0- }- // TeaCache enabled by default- cfg.TeaCache = true- if cfg.TeaCacheThreshold <= 0 {- cfg.TeaCacheThreshold = 0.15- }-- // Enable fused QKV if requested (only fuse once)- if cfg.FusedQKV && !m.qkvFused {- m.Transformer.FuseAllQKV()- m.qkvFused = true- fmt.Println(" Fused QKV enabled")- }-- useCFG := cfg.NegativePrompt != ""- tcfg := m.Transformer.TransformerConfig- latentH := cfg.Height / 8- latentW := cfg.Width / 8- hTok := latentH / tcfg.PatchSize- wTok := latentW / tcfg.PatchSize-- // Text encoding with padding to multiple of 32- var posEmb, negEmb *mlx.Array- {- posEmb, _ = m.TextEncoder.EncodePrompt(m.Tokenizer, cfg.Prompt, 512, false)- if useCFG {- negEmb, _ = m.TextEncoder.EncodePrompt(m.Tokenizer, cfg.NegativePrompt, 512, false)- }-- // Pad both to same length (multiple of 32)- maxLen := posEmb.Shape()[1]- if useCFG && negEmb.Shape()[1] > maxLen {- maxLen = negEmb.Shape()[1]- }- if pad := (32 - (maxLen % 32)) % 32; pad > 0 {- maxLen += pad- }-- posEmb = padToLength(posEmb, maxLen)- if useCFG {- negEmb = padToLength(negEmb, maxLen)- mlx.Keep(posEmb, negEmb)- mlx.Eval(posEmb, negEmb)- } else {- mlx.Keep(posEmb)- mlx.Eval(posEmb)- }- }-- // Scheduler- scheduler := NewFlowMatchEulerScheduler(DefaultFlowMatchSchedulerConfig())- scheduler.SetTimestepsWithMu(cfg.Steps, CalculateShift(hTok*wTok))-- // Init latents [B, C, H, W]- var latents *mlx.Array- {- latents = scheduler.InitNoise([]int32{1, tcfg.InChannels, latentH, latentW}, cfg.Seed)- mlx.Eval(latents)- }-- // RoPE cache- var ropeCache *RoPECache- {- ropeCache = m.Transformer.PrepareRoPECache(hTok, wTok, posEmb.Shape()[1])- mlx.Keep(ropeCache.ImgCos, ropeCache.ImgSin, ropeCache.CapCos, ropeCache.CapSin,- ropeCache.UnifiedCos, ropeCache.UnifiedSin)- mlx.Eval(ropeCache.UnifiedCos)- }-- // Pre-compute batched embeddings for CFG (outside the loop for efficiency)- var batchedEmb *mlx.Array- if useCFG {- // Concatenate embeddings once: [1, L, D] + [1, L, D] -> [2, L, D]- batchedEmb = mlx.Concatenate([]*mlx.Array{posEmb, negEmb}, 0)- mlx.Keep(batchedEmb)- mlx.Eval(batchedEmb)- }-- // TeaCache for timestep-aware caching- // For CFG mode, we cache pos/neg separately, skip early steps, and always compute CFG fresh- var teaCache *cache.TeaCache- if cfg.TeaCache {- skipEarly := 0- if useCFG {- skipEarly = 3 // Skip first 3 steps for CFG to preserve structure- }- teaCache = cache.NewTeaCache(&cache.TeaCacheConfig{- Threshold: cfg.TeaCacheThreshold,- RescaleFactor: 1.0,- SkipEarlySteps: skipEarly,- })- if useCFG {- fmt.Printf(" TeaCache enabled (CFG mode): threshold=%.2f, skip first %d steps\n", cfg.TeaCacheThreshold, skipEarly)- } else {- fmt.Printf(" TeaCache enabled: threshold=%.2f\n", cfg.TeaCacheThreshold)- }- }-- // cleanup frees all kept arrays when we need to abort early- cleanup := func() {- posEmb.Free()- if negEmb != nil {- negEmb.Free()- }- ropeCache.ImgCos.Free()- ropeCache.ImgSin.Free()- ropeCache.CapCos.Free()- ropeCache.CapSin.Free()- ropeCache.UnifiedCos.Free()- ropeCache.UnifiedSin.Free()- if batchedEmb != nil {- batchedEmb.Free()- }- if teaCache != nil {- teaCache.Free()- }- latents.Free()- }-- // Denoising loop- if cfg.Progress != nil {- cfg.Progress(0, cfg.Steps) // Start at 0%- }- for i := range cfg.Steps {- // Check for cancellation- if ctx != nil {- select {- case <-ctx.Done():- cleanup()- return nil, ctx.Err()- default:- }- }- stepStart := time.Now()-- // GPU capture on step 2 if requested- if cfg.CapturePath != "" && i == 1 {- mlx.MetalStartCapture(cfg.CapturePath)- }-- tCurr := scheduler.Timesteps[i]- var noisePred *mlx.Array-- // TeaCache: check if we should compute or reuse cached output- shouldCompute := teaCache == nil || teaCache.ShouldCompute(i, tCurr)-- if shouldCompute {- timestep := mlx.ToBFloat16(mlx.NewArray([]float32{1.0 - tCurr}, []int32{1}))- patches := PatchifyLatents(latents, tcfg.PatchSize)-- var output *mlx.Array- if useCFG {- // CFG Batching: single forward pass with batch=2- // Tile patches: [1, L, D] -> [2, L, D]- batchedPatches := mlx.Tile(patches, []int32{2, 1, 1})- // Tile timestep: [1] -> [2]- batchedTimestep := mlx.Tile(timestep, []int32{2})-- // Single batched forward pass (RoPE broadcasts from [1,L,H,D] to [2,L,H,D])- batchedOutput := m.Transformer.Forward(batchedPatches, batchedTimestep, batchedEmb, ropeCache)-- // Split output: [2, L, D] -> pos [1, L, D], neg [1, L, D]- outputShape := batchedOutput.Shape()- L := outputShape[1]- D := outputShape[2]- posOutput := mlx.Slice(batchedOutput, []int32{0, 0, 0}, []int32{1, L, D})- negOutput := mlx.Slice(batchedOutput, []int32{1, 0, 0}, []int32{2, L, D})-- // Convert to noise predictions (unpatchify and negate)- posPred := UnpatchifyLatents(posOutput, tcfg.PatchSize, latentH, latentW, tcfg.InChannels)- posPred = mlx.Neg(posPred)- negPred := UnpatchifyLatents(negOutput, tcfg.PatchSize, latentH, latentW, tcfg.InChannels)- negPred = mlx.Neg(negPred)-- // Cache pos/neg separately for TeaCache- if teaCache != nil {- teaCache.UpdateCFGCache(posPred, negPred, tCurr)- mlx.Keep(teaCache.Arrays()...)- }-- // Apply CFG: noisePred = neg + scale * (pos - neg)- diff := mlx.Sub(posPred, negPred)- scaledDiff := mlx.MulScalar(diff, cfg.CFGScale)- noisePred = mlx.Add(negPred, scaledDiff)- } else {- // Non-CFG forward pass- output = m.Transformer.Forward(patches, timestep, posEmb, ropeCache)- noisePred = UnpatchifyLatents(output, tcfg.PatchSize, latentH, latentW, tcfg.InChannels)- noisePred = mlx.Neg(noisePred)-- // Update TeaCache- if teaCache != nil {- teaCache.UpdateCache(noisePred, tCurr)- mlx.Keep(teaCache.Arrays()...)- }- }- } else if useCFG && teaCache != nil && teaCache.HasCFGCache() {- // CFG mode: get cached pos/neg and compute CFG fresh- posPred, negPred := teaCache.GetCFGCached()- diff := mlx.Sub(posPred, negPred)- scaledDiff := mlx.MulScalar(diff, cfg.CFGScale)- noisePred = mlx.Add(negPred, scaledDiff)- fmt.Printf(" [TeaCache: reusing cached pos/neg outputs]\n")- } else {- // Non-CFG mode: reuse cached noise prediction- noisePred = teaCache.GetCached()- fmt.Printf(" [TeaCache: reusing cached output]\n")- }-- oldLatents := latents- latents = scheduler.Step(noisePred, latents, i)-- mlx.Eval(latents)- oldLatents.Free()-- if cfg.CapturePath != "" && i == 1 {- mlx.MetalStopCapture()- }-- activeMem := float64(mlx.MetalGetActiveMemory()) / (1024 * 1024 * 1024)- peakMem := float64(mlx.MetalGetPeakMemory()) / (1024 * 1024 * 1024)- fmt.Printf(" Step %d/%d: t=%.4f (%.2fs) [%.1f GB active, %.1f GB peak]\n",- i+1, cfg.Steps, tCurr, time.Since(stepStart).Seconds(), activeMem, peakMem)-- if cfg.Progress != nil {- cfg.Progress(i+1, cfg.Steps) // Report completed step- }- }-- // Free denoising temporaries before VAE decode- posEmb.Free()- if negEmb != nil {- negEmb.Free()- }- ropeCache.ImgCos.Free()- ropeCache.ImgSin.Free()- ropeCache.CapCos.Free()- ropeCache.CapSin.Free()- ropeCache.UnifiedCos.Free()- ropeCache.UnifiedSin.Free()- if batchedEmb != nil {- batchedEmb.Free()- }- if teaCache != nil {- hits, misses := teaCache.Stats()- fmt.Printf(" TeaCache stats: %d hits, %d misses (%.1f%% cache rate)\n",- hits, misses, float64(hits)/float64(hits+misses)*100)- teaCache.Free()- }-- // VAE decode - enable tiling for larger images to reduce memory- // VAE attention is O(n²) on latent pixels, tiling helps significantly- if latentH > 64 || latentW > 64 {- m.VAEDecoder.Tiling = vae.DefaultTilingConfig()- }- decoded := m.VAEDecoder.Decode(latents)- latents.Free()-- return decoded, nil-}--// padToLength pads a sequence tensor to the target length by repeating the last token.-func padToLength(x *mlx.Array, targetLen int32) *mlx.Array {- shape := x.Shape()- currentLen := shape[1]- if currentLen >= targetLen {- return x- }- padLen := targetLen - currentLen- lastToken := mlx.Slice(x, []int32{0, currentLen - 1, 0}, []int32{shape[0], currentLen, shape[2]})- padding := mlx.Tile(lastToken, []int32{1, padLen, 1})- return mlx.Concatenate([]*mlx.Array{x, padding}, 1)-}--// CalculateShift computes the mu shift value for dynamic scheduling-func CalculateShift(imgSeqLen int32) float32 {- baseSeqLen := float32(256)- maxSeqLen := float32(4096)- baseShift := float32(0.5)- maxShift := float32(1.15)-- m := (maxShift - baseShift) / (maxSeqLen - baseSeqLen)- b := baseShift - m*baseSeqLen- return float32(imgSeqLen)*m + b-}diff --git a/x/imagegen/nn/nn.go b/x/imagegen/nn/nn.godeleted file mode 100644index 98696b18f..000000000--- a/x/imagegen/nn/nn.go+++ /dev/null@@ -1,258 +0,0 @@-// Package nn provides neural network layer types.-package nn--import "github.com/ollama/ollama/x/imagegen/mlx"--// Layer is the interface for neural network layers with a Forward method.-type Layer interface {- Forward(x *mlx.Array) *mlx.Array-}--// LinearLayer is an interface for linear layers (both regular and quantized).-// This allows swapping between Linear and QuantizedLinear at runtime.-type LinearLayer interface {- Forward(x *mlx.Array) *mlx.Array- OutputDim() int32 // Returns the output dimension of the layer-}--// Linear applies an affine transformation: y = x @ W.T + b-// Weight is stored as [out_features, in_features], matching PyTorch/MLX convention.-type Linear struct {- Weight *mlx.Array `weight:"weight"` // [out_features, in_features]- Bias *mlx.Array `weight:"bias,optional"` // [out_features] or nil-}--// NewLinear creates a linear layer.-// Weight should be [out_features, in_features].-func NewLinear(weight *mlx.Array, bias *mlx.Array) *Linear {- return &Linear{Weight: weight, Bias: bias}-}--// NewQuantizedLinear creates a quantized linear layer directly from bf16 weights.-// Quantizes the weight immediately and evaluates to break lazy dependencies.-// Note: For modes like "nvfp4", qbiases will be nil.-func NewQuantizedLinear(weight *mlx.Array, bias *mlx.Array, groupSize, bits int, mode string) *QuantizedLinear {- qw, scales, qbiases := mlx.Quantize(weight, groupSize, bits, mode)- // Eval immediately so bf16 weight can be freed- // Handle modes that don't return qbiases (e.g., nvfp4)- if qbiases != nil {- mlx.Eval(qw, scales, qbiases)- } else {- mlx.Eval(qw, scales)- }- return &QuantizedLinear{- Weight: qw,- Scales: scales,- QBiases: qbiases,- Bias: bias,- GroupSize: groupSize,- Bits: bits,- Mode: mode,- }-}--// Forward applies the linear transformation: x @ W.T + bias-func (l *Linear) Forward(x *mlx.Array) *mlx.Array {- w := mlx.Transpose(l.Weight, 1, 0)- if l.Bias != nil {- return mlx.AddMM(l.Bias, x, w, 1.0, 1.0)- }- return mlx.Linear(x, w)-}--// OutputDim returns the output dimension of the linear layer.-func (l *Linear) OutputDim() int32 {- return l.Weight.Shape()[0]-}--// ToQuantized converts this Linear to a QuantizedLinear.-func (l *Linear) ToQuantized(groupSize, bits int, mode string) *QuantizedLinear {- qw, scales, qbiases := mlx.Quantize(l.Weight, groupSize, bits, mode)- return &QuantizedLinear{- Weight: qw,- Scales: scales,- QBiases: qbiases,- Bias: l.Bias,- GroupSize: groupSize,- Bits: bits,- Mode: mode,- }-}--// QuantizedLinear applies an affine transformation using quantized weights.-// Equivalent to mlx.nn.QuantizedLinear.-// Supports multiple quantization modes:-// - "affine": scale + zero-point bias (QBiases required)-// - "nvfp4": NVIDIA FP4 with E4M3 scales (QBiases nil)-type QuantizedLinear struct {- Weight *mlx.Array // Quantized weight data- Scales *mlx.Array // Scale factors for dequantization- QBiases *mlx.Array // Quantization biases (NOT layer bias), nil for nvfp4- Bias *mlx.Array // Layer bias [output_dims] or nil- GroupSize int- Bits int- Mode string-}--// Forward applies the quantized linear transformation.-func (ql *QuantizedLinear) Forward(x *mlx.Array) *mlx.Array {- out := mlx.QuantizedMatmul(x, ql.Weight, ql.Scales, ql.QBiases, true, ql.GroupSize, ql.Bits, ql.Mode)- if ql.Bias != nil {- out = mlx.Add(out, ql.Bias)- }- return out-}--// OutputDim returns the output dimension of the quantized linear layer.-// For mxfp8/mxfp4, quantized weight shape is [out_features, in_features / group_size].-// The output dimension is the first dimension of the weight.-func (ql *QuantizedLinear) OutputDim() int32 {- return ql.Weight.Shape()[0]-}--// RMSNorm represents an RMS normalization layer.-type RMSNorm struct {- Weight *mlx.Array `weight:"weight"`- Eps float32 // optional: used if Forward called with eps=0-}--// NewRMSNorm creates an RMSNorm layer (for models not using weight loader).-func NewRMSNorm(weight *mlx.Array, eps float32) *RMSNorm {- return &RMSNorm{Weight: weight, Eps: eps}-}--// Forward applies RMS normalization. If eps=0, uses stored Eps.-func (rn *RMSNorm) Forward(x *mlx.Array, eps float32) *mlx.Array {- if eps == 0 {- eps = rn.Eps- }- return mlx.RMSNorm(x, rn.Weight, eps)-}--// Embedding represents an embedding layer.-type Embedding struct {- Weight *mlx.Array `weight:"weight"`-}--// NewEmbedding creates an embedding layer.-func NewEmbedding(weight *mlx.Array) *Embedding {- return &Embedding{Weight: weight}-}--// Forward looks up embeddings by indices.-func (e *Embedding) Forward(indices *mlx.Array) *mlx.Array {- return mlx.Take(e.Weight, indices, 0)-}--// RepeatKV repeats K/V tensors for grouped query attention-// x: [B, num_kv_heads, S, head_dim] -> [B, num_heads, S, head_dim]-func RepeatKV(x *mlx.Array, repeatFactor int32) *mlx.Array {- if repeatFactor == 1 {- return x- }- shape := x.Shape()- // [B, num_kv_heads, S, head_dim] -> [B, num_kv_heads, 1, S, head_dim]- x = mlx.ExpandDims(x, 2)- // Repeat along the new axis- reps := []int32{1, 1, repeatFactor, 1, 1}- x = mlx.Tile(x, reps)- // Reshape: [B, num_kv_heads, repeat, S, head_dim] -> [B, num_kv_heads * repeat, S, head_dim]- return mlx.Reshape(x, shape[0], shape[1]*repeatFactor, shape[2], shape[3])-}--// ApplyCausalMask applies causal (lower triangular) mask to attention scores-func ApplyCausalMask(scores *mlx.Array) *mlx.Array {- // scores: [B, num_heads, S, S]- shape := scores.Shape()- seqLen := shape[2]-- // Create causal mask: 1 for positions to keep, 0 for positions to mask- mask := mlx.Tri(seqLen, seqLen, 0)-- // Where mask is 0, set score to -inf- negInf := mlx.NewScalarArray(float32(-1e9))-- // Broadcast mask to match scores shape- mask = mlx.ExpandDims(mlx.ExpandDims(mask, 0), 0) // [1, 1, S, S]-- // Use where: if mask > 0, keep scores, else -inf- return mlx.Where(mask, scores, negInf)-}--// ApplyCausalMaskWithOffset applies causal mask for cached attention-// scores: [B, num_heads, queryLen, keyLen] where keyLen = cacheLen + queryLen-// offset: the starting position of the new queries (i.e., cache length)-func ApplyCausalMaskWithOffset(scores *mlx.Array, offset int32) *mlx.Array {- if offset == 0 {- return ApplyCausalMask(scores)- }-- shape := scores.Shape()- queryLen := shape[2]- keyLen := shape[3]-- // For cached attention, new queries can attend to all cached keys plus- // new keys up to and including their position.- mask := mlx.Tri(queryLen, keyLen, int(offset))-- negInf := mlx.NewScalarArray(float32(-1e9))- mask = mlx.ExpandDims(mlx.ExpandDims(mask, 0), 0) // [1, 1, queryLen, keyLen]-- return mlx.Where(mask, scores, negInf)-}--// LayerNorm represents a standard layer normalization layer (with bias).-type LayerNorm struct {- Weight *mlx.Array `weight:"weight"`- Bias *mlx.Array `weight:"bias"`- Eps float32-}--// Forward applies layer normalization: (x - mean) / sqrt(var + eps) * weight + bias-func (ln *LayerNorm) Forward(x *mlx.Array) *mlx.Array {- eps := ln.Eps- if eps == 0 {- eps = 1e-5- }- // Compute mean and variance along last dimension- mean := mlx.Mean(x, -1, true)- centered := mlx.Sub(x, mean)- variance := mlx.Mean(mlx.Mul(centered, centered), -1, true)- normalized := mlx.Mul(centered, mlx.RSqrt(mlx.AddScalar(variance, eps)))-- // Scale and shift- out := mlx.Mul(normalized, ln.Weight)- if ln.Bias != nil {- out = mlx.Add(out, ln.Bias)- }- return out-}--// MultiLinearLayer is an interface for per-head linear layers.-// This allows swapping between MultiLinear (bf16) and pre-dequantized weights.-type MultiLinearLayer interface {- Forward(x *mlx.Array) *mlx.Array-}--// MultiLinear performs per-head linear projections.-// Weight shape: [num_heads, output_dims, input_dims]-// Input shape: [B, num_heads, L, input_dims]-// Output shape: [B, num_heads, L, output_dims]-type MultiLinear struct {- Weight *mlx.Array `weight:"weight"`-}--// NewMultiLinear creates a MultiLinear layer with the given weight.-func NewMultiLinear(weight *mlx.Array) *MultiLinear {- return &MultiLinear{Weight: weight}-}--// Forward applies per-head linear transformation: x @ weight.T per head via broadcasting.-func (ml *MultiLinear) Forward(x *mlx.Array) *mlx.Array {- // Weight: [num_heads, output_dims, input_dims]- // x: [B, num_heads, L, input_dims]- // wT: [num_heads, input_dims, output_dims]- // Result: [B, num_heads, L, output_dims]- wT := mlx.Transpose(ml.Weight, 0, 2, 1)- return mlx.Matmul(x, wT)-}diff --git a/x/imagegen/nn/nn_test.go b/x/imagegen/nn/nn_test.godeleted file mode 100644index 0fc433ef6..000000000--- a/x/imagegen/nn/nn_test.go+++ /dev/null@@ -1,408 +0,0 @@-package nn--import (- "fmt"- "math"- "os"- "path/filepath"- "runtime"- "testing"-- "github.com/ollama/ollama/x/imagegen/mlx"-)--// TestMain initializes MLX before running tests.-// If MLX libraries are not available, tests are skipped.-func TestMain(m *testing.M) {- // Change to repo root so ./build/lib/ollama/ path works- _, thisFile, _, _ := runtime.Caller(0)- repoRoot := filepath.Join(filepath.Dir(thisFile), "..", "..", "..")- if err := os.Chdir(repoRoot); err != nil {- fmt.Printf("Failed to change to repo root: %v\n", err)- os.Exit(1)- }-- if err := mlx.InitMLX(); err != nil {- fmt.Printf("Skipping nn tests: %v\n", err)- os.Exit(0)- }- os.Exit(m.Run())-}--func useMLXTestThread(t *testing.T) {- t.Helper()- runtime.LockOSThread()- t.Cleanup(func() {- mlx.ReleaseAll()- mlx.ClearCache()- runtime.UnlockOSThread()- })-}--// TestLinearNoBias verifies Linear without bias computes x @ w.T correctly.-func TestLinearNoBias(t *testing.T) {- useMLXTestThread(t)-- // Weight: [out=2, in=3] -> transposed at forward time- weight := mlx.NewArrayFloat32([]float32{- 1, 2, 3, // row 0- 4, 5, 6, // row 1- }, []int32{2, 3})- mlx.Eval(weight)-- linear := NewLinear(weight, nil)-- // Input: [1, 3]- x := mlx.NewArrayFloat32([]float32{1, 1, 1}, []int32{1, 3})- mlx.Eval(x)-- out := linear.Forward(x)- mlx.Eval(out)-- // Expected: [1,1,1] @ [[1,4],[2,5],[3,6]] = [6, 15]- data := out.Data()- if len(data) != 2 || data[0] != 6 || data[1] != 15 {- t.Errorf("expected [6, 15], got %v", data)- }-}--// TestLinearWithBias verifies Linear with bias computes x @ w.T + b correctly.-func TestLinearWithBias(t *testing.T) {- useMLXTestThread(t)-- weight := mlx.NewArrayFloat32([]float32{- 1, 2, 3,- 4, 5, 6,- }, []int32{2, 3})- bias := mlx.NewArrayFloat32([]float32{10, 20}, []int32{2})- mlx.Eval(weight, bias)-- linear := NewLinear(weight, bias)-- x := mlx.NewArrayFloat32([]float32{1, 1, 1}, []int32{1, 3})- mlx.Eval(x)-- out := linear.Forward(x)- mlx.Eval(out)-- // Expected: [6, 15] + [10, 20] = [16, 35]- data := out.Data()- if len(data) != 2 || data[0] != 16 || data[1] != 35 {- t.Errorf("expected [16, 35], got %v", data)- }-}--// TestLinearBatched verifies Linear works with batched input.-func TestLinearBatched(t *testing.T) {- useMLXTestThread(t)-- weight := mlx.NewArrayFloat32([]float32{- 1, 0,- 0, 1,- }, []int32{2, 2}) // Identity- mlx.Eval(weight)-- linear := NewLinear(weight, nil)-- // Batch of 3 inputs- x := mlx.NewArrayFloat32([]float32{- 1, 2,- 3, 4,- 5, 6,- }, []int32{3, 2})- mlx.Eval(x)-- out := linear.Forward(x)- mlx.Eval(out)-- // Identity should return same values- data := out.Data()- expected := []float32{1, 2, 3, 4, 5, 6}- for i, v := range expected {- if data[i] != v {- t.Errorf("at %d: expected %f, got %f", i, v, data[i])- }- }-}--// TestRMSNorm verifies RMSNorm computation.-func TestRMSNorm(t *testing.T) {- useMLXTestThread(t)-- weight := mlx.NewArrayFloat32([]float32{1, 1, 1, 1}, []int32{4})- mlx.Eval(weight)-- norm := NewRMSNorm(weight, 1e-5)-- // Input with known RMS- x := mlx.NewArrayFloat32([]float32{2, 2, 2, 2}, []int32{1, 4})- mlx.Eval(x)-- out := norm.Forward(x, 0) // eps=0 uses stored Eps- mlx.Eval(out)-- // RMS of [2,2,2,2] = 2, so normalized = [1,1,1,1]- data := out.Data()- for i, v := range data {- if math.Abs(float64(v-1.0)) > 1e-4 {- t.Errorf("at %d: expected ~1.0, got %f", i, v)- }- }-}--// TestRMSNormWithScale verifies RMSNorm applies weight scaling.-func TestRMSNormWithScale(t *testing.T) {- useMLXTestThread(t)-- weight := mlx.NewArrayFloat32([]float32{2, 2, 2, 2}, []int32{4})- mlx.Eval(weight)-- norm := NewRMSNorm(weight, 1e-5)-- x := mlx.NewArrayFloat32([]float32{2, 2, 2, 2}, []int32{1, 4})- mlx.Eval(x)-- out := norm.Forward(x, 0) // eps=0 uses stored Eps- mlx.Eval(out)-- // Normalized [1,1,1,1] * weight [2,2,2,2] = [2,2,2,2]- data := out.Data()- for i, v := range data {- if math.Abs(float64(v-2.0)) > 1e-4 {- t.Errorf("at %d: expected ~2.0, got %f", i, v)- }- }-}--// TestEmbedding verifies embedding lookup.-func TestEmbedding(t *testing.T) {- useMLXTestThread(t)-- // Embedding table: 4 tokens, dim 3- weight := mlx.NewArrayFloat32([]float32{- 0, 0, 0, // token 0- 1, 1, 1, // token 1- 2, 2, 2, // token 2- 3, 3, 3, // token 3- }, []int32{4, 3})- mlx.Eval(weight)-- emb := NewEmbedding(weight)-- // Look up tokens [1, 3, 0]- indices := mlx.NewArrayInt32([]int32{1, 3, 0}, []int32{3})- mlx.Eval(indices)-- out := emb.Forward(indices)- mlx.Eval(out)-- data := out.Data()- expected := []float32{1, 1, 1, 3, 3, 3, 0, 0, 0}- for i, v := range expected {- if data[i] != v {- t.Errorf("at %d: expected %f, got %f", i, v, data[i])- }- }-}--// TestRepeatKV verifies K/V repetition for GQA.-func TestRepeatKV(t *testing.T) {- useMLXTestThread(t)-- // [B=1, num_kv_heads=2, S=2, head_dim=2]- x := mlx.NewArrayFloat32([]float32{- // head 0- 1, 2, // pos 0- 3, 4, // pos 1- // head 1- 5, 6, // pos 0- 7, 8, // pos 1- }, []int32{1, 2, 2, 2})- mlx.Eval(x)-- // Repeat factor 2: 2 kv heads -> 4 heads- out := RepeatKV(x, 2)- mlx.Eval(out)-- shape := out.Shape()- if shape[0] != 1 || shape[1] != 4 || shape[2] != 2 || shape[3] != 2 {- t.Errorf("expected shape [1,4,2,2], got %v", shape)- }-- data := out.Data()- // After repeat: head0, head0, head1, head1- expected := []float32{- 1, 2, 3, 4, // head 0 (original)- 1, 2, 3, 4, // head 0 (repeat)- 5, 6, 7, 8, // head 1 (original)- 5, 6, 7, 8, // head 1 (repeat)- }- for i, v := range expected {- if data[i] != v {- t.Errorf("at %d: expected %f, got %f", i, v, data[i])- }- }-}--// TestRepeatKVNoOp verifies RepeatKV with factor 1 returns input unchanged.-func TestRepeatKVNoOp(t *testing.T) {- useMLXTestThread(t)-- x := mlx.NewArrayFloat32([]float32{1, 2, 3, 4}, []int32{1, 1, 2, 2})- mlx.Eval(x)-- out := RepeatKV(x, 1)- // Should return same pointer- if out != x {- t.Error("RepeatKV with factor 1 should return input unchanged")- }-}--// TestApplyCausalMask verifies causal masking.-func TestApplyCausalMask(t *testing.T) {- useMLXTestThread(t)-- // [B=1, heads=1, S=3, S=3] - all ones- scores := mlx.Ones(1, 1, 3, 3)- mlx.Eval(scores)-- out := ApplyCausalMask(scores)- mlx.Eval(out)-- data := out.Data()- // Lower triangular should be 1, upper should be -1e9- // Row 0: [1, -inf, -inf]- // Row 1: [1, 1, -inf]- // Row 2: [1, 1, 1]- if data[0] != 1 || data[1] >= 0 || data[2] >= 0 {- t.Errorf("row 0 wrong: %v", data[0:3])- }- if data[3] != 1 || data[4] != 1 || data[5] >= 0 {- t.Errorf("row 1 wrong: %v", data[3:6])- }- if data[6] != 1 || data[7] != 1 || data[8] != 1 {- t.Errorf("row 2 wrong: %v", data[6:9])- }-}--// TestApplyCausalMaskWithOffset verifies causal masking with cache offset.-func TestApplyCausalMaskWithOffset(t *testing.T) {- useMLXTestThread(t)-- // Simulating: cache has 2 tokens, adding 1 new query- // scores: [B=1, heads=1, queryLen=1, keyLen=3]- scores := mlx.Ones(1, 1, 1, 3)- mlx.Eval(scores)-- out := ApplyCausalMaskWithOffset(scores, 2)- mlx.Eval(out)-- data := out.Data()- // With offset=2, query at position 2 can attend to all 3 positions- if data[0] != 1 || data[1] != 1 || data[2] != 1 {- t.Errorf("expected [1, 1, 1], got %v", data)- }-}--// TestApplyCausalMaskWithOffsetZero verifies offset=0 falls back to regular causal.-func TestApplyCausalMaskWithOffsetZero(t *testing.T) {- useMLXTestThread(t)-- scores := mlx.Ones(1, 1, 2, 2)- mlx.Eval(scores)-- out := ApplyCausalMaskWithOffset(scores, 0)- mlx.Eval(out)-- data := out.Data()- // Standard causal: [1, -inf], [1, 1]- if data[0] != 1 || data[1] >= 0 {- t.Errorf("row 0 wrong: %v", data[0:2])- }- if data[2] != 1 || data[3] != 1 {- t.Errorf("row 1 wrong: %v", data[2:4])- }-}--// BenchmarkLinearSmall benchmarks small Linear forward pass.-func BenchmarkLinearSmall(b *testing.B) {- weight := mlx.RandomNormal([]int32{256, 256}, 42)- mlx.Eval(weight)-- linear := NewLinear(weight, nil)-- x := mlx.RandomNormal([]int32{1, 256}, 43)- mlx.Eval(x)-- b.ResetTimer()- for range b.N {- out := linear.Forward(x)- mlx.Eval(out)- }-}--// BenchmarkLinearLarge benchmarks larger Linear forward pass.-func BenchmarkLinearLarge(b *testing.B) {- weight := mlx.RandomNormal([]int32{4096, 4096}, 42)- mlx.Eval(weight)-- linear := NewLinear(weight, nil)-- x := mlx.RandomNormal([]int32{1, 4096}, 43)- mlx.Eval(x)-- b.ResetTimer()- for range b.N {- out := linear.Forward(x)- mlx.Eval(out)- }-}--// BenchmarkRMSNorm benchmarks RMSNorm forward pass.-func BenchmarkRMSNorm(b *testing.B) {- weight := mlx.Ones(4096)- mlx.Eval(weight)-- norm := NewRMSNorm(weight, 1e-5)-- x := mlx.RandomNormal([]int32{1, 4096}, 42)- mlx.Eval(x)-- b.ResetTimer()- for range b.N {- out := norm.Forward(x, 0)- mlx.Eval(out)- }-}--// BenchmarkEmbedding benchmarks embedding lookup.-func BenchmarkEmbedding(b *testing.B) {- // Typical vocab size- weight := mlx.RandomNormal([]int32{32000, 4096}, 42)- mlx.Eval(weight)-- emb := NewEmbedding(weight)-- // Single token lookup- indices := mlx.NewArrayInt32([]int32{1000}, []int32{1})- mlx.Eval(indices)-- b.ResetTimer()- for range b.N {- out := emb.Forward(indices)- mlx.Eval(out)- }-}--// BenchmarkRepeatKV benchmarks K/V repetition.-func BenchmarkRepeatKV(b *testing.B) {- // Typical GQA setup: 8 kv heads -> 32 heads- x := mlx.RandomNormal([]int32{1, 8, 512, 128}, 42)- mlx.Eval(x)-- b.ResetTimer()- for range b.N {- out := RepeatKV(x, 4)- mlx.Eval(out)- }-}diff --git a/x/imagegen/runner.go b/x/imagegen/runner.godeleted file mode 100644index 59a84e915..000000000--- a/x/imagegen/runner.go+++ /dev/null@@ -1,181 +0,0 @@-// Package imagegen provides a unified MLX runner for both LLM and image generation models.-package imagegen--import (- "context"- "encoding/json"- "flag"- "fmt"- "log/slog"- "net/http"- "os"- "os/signal"- "syscall"- "time"-- "github.com/ollama/ollama/envconfig"- "github.com/ollama/ollama/x/imagegen/mlx"- "github.com/ollama/ollama/x/internal/mlxthread"-)--// Execute is the entry point for the unified MLX runner subprocess.-func Execute(args []string) error {- // Set up logging with appropriate level from environment- slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: envconfig.LogLevel()})))-- fs := flag.NewFlagSet("mlx-runner", flag.ExitOnError)- modelName := fs.String("model", "", "path to model")- port := fs.Int("port", 0, "port to listen on")-- if err := fs.Parse(args); err != nil {- return err- }-- if *modelName == "" {- return fmt.Errorf("--model is required")- }- if *port == 0 {- return fmt.Errorf("--port is required")- }-- // Detect model type from capabilities- mode := detectModelMode(*modelName)- slog.Info("starting mlx runner", "model", *modelName, "port", *port, "mode", mode)-- if mode != ModeImageGen {- return fmt.Errorf("imagegen runner only supports image generation models")- }-- worker, err := mlxthread.Start("imagegen", func() error {- if err := mlx.InitMLX(); err != nil {- slog.Error("unable to initialize MLX", "error", err)- return err- }- slog.Info("MLX library initialized")- return nil- })- if err != nil {- return err- }-- // Create and start server- var server *server- if err := worker.Do(context.Background(), func() error {- var err error- server, err = newServer(*modelName, *port)- if err != nil {- return fmt.Errorf("failed to create server: %w", err)- }- server.mlxThread = worker- return nil- }); err != nil {- return err- }-- // Set up HTTP handlers- mux := http.NewServeMux()- mux.HandleFunc("/health", server.healthHandler)- mux.HandleFunc("/completion", server.completionHandler)-- httpServer := &http.Server{- Addr: fmt.Sprintf("127.0.0.1:%d", *port),- Handler: mux,- }-- // Handle shutdown- done := make(chan struct{})- go func() {- sigCh := make(chan os.Signal, 1)- signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)- <-sigCh- slog.Info("shutting down mlx runner")- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)- defer cancel()- if err := httpServer.Shutdown(ctx); err != nil {- slog.Warn("graceful shutdown timed out", "error", err)- if err := httpServer.Close(); err != nil {- slog.Warn("failed to close http server", "error", err)- }- }- if err := worker.Stop(ctx, func() {- mlx.ClearCache()- }); err != nil {- slog.Warn("failed to stop mlx worker", "error", err)- }- close(done)- }()-- slog.Info("mlx runner listening", "addr", httpServer.Addr)- if err := httpServer.ListenAndServe(); err != http.ErrServerClosed {- return err- }-- <-done- return nil-}--// detectModelMode determines whether a model is an LLM or image generation model.-func detectModelMode(modelName string) ModelMode {- // Check for image generation model by looking at model_index.json- modelType := DetectModelType(modelName)- if modelType != "" {- // Known image generation model types- switch modelType {- case "ZImagePipeline", "FluxPipeline", "Flux2KleinPipeline":- return ModeImageGen- }- }-- // Default to LLM mode for safetensors models without known image gen types- return ModeLLM-}--// server holds the model and handles HTTP requests.-type server struct {- modelName string- port int- mlxThread *mlxthread.Thread-- // Image generation model.- imageModel ImageModel-}--// newServer creates a new server instance for image generation models.-func newServer(modelName string, port int) (*server, error) {- s := &server{- modelName: modelName,- port: port,- }-- if err := s.loadImageModel(); err != nil {- return nil, fmt.Errorf("failed to load image model: %w", err)- }-- return s, nil-}--func (s *server) healthHandler(w http.ResponseWriter, r *http.Request) {- resp := HealthResponse{Status: "ok"}- w.Header().Set("Content-Type", "application/json")- json.NewEncoder(w).Encode(resp)-}--func (s *server) completionHandler(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodPost {- http.Error(w, "method not allowed", http.StatusMethodNotAllowed)- return- }-- var req Request- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- http.Error(w, err.Error(), http.StatusBadRequest)- return- }-- if err := s.mlxThread.Do(r.Context(), func() error {- s.handleImageCompletion(w, r, req)- return nil- }); err != nil && r.Context().Err() == nil {- http.Error(w, err.Error(), http.StatusInternalServerError)- }-}diff --git a/x/imagegen/safetensors/loader.go b/x/imagegen/safetensors/loader.godeleted file mode 100644index bf2110d23..000000000--- a/x/imagegen/safetensors/loader.go+++ /dev/null@@ -1,429 +0,0 @@-package safetensors--import (- "fmt"- "reflect"- "strings"-- "github.com/ollama/ollama/x/imagegen/mlx"- "github.com/ollama/ollama/x/imagegen/nn"-)--// WeightSource is an interface for loading weights.-// Both ModelWeights (directory-based) and ManifestWeights (blob-based) implement this.-type WeightSource interface {- GetTensor(name string) (*mlx.Array, error)- ListTensors() []string- HasTensor(name string) bool- Quantization() string // Returns "NVFP4", "INT4", "INT8", or ""- GroupSize() int // Returns quantization group size, or 0 if not specified-}--// QuantizationParams returns groupSize, bits, mode for a quantization type.-// MLX quantization modes:-// - "affine": scale + zero-point bias, group_size=32/64/128-// - "nvfp4": NVIDIA FP4 with E4M3 scales, group_size=16 (no bias)-// - "mxfp8": Microsoft MX FP8 with E4M3 scales, group_size=32 (no bias)-func QuantizationParams(quantization string) (groupSize, bits int, mode string) {- switch strings.ToUpper(quantization) {- case "NVFP4":- // NVIDIA FP4: group_size=16, bits=4, E4M3 scales (no qbias)- return 16, 4, "nvfp4"- case "FP4", "Q4", "INT4":- // 4-bit quantization with affine mode (scale + qbias)- return 32, 4, "affine"- case "MXFP8":- // Microsoft MX FP8: group_size=32, bits=8, E4M3 scales (no qbias)- return 32, 8, "mxfp8"- case "FP8", "Q8", "INT8":- // 8-bit quantization with affine mode (default for quantized models)- return 64, 8, "affine"- case "":- return 0, 0, ""- default:- return 32, 8, "affine" // Default to affine- }-}--// Transformer allows structs to transform weight arrays before assignment.-// Implement this to apply operations like transpose during loading.-type Transformer interface {- Transform(field string, arr *mlx.Array) *mlx.Array-}--// LoadModule loads weights into a struct using reflection and struct tags.-//-// Struct tags use the format: `weight:"path[,optional]"`-// - path: the weight name suffix (appended to prefix)-// - optional: if present, missing weights don't cause errors-// - "-": skip this field entirely-// - no tag on struct pointer: recurse with current prefix-// - no tag on *mlx.Array: skip (computed fields don't need loading)-//-// For slices of struct pointers, the loader iterates with .0, .1, .2... suffixes.-// The slice must be pre-allocated to the correct length.-//-// Example:-//-// type Attention struct {-// QProj *nn.Linear `weight:"self_attn.q_proj"`-// KProj *nn.Linear `weight:"self_attn.k_proj"`-// Cache *mlx.Array // no tag = skipped (computed field)-// }-//-// err := LoadModule(&attn, weights, "model.layers.0")-func LoadModule(dst any, weights WeightSource, prefix string) error {- v := reflect.ValueOf(dst)- if v.Kind() != reflect.Pointer || v.IsNil() {- return fmt.Errorf("LoadModule: dst must be a non-nil pointer")- }- v = v.Elem()- if v.Kind() != reflect.Struct {- return fmt.Errorf("LoadModule: dst must be a pointer to struct, got %v", v.Kind())- }-- var errs []string- loadStruct(v, weights, prefix, &errs, false)-- if len(errs) > 0 {- return fmt.Errorf("LoadModule: missing weights:\n %s", strings.Join(errs, "\n "))- }- return nil-}--// loadStruct recursively loads weights into a struct value.-func loadStruct(v reflect.Value, weights WeightSource, prefix string, errs *[]string, parentOptional bool) {- t := v.Type()-- for i := range t.NumField() {- field := t.Field(i)- fieldVal := v.Field(i)-- // Skip unexported fields- if !fieldVal.CanSet() {- continue- }-- // Parse tag- tag, hasTag := field.Tag.Lookup("weight")- if tag == "-" {- continue- }-- // Parse tag options- optional := parentOptional- weightPath := tag- if idx := strings.Index(tag, ","); idx != -1 {- weightPath = tag[:idx]- if strings.Contains(tag[idx+1:], "optional") {- optional = true- }- }-- // Build full path- fullPath := joinPath(prefix, weightPath)-- // For struct pointers without a tag, recurse with current prefix- if !hasTag && fieldVal.Kind() == reflect.Pointer {- elemType := fieldVal.Type().Elem()- if elemType.Kind() == reflect.Struct && elemType != reflect.TypeOf(mlx.Array{}) {- if fieldVal.IsNil() {- fieldVal.Set(reflect.New(elemType))- }- loadStruct(fieldVal.Elem(), weights, prefix, errs, optional)- continue- }- }-- // Handle nn.LinearLayer interface fields specially- linearLayerType := reflect.TypeOf((*nn.LinearLayer)(nil)).Elem()- if field.Type == linearLayerType {- if !hasTag {- continue // no tag = skip- }- layer, err := LoadLinearLayer(weights, fullPath)- if err != nil {- if !optional {- *errs = append(*errs, fullPath+": "+err.Error())- }- continue- }- fieldVal.Set(reflect.ValueOf(layer))- continue- }-- // Handle nn.MultiLinearLayer interface fields specially- multiLinearLayerType := reflect.TypeOf((*nn.MultiLinearLayer)(nil)).Elem()- if field.Type == multiLinearLayerType {- if !hasTag {- continue // no tag = skip- }- layer, err := LoadMultiLinearLayer(weights, fullPath)- if err != nil {- if !optional {- *errs = append(*errs, fullPath+": "+err.Error())- }- continue- }- fieldVal.Set(reflect.ValueOf(layer))- continue- }-- // Handle by kind- switch fieldVal.Kind() {- case reflect.Pointer:- elemType := fieldVal.Type().Elem()-- // *mlx.Array - load directly (but skip if no tag - computed fields)- if fieldVal.Type() == reflect.TypeOf((*mlx.Array)(nil)) {- if !hasTag {- continue // no tag on *mlx.Array = computed field, skip- }- arr, err := weights.GetTensor(fullPath)- if err != nil {- if !optional {- *errs = append(*errs, fullPath)- }- continue- }- // Transform before assigning if parent implements Transformer- if t, ok := v.Addr().Interface().(Transformer); ok {- arr = t.Transform(field.Name, arr)- }- fieldVal.Set(reflect.ValueOf(arr))- continue- }-- // Pointer to struct - allocate and recurse- if elemType.Kind() == reflect.Struct {- if optional && !hasWeightsWithPrefix(weights, fullPath) {- continue- }- if fieldVal.IsNil() {- fieldVal.Set(reflect.New(elemType))- }- loadStruct(fieldVal.Elem(), weights, fullPath, errs, optional)- }-- case reflect.Slice:- elemType := fieldVal.Type().Elem()- if elemType.Kind() == reflect.Pointer && elemType.Elem().Kind() == reflect.Struct {- loadSlice(fieldVal, weights, fullPath, errs)- }- }- }-}--// hasWeightsWithPrefix checks if any weights exist with the given prefix.-func hasWeightsWithPrefix(weights WeightSource, prefix string) bool {- for _, name := range weights.ListTensors() {- if strings.HasPrefix(name, prefix+".") || name == prefix {- return true- }- }- return false-}--// loadSlice loads weights into each element of a slice of struct pointers.-func loadSlice(v reflect.Value, weights WeightSource, prefix string, errs *[]string) {- elemStructType := v.Type().Elem().Elem()-- for i := range v.Len() {- elem := v.Index(i)- if elem.IsNil() {- elem.Set(reflect.New(elemStructType))- }- loadStruct(elem.Elem(), weights, fmt.Sprintf("%s.%d", prefix, i), errs, false)- }-}--// joinPath joins path segments with dots, handling empty segments.-func joinPath(prefix, suffix string) string {- if prefix == "" {- return suffix- }- if suffix == "" {- return prefix- }- return prefix + "." + suffix-}--// LoadMultiLinearLayer loads a per-head linear layer from weights.-// Weight shape should be [num_heads, output_dims, input_dims].-// If quantized, always dequantizes since batched quantized matmul isn't supported.-func LoadMultiLinearLayer(weights WeightSource, path string) (nn.MultiLinearLayer, error) {- // Check if this is a quantized layer by looking for scale tensor- scalePath := path + ".weight_scale"- hasScale := weights.HasTensor(scalePath)-- weight, err := weights.GetTensor(path + ".weight")- if err != nil {- return nil, fmt.Errorf("failed to load weight %s: %w", path, err)- }-- if hasScale {- scales, err := weights.GetTensor(scalePath)- if err != nil {- return nil, fmt.Errorf("failed to load scales %s: %w", scalePath, err)- }-- var qbiases *mlx.Array- qbiasPath := path + ".weight_qbias"- if weights.HasTensor(qbiasPath) {- qbiases, _ = weights.GetTensor(qbiasPath)- }-- // Always dequantize for MultiLinear - no batched quantized matmul support- // Detect bits from tensor shapes (supports mixed-precision Q4/Q8)- weightShape := weight.Shape()- scalesShape := scales.Shape()- weightCols := int(weightShape[len(weightShape)-1])- scalesCols := int(scalesShape[len(scalesShape)-1])-- // Detect quantization from tensor shapes- // groupSize = weightCols * packFactor / scalesCols- // Note: groupSize4 = 2 * groupSize8 always, so ambiguous cases need metadata- groupSize4 := weightCols * 8 / scalesCols- groupSize8 := weightCols * 4 / scalesCols-- var bits, groupSize int- // Use metadata to help disambiguate when shapes are ambiguous- // (e.g., Q4 with group_size=64 has same shapes as Q8 with group_size=32)- quantType := strings.ToUpper(weights.Quantization())- isQ8Type := quantType == "Q8" || quantType == "FP8" || quantType == "INT8"-- if groupSize4 == 32 {- // Unambiguous: Q4 with group_size=32- bits = 4- groupSize = 32- } else if groupSize8 == 64 {- // Unambiguous: Q8 with group_size=64- bits = 8- groupSize = 64- } else if groupSize4 == 64 && groupSize8 == 32 {- // Ambiguous: could be Q4/gs=64 or Q8/gs=32, use metadata- if isQ8Type {- bits = 8- groupSize = 32- } else {- bits = 4- groupSize = 64- }- } else {- // Fallback: use global quantization params- _, bits, _ = QuantizationParams(weights.Quantization())- packFactor := 32 / bits- groupSize = weightCols * packFactor / scalesCols- }- weight = mlx.Dequantize(weight, scales, qbiases, groupSize, bits, "affine")- }-- return nn.NewMultiLinear(weight), nil-}--// LoadLinearLayer loads a linear layer from weights, automatically detecting if it's quantized.-// If {path}.weight_scale exists, creates a QuantizedLinear layer (or dequantizes if no kernel support).-func LoadLinearLayer(weights WeightSource, path string) (nn.LinearLayer, error) {- // Check if this is a quantized layer by looking for scale tensor- scalePath := path + ".weight_scale"- hasScale := weights.HasTensor(scalePath)- if hasScale {- weight, err := weights.GetTensor(path + ".weight")- if err != nil {- return nil, fmt.Errorf("failed to load quantized weight %s: %w", path, err)- }-- scales, err := weights.GetTensor(scalePath)- if err != nil {- return nil, fmt.Errorf("failed to load scales %s: %w", scalePath, err)- }-- // Bias is optional- var bias *mlx.Array- biasPath := path + ".bias"- if weights.HasTensor(biasPath) {- bias, _ = weights.GetTensor(biasPath)- }-- var qbiases *mlx.Array- qbiasPath := path + ".weight_qbias"- if weights.HasTensor(qbiasPath) {- qbiases, _ = weights.GetTensor(qbiasPath)- }-- // Detect bits from tensor shapes (supports mixed-precision Q4/Q8)- weightShape := weight.Shape()- scalesShape := scales.Shape()- weightCols := int(weightShape[len(weightShape)-1])- scalesCols := int(scalesShape[len(scalesShape)-1])-- // Detect quantization from tensor shapes- // groupSize = weightCols * packFactor / scalesCols- // Note: groupSize4 = 2 * groupSize8 always, so ambiguous cases need metadata- groupSize4 := weightCols * 8 / scalesCols- groupSize8 := weightCols * 4 / scalesCols-- var bits, groupSize int- mode := "affine"- // Use metadata to help disambiguate when shapes are ambiguous- // (e.g., Q4 with group_size=64 has same shapes as Q8 with group_size=32)- quantType := strings.ToUpper(weights.Quantization())- isQ8Type := quantType == "Q8" || quantType == "FP8" || quantType == "INT8"-- if groupSize4 == 32 {- // Unambiguous: Q4 with group_size=32- bits = 4- groupSize = 32- } else if groupSize8 == 64 {- // Unambiguous: Q8 with group_size=64- bits = 8- groupSize = 64- } else if groupSize4 == 64 && groupSize8 == 32 {- // Ambiguous: could be Q4/gs=64 or Q8/gs=32, use metadata- if isQ8Type {- bits = 8- groupSize = 32- } else {- bits = 4- groupSize = 64- }- } else {- // Fallback: use global quantization params- _, bits, mode = QuantizationParams(weights.Quantization())- packFactor := 32 / bits- groupSize = weightCols * packFactor / scalesCols- }-- // NVFP4 and MXFP8 don't have native quantized matmul kernels in MLX,- // so we always dequantize at load time. Affine modes (FP4, FP8) have kernel support.- if mlx.MetalIsAvailable() && mode != "nvfp4" && mode != "mxfp8" {- return &nn.QuantizedLinear{- Weight: weight,- Scales: scales,- QBiases: qbiases,- Bias: bias,- GroupSize: groupSize,- Bits: bits,- Mode: mode,- }, nil- }-- dequantized := mlx.Dequantize(weight, scales, qbiases, groupSize, bits, mode)- return nn.NewLinear(dequantized, bias), nil- }-- // Load as regular Linear- weight, err := weights.GetTensor(path + ".weight")- if err != nil {- return nil, fmt.Errorf("failed to load weight %s: %w", path, err)- }-- // Bias is optional- var bias *mlx.Array- biasPath := path + ".bias"- if weights.HasTensor(biasPath) {- bias, _ = weights.GetTensor(biasPath)- }-- return nn.NewLinear(weight, bias), nil-}diff --git a/x/imagegen/safetensors/safetensors.go b/x/imagegen/safetensors/safetensors.godeleted file mode 100644index f787c95cd..000000000--- a/x/imagegen/safetensors/safetensors.go+++ /dev/null@@ -1,317 +0,0 @@-package safetensors--import (- "encoding/binary"- "encoding/json"- "fmt"- "os"- "path/filepath"- "sort"- "strings"-- "github.com/ollama/ollama/x/imagegen/mlx"-)--// SafetensorHeader represents the JSON header of a safetensors file-type SafetensorHeader map[string]TensorInfo--// TensorInfo contains metadata about a tensor-type TensorInfo struct {- Dtype string `json:"dtype"`- Shape []int32 `json:"shape"`- DataOffsets [2]int `json:"data_offsets"`-}--// parseSafetensorHeader reads only the JSON header from a safetensors file.-func parseSafetensorHeader(path string) (SafetensorHeader, error) {- f, err := os.Open(path)- if err != nil {- return nil, fmt.Errorf("failed to open file: %w", err)- }- defer f.Close()-- var headerSize uint64- if err := binary.Read(f, binary.LittleEndian, &headerSize); err != nil {- return nil, fmt.Errorf("failed to read header size: %w", err)- }-- headerBytes := make([]byte, headerSize)- if _, err := f.Read(headerBytes); err != nil {- return nil, fmt.Errorf("failed to read header: %w", err)- }-- var header SafetensorHeader- if err := json.Unmarshal(headerBytes, &header); err != nil {- return nil, fmt.Errorf("failed to parse header: %w", err)- }-- delete(header, "__metadata__")- return header, nil-}--// dtypeFromString converts safetensors dtype string to mlx.Dtype-func dtypeFromString(s string) mlx.Dtype {- switch strings.ToUpper(s) {- case "F32", "FLOAT32":- return mlx.DtypeFloat32- case "F16", "FLOAT16":- return mlx.DtypeFloat16- case "BF16", "BFLOAT16":- return mlx.DtypeBFloat16- case "I32", "INT32":- return mlx.DtypeInt32- case "I64", "INT64":- return mlx.DtypeInt64- case "U8", "UINT8":- return mlx.DtypeUint8- case "F8_E4M3", "F8_E5M2", "F8_E4M3FN", "F8_E5M2FNUZ":- return mlx.DtypeUint8 // FP8 types stored as raw uint8 bytes- default:- return mlx.DtypeFloat32- }-}--// ModelWeights manages weights from multiple safetensor files.-type ModelWeights struct {- dir string // Model directory- tensorFiles map[string]string // tensor name -> file path- tensorInfo map[string]TensorInfo // tensor name -> metadata- nativeCache map[string]*mlx.SafetensorsFile // file path -> loaded native handle- cache map[string]*mlx.Array // tensor name -> array (after Load)-}--// LoadModelWeights scans safetensor files and builds a tensor index.-// This only reads JSON headers, not tensor data.-func LoadModelWeights(dir string) (*ModelWeights, error) {- mw := &ModelWeights{- dir: dir,- tensorFiles: make(map[string]string),- tensorInfo: make(map[string]TensorInfo),- nativeCache: make(map[string]*mlx.SafetensorsFile),- }-- entries, err := os.ReadDir(dir)- if err != nil {- return nil, fmt.Errorf("failed to read directory: %w", err)- }-- for _, entry := range entries {- if strings.HasSuffix(entry.Name(), ".safetensors") {- path := filepath.Join(dir, entry.Name())-- header, err := parseSafetensorHeader(path)- if err != nil {- return nil, fmt.Errorf("failed to parse %s: %w", entry.Name(), err)- }-- for name, info := range header {- mw.tensorFiles[name] = path- mw.tensorInfo[name] = info- }- }- }-- if len(mw.tensorFiles) == 0 {- return nil, fmt.Errorf("no safetensor files found in %s", dir)- }-- return mw, nil-}--// LoadModelWeightsFromPaths loads weights from specific safetensor file paths.-// Used for loading from blob storage where files are not in a directory.-func LoadModelWeightsFromPaths(paths []string) (*ModelWeights, error) {- mw := &ModelWeights{- tensorFiles: make(map[string]string),- tensorInfo: make(map[string]TensorInfo),- nativeCache: make(map[string]*mlx.SafetensorsFile),- }-- for _, path := range paths {- header, err := parseSafetensorHeader(path)- if err != nil {- return nil, fmt.Errorf("failed to parse %s: %w", path, err)- }-- for name, info := range header {- mw.tensorFiles[name] = path- mw.tensorInfo[name] = info- }- }-- if len(mw.tensorFiles) == 0 {- return nil, fmt.Errorf("no tensors found in provided paths")- }-- return mw, nil-}--// Load loads all tensors into cache with the specified dtype.-// If dtype is 0, tensors are loaded in their original dtype.-// Automatically uses streaming (memory-efficient) when dtype conversion is needed,-// or native loading when tensors are already in the target dtype.-func (mw *ModelWeights) Load(dtype mlx.Dtype) error {- if dtype == 0 {- return mw.loadNative()- }-- // Check if any tensor needs conversion- needsConversion := false- for name := range mw.tensorFiles {- info := mw.tensorInfo[name]- if dtypeFromString(info.Dtype) != dtype {- needsConversion = true- break- }- }-- if needsConversion {- return mw.loadStreaming(dtype)- }- return mw.loadNative()-}--// loadNative loads all tensors using the native memory-mapped loader.-func (mw *ModelWeights) loadNative() error {- mw.cache = make(map[string]*mlx.Array)-- fileToTensors := make(map[string][]string)- for name, path := range mw.tensorFiles {- fileToTensors[path] = append(fileToTensors[path], name)- }-- for path, names := range fileToTensors {- native, err := mlx.LoadSafetensorsNative(path)- if err != nil {- return fmt.Errorf("failed to load %s: %w", path, err)- }-- for _, name := range names {- arr := native.Get(name)- if arr == nil {- native.Free()- return fmt.Errorf("tensor %q not found in %s", name, path)- }- mw.cache[name] = arr- }-- mw.nativeCache[path] = native- }-- return nil-}--// loadStreaming loads tensors with dtype conversion.-// Uses the same pattern as Python: replace each entry in the map after conversion,-// so the original tensor loses its reference and can be freed.-func (mw *ModelWeights) loadStreaming(dtype mlx.Dtype) error {- mw.cache = make(map[string]*mlx.Array)-- fileToTensors := make(map[string][]string)- for name, path := range mw.tensorFiles {- fileToTensors[path] = append(fileToTensors[path], name)- }-- for path, names := range fileToTensors {- native, err := mlx.LoadSafetensorsNative(path)- if err != nil {- return fmt.Errorf("failed to load %s: %w", path, err)- }-- for _, name := range names {- src := native.Get(name)- if src == nil {- native.Free()- return fmt.Errorf("tensor %q not found in %s", name, path)- }-- dst := mlx.AsType(src, dtype)- mlx.Eval(dst)- native.Set(name, dst)- mw.cache[name] = dst- }-- native.Free()- }-- return nil-}--// Get returns a tensor from cache. Call Load() first.-func (mw *ModelWeights) Get(name string) (*mlx.Array, error) {- if mw.cache == nil {- return nil, fmt.Errorf("cache not initialized: call Load() first")- }- arr, ok := mw.cache[name]- if !ok {- return nil, fmt.Errorf("tensor %q not found in cache", name)- }- return arr, nil-}--// GetTensor loads a tensor using the native loader without caching.-// For bulk loading, use Load() + Get() instead.-func (mw *ModelWeights) GetTensor(name string) (*mlx.Array, error) {- if mw.cache != nil {- if arr, ok := mw.cache[name]; ok {- return arr, nil- }- }-- path, ok := mw.tensorFiles[name]- if !ok {- return nil, fmt.Errorf("tensor %q not found", name)- }-- native, ok := mw.nativeCache[path]- if !ok {- var err error- native, err = mlx.LoadSafetensorsNative(path)- if err != nil {- return nil, fmt.Errorf("failed to load %s: %w", path, err)- }- mw.nativeCache[path] = native- }-- return native.Get(name), nil-}--// GetTensorInfo returns metadata about a tensor without loading it.-func (mw *ModelWeights) GetTensorInfo(name string) (TensorInfo, bool) {- info, ok := mw.tensorInfo[name]- return info, ok-}--// ListTensors returns all tensor names.-func (mw *ModelWeights) ListTensors() []string {- names := make([]string, 0, len(mw.tensorFiles))- for name := range mw.tensorFiles {- names = append(names, name)- }- sort.Strings(names)- return names-}--// HasTensor checks if a tensor exists.-func (mw *ModelWeights) HasTensor(name string) bool {- _, ok := mw.tensorFiles[name]- return ok-}--// Quantization returns empty string for directory-based weights (not quantized).-func (mw *ModelWeights) Quantization() string {- return ""-}--// GroupSize returns 0 for directory-based weights (use default).-func (mw *ModelWeights) GroupSize() int {- return 0-}--// ReleaseAll releases all cached native file handles.-func (mw *ModelWeights) ReleaseAll() {- for path, native := range mw.nativeCache {- native.Free()- delete(mw.nativeCache, path)- }-}diff --git a/x/imagegen/safetensors/safetensors_test.go b/x/imagegen/safetensors/safetensors_test.godeleted file mode 100644index 5f3e10d71..000000000--- a/x/imagegen/safetensors/safetensors_test.go+++ /dev/null@@ -1,165 +0,0 @@-package safetensors--import (- "os"- "path/filepath"- "testing"-- "github.com/ollama/ollama/x/imagegen/mlx"-)--func TestLoadModelWeights(t *testing.T) {- // Skip if no model available- modelDir := "../weights/gpt-oss-20b"- if _, err := os.Stat(modelDir); os.IsNotExist(err) {- t.Skip("model weights not available")- }-- mw, err := LoadModelWeights(modelDir)- if err != nil {- t.Fatalf("LoadModelWeights: %v", err)- }- defer mw.ReleaseAll()-- // Check we found tensors- tensors := mw.ListTensors()- if len(tensors) == 0 {- t.Fatal("no tensors found")- }- t.Logf("found %d tensors", len(tensors))-- // Check HasTensor- if !mw.HasTensor(tensors[0]) {- t.Errorf("HasTensor(%q) = false", tensors[0])- }- if mw.HasTensor("nonexistent.weight") {- t.Error("HasTensor returned true for nonexistent tensor")- }-}--func TestGetTensor(t *testing.T) {- modelDir := "../weights/gpt-oss-20b"- if _, err := os.Stat(modelDir); os.IsNotExist(err) {- t.Skip("model weights not available")- }-- mw, err := LoadModelWeights(modelDir)- if err != nil {- t.Fatalf("LoadModelWeights: %v", err)- }- defer mw.ReleaseAll()-- tensors := mw.ListTensors()- if len(tensors) == 0 {- t.Skip("no tensors")- }-- // Load first tensor- arr, err := mw.GetTensor(tensors[0])- if err != nil {- t.Fatalf("GetTensor(%q): %v", tensors[0], err)- }-- // Verify it has a shape- shape := arr.Shape()- if len(shape) == 0 {- t.Error("tensor has no shape")- }- t.Logf("%s: shape=%v dtype=%v", tensors[0], shape, arr.Dtype())-}--func TestLoadWithDtype(t *testing.T) {- modelDir := "../weights/gpt-oss-20b"- if _, err := os.Stat(modelDir); os.IsNotExist(err) {- t.Skip("model weights not available")- }-- mw, err := LoadModelWeights(modelDir)- if err != nil {- t.Fatalf("LoadModelWeights: %v", err)- }- defer mw.ReleaseAll()-- // Load all tensors as bfloat16- if err := mw.Load(mlx.DtypeBFloat16); err != nil {- t.Fatalf("Load: %v", err)- }-- // Get a tensor from cache- tensors := mw.ListTensors()- arr, err := mw.Get(tensors[0])- if err != nil {- t.Fatalf("Get: %v", err)- }-- // Verify dtype (unless it was already bf16)- t.Logf("%s: dtype=%v", tensors[0], arr.Dtype())-}--func TestLookupTensor(t *testing.T) {- modelDir := "../weights/gpt-oss-20b"- if _, err := os.Stat(modelDir); os.IsNotExist(err) {- t.Skip("model weights not available")- }-- mw, err := LoadModelWeights(modelDir)- if err != nil {- t.Fatalf("LoadModelWeights: %v", err)- }- defer mw.ReleaseAll()-- // HasTensor returns false for nonexistent- if mw.HasTensor("nonexistent") {- t.Error("HasTensor should return false for nonexistent")- }-- // HasTensor returns true for existing tensor- tensors := mw.ListTensors()- if !mw.HasTensor(tensors[0]) {- t.Error("HasTensor should return true for existing tensor")- }-}--func TestParseSafetensorHeader(t *testing.T) {- modelDir := "../weights/gpt-oss-20b"- if _, err := os.Stat(modelDir); os.IsNotExist(err) {- t.Skip("model weights not available")- }-- // Find a safetensors file- entries, err := os.ReadDir(modelDir)- if err != nil {- t.Fatal(err)- }-- var stFile string- for _, e := range entries {- if filepath.Ext(e.Name()) == ".safetensors" {- stFile = filepath.Join(modelDir, e.Name())- break- }- }- if stFile == "" {- t.Skip("no safetensors file found")- }-- header, err := parseSafetensorHeader(stFile)- if err != nil {- t.Fatalf("parseSafetensorHeader: %v", err)- }-- if len(header) == 0 {- t.Error("header is empty")- }-- // Check a tensor has valid info- for name, info := range header {- if info.Dtype == "" {- t.Errorf("%s: empty dtype", name)- }- if len(info.Shape) == 0 {- t.Errorf("%s: empty shape", name)- }- break // just check one- }-}diff --git a/x/imagegen/server.go b/x/imagegen/server.godeleted file mode 100644index 7d9031f4e..000000000--- a/x/imagegen/server.go+++ /dev/null@@ -1,471 +0,0 @@-package imagegen--import (- "bufio"- "bytes"- "context"- "encoding/json"- "errors"- "fmt"- "io"- "log/slog"- "math/rand"- "net"- "net/http"- "os"- "os/exec"- "path/filepath"- "runtime"- "strconv"- "strings"- "sync"- "time"-- "github.com/ollama/ollama/envconfig"- "github.com/ollama/ollama/format"- "github.com/ollama/ollama/llm"- "github.com/ollama/ollama/ml"- "github.com/ollama/ollama/x/imagegen/manifest"-)--// Server wraps an MLX runner subprocess to implement llm.LlamaServer.-//-// This implementation is compatible with Ollama's scheduler and can be loaded/unloaded-// like any other model. It is used for image generation models.-type Server struct {- mu sync.Mutex- cmd *exec.Cmd- port int- modelName string- vramSize uint64- done chan error- client *http.Client- lastErr string // Last stderr line for error reporting- lastErrLock sync.Mutex-}--// NewServer prepares a new MLX runner server for image generation models.-// The subprocess is not started until Load() is called.-func NewServer(modelName string) (*Server, error) {- // Validate platform support before attempting to start- if err := CheckPlatformSupport(); err != nil {- return nil, err- }-- return &Server{- modelName: modelName,- done: make(chan error, 1),- client: &http.Client{Timeout: 10 * time.Minute},- }, nil-}--// ModelPath returns the path to the model.-func (s *Server) ModelPath() string {- return s.modelName-}--// Load checks whether the model fits in GPU memory and starts the subprocess.-func (s *Server) Load(ctx context.Context, _ ml.SystemInfo, gpus []ml.DeviceInfo, requireFull bool) ([]ml.DeviceID, error) {- // Estimate VRAM based on tensor size from manifest- if modelManifest, err := manifest.LoadManifest(s.modelName); err == nil {- s.vramSize = uint64(modelManifest.TotalTensorSize())- } else {- s.vramSize = 8 * 1024 * 1024 * 1024- }-- if len(gpus) > 0 {- available := gpus[0].FreeMemory- overhead := gpus[0].MinimumMemory() + envconfig.GpuOverhead()- if available > overhead {- available -= overhead- } else {- available = 0- }-- if s.vramSize > available {- if requireFull {- return nil, llm.ErrLoadRequiredFull- }- return nil, fmt.Errorf("model requires %s but only %s are available (after %s overhead)", format.HumanBytes2(s.vramSize), format.HumanBytes2(available), format.HumanBytes2(overhead))- }- }-- // Find a free port- port := 0- if a, err := net.ResolveTCPAddr("tcp", "localhost:0"); err == nil {- if l, err := net.ListenTCP("tcp", a); err == nil {- port = l.Addr().(*net.TCPAddr).Port- l.Close()- }- }- if port == 0 {- port = rand.Intn(65535-49152) + 49152- }- s.port = port-- // Get the current executable path (we use the same binary with runner subcommand)- exe, err := os.Executable()- if err != nil {- return nil, fmt.Errorf("unable to lookup executable path: %w", err)- }- if eval, err := filepath.EvalSymlinks(exe); err == nil {- exe = eval- }-- // Spawn subprocess: ollama runner --imagegen-engine --model <path> --port <port>- cmd := exec.Command(exe, "runner", "--imagegen-engine", "--model", s.modelName, "--port", strconv.Itoa(port))- cmd.Env = os.Environ()- configureMLXSubprocessEnv(cmd, ml.LibraryPaths(gpus))-- s.cmd = cmd-- // Forward subprocess stdout/stderr to server logs- stdout, _ := cmd.StdoutPipe()- stderr, _ := cmd.StderrPipe()- go func() {- scanner := bufio.NewScanner(stdout)- for scanner.Scan() {- slog.Info("mlx-runner", "msg", scanner.Text())- }- }()- go func() {- scanner := bufio.NewScanner(stderr)- for scanner.Scan() {- line := scanner.Text()- slog.Warn("mlx-runner", "msg", line)- s.lastErrLock.Lock()- s.lastErr = line- s.lastErrLock.Unlock()- }- }()-- slog.Info("starting mlx runner subprocess", "model", s.modelName, "port", s.port)- if err := cmd.Start(); err != nil {- return nil, fmt.Errorf("failed to start mlx runner: %w", err)- }-- // Reap subprocess when it exits- go func() {- err := cmd.Wait()- s.done <- err- }()-- return nil, nil-}--// Ping checks if the subprocess is healthy.-func (s *Server) Ping(ctx context.Context) error {- url := fmt.Sprintf("http://127.0.0.1:%d/health", s.port)- req, err := http.NewRequestWithContext(ctx, "GET", url, nil)- if err != nil {- return err- }- resp, err := s.client.Do(req)- if err != nil {- return err- }- defer resp.Body.Close()- if resp.StatusCode != http.StatusOK {- return fmt.Errorf("health check failed: %d", resp.StatusCode)- }- return nil-}--func mlxLibraryPathEnv() string {- switch runtime.GOOS {- case "windows":- return "PATH"- case "darwin":- return "DYLD_LIBRARY_PATH"- default:- return "LD_LIBRARY_PATH"- }-}--func configureMLXSubprocessEnv(cmd *exec.Cmd, libraryPaths []string) {- if len(libraryPaths) == 0 {- return- }-- // Search order for the imagegen runner is:- // 1. bundled lib/ollama root- // 2. backend-specific library dirs selected during GPU discovery- // 3. any existing caller-provided library path values- pathEnv := mlxLibraryPathEnv()- pathEnvPaths := append([]string{}, libraryPaths...)- if existingPath, ok := os.LookupEnv(pathEnv); ok {- pathEnvPaths = append(pathEnvPaths, filepath.SplitList(existingPath)...)- }- setSubprocessEnv(cmd, pathEnv, strings.Join(pathEnvPaths, string(filepath.ListSeparator)))- slog.Debug("mlx subprocess library path", pathEnv, strings.Join(pathEnvPaths, string(filepath.ListSeparator)))-- ollamaLibraryPaths := append([]string{}, libraryPaths...)- if existingPath, ok := os.LookupEnv("OLLAMA_LIBRARY_PATH"); ok {- ollamaLibraryPaths = append(ollamaLibraryPaths, filepath.SplitList(existingPath)...)- }- setSubprocessEnv(cmd, "OLLAMA_LIBRARY_PATH", strings.Join(ollamaLibraryPaths, string(filepath.ListSeparator)))- slog.Debug("mlx subprocess library path", "OLLAMA_LIBRARY_PATH", strings.Join(ollamaLibraryPaths, string(filepath.ListSeparator)))-}--func setSubprocessEnv(cmd *exec.Cmd, key, value string) {- for i := range cmd.Env {- name, _, ok := strings.Cut(cmd.Env[i], "=")- if ok && strings.EqualFold(name, key) {- cmd.Env[i] = key + "=" + value- return- }- }- cmd.Env = append(cmd.Env, key+"="+value)-}--// getLastErr returns the last stderr line.-func (s *Server) getLastErr() string {- s.lastErrLock.Lock()- defer s.lastErrLock.Unlock()- return s.lastErr-}--// WaitUntilRunning waits for the subprocess to be ready.-func (s *Server) WaitUntilRunning(ctx context.Context) error {- timeout := time.After(envconfig.LoadTimeout())- ticker := time.NewTicker(100 * time.Millisecond)- defer ticker.Stop()-- for {- select {- case err := <-s.done:- errMsg := s.getLastErr()- if errMsg != "" {- return fmt.Errorf("mlx runner failed: %s (exit: %v)", errMsg, err)- }- return fmt.Errorf("mlx runner exited unexpectedly: %w", err)- case <-timeout:- errMsg := s.getLastErr()- if errMsg != "" {- return fmt.Errorf("timeout waiting for mlx runner: %s", errMsg)- }- return errors.New("timeout waiting for mlx runner to start")- case <-ticker.C:- if err := s.Ping(ctx); err == nil {- slog.Info("mlx runner is ready", "port", s.port)- return nil- }- }- }-}--// Completion handles both text and image generation requests.-func (s *Server) Completion(ctx context.Context, req llm.CompletionRequest, fn func(llm.CompletionResponse)) error {- seed := req.Seed- if seed == 0 {- seed = time.Now().UnixNano()- }-- // Extract raw image bytes from the request media.- var images [][]byte- for _, media := range req.Media {- images = append(images, media.Data)- }-- // Build request for subprocess- creq := Request{- Prompt: req.Prompt,- Width: req.Width,- Height: req.Height,- Steps: int(req.Steps),- Seed: seed,- Images: images,- }-- // Pass LLM options if present- if req.Options != nil {- creq.Options = &RequestOptions{- NumPredict: req.Options.NumPredict,- Temperature: float64(req.Options.Temperature),- TopP: float64(req.Options.TopP),- TopK: req.Options.TopK,- Stop: req.Options.Stop,- }- }-- body, err := json.Marshal(creq)- if err != nil {- return err- }-- url := fmt.Sprintf("http://127.0.0.1:%d/completion", s.port)- httpReq, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))- if err != nil {- return err- }- httpReq.Header.Set("Content-Type", "application/json")-- resp, err := s.client.Do(httpReq)- if err != nil {- return err- }- defer resp.Body.Close()-- if resp.StatusCode != http.StatusOK {- body, _ := io.ReadAll(resp.Body)- return fmt.Errorf("%s", strings.TrimSpace(string(body)))- }-- scanner := bufio.NewScanner(resp.Body)- scanner.Buffer(make([]byte, 1024*1024), 16*1024*1024) // 16MB max- for scanner.Scan() {- // Parse subprocess response- var raw struct {- Image string `json:"image,omitempty"`- Content string `json:"content,omitempty"`- Done bool `json:"done"`- Step int `json:"step,omitempty"`- Total int `json:"total,omitempty"`- StopReason string `json:"stop_reason,omitempty"`- PromptEvalCount int `json:"prompt_eval_count,omitempty"`- PromptEvalDuration int `json:"prompt_eval_duration,omitempty"`- EvalCount int `json:"eval_count,omitempty"`- EvalDuration int `json:"eval_duration,omitempty"`- }- if err := json.Unmarshal(scanner.Bytes(), &raw); err != nil {- slog.Debug("mlx response parse error", "error", err, "line", string(scanner.Bytes()))- continue- }-- // Log stop reason when generation completes- if raw.Done && raw.StopReason != "" {- slog.Info("mlx generation completed", "stop_reason", raw.StopReason)- }-- // Convert to llm.CompletionResponse- cresp := llm.CompletionResponse{- Content: raw.Content,- Done: raw.Done,- Step: raw.Step,- TotalSteps: raw.Total,- Image: raw.Image,- PromptEvalCount: raw.PromptEvalCount,- PromptEvalDuration: time.Duration(raw.PromptEvalDuration),- EvalCount: raw.EvalCount,- EvalDuration: time.Duration(raw.EvalDuration),- }-- fn(cresp)- if cresp.Done {- return nil- }- }-- // Scanner exited without receiving Done - connection was likely closed- scanErr := scanner.Err()- if scanErr != nil {- slog.Error("mlx scanner error", "error", scanErr)- } else {- slog.Warn("mlx scanner EOF without Done response - subprocess may have crashed")- }-- // Check if subprocess is still alive- if s.HasExited() {- slog.Error("mlx subprocess has exited unexpectedly")- if errMsg := s.getLastErr(); errMsg != "" {- return fmt.Errorf("mlx runner closed response before completion: %s", errMsg)- }- }-- if scanErr != nil {- return scanErr- }-- return errors.New("mlx runner closed response before completion")-}--func (s *Server) Chat(ctx context.Context, req llm.ChatRequest, fn func(llm.ChatResponse)) error {- return errors.New("image generation runner does not support native chat")-}--func (s *Server) ApplyChatTemplate(ctx context.Context, req llm.ChatRequest) (string, error) {- return "", errors.New("image generation runner does not support native chat templates")-}--// Close terminates the subprocess.-func (s *Server) Close() error {- s.mu.Lock()- defer s.mu.Unlock()-- if s.cmd != nil && s.cmd.Process != nil {- slog.Info("stopping mlx runner subprocess", "pid", s.cmd.Process.Pid)- s.cmd.Process.Signal(os.Interrupt)-- // Wait briefly for graceful shutdown- select {- case <-s.done:- case <-time.After(5 * time.Second):- s.cmd.Process.Kill()- }- s.cmd = nil- }- return nil-}--// MemorySize returns the total and VRAM memory usage.-func (s *Server) MemorySize() (total, vram uint64) {- return s.vramSize, s.vramSize-}--// VRAMByGPU returns VRAM usage for a specific GPU.-func (s *Server) VRAMByGPU(id ml.DeviceID) uint64 {- return s.vramSize-}--// ContextLength returns the context length (not applicable for image generation).-func (s *Server) ContextLength() int {- return 0-}--// Embedding returns embeddings for the input.-func (s *Server) Embedding(ctx context.Context, input string) ([]float32, int, error) {- return nil, 0, errors.New("embeddings not supported for MLX models")-}--// Tokenize tokenizes the input content.-func (s *Server) Tokenize(ctx context.Context, content string) ([]int, error) {- return nil, errors.New("tokenization not supported for image generation models")-}--// Detokenize converts tokens back to text.-func (s *Server) Detokenize(ctx context.Context, tokens []int) (string, error) {- return "", errors.New("detokenization not supported for MLX models")-}--// Pid returns the process ID of the subprocess.-func (s *Server) Pid() int {- s.mu.Lock()- defer s.mu.Unlock()- if s.cmd != nil && s.cmd.Process != nil {- return s.cmd.Process.Pid- }- return -1-}--// GetPort returns the port the subprocess is listening on.-func (s *Server) GetPort() int {- return s.port-}--// GetDeviceInfos returns device information.-func (s *Server) GetDeviceInfos(ctx context.Context) []ml.DeviceInfo {- return nil-}--// HasExited returns whether the subprocess has exited.-func (s *Server) HasExited() bool {- select {- case <-s.done:- return true- default:- return false- }-}--// Ensure Server implements llm.LlamaServer-var _ llm.LlamaServer = (*Server)(nil)diff --git a/x/imagegen/server_test.go b/x/imagegen/server_test.godeleted file mode 100644index 9386d2858..000000000--- a/x/imagegen/server_test.go+++ /dev/null@@ -1,102 +0,0 @@-package imagegen--import (- "context"- "encoding/json"- "io"- "net/http"- "strings"- "testing"-- "github.com/ollama/ollama/llm"-)--type roundTripFunc func(*http.Request) (*http.Response, error)--func (fn roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {- return fn(req)-}--func newCompletionTestServer(handler func(*http.Request) string) *Server {- return &Server{- port: 11434,- done: make(chan error, 1),- client: &http.Client{- Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {- body := handler(req)- return &http.Response{- StatusCode: http.StatusOK,- Header: make(http.Header),- Body: io.NopCloser(strings.NewReader(body)),- Request: req,- }, nil- }),- },- }-}--func TestCompletionReturnsImageData(t *testing.T) {- s := newCompletionTestServer(func(r *http.Request) string {- if r.URL.Path != "/completion" {- t.Fatalf("path = %q, want /completion", r.URL.Path)- }-- var req Request- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- t.Fatal(err)- }- if req.Prompt != "test prompt" || req.Width != 512 || req.Height != 256 || req.Steps != 7 || req.Seed != 42 {- t.Fatalf("unexpected request: %+v", req)- }- if len(req.Images) != 1 || string(req.Images[0]) != "input-image" {- t.Fatalf("images = %q, want input-image", req.Images)- }-- return `{"step":1,"total":2}` + "\n" +- `{"done":true,"image":"base64png"}` + "\n"- })-- var responses []llm.CompletionResponse- err := s.Completion(context.Background(), llm.CompletionRequest{- Prompt: "test prompt",- Width: 512,- Height: 256,- Steps: 7,- Seed: 42,- Media: []llm.MediaData{llm.NewMediaData(0, []byte("input-image"))},- }, func(resp llm.CompletionResponse) {- responses = append(responses, resp)- })- if err != nil {- t.Fatal(err)- }- if len(responses) != 2 {- t.Fatalf("responses = %d, want 2", len(responses))- }- if responses[0].Step != 1 || responses[0].TotalSteps != 2 || responses[0].Done {- t.Fatalf("progress response = %+v", responses[0])- }- if !responses[1].Done || responses[1].Image != "base64png" {- t.Fatalf("final response = %+v", responses[1])- }-}--func TestCompletionEOFBeforeDoneReturnsError(t *testing.T) {- s := newCompletionTestServer(func(r *http.Request) string {- return `{"step":1,"total":2}` + "\n"- })-- var responses []llm.CompletionResponse- err := s.Completion(context.Background(), llm.CompletionRequest{Prompt: "test prompt"}, func(resp llm.CompletionResponse) {- responses = append(responses, resp)- })- if err == nil {- t.Fatal("expected error")- }- if !strings.Contains(err.Error(), "closed response before completion") {- t.Fatalf("error = %v", err)- }- if len(responses) != 1 || responses[0].Done {- t.Fatalf("responses = %+v, want one non-done progress response", responses)- }-}diff --git a/x/imagegen/tokenizer/README.md b/x/imagegen/tokenizer/README.mddeleted file mode 100644index 03de51510..000000000--- a/x/imagegen/tokenizer/README.md+++ /dev/null@@ -1,85 +0,0 @@-# Tokenizer--Tokenizer for LLM inference supporting BPE, SentencePiece, and WordPiece algorithms. The goal of this package is to see if a pure Go tokenizer can be fast and correct. It primarily supports the `imagegen` models however it (or parts of it) could be considered to replace Ollama's tokenizer in the `model` package.--## Features--- **BPE (Byte Pair Encoding)** - GPT-2/Llama style with byte-level encoding-- **SentencePiece** - Gemma style with `▁` space handling-- **WordPiece** - BERT style with `##` continuation tokens-- **Parallel encoding** - Automatic parallelization for inputs >4KB-- **HuggingFace compatible** - Loads `tokenizer.json` directly--## Usage--```go-import "github.com/ollama/ollama/x/imagegen/tokenizer"--// Load from HuggingFace model directory-tok, err := tokenizer.Load("./weights/Llama-3.2-1B")-if err != nil {- log.Fatal(err)-}--// Encode text to token IDs-ids := tok.Encode("Hello, world!", false) // false = don't add BOS--// Decode back to text-text := tok.Decode(ids)--// Check special tokens-if tok.IsEOS(ids[len(ids)-1]) {- // End of sequence-}-```--## Performance--Benchmarks on Apple M3 Max:--| Input Size | Encode | Decode | Tokens |-|------------|--------|--------|--------|-| 1 KB | 14.5 MB/s | 267 MB/s | 231 |-| 10 KB | 10.9 MB/s | 321 MB/s | 2,301 |-| 100 KB | 8.9 MB/s | 311 MB/s | 23,001 |-| 1 MB | 9.6 MB/s | 321 MB/s | 230,001 |--Comparison with other implementations (10 MB input):--| Implementation | Encode Speed | Notes |-|----------------|--------------|-------|-| Engine (this) | ~10 MB/s | stdlib RE2, parallel >4KB |-| tiktoken (Rust) | ~17 MB/s | Highly optimized regex |-| Ollama (Go) | ~2-3 MB/s | regexp2 backtracking |--## Performance Opportunities--Potential optimizations not yet implemented:--| Optimization | Expected Gain | Complexity |-|--------------|---------------|------------|-| Aho-Corasick for special tokens | 2-3x for many special tokens | Medium |-| Custom regex engine (like tiktoken) | 1.5-2x | High |-| SIMD byte scanning | 1.3-1.5x for pretokenizer | Medium |-| Assembly BPE merge loop | 1.2-1.5x | High |-| Memoization for repeated substrings | Variable | Low |--Current bottleneck is the pretokenizer regex (~60% of encode time). tiktoken achieves ~17 MB/s with a hand-tuned Rust regex engine.--## Not Yet Implemented--| Feature | Used By | Notes |-|---------|---------|-------|-| Unigram tokenizer | T5, ALBERT, mBART | Different algorithm (not BPE) |-| Unicode normalizers | Some multilingual models | NFD, NFKC, lowercase, etc. |-| Custom pretokenizers | Model-specific | Beyond standard patterns |--Most HuggingFace models use BPE or SentencePiece, which are fully supported. WordPiece (BERT-style) is also supported with standard `[UNK]` fallback for out-of-vocabulary characters.--## Files--| File | Description |-|------|-------------|-| `tokenizer.go` | Main implementation (~1000 lines) |-| `tokenizer_test.go` | Tests and benchmarks |-| `testdata/` | Mini tokenizer for unit tests |diff --git a/x/imagegen/tokenizer/tokenizer.go b/x/imagegen/tokenizer/tokenizer.godeleted file mode 100644index 2e1ccae16..000000000--- a/x/imagegen/tokenizer/tokenizer.go+++ /dev/null@@ -1,1170 +0,0 @@-// tokenizer.go - BPE and SentencePiece tokenizer for HuggingFace models-//-// Based on standard BPE algorithm (Sennrich et al. 2015) with:-// - GPT-2 byte-level encoding (OpenAI tiktoken)-// - HuggingFace tokenizer.json pretokenizer patterns-// - SentencePiece ▁-style space handling--package tokenizer--import (- "encoding/json"- "fmt"- "os"- "regexp"- "runtime"- "sort"- "strconv"- "strings"- "sync"- "unicode"- "unicode/utf8"-)--// TokenizerType identifies the tokenization algorithm-type TokenizerType int--const (- TokenizerBPE TokenizerType = iota // GPT-2 style byte-level BPE- TokenizerSentencePiece // SentencePiece with ▁ for spaces- TokenizerWordPiece // BERT style with ## continuations-)--// Vocabulary holds the tokenizer vocabulary and merges-type Vocabulary struct {- Values []string- Reverse map[string]int32- Merges map[string]int-- BOS int32- EOS []int32 // Multiple EOS tokens supported (e.g., Gemma has <eos> and <end_of_turn>)- PAD int32 // Padding token (often <|endoftext|> or <pad>)- AddBOS bool- AddEOS bool-- // Precomputed byte token IDs for <0xNN> fallback (256 entries, -1 if not found)- byteTokens [256]int32-}--// Tokenizer handles BPE, SentencePiece, and WordPiece tokenization-type Tokenizer struct {- vocab *Vocabulary- pretokenizer *regexp.Regexp- specialTokens map[string]int32 // Special tokens for direct lookup- typ TokenizerType // Algorithm type- unkToken int32 // [UNK] token ID for WordPiece fallback-}--// Precomputed GPT-2 byte-level encoding table-// Maps byte values to their encoded rune equivalents-var byteToRune [256]rune--func init() {- for b := range 256 {- r := rune(b)- switch {- case r == 0x00ad:- r = 0x0143- case r <= 0x0020:- r = r + 0x0100- case r >= 0x007f && r <= 0x00a0:- r = r + 0x00a2- }- byteToRune[b] = r- }-}--// loadSpecialTokenConfig loads special token configuration from HuggingFace companion files.-//-// Loading priority for EOS tokens (can be single int or []int):-// 1. generation_config.json - eos_token_id (preferred, matches HuggingFace generation)-// 2. config.json - eos_token_id (model config fallback)-// 3. tokenizer_config.json - eos_token string + add_bos/add_eos flags-// 4. special_tokens_map.json - final fallback-func loadSpecialTokenConfig(dir string, t *Tokenizer) {- // Helper to parse eos_token_id which can be int or []int- parseTokenIDs := func(v interface{}) []int32 {- switch val := v.(type) {- case float64:- return []int32{int32(val)}- case []interface{}:- ids := make([]int32, 0, len(val))- for _, id := range val {- if f, ok := id.(float64); ok {- ids = append(ids, int32(f))- }- }- return ids- }- return nil- }-- // Priority 1: generation_config.json (eos_token_id can be int or []int)- if data, err := os.ReadFile(dir + "generation_config.json"); err == nil {- var config struct {- EOSTokenID interface{} `json:"eos_token_id"`- BOSTokenID interface{} `json:"bos_token_id"`- }- if err := json.Unmarshal(data, &config); err == nil {- if ids := parseTokenIDs(config.EOSTokenID); len(ids) > 0 {- t.vocab.EOS = ids- }- if ids := parseTokenIDs(config.BOSTokenID); len(ids) > 0 {- t.vocab.BOS = ids[0]- }- }- }-- // Priority 2: config.json (model config, same format)- if len(t.vocab.EOS) == 0 || t.vocab.BOS < 0 {- if data, err := os.ReadFile(dir + "config.json"); err == nil {- var config struct {- EOSTokenID interface{} `json:"eos_token_id"`- BOSTokenID interface{} `json:"bos_token_id"`- }- if err := json.Unmarshal(data, &config); err == nil {- if len(t.vocab.EOS) == 0 {- if ids := parseTokenIDs(config.EOSTokenID); len(ids) > 0 {- t.vocab.EOS = ids- }- }- if t.vocab.BOS < 0 {- if ids := parseTokenIDs(config.BOSTokenID); len(ids) > 0 {- t.vocab.BOS = ids[0]- }- }- }- }- }-- // Priority 3: tokenizer_config.json (token strings + add_bos/add_eos flags)- if data, err := os.ReadFile(dir + "tokenizer_config.json"); err == nil {- var config struct {- BOSToken interface{} `json:"bos_token"`- EOSToken interface{} `json:"eos_token"`- PADToken interface{} `json:"pad_token"`- AddBOSToken *bool `json:"add_bos_token"`- AddEOSToken *bool `json:"add_eos_token"`- }- if err := json.Unmarshal(data, &config); err == nil {- if t.vocab.BOS < 0 {- if bosStr := extractTokenString(config.BOSToken); bosStr != "" {- if id, ok := t.specialTokens[bosStr]; ok {- t.vocab.BOS = id- }- }- }- if len(t.vocab.EOS) == 0 {- if eosStr := extractTokenString(config.EOSToken); eosStr != "" {- if id, ok := t.specialTokens[eosStr]; ok {- t.vocab.EOS = []int32{id}- }- }- }- if t.vocab.PAD < 0 {- if padStr := extractTokenString(config.PADToken); padStr != "" {- if id, ok := t.specialTokens[padStr]; ok {- t.vocab.PAD = id- }- }- }- if config.AddBOSToken != nil {- t.vocab.AddBOS = *config.AddBOSToken- }- if config.AddEOSToken != nil {- t.vocab.AddEOS = *config.AddEOSToken- }- }- }-- // Priority 4: special_tokens_map.json (final fallback)- if data, err := os.ReadFile(dir + "special_tokens_map.json"); err == nil {- var tokensMap map[string]interface{}- if err := json.Unmarshal(data, &tokensMap); err == nil {- if t.vocab.BOS < 0 {- if bosStr := extractTokenString(tokensMap["bos_token"]); bosStr != "" {- if id, ok := t.specialTokens[bosStr]; ok {- t.vocab.BOS = id- }- }- }- if len(t.vocab.EOS) == 0 {- if eosStr := extractTokenString(tokensMap["eos_token"]); eosStr != "" {- if id, ok := t.specialTokens[eosStr]; ok {- t.vocab.EOS = []int32{id}- }- }- }- if t.vocab.PAD < 0 {- if padStr := extractTokenString(tokensMap["pad_token"]); padStr != "" {- if id, ok := t.specialTokens[padStr]; ok {- t.vocab.PAD = id- }- }- }- }- }-}--// extractTokenString extracts the token string from various formats used in HuggingFace configs.-// Tokens can be represented as:-// - string: "token"-// - object: {"content": "token", ...}-func extractTokenString(v interface{}) string {- if v == nil {- return ""- }- // Direct string- if s, ok := v.(string); ok {- return s- }- // Object with content field- if m, ok := v.(map[string]interface{}); ok {- if content, ok := m["content"].(string); ok {- return content- }- }- return ""-}--// rewritePatternForRE2 rewrites HuggingFace pretokenizer regex patterns to be-// compatible with Go's regexp package (RE2). HuggingFace patterns use PCRE features:-// - (?!\S) negative lookahead - RE2 doesn't support this-// - (?i:...) inline case-insensitive groups - RE2 doesn't support this-//-// We replace \s+(?!\S)|\s+ with \s+ and fix whitespace boundaries in encodeWithRegex().-// The lookahead version splits "a b" into ["a", " ", " b"] (space prepended to word).-// Simple \s+ would give ["a", " ", "b"]. We post-process to match Python's behavior.-func rewritePatternForRE2(pattern string) string {- // Replace lookahead pattern with simple \s+ - we fix boundaries in encodeWithRegex()- pattern = strings.ReplaceAll(pattern, `\s+(?!\S)|\s+`, `\s+`)-- // Handle the pattern when it appears with a ? suffix (optional contractions in GPT-4o style)- // IMPORTANT: Must be done before the non-optional version to avoid partial replacement- pattern = strings.ReplaceAll(pattern,- `(?i:'s|'t|'re|'ve|'m|'ll|'d)?`,- `(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?`)-- // Expand case-insensitive contraction pattern to explicit alternations- // (?i:'s|'t|'re|'ve|'m|'ll|'d) -> '[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD]- pattern = strings.ReplaceAll(pattern,- `(?i:'s|'t|'re|'ve|'m|'ll|'d)`,- `(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])`)-- return pattern-}--// LoadFromBytes loads a tokenizer from tokenizer.json bytes.-// This is useful when loading from blob storage where the file content is already in memory.-// Note: This won't load special token config from companion files. Use LoadFromBytesWithConfig-// to provide tokenizer_config.json data for proper PAD/EOS token loading.-func LoadFromBytes(data []byte) (*Tokenizer, error) {- return loadFromTokenizerJSON(data, "")-}--// TokenizerConfig holds optional configuration data that can be passed to LoadFromBytesWithConfig.-type TokenizerConfig struct {- TokenizerConfigJSON []byte // tokenizer_config.json content- GenerationConfigJSON []byte // generation_config.json content- SpecialTokensMapJSON []byte // special_tokens_map.json content- ConfigJSON []byte // config.json content-}--// LoadFromBytesWithConfig loads a tokenizer from tokenizer.json bytes with additional config files.-// This is useful when loading from blob storage where companion config files are also blobs.-func LoadFromBytesWithConfig(data []byte, config *TokenizerConfig) (*Tokenizer, error) {- t, err := loadFromTokenizerJSON(data, "")- if err != nil {- return nil, err- }-- if config == nil {- return t, nil- }-- // Apply special token configs from provided data- loadSpecialTokenConfigFromBytes(t, config)-- return t, nil-}--// loadSpecialTokenConfigFromBytes loads special token configuration from byte slices.-func loadSpecialTokenConfigFromBytes(t *Tokenizer, config *TokenizerConfig) {- // Helper to parse eos_token_id which can be int or []int- parseTokenIDs := func(v interface{}) []int32 {- switch val := v.(type) {- case float64:- return []int32{int32(val)}- case []interface{}:- ids := make([]int32, 0, len(val))- for _, id := range val {- if f, ok := id.(float64); ok {- ids = append(ids, int32(f))- }- }- return ids- }- return nil- }-- // Priority 1: generation_config.json- if len(config.GenerationConfigJSON) > 0 {- var genConfig struct {- EOSTokenID interface{} `json:"eos_token_id"`- BOSTokenID interface{} `json:"bos_token_id"`- }- if err := json.Unmarshal(config.GenerationConfigJSON, &genConfig); err == nil {- if ids := parseTokenIDs(genConfig.EOSTokenID); len(ids) > 0 {- t.vocab.EOS = ids- }- if ids := parseTokenIDs(genConfig.BOSTokenID); len(ids) > 0 {- t.vocab.BOS = ids[0]- }- }- }-- // Priority 2: config.json- if len(config.ConfigJSON) > 0 && (len(t.vocab.EOS) == 0 || t.vocab.BOS < 0) {- var modelConfig struct {- EOSTokenID interface{} `json:"eos_token_id"`- BOSTokenID interface{} `json:"bos_token_id"`- }- if err := json.Unmarshal(config.ConfigJSON, &modelConfig); err == nil {- if len(t.vocab.EOS) == 0 {- if ids := parseTokenIDs(modelConfig.EOSTokenID); len(ids) > 0 {- t.vocab.EOS = ids- }- }- if t.vocab.BOS < 0 {- if ids := parseTokenIDs(modelConfig.BOSTokenID); len(ids) > 0 {- t.vocab.BOS = ids[0]- }- }- }- }-- // Priority 3: tokenizer_config.json- if len(config.TokenizerConfigJSON) > 0 {- var tokConfig struct {- BOSToken interface{} `json:"bos_token"`- EOSToken interface{} `json:"eos_token"`- PADToken interface{} `json:"pad_token"`- AddBOSToken *bool `json:"add_bos_token"`- AddEOSToken *bool `json:"add_eos_token"`- }- if err := json.Unmarshal(config.TokenizerConfigJSON, &tokConfig); err == nil {- if t.vocab.BOS < 0 {- if bosStr := extractTokenString(tokConfig.BOSToken); bosStr != "" {- if id, ok := t.specialTokens[bosStr]; ok {- t.vocab.BOS = id- }- }- }- if len(t.vocab.EOS) == 0 {- if eosStr := extractTokenString(tokConfig.EOSToken); eosStr != "" {- if id, ok := t.specialTokens[eosStr]; ok {- t.vocab.EOS = []int32{id}- }- }- }- if t.vocab.PAD < 0 {- if padStr := extractTokenString(tokConfig.PADToken); padStr != "" {- if id, ok := t.specialTokens[padStr]; ok {- t.vocab.PAD = id- }- }- }- if tokConfig.AddBOSToken != nil {- t.vocab.AddBOS = *tokConfig.AddBOSToken- }- if tokConfig.AddEOSToken != nil {- t.vocab.AddEOS = *tokConfig.AddEOSToken- }- }- }-- // Priority 4: special_tokens_map.json- if len(config.SpecialTokensMapJSON) > 0 {- var tokensMap map[string]interface{}- if err := json.Unmarshal(config.SpecialTokensMapJSON, &tokensMap); err == nil {- if t.vocab.BOS < 0 {- if bosStr := extractTokenString(tokensMap["bos_token"]); bosStr != "" {- if id, ok := t.specialTokens[bosStr]; ok {- t.vocab.BOS = id- }- }- }- if len(t.vocab.EOS) == 0 {- if eosStr := extractTokenString(tokensMap["eos_token"]); eosStr != "" {- if id, ok := t.specialTokens[eosStr]; ok {- t.vocab.EOS = []int32{id}- }- }- }- if t.vocab.PAD < 0 {- if padStr := extractTokenString(tokensMap["pad_token"]); padStr != "" {- if id, ok := t.specialTokens[padStr]; ok {- t.vocab.PAD = id- }- }- }- }- }-}--// Load loads a tokenizer from a path which can be:-// - A tokenizer.json file-// - A directory containing tokenizer.json or vocab.json + merges.txt-func Load(path string) (*Tokenizer, error) {- // Check if path is a directory- if info, err := os.Stat(path); err == nil && info.IsDir() {- dir := strings.TrimSuffix(path, "/") + "/"- // Try tokenizer.json first- if data, err := os.ReadFile(dir + "tokenizer.json"); err == nil {- return loadFromTokenizerJSON(data, dir)- }- // Fall back to vocab.json + merges.txt- return LoadVocabMerges(path)- }-- // It's a file - read it directly- data, err := os.ReadFile(path)- if err != nil {- return nil, fmt.Errorf("failed to read tokenizer: %w", err)- }-- // Get directory for loading companion files- dir := ""- if idx := strings.LastIndex(path, "/"); idx >= 0 {- dir = path[:idx+1]- }- return loadFromTokenizerJSON(data, dir)-}--// loadFromTokenizerJSON parses a tokenizer.json file-func loadFromTokenizerJSON(data []byte, dir string) (*Tokenizer, error) {- var raw struct {- Model struct {- Type string `json:"type"` // "BPE" or "WordPiece"- Vocab map[string]int32 `json:"vocab"`- Merges json.RawMessage `json:"merges"` // Can be []string or [][]string (BPE only)- } `json:"model"`- PreTokenizer json.RawMessage `json:"pre_tokenizer"`- Decoder json.RawMessage `json:"decoder"`- AddedTokens []struct {- ID int32 `json:"id"`- Content string `json:"content"`- Special bool `json:"special"`- } `json:"added_tokens"`- }-- if err := json.Unmarshal(data, &raw); err != nil {- return nil, fmt.Errorf("failed to parse tokenizer: %w", err)- }-- // Parse merges - can be []string (Llama) or [][]string (GPT-OSS)- // WordPiece models don't have merges- var mergesStrings []string- if raw.Model.Type != "WordPiece" && raw.Model.Merges != nil {- var mergesArrays [][]string- if err := json.Unmarshal(raw.Model.Merges, &mergesStrings); err != nil {- // Try array of arrays format- if err := json.Unmarshal(raw.Model.Merges, &mergesArrays); err != nil {- return nil, fmt.Errorf("failed to parse merges: %w", err)- }- // Convert [][]string to []string- mergesStrings = make([]string, len(mergesArrays))- for i, pair := range mergesArrays {- mergesStrings[i] = pair[0] + " " + pair[1]- }- }- }-- // Build tokenizer- t := &Tokenizer{- vocab: &Vocabulary{- Values: make([]string, len(raw.Model.Vocab)),- Reverse: raw.Model.Vocab,- Merges: make(map[string]int, len(mergesStrings)),- BOS: -1,- PAD: -1,- },- specialTokens: make(map[string]int32),- }-- // Build values array- for token, id := range raw.Model.Vocab {- if int(id) >= len(t.vocab.Values) {- newValues := make([]string, id+1)- copy(newValues, t.vocab.Values)- t.vocab.Values = newValues- }- t.vocab.Values[id] = token- }-- // Build merges map- for i, merge := range mergesStrings {- t.vocab.Merges[merge] = i- }-- // Add all added_tokens to vocabulary and special tokens map.- // HuggingFace treats ALL added_tokens as special for tokenization purposes -- // they bypass BPE and get their own token ID. The "special" flag just indicates- // if it's a "truly special" token like BOS/EOS/PAD, but for tokenization we need- // to treat all added_tokens as special to match HuggingFace behavior.- for _, tok := range raw.AddedTokens {- if int(tok.ID) >= len(t.vocab.Values) {- newValues := make([]string, tok.ID+1)- copy(newValues, t.vocab.Values)- t.vocab.Values = newValues- }- t.vocab.Values[tok.ID] = tok.Content- t.specialTokens[tok.Content] = tok.ID // Add ALL added_tokens to special tokens- }-- // Load special token configuration from companion files- loadSpecialTokenConfig(dir, t)-- // Precompute byte token IDs for <0xNN> fallback- initByteTokens(t)-- // Determine tokenizer type- switch {- case raw.Model.Type == "WordPiece":- t.typ = TokenizerWordPiece- case detectSentencePiece(raw.Decoder):- t.typ = TokenizerSentencePiece- default:- t.typ = TokenizerBPE- }-- // Parse and compile pretokenizer pattern (BPE only - SentencePiece doesn't use pretokenizer)- if t.typ == TokenizerBPE {- pattern := extractPretokenizer(raw.PreTokenizer)- if pattern == "" {- pattern = `'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+`- }- re, err := regexp.Compile(rewritePatternForRE2(pattern))- if err != nil {- return nil, fmt.Errorf("failed to compile pretokenizer regex %q: %w", pattern, err)- }- t.pretokenizer = re- }-- return t, nil-}--// detectSentencePiece checks if the decoder uses SentencePiece-style (▁ for spaces)-// vs GPT-2 byte-level encoding-func detectSentencePiece(data json.RawMessage) bool {- if data == nil {- return false- }-- // Check for Sequence decoder with Replace step (SentencePiece style)- var seq struct {- Type string `json:"type"`- Decoders []struct {- Type string `json:"type"`- Pattern struct {- String string `json:"String"`- } `json:"pattern"`- } `json:"decoders"`- }- if err := json.Unmarshal(data, &seq); err == nil {- if seq.Type == "Sequence" {- for _, dec := range seq.Decoders {- // Look for Replace decoder that converts ▁ to space- if dec.Type == "Replace" && dec.Pattern.String == "▁" {- return true- }- }- }- }-- // Check for direct ByteLevel decoder (GPT-2 style)- var simple struct {- Type string `json:"type"`- }- if err := json.Unmarshal(data, &simple); err == nil {- if simple.Type == "ByteLevel" {- return false- }- }-- return false-}--// initByteTokens precomputes byte token IDs for <0xNN> fallback encoding-func initByteTokens(t *Tokenizer) {- for i := range t.vocab.byteTokens {- t.vocab.byteTokens[i] = -1- }- for b := range 256 {- token := fmt.Sprintf("<0x%02X>", b)- if id, ok := t.vocab.Reverse[token]; ok {- t.vocab.byteTokens[b] = id- }- }-}--// extractPretokenizer extracts the regex pattern from the pre_tokenizer config-func extractPretokenizer(data json.RawMessage) string {- if data == nil {- return ""- }-- // Try to parse as a single Split pretokenizer- var single struct {- Type string `json:"type"`- Pattern struct {- Regex string `json:"Regex"`- } `json:"pattern"`- }- if err := json.Unmarshal(data, &single); err == nil && single.Pattern.Regex != "" {- return single.Pattern.Regex- }-- // Try to parse as Sequence of pretokenizers - use first Split pattern- var seq struct {- Type string `json:"type"`- Pretokenizers []struct {- Type string `json:"type"`- Pattern struct {- Regex string `json:"Regex"`- } `json:"pattern"`- } `json:"pretokenizers"`- }- if err := json.Unmarshal(data, &seq); err == nil && seq.Type == "Sequence" {- for _, pt := range seq.Pretokenizers {- if pt.Type == "Split" && pt.Pattern.Regex != "" {- return pt.Pattern.Regex- }- }- }-- return ""-}--// isNonNewlineWhitespace returns true if s contains only whitespace characters (no newlines)-func isNonNewlineWhitespace(s string) bool {- if s == "" {- return false- }- for _, r := range s {- if r == '\n' || r == '\r' {- return false- }- if !unicode.IsSpace(r) {- return false- }- }- return true-}--// splitBySpecialTokens splits text into parts, keeping special tokens as separate elements-func (t *Tokenizer) splitBySpecialTokens(s string) []string {- if len(t.specialTokens) == 0 {- return []string{s}- }-- // Sort special tokens by length (longest first) to match greedily- tokens := make([]string, 0, len(t.specialTokens))- for tok := range t.specialTokens {- tokens = append(tokens, tok)- }- sort.Slice(tokens, func(i, j int) bool {- return len(tokens[i]) > len(tokens[j])- })-- var result []string- remaining := s-- for len(remaining) > 0 {- found := false- for _, tok := range tokens {- if strings.HasPrefix(remaining, tok) {- result = append(result, tok)- remaining = remaining[len(tok):]- found = true- break- }- }- if !found {- // Find next special token position- nextPos := len(remaining)- for _, tok := range tokens {- if idx := strings.Index(remaining, tok); idx != -1 && idx < nextPos {- nextPos = idx- }- }- if nextPos > 0 {- result = append(result, remaining[:nextPos])- }- remaining = remaining[nextPos:]- }- }-- return result-}--// Encode tokenizes text to token IDs. Parallelizes for large inputs (>10KB).-func (t *Tokenizer) Encode(s string, addBOS bool) []int32 {- // First: split by special tokens- parts := t.splitBySpecialTokens(s)-- // Second: collect all pretokenizer chunks- type chunk struct {- text string- isSpecial bool- }- var allChunks []chunk-- if t.pretokenizer != nil {- re := t.pretokenizer- for _, part := range parts {- if _, ok := t.specialTokens[part]; ok {- allChunks = append(allChunks, chunk{part, true})- continue- }-- // Split by pretokenizer regex- type match struct{ start, end int }- var matches []match- offset := 0- for offset < len(part) {- loc := re.FindStringIndex(part[offset:])- if loc == nil {- break- }- matches = append(matches, match{offset + loc[0], offset + loc[1]})- offset += loc[1]- }-- // Apply whitespace boundary fix for Python regex compatibility- for i := range len(matches) - 1 {- m := part[matches[i].start:matches[i].end]- next := part[matches[i+1].start:matches[i+1].end]-- if isNonNewlineWhitespace(m) && len(next) > 0 {- firstRune, _ := utf8.DecodeRuneInString(next)- if unicode.IsLetter(firstRune) {- lastSpaceStart := matches[i].end- for j := matches[i].end; j > matches[i].start; {- r, size := utf8.DecodeLastRuneInString(part[matches[i].start:j])- if unicode.IsSpace(r) {- lastSpaceStart = j - size- break- }- j -= size- }- if lastSpaceStart > matches[i].start {- matches[i].end = lastSpaceStart- matches[i+1].start = lastSpaceStart- } else {- matches[i+1].start = matches[i].start- matches[i].end = matches[i].start- }- }- }- }-- for _, m := range matches {- if m.end > m.start {- allChunks = append(allChunks, chunk{part[m.start:m.end], false})- }- }- }- } else {- // No pretokenizer - treat each part as a single chunk- for _, part := range parts {- if _, ok := t.specialTokens[part]; ok {- allChunks = append(allChunks, chunk{part, true})- } else {- allChunks = append(allChunks, chunk{part, false})- }- }- }-- // Encode chunks - parallel for large inputs (>4KB), sequential otherwise- var ids []int32- if len(s) < 4096 {- for _, c := range allChunks {- if c.isSpecial {- if id, ok := t.specialTokens[c.text]; ok {- ids = append(ids, id)- }- } else {- ids = t.encodeChunkInto(c.text, ids)- }- }- } else {- numWorkers := runtime.GOMAXPROCS(0)- if numWorkers > len(allChunks) {- numWorkers = len(allChunks)- }-- chunksPer := (len(allChunks) + numWorkers - 1) / numWorkers- results := make([][]int32, numWorkers)- var wg sync.WaitGroup-- for i := range numWorkers {- start := i * chunksPer- end := start + chunksPer- if end > len(allChunks) {- end = len(allChunks)- }- if start >= end {- continue- }-- wg.Add(1)- go func(i int, chunks []chunk) {- defer wg.Done()- var r []int32- for _, c := range chunks {- if c.isSpecial {- if id, ok := t.specialTokens[c.text]; ok {- r = append(r, id)- }- } else {- r = t.encodeChunkInto(c.text, r)- }- }- results[i] = r- }(i, allChunks[start:end])- }- wg.Wait()-- for _, r := range results {- ids = append(ids, r...)- }- }-- if addBOS && t.vocab.BOS >= 0 {- ids = append([]int32{t.vocab.BOS}, ids...)- }- return ids-}--// encodeChunkInto appends encoded tokens to ids and returns the extended slice-// Uses BPE merge algorithm when merges are available, otherwise longest-match-func (t *Tokenizer) encodeChunkInto(s string, ids []int32) []int32 {- if t.typ == TokenizerWordPiece {- return t.encodeWordPieceInto(s, ids)- }-- if s == "" {- return ids- }-- // Apply encoding transformation- // SentencePiece: replace space with ▁- // BPE: convert bytes using precomputed table (GPT-2 byte-level encoding)- var encoded string- if t.typ == TokenizerSentencePiece {- encoded = strings.ReplaceAll(s, " ", "▁")- } else {- var sb strings.Builder- sb.Grow(len(s) * 2)- for i := range len(s) {- sb.WriteRune(byteToRune[s[i]])- }- encoded = sb.String()- }-- // Fast path: check if entire chunk is a single token- if id, ok := t.vocab.Reverse[encoded]; ok {- return append(ids, id)- }-- return t.encodeBPEMerge(encoded, ids)-}--// encodeBPEMerge encodes using BPE merge algorithm.-// Repeatedly merges the pair with lowest rank until no more merges possible.-// Works correctly with empty merges (falls back to individual rune/byte encoding).-func (t *Tokenizer) encodeBPEMerge(encoded string, ids []int32) []int32 {- // Start with individual runes as parts- runes := []rune(encoded)- parts := make([]string, len(runes))- for i, r := range runes {- parts[i] = string(r)- }-- // Repeatedly merge lowest-rank pair- for len(parts) > 1 {- minRank := int(0x7FFFFFFF)- minIdx := -1-- for i := range len(parts) - 1 {- // Merge key format: "token1 token2" (space-separated)- mergeKey := parts[i] + " " + parts[i+1]- if rank, ok := t.vocab.Merges[mergeKey]; ok {- if rank < minRank {- minRank = rank- minIdx = i- }- }- }-- if minIdx < 0 {- break // No more merges possible- }-- // Merge the pair- parts[minIdx] = parts[minIdx] + parts[minIdx+1]- parts = append(parts[:minIdx+1], parts[minIdx+2:]...)- }-- // Convert parts to token IDs- for _, part := range parts {- if id, ok := t.vocab.Reverse[part]; ok {- ids = append(ids, id)- } else {- // Byte fallback for unknown parts- for _, b := range []byte(part) {- if id := t.vocab.byteTokens[b]; id >= 0 {- ids = append(ids, id)- }- }- }- }-- return ids-}--// encodeWordPieceInto appends WordPiece tokens to ids and returns extended slice-// Uses greedy longest-match with ## prefix for continuation tokens-func (t *Tokenizer) encodeWordPieceInto(s string, ids []int32) []int32 {- if s == "" {- return ids- }-- // Check if entire string is in vocabulary (common case)- if id, ok := t.vocab.Reverse[s]; ok {- return append(ids, id)- }-- runes := []rune(s)- start := 0-- for start < len(runes) {- end := len(runes)- found := false-- // Greedy longest-match- for end > start {- substr := string(runes[start:end])- if start > 0 {- // Continuation token: prefix with ##- substr = "##" + substr- }-- if id, ok := t.vocab.Reverse[substr]; ok {- ids = append(ids, id)- found = true- start = end- break- }- end--- }-- if !found {- // No match found - use [UNK] token or skip- if t.unkToken >= 0 {- ids = append(ids, t.unkToken)- }- start++- }- }-- return ids-}--// Decode converts token IDs back to text-func (t *Tokenizer) Decode(ids []int32) string {- var sb strings.Builder-- for _, id := range ids {- if int(id) >= len(t.vocab.Values) {- continue- }-- token := t.vocab.Values[id]-- switch t.typ {- case TokenizerWordPiece:- // WordPiece style: strip ## prefix from continuation tokens- if strings.HasPrefix(token, "##") {- sb.WriteString(token[2:])- } else {- sb.WriteString(token)- }- case TokenizerSentencePiece:- // SentencePiece style: replace ▁ with space, decode byte tokens- token = strings.ReplaceAll(token, "▁", " ")- // Handle byte fallback tokens like <0x0D>- if len(token) == 6 && token[0] == '<' && token[1] == '0' && token[2] == 'x' && token[5] == '>' {- if v, err := strconv.ParseUint(token[3:5], 16, 8); err == nil {- sb.WriteByte(byte(v))- continue- }- }- sb.WriteString(token)- default:- // GPT-2 BPE style: decode byte-level encoding- for _, r := range token {- switch {- case r == 0x0100:- // NULL byte (0x00 encoded as 0x0100)- sb.WriteByte(0)- continue- case r == 0x0143:- r = 0x00ad- case r > 0x0100 && r <= 0x0120:- r = r - 0x0100- case r > 0x0120 && r <= 0x0142:- r = r - 0x00a2- }-- // Write as byte, not UTF-8 encoded rune- sb.WriteByte(byte(r))- }- }- }-- return sb.String()-}--// VocabSize returns the vocabulary size-func (t *Tokenizer) VocabSize() int {- return len(t.vocab.Values)-}--// BOS returns the beginning of sequence token ID-func (t *Tokenizer) BOS() int32 {- return t.vocab.BOS-}--// EOS returns the first end of sequence token ID (for backwards compatibility)-func (t *Tokenizer) EOS() int32 {- if len(t.vocab.EOS) > 0 {- return t.vocab.EOS[0]- }- return -1-}--// EOSTokens returns all end of sequence token IDs-func (t *Tokenizer) EOSTokens() []int32 {- return t.vocab.EOS-}--// PAD returns the padding token ID, or -1 if not set-func (t *Tokenizer) PAD() int32 {- return t.vocab.PAD-}--// IsEOS returns true if the token ID is an end of sequence token-func (t *Tokenizer) IsEOS(id int32) bool {- for _, eos := range t.vocab.EOS {- if id == eos {- return true- }- }- return false-}--// GetSpecialToken returns the token ID for a special token string-func (t *Tokenizer) GetSpecialToken(name string) (int32, bool) {- id, ok := t.specialTokens[name]- return id, ok-}--// LoadVocabMerges loads a tokenizer from vocab.json + merges.txt format (GPT-style)-func LoadVocabMerges(dir string) (*Tokenizer, error) {- vocabPath := dir + "/vocab.json"- mergesPath := dir + "/merges.txt"- addedTokensPath := dir + "/added_tokens.json"-- // Load vocab- vocabData, err := os.ReadFile(vocabPath)- if err != nil {- return nil, fmt.Errorf("failed to read vocab.json: %w", err)- }-- vocabMap := make(map[string]int32)- if err := json.Unmarshal(vocabData, &vocabMap); err != nil {- return nil, fmt.Errorf("failed to parse vocab.json: %w", err)- }-- // Load merges- mergesData, err := os.ReadFile(mergesPath)- if err != nil {- return nil, fmt.Errorf("failed to read merges.txt: %w", err)- }-- mergesLines := strings.Split(string(mergesData), "\n")- var mergesStrings []string- for _, line := range mergesLines {- line = strings.TrimSpace(line)- if line == "" || strings.HasPrefix(line, "#") {- continue- }- mergesStrings = append(mergesStrings, line)- }-- // Build tokenizer- t := &Tokenizer{- vocab: &Vocabulary{- Values: make([]string, len(vocabMap)),- Reverse: vocabMap,- Merges: make(map[string]int, len(mergesStrings)),- BOS: -1,- PAD: -1,- },- specialTokens: make(map[string]int32),- }-- // Load added tokens if exists- if addedData, err := os.ReadFile(addedTokensPath); err == nil {- addedMap := make(map[string]int32)- if err := json.Unmarshal(addedData, &addedMap); err == nil {- for token, id := range addedMap {- vocabMap[token] = id- t.specialTokens[token] = id- }- }- }-- // Build values array- for token, id := range vocabMap {- if int(id) >= len(t.vocab.Values) {- newValues := make([]string, id+1)- copy(newValues, t.vocab.Values)- t.vocab.Values = newValues- }- t.vocab.Values[id] = token- }-- // Build merges map- for i, merge := range mergesStrings {- t.vocab.Merges[merge] = i- }-- // Load special token configuration from companion files- loadSpecialTokenConfig(dir+"/", t)-- // Precompute byte token IDs for <0xNN> fallback- initByteTokens(t)-- // GPT-2/tiktoken pretokenizer pattern- pattern := `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`- re, err := regexp.Compile(rewritePatternForRE2(pattern))- if err != nil {- return nil, fmt.Errorf("failed to compile pretokenizer regex: %w", err)- }- t.pretokenizer = re-- return t, nil-}diff --git a/x/imagegen/tokenizer/tokenizer_test.go b/x/imagegen/tokenizer/tokenizer_test.godeleted file mode 100644index 4aa6818a2..000000000--- a/x/imagegen/tokenizer/tokenizer_test.go+++ /dev/null@@ -1,783 +0,0 @@-package tokenizer--import (- "bytes"- "os"- "os/exec"- "path/filepath"- "regexp"- "strings"- "sync"- "testing"-)--// TestPatternCompilation validates that HuggingFace pretokenizer patterns-// can be rewritten for Go's RE2 regexp engine and compiled successfully.-func TestPatternCompilation(t *testing.T) {- patterns := []struct {- name string- pattern string- }{- {"llama3", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`},- {"qwen2", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`},- {"gpt4o", `[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`},- {"gpt2", `'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+`},- {"deepseek_cjk", `[一-龥\x{3040}-ゟ゠-ヿ]+`},- }-- for _, p := range patterns {- t.Run(p.name, func(t *testing.T) {- rewritten := rewritePatternForRE2(p.pattern)- if _, err := regexp.Compile(rewritten); err != nil {- t.Errorf("failed to compile pattern: %v\noriginal: %s\nrewritten: %s", err, p.pattern, rewritten)- }- })- }-}--// TestRoundtrip verifies the fundamental property: encode(text) -> decode -> text-// This is the key invariant from tiktoken's test suite.-func TestRoundtrip(t *testing.T) {- tok, err := Load("testdata/mini_llama.json")- if err != nil {- t.Fatalf("failed to load tokenizer: %v", err)- }-- // Test cases covering key edge cases from tiktoken- inputs := []string{- // Empty and simple- "",- "a",- "hello",- "hello world",-- // Whitespace edge cases- " ",- " ",- " ",- " hello",- "hello ",- " hello ",- "hello world",- "hello world",- "\t",- "\n",- "\r\n",- "hello\nworld",- "hello\n\nworld",-- // Contractions- "don't",- "I'm",- "we'll",- "they're",- "it's",- "DON'T", // uppercase-- // Numbers- "123",- "1234567890",- "3.14159",- "$100",- "50%",-- // Unicode- "こんにちは", // Japanese- "你好", // Chinese- "مرحبا", // Arabic (RTL)- "🎉", // Emoji- "Hello 世界", // Mixed- "café", // Accented- "naïve", // Diaeresis- "Ω≈ç√∫", // Math symbols-- // Code- "func main() {}",- "if (x == 0) { return; }",- "import \"fmt\"",- "x := 42",- "// comment",- "/* block */",-- // Repetition (tiktoken specifically tests this)- "aaaa",- "aaaaaaaaaaaa",- strings.Repeat("a", 100),- strings.Repeat("hello ", 50),-- // Punctuation- "...",- "!!!",- "???",- "hello, world!",- "(parentheses)",- "[brackets]",- "{braces}",-- // Mixed complexity- "The quick brown fox jumps over the lazy dog.",- "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",- "func TestRoundtrip(t *testing.T) { t.Run(\"test\", func(t *testing.T) {}) }",- }-- for _, input := range inputs {- name := input- if len(name) > 30 {- name = name[:30] + "..."- }- if name == "" {- name = "<empty>"- }- name = strings.ReplaceAll(name, "\n", "\\n")- name = strings.ReplaceAll(name, "\t", "\\t")-- t.Run(name, func(t *testing.T) {- tokens := tok.Encode(input, false)- decoded := tok.Decode(tokens)- if decoded != input {- t.Errorf("roundtrip failed:\n input: %q\n tokens: %v\n decoded: %q", input, tokens, decoded)- }- })- }-}--// TestSpecialTokens verifies that special tokens are handled correctly-func TestSpecialTokens(t *testing.T) {- tok, err := Load("testdata/mini_llama.json")- if err != nil {- t.Fatalf("failed to load tokenizer: %v", err)- }-- // Special tokens should be preserved through encode/decode- t.Run("bos_preserved", func(t *testing.T) {- if tok.BOS() < 0 {- t.Skip("no BOS token")- }- tokens := tok.Encode("hello", true)- if len(tokens) == 0 || tokens[0] != tok.BOS() {- t.Errorf("BOS not prepended: got %v, want first token to be %d", tokens, tok.BOS())- }- })-- t.Run("special_token_split", func(t *testing.T) {- // If we have special tokens, verify they're split correctly- for tokenStr, tokenID := range tok.specialTokens {- input := "before" + tokenStr + "after"- tokens := tok.Encode(input, false)-- found := false- for _, id := range tokens {- if id == tokenID {- found = true- break- }- }- if !found {- t.Errorf("special token %q (id=%d) not found in encoding of %q: %v",- tokenStr, tokenID, input, tokens)- }- }- })-}--// TestConcurrency verifies thread-safe encoding-func TestConcurrency(t *testing.T) {- tok, err := Load("testdata/mini_llama.json")- if err != nil {- t.Fatalf("failed to load tokenizer: %v", err)- }-- input := "The quick brown fox jumps over the lazy dog."- expected := tok.Encode(input, false)-- var wg sync.WaitGroup- errors := make(chan error, 100)-- for range 100 {- wg.Add(1)- go func() {- defer wg.Done()- got := tok.Encode(input, false)- if len(got) != len(expected) {- errors <- nil // just signal error- return- }- for j := range got {- if got[j] != expected[j] {- errors <- nil- return- }- }- }()- }-- wg.Wait()- close(errors)-- if len(errors) > 0 {- t.Errorf("concurrent encoding produced inconsistent results")- }-}--// TestIntegration runs against real model directories, comparing with Python transformers.-// Skips if model weights are not available.-func TestIntegration(t *testing.T) {- models := []string{- "../weights/Llama-3.2-1B",- "../weights/gemma-3-1b-it",- "../weights/gpt-oss-20b",- }-- // Test inputs covering various edge cases- inputs := []string{- "Hello, world!",- "The quick brown fox jumps over the lazy dog.",- "こんにちは世界",- "def fibonacci(n):\n if n <= 1:\n return n\n return fibonacci(n-1) + fibonacci(n-2)",- "1234567890",- " spaces ",- "don't won't can't",- }-- for _, modelPath := range models {- modelName := filepath.Base(modelPath)-- t.Run(modelName, func(t *testing.T) {- tokenizerPath := filepath.Join(modelPath, "tokenizer.json")- if _, err := os.Stat(tokenizerPath); err != nil {- t.Skipf("skipping: %s not found", tokenizerPath)- }-- tok, err := Load(tokenizerPath)- if err != nil {- t.Fatalf("failed to load tokenizer: %v", err)- }-- for _, input := range inputs {- t.Run(truncate(input, 20), func(t *testing.T) {- // Test roundtrip- tokens := tok.Encode(input, false)- decoded := tok.Decode(tokens)- if decoded != input {- t.Errorf("roundtrip failed:\n input: %q\n decoded: %q", input, decoded)- }-- // Compare with Python if available- if pythonTokens, err := pythonEncode(modelPath, input); err == nil {- if !equalInt32Slice(tokens, pythonTokens) {- t.Errorf("mismatch with Python:\n go: %v\n python: %v", tokens, pythonTokens)- }- }- })- }- })- }-}--// pythonEncode calls Python transformers to encode text, for comparison-func pythonEncode(modelPath, text string) ([]int32, error) {- script := `-import sys, json-from transformers import AutoTokenizer-tok = AutoTokenizer.from_pretrained(sys.argv[1])-tokens = tok.encode(sys.argv[2], add_special_tokens=False)-print(json.dumps(tokens))-`- cmd := exec.Command("python3", "-c", script, modelPath, text)- var out bytes.Buffer- cmd.Stdout = &out- cmd.Stderr = nil-- if err := cmd.Run(); err != nil {- return nil, err- }-- // Parse JSON array- var tokens []int32- output := strings.TrimSpace(out.String())- if output == "" || output == "[]" {- return []int32{}, nil- }-- // Simple parsing for [1, 2, 3] format- output = strings.Trim(output, "[]")- if output == "" {- return []int32{}, nil- }-- for _, s := range strings.Split(output, ",") {- s = strings.TrimSpace(s)- var v int32- if _, err := parseIntSimple(s, &v); err == nil {- tokens = append(tokens, v)- }- }-- return tokens, nil-}--func parseIntSimple(s string, v *int32) (bool, error) {- var n int64- for _, c := range s {- if c >= '0' && c <= '9' {- n = n*10 + int64(c-'0')- }- }- *v = int32(n)- return true, nil-}--func equalInt32Slice(a, b []int32) bool {- if len(a) != len(b) {- return false- }- for i := range a {- if a[i] != b[i] {- return false- }- }- return true-}--func truncate(s string, n int) string {- if len(s) <= n {- return s- }- return s[:n] + "..."-}--// TestBPEPretokenizer verifies BPE pretokenizer splits text correctly-// using the GPT-2 style regex pattern (no dependency on tokenizer files)-func TestBPEPretokenizer(t *testing.T) {- pattern := `'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+`- re := regexp.MustCompile(rewritePatternForRE2(pattern))-- tests := []struct {- input string- expected []string- }{- {"Hello", []string{"Hello"}},- {"Hello world", []string{"Hello", " world"}},- {"Hello, world!", []string{"Hello", ",", " world", "!"}},- {"don't", []string{"don", "'t"}},- {"I'm", []string{"I", "'m"}},- {"123", []string{"123"}},- {"12345", []string{"12345"}}, // GPT-2 pattern matches any digit sequence- {"a b", []string{"a", " ", " b"}}, // whitespace boundary: last space prepends to word- {" ", []string{" "}}, // pure whitespace stays together- {"\n\n", []string{"\n\n"}}, // newlines stay together- }-- for _, tt := range tests {- t.Run(tt.input, func(t *testing.T) {- // Get regex matches- matches := re.FindAllStringIndex(tt.input, -1)- var chunks []string- for _, m := range matches {- chunks = append(chunks, tt.input[m[0]:m[1]])- }-- // Apply whitespace boundary fix (same logic as Encode)- for i := range len(chunks) - 1 {- if isNonNewlineWhitespace(chunks[i]) && len(chunks[i+1]) > 0 {- r, _ := []rune(chunks[i+1])[0], 0- if r >= 'A' && r <= 'z' { // simplified letter check- // Move last space to next chunk- if len(chunks[i]) > 0 {- lastSpace := chunks[i][len(chunks[i])-1:]- chunks[i] = chunks[i][:len(chunks[i])-1]- chunks[i+1] = lastSpace + chunks[i+1]- }- }- }- }-- // Filter empty chunks- var result []string- for _, c := range chunks {- if c != "" {- result = append(result, c)- }- }-- if len(result) != len(tt.expected) {- t.Errorf("got %v, want %v", result, tt.expected)- return- }- for i := range result {- if result[i] != tt.expected[i] {- t.Errorf("chunk %d: got %q, want %q", i, result[i], tt.expected[i])- }- }- })- }-}--// TestSentencePiecePretokenizer verifies SentencePiece doesn't use pretokenizer-// and correctly replaces spaces with ▁ (no dependency on tokenizer files)-func TestSentencePiecePretokenizer(t *testing.T) {- // SentencePiece has no pretokenizer - whole text is one chunk- // Spaces are replaced with ▁ during encoding-- tests := []struct {- input string- expected string // after space replacement- }{- {"Hello", "Hello"},- {"Hello world", "Hello▁world"},- {"Hello, world!", "Hello,▁world!"},- {" spaces ", "▁▁▁spaces▁▁▁"},- {" Hello", "▁Hello"},- {"Hello ", "Hello▁"},- {"a b c", "a▁b▁c"},- }-- for _, tt := range tests {- t.Run(tt.input, func(t *testing.T) {- // SentencePiece encoding: replace space with ▁- result := strings.ReplaceAll(tt.input, " ", "▁")- if result != tt.expected {- t.Errorf("got %q, want %q", result, tt.expected)- }- })- }-}--// TestWordPiecePretokenizer verifies WordPiece (BERT) pretokenizer splits correctly-// BertPreTokenizer splits on whitespace and punctuation-func TestWordPiecePretokenizer(t *testing.T) {- // BertPreTokenizer behavior: split on whitespace and punctuation- // Whitespace is stripped, punctuation becomes separate tokens-- tests := []struct {- input string- expected []string- }{- {"Hello", []string{"Hello"}},- {"Hello world", []string{"Hello", "world"}}, // whitespace stripped- {"Hello, world!", []string{"Hello", ",", "world", "!"}}, // punct separate- {"don't", []string{"don", "'", "t"}}, // apostrophe separate (unlike BPE)- {" spaces ", []string{"spaces"}}, // whitespace stripped- {"Hello.World", []string{"Hello", ".", "World"}}, // punct splits- {"[email protected]", []string{"test", "@", "email", ".", "com"}},- }-- for _, tt := range tests {- t.Run(tt.input, func(t *testing.T) {- result := splitBertStyle(tt.input)- if len(result) != len(tt.expected) {- t.Errorf("got %v, want %v", result, tt.expected)- return- }- for i := range result {- if result[i] != tt.expected[i] {- t.Errorf("token %d: got %q, want %q", i, result[i], tt.expected[i])- }- }- })- }-}--// splitBertStyle mimics BertPreTokenizer: split on whitespace and punctuation-func splitBertStyle(s string) []string {- var result []string- var current strings.Builder-- for _, r := range s {- if r == ' ' || r == '\t' || r == '\n' || r == '\r' {- // Whitespace: flush current token, don't add whitespace- if current.Len() > 0 {- result = append(result, current.String())- current.Reset()- }- } else if isPunct(r) {- // Punctuation: flush current, add punct as separate token- if current.Len() > 0 {- result = append(result, current.String())- current.Reset()- }- result = append(result, string(r))- } else {- current.WriteRune(r)- }- }- if current.Len() > 0 {- result = append(result, current.String())- }- return result-}--func isPunct(r rune) bool {- // Common ASCII punctuation- return (r >= '!' && r <= '/') || (r >= ':' && r <= '@') ||- (r >= '[' && r <= '`') || (r >= '{' && r <= '~')-}--// TestRepeatedDigits verifies correct tokenization of repeated digit sequences.-// Llama-style tokenizers split digits in groups of 1-3 due to the \p{N}{1,3} pattern.-func TestRepeatedDigits(t *testing.T) {- tok, err := Load("./testdata/mini_llama.json")- if err != nil {- t.Skipf("mini_llama.json not available: %v", err)- }-- // Pattern: 1 digit, 2 digits, 3 digits, then repeats- // "0" -> [single], "00" -> [double], "000" -> [triple]- // "0000" -> [triple, single], etc.- tests := []struct {- input string- count int // expected token count- }{- {"0", 1},- {"00", 1},- {"000", 1},- {"0000", 2}, // 3 + 1- {"00000", 2}, // 3 + 2- {"000000", 2}, // 3 + 3- {"0000000", 3},- {"00000000", 3},- {"000000000", 3},- }-- for _, tt := range tests {- t.Run(tt.input, func(t *testing.T) {- ids := tok.Encode(tt.input, false)- if len(ids) != tt.count {- t.Errorf("Encode(%q) = %d tokens, want %d", tt.input, len(ids), tt.count)- }- // Verify roundtrip- decoded := tok.Decode(ids)- if decoded != tt.input {- t.Errorf("Decode(Encode(%q)) = %q", tt.input, decoded)- }- })- }-}--// TestNullByte verifies that null bytes roundtrip correctly-func TestNullByte(t *testing.T) {- tok, err := Load("./testdata/mini_llama.json")- if err != nil {- t.Skipf("mini_llama.json not available: %v", err)- }-- ids := tok.Encode("\x00", false)- decoded := tok.Decode(ids)- if decoded != "\x00" {- t.Errorf("null byte roundtrip failed: got %q, want %q", decoded, "\x00")- }-}--// TestTokenizerTypeDetection verifies correct detection of tokenizer types-func TestTokenizerTypeDetection(t *testing.T) {- tests := []struct {- name string- decoder string- expected TokenizerType- }{- {- name: "ByteLevel decoder (BPE)",- decoder: `{"type": "ByteLevel"}`,- expected: TokenizerBPE,- },- {- name: "Sequence with Replace ▁ (SentencePiece)",- decoder: `{- "type": "Sequence",- "decoders": [- {"type": "Replace", "pattern": {"String": "▁"}, "content": " "}- ]- }`,- expected: TokenizerSentencePiece,- },- {- name: "null decoder (BPE default)",- decoder: `null`,- expected: TokenizerBPE,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- isSPM := detectSentencePiece([]byte(tt.decoder))- var got TokenizerType- if isSPM {- got = TokenizerSentencePiece- } else {- got = TokenizerBPE- }- if got != tt.expected {- t.Errorf("got %v, want %v", got, tt.expected)- }- })- }-}--// TestPADTokenDefault verifies PAD() returns -1 when not configured-func TestPADTokenDefault(t *testing.T) {- tok, err := Load("testdata/mini_llama.json")- if err != nil {- t.Fatalf("failed to load tokenizer: %v", err)- }-- // mini_llama.json has no PAD token configured, should return -1- if got := tok.PAD(); got != -1 {- t.Errorf("PAD() = %d, want -1 (not configured)", got)- }-}--// TestPADTokenFromConfig verifies PAD token is loaded from tokenizer_config.json-func TestPADTokenFromConfig(t *testing.T) {- // Create temp directory with tokenizer files- dir := t.TempDir()-- // Write minimal tokenizer.json- tokenizerJSON := `{- "model": {- "type": "BPE",- "vocab": {"<|endoftext|>": 0, "hello": 1, "world": 2},- "merges": []- },- "added_tokens": [- {"id": 0, "content": "<|endoftext|>", "special": true}- ]- }`- if err := os.WriteFile(filepath.Join(dir, "tokenizer.json"), []byte(tokenizerJSON), 0o644); err != nil {- t.Fatalf("failed to write tokenizer.json: %v", err)- }-- // Write tokenizer_config.json with pad_token- configJSON := `{- "pad_token": "<|endoftext|>"- }`- if err := os.WriteFile(filepath.Join(dir, "tokenizer_config.json"), []byte(configJSON), 0o644); err != nil {- t.Fatalf("failed to write tokenizer_config.json: %v", err)- }-- tok, err := Load(dir)- if err != nil {- t.Fatalf("failed to load tokenizer: %v", err)- }-- if got := tok.PAD(); got != 0 {- t.Errorf("PAD() = %d, want 0 (<|endoftext|>)", got)- }-}--// TestPADTokenFromSpecialTokensMap verifies PAD falls back to special_tokens_map.json-func TestPADTokenFromSpecialTokensMap(t *testing.T) {- dir := t.TempDir()-- // Write minimal tokenizer.json- tokenizerJSON := `{- "model": {- "type": "BPE",- "vocab": {"<pad>": 0, "hello": 1, "world": 2},- "merges": []- },- "added_tokens": [- {"id": 0, "content": "<pad>", "special": true}- ]- }`- if err := os.WriteFile(filepath.Join(dir, "tokenizer.json"), []byte(tokenizerJSON), 0o644); err != nil {- t.Fatalf("failed to write tokenizer.json: %v", err)- }-- // Write special_tokens_map.json with pad_token- mapJSON := `{- "pad_token": "<pad>"- }`- if err := os.WriteFile(filepath.Join(dir, "special_tokens_map.json"), []byte(mapJSON), 0o644); err != nil {- t.Fatalf("failed to write special_tokens_map.json: %v", err)- }-- tok, err := Load(dir)- if err != nil {- t.Fatalf("failed to load tokenizer: %v", err)- }-- if got := tok.PAD(); got != 0 {- t.Errorf("PAD() = %d, want 0 (<pad>)", got)- }-}--// TestPADTokenWithContentObject verifies PAD token works with {"content": "..."} format-func TestPADTokenWithContentObject(t *testing.T) {- dir := t.TempDir()-- // Write minimal tokenizer.json- tokenizerJSON := `{- "model": {- "type": "BPE",- "vocab": {"[PAD]": 0, "hello": 1},- "merges": []- },- "added_tokens": [- {"id": 0, "content": "[PAD]", "special": true}- ]- }`- if err := os.WriteFile(filepath.Join(dir, "tokenizer.json"), []byte(tokenizerJSON), 0o644); err != nil {- t.Fatalf("failed to write tokenizer.json: %v", err)- }-- // Write tokenizer_config.json with pad_token as object (HuggingFace format)- configJSON := `{- "pad_token": {"content": "[PAD]", "lstrip": false, "normalized": false}- }`- if err := os.WriteFile(filepath.Join(dir, "tokenizer_config.json"), []byte(configJSON), 0o644); err != nil {- t.Fatalf("failed to write tokenizer_config.json: %v", err)- }-- tok, err := Load(dir)- if err != nil {- t.Fatalf("failed to load tokenizer: %v", err)- }-- if got := tok.PAD(); got != 0 {- t.Errorf("PAD() = %d, want 0 ([PAD])", got)- }-}--// Benchmarks--func BenchmarkEncode(b *testing.B) {- tok, err := Load("testdata/mini_llama.json")- if err != nil {- b.Fatalf("failed to load tokenizer: %v", err)- }-- inputs := []struct {- name string- text string- }{- {"short", "Hello, world!"},- {"medium", "The quick brown fox jumps over the lazy dog. " + strings.Repeat("This is a test. ", 10)},- {"long", strings.Repeat("The quick brown fox jumps over the lazy dog. ", 100)},- }-- for _, input := range inputs {- b.Run(input.name, func(b *testing.B) {- b.SetBytes(int64(len(input.text)))- for range b.N {- tok.Encode(input.text, false)- }- })- }-}--func BenchmarkDecode(b *testing.B) {- tok, err := Load("testdata/mini_llama.json")- if err != nil {- b.Fatalf("failed to load tokenizer: %v", err)- }-- text := strings.Repeat("The quick brown fox jumps over the lazy dog. ", 100)- tokens := tok.Encode(text, false)-- b.SetBytes(int64(len(text)))- b.ResetTimer()-- for range b.N {- tok.Decode(tokens)- }-}diff --git a/x/imagegen/types.go b/x/imagegen/types.godeleted file mode 100644index 7c837a021..000000000--- a/x/imagegen/types.go+++ /dev/null@@ -1,81 +0,0 @@-// Package imagegen provides a unified MLX runner for both LLM and image generation models.-//-// This package handles safetensors models created with `ollama create --experimental`,-// supporting both text generation (LLM) and image generation (diffusion) models-// through a single unified interface.-package imagegen--// Request is the request format for completion requests.-type Request struct {- Prompt string `json:"prompt"`-- // LLM-specific fields- Options *RequestOptions `json:"options,omitempty"`-- // Image generation fields- Width int32 `json:"width,omitempty"`- Height int32 `json:"height,omitempty"`- Steps int `json:"steps,omitempty"`- Seed int64 `json:"seed,omitempty"`- Images [][]byte `json:"images,omitempty"` // Input images for image editing/conditioning-}--// RequestOptions contains LLM-specific generation options.-type RequestOptions struct {- NumPredict int `json:"num_predict,omitempty"`- Temperature float64 `json:"temperature,omitempty"`- TopP float64 `json:"top_p,omitempty"`- TopK int `json:"top_k,omitempty"`- Stop []string `json:"stop,omitempty"`-}--// Response is streamed back for each progress update.-type Response struct {- // Text generation response- Content string `json:"content,omitempty"`-- // Image generation response- Image string `json:"image,omitempty"` // Base64-encoded PNG-- // Common fields- Done bool `json:"done"`- DoneReason int `json:"done_reason,omitempty"`- StopReason string `json:"stop_reason,omitempty"` // Debug: why generation stopped-- // Progress fields- Step int `json:"step,omitempty"`- Total int `json:"total,omitempty"`-- // Statistics- PromptEvalCount int `json:"prompt_eval_count,omitempty"`- PromptEvalDuration int `json:"prompt_eval_duration,omitempty"`- EvalCount int `json:"eval_count,omitempty"`- EvalDuration int `json:"eval_duration,omitempty"`-}--// HealthResponse is returned by the health endpoint.-type HealthResponse struct {- Status string `json:"status"`- Progress float32 `json:"progress,omitempty"`-}--// ModelMode represents the type of model being run.-type ModelMode int--const (- // ModeLLM indicates a text generation model.- ModeLLM ModelMode = iota- // ModeImageGen indicates an image generation model.- ModeImageGen-)--func (m ModelMode) String() string {- switch m {- case ModeLLM:- return "llm"- case ModeImageGen:- return "imagegen"- default:- return "unknown"- }-}diff --git a/x/imagegen/vae/tiling.go b/x/imagegen/vae/tiling.godeleted file mode 100644index d63aefa5a..000000000--- a/x/imagegen/vae/tiling.go+++ /dev/null@@ -1,213 +0,0 @@-// Package vae provides shared utilities for VAE (Variational Autoencoder) operations.-package vae--import (- "github.com/ollama/ollama/x/imagegen/mlx"-)--// TilingConfig holds configuration for tiled VAE decoding.-// This is a general technique to reduce memory usage when decoding large latents.-type TilingConfig struct {- TileSize int32 // Tile size in latent space (e.g., 64 latent → 512 pixels for 8x VAE)- Overlap int32 // Overlap in latent space (e.g., 16 latent = 25% of 64)-}--// DefaultTilingConfig returns reasonable defaults matching diffusers.-// tile_latent_min_size=64, tile_overlap_factor=0.25-func DefaultTilingConfig() *TilingConfig {- return &TilingConfig{- TileSize: 64, // 64 latent pixels- Overlap: 16, // 25% overlap- }-}--// decodedTile holds a decoded tile's pixel data and dimensions-type decodedTile struct {- data []float32- height int32- width int32-}--// DecodeTiled decodes latents using tiled processing with overlap blending.-// This reduces memory usage for large images by processing in overlapping tiles.-//-// Parameters:-// - latents: [1, H, W, C] latent tensor in NHWC format-// - cfg: tiling configuration (tile size and overlap)-// - decoder: function to decode a single tile [1, H, W, C] -> [1, H*scale, W*scale, 3]-//-// Returns: [1, 3, H*scale, W*scale] decoded image in NCHW format-func DecodeTiled(latents *mlx.Array, cfg *TilingConfig, decoder func(*mlx.Array) *mlx.Array) *mlx.Array {- shape := latents.Shape()- H := shape[1] // latent height- W := shape[2] // latent width- C := shape[3]-- tileLatentSize := cfg.TileSize- overlapLatent := cfg.Overlap-- // If image is small enough, just decode normally- if H <= tileLatentSize && W <= tileLatentSize {- decoded := decoder(latents)- decoded = mlx.AsType(decoded, mlx.DtypeFloat32)- decoded = mlx.ClipScalar(decoded, 0.0, 1.0, true, true)- decoded = mlx.Transpose(decoded, 0, 3, 1, 2) // NHWC -> NCHW- return decoded- }-- // Calculate tiling parameters (matching diffusers)- overlapSize := tileLatentSize - overlapLatent // stride in latent space-- // Blend extent in pixel space (assumes 8x upscale, adjust if needed)- // For other scale factors, this could be made configurable- tileSampleSize := tileLatentSize * 8 // tile size in pixels after 8x upscale- blendExtent := overlapLatent * 8 // blend region in pixels- rowLimit := tileSampleSize - blendExtent // non-overlapping region per tile-- // Phase 1: Decode all tiles and store in 2D grid- var rows [][]decodedTile-- for i := int32(0); i < H; i += overlapSize {- var row []decodedTile- for j := int32(0); j < W; j += overlapSize {- // Extract tile (may be smaller at edges)- i2 := min(i+tileLatentSize, H)- j2 := min(j+tileLatentSize, W)-- tile := mlx.Slice(latents, []int32{0, i, j, 0}, []int32{1, i2, j2, C})- decoded := decoder(tile)- decoded = mlx.AsType(decoded, mlx.DtypeFloat32)- mlx.Eval(decoded)-- decodedShape := decoded.Shape()- tileH := decodedShape[1]- tileW := decodedShape[2]- tileData := decoded.Data()- decoded.Free()-- row = append(row, decodedTile{data: tileData, height: tileH, width: tileW})- }- rows = append(rows, row)- }-- // Phase 2: Blend adjacent tiles (modifies in place)- for i := range rows {- for j := range rows[i] {- tile := &rows[i][j]-- // Blend with tile above- if i > 0 {- above := &rows[i-1][j]- blendV(above, tile, blendExtent)- }-- // Blend with tile to the left- if j > 0 {- left := &rows[i][j-1]- blendH(left, tile, blendExtent)- }- }- }-- // Phase 3: Calculate crop dimensions for each tile- colWidths := make([]int32, len(rows[0]))- for j := range rows[0] {- keepW := rowLimit- if int32(j+1)*overlapSize >= W {- keepW = rows[0][j].width- }- colWidths[j] = keepW- }-- rowHeights := make([]int32, len(rows))- for i := range rows {- keepH := rowLimit- if int32(i+1)*overlapSize >= H {- keepH = rows[i][0].height- }- rowHeights[i] = keepH- }-- // Calculate total dimensions- var totalW, totalH int32- for _, w := range colWidths {- totalW += w- }- for _, h := range rowHeights {- totalH += h- }-- // Phase 4: Assemble final image by interleaving tiles row-by-row- finalData := make([]float32, totalH*totalW*3)-- dstY := int32(0)- for i, row := range rows {- keepH := rowHeights[i]-- for y := range keepH {- dstX := int32(0)- for j, tile := range row {- keepW := colWidths[j]-- for x := range keepW {- for c := range int32(3) {- srcIdx := (y*tile.width+x)*3 + c- dstIdx := ((dstY+y)*totalW+(dstX+x))*3 + c- finalData[dstIdx] = tile.data[srcIdx]- }- }- dstX += keepW- }- }- dstY += keepH- }-- // Create mlx array [1, H, W, 3] then transpose to NCHW [1, 3, H, W]- result := mlx.NewArray(finalData, []int32{1, totalH, totalW, 3})- result = mlx.Transpose(result, 0, 3, 1, 2)- result = mlx.ClipScalar(result, 0.0, 1.0, true, true)-- return result-}--// blendV blends the bottom of 'above' tile into top of 'current' tile (vertical blend)-// Matches diffusers blend_v formula-func blendV(above, current *decodedTile, blendExtent int32) {- blend := min(blendExtent, min(above.height, current.height))- if blend <= 0 {- return- }-- w := min(above.width, current.width)- for y := range blend {- alpha := float32(y) / float32(blend)- for x := range w {- for c := range int32(3) {- aboveIdx := ((above.height-blend+y)*above.width+x)*3 + c- currIdx := (y*current.width+x)*3 + c- current.data[currIdx] = above.data[aboveIdx]*(1-alpha) + current.data[currIdx]*alpha- }- }- }-}--// blendH blends the right of 'left' tile into left of 'current' tile (horizontal blend)-// Matches diffusers blend_h formula-func blendH(left, current *decodedTile, blendExtent int32) {- blend := min(blendExtent, min(left.width, current.width))- if blend <= 0 {- return- }-- h := min(left.height, current.height)- for y := range h {- for x := range blend {- alpha := float32(x) / float32(blend)- for c := range int32(3) {- leftIdx := (y*left.width+(left.width-blend+x))*3 + c- currIdx := (y*current.width+x)*3 + c- current.data[currIdx] = left.data[leftIdx]*(1-alpha) + current.data[currIdx]*alpha- }- }- }-}diff --git a/x/mlxrunner/client.go b/x/mlxrunner/client.goindex 31d02f699..07fd49092 100644--- a/x/mlxrunner/client.go+++ b/x/mlxrunner/client.go@@ -26,7 +26,6 @@ import ("github.com/ollama/ollama/format""github.com/ollama/ollama/llm""github.com/ollama/ollama/ml"- "github.com/ollama/ollama/x/imagegen""github.com/ollama/ollama/x/imagegen/manifest")@@ -48,7 +47,7 @@ type Client struct {// NewClient prepares a new MLX runner client for LLM models.// The subprocess is not started until Load() is called.func NewClient(modelName string, softContextLength int) (*Client, error) {- if err := imagegen.CheckPlatformSupport(); err != nil {+ if err := checkPlatformSupport(); err != nil {return nil, err}@@ -68,6 +67,20 @@ func NewClient(modelName string, softContextLength int) (*Client, error) {return c, nil}+func checkPlatformSupport() error {+ switch runtime.GOOS {+ case "darwin":+ if runtime.GOARCH != "arm64" {+ return fmt.Errorf("MLX on macOS requires Apple Silicon (arm64), got %s", runtime.GOARCH)+ }+ return nil+ case "linux", "windows":+ return nil+ default:+ return fmt.Errorf("MLX is not supported on %s", runtime.GOOS)+ }+}+// WaitUntilRunning waits for the subprocess to be ready.func (c *Client) WaitUntilRunning(ctx context.Context) error {timeout := time.After(envconfig.LoadTimeout())diff --git a/x/mlxrunner/mlx/CMakeLists.txt b/x/mlxrunner/mlx/CMakeLists.txtindex 3db230012..4cb266321 100644--- a/x/mlxrunner/mlx/CMakeLists.txt+++ b/x/mlxrunner/mlx/CMakeLists.txt@@ -15,8 +15,8 @@ set(CMAKE_INSTALL_RPATH "@loader_path")include(FetchContent)-# Read MLX-C version from top-level file (shared with imagegen CMakeLists)-file(READ "${CMAKE_SOURCE_DIR}/MLX_C_VERSION" MLX_C_GIT_TAG)+# Read MLX-C version from top-level file.+file(READ "${CMAKE_CURRENT_LIST_DIR}/../../../MLX_C_VERSION" MLX_C_GIT_TAG)string(STRIP "${MLX_C_GIT_TAG}" MLX_C_GIT_TAG)FetchContent_Declare(diff --git a/x/mlxrunner/mlx/ops_extra.go b/x/mlxrunner/mlx/ops_extra.goindex 9d2dfc069..8ac7a5c79 100644--- a/x/mlxrunner/mlx/ops_extra.go+++ b/x/mlxrunner/mlx/ops_extra.go@@ -326,7 +326,7 @@ func TakeAlongAxis(a, indices *Array, axis int) *Array {return a.TakeAlongAxis(indices, axis)}-// Function-style wrappers matching imagegen API+// Function-style wrappers for model code.func Add(a, b *Array) *Array {return a.Add(b)diff --git a/x/imagegen/tokenizer/testdata/mini_llama.json b/x/tokenizer/testdata/mini_llama.jsonsimilarity index 100%rename from x/imagegen/tokenizer/testdata/mini_llama.jsonrename to x/tokenizer/testdata/mini_llama.jsondiff --git a/x/tokenizer/tokenizer_benchmark_test.go b/x/tokenizer/tokenizer_benchmark_test.goindex 7d2849bf4..dc9ccf579 100644--- a/x/tokenizer/tokenizer_benchmark_test.go+++ b/x/tokenizer/tokenizer_benchmark_test.go@@ -66,7 +66,7 @@ func benchmarkMiniLlamaPath(tb testing.TB) string {tb.Fatal("failed to resolve benchmark file path")}- return filepath.Join(filepath.Dir(filename), "..", "imagegen", "tokenizer", "testdata", "mini_llama.json")+ return filepath.Join(filepath.Dir(filename), "testdata", "mini_llama.json")}func benchmarkLoadMiniLlama(tb testing.TB) *Tokenizer {