Repository navigation
[Apple Silicon] Add an Apple Silicon (MPS) platform to the standard Torch model runner - #36780
Conversation
6f91278 to
3f46196
Compare
yeahdongcn
left a comment
There was a problem hiding this comment.
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()
PYThe 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.
|
/tag-and-rerun-ci |
6f5f3ec to
d26ca4c
Compare
yeahdongcn
left a comment
There was a problem hiding this comment.
@alexnails Could you please take another look? Thanks!
|
/rerun-failed-ci |
|
One MLX failure is due to upstream issue. Fix is in this PR : #37272 . |
8b48e12 to
6e3e768
Compare
|
/rerun-failed-ci |
cfb53eb to
ba4b196
Compare
c53edc0 to
acc4d64
Compare
alexnails
left a comment
There was a problem hiding this comment.
initial set of comments
alexnails
left a comment
There was a problem hiding this comment.
take second look over the tests pls, approved
|
/rerun-failed-ci |
1 similar comment
|
/rerun-failed-ci |
|
/rerun-failed-ci |
f23bd4e to
18e3c0d
Compare
|
@alexnails gentle reminder. |
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.
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.
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:current_platformhas no MPS branch, so device resolution,stream creation, and memory accounting fall through to code that assumes CUDA semantics.
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(), soSGLANG_USE_MLX=1behaves exactly as before.
Modifications
platforms/mps.py(new) —MpsDeviceMixin/MpsSRTPlatform. The interesting part ismemory: capacity comes from
torch.mps.recommended_max_memory()and usage fromtorch.mps.driver_allocated_memory(), somem_fraction_staticapplies to the budget Metalwill actually honor. Also sets MPS defaults:
torch_nativeattention,eager(no CUDAgraphs),
gloofor distributed init.hardware_backend/mps/runtime.py(new) —validate_mps_runtime()checks Metal is reallyusable;
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.pypromotesget_device/set_device/create_streamfrom"planned" to active hooks so a platform can own device selection instead of callers branching
on device strings;
platforms/__init__.py,_platform_stubs.py, andutils/common.pyregister and detect MPS (
is_mps());model_runner.pyroutes through the new hooks.server_args.py—_handle_mps_backendssets the MPS defaults(
disable_overlap_schedule=True,sampling_backend="pytorch"), and_validate_standard_mps_server_argsfails fast on what the Torch MPS path can't do yet:non-
torch_nativeattention, non-pytorchsampling, non-auto/bf16 KV dtype, HND KV cache,LoRA on a non-
torch_nativebackend, 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 pristineself.device. On macOS--deviceis usuallyomitted and auto-detected, so
self.deviceisNoneat gate time — reading it would make thewhole validation block dead code on the normal
sglang servepath, while the defaults handler(already using
resolving_view) would still quietly override your settings. Reading theresolved device keeps "we override this" and "we reject this" consistent.
CI — adds a
register_mps_cimarker and anMPSHWBackendmember, mirroring the otherper-backend helpers.
Accuracy Tests
Qwen/Qwen3-0.6B,--device mps,mem_fraction_static=0.6, M4 Pro / 48 GB.An end-to-end serving test is added at
test/registered/mps/models_e2e/test_qwen3_torch_mps.py(registered asstage-b-e2e-mps, skipped unlesstorch.backends.mps.is_available()); it launches a realserver and asserts coherent generation. Passes in 37 s.
Unit sweep over
hardware_backend/{mps,mlx},platforms, andmanagers:867 passed, 20 skipped, 1 failed — where the single failure
(
test_load_snapshot_backends.py::TestFactoryFunctions::test_shm_mode) reproduces onunmodified
mainand is unrelated to this change. This matches themainbaseline exactly.Speed Tests and Profiling
Online serving, same host and model (
bench_serving, random dataset, 40 prompts,256 in / 128 out, max concurrency 8):
Offline
bench_one_batch(batch 4, 256 in / 32 out):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
mainbaseline run on the same host this is performance-neutral. That isexpected: on non-MPS hardware the added code is inert, and the shared plumbing changes in
device_mixin.pyandmodel_runner.pyreplace direct calls with platform-hook dispatchrather than adding work.
Compatibility and Breaking Changes
when the resolved device is
mps.not use_mlx();SGLANG_USE_MLX=1continues to select the MLX runner with its previousdefaults. Verified: under
SGLANG_USE_MLX=1the MPS defaults are not applied(
disable_overlap_schedule=False,sampling_backend=None).deep in model loading now fail immediately with an explicit message. Verified:
--tp-size 2now fails before model loading withThe 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.pyinstalls a customcustomized_info_probesampling backend, which the MPS contract now rejects. The test isskipped 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.
SGLANG_USE_MLX=0 HF_HUB_OFFLINE=1 python test/run_suite.py --hw mps --suite stage-a-unit-test-mpsSGLANG_USE_MLX=0 HF_HUB_OFFLINE=1 python test/run_suite.py --hw mps --suite stage-b-e2e-mpsSGLANG_USE_MLX=1 python -m sglang.launch_server --model-path Qwen/Qwen3-0.6B --device mps --max-total-tokens 4096, followed by/healthand/generateTests Added
test/registered/unit/hardware_backend/mps/test_mps_runtime.pytest/registered/unit/platforms/test_platform_interface.pytest/registered/mps/models_e2e/test_qwen3_torch_mps.pyChecklist
Review and Merge Process
/tag-and-rerun-ci,/tag-run-ci-label,/rerun-failed-ciCI States
Latest PR Test (Base): ✅ Run #37048059790
Latest PR Test (Extra): ❌ Run #37048059511
Latest PR Test (AMD ROCm 10): ❌ Run #37048060264