Skip to content

[Apple Silicon] Add an Apple Silicon (MPS) platform to the standard Torch model runner - #36780

Merged
alexnails merged 15 commits into
sgl-project:mainfrom
adityavaid:add-mps-standard-torch-runner
Oct 4, 2026
Merged

alexnails merged 15 commits into
sgl-project:mainfrom
adityavaid:add-mps-standard-torch-runner

Conversation

@adityavaid

@adityavaid adityavaid commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Part of #32321
Right now the only way to run SGLang on a Mac is the MLX backend, which brings its own
runner, attention, and memory model. The standard Torch path — the one every other
accelerator uses — just doesn't work on macOS, so folks on Apple hardware can't exercise the
mainline scheduler, model runner, or memory-pool code locally.

Two things block plain --device mps:

  1. No MPS platform object. current_platform has no MPS branch, so device resolution,
    stream creation, and memory accounting fall through to code that assumes CUDA semantics.
  2. Memory accounting is wrong on unified memory. The GPU has no private VRAM — it borrows
    system RAM, and Metal enforces a recommended working set smaller than physical RAM. On my
    M4 Pro / 48 GB that budget is 37.44 GiB, not 48 GB. Size the KV cache off total RAM and
    the allocation just fails.

This adds the MPS platform so the standard Torch runner works on Apple Silicon. MLX routing is
untouched — every new default and check is gated behind not use_mlx(), so SGLANG_USE_MLX=1
behaves exactly as before.

NOTE :
Upstream PR https://github.com/sgl-project/sglang/pull/37164 moved Mamba allocation state into ReqKvInfo , but the MLX FakeRequest fixture did not retain the separate top-level  mamba_branching_seqlen  field required by  MlxModelRunner .
Add the missing field to align the test double with the production  Req  contract and restore the MLX stage-A unit suite.

Modifications

platforms/mps.py (new) — MpsDeviceMixin / MpsSRTPlatform. The interesting part is
memory: capacity comes from torch.mps.recommended_max_memory() and usage from
torch.mps.driver_allocated_memory(), so mem_fraction_static applies to the budget Metal
will actually honor. Also sets MPS defaults: torch_native attention, eager (no CUDA
graphs), gloo for distributed init.

hardware_backend/mps/runtime.py (new) — validate_mps_runtime() checks Metal is really
usable; validate_mps_model_config() rejects checkpoint-derived modes we can't serve
(quantized, multimodal). Both run before model loading, so bad launches fail in seconds
instead of after a multi-GB download.

Plumbing — device_mixin.py promotes get_device / set_device / create_stream from
"planned" to active hooks so a platform can own device selection instead of callers branching
on device strings; platforms/__init__.py, _platform_stubs.py, and utils/common.py
register and detect MPS (is_mps()); model_runner.py routes through the new hooks.

server_args.py — _handle_mps_backends sets the MPS defaults
(disable_overlap_schedule=True, sampling_backend="pytorch"), and
_validate_standard_mps_server_args fails fast on what the Torch MPS path can't do yet:
non-torch_native attention, non-pytorch sampling, non-auto/bf16 KV dtype, HND KV cache,
LoRA on a non-torch_native backend, DLLM, multimodal, spec decoding, torch.compile,
disaggregated serving, quantized weights, and tp/pp/dp != 1.

One detail worth calling out: the validation gate reads the resolved device
(resolving_view(self).device), not pristine self.device. On macOS --device is usually
omitted and auto-detected, so self.device is None at gate time — reading it would make the
whole validation block dead code on the normal sglang serve path, while the defaults handler
(already using resolving_view) would still quietly override your settings. Reading the
resolved device keeps "we override this" and "we reject this" consistent.

CI — adds a register_mps_ci marker and an MPS HWBackend member, mirroring the other
per-backend helpers.

Accuracy Tests

Qwen/Qwen3-0.6B, --device mps, mem_fraction_static=0.6, M4 Pro / 48 GB.

Benchmark Result
GSM8K (200 questions, 5-shot, parallel 8) accuracy 0.425, invalid 0.000

An end-to-end serving test is added at
test/registered/mps/models_e2e/test_qwen3_torch_mps.py (registered as
stage-b-e2e-mps, skipped unless torch.backends.mps.is_available()); it launches a real
server and asserts coherent generation. Passes in 37 s.

Unit sweep over hardware_backend/{mps,mlx}, platforms, and managers:
867 passed, 20 skipped, 1 failed — where the single failure
(test_load_snapshot_backends.py::TestFactoryFunctions::test_shm_mode) reproduces on
unmodified main and is unrelated to this change. This matches the main baseline exactly.

Speed Tests and Profiling

Online serving, same host and model (bench_serving, random dataset, 40 prompts,
256 in / 128 out, max concurrency 8):

