← Back to Pull requests

Add native Apple Metal/MPS backend #2077

Closed
unknown closed this pull request without merging on Nov 09, 2026 12:21 UTC
View on GitHub
unknown unknown commented on Jul 21, 2026 20:03 UTC
Author

Summary

This PR adds an experimental native Metal/MPS backend for CTranslate2 on Apple Silicon. It is opt-in with -DWITH_MPS=ON and makes the existing C++ and Python APIs accept device="mps" without changing the default CPU, CUDA, or HIP behavior.

I started this port about six months ago because CTranslate2 could use Apple CPUs efficiently but had no path to the Apple GPU. The first versions could run a few operations, but real Marian and Whisper inference exposed missing operators, excessive synchronization, lifetime bugs, and poor batch-size-1 performance. I used those end-to-end workloads—not only large synthetic GEMMs—to guide the implementation in this PR.

What is included

  • Device::MPS support in device parsing, dispatch, storage, synchronization, the CLI, and Python bindings

  • ctranslate2.get_mps_device_count() and get_supported_compute_types("mps")

  • Source builds on Apple Silicon with Metal, Metal Performance Shaders, and Foundation

  • FP32, FP16, BF16, and signed INT8 execution; compute_type="auto" selects FP16

  • A thread-local persistent Metal execution stream that batches commands, reuses compute/blit encoders, supports several command buffers in flight, and only waits at host-visible synchronization points

  • Shared-memory Metal allocation with an ordered interior-pointer lookup and GPU-lifetime tracking for buffers and Objective-C objects

  • Cached Metal pipelines, MPS matrix multiplication objects, TopK objects, and persistent output-major decode weights

  • A specialized FP16 M == 1 GEMV path for autoregressive projections, including a fused bias/residual/activation epilogue

  • MPSMatrix and custom GEMM paths for prefill, transposed inputs, batched GEMM, broadcast strides, odd dimensions, and tails

  • GPU argmax and small TopK (k <= 8), with MPSMatrix TopK used for supported larger values

  • Metal implementations for the common elementwise, reduction, normalization, rotary, copy/layout, gather, concat/split/tile, and Conv1D paths needed by Transformer, Marian, and Whisper inference

  • BF16 storage with FP32 accumulation where required, plus INT8 quantize/GEMM/dequantize support

  • Optional MPS profiling, GEMM-path logging, synchronization logging, and command-buffer tuning environment variables

  • MPS correctness tests and standalone primitive/Marian benchmark tools
  • The dispatch changes also preserve non-MPS builds. In particular, FP16/BF16 dispatch is restricted to enabled GPU backends so MSVC does not instantiate unsupported CPU half-precision symbols in CUDA wheel builds.

    Build and use

    cmake -S . -B build-mps \
      -DCMAKE_BUILD_TYPE=Release \
      -DCMAKE_POLICY_VERSION_MINIMUM=3.5 \
      -DWITH_MPS=ON \
      -DWITH_ACCELERATE=ON \
      -DWITH_MKL=OFF \
      -DWITH_RUY=ON \
      -DOPENMP_RUNTIME=NONE
    cmake --build build-mps -j
    

    import ctranslate2
    
    translator = ctranslate2.Translator(
        "model",
        device="mps",
        compute_type="float16",
    )
    

    The minimum deployment target is macOS 11. MPS is not enabled in prebuilt wheels by this PR and currently has to be built from source.

    Correctness and CI validation

    Local validation and the reportable benchmarks were run on a MacBook Air with an Apple M1 (7-core GPU, 8 GB unified memory), arm64, macOS 26.5.2, using Release builds.

    The CI configuration includes a dedicated real Apple Silicon MPS GPU job. It builds with -DWITH_MPS=ON, runs the MPS runtime suite, and then runs the normal CPU/shared suite from the same MPS-enabled build. It also builds the Python bindings, tests explicit device="mps" inference, and verifies that device="auto" remains on CPU so the experimental backend is opt-in.

    The equivalent workflow passed on the self-hosted Apple M1 runner: 192 MPS C++ tests passed, 198 CPU/shared C++ tests passed with one existing CPU-only skip, and both Python MPS integration tests passed.

    https://github.com/TBO22/CTranslate2/actions/runs/32951573494/job/98123905546

    The upstream macos-15-xlarge job could not be scheduled because larger-runner billing is not enabled for the repository. No test process started in that failed job; this was a runner availability/billing issue rather than a test failure. The upstream workflow retains macos-15-xlarge, so the merged CI configuration does not depend on contributor-owned hardware.

    MPS coverage includes FP32/FP16/BF16, INT8, odd sizes, tails, broadcast and nonzero batch strides, transposed GEMM, alpha/beta, interior offsets, dependent asynchronous dispatches, TopK tie behavior, Gather, Conv1D, and translation output comparison. git diff --check also passes.

    Quality Validation

    The reproducible evaluation scripts and methodology are under tools/benchmark/quality/. CPU used FP32 and MPS used FP16 with the same models, inputs, sample order, and decoding settings. Model loading and one warm-up inference were excluded from inference timing.

    | Benchmark | CPU quality | MPS quality | Output agreement | MPS speedup |
    | --- | ---: | ---: | ---: | ---: |
    | LibriSpeech clean, 2,703 utterances, beam 5 | 2.9125% WER | 2.9089% WER | 99.63% normalized transcript agreement | 1.93× |
    | WMT14 En→De, 2,737 sentences, beam 4, batch 4 | 27.9152 BLEU | 27.9332 BLEU | 96.60% exact translation agreement | 2.13× |

    Performance

    Performance varies by model and sequence length, so this is not intended as a universal claim. One representative end-to-end result from the M1 test machine was a 12.52-second, batch-size-1 Whisper transcription/translation workload:

    | Backend | Compute type | Latency | Output |
    | --- | --- | ---: | --- |
    | CPU | FP32 | 54.950 s | reference |
    | MPS | FP16 | 15.531 s | exact text match |

    This is a 3.54x end-to-end speedup for that workload. The PR also includes tools/benchmark_mps_marian.py, which runs CPU and MPS in separate processes with warmups and repeated measurements across source lengths and beam sizes, and tests/benchmark_mps.cc for decode GEMM, vocabulary projection, prefill GEMM, TopK, and copy-heavy operations.

    Current limitations

  • Apple Silicon and source builds only; no MPS-enabled release wheel in this PR

  • WITH_MPS cannot currently be combined with CUDA or HIP in one build

  • FlashAttention, AWQ INT4, INT16 GEMM, distributed collectives, and packed/shifted-u8 INT8 GEMM are not implemented on MPS

  • Metal kernels are currently compiled from source once and cached at runtime; a precompiled metallib can be added separately

  • INT8 is supported for compatibility and reduced weight memory, but FP16 is normally faster for batch-size-1 decoding and remains the automatic default
  • AI-assisted development disclosure

    I used Codex with GPT-5.6 as a pair-programming tool for repository navigation, repetitive implementation work, test scaffolding, diff review, and tracing build and lifetime failures. I did not treat generated suggestions as authoritative. I researched the execution model and kernel design myself, including how Apple MLX kernels differ from ggml/PyTorch and CUDA implementations and how Apple unified memory affects synchronization and ownership. I selected the design, ran the benchmarks, reproduced correctness failures, reviewed the changes, and remain responsible for the implementation and results in this PR.

    I understand that this is a large, performance-sensitive change and am happy to respond to detailed review or split follow-up work where maintainers prefer a different boundary.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: jordimas Review duration: 159378m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #2077"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%