Repository navigation
feat: Apple Silicon MLX/MPS, GGUF and Ollama backends - #4
Merged
Merged
Conversation
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
…odels' published files
feat: Apple Silicon backends (MLX, MPS)
feat: GGUF backend (llama.cpp) + Apple Silicon engine comparison
Reviewer's GuideThis 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 inferencesequenceDiagram
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
Sequence diagram for Ollama safetensors logprob inferencesequenceDiagram
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
Flow diagram for platform-aware default mode selectionflowchart 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]
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
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>
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.
This was referenced Oct 14, 2026
Merged
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
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
mainfor review.Changes
mlxwith shared-prefix, batched two-order inference and explicit per-token RoPE positions;mlx-q8quantizes decoder weights at load time. Addmpswith 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.basal-benchselect a device-appropriate reference and report MPS/MLX timings and memory without CUDA-only APIs on a Mac.ggufvia llama-cpp-python (Metal/CUDA/CPU), using the original Hugging Face tokenizer/template/calibration and a shared llama.cpp prefix. Addollamausing an import of the original safetensors and next-token option-letter logprobs; missing letters fail rather than silently becoming zero.Review fixes
mpsto fit a 4.5B model on 16 GB Macs;agreeis not fp32 agreement in that case. The CLI help and README say this explicitly, and each JSON result now includesreference_mode. For fp32 agreement on a machine with sufficient memory, use--modes eager-fp32 mps mlx.[test]no longer installsllama-cpp-pythonorggufon 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 --checkpassed and the lock's[test]group excludes GGUF native dependencies.basal-benchrun with 1.5B, eight choice items,--modes mps mlx: MPS two-order median 99.4 ms, MLX 77.6 ms; both emittedreference_mode: "mps", and MLX's top-choice agreement with MPS was 1.000. This is a smoke check, not a model-quality estimate.Review considerations
Remek/*checkpoints are separate, and their model cards were not changed here.