Metric Value
Total token throughput 213.49 tok/s
Output token throughput 72.94 tok/s
Median TTFT 186.48 ms
Median TPOT 104.33 ms
Median ITL 98.95 ms

Offline bench_one_batch (batch 4, 256 in / 32 out):

Metric Value
Prefill throughput 2530.63 tok/s
Decode median throughput 65.90 tok/s
Decode median latency 60.70 ms
Total throughput 504.58 tok/s

All benchmarks above were run twice on separate server launches and agreed within noise
(total serving throughput 213.5 / 215.9 tok/s; offline total 504.6 / 505.0 tok/s; GSM8K
accuracy identical at 0.425 both times).

Compared against a main baseline run on the same host this is performance-neutral. That is
expected: on non-MPS hardware the added code is inert, and the shared plumbing changes in
device_mixin.py and model_runner.py replace direct calls with platform-hook dispatch
rather than adding work.

Compatibility and Breaking Changes

  • No behavior change on CUDA / ROCm / other backends. The new platform only activates
    when the resolved device is mps.
  • No behavior change for MLX users. Every new default and validation is behind
    not use_mlx(); SGLANG_USE_MLX=1 continues to select the MLX runner with its previous
    defaults. Verified: under SGLANG_USE_MLX=1 the MPS defaults are not applied
    (disable_overlap_schedule=False, sampling_backend=None).
  • Newly enforced on plain macOS: launches that previously proceeded and then failed
    deep in model loading now fail immediately with an explicit message. Verified:
    --tp-size 2 now fails before model loading with
    The standard Torch MPS path requires tp_size=1, pp_size=1, and dp_size=1.

One existing test needed a skip as a consequence of that enforcement.
test/registered/unit/managers/test_customized_info_streaming.py installs a custom
customized_info_probe sampling backend, which the MPS contract now rejects. The test is
skipped on MPS rather than loosening the contract — the restriction is real, and the test is
exercising sampler plumbing rather than anything MPS-specific.

Apple Silicon Runtime Validation

Final serving checks ran on an M4 Pro with 48 GB unified memory, macOS 26.6.2, Python 3.11.15,
Torch 2.13.0, and MLX 0.32.0.

Path Validation Result
Standard Torch MPS SGLANG_USE_MLX=0 HF_HUB_OFFLINE=1 python test/run_suite.py --hw mps --suite stage-a-unit-test-mps Passed (1/1)
Standard Torch MPS SGLANG_USE_MLX=0 HF_HUB_OFFLINE=1 python test/run_suite.py --hw mps --suite stage-b-e2e-mps Passed (1/1); launches Qwen3-0.6B, generates output, and verifies radix-cache reuse
MLX SGLANG_USE_MLX=1 python -m sglang.launch_server --model-path Qwen/Qwen3-0.6B --device mps --max-total-tokens 4096, followed by /health and /generate Passed; server started and returned a generation

Tests Added

File Covers
test/registered/unit/hardware_backend/mps/test_mps_runtime.py Runtime gate, checkpoint-derived config rejection, and that the gate is selected by execution path (Torch vs MLX)
test/registered/unit/platforms/test_platform_interface.py Extends the shared platform-interface contract to cover MPS and the newly-active device hooks
test/registered/mps/models_e2e/test_qwen3_torch_mps.py End-to-end server launch and generation on MPS

Checklist

Review and Merge Process

  1. Ping Merge Oncalls to start the process. See the PR Merge Process.
  2. Get approvals from CODEOWNERS and other reviewers.
  3. Trigger CI tests with comments or contact authorized users to do so.
    • Common commands include /tag-and-rerun-ci, /tag-run-ci-label, /rerun-failed-ci
  4. After green CI and required approvals, ask Merge Oncalls or people with Write permission to merge the PR.

CI States

Latest PR Test (Base): ✅ Run #37048059790
Latest PR Test (Extra): ❌ Run #37048059511
Latest PR Test (AMD ROCm 10): ❌ Run #37048060264

Comment thread python/sglang/srt/utils/common.py Resolved
Comment thread python/sglang/srt/utils/common.py Resolved
Comment thread python/sglang/srt/utils/common.py Resolved
Comment thread python/sglang/test/ci/ci_register.py Resolved
Comment thread python/sglang/srt/server_args.py Resolved
Comment thread python/sglang/test/ci/ci_register.py Resolved
Comment thread python/sglang/srt/utils/common.py Resolved
Comment thread python/sglang/srt/utils/common.py Resolved
Comment thread python/sglang/srt/utils/common.py Resolved
Comment thread python/sglang/srt/utils/common.py Resolved
Comment thread python/sglang/srt/utils/common.py Resolved
Comment thread python/sglang/srt/server_args.py Resolved
Comment thread python/sglang/srt/server_args.py Resolved
@adityavaid
adityavaid force-pushed the add-mps-standard-torch-runner branch from 6f91278 to 3f46196 Compare August 30, 2026 13:40

@yeahdongcn yeahdongcn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

One issue my agent encountered while running the E2E tests, so I asked it to write a small test case:

SGLANG_IS_IN_CI=1 \
SGLANG_USE_MLX=0 \
PYTHONPATH=python \
uv run python - <<'PY'
import torch
from sglang.srt.managers import overlap_utils
import triton.runtime.cache as cache

print(
    f"torch={torch.__version__} "
    f"mps={torch.backends.mps.is_available()} "
    f"debug_assert={overlap_utils._DEBUG_ASSERT}"
)
print(
    f"triton.runtime.cache.triton_key={cache.triton_key!r} "
    f"callable={callable(cache.triton_key)}"
)

values = torch.ones(2, dtype=torch.int64, device="mps")
buffer = torch.full((4,), -1, dtype=torch.int64, device="mps")
indices = torch.tensor([0, 1], dtype=torch.int64, device="mps")

overlap_utils._assert_nonneg_and_invalidate(values, buffer, indices)
torch.mps.synchronize()
PY

The result is:

torch=2.13.0 mps=True debug_assert=True
triton.runtime.cache.triton_key=<module ...> callable=False
torch._dynamo.exc.BackendCompilerFailed:
backend='inductor' raised:
TypeError: 'module' object is not callable

The registered Qwen3-0.6B MPS E2E shows the same behavior: the server loads the model and becomes ready, but the first request fails in resolve_forward_inputs() when _assert_nonneg_and_invalidate() enters its @torch.compile wrapper.

So I'd prefer that you also run some E2E tests rather than relying solely on unit tests.

@yeahdongcn

Copy link
Copy Markdown
Collaborator

/tag-and-rerun-ci

@github-actions github-actions Bot added the run-ci CI: run the baseline test suite on this PR label Aug 31, 2026
@adityavaid
adityavaid force-pushed the add-mps-standard-torch-runner branch from 6f5f3ec to d26ca4c Compare August 31, 2026 06:39

@yeahdongcn yeahdongcn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@alexnails Could you please take another look? Thanks!

@adityavaid

Copy link
Copy Markdown
Contributor Author

/rerun-failed-ci

@adityavaid

Copy link
Copy Markdown
Contributor Author

One MLX failure is due to upstream issue. Fix is in this PR : #37272 .
Let me know you want to add these changes in this PR itself.

@adityavaid
adityavaid force-pushed the add-mps-standard-torch-runner branch 2 times, most recently from 8b48e12 to 6e3e768 Compare September 15, 2026 12:04
@adityavaid

Copy link
Copy Markdown
Contributor Author

/rerun-failed-ci

@adityavaid
adityavaid force-pushed the add-mps-standard-torch-runner branch 2 times, most recently from cfb53eb to ba4b196 Compare September 21, 2026 20:40
@adityavaid
adityavaid force-pushed the add-mps-standard-torch-runner branch from c53edc0 to acc4d64 Compare September 24, 2026 12:11

@alexnails alexnails left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

initial set of comments

Comment thread python/sglang/_platform_stubs.py Resolved
Comment thread python/sglang/_platform_stubs.py Resolved
Comment thread python/sglang/srt/platforms/mps.py Resolved
Comment thread python/sglang/srt/platforms/mps.py Resolved

@alexnails alexnails left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

take second look over the tests pls, approved

@adityavaid

Copy link
Copy Markdown
Contributor Author

/rerun-failed-ci

1 similar comment
@adityavaid

Copy link
Copy Markdown
Contributor Author

/rerun-failed-ci

@adityavaid

Copy link
Copy Markdown
Contributor Author

/rerun-failed-ci

@adityavaid
adityavaid force-pushed the add-mps-standard-torch-runner branch from f23bd4e to 18e3c0d Compare October 2, 2026 18:31
@adityavaid

Copy link
Copy Markdown
Contributor Author

@alexnails gentle reminder.

@adityavaid
adityavaid requested a review from alexnails October 4, 2026 07:23
@alexnails
alexnails merged commit caf9632 into sgl-project:main Oct 4, 2026
162 of 183 checks passed
pllimax added a commit to pllimax/sglang that referenced this pull request Oct 8, 2026
The pinned cann9.1.0-a3-B081 image ships a stale sglang snapshot lacking HWBackend.MPS (added by sgl-project#36780 on Oct 5), so run_suite.py aborted at import. Enable install_sglang_deps for this job so the suite runs against the checked-out source, matching the PR pipeline behavior.
pllimax added a commit to pllimax/sglang that referenced this pull request Oct 12, 2026
The pinned cann9.1.0-a3-B081 image ships a stale sglang snapshot lacking HWBackend.MPS (added by sgl-project#36780 on Oct 5), so run_suite.py aborted at import. Enable install_sglang_deps for this job so the suite runs against the checked-out source, matching the PR pipeline behavior.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

apple-silicon run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants