Skip to content

perf(mps): run the packed engine on the CPU (--mode mps --device cpu); same answers - #26

Merged
rkinas merged 3 commits into
rkinas:mainfrom
Butterski:perf/mps-on-cpu
Oct 20, 2026
Merged

rkinas merged 3 commits into
rkinas:mainfrom
Butterski:perf/mps-on-cpu

Conversation

@Butterski

@Butterski Butterski commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Problem

On a CPU the only PyTorch path is --mode eager, which runs every prompt of a request whole: with several questions or
option orders over one state (tasks, --orders 2), the state is computed once per prompt. 2.3's shared-state eager
forward covers Gemma 4 only (EagerBackend.g4), so the Llama-based models (basal-2.0, 1.5) still pay this on CPU.

basal already has the engine that computes the state once without CUDA graphs: MPSBackend (prefix trie, SOAM,
token-budget batching, plain forwards). Nothing in its path is Apple-specific (it accepts device; host copies pin
memory only on CUDA), but the server builds it as MPSBackend(md, a.dtype, shared=shared) and it defaults to
device="mps", so on Linux / Windows --mode mps fails with "PyTorch is not linked with support for mps devices".

Change

  • server.py: pass --device to MPSBackend; refuse --mode mps --device cuda (that is --mode fast); --device
    help covers --mode mps.
  • engine.py: MPSBackend(device=None) = mps where MPS is available, else cpu (Apple Silicon behaves as before;
    basal-bench --modes mps also works on a CPU machine).
  • Docs: the mps row in SERVING.md, the engines tables (HARDWARE.md, QUANTIZATION.md, INSTALL.md), the CPU section of
    INSTALL.md, WHATS_NEW.md.

Measurements

basal-2.0-mini, --dtype float32, 6-core AMD Ryzen 5 PRO 4650GE, torch 2.11 / transformers 5.17.0.

Recorded task requests through run_shared (2.3.0 engine, same process, EagerBackend vs MPSBackend(device="cpu")):

request prompts eager mps on CPU speed-up
compress, unit sentence 41 439.1 s 43.1 s 10.2x
compress, unit paragraph 24 287.5 s 29.2 s 9.8x
verify, 10 claims 10 111.9 s 15.3 s 7.3x
total 75 838.5 s 87.6 s 9.6x

Same top answer on 75 of 75 readouts, max |Δp| 4.4e-6.

End to end over HTTP (basal-serve --mode mps --device cpu vs --mode eager --device cpu, the five
basal/examples/complex.jsonl requests plus one verify request with 4 claims over 6,000 characters of
docs/SOAM.md): 53.6 s vs 184.9 s in total (complex requests 4.2–4.7 s vs 5.1–7.8 s; the verify request 31.2 s vs
153.7 s); all 18 probability vectors with the same top answer, max |Δp| 2.7e-6. Single questions gain nothing (one
prompt, nothing to share).

Not measured: bf16 on CPU, other CPUs, Apple Silicon (unchanged code path there).

Tests

  • test_mps_backend_on_cpu_equals_separate (tests/test_engine.py): MPSBackend.run_shared on the CPU, three
    requests in one call (rows padded to the longest, a state shared by three questions in two option orders), once
    with every row under the largest length and once with one over it (the long path): every readout equals its prompt
    run alone (fp32, atol 1e-5).
  • tests/ without test_gguf.py (needs llama-cpp-python): 613 passed, 73 skipped (CUDA / MLX / TPU only).
  • basal-serve --mode mps --device cuda exits with "--mode mps runs on Apple Silicon or the CPU (--device mps / cpu);
    on CUDA: --mode fast".

Open for you: whether mps should become the default on CPU instead of eager (default_mode()), and whether the
name should change (mps for a CPU mode reads oddly; a packed alias would be a small follow-up).

Summary by Sourcery

Run the packed no-graphs engine on CPUs to accelerate multi-prompt requests while preserving answer parity with eager execution.

New Features:

  • Enable the packed mps engine to run on CPUs, computing shared request state once across multiple prompts and option orders.
  • Expose --device selection for --mode mps while rejecting CUDA usage in favor of the CUDA graph engine.

Enhancements:

  • Automatically select Apple MPS when available and CPU otherwise, preserving existing Apple Silicon behavior.
  • Document CPU packed-engine usage, supported hardware, performance characteristics, and equivalent-answer expectations.

Documentation:

  • Update serving, installation, hardware, quantization, and release documentation for CPU support in --mode mps.

Tests:

  • Add CPU coverage verifying packed MPS results match separate prompt execution across padded and long-row paths.

…; same answers

On a CPU, --mode eager runs every prompt whole, so a request with several
questions or option orders computes its state once per prompt (2.3's
shared-state eager forward is Gemma 4 only). MPSBackend already packs a
request into one prefix trie and runs plain forwards with nothing
Apple-specific, but the server never passed --device and it defaulted to
mps, so it could not run on Linux / Windows.

Pass --device to MPSBackend, default it to cpu where MPS is unavailable,
refuse --device cuda (that is --mode fast).

basal-2.0-mini, fp32, 6-core Zen 2: three task requests 838 s -> 88 s
(9.6x), 75/75 same top answers, max |dp| 4.4e-6; over HTTP, the complex
examples plus a verify request 184.9 s -> 53.6 s, 18/18 same, max |dp|
2.7e-6.
@sourcery-ai

sourcery-ai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Adds CPU support to the existing packed MPS backend, exposing shared-state batching through --mode mps --device cpu while retaining Apple MPS behavior, rejecting CUDA misuse, validating numerical equivalence, and updating documentation with the measured performance gains.

Sequence diagram for packed CPU request execution

sequenceDiagram
    participant Client
    participant Server
    participant MPSBackend
    participant CPU

    Client->>Server: run_shared request
    Server->>MPSBackend: MPSBackend(device=cpu)
    MPSBackend->>MPSBackend: pack shared prefixes and batch prompts
    MPSBackend->>CPU: compute shared state once
    CPU-->>MPSBackend: shared state
    MPSBackend->>CPU: run question and option-order readouts
    CPU-->>MPSBackend: probability vectors
    MPSBackend-->>Server: readouts
    Server-->>Client: response
Loading

Flow diagram for mps device selection and validation

flowchart TD
    A[--mode mps] --> B{--device cuda?}
    B -->|yes| C[Reject: use --mode fast]
    B -->|no| D{Device specified?}
    D -->|mps| E[Run MPSBackend on Apple MPS]
    D -->|cpu| F[Run MPSBackend on CPU]
    D -->|no| G{MPS available?}
    G -->|yes| E
    G -->|no| F
    F --> H[Shared state computed once for all prompts]
Loading

File-Level Changes

Change Details Files
Extend the packed MPS backend to support CPU execution with automatic device selection.
  • Default to MPS when available and CPU otherwise, while preserving explicit device selection.
  • Reuse the existing prefix-trie, SOAM, token-budget batching, and plain-forward shared-state path on CPU.
  • Document that CPU packed execution computes shared request state once across prompts and option orders.
basal/engine.py
Wire the selected device through server configuration and reject unsupported CUDA usage.
  • Pass --device into MPSBackend construction.
  • Reject --mode mps --device cuda and direct users to --mode fast.
  • Update --device help text with MPS/CPU behavior and defaults.
basal/server.py
Add regression coverage proving CPU packed execution matches independent prompt execution.
  • Exercise multiple requests, shared questions and option orders, padded rows, and the long-row path.
  • Compare all packed readouts with separate CPU runs at fp32 tolerance.
tests/test_engine.py
Update engine availability, serving guidance, and release notes for CPU MPS mode.
  • Advertise mps --device cpu in hardware, installation, quantization, and serving tables.
  • Add CPU usage guidance, performance results, answer agreement, and CUDA restriction to the changelog.
docs/HARDWARE.md
docs/INSTALL.md
docs/QUANTIZATION.md
docs/SERVING.md
docs/WHATS_NEW.md

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/server.py" line_range="1290-1291" />
<code_context>
     ap.add_argument("--device", default=None, choices=["cuda", "mps", "cpu"],
-                    help="device for --mode eager (default: BASAL_DEVICE, else cuda, else Apple Silicon mps, else cpu)")
+                    help="device for --mode eager (default: BASAL_DEVICE, else cuda, else Apple Silicon mps, else cpu) "
+                         "and --mode mps (mps or cpu; default: mps on Apple Silicon, else cpu: a request's state "
+                         "computed once for all its prompts, where eager computes it once per prompt)")
     ap.add_argument("--orders", type=orders_arg, default=None,
                     help="1 = the option order given; 2 = also the reversed order, averaged (shares the state); auto = "
</code_context>
<issue_to_address>
**CPU default misses packed engine**

When a CPU user starts the server without specifying `--mode`, `default_mode()` still returns `eager` on a CPU, so starting `basal-serve` without `--mode` computes the request state once per prompt and users get none of the new CPU packing benefit.

Decide whether CPU defaults should select `mps`; if so, update `default_mode()` and its help, otherwise clearly preserve and document `eager` as the intentional default.
</issue_to_address>

### Comment 2
<location path="basal/server.py" line_range="657-658" />
<code_context>
             raise SystemExit("--ple-offload on needs --mode eager")
         if getattr(a, "eager_attn", "math") != "math" and kind != "eager":
             raise SystemExit("--eager-attn needs --mode eager (the CUDA graph engine takes --attn)")
+        if kind == "mps" and a.device == "cuda":
+            raise SystemExit("--mode mps runs on Apple Silicon or the CPU (--device mps / cpu); on CUDA: --mode fast")
         if kind == "eager":
             self.backend = EagerBackend(md, a.dtype, device=a.device, media=getattr(a, "media", "off") == "on",
</code_context>
<issue_to_address>
**Invalid mode downloads model first**

When `--mode mps --device cuda` is used with a remote model that is not cached, `Server.__init__` calls `resolve` before reaching the CUDA-device guard, so an uncached remote model is downloaded before the command rejects `--mode mps --device cuda`; users incur the download and storage cost for a configuration that cannot run.

Move the device guard ahead of model resolution.
</issue_to_address>

### Comment 3
<location path="tests/test_engine.py" line_range="116-117" />
<code_context>
+    groups = [g1, g2, g3]
+    for lens in ([64], [12]):  # 12: g1's packed row (34 tokens) is over the largest length and takes the long path
+        be.LENS = lens
+        for (toks, lids), res in zip(groups, be.run_shared(groups)):
+            for r, e in zip(res, separate(m, toks, lids)):
+                assert torch.allclose(torch.tensor(r), e, atol=1e-5), lens
+
</code_context>
<issue_to_address>
**Missing readouts go unnoticed**

When `run_shared` returns fewer request results or readouts than the inputs contain, `test_mps_backend_on_cpu_equals_separate` truncates both comparisons with `zip`, so a `run_shared` result missing a request or trailing readouts produces no assertion for those omissions and the test passes.

Assert the number of returned requests and each request's readout count before comparing values.
</issue_to_address>

### Comment 4
<location path="basal/engine.py" line_range="1735-1738" />
<code_context>
-    """Apple GPU through PyTorch MPS: the shared-prefix packing (prefix trie, SOAM) and token-budget batching of
-    GraphBackend, run as plain forwards (MPS has no CUDA graphs). Rows are padded on the right to the longest packed
-    row of the chunk."""
+    """The shared-prefix packing (prefix trie, SOAM) and token-budget batching of GraphBackend, run as plain forwards
+    without CUDA graphs: on the Apple GPU through PyTorch MPS, or on the CPU (no MPS, or device="cpu"), where a
+    request's state is then computed once instead of once per prompt as in EagerBackend. Rows are padded on the right
+    to the longest packed row of the chunk."""

     streams, inflight = False, 1  # its own run_shared: no early readouts, one call at a time
</code_context>
<issue_to_address>
**Backend overview omits CPU support**

The module-level backend list still describes `MPSBackend` as running “on Apple MPS,” so consumers reading that overview are not told that the backend now also runs on CPU.

Update the module-level backend overview to include CPU execution.
</issue_to_address>

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

Comment thread basal/server.py Resolved
Comment thread basal/server.py Resolved
Comment thread tests/test_engine.py Resolved
Comment thread basal/engine.py Resolved
@rkinas
rkinas merged commit 31456f3 into rkinas:main Oct 20, 2026
1 check passed
@rkinas

rkinas commented Oct 20, 2026

Copy link
Copy Markdown
Owner

Thanks, Milosz! Merged for basal 2.3.1. --mode mps --device cpu gives the Llama-based models a shared state on the CPU too, and the new CPU test matches separate prompts. You are credited in WHATS_NEW and in the 2.3.1 release notes.

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