>_faiz.palwala

The Hitchhiker's Guide to Apple Silicon

November 18, 2026[Tech]

The 5 Immutable Laws of Sub-Byte GEMV and Metal GPU Architecture


The Prologue: When CUDA Lore Leads You Astray

For the last decade, high-performance GPU programming had a single default: NVIDIA hardware. Kudos to CUDA. It earned that dominance through the genuine affection of the developer community and sheer, compounding market share. Warps, shared memory banks, constant cache broadcast serialization, and streaming multiprocessor thread schedules became the universal vocabulary of systems engineering.

But the engineering reality on the ground has shifted. Modern AI deployment is no longer confined to monolithic server racks running FP16 matrix multiplies. We are operating across fundamentally different silicon paradigms, and NVIDIA is no longer the only hardware platform developers are targeting.

When engineers port sub-byte matrix multiplication kernels to Apple Silicon, they instinctively bring that CUDA muscle memory along:

  • Staging lookup tables in threadgroup memory to prevent broadcast stalls.
  • Double-buffering activation tiles in shared SRAM to hide memory latency.
  • Assembling packed vector registers in software before dispatching instructions.

On Apple Silicon, almost every single one of those textbook optimizations makes your kernel slower.

This is the fundamental pitfall of approaching kernel engineering like high-level software development: assuming algorithmic optimizations are portable across silicon. In GPU systems, you don’t optimize abstract algorithms; you optimize physical hardware constraints. What unlocks peak throughput on a discrete CUDA streaming multiprocessor actively degrades performance on unified Apple Silicon.

During the engineering of mlx-ternary (a native runtime executing 1.58-bit ternary matrix-vector multiplications for M = 1 autoregressive decode on Apple Silicon), we ran over 300 atomic kernel ablations on bare-metal Apple M4 Pro hardware with an empirical DRAM ceiling of 255.07 GB/s.

These are the 5 Immutable Laws that emerged from the telemetry.


Law 1: The Sacred 32-Register Occupancy Threshold

The Law: Never permit thread register allocation to exceed 32 registers in M = 1 autoregressive decode. High warp occupancy is the sole hardware mechanism capable of hiding DRAM latency.

The Hardware Mechanism

Apple Silicon execution units feature a unified physical register file partitioned across executing threads. When a Metal kernel allocates ≤ 32 32-bit registers per thread, the execution unit maintains 100% warp occupancy, allowing 16 to 24 SIMD warps to interleave instruction issue concurrently.

The moment register pressure pushes allocation into the 33–48 register range, the hardware thread scheduler automatically drops active occupancy by 50%.

In compute-bound batched GEMM (M ≥ 32), higher register pressure can be tolerated because high arithmetic intensity hides execution latency. But in M = 1 autoregressive decode, arithmetic intensity is < 2 FLOP/byte. There is virtually zero compute to hide latency behind; concurrent threadgroup interleaving is the single physical mechanism that hides DRAM fetch latency.

Empirical Ablation: Shared Memory Activation Double-Buffering

In classical GPU engineering, double-buffering activations across shared memory is standard practice. We implemented an activation double-buffer (shared_act[2][128]) with prefetching to overlap DRAM latency with arithmetic contraction and cut threadgroup synchronization barriers from 80 down to 40 per layer.

Kernel Variant Latency (µs) DRAM Throughput Active Register Footprint Delta
Single-Buffer Baseline (Lean Registers) 280.33 µs 79.48 GB/s ~24 Regs (100% Occupancy) Reference
Double-Buffered Kernel (Prefetch) 306.39 µs 72.72 GB/s ~46 Regs (50% Occupancy) +26.41 µs (+9.4% Regression)

Holding current and prefetch vector pointers (cur_vec0/1 and next_vec0/1) live across loop boundaries pushed register allocation to ~46 registers. The resulting 50% occupancy collapse destroyed memory latency hiding. Because an unrolled 128-element dot-product block completes in roughly 30 ALU cycles, there is insufficient arithmetic slack to hide DRAM fetch latency anyway.

The Invariant: In low-batch GEMV, lean register allocation (≤ 24 registers) and maximal warp occupancy beat algorithmic software pipelining every single time.


Law 2: The L1 Constant Cache Invariant (The Anti-CUDA Law)

The Law: Small static lookup tables (< 4 KB) reside hot in Apple’s private L1 Instruction/Read-Only Cache. Copying them to threadgroup SRAM yields zero read speedup and introduces barrier and memory copy overhead.

The Hardware Mechanism

In CUDA architecture, __constant__ memory relies on a broadcast cache that serializes divergent warp accesses across successive clock cycles, forcing practitioners to stage lookup tables into shared memory (SRAM) to utilize independent memory banks. Apple Silicon inverts this constraint: static compile-time tables in the constant address space (base3_lut_low) map directly into the GPU core’s private, multi-ported L1 Instruction/Read-Only Cache (KCache). This provides high-bandwidth parallel throughput on-die, eliminating the need to burn threadgroup SRAM or stall on synchronization barriers.

Empirical Ablation: Threadgroup SRAM vs. L1 Constant Address Space LUT

We staged our 243-entry ternary weight lookup table (1,944 bytes) into 32-bank threadgroup SRAM:

Kernel Variant Latency (µs) DRAM Throughput Synchronization Overhead Delta
Production constant Address Space 291.06 µs 76.56 GB/s 0 Barriers (Direct L1 Hit) Reference
Aligned Vector SRAM LUT 290.82 µs 76.62 GB/s 1 Cooperative Barrier -0.24 µs (Flat)
Uncoalesced threadgroup SRAM LUT 315.07 µs 70.72 GB/s Bank Conflicts + Startup Barrier +24.01 µs (+8.3% Regression)

Because the 243-entry table occupies less than 2 KB, it never leaves the on-core L1 cache. Moving it to threadgroup SRAM forced all 128 threads to execute cooperative copy loops and stall on an explicit threadgroup synchronization barrier, gaining zero memory access speed in return.

The Invariant: Keep static lookup tables in constant space. Do not waste SRAM or synchronization cycles attempting to outsmart Apple’s L1 cache hierarchy.


Law 3: The Load/Store Issue Slot Bottleneck

The Law: Scalar memory loads consume the identical instruction issue bandwidth as 128-bit vector loads. Sub-byte memory accesses must be chunked to natural SIMD vector boundaries.

The Hardware Mechanism

In Apple Silicon execution units, instruction fetch and dispatch pipelines are finite. A single-element 16-bit scalar load (half) consumes one full load/store instruction dispatch slot. A 4-element 64-bit vector load (half4) or a 128-bit vector load (uint4) also consumes exactly one instruction dispatch slot.

When sub-byte unpacking logic issues scalar memory reads, the execution unit’s Load/Store Unit (LSU) starves the arithmetic pipelines, leaving dual-issue ALUs idling while waiting for memory address generation.

Empirical Ablation: 20-Trit Vector Chunking vs. Scalar Unrolling

In 1.58-bit ternary quantization, 5 trits pack into 1 byte (3^5 = 243 ≤ 256). Naive unrolling indexes memory in strides of 5 elements (curr_x = i * 5). Because 5 does not align with 8-byte or 16-byte vector boundaries, the Metal compiler emits scalar loads: 130 scalar loads per 128-element contraction block.

We restructured the memory access pattern around 20-trit vector chunking:

4 packed bytes × 5 trits = 20 trits = 5 × half4 vector loads
Memory Access Strategy Latency (µs) DRAM Throughput LSU Instructions / Block Delta
Naive Striding (130 Scalar Loads) 301.56 µs 73.89 GB/s 130 Instructions Reference
Register-Scoped 20-Trit Chunking 279.71 µs 79.66 GB/s 16 Vector Instructions -21.84 µs (-7.2% Speedup)
Bulk 20-Trit Vector Chunking 278.44 µs 80.03 GB/s 16 Vector Instructions -23.12 µs (-7.7% Speedup)

By replacing scalar loads with contiguous half4 vector loads, total memory load instructions dropped by 75% (from 130 down to 16 instructions per block). This uncapped the LSU pipeline and allowed the kernel to surpass 80 GB/s streaming throughput.

The Invariant: Always align memory reads to vector boundaries (half4, uint4). Reorganize unpacking strides mathematically so the compiler emits vector load instructions.


Law 4: Native Operand Collectors vs. Software Vector Packing

The Law: Apple execution units extract sub-vector components natively at zero cycle cost. Reassembling packed vectors in software introduces severe register permutation stalls.

The Hardware Mechanism

Apple execution units include dedicated hardware operand collector circuits. When an instruction references a sub-component of a vector register (such as .x, .y, .z, or .w from a half4), the operand collector routes the specific 16-bit lane directly into the ALU input operand bus with zero latency penalties.

Conversely, attempting to reassemble scattered scalar components into a synthetic vector in software at runtime forces the compiler to emit a cascade of bitwise shift, mask, and register-permute instructions.

Empirical Ablation: Hardware Component Slicing vs. Software Vector Packing

Because 5 trits do not evenly divide into 4-component vectors, 20-trit chunking produces boundary straddles across bytes 1, 2, and 3. We evaluated assembling those 20 straddled weights into 5 synthetic half4 vectors prior to running vector dot products (half4(w0_high, w1_low.x, ...)):

Lane Extraction Strategy Latency (µs) Arithmetic Instructions Pipeline Efficiency Delta
Hardware Operand Collector Slicing 330.27 µs Minimal (Direct Bus Routing) 100% ALU Saturation Reference
Software Vector Reassembly (half4(...)) 645.07 µs Cascade Shifts / Bit Permutes LSU & ALU Stalls +314.80 µs (+95.3% Regression)

Attempting to construct synthetic vector types in software exploded the dynamic instruction count by nearly double. The execution units spent more cycles shuffling register bits than computing multiply-accumulate operations.

The Invariant: Never assemble vector primitives in software at runtime. Feed individual scalar component references (reg.x, reg.y) directly into arithmetic instructions.


Law 5: The 3-Cycle Dual-Issue Pipeline and RAW Hazard Decoupling

The Law: Apple M-series FP16 ALUs run a 3-cycle pipeline latency. Rotating dot-product accumulation across 4 independent registers eliminates Read-After-Write (RAW) stall bubbles.

The Hardware Mechanism

Apple Silicon GPU cores provide dual-issue FP16 execution units capable of firing two Fused Multiply-Accumulate (fma) instructions per cycle per core. However, each individual fma instruction has an execution pipeline latency of 3 clock cycles.

When a loop accumulates results into a single target variable:

acc += weight * activation;

every successive instruction depends on the register writeback of the immediately preceding operation. The execution unit stalls for 2 clock cycles between consecutive issues, dropping ALU efficiency to one-third of theoretical throughput.

Empirical Ablation: 4-Way ILP Accumulator Splitting vs. Single Accumulator

We split accumulation across 4 independent register variables (acc0, acc1, acc2, acc3), rotating issues sequentially before performing a single final reduction at block termination:

Accumulation Architecture Latency (µs) DRAM Throughput Pipeline Stalls Delta
Single Accumulator Baseline (acc += ...) 301.56 µs 73.89 GB/s 2 Cycles per Issue Bubble Reference
4-Way Accumulator Rotation (acc0..3) 282.47 µs 78.88 GB/s Continuous Dual-Issue Fill -19.08 µs (-6.3% Speedup)

Breaking the RAW dependency chain permitted the Apple hardware instruction scheduler to issue independent FMAs concurrently, filling the 3-cycle execution pipeline without spilling beyond the 32-register occupancy threshold.

The Invariant: Rotate inner-loop dot-product accumulation across 4 independent registers, then reduce once when exiting the tile.


Silicon Foresight: Designing for Hardware-Elastic Scaling

Most experienced systems engineers already understand that production software shouldn’t be hardcoded for a single testbed machine. On Apple Silicon, however, the disparity across a single processor family isn’t a minor clock frequency delta. It is a 4x to 8x explosion in GPU execution unit core counts sharing a unified memory fabric:

Generation / Chip Tier GPU Cores Memory Bandwidth (Theoretical / Empirical) Static Dispatch (N = 5120) Hardware Saturation State
Apple M4 Pro (Testbed) 20 Cores 273 GB/s / 255.07 GB/s empirical 40 Threadgroups 2.0 Threadgroups / Core (Balanced Saturation)
Apple M4 Max 40 Cores 546 GB/s / ~490 GB/s empirical 40 Threadgroups 1.0 Threadgroup / Core (Marginal Latency Hiding)
Apple M5 Pro 20 Cores 307 GB/s theoretical 40 Threadgroups 2.0 Threadgroups / Core (Balanced Saturation)
Apple M5 Max 40 Cores 614 GB/s theoretical 40 Threadgroups 1.0 Threadgroup / Core (Marginal Latency Hiding)
Apple M5 Ultra 80 Cores ~1,228 GB/s (1.2 TB/s) theoretical 40 Threadgroups 50% Core Starvation (40 Cores Completely Idle)
Future M6 / Extreme (Est.) 128+ Cores > 1,800 GB/s (1.8 TB/s) theoretical 40 Threadgroups Severe Hardware Underutilization

A static kernel configuration that yields optimal occupancy on an M4 Pro leaves wide-die chips like the Max and Ultra severely starved of work.

To maintain scale invariance across device tiers, matrix contraction runtimes should treat grid dimensions as an elastic function of device telemetry: querying active GPU core counts at runtime and sizing dispatch geometry to preserve a lower bound of ≥ 2.0 Threadgroups per active GPU Core.


The Modern Developer Companion: Stop Your AI Agent from Writing CUDA on Apple Silicon

Today, a significant portion of GPU shader code is drafted or refactored alongside AI coding agents (Antigravity, Cursor, Claude Code).

The issue is systemic: LLMs have ingested a decade of NVIDIA CUDA documentation, blog posts, and StackOverflow threads, but only a fraction of Apple Metal systems literature.

When you ask an agent to “optimize this Metal kernel,” its default instinct is to hallucinate CUDA idioms: it stages lookup tables in threadgroup memory, introduces software double-buffering, and packs synthetic vector structs in register space.

To prevent your agent from introducing regressions, you can enforce these 5 Laws as deterministic invariants in your repository.

Drop-In AGENTS.md / .cursorrules Guardrail

# Apple Silicon & Metal Kernel Development Invariants (The Anti-CUDA Rulebook)

When authoring or optimizing Apple Metal Shading Language (MSL) compute kernels or MLX custom extensions, you MUST strictly adhere to the following physical hardware invariants:

1. The 32-Register Occupancy Rule (M=1 Autoregressive Decode):
   - In single-token decode or low-batch matrix-vector operations (GEMV), strictly limit live variables to preserve <= 32 physical registers per thread.
   - Do NOT implement software double-buffering or multi-column unrolling if it increases live register pressure past 32 registers. High threadgroup occupancy is the sole hardware mechanism that hides DRAM latency.

2. The L1 Constant Cache Invariant:
   - NEVER copy small static lookup tables (< 4 KB) into threadgroup memory.
   - Declare static tables in the constant address space. Apple Silicon caches static constant tables in private on-core L1 KCache with single-cycle parallel access. Do not introduce threadgroup copy loops or barriers.

3. LSU Issue Slot Alignment:
   - Memory load instructions consume execution unit issue slots equally regardless of bit-width. NEVER write scalar unpack loops (half, char).
   - Restructure sub-byte packing patterns into natural 64-bit or 128-bit vector boundaries (half4, uint4) to minimize Load/Store Unit instruction dispatch overhead.

4. Zero-Cycle Sub-Vector Component Extraction:
   - NEVER assemble synthetic vector types (half4(...)) in software before arithmetic dispatch.
   - Rely on Apple's native hardware operand collectors by referencing scalar lanes directly (val.x, val.y) in arithmetic calls.

5. 3-Cycle FMA Latency Decoupling:
   - Apple FP16 ALUs run a 3-cycle execution pipeline. NEVER accumulate inner-loop dot products into a single scalar register (acc += ...).
   - Rotate inner-loop accumulation across 4 independent registers (acc0..3) to eliminate Read-After-Write (RAW) stall bubbles, and reduce once at tile exit.

6. Hardware-Elastic Grid Sizing:
   - NEVER hardcode static grid or threadgroup dispatch dimensions.
   - Query the active GPU execution unit core count at runtime and ensure the grid allocates at least >= 2.0 threadgroups per active GPU core to avoid starvation on Max/Ultra chips.

You can download this ready-to-use rule directly into your projects:
📥 Download apple-silicon-metal.cursorrules


Epilogue: Physics Over Heuristics

Engineering for Apple Silicon requires discarding desktop GPU heuristics in favor of empirical hardware measurements. When you design around the physical realities of unified memory, multi-ported L1 caches, and dual-issue ALUs, Apple Silicon finally unlocks its full potential: an incredible compute and memory envelope delivering server-grade throughput, running completely silent at 30 watts.