Drop-in Strassen–Winograd matrix multiplication for MLX and mlx-lm on Apple Silicon.
This is the code release corresponding to the paper Strassen-Winograd Matrix Multiplies and Apple Silicon: Two Fast Things That Go Fast Together
DropSW accelerates LLM prefill (time-to-first-token) for dense FP16, BF16, FP32, and 4-bit / 8-bit affine group-quantized models (group_size 32 or 64) with no increase in weight RAM and only modest (1/2GB) increase in scratch buffer
size during compute, and automatically falls back to native MLX kernels during single-token decode (M = 1), short prompts, and fine-grained sparse MoE expert calls.
Please use with appropriate caution: This code was primarily AI generated and has only been tested on two machines by the author. It is being released primarily to verify reseach results and to serve as a reference for integrating into real LLM serving.
This work was supported by the Carnegie Mellon University Parallel Data Lab. If you find it valuable, please support our research.
pip install -e .
# or directly from a git checkout:
pip install .Requires macOS on Apple Silicon (M1–M4 series) and mlx >= 0.30.0 (tested on mlx == 0.32.5, mlx-lm == 0.32.2). For patching LLM models, install mlx-lm.
Patch any loaded mlx-lm model in place with one call, and pass prefill_step_size=4096 (or 8192) when generating from long prompts:
import mlx_lm
import dropsw
model, tokenizer = mlx_lm.load("mlx-community/Meta-Llama-3.1-8B-Instruct-4bit")
n_patched = dropsw.patch_model(model)
print(f"Patched {n_patched} linear layers with DropSW")
# Raise prefill_step_size from mlx-lm's 2048 default to 4096 (or 8192)
# to unlock k=2 Strassen-Winograd and M >= 4096 input fusions:
response = mlx_lm.generate(
model,
tokenizer,
prompt="...",
max_tokens=128,
prefill_step_size=4096,
)Note on prefill chunk size: Many local serving frontends split prompts into smaller microbatches during prefill (
512tokens in older configurations, or2048tokens inmlx-lm's defaultprefill_step_size). A512-token step stays below DropSW's crossover thresholds (M >= 768quantized,M >= 1536dense), while2048caps FP16 recursion atk = 1(M < 3840). Settingprefill_step_size=4096(or8192) enables fullk = 2and input-fusion speedups on unified-memory Apple Silicon.
See examples/quickstart_mlx_lm.py for a runnable CLI benchmark, and examples/verify.py for a self-contained accuracy, outlier-peeling, and microbenchmark suite.
dropsw.patch_model(model, cfg) accepts an SWConfig object. Defaults are chosen to preserve model perplexity and avoid decode regressions:
from dropsw import SWConfig, patch_model
cfg = SWConfig(
enabled=True, # Toggle on/off live without re-patching
backend="metal", # "metal" (128-bit Metal kernels) or "pure" (zero custom shaders)
max_depth_fp16=2, # Strassen-Winograd depth for FP16 (k=1 at M>=1536, k=2 at M>=3840)
max_depth_bf16=1, # Capped at k=1 for BF16 numerical stability
min_M=1536, # Dense FP16/BF16/FP32 crossover threshold
min_M_quantized=768, # Q4/Q8 quantized crossover threshold
peel_head=1, # Peel row 0 (<bos>) to native GEMM/QMM to avoid outlier contamination
peel_head_mode="down_only", # Apply outlier peeling on down_proj layers
skip_peel_on_cache_offset=True, # Skip head peel when cache.offset > 0 (prefix cache / chunks 2..C)
peel_rows=None, # Optional list of sequence-start row indices for ragged batching
outlier_threshold=None, # Optional dynamic SIMD row_absmax multiple (e.g. 32.0) for non-row-0 sinks
shared_A=True, # Share FusedA transform across sibling gate_proj & up_proj
fuse_swiglu_A=False, # Optional: fuse SiLU(gate)*up -> down_proj FusedA (M >= 4096)
fuse_rmsnorm_A=False, # Optional: fuse RMSNorm -> FusedA on standard Llama blocks (M >= 4096)
)
patch_model(model, cfg)You can also call the operators directly without patching a model:
dropsw.sw_linear_matmul(A, W, depth=None, peel_head=0, peel_rows=None, outlier_threshold=None)— computesA @ W.Tfor 2DFP16/BF16/FP32tensors (depth=Noneauto-selectskusing DropSW's roofline dispatch thresholds).dropsw.pure_sw_linear_k1(A, W, peel_head=0)— shader-freek = 1Strassen–Winograd reference implementation using@mx.compileandmx.addmm.dropsw.sw_quantized_matmul(A, wq, scales, biases, N, K, bits, depth=None, group_size=64, peel_head=0, ...)— fuseddequant_fused_WT+ Strassen–Winograd for 4-bit/8-bit affine quantized weights.dropsw.sw_moe_matmul(A, W, min_M=1536, min_KN=2048)— 3D in-place 6th-leaf-fused batched matmul(B, M, K) @ (B, N, K).swapaxes(-1, -2)for coarse 3D batched GEMMs (auto-falls back to nativemx.matmulon fine-grained sparse MoEs).dropsw.sw_hybrid_7xB7_k2_f16(A, W, peel_head=0)— Hybrid7 × Batch7k = 2FP16 schedule (outer in-placek = 1+ inner 3DBatch7GEMMs).
Measured on Apple M4 Pro (20-core GPU, 64 GB, MLX 0.32.5, mlx-lm 0.32.2; speedup = +0.3–0.7 GB transient MLX peak allocator delta at S <= 4096 and 0% permanent weight RAM overhead):
| Model & Precision | S = 1024 |
S = 2048 |
S = 4096 |
S = 8192 |
Batched 4 × 2048 |
WikiText-2 ΔPPL |
|---|---|---|---|---|---|---|
| Llama-3.1-8B Q4 (FP16 act.) | 1.09× | 1.15× | 1.25× | 1.24× | — | -0.0004 |
| Llama-3.1-8B Q4 (BF16 act.) | 1.09× | 1.15× | 1.17× | 1.16× | — | 0.0000 |
| Llama-3.1-8B Q8 (FP16 act.) | 1.09× | 1.17× | 1.23× | 1.25× | — | -0.0001 |
| Llama-3.1-8B Q8 (BF16 act.) | 1.08× | 1.14× | 1.17× | 1.17× | — | +0.0037 |
| Qwen3.8-27B Q4/Q8 (BF16 act.) | 1.10× | 1.21× | 1.20× | — | — | -0.0035 |
| Llama-3.1-8B Dense FP16 | — | 1.06× | 1.10× | 1.12× | 1.13× (1.14×*) |
+0.0002 |
| Llama-3.1-8B Dense BF16 | — | 1.06× | 1.07× | 1.08× | 1.09× | +0.0006 |
*With fuse_swiglu_A=True and fuse_rmsnorm_A=True.
-
In-place transpose-aware quadrant transforms: Keeps
nn.Linearweights in native(N, K)row-major layout (NT), reads the three unmodified quadrants in place via 2D strided offsets (avoiding hidden slice copies atk = 2), and computes Winograd's four linear combinations in 128-bit vectorized Metal kernels (half8for FP16, bit-packed RNEuint4for BF16,float4for FP32). -
6th-leaf
addmmepilogue fusion: Folds 6 of the 7 output additions into MLXsteelmx.addmmepilogues and computesC11 = (U3 - U2) + U2M5insidePackC. -
Fused quantized dequantization (
dequant_fused_WT): Reads packed Q4/Q8 weights (group_size32 or 64) once, unpacks and forms Winograd's weight combinations in FP32 registers, and executes all$7^k$ leaf GEMMs at full densesteelspeed without storing dequantized weights permanently. -
Generalized
<bos>& massive-activation peeling (PackCStitch): Peels row 0 (or arbitrary sequence-start / SIMDrow_absmaxoutlier rows) plus tile-alignment remainder rows into a single native GEMM/QMM call, skips head peeling automatically whencache.offset > 0(prefix caching and continuation chunks), and preserves<bos>self-pairing on aligned power-of-two multi-prompt batches.
MIT License — see LICENSE.