Training an LLM in Swift, Part 1: Taking matrix mult from Gflop/s to Tflop/s
TL;DR Highlight
Tuning handwritten Swift matmul brought LLM training to par with C's llm.c
Who Should Read
A developer writing numeric code in Swift on Apple Silicon who is struggling with poor performance
Core Mechanics
- Basic Swift was far slower than llm.c
- The C version takes about 7 seconds per training iteration and under 1 token/s for inference.
- Basic Swift trained at 7.3% of llm.c speed, about 2.8 Gflop/s.
- Generation was about one token every 19 seconds.
- mutableSpan beat Array by 3x
- Instruments showed _ArrayBuffer.beginCOWMutation() uniqueness checks as the biggest cost.
- Wrapping out with out.mutableSpan raised training from 7.3% to 24.0% of llm.c.
- The forward pass barely changed.
- Relaxed.multiplyAdd enabled FMA
- C uses the fmadd instruction thanks to -ffast-math, while Swift emitted separate multiplies and adds.
- Swift-Numerics' Relaxed fixed this.
- Inference went from 0.056 to 0.533 tokens/s (about 10x) and training reached 85.1% of llm.c.
- InlineArray mimicked C's 8x unrolling
- The real C code keeps a result[8] buffer and strides the outer loop by 8.
- Swift 6.2's InlineArray<8, Float> acts as a stack array.
- Result: 0.918 tokens/s inference and 0.189 iter/s training, 106.6% of llm.c for training.
- Multithreading used DispatchQueue.concurrentPerform
- TaskGroup had similar speed but forced the buffer pointer to escape its closure, with no benefit.
- concurrentPerform's closure is non-escaping, so Span passes without copying.
- It still needs withUnsafeMutableBufferPointer and an @unchecked Sendable wrapper, which clutters the code.
Community Reactions
- Opinion on whether 1.1 Tflop/s is good
- A commenter says the M3 Max GPU is theoretically about 15 Tflop/s but the realistic ceiling here is 3-5 Tflop/s.
- They say basic GPU benchmarks shouldn't be taken too seriously.
- Opinion to use -ffp-contract=fast instead of -ffast-math
- A commenter says -ffp-contract=fast is the right flag for FMA in both gcc and clang.
- They say -ffast-math enables other transformations that hurt accuracy, so outside ML and graphics only experts should use it.
- Info that Xcode's clang can compile OpenMP
- A commenter says you can supply libomp.dylib and headers yourself.
- They point to builds distributed by the R project at mac.r-project.org/openmp.
- Remark on the bias? branch in the inner loop
- A commenter says it was the worst offender from the start.
How to Apply
- Wrap hot-loop arrays in mutableSpan
- If _ArrayBuffer.beginCOWMutation() ranks high in Instruments, add var out = out.mutableSpan at the top of the function.
- Compare timings before and after on Swift 6.2+ in Release.
- Apply Relaxed.multiplyAdd to accumulations
- Add Swift-Numerics and replace a += b * c with Relaxed.multiplyAdd(b, c, a).
- Skip functions where accuracy matters and compare results against the old version.
- Unroll with an InlineArray result buffer
- Replace in-loop Array allocations with InlineArray<8, Float>.
- Drive the outer loop with stride(from:to:by: 8) to process tiles.
- Parallelize tiles with DispatchQueue.concurrentPerform
- Split tiles into chunks based on activeProcessorCount and pass them to concurrentPerform.
- Wrap the output buffer with withUnsafeMutableBufferPointer and a Sendable wrapper.
Try It
// Paste into Claude or ChatGPT as is (the article's method turned into a prompt)
Improve the performance of the Swift 6.2 function below. Apply these steps one at a time and show the code after each step.
1. Wrap the array argument out with var out = out.mutableSpan to remove COW uniqueness-check cost.
2. Replace accumulations of the form a += b * c with Swift-Numerics' Relaxed.multiplyAdd(b, c, a) to get FMA.
3. Keep results in an InlineArray<8, Float> and stride the outer loop by 8 to unroll.
4. Finally, parallelize by tiles with DispatchQueue.concurrentPerform.
Do not use Relaxed in functions where accuracy matters, and explain why.
{{Swift function to optimize}}Terminology
Related Papers
A Beginner's Guide to Local AI with Inkling, Qwen, and Unsloth
Install Unsloth Desktop, load a quantized Qwen model, and share a private ChatGPT-like AI on your home LAN.
Muru – AI-assisted Rust server for Python apps by mod_WSGI's creator
mod_wsgi's creator is building Muru, an AI-assisted Rust ASGI/WSGI server, documenting it in public
87% of the Anthropic power will come from gas and 11% from coal in 2028
Analysis of Anthropic's contracted data centers: 87% gas, 11% coal power in 2028
Anthropic’s Nasdaq debut
Anthropic listed on Nasdaq and closed its first day below its opening price.
OpenAI still has a WebRTC Problem
WebRTC drops late audio, hurting voice AI; MoQ retransmits and buffers instead
Gemini 4 Neon
Gemini 4 Neon cuts cost per task 32% versus Carbon, at $3 input and $15 output per million tokens
AI is killing All About Berlin
After Google AI Overviews, a Berlin guide site lost 70-75% of its traffic.
Not Everything Needs an LLM
PostHog used small decision models to skip 98.7% of expensive LLM calls