Pidoku

Apple Silicon and MLX

Module 29 Lesson 29.c 1h 15m Difficulty 3/5

Prerequisites 29.a, 29.b, 8.d, 15.e, 14.g


Before you start: words you need#

WordPlain meaning
Apple siliconApple’s own SoCs: the A-series in iPhones and the M-series in Macs and iPads.
Neural Engine (ANE)Apple’s NPU: a fixed-purpose block for low-power matrix work, used mostly through Apple’s frameworks.
Neural AcceleratorsMatrix units inside each GPU core, new with the A19 and M5 generation. They speed up the GPU’s matrix multiplies, which is what prefill needs.
MetalApple’s GPU programming interface, the counterpart of CUDA.
MLXApple’s open-source array framework for Apple silicon (Python, Swift, C++), with mlx-lm for language models.
Lazy evaluationOperations are recorded, not run, until a result is actually needed; then the whole graph runs at once.
Foundation Models frameworkApple’s Swift API that gives every app access to the on-device Apple Intelligence model.
Core AIApple’s framework for running your own models on Apple silicon, introduced at WWDC26 as the successor path to Core ML for neural networks.

1. What is it?#

Apple silicon is the most common high-bandwidth, large-memory hardware outside the data centre: every Mac since 2020 and every recent iPhone and iPad. Its defining feature is unified memory: CPU, GPU and Neural Engine share one pool of LPDDR5X, so a Mac with 128 GB can give most of it to a model, and nothing is copied between processors.

Apple offers three ways to run models on it:

  1. The system model, through the Foundation Models framework: Apple’s own on-device model, shared by every app, with no download.
  2. Your own model through Apple’s frameworks: Core AI (WWDC26) and the older Core ML, which can use the CPU, GPU and Neural Engine.
  3. Your own model through open frameworks: MLX (Apple’s research framework), llama.cpp’s Metal backend (29.b), and on top of them Ollama, LM Studio and vllm-metal (15.e).

Versions on 13 November 2026: MLX v0.32.4 (14 October 2026), mlx-lm v0.32.2 (16 October 2026). Facts checked on 13 November 2026.


2. Why does it matter?#

  • Capacity at a desk. A Mac Studio with M5 Ultra holds 512 GB at 1.2 TB/s. No other single desk-side machine at that price holds a 400B-class model in memory (8.d).
  • Reach on phones. Hundreds of millions of iPhones run Apple’s on-device model. If your product is an iOS app, the Foundation Models framework is the cheapest model you will ever call.
  • Developer machines. Many inference engineers’ laptops are Macs; knowing what MLX and Metal can do lets you test real models locally.
  • A different design point. Apple bets on unified memory and modest bandwidth rather than fast-but-small GDDR. That bet makes mixture-of-experts models, long contexts and large models practical locally, at moderate speed.

3. Simple analogy#

A PC with a graphics card is a house with a garage workshop: the tools (GPU) are fast, but every part must be carried from the house (system RAM) to the garage (VRAM) over a narrow path (PCIe), and the garage is small. Apple silicon is an open-plan workshop: one big room where the CPU, GPU and Neural Engine all reach the same shelves. The room’s doors (bandwidth) are not the widest in town, but nothing is ever carried between rooms, and the room is big.


4. Tiny example: one MoE model on two Macs#

Qwen3-30B-A3B, 4-bit, stores about 17 GB and reads about 1.9 GB of weights per token (3.3B active parameters at 4.5 bits, 29.a).

MacBook Air M5, 16 GB, 153 GB/s
  macOS lets the GPU wire only part of RAM (about 2/3–3/4 by default)
  17 GB does not fit                                    → choose a smaller model

MacBook Pro M5 Max, 128 GB, 614 GB/s
  fits easily; decode ceiling 614 ÷ 1.9 ≈ 320 tok/s at short context
  Apple measured M5 vs M4 on this model in MLX: time to first token 3.52x faster,
  decode 1.25x faster

The M5’s gain is lopsided: the new GPU Neural Accelerators speed up compute-bound prefill a lot, while decode improves only with bandwidth (153 vs 120 GB/s on the base chips).


5. Technical explanation#

The hardware#

Inside an M-series or A-series SoC:

  • CPU: performance (“super”) and efficiency cores, with Arm matrix extensions (SME on M4 and later) that Accelerate and some kernels use.
  • GPU: Apple’s tile-based GPU, programmed through Metal. From A19 and M5, every GPU core has a Neural Accelerator, a matrix unit for FP16/BF16 and low-precision multiply-accumulate. MLX uses them through Metal 4’s tensor APIs on macOS 26.2 or later; its kernel files for them carry the suffix nax.
  • Neural Engine: 16 cores on most chips, 32 on Ultra and on A20 Pro (“dual 16-core”). Reached through Apple’s frameworks (Core ML, Core AI), not directly.
  • Unified memory: LPDDR5X on a wide bus, plus a large system-level cache.

The 2026 range:

ChipWhereMemoryBandwidth
A19 ProiPhone 17 Pro12 GB~77 GB/s (computed)
A20 ProiPhone 18 Pro (September 2026)not published by Applereported +50% over A19 Pro
M5MacBook Air/Pro, iPad Proup to 32 GB153 GB/s
M5 MaxMacBook Pro, Mac Studio36–128 GB460 GB/s (32-core GPU) or 614 GB/s (40-core GPU)
M5 UltraMac Studio (August 2026)96, 256 or 512 GB1.2 TB/s

One practical limit: macOS caps how much memory the GPU may wire. By default it is a share of RAM (roughly two-thirds to three-quarters, depending on size), so a 128 GB Mac cannot give all 128 GB to a model. Advanced users raise it with sudo sysctl iogpu.wired_limit_mb=<MB>; leave enough for the OS or the machine will swap.

MLX: what makes it different#

MLX looks like NumPy (mx.array, mx.matmul), with four ideas that matter for inference:

  1. Unified memory as a first principle. Arrays live in shared memory. You choose where an operation runs (stream=mx.gpu or mx.cpu), not where data lives. No .to(device) copies.
  2. Lazy evaluation. c = a @ b records an operation; mx.eval(c) runs the graph. This lets MLX fuse work and skip unused results, but it also means the line that “is slow” in a profile is often the eval, not the maths.
  3. Compilation. mx.compile traces a function and fuses element-wise operations into fewer Metal kernels, cutting launch overhead for decode, where each step is small.
  4. Composable transforms (grad, vmap), so the same framework fine-tunes (LoRA, DWQ) and serves.

MLX also has a CUDA backend, so the same code runs on NVIDIA GPUs, and mx.distributed for multi-machine work.

MLX quantization#

mlx.nn.quantize and mlx_lm.convert -q support four modes, from MLX’s source:

ModeDefault group sizeDefault bitsWhat it is
affine644integer weights with a scale and a bias per group of 64 (bits 2–8 allowed)
mxfp4324OCP microscaling FP4 (as used by gpt-oss)
nvfp4164NVIDIA’s FP4 with an FP8 scale per 16
mxfp8328microscaling FP8

Affine 4-bit with group 64 stores a 16-bit scale and a 16-bit bias per 64 weights: 4 + 32/64 = 4.5 bits per weight, like Q4_K in GGUF. Because MLX reads mxfp4 and nvfp4 natively, checkpoints quantized for data-centre GPUs run on a Mac without re-quantization (this is what Ollama’s MLX path relies on, 15.e).

mlx-lm adds:

  • Mixed recipes (--quant-predicate mixed_2_6, mixed_3_4, mixed_3_6, mixed_4_6): lower bits for most layers, higher for sensitive ones, the same idea as Q4_K_M (29.b).
  • Learned quantization (mlx_lm.dwq, mlx_lm.awq, mlx_lm.gptq, mlx_lm.dynamic_quant). DWQ (distilled weight quantization) fine-tunes the scales and biases of a quantized model to match the full-precision model’s outputs; the docs recommend it for 2–4-bit targets (29.f).

Running and serving with mlx-lm#

Shell
pip install mlx-lm
mlx_lm.convert --model Qwen/Qwen3-8B -q --q-bits 4 --q-group-size 64 --mlx-path qwen3-8b-4bit
mlx_lm.generate --model qwen3-8b-4bit --prompt "Explain unified memory in one paragraph."
mlx_lm.server --model qwen3-8b-4bit --port 8080      # OpenAI-compatible HTTP server

Useful knobs:

  • --max-kv-size n uses a rotating KV cache of n tokens: bounded memory, at a quality cost for long inputs.
  • --prefill-step-size n (default 2048) reads long prompts in chunks: smaller chunks lower peak memory.
  • mlx_lm.cache_prompt saves a long prefix’s KV cache to a file and reuses it across runs (12.m).

Several Macs as one machine#

mx.distributed supports a TCP ring backend, JACCL (RDMA over Thunderbolt 5, available from macOS 26.2, low enough latency for tensor parallelism), MPI, and NCCL on CUDA. With mlx.launch, two to four Mac Studios connected by Thunderbolt can split a model too big for one (14.c). The links are far slower than NVLink, so this suits holding a huge model at all rather than serving many users fast.

Apple’s own models and frameworks#

The Foundation Models framework (iOS, iPadOS, macOS 26 and later) exposes the on-device Apple Intelligence model to any Swift app:

swift
import FoundationModels

let session = LanguageModelSession(instructions: "You summarise support tickets in one sentence.")
let reply = try await session.respond(to: ticketText)
print(reply.content)

It adds guided generation (mark a Swift type @Generable and the model fills it, using constrained decoding), tool calling through a Tool protocol, and, from WWDC26, image input and the option to send requests to larger server models. Check SystemLanguageModel.default.availability first: the model exists only on Apple Intelligence devices with the feature turned on.

What runs underneath, from Apple’s own papers:

  • 2025 on-device model: about 3B parameters, split into two blocks with a 5:3 depth ratio where the second block reuses the first block’s KV cache (37.5% less KV memory); 2-bit weights trained with quantization-aware training, 4-bit embeddings, 8-bit KV cache, and low-rank adapters to recover the quality lost to compression.
  • 2026 (AFM 3, 8 June 2026): AFM 3 Core continues the ~3B dense model. AFM 3 Core Advanced is a 20B-parameter sparse model that activates 1–4B parameters per request, is natively multimodal, and is “unlocked by” only the most capable Apple silicon. Its full weights live in flash; shared experts are always active and routed experts are loaded into DRAM per prompt (see section 6). Server models (AFM 3 Cloud and Cloud Pro) run in Private Cloud Compute (29.g). Apple describes the family as “custom-built in collaboration with Google”.

Core AI (WWDC26, session “Meet Core AI”) is Apple’s framework for deploying your own models: the inference framework behind on-device Apple Intelligence, now open to apps. You convert a PyTorch torch.export program with the coreai-torch package to an .aimodel asset, compile it ahead of time in Xcode, and run it on CPU, GPU and Neural Engine from Swift. A Core AI language model can plug into the Foundation Models API, so an app can swap Apple’s model for its own behind the same interface. Core ML remains for existing models; its coremltools 9.0 (November 2025) is still the tool for palettization and other Core ML compression.

When to use which#

NeedUse
Summaries, extraction, classification in an iOS app, no downloadFoundation Models framework
Your own fine-tuned small model in an iOS app, low powerCore AI (or Core ML), so the Neural Engine can be used
Experiments, fine-tuning and serving large models on a MacMLX / mlx-lm
Same model file on Mac, Linux and Windowsllama.cpp (GGUF)
Several users or agents sharing one Macvllm-metal, or mlx_lm.server with a small batch

6. Under the hood: why a flash-resident model routes per prompt#

AFM 3 Core Advanced keeps 20B parameters in flash, which reads far more slowly than DRAM. A normal mixture-of-experts model (14.g) picks experts per token: if the experts change, they must be loaded before the token can finish. Apple’s design picks routed experts per prompt and re-selects them only periodically. This program shows why, with illustrative assumptions (Apple has not published the bit width, the split between shared and routed parameters, or flash read rates).

Go
// flash.go — why a sparse model kept in flash must route per prompt, not per token.
// All model and storage numbers are illustrative assumptions, not Apple's figures.
package main

import "fmt"

func main() {
	const (
		bitsPerWeight = 4.0   // assumed average after quantization
		sharedB       = 0.5   // always-resident parameters (billions): attention, shared experts
		routedB       = 1.5   // routed-expert parameters active for one request (billions)
		flashGBs      = 2.0   // assumed sustained flash read rate for scattered expert reads
		dramGBs       = 115.0 // phone LPDDR5X bandwidth
		answer        = 300   // tokens generated per request
	)
	gb := func(b float64) float64 { return b * bitsPerWeight / 8 }

	activeGB := gb(sharedB + routedB)
	dramCeiling := dramGBs / activeGB
	fmt.Printf("active weights per token: %.2f GB  →  DRAM decode ceiling %.0f tok/s\n\n", activeGB, dramCeiling)

	// Per-token routing (a normal MoE): some routed experts change every token
	// and must be fetched from flash before the token can finish.
	fmt.Println("per-token routing (MoE as trained for servers):")
	for _, churn := range []float64{0.05, 0.2, 0.5} {
		loadGB := gb(routedB) * churn
		tokenTime := loadGB/flashGBs + 1/dramCeiling
		fmt.Printf("  %3.0f%% of routed experts change per token: load %.3f GB/token → %5.1f tok/s\n",
			churn*100, loadGB, 1/tokenTime)
	}

	// Per-prompt routing: choose the routed experts once while reading the prompt,
	// load them once, then decode from DRAM.
	load := gb(routedB) / flashGBs
	decode := float64(answer) / dramCeiling
	fmt.Println("\nper-prompt routing (experts chosen once per request):")
	fmt.Printf("  one-time load %.2f GB → +%.2f s to time to first token\n", gb(routedB), load)
	fmt.Printf("  then %d tokens at the DRAM ceiling: %.1f s; whole answer %.1f s (%.0f tok/s overall)\n",
		answer, decode, load+decode, float64(answer)/(load+decode))
}

Output:

active weights per token: 1.00 GB  →  DRAM decode ceiling 115 tok/s

per-token routing (MoE as trained for servers):
    5% of routed experts change per token: load 0.038 GB/token →  36.4 tok/s
   20% of routed experts change per token: load 0.150 GB/token →  11.9 tok/s
   50% of routed experts change per token: load 0.375 GB/token →   5.1 tok/s

per-prompt routing (experts chosen once per request):
  one-time load 0.75 GB → +0.38 s to time to first token
  then 300 tokens at the DRAM ceiling: 2.6 s; whole answer 3.0 s (101 tok/s overall)

How to read it:

  • With per-token routing, even 5% churn drops decode to a third of the DRAM ceiling: flash, not DRAM, sets the pace. This is the problem “LLM in a flash” (Apple, 2023) attacked with caching and bundling; AFM 3 solves it in the model’s design instead.
  • With per-prompt routing the flash cost is paid once, inside time to first token, and decode runs at DRAM speed. The price is quality: the model must be trained so that one expert set serves a whole request. That is a model-architecture decision made for the device, not a runtime trick.
  • The same reasoning explains Gemma 4’s memory-mapped per-layer embeddings (29.a): put in flash what is read rarely or predictably, keep in DRAM what every token needs.

7. Performance implications#

  • Decode follows bandwidth. Apple’s own M5 vs M4 MLX measurements show 1.19–1.27x faster decode, close to the 153 ÷ 120 bandwidth ratio, across dense, MoE and MXFP4 models.
  • Prefill follows the Neural Accelerators. The same measurements show 3.33–4.06x faster time to first token. On M5-generation Macs, long prompts stop being the bottleneck they were on M1–M4.
  • MoE models are the sweet spot for Max and Ultra machines: capacity is plentiful, bandwidth modest, and active parameters are few.
  • Lazy evaluation hides cost. Profile around mx.eval, and use mx.compile for the decode step.
  • Thermals differ by enclosure. A fanless MacBook Air throttles under sustained generation; a Mac Studio does not. Benchmark in the enclosure you will ship on.
  • Neural Engine vs GPU. For your own models, the Neural Engine saves power at batch 1 for models it supports well; the GPU is more flexible and usually faster for large LLMs. Core AI chooses per operation; measure power, not just speed.

8. Production implications#

  • iOS apps: start with the Foundation Models framework; ship your own model only when it is clearly better for the task. Your own model costs download size, memory you compete for, and updates.
  • Check availability at runtime: devices without Apple Intelligence, or with it switched off, have no system model. Design the fallback (29.g).
  • Apple’s model changes with the OS. Its behaviour can shift with an iOS update; keep a regression suite of your prompts and expected outputs and run it on new OS betas (28.d).
  • On Macs for teams, a Mac Studio running mlx_lm.server or vllm-metal is a cheap, quiet, private endpoint for a few users. It is not a substitute for a GPU server for many users (15.e).
  • Pin MLX and mlx-lm versions: both release often, and quantized formats have changed across versions.

9. Common mistakes#

  1. Assuming all RAM is usable by the GPU. macOS caps wired GPU memory.
  2. Timing MLX code without mx.eval. Without it, nothing has run yet.
  3. Comparing an M5 to an M4 on decode only. The big change is prefill.
  4. Expecting the Neural Engine to run any model. It runs what Apple’s compilers support, and LLMs often run on the GPU instead.
  5. Treating the Foundation Models framework as a general chatbot. Apple positions the on-device model for focused tasks (summaries, extraction, classification), not world knowledge.
  6. Shipping an mxfp4 or nvfp4 MLX model to an older MLX that does not support the mode.

10. Hands-on exercise#

  1. Run flash.go. Raise flashGBs to 6 and lower it to 0.5. At what flash speed does per-token routing with 5% churn reach half the DRAM ceiling?
  2. Change answer to 30 tokens. Is per-prompt routing still a clear win? What does that say about short replies such as notifications?
  3. On a Mac, convert one model with mlx_lm.convert in affine 4-bit, mxfp4 and mixed_3_6. Compare file size, mlx_lm.benchmark numbers and the outputs on ten prompts you care about.
  4. Write a ten-line Swift program with the Foundation Models framework that extracts a @Generable struct (name, date, amount) from a receipt text. How often does it fail to fill a field?
  5. If you have two Macs with Thunderbolt 5, run a model with mlx.launch over the ring and JACCL backends and compare tokens per second.

11. Interview questions#

  1. What does unified memory change for local inference, and what does it not change?
  2. Why did the M5 speed up time to first token about 4x but decode only about 1.25x?
  3. What are MLX’s four quantization modes, and why does native nvfp4 support matter?
  4. Explain why a 20B sparse model stored in flash routes experts per prompt rather than per token.
  5. An iOS team asks whether to ship their own 3B model or use the Foundation Models framework. What do you ask, and what do you recommend by default?

12. Further reading#

Checked on 13 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in