Repository navigation
perf(mps): run the packed engine on the CPU (--mode mps --device cpu); same answers - #26
Merged
Merged
Conversation
…; 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.
Reviewer's GuideAdds 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 executionsequenceDiagram
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
Flow diagram for mps device selection and validationflowchart 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]
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/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>…s; docs: CPU default stays eager
Owner
|
Thanks, Milosz! Merged for basal 2.3.1. |
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.
Problem
On a CPU the only PyTorch path is
--mode eager, which runs every prompt of a request whole: with several questions oroption orders over one state (tasks,
--orders 2), the state is computed once per prompt. 2.3's shared-state eagerforward 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 pinmemory only on CUDA), but the server builds it as
MPSBackend(md, a.dtype, shared=shared)and it defaults todevice="mps", so on Linux / Windows--mode mpsfails with "PyTorch is not linked with support for mps devices".Change
server.py: pass--devicetoMPSBackend; refuse--mode mps --device cuda(that is--mode fast);--devicehelp covers
--mode mps.engine.py:MPSBackend(device=None)=mpswhere MPS is available, elsecpu(Apple Silicon behaves as before;basal-bench --modes mpsalso works on a CPU machine).mpsrow in SERVING.md, the engines tables (HARDWARE.md, QUANTIZATION.md, INSTALL.md), the CPU section ofINSTALL.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,EagerBackendvsMPSBackend(device="cpu")):compress, unit sentencecompress, unit paragraphverify, 10 claimsSame top answer on 75 of 75 readouts, max |Δp| 4.4e-6.
End to end over HTTP (
basal-serve --mode mps --device cpuvs--mode eager --device cpu, the fivebasal/examples/complex.jsonlrequests plus oneverifyrequest with 4 claims over 6,000 characters ofdocs/SOAM.md): 53.6 s vs 184.9 s in total (complex requests 4.2–4.7 s vs 5.1–7.8 s; theverifyrequest 31.2 s vs153.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_sharedon the CPU, threerequests 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/withouttest_gguf.py(needs llama-cpp-python): 613 passed, 73 skipped (CUDA / MLX / TPU only).basal-serve --mode mps --device cudaexits with "--mode mps runs on Apple Silicon or the CPU (--device mps / cpu);on CUDA: --mode fast".
Open for you: whether
mpsshould become the default on CPU instead ofeager(default_mode()), and whether thename should change (
mpsfor a CPU mode reads oddly; apackedalias 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:
mpsengine to run on CPUs, computing shared request state once across multiple prompts and option orders.--deviceselection for--mode mpswhile rejecting CUDA usage in favor of the CUDA graph engine.Enhancements:
Documentation:
--mode mps.Tests: