Skip to content

feat: Apple Silicon MLX/MPS, GGUF and Ollama backends - #4

Merged
rkinas merged 15 commits into
rkinas:mainfrom
pawelkiszczak:main
Sep 30, 2026
Merged

rkinas merged 15 commits into
rkinas:mainfrom
pawelkiszczak:main

Conversation

@pawelkiszczak

@pawelkiszczak pawelkiszczak commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Purpose

Enable basal typed-decision inference and benchmarking on Apple Silicon while retaining the existing CUDA paths. This pulls the fork changes from Apple PR #1 and GGUF/Ollama PR #2 into upstream main for review.

Changes

  • Add mlx with shared-prefix, batched two-order inference and explicit per-token RoPE positions; mlx-q8 quantizes decoder weights at load time. Add mps with packed shared-prefix inference but no CUDA graphs. On Apple Silicon, serving defaults to MLX when installed, otherwise MPS. PyTorch eager selects MPS where available.
  • Make basal-bench select a device-appropriate reference and report MPS/MLX timings and memory without CUDA-only APIs on a Mac.
  • Add gguf via llama-cpp-python (Metal/CUDA/CPU), using the original Hugging Face tokenizer/template/calibration and a shared llama.cpp prefix. Add ollama using an import of the original safetensors and next-token option-letter logprobs; missing letters fail rather than silently becoming zero.
  • Document setup and limitations, GGUF conversion, measured Apple engine comparisons, and quantized-format tradeoffs. Include per-item data and eight generated figures.

Review fixes

  • Synchronize PyTorch MPS work on the measured backend before stopping each benchmark timer. Choose CUDA/MPS memory reporting by that backend's device, not global GPU availability; CPU and untracked backends report unavailable memory. A regression test covers MPS timing and explicit CPU mode on an MPS host.
  • The Apple default comparison deliberately starts with bf16 mps to fit a 4.5B model on 16 GB Macs; agree is not fp32 agreement in that case. The CLI help and README say this explicitly, and each JSON result now includes reference_mode. For fp32 agreement on a machine with sufficient memory, use --modes eager-fp32 mps mlx.
  • [test] no longer installs llama-cpp-python or gguf on every platform. [gguf] stays opt-in; docs show how to install the GGUF-specific test requirements.

Local verification (Apple M4 Max)

  • pytest -q tests: 29 passed, including the MPS/device regression. Reviewer-focused subset: 26 passed. uv lock --check passed and the lock's [test] group excludes GGUF native dependencies.
  • Real basal-bench run with 1.5B, eight choice items, --modes mps mlx: MPS two-order median 99.4 ms, MLX 77.6 ms; both emitted reference_mode: "mps", and MLX's top-choice agreement with MPS was 1.000. This is a smoke check, not a model-quality estimate.
  • Earlier HTTP smoke: MLX on 1.5B, GGUF Q8_0 on 1.5B and Ollama on 1.5B returned decisions; the GGUF and Ollama eight-item runs had zero errors. The packaged Ollama backend completed 44-item comparisons for both sizes.
  • Ollama original-safetensors import, 44 bundled decisions, two option orders: 4.5B median 276.2 ms, 3.33 decisions/s, 44/44 top-choice agreement with fp32; 1.5B median 103.8 ms, 9.04 decisions/s, 43/44 agreement. This small sample is a functional comparison, not a statistical quality claim.

Review considerations

  • Upstream PR #1 independently adds MPS support. This PR overlaps that implementation and additionally includes MLX, GGUF, Ollama and the Apple comparisons; maintainers should choose an integration path rather than merge both MPS implementations unexamined. Upstream PR #2 includes a visualizer based on PR Run on Apple Silicon (MPS) #1 and may need rebasing if this PR is chosen.
  • The six converted model repositories linked by the README/docs are private until their owner releases them. Docs explicitly mark that limitation; those links cannot be used by other readers yet. The original Remek/* checkpoints are separate, and their model cards were not changed here.
  • CUDA serving and quantized CUDA paths were not rerun on an NVIDIA GPU; no CI/CD changes are included.

pawelkiszczak and others added 14 commits September 29, 2026 22:16
Default `fast` mode and basal-bench required CUDA, so nothing ran on
a Mac. New modes reuse the shared-prefix packing of the CUDA path:

- mlx (default on Apple Silicon), mlx-q8 (8-bit weights, ~half memory)
- mps (PyTorch MPS, fallback without MLX); eager picks MPS
- explicit RoPE positions: mlx-lm's offset RoPE cannot express option
  blocks, and its Llama ignores transformers-5 rope_parameters
- basal-bench: device-agnostic sync/memory, platform default modes
- `[mlx]` extra; README install section; HARDWARE.md M4 Max numbers
--mode gguf runs converted checkpoints through llama-cpp-python
(Metal / CUDA / CPU). Tokenizer, template and calibration stay on the
HF model dir: the GGUF vocabulary splits basal prompts differently
(all 88 bundled prompts), which shifts probabilities in text-only
front ends (LM Studio, Ollama GGUF import). Both option orders share
their prefix as llama.cpp sequences in one llama_decode.

- F16 GGUF: closest to fp32 of all reduced-precision paths (TV 0.0006)
  at mlx speed on M4 Max; Q8_0 halves memory; Q4_K_M not recommended
- basal-bench: gguf / gguf@<file> modes
- docs/GGUF.md: conversion recipe (transformers 5 needed), results
- HARDWARE.md: 14 engines compared on M4 Max (mlx-lm, mlx_lm.server,
  llama.cpp, vllm-metal, MTPLX, Ollama, LM Studio; oMLX, vllm-mlx
  unusable); mlx-lm-based engines need rope_theta in config.json
- latency/throughput bars, speed-vs-fidelity scatter, memory-vs-fidelity
  for MLX and GGUF variants, per-item TV heatmap (engines x items)
- heatmap adds unpatched rope_theta and text-tokenized llama-server
  rows, making both failure modes visible item by item
- docs/figures/make_figures.py regenerates from apple_engines.json
- apple_quality.png: accuracy vs gold with 95% Wilson intervals,
  log-loss of the gold option, decisions changed vs fp32, per engine
- apple_gold_prob_heatmap.png: P(gold) per item and engine
- 44 gold-labelled items cannot rank engines (all within ±12 points;
  rope-broken engines even score higher), so backend quality is
  documented as faithfulness to fp32

VLLMBackend passes logprob_token_ids where vLLM supports it:
vllm-metal ignores logprobs_mode="processed_logprobs" and returns the
unrestricted top-k, which dropped the least likely option (p = 0) on
14/44 items of the 1.5B.
17 formats of the 1.5B and 9 of the 4.5B (mlx_lm.convert affine
8/6/4-bit, mixed_4_6, mxfp8, mxfp4, nvfp4; oMLX oQ8/6/6e/4/4e/3e; GGUF)
through basal's mlx / gguf modes, plus LM Studio's MLX runner:

- all formats run at bf16 speed (compute-bound); quantisation only
  saves memory
- 8-bit: GGUF Q8_0 at bf16 level, MLX 8-bit ~2x the deviation
  (embeddings and LM head quantised too); oQ8 == MLX affine 8-bit
- 4-bit changes 1-9/44 decisions in every format; oQ4e and Q4_K_M
  best, mxfp4 worst
- LM Studio MLX runner: format's fidelity at ~2x latency; logprobs only
  on chat with max_tokens >= 2; duplicate letter strings -> match bytes
feat: GGUF backend (llama.cpp) + Apple Silicon engine comparison
@sourcery-ai

sourcery-ai Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR adds Apple Silicon MLX/MPS inference, llama.cpp GGUF, and Ollama safetensors backends while retaining CUDA behavior, then integrates platform-aware serving and benchmarking, documents conversion and fidelity tradeoffs, and adds backend-specific correctness tests and Apple comparison artifacts.

Sequence diagram for shared-prefix typed decision inference

sequenceDiagram
    participant Request as Request
    participant Backend as MLX MPS or GGUF backend
    participant Pack as Shared-prefix packer
    participant Runtime as MLX MPS or llama.cpp runtime
    participant Readout as Letter probability readout
    Request->>Backend: run_shared(groups)
    Backend->>Pack: _pack(prompts)
    Pack-->>Backend: prefix and option-order token blocks
    Backend->>Runtime: Execute packed batch with shared prefix
    Runtime-->>Backend: Hidden states or logits
    Backend->>Readout: Convert option-letter logits to probabilities
    Readout-->>Request: Typed decision probabilities
Loading

Sequence diagram for Ollama safetensors logprob inference

sequenceDiagram
    participant Backend as OllamaBackend
    participant Ollama as Ollama API
    participant Model as Original safetensors import
    Backend->>Ollama: POST /api/show
    Ollama-->>Backend: Model metadata
    Backend->>Backend: Validate architecture and vocabulary
    Backend->>Ollama: POST /api/generate with raw prompt and top_logprobs
    Ollama->>Model: Generate one next token
    Model-->>Ollama: Top-20 token logprobs
    Ollama-->>Backend: Letter logprobs
    alt Every option letter is present
        Backend-->>Backend: Normalize letter probabilities
    else Letter is missing
        Backend-->>Backend: Raise error
    end
Loading

Flow diagram for platform-aware default mode selection

flowchart TD
    Start[Start server or benchmark] --> CUDA{CUDA available?}
    CUDA -->|Yes| Fast[Use fast CUDA mode]
    CUDA -->|No| MPS{MPS available?}
    MPS -->|No| Eager[Use eager CPU mode]
    MPS -->|Yes| MLX{MLX and mlx-lm installed?}
    MLX -->|Yes| MLXMode[Use MLX mode]
    MLX -->|No| MPSMode[Use MPS mode]
Loading

File-Level Changes

Change Details Files
Add Apple Silicon inference backends with shared-prefix, batched typed-decision execution.
  • Add MLX bf16 and load-time decoder-only q8 paths with explicit RoPE positions and segment masks.
  • Add PyTorch MPS execution using the existing packed shared-prefix flow without CUDA graphs.
  • Select MLX, MPS, CUDA, or CPU defaults based on available hardware and installed packages.
  • Extend backend validation and quantization handling for the new modes.
basal/engine.py
basal/server.py
pyproject.toml
uv.lock
Add llama.cpp GGUF inference while preserving the original tokenizer and calibration behavior.
  • Load GGUF weights through llama-cpp-python with Metal, CUDA, or CPU support and validate architecture/vocabulary compatibility.
  • Pass Hugging Face token IDs and use llama.cpp sequences to share prefixes across option orders and batched questions.
  • Expose GGUF server and benchmark configuration, including per-file benchmark modes.
basal/engine.py
basal/server.py
basal/bench.py
docs/GGUF.md
pyproject.toml
uv.lock
Add an Ollama backend for original safetensors imports and exact option-letter logprob scoring.
  • Call Ollama's raw generation API for next-token top-logprobs and normalize only the requested option letters.
  • Validate that the Ollama model is a safetensors import matching the source model architecture and vocabulary.
  • Fail explicitly when an option letter is absent from the truncated logprob list.
basal/ollama.py
basal/server.py
basal/bench.py
docs/HARDWARE.md
README.md
Make benchmarking portable across CUDA, MPS, MLX, GGUF, and Ollama.
  • Choose device-appropriate reference and serving modes automatically.
  • Replace CUDA-only synchronization, cache, device-name, and memory calls with backend-aware handling.
  • Report MLX/MPS memory and timing metrics while leaving llama.cpp memory unmeasured.
basal/bench.py
basal/server.py
tests/test_server.py
Document Apple installation, backend limitations, conversion workflows, and measured comparisons.
  • Document private converted checkpoints, GGUF conversion and serving, Ollama safetensors setup, and backend-specific quantization limitations.
  • Add hardware, fidelity, latency, throughput, quality, and format-comparison data with generated visualizations.
  • Record tokenizer and RoPE compatibility caveats for external llama.cpp, MLX, vLLM, and Ollama front ends.
README.md
docs/HARDWARE.md
docs/GGUF.md
docs/figures/apple_engines.json
docs/figures/make_figures.py
docs/figures/apple_memory_vs_fidelity.png
docs/figures/apple_latency_throughput.png
docs/figures/apple_speed_vs_fidelity.png
docs/figures/apple_fidelity_heatmap.png
docs/figures/apple_quality.png
docs/figures/apple_gold_prob_heatmap.png
docs/figures/apple_formats_size_vs_fidelity.png
docs/figures/apple_formats_heatmap.png
Add focused coverage for backend correctness and platform-default behavior.
  • Verify packed GGUF sequences match separate orders and isolate batched questions.
  • Compare MLX packed outputs with PyTorch outputs on a tiny biased Llama checkpoint.
  • Test Ollama probability extraction and missing-letter failures.
  • Test default mode selection and rejection of unsupported quantization overrides.
tests/test_gguf.py
tests/test_mlx.py
tests/test_ollama.py
tests/test_server.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="basal/bench.py" line_range="106-107" />
<code_context>
+    return float("nan")
+
+
+def sync():
+    if torch.cuda.is_available():
+        torch.cuda.synchronize()
+
</code_context>
<issue_to_address>
**issue (testing):** `sync()` does nothing for MPS, so `timed()` records latency before asynchronous MPS kernels finish and samples memory before the workload has necessarily completed. MPS benchmark timings and peak-memory results are therefore understated or inconsistent.

**Triggers:** When benchmarking `mps` or another PyTorch backend on Apple Silicon.

**Suggested fix:** Call `torch.mps.synchronize()` when MPS is available and the backend uses MPS.
</issue_to_address>

### Comment 2
<location path="basal/bench.py" line_range="59-66" />
<code_context>
     return GraphBackend(md, "bfloat16", quant, compile=comp, shared=True)


+def default_modes():
+    """Choose a reference that fits the selected device, then the serving default."""
+    mode = default_mode()
+    if torch.cuda.is_available():
+        return ["eager-fp32", mode]
+    if torch.backends.mps.is_available():
+        return [mode] if mode == "mps" else ["mps", mode]
</code_context>
<issue_to_address>
**issue (bug_risk):** On an MPS machine with MLX installed, the first benchmark mode is `mps`, so `measure()` uses bfloat16 MPS as the reference and reports MLX agreement against MPS rather than against the documented fp32 reference. The reported `agree` value and any conclusions based on it do not measure fidelity to eager fp32.

**Triggers:** When `basal-bench` is run without an explicit `--modes` on Apple Silicon where MLX is available.

**Suggested fix:** Benchmark `eager-fp32` first when it fits, or rename and document the first mode as the MPS reference instead of reporting it as fp32 agreement.
</issue_to_address>

### Comment 3
<location path="pyproject.toml" line_range="31-36" />
<code_context>
+  "mlx-lm>=0.31; sys_platform == 'darwin' and platform_machine == 'arm64'",
+]
+gguf = ["llama-cpp-python>=0.3.35"]
+test = [
+  "pytest", "jsonschema", "gguf", "llama-cpp-python>=0.3.35",
+  "mlx>=0.32; sys_platform == 'darwin' and platform_machine == 'arm64'",
+  "mlx-lm>=0.31; sys_platform == 'darwin' and platform_machine == 'arm64'",
+]

 [project.scripts]
</code_context>
<issue_to_address>
**issue (bug_risk):** The `test` extra now unconditionally installs `llama-cpp-python` and `gguf` on every platform, even though the tests use `importorskip` for these optional backends. Environments without a compatible llama-cpp-python wheel or native build toolchain fail while installing the test dependencies before pytest can skip the tests.

**Triggers:** When CI or developers install the `test` extra on platforms without a supported llama-cpp-python wheel or compiler dependencies.

**Suggested fix:** Keep GGUF dependencies in a separate optional extra, or add platform-specific markers and install the backend test dependencies only in the jobs that exercise GGUF.

```suggestion
gguf = ["gguf", "llama-cpp-python>=0.3.35"]
test = [
  "pytest", "jsonschema",
  "mlx>=0.32; sys_platform == 'darwin' and platform_machine == 'arm64'",
  "mlx-lm>=0.31; sys_platform == 'darwin' and platform_machine == 'arm64'",
]
```
</issue_to_address>

### Comment 4
<location path="basal/bench.py" line_range="92-102" />
<code_context>
+        pass
+
+
+def memory_gb(be):
+    """Peak allocated memory (CUDA, MLX); for MPS the memory held by the Metal driver at the end of the run; not
+    measured for llama.cpp (GGUF), whose buffers torch and MLX do not see."""
+    if isinstance(be, GGUFBackend):
+        return float("nan")
+    if isinstance(be, MLXBackend):
+        return be.mx.get_peak_memory() / 2**30
+    if torch.cuda.is_available():
+        return torch.cuda.max_memory_allocated() / 2**30
+    if torch.backends.mps.is_available():
+        return torch.mps.driver_allocated_memory() / 2**30
+    return float("nan")
+
</code_context>
<issue_to_address>
**nitpick (bug_risk):** `memory_gb()` chooses MPS memory reporting from global availability rather than from the backend's actual device. An explicitly requested CPU or CUDA-ineligible backend on a Mac is reported with `torch.mps.driver_allocated_memory()`, which measures unrelated MPS allocations instead of that benchmark's memory.

**Triggers:** When a user explicitly benchmarks a CPU/eager mode on a machine where MPS is available.

**Suggested fix:** Select memory reporting from `be.dev` or the backend type, and return an unavailable value for CPU rather than using global MPS availability.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread basal/bench.py Resolved
Comment thread basal/bench.py Resolved
Comment thread pyproject.toml Resolved
Comment thread basal/bench.py Resolved
@rkinas
rkinas merged commit 3fa2eea into rkinas:main Sep 30, 2026
1 check passed
rkinas added a commit that referenced this pull request Oct 4, 2026
Merge origin/main (PR #4 by Paweł Kiszczak: MPS, GGUF, MLX q8, device-independent
benchmark) into the 1.5.0 release. The 1.5 engine is the base; from #4:

- mps mode: MPSBackend now runs the 1.5 prefix-trie packing (SOAM) as plain forwards
  on the Mac's GPU; evidence spans work (PyTorch model)
- gguf mode: GGUFBackend in process (llama-cpp-python); the trie becomes llama.cpp
  sequences (each token in the sequences of all readouts below it), chunks limited
  to N_CTX tokens and N_SEQ readouts; config.json optional, so a -GGUF folder works
  as --model; downloaded without weights
- mlx-q8: 8-bit weights at load time in the 1.5 MLXBackend (lazy load, decoder only)
- default mode per platform (fast / mlx / mps / eager), --quant validated before
  loading, vLLM logprob_token_ids where supported
- basal-bench: device-independent sync, memory and reference (mps on Apple Silicon)
- the 1.5 OllamaBackend (GGUF ports) replaces #4's safetensors-import variant
- docs: GGUF.md for 1.5, the M4 Max engine study in HARDWARE.md (basal-1.0), README
  modes and credits; figures kept, the memory figure's title updated
- tests: MLX, Ollama and llama.cpp port tests of 1.5, GGUF tests with nested
  prefixes and readout limits, PR #4's server and bench tests

Checked on an Apple M4 Pro with basal-1.5-mini: mps, mlx, mlx-q8 and gguf Q8_0 agree
1.000 with bf16 eager on the 44 bundled examples; whole requests (up to 14
questions) give 28/28 identical top answers with SOAM.
rkinas added a commit that referenced this pull request Oct 19, 2026
One line per external contributor whose commits are in main or in 2.2, with what they added and the PR: Paweł Kiszczak (#4), Piotr Durlej (#8), Kuba Sołtys (#15), Michał Kardyś (#14); names from their GitHub profiles and commit authors. README and WHATS_NEW 2.2 list basal-export-gguf, --mode tpu and --mode strix; NOTICE names the contributors.
rkinas added a commit that referenced this pull request Oct 19, 2026
@lukaspoloki)

Conflicts: the MPS commit of the branch (c531ba3) is not taken, since main has MPS from #4: README.md, basal/engine.py, basal/server.py, basal/bench.py and tests/test_engine.py stay as on 2.2. Kept: basal/viz.py, basal/viz.html, the basal-viz script, viz.html as package data and the segments test. The port to the 2.2 engine follows.
rkinas added a commit that referenced this pull request Oct 19, 2026
… option orders, calibration and answer

Port of #2 to the current engine without its MPS backend (main has MPS since #4): the page runs a basal-serve Server in process (--mode mps on Apple Silicon, eager elsewhere) and reads its PyTorch model for the per-layer readout. Prompts, option codes (up to 255, format 2 from basal.json) and option orders (one by default for format-2 models; --orders 1|2) come from Server.jobs_for; temperatures per type and option-count bucket and the per-type certified thresholds from the calibration file basal-serve loads; multi questions are explained per label, act and tool by their base type. The code logits are read in fp32 as the engines read them. Each request is also answered by Server.decide and the page shows the difference. The page handles one or two orders and types without a certified threshold; question types the form does not edit (act, tool, tasks) are sent as JSON. Llama-architecture models only (refused otherwise). Docs: SERVING.md, "See how a decision is made". Checked with basal-2.0-mini on MPS and CPU, bundled examples and a multi / act / 30-option request: equal to the served answer for single questions (0 on MPS), within 0.006 for requests with several questions (one packed row over the state, bf16).
agentGreg added a commit to agentGreg/basal that referenced this pull request Oct 20, 2026
rkinas#4), how -MLX-8bit agreement was measured, 4.0x upper bound, M4 Max note

Addresses the review comments on rkinas#18.
rkinas added a commit that referenced this pull request Oct 21, 2026
…, and its cause (#18)

basal-1.0-1.5B 126 vs 149 ms, -4.5B 388 vs 506 ms (3fa2eea against v2.2.0 / 2.3.1). Since the merge of #4
into basal 1.5 (4c11a87) the mlx backend runs the shared prefix and the option blocks as two forwards instead
of one packed forward. A packed forward for Llama models changed probabilities (max 0.045 on 8-bit weights) and
was slower beyond ~900-token prompts, so 2.3.1 keeps the backend.
@pawelkiszczak pawelkiszczak changed the title feat: Apple Silicon MLX/MPS, GGUF and Ollama backends chore: sync fork with upstream basal 2.3.1 (upstream main @ 621bc57) Oct 21, 2026
@pawelkiszczak pawelkiszczak changed the title chore: sync fork with upstream basal 2.3.1 (upstream main @ 621bc57) feat: Apple Silicon MLX/MPS, GGUF and Ollama backends Oct 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants