Skip to content
efficientPublic

About

Drop-in Strassen-Winograd shim layer for MacOS M1-M4 LLM serving

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

DropSW

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.

Installation

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.

Quick Start (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 (512 tokens in older configurations, or 2048 tokens in mlx-lm's default prefill_step_size). A 512-token step stays below DropSW's crossover thresholds (M >= 768 quantized, M >= 1536 dense), while 2048 caps FP16 recursion at k = 1 (M < 3840). Setting prefill_step_size=4096 (or 8192) enables full k = 2 and 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.

Configuration

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)

Standalone Matrix Multiply APIs

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) — computes A @ W.T for 2D FP16/BF16/FP32 tensors (depth=None auto-selects k using DropSW's roofline dispatch thresholds).
  • dropsw.pure_sw_linear_k1(A, W, peel_head=0) — shader-free k = 1 Strassen–Winograd reference implementation using @mx.compile and mx.addmm.
  • dropsw.sw_quantized_matmul(A, wq, scales, biases, N, K, bits, depth=None, group_size=64, peel_head=0, ...) — fused dequant_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 native mx.matmul on fine-grained sparse MoEs).
  • dropsw.sw_hybrid_7xB7_k2_f16(A, W, peel_head=0) — Hybrid 7 × Batch7 k = 2 FP16 schedule (outer in-place k = 1 + inner 3D Batch7 GEMMs).

End-to-End Prefill Speedups (mlx-lm, Apple M4 Pro)

Measured on Apple M4 Pro (20-core GPU, 64 GB, MLX 0.32.5, mlx-lm 0.32.2; speedup = $t_{\text{native}} / t_{\text{DropSW}}$, higher is better; zero decode regression; +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.

How It Works

  1. In-place transpose-aware quadrant transforms: Keeps nn.Linear weights in native (N, K) row-major layout (NT), reads the three unmodified quadrants in place via 2D strided offsets (avoiding hidden slice copies at k = 2), and computes Winograd's four linear combinations in 128-bit vectorized Metal kernels (half8 for FP16, bit-packed RNE uint4 for BF16, float4 for FP32).
  2. 6th-leaf addmm epilogue fusion: Folds 6 of the 7 output additions into MLX steel mx.addmm epilogues and computes C11 = (U3 - U2) + U2M5 inside PackC.
  3. Fused quantized dequantization (dequant_fused_WT): Reads packed Q4/Q8 weights (group_size 32 or 64) once, unpacks and forms Winograd's weight combinations in FP32 registers, and executes all $7^k$ leaf GEMMs at full dense steel speed without storing dequantized weights permanently.
  4. Generalized <bos> & massive-activation peeling (PackCStitch): Peels row 0 (or arbitrary sequence-start / SIMD row_absmax outlier rows) plus tile-alignment remainder rows into a single native GEMM/QMM call, skips head peeling automatically when cache.offset > 0 (prefix caching and continuation chunks), and preserves <bos> self-pairing on aligned power-of-two multi-prompt batches.

License

MIT License — see LICENSE.

About

Drop-in Strassen-Winograd shim layer for MacOS M1-M4 LLM serving

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages