# xFermat Technical White Paper (`v0.7.0`)

**Algebraic Weight-and-KV Compression with Hardware-Aware Dispatch on Unified-Memory Apple Silicon**

- **Document ID:** `XF-WP-2026-07`
- **Version:** `v0.7.0` (November 2026)
- **Hardware Reference:** `Apple Silicon Unified GPU (applegpu_g14g, 8 GB)` (`5.33 GB` max recommended working set, `mlx 0.32.4`, `mlx-lm 0.32.2`)
- **Verification Suite:** `59/59` automated unit & integration tests (`tests/test_fermat.py`, `tests/test_academic_fixes_v07.py`, `tests/test_api_v07.py`, `tests/test_kivi_v07.py`, `tests/test_quant_v07.py`, `tests/test_surgery_v07.py`), streamed $16,384 > D_{\text{max}}$ calibration tokens ($D_{\text{max}} \in [4864, 11008]$), full $301,680$-token `WikiText-2` test set (`0.5B`) + $65,504$-token test set (`1.1B`, `1.5B`, `3B`) at 2048 context, 4 downstream multiple-choice tasks ($n=100 \pm \text{stderr}$), 5-run median $\pm$ IQR statistics, and reproducible public benchmark artifacts ([`benchmarks/v07_rigorous_results.json`](benchmarks/v07_rigorous_results.json))

---

## Executive Summary

Consumer workstations built on unified-memory Apple Silicon architectures share a single physical memory pool between CPU and GPU. While this eliminates discrete PCIe host-to-device transfer latency, local autoregressive LLM inference is strictly governed by physical **memory capacity** and **effective memory bandwidth** (measured at $\sim 63\text{--}84\text{ GB/s}$ sustained streaming bandwidth across models, peaking at $84.0\text{ GB/s}$ on `TinyLlama-1.1B` BF16), rather than raw FP16 computational throughput. On an `8 GB` system with a $5.33\text{ GB}$ maximum recommended GPU working set, running larger models or multi-thousand-token context windows rapidly exhausts available RAM, triggering catastrophic operating system swap thrashing or outright Out-Of-Memory (OOM) process termination.

Standard open-source quantization toolkits confront practitioners with severe compromises:
1. Scalar round-to-nearest (RTN) quantization destructively clips activation outlier channels, collapsing perplexity at 3-bit (`mlx_native_3bit` $39.12$ vs $14.42$ BF16 on `Qwen2.5-0.5B-Instruct`) and outputting pure noise at 2-bit ($56,956.39$ PPL).
2. Sub-3-bit vector quantization and codebook search historically suffered massive atomic lock contention and catastrophic out-of-domain degradation.
3. Linear-algebra accelerations from academic literature (Winograd–Strassen, rank-48 tensor decompositions, ternary bit-slicing, modular rings) frequently exhibit slower wall-clock execution than vendor Metal GEMMs on dense matrices when launched without hardware-aware empirical calibration.

**xFermat** resolves this engineering challenge by synthesizing **18 foundational publications (15 peer-reviewed venue papers and 3 arXiv preprints)** into five interlocking subsystems paired with custom Metal Shading Language kernels and an empirical shape autotuner ([`FermatEngine`](src/fermat/engine.py)):

1. **Outlier-Free 3-Bit & 4-Bit Weight Surgery (`Clip-GPTQ`):** Combines offline $R_1$ randomized block-Hadamard rotations folded directly into normalization weights with on-chip $R_4$ Walsh–Hadamard transforms, full-rank Hessian Cholesky error compensation ($N=16,384 > D_{\text{max}}$, `damp=0.05`), and per-row group scale clipping. On `Qwen2.5-0.5B-Instruct`, xFermat 4-bit delivers **$15.20$** full `WikiText-2` PPL ($301,680$ tokens) at **$181.8 \pm 3.9\text{ tok/s}$** ($62.9\text{ GB/s}$ effective bandwidth), improving perplexity over `mlx_lm.awq` ($16.06$ PPL, $173.4\text{ tok/s}$) at decode throughput parity. xFermat 3-bit achieves **$17.99$** PPL and held-out KL $0.606$ in $287.6\text{ MB}$, outperforming `mlx_lm.awq` ($23.27$ PPL, $0.848$ KL) while preserving comparable downstream reasoning accuracy ($34.0\%$ vs $27.0\%$ ARC-Challenge, $71.0\%$ vs $65.0\%$ PIQA; $53.0\%$ vs $56.0\%$ ARC-Easy).
2. **Untied Head Acceleration & Genuine 3B Memory Recovery:** Introduced `--head-bits 8` for untied vocabulary projections, lifting `TinyLlama-1.1B` 3-bit xFermat decode speed from an FP16-head bottleneck by **$+59.5\%$** ($61.4 \rightarrow 98.0\text{ tok/s}$, at identical $9.62$ PPL, vs. $97.9\text{ tok/s}$ native RTN and $120.7\text{ tok/s}$ AWQ). On `Qwen2.5-3B-Instruct`, where BF16 static weights ($5,886\text{ MB}$ / $\sim 5.75\text{ GiB}$) exceed the $5.33\text{ GiB}$ system working-set limit causing OOM, xFermat compresses the model to $1.80\text{ GB}$ (4-bit, $9.43$ PPL @ $27.8\text{ tok/s}$), $1.47\text{ GB}$ (3-bit, $10.42$ PPL @ $29.1\text{ tok/s}$), and $1.19\text{ GB}$ (mixed 2/3-bit, $16.01$ PPL @ $56.9\text{ tok/s}$), restoring local execution within unified memory limits.
3. **GQA-Packed KIVI KV Cache Scaling to 16K Context:** Promotes the top $62.5\%$ salient Key channels per 64-token block to 4-bit (remaining $37.5\%$ at 2-bit), quantizes Values 2-bit per-token, and keeps a 64-token FP16 streaming tail ($3.16\text{ bpw}$). On `Qwen2.5-1.5B-Instruct`, xFermat Mixed KIVI maintains **$5/5$ ($100\%$) Passkey retrieval** through $4K$, $8K$, and $16K$ tokens, shrinking $16K$ KV cache memory **$5.06\times$** ($88.6\text{ MB}$ vs $448.0\text{ MB}$ FP16) with decode parity at $8K$ ($43.3$ vs $43.6\text{ tok/s}$, $10.51$ vs $9.93$ WT2 PPL). In synthetic kernel microbenchmarks, the 4-bit $G=7, D=64$ kernel reaches up to **$2.34\times$** vs Apple Silicon SDPA at $4K$ ($0.0843\text{ ms}$ vs $0.1973\text{ ms}$, though 4-bit KIVI loses passkey recall at 16K), whereas $G=6, D=128$ mixed KIVI runs $0.41\text{--}0.67\times$ SDPA while providing $5.06\times$ capacity savings.
4. **Structured Microkernel Fusion & Zero-Pad Ternary:** Replaced power-of-2 padding waste ($40.6\%$ overhead on $4864$ ternary dimensions) with zero-pad Kronecker-Paley ternary construction ($0.0\%$ Hadamard pad waste with 1 alignment dimension, `pad_dim: 4865`, $1.60\text{ bpw}$ 1-slice, $3.21\text{ bpw}$ 2-slice). Shipped zero-barrier register-shuffle Metal FWHT (**$4.60\times$** faster than dense baseline, $0.192\text{ ms}$ vs $0.884\text{ ms}$), fused SwiGLU + RHT (**$2.14\times$** speedup, intermediate RAM cut from $156.95\text{ MB}$ to $86.95\text{ MB}$), and vectorized VQ4 Metal GEMV (**$3.81\times$** faster than FP16 at $M=1$, $0.104\text{ ms}$, $45.36\text{ GB/s}$).
5. **Exact Signed 150-Bit Garner CRT & Sliced Multi-Exponent GEMM:** Upgraded modular FP64 arithmetic from unregularized 120-bit limbs to signed 150-bit Garner CRT ($3 \times 50$-bit integer limbs with Knuth two-sum combination) delivering $0.0$ relative error across $p \in \{25..45\}$. Paired with GPU mantissa slicing (`ozaki_crt_sliced`), all-GPU execution reaches $1.07 \times 10^{-15}$ error on $1024^2$ IID and exact $0.0$ error vs 50-digit reference on ill-conditioned $\kappa=10^{12}$ matrices (matching sliced $0.0$ exactness completely on GPU without CPU round-trips).
6. **Leakage-Free 3-Stage MOHAWK Hybrid Distillation:** Fixed evaluation leakage by deploying a genuine 3-stage MOHAWK pipeline (Stage 0 matrix orientation warm-start, Stage 1 hidden-state alignment, Stage 2 logit distillation). Synthetic equal-compute benchmarks reach $3.71$ val PPL ($0.320$ KL) vs $5.54$ val PPL ($2.757$ KL) for scratch training. On real pretrained `Qwen2.5-0.5B-Instruct`, converting 6 of 24 attention layers to Mamba-2 SSD mixers recovers validation perplexity on $3 \times 256$ subsets from $129.96$ student initialization down to **$14.46$** final PPL (near teacher $12.50$, $0.575$ KL), cutting live $8K$ KV cache memory by **$-24.56\%$** ($72.42\text{ MB}$ vs $96.0\text{ MB}$).

| Benchmark Target (`Apple Silicon Unified GPU (applegpu_g14g, 8 GB)`) | Strongest Native / Baseline | **xFermat `v0.7.0`** | Verified Advance |
| :--- | :--- | :--- | :--- |
| **`Qwen2.5-0.5B` 4-Bit WT2 PPL & Speed** | `mlx_lm.awq`: `16.06` PPL (`173.4 ± 0.6 tok/s`) | **`15.20` PPL (`181.8 ± 3.9 tok/s`, `330.0 MB`)** | **-5.4% PPL** at same-format decode parity (`62.9 GB/s` bw) |
| **`Qwen2.5-0.5B` 3-Bit Quality** | `mlx_lm.awq`: `23.27` PPL (`0.848` KL) | **`17.99` PPL (`0.606` KL, `287.6 MB`)** | **-22.7% PPL**, **-28.5% KL** (`143.0 ± 5.7 tok/s`), comparable MC |
| **`TinyLlama-1.1B` 3-Bit Untied Head** | `xfermat` FP16 head: `61.4 ± 4.5 tok/s` (`38.4 GB/s`) | **`head_bits=8`: `98.0 ± 6.7 tok/s` (`55.2 GB/s`)** | **+59.5%** vs FP16 head (`9.62` PPL; AWQ `10.35` @ `120.7 t/s`) |
| **`Qwen2.5-1.5B` 3-Bit & VPTQ 2-Bit** | `mlx_lm.awq` 3b: `13.02` PPL (`55.9 t/s`) | **`11.48` PPL 3b (`54.0 t/s`) · `16.63` PPL VPTQ 2b (`589 MB`)** | **-11.8% 3b PPL** vs AWQ; **`5.00×`** 2b comp beating native 3b PPL |
| **`Qwen2.5-3B` 8 GB Memory Recovery** | BF16: `5,886 MB` (~5.75 GiB > 5.33 GiB → OOM) | **`1,474 MB` (`10.42` PPL @ `29.1 tok/s`) / `1,193 MB` mixed (`56.9 tok/s`)** | **Unlocks 3B on 8 GB unified memory** cleanly |
| **`16K` Context Mixed KIVI KV Cache** | FP16 `448.0 MB` (`16.0 bpw`) | **`88.6 MB` (`5.06×` smaller, `3.16 bpw`), `5/5` Passkey** | Holds 100% Passkey through 16K; decode parity at 8K (`43.3 vs 43.6 t/s`) |
| **Real `0.5B` 3:1 Hybrid Conversion** | Student init: `129.96` PPL ($3 \times 256$ val) | **`14.46` final PPL (`0.575` KL, `6618 MB` peak)** | **-24.56% 8K KV cache** with near-teacher generation quality |

---

## `v0.6.0` vs. `v0.7.0` KPI, Kernel & Methodological Progression

Between `v0.6.0` and `v0.7.0`, xFermat underwent a rigorous academic and numerical overhaul. Prior evaluations relied on small calibration token counts ($2,539$ tokens), short out-of-domain evaluation slices ($3,064$ tokens), single-trial latency measurements, and nominal bit-width metrics. Furthermore, mathematical edge cases in modular arithmetic, padding overhead in ternary layers, distillation evaluation leakage, and uncalibrated baseline claims required rigorous correction.

The table below catalogs every dimension of progression from `v0.6.0` to `v0.7.0`:

| Dimension / Metric | `v0.6.0` Baseline | `v0.7.0` Verified Advance | Architectural & Methodological Impact |
| :--- | :--- | :--- | :--- |
| **Calibration Corpus** | 2,539 tokens ($N < D_{\text{max}}=4864$, rank-deficient) | **16,384 streamed tokens** ($N > D_{\text{max}}$, `damp=0.05`, `n_gt_d_verified=True`) | Full-rank Cholesky Hessian across all models ($D_{\text{max}} \le 11008$); eliminates ill-conditioned inversion artifacts |
| **Perplexity Evaluation** | 3,064-token WikiText-2 raw slice | **301,680-tok full WT2 (0.5B)** + **65,504-tok (1.1B/1.5B/3B)** at 2048 ctx | Eliminates slice bias; tests long-range autoregressive perplexity across full corpus |
| **Zero-Shot Reasoning** | None (in-domain technical prose only) | **4 MC benchmarks ($n=100 \pm \text{stderr}$)**: ARC-e, ARC-c, PIQA, Hella | Standardized downstream zero-shot reasoning evaluation on held-out tasks |
| **Statistical Rigor** | Single-trial timings | **5-run median ± IQR** (with recorded min/max) | Standard systems reporting capturing thermal, scheduling, and cache dispersion |
| **Bit-Width Accounting** | Nominal bit-widths only | **Dual `linear_bpw` & `model_bpw`** | Full transparency on embeddings, untied heads, scales, and normalization overhead |
| **Automated Test Suite** | 36/36 tests (`test_fermat.py`) | **59/59 tests** across 6 dedicated test suites | Comprehensive academic regression coverage of numerical edge cases and kernels |
| **Modular Exact GEMM** | Unguarded 120-bit CRT (fails at $p \ge 28$, $2.5\text{e-}9$ err) | **Signed 150-bit Garner CRT + GPU sliced** ($<1\text{e-}15$ err IID, $0.0$ sliced on $\kappa=10^{12}$) | Multi-exponent dynamic range with zero cancellation across $p=25..45$ |
| **KV-Cache Compression** | 8K single-head prototype ($D=128$, 3.16 MB) | **GQA-packed KIVI 3.16 bpw holding 5/5 Passkey through 16K** | 2× context horizon (`88.6 MB` vs `448 MB` FP16); `2.34×` peak microbench in `4b G=7, D=64` |
| **Hardware Working Set** | 1.5B BF16 mislabeled as "swap-limited at 21.3 tok/s" | **Genuine `Qwen2.5-3B` swap cliff** ($5,886\text{ MB}$ / $\sim 5.75\text{ GiB} > 5.33\text{ GiB}$ unlocked to $1,474\text{ MB}$) | Resolves physical memory model; unlocks 3B parameter models on 8 GB systems |
| **Untied Head Speed** | Tied/FP16 head policy (`TinyLlama-1.1B` $61.4\text{ tok/s}$) | **`--head-bits 8` lifting xFermat decode +59.5%** ($61.4 \rightarrow 98.0\text{ tok/s}$; AWQ `120.7 t/s`) | Fixes untied FP16 vocabulary projection bottleneck in xFermat |
| **Structured Microkernels** | 8192 pow2 pad waste on 4864 ($40.6\%$ waste); 8-barrier FWHT | **Zero-pad 4864 ternary (0.0% pad)**, **shuffle FWHT 4.60×**, **fused SwiGLU 2.14×**, **VQ4 3.81×** | Eliminates padding memory waste and register round-trips via fused kernels |
| **SSM Distillation** | Train-target cosine leakage during evaluation | **3-stage MOHAWK**: syn $3.71$ vs $5.54$ PPL; real 0.5B $129.96 \rightarrow 14.46$ PPL | Clean progressive knowledge distillation saving -24.56% 8K KV cache on real LLM |

---

## Formal Withdrawal of Earlier Claims & Physical Roofline Realities

Technical integrity requires documenting and retracting invalid historical claims:

### 1. Withdrawal of "1.47× Faster than AWQ" on 3-Bit Decoding
In `v0.6.0`, an uncalibrated single-trial timing benchmark reported `mlx_lm.awq` 3-bit running at $98.3\text{ tok/s}$ against xFermat 3-bit at $144.1\text{ tok/s}$. Under the rigorous 5-run median $\pm$ IQR protocol of `v0.7.0` (with pre-warmed allocator state), `mlx_lm.awq` 3-bit decodes at **$147.73 \pm 5.42\text{ tok/s}$** ($44.52\text{ GB/s}$ effective bandwidth), while `xfermat_3bit` decodes at **$143.02 \pm 5.69\text{ tok/s}$** ($43.13\text{ GB/s}$). 

Both implementations operate at the physical bandwidth roofline ($\sim 43\text{--}45\text{ GB/s}$) for a $\sim 287\text{ MB}$ compressed model weight payload. The claim of a $1.47\times$ decode speed advantage over AWQ is **formally withdrawn**.

Instead, xFermat 3-bit achieves a decisive and verified **accuracy and reasoning superiority**:
- Full `WikiText-2` PPL: **$17.99$ vs $23.27$** ($-22.7\%$ lower perplexity).
- Held-out technical prose KL divergence: **$0.606$ vs $0.848$** ($-28.5\%$ lower KL).
- Downstream multiple-choice reasoning: **$34.0\% \pm 4.7\%$ vs $27.0\% \pm 4.4\%$** on ARC-Challenge; **$71.0\% \pm 4.5\%$ vs $65.0\% \pm 4.8\%$** on PIQA; **$54.0\% \pm 5.0\%$ vs $51.0\% \pm 5.0\%$** on HellaSwag.

### 2. Withdrawal of "1.5B BF16 Swap-Limited" Description
In `v0.6.0`, `Qwen2.5-1.5B-Instruct` in BF16 ($2,944.4\text{ MB}$ static weights) was described as "swap-limited at 21.3 tok/s" on an 8 GB system. In reality, $2.94\text{ GB}$ of static weights sits comfortably beneath the macOS $5.33\text{ GB}$ recommended working set limit. The measured generation throughput of **$25.84 \pm 0.11\text{ tok/s}$** is entirely bandwidth-governed: streaming $2.944\text{ GB}$ per token at $25.84\text{ tok/s}$ requires $2.944 \times 25.84 \approx 76.08\text{ GB/s}$ of continuous memory traffic ($79.78\text{ GB/s}$ effective bandwidth within the observed $\sim 63\text{--}84\text{ GB/s}$ sustained streaming range). The characterization of 1.5B BF16 as swap-throttled is **formally withdrawn**.

The *genuine* memory swap cliff is demonstrated in `v0.7.0` by `Qwen2.5-3B-Instruct`. In BF16, 3B requires $5,886.0\text{ MB}$ ($\sim 5.75\text{ GiB}$) of static weights, strictly exceeding the $5.33\text{ GiB}$ working-set ceiling. This triggers immediate operating system memory pressure and OOM termination. xFermat resolves this physical cliff: 4-bit ($1,804.1\text{ MB}$, $9.43$ PPL @ $27.8\text{ tok/s}$), 3-bit ($1,474.2\text{ MB}$, $10.42$ PPL @ $29.1\text{ tok/s}$), and mixed 2/3-bit ($1,193.0\text{ MB}$, $16.01$ PPL @ $56.9\text{ tok/s}$) all operate safely within unified memory limits.

---

## 1. The Unified-Memory Hardware Roofline & Bottleneck

Autoregressive token generation proceeds in two distinct operational phases:
1. **Prompt Prefill Phase (Compute-Bound):** Ingests $L_{\text{prompt}}$ tokens simultaneously. Activations scale as $O(L_{\text{prompt}} \times D)$, enabling high matrix-matrix operational intensity ($>100\text{ FLOPs/byte}$). Apple Silicon matrix coprocessors and GPU SIMD units achieve high utilization ($>900\text{ tok/s}$ on $0.5\text{B}$).
2. **Autoregressive Decode Phase (Memory-Bound):** Generates single tokens sequentially ($L_q = 1$). For every single token produced, the entire weight tensor $\mathbf{W} \in \mathbb{R}^{D_{\text{out}} \times D_{\text{in}}}$ and accumulated Key-Value cache $\mathbf{K}, \mathbf{V} \in \mathbb{R}^{2 \times L_{\text{ctx}} \times H_{\text{kv}} \times D_{\text{head}}}$ must be streamed from unified RAM into on-chip registers. The operational intensity drops to:
   $$\text{Intensity} = \frac{2 \times \text{Params}}{M_{\text{weights}} + M_{\text{KV}}} \approx 1\text{--}2\text{ FLOPs/byte}$$

On Apple Silicon Unified GPU (`applegpu_g14g, 8 GB`), device telemetry reports $8.0\text{ GB}$ physical unified RAM with a $5.33\text{ GB}$ maximum recommended GPU working set. Real-world sequential streaming benchmarks achieve sustained effective memory bandwidth between $\sim 63\text{ GB/s}$ and $84\text{ GB/s}$ (peaking at $83.96\text{ GB/s}$ on `TinyLlama-1.1B` BF16).

Under this bandwidth roofline, generation speed is physically capped:
$$\text{Tokens per Second} \le \frac{\text{Bandwidth}_{\text{eff}}}{\text{Bytes per Parameter} \times \text{Param Count} + \text{KV Bytes per Token}}$$

To double decode throughput, one must halve the memory payload per parameter without collapsing representation quality.

```
Unified Memory Bandwidth & Capacity Hierarchy (applegpu_g14g, 8 GB)
┌──────────────────────────────────────────────────────────────────────────────┐
│ Physical RAM: 8.00 GB (Measured ~63–84 GB/s Streaming Bandwidth)             │
├──────────────────────────────────────────────────────┬───────────────────────┤
│ Max Recommended Working Set: 5.33 GB                 │ OS & System: 2.67 GB  │
│ ┌──────────────────────────────────────────────────┐ │ (Kernel, WindowServer)│
│ │ Safe GPU Inference Region: Weights + KV Cache    │ │                       │
│ │   - Qwen2.5-0.5B BF16 (942 MB): Safe (77.7 t/s)       │ │                       │
│ │   - Qwen2.5-1.5B BF16 (2,944 MB / 2.88 GiB): Safe (25.8 t/s) │ │               │
│ │   - Qwen2.5-3B BF16 (5,886 MB / 5.75 GiB): SWAP CLIFF / OOM! │ │               │
│ │   - xFermat 3B 3-bit (1,474 MB): RESTORED (29.1 t/s)│ │                        │
│ └──────────────────────────────────────────────────┘ │                       │
└──────────────────────────────────────────────────────┴───────────────────────┘
```

---

## 2. Five-Pillar Architecture & Mathematical Foundations

xFermat unifies **18 foundational publications (15 peer-reviewed venue papers and 3 arXiv preprints)** across five architectural pillars, ensuring theoretical algorithms translate into wall-clock speedups on Apple Silicon:

```
┌──────────────────────────────────────────────────────────────────────────────┐
│                    xFermat v0.7.0 FIVE-PILLAR ARCHITECTURE                   │
├──────────────────────────────────────────────────────────────────────────────┤
│ PILLAR 1: MODULAR EXACT FP64 ARITHMETIC (src/fermat/rns_ozaki.py)            │
│   Signed 150-Bit Garner CRT (3x50-bit limbs, Knuth two-sum combination)      │
│   All-GPU ozaki_crt_sliced mantissa splitting (<1e-15 rel err for p=25..45)  │
├──────────────────────────────────────────────────────────────────────────────┤
│ PILLAR 2: SUB-CUBIC BILINEAR TENSORS (src/fermat/bilinear.py)                │
│   AlphaEvolve <4,4,4> rank-48 complex GEMM + AlphaTensor factorizations      │
│   Winograd-Strassen O(n^2.807) with automated shape-dispatch gating          │
├──────────────────────────────────────────────────────────────────────────────┤
│ PILLAR 3: WEIGHT SURGERY & STRUCTURED MICROKERNELS (surgery.py, structured.py)│
│   R1/R4 Hadamard Incoherence + Streamed Hessian Cholesky (N=16,384 > D_max)  │
│   Zero-Pad 4864 Kronecker-Paley Ternary (0% Hadamard waste, pad_dim: 4865)   │
│   Zero-Barrier Register-Shuffle FWHT (4.6x) & Fused SwiGLU+RHT (2.14x)       │
│   Vectorized VQ4 Metal GEMV (3.81x at M=1, 45.36 GB/s)                       │
├──────────────────────────────────────────────────────────────────────────────┤
│ PILLAR 4: FUSED GQA-PACKED KIVI KV CACHE (src/fermat/kv_quant.py)            │
│   Block-grouped (G=64) Key 62.5% 4b / 37.5% 2b + Value 2b (3.16 bpw)         │
│   16K Passkey 5/5 + 4b G=7,D=64 up to 2.34x SDPA (8K mixed decode parity)    │
├──────────────────────────────────────────────────────────────────────────────┤
│ PILLAR 5: STATE SPACE DUALITY & MOHAWK DISTILLATION (ssd_mamba.py, distill.py)│
│   3:1 Hybrid Mamba-2 SSD + Causal SDPA Architecture                          │
│   Leakage-free 3-stage MOHAWK distillation: synthetic 3.71 PPL & real LLM   │
├──────────────────────────────────────────────────────────────────────────────┤
│ EMPIRICAL RUNTIME DISPATCH AUTOTUNER (src/fermat/engine.py)                  │
│   FermatEngine(mode="auto"): Median + 10% hysteresis benchmarking per shape  │
│   Rejects asymptotic paths when vendor Metal GEMM/BLAS is faster             │
└──────────────────────────────────────────────────────────────────────────────┘
```

---

## 3. Algorithmic & Kernel Derivations

### 3.1 Signed 150-Bit Garner CRT & Multi-Exponent Sliced GEMM
In modular floating-point matrix multiplication (Ozaki Scheme II), large floating-point matrices are partitioned into integer mantissa matrices and evaluated over a residue number system (RNS). In `v0.6.0`, the system used an unregularized 120-bit modulus system ($3 \times 40$-bit limbs, total modulus $M_{\text{total}} \approx 2^{135.86}$). When evaluating matrix pairs with large exponent disparity ($A_{ik} = 1$, $B_{kj} = 2^{-p}$ for $p \ge 28$), the product integer falls within $C_{\text{int}} \in [-M_{\text{total}}/2, M_{\text{total}}/2]$, but naive double-precision reconstruction suffers catastrophic cancellation loss ($\ge 2.50 \times 10^{-9}$ relative error at $p=25$, $1.46 \times 10^{-7}$ at $p=30$).

`v0.7.0` replaces this with exact mixed-radix signed Garner reconstruction to 150-bit integer limbs ($3 \times 50$-bit limbs: $l_2, l_1, l_0$):
$$C_{\text{val}} = l_2 \cdot 2^{100} + l_1 \cdot 2^{50} + l_0$$
The conversion from exact 150-bit integer to `float64` employs Knuth's exact `two_sum`:
$$(\text{hi}, r_1) = \text{two\_sum}(\text{ldexp}(l_2, 100), \text{ldexp}(l_1, 50)), \quad C_{\text{float}} = \text{hi} + (r_1 + l_0)$$
For matrices with dynamic ranges exceeding 63 bits, `ozaki_crt_sliced` performs recursive residual mantissa splitting entirely on the GPU (`OZAKI_SLICE_MODULI_11`), reconstructing intermediate integer slices via a dedicated Metal Garner reconstruction kernel without CPU memory round-trips. This delivers verified $<1 \times 10^{-15}$ relative Frobenius error across $p \in \{25, 28, 30, 40, 45\}$, and exact $0.0$ error vs 50-digit arbitrary-precision reference on ill-conditioned $\kappa=10^{12}$ matrices.

### 3.2 Outlier Incoherence & Streamed Full-Rank Weight Surgery
Transformer activation outliers concentrate energy along specific hidden channels, causing scalar quantization scales to widen and destroying precision. Following *SpinQuant* and *QuIP#*, xFermat applies orthogonal randomized block-Hadamard transforms:
$$\mathbf{W}' = \mathbf{W} \mathbf{R}_1^\top, \quad \mathbf{x}' = \mathbf{R}_1 \mathbf{x}$$
$\mathbf{R}_1$ is absorbed offline into preceding `RMSNorm` scale weights and embedding matrices, imposing zero inference latency overhead. For 3-bit linear layers, an on-chip Walsh–Hadamard transform $\mathbf{R}_4$ is executed on activations using custom register-shuffle Metal shaders.

In `v0.7.0`, calibration is executed over $16,384 > D_{\text{max}}$ streamed tokens (`--calib-tokens 16384`, `damp=0.05`). Because the token count exceeds the maximum linear layer dimension across all evaluated models ($D_{\text{max}} = 4864$ on `0.5B`, $5632$ on `1.1B`, $8960$ on `1.5B`, and $11,008$ on `3B`), the activation covariance matrix:
$$\mathbf{H} = \frac{1}{N} \mathbf{X} \mathbf{X}^\top + \lambda \mathbf{I}$$
is strictly full-rank and positive definite, eliminating ill-conditioned Cholesky inversion artifacts during sequential column error feedback:
$$\mathbf{W}_{:, j+1:} \leftarrow \mathbf{W}_{:, j+1:} - \frac{w_{ij} - \hat{w}_{ij}}{[\mathbf{H}^{-1}]_{jj}} [\mathbf{H}^{-1}]_{j, j+1:}$$

### 3.3 Zero-Barrier Shuffle FWHT, Fused SwiGLU+RHT & Zero-Pad Ternary
1. **Zero-Barrier Register-Shuffle FWHT:** Traditional fast Walsh–Hadamard transforms synchronize across SIMD lanes using threadgroup shared memory (SRAM) and explicit `threadgroup_barrier()`. `v0.7.0` introduces a register-shuffle FWHT kernel using Metal SIMD shuffle primitives (`simd_shuffle_xor`), executing butterfly stages in-register across $32$-wide SIMD warps. This achieves **$4.60\times$** speedup over dense fallback ($0.192\text{ ms}$ vs $0.884\text{ ms}$ at $1024 \times 4096$) and **$1.69\times$** speedup over 8-barrier SRAM ($0.192\text{ ms}$ vs $0.325\text{ ms}$).
2. **Fused SwiGLU + RHT:** In modern MLP blocks, SwiGLU computes $\mathbf{y} = \text{SiLU}(\mathbf{x} \mathbf{W}_{\text{gate}}) \odot (\mathbf{x} \mathbf{W}_{\text{up}})$, followed by randomized Hadamard rotation before `down_proj`. Naive execution materializes intermediate activation tensors and launches two distinct kernels. `fused_swiglu_rht` fuses the elementwise SiLU-multiplication and randomized sign-flip butterfly into a single pass, delivering **$2.14\times$** speedup ($0.181\text{ ms}$ vs $0.388\text{ ms}$) and reducing peak intermediate allocations from $156.95\text{ MB}$ to $86.95\text{ MB}$.
3. **Zero-Pad Kronecker-Paley Ternary:** To quantize matrices into ternary weights $\{-1, 0, +1\}$ using Hadamard transformations, prior approaches zero-padded $4864$-dim matrices to the nearest power of 2 ($8192$), incurring a $40.6\%$ memory penalty. `v0.7.0` constructs Kronecker-Paley factors that decompose $4864$ into block-Hadamard structures requiring $0.0\%$ Hadamard padding waste (using $4864$ as the exact rotation dimension, with a single $+1$ coordinate for ternary word alignment yielding `pad_dim: 4865`), achieving $1.60\text{ bpw}$ (1-slice) and $3.21\text{ bpw}$ (2-slice) with $>0.977$ cosine similarity.

### 3.4 Fused GQA-Packed KIVI KV Cache
In standard autoregressive generation, Keys and Values display asymmetric outlier behavior: Keys exhibit persistent high-magnitude channel outliers induced by high-base RoPE frequencies ($\theta = 10^6$), whereas Values shift token-by-token. 

xFermat implements:
- **Block-Grouped Per-Channel Key Quantization ($G=64$):** Quantizes Key channels within $64$-token time chunks, preventing early outlier tokens from degrading scales for later tokens.
- **Salient Outlier Promotion (`k_outlier_ratio=0.625`):** Promotes the top $62.5\%$ high-variance Key channels per block to 4-bit via a 2-bit residual, compresses the remaining $37.5\%$ Keys and per-token Values to 2-bit, and keeps a 64-token FP16 tail, achieving an effective bit-width of $3.16\text{ bpw}$.
- **GQA-Packed Metal FlashDecode:** Groups $G = H_q / H_{\text{kv}}$ query heads per threadgroup, loading packed `uint32` quantized KV blocks directly into threadgroup SRAM and unpacking in-register, completely avoiding DRAM dequantization.

### 3.5 Leakage-Free 3-Stage MOHAWK Progressive Distillation
Converting quadratic attention models into sub-quadratic linear-time state space models (Mamba-2 SSD) requires progressive knowledge transfer. `v0.7.0` implements a 3-stage distillation pipeline:
- **Stage 0 (Matrix Orientation Warm-Start):** Solves Ridge-regularized Procrustes normal equations between teacher attention projection blocks and student SSD input/output projections, aligning initial matrix representations ($0.012 \rightarrow 0.367$ cosine).
- **Stage 1 (Hidden-State Alignment):** Trains SSM mixer parameters to minimize Mean Squared Error (MSE) against frozen teacher layer representations.
- **Stage 2 (End-to-End Distillation):** Optimizes student parameters over a combined Cross-Entropy and Kullback–Leibler divergence objective against teacher output logits:
  $$\mathcal{L} = (1 - \alpha) \mathcal{L}_{\text{CE}}(\hat{\mathbf{y}}, \mathbf{y}) + \alpha T^2 \mathcal{D}_{\text{KL}}(\sigma(\mathbf{z}_{\text{teacher}} / T) \,\|\, \sigma(\mathbf{z}_{\text{student}} / T))$$

---

## 4. Comprehensive Empirical Verification Results

All measurements cited below are extracted verbatim from the reproducible artifact [`benchmarks/v07_rigorous_results.json`](benchmarks/v07_rigorous_results.json), executed on an **`Apple Silicon Unified GPU (applegpu_g14g, 8 GB)`** running macOS 26.2, Python 3.12.16, `mlx 0.32.4`, and `mlx-lm 0.32.2`.

### 4.1 Real Pretrained LLM Weight Compression

#### `Qwen/Qwen2.5-0.5B-Instruct`
*Full WikiText-2 Test Set: $301,680$ tokens at context length $2048$. Held-out technical prose: $2,255$ tokens. Timings: 5-run median $\pm$ IQR.*

| Variant | Linear BPW | Model BPW | Weight MB | WT2 PPL ($301\text{k}$) | Held-Out KL | Decode tok/s (IQR) | Effective BW |
| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
| `bf16` | 16.00 | 16.00 | 942.3 | 14.42 | 0.0000 | 77.7 ± 1.3 | 76.8 GB/s |
| `mlx_native_4bit` | 4.50 | 5.60 | 330.0 | 16.80 | 0.2579 | 153.3 ± 3.3 | 53.1 GB/s |
| `mlx_lm_awq_4bit` | 4.50 | 5.60 | 330.0 | 16.06 | 0.1888 | 173.4 ± 0.6 | 60.0 GB/s |
| **`xfermat_4bit`** | **4.50** | **5.60** | **330.0** | **15.20** | **0.1579** | **181.8 ± 3.9** | **62.9 GB/s** |
| `mlx_native_3bit` | 3.50 | 4.88 | 287.4 | 39.12 | 1.3222 | 154.2 ± 0.7 | 46.5 GB/s |
| `mlx_lm_awq_3bit` | 3.50 | 4.88 | 287.4 | 23.27 | 0.8479 | 147.7 ± 5.4 | 44.5 GB/s |
| **`xfermat_3bit`** | **3.50** | **4.88** | **287.6** | **17.99** | **0.6059** | **143.0 ± 5.7** | **43.1 GB/s** |
| `xfermat_mixed_2_3bit` | 2.65 | 4.26 | 251.3 | 41.16 | 2.4297 | 135.4 ± 5.0 | 35.7 GB/s |
| `mlx_native_2bit` | 2.50 | 4.16 | 244.7 | 56956.39 | 8.0679 | 159.4 ± 3.2 | 40.9 GB/s |
| `xfermat_2bit_e2e_qp` | 2.50 | 4.16 | 244.9 | 79.36 | 3.8786 | 152.3 ± 5.8 | 39.1 GB/s |
| `xfermat_vptq_2bit_pv` | 2.26 | 3.98 | 234.6 | 26.73 | 1.6542 | 74.4 ± 0.9 | 18.3 GB/s |

#### `TinyLlama/TinyLlama-1.1B-Chat-v1.0`
*WikiText-2 Test Set: $65,504$ tokens at context length $2048$. Untied vocabulary matrix ($32,000 \times 2048$).*

| Variant | Linear BPW | Model BPW | Weight MB | WT2 PPL ($65\text{k}$) | Held-Out KL | Decode tok/s (IQR) | Effective BW |
| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
| `bf16` | 16.00 | 16.00 | 2098.2 | 8.57 | 0.0000 | 38.2 ± 9.1 | 84.0 GB/s |
| `mlx_native_3bit` | 4.29 | 4.54 | 595.8 | 10.97 | 0.3746 | 97.9 ± 2.2 | 61.2 GB/s |
| `mlx_lm_awq_3bit` | 3.82 | 4.10 | 537.2 | 10.35 | 0.3310 | 120.7 ± 2.9 | 68.0 GB/s |
| `xfermat_4bit_head8` | 4.75 | 4.98 | 652.8 | 8.85 | 0.0869 | 110.1 ± 2.2 | 75.4 GB/s |
| `xfermat_3bit_bf16head` | 4.29 | 4.54 | 596.1 | 9.62 | 0.3880 | 61.4 ± 4.5 | 38.4 GB/s |
| **`xfermat_3bit_head8`** | **3.82** | **4.10** | **537.5** | **9.62** | **0.3876** | **98.0 ± 6.7** | **55.2 GB/s** |
| `xfermat_mixed_2_3bit_head8` | 3.02 | 3.35 | 439.3 | 15.63 | 1.9223 | 136.6 ± 3.2 | 62.9 GB/s |

*Key finding: Quantizing the untied vocabulary projection with `--head-bits 8` (`xfermat_3bit_head8`) fixes xFermat's untied-head bottleneck by **$+59.5\%$** ($61.4 \rightarrow 98.0\text{ tok/s}$) with identical perplexity ($9.618$ vs $9.619$, beating native $10.97$ and AWQ $10.35$, while AWQ decodes at $120.7\text{ tok/s}$).*

#### `Qwen/Qwen2.5-1.5B-Instruct`
*WikiText-2 Test Set: $65,504$ tokens at context length $2048$.*

| Variant | Linear BPW | Model BPW | Weight MB | WT2 PPL ($65\text{k}$) | Held-Out KL | Decode tok/s (IQR) | Effective BW |
| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
| `bf16` | 16.00 | 16.00 | 2944.4 | 9.96 | 0.0000 | 25.8 ± 0.1 | 79.8 GB/s |
| `mlx_native_4bit` | 4.50 | 5.11 | 939.6 | 10.77 | 0.1946 | 71.5 ± 2.3 | 70.4 GB/s |
| `mlx_lm_awq_4bit` | 4.50 | 5.11 | 939.6 | 10.67 | 0.1262 | 50.0 ± 4.0 | 49.3 GB/s |
| **`xfermat_4bit`** | **4.50** | **5.11** | **939.6** | **10.34** | **0.1266** | **67.0 ± 2.5** | **66.1 GB/s** |
| `mlx_native_3bit` | 3.50 | 4.26 | 783.4 | 17.75 | 0.9850 | 49.2 ± 2.2 | 40.5 GB/s |
| `mlx_lm_awq_3bit` | 3.50 | 4.26 | 783.4 | 13.02 | 0.5846 | 55.9 ± 5.2 | 45.9 GB/s |
| **`xfermat_3bit`** | **3.50** | **4.26** | **783.9** | **11.48** | **0.4868** | **54.0 ± 4.4** | **44.4 GB/s** |
| `xfermat_mixed_2_3bit` | 2.65 | 3.54 | 651.1 | 20.27 | 2.5004 | 58.3 ± 4.9 | 39.8 GB/s |
| **`xfermat_vptq_2bit`** | **2.26** | **3.20** | **589.0** | **16.63** | **1.7790** | **34.4 ± 3.9** | **21.2 GB/s** |

*(Note: On `Qwen2.5-1.5B-Instruct`, NaN-guarded `xfermat_vptq_2bit` achieves $16.63$ WikiText-2 PPL at $589.0\text{ MB}$ [$5.00\times$ compression]—lower WT2 PPL than `mlx_native_3bit` [$17.75$ @ $783.4\text{ MB}$], while `mlx_native_3bit` retains better held-out KL [$0.985$ vs $1.779$], MC average [$58.0\%$ vs $51.0\%$], and decode speed [$49.2$ vs $34.4\text{ tok/s}$].)*

#### `Qwen/Qwen2.5-3B-Instruct`
*WikiText-2 Test Set: $65,504$ tokens at context length $2048$. Working set threshold: $5.33\text{ GiB}$.*

| Variant | Linear BPW | Model BPW | Weight MB | WT2 PPL ($65\text{k}$) | Held-Out KL | Decode tok/s (IQR) | Status |
| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :--- |
| `bf16` | 16.00 | 16.00 | 5886.0 | — | — | — | **OOM (Exceeds 5.33 GiB limit)** |
| `mlx_native_3bit` | 3.50 | 4.01 | 1473.4 | 180.84 | 4.4302 | 24.5 ± 1.2 | Extreme Degeneracy ($180.8$ PPL) |
| **`xfermat_4bit`** | **4.50** | **4.90** | **1804.1** | **9.43** | **0.1113** | **27.8 ± 3.1** | **Unlocked within 1.80 GB** ($52.6\text{ GB/s}$) |
| **`xfermat_3bit`** | **3.50** | **4.01** | **1474.2** | **10.42** | **0.4336** | **29.1 ± 2.2** | **Unlocked within 1.47 GB** ($45.0\text{ GB/s}$) |
| **`xfermat_mixed_2_3bit`** | **2.65** | **3.24** | **1193.0** | **16.01** | **1.9546** | **56.9 ± 0.3** | **High Throughput** ($71.2\text{ GB/s}$) |

---

### 4.2 Standardized Multiple-Choice Reasoning Benchmarks

Evaluation performed across 4 canonical reasoning tasks ($n=100$ random held-out samples per task, reporting normalized accuracy $\pm \text{stderr}$):
- **ARC-Easy:** Science question answering (grade school).
- **ARC-Challenge:** Hard science questions requiring multi-hop reasoning.
- **PIQA:** Physical Interaction Question Answering.
- **HellaSwag:** Commonsense sentence continuation reasoning.

| Model & Compression Variant | ARC-Easy ($n=100$) | ARC-Challenge ($n=100$) | PIQA ($n=100$) | HellaSwag ($n=100$) |
| :--- | :---: | :---: | :---: | :---: |
| **`Qwen2.5-0.5B` BF16 Baseline** | 57.0% ± 5.0% | 35.0% ± 4.8% | 75.0% ± 4.3% | 59.0% ± 4.9% |
| `Qwen2.5-0.5B` `mlx_native_4bit` | 54.0% ± 5.0% | 38.0% ± 4.9% | 74.0% ± 4.4% | 55.0% ± 5.0% |
| `Qwen2.5-0.5B` `mlx_lm_awq_4bit` | 56.0% ± 5.0% | 28.0% ± 4.5% | 70.0% ± 4.6% | 55.0% ± 5.0% |
| **`Qwen2.5-0.5B` `xfermat_4bit`** | **61.0% ± 4.9%** | **34.0% ± 4.7%** | **74.0% ± 4.4%** | **57.0% ± 5.0%** |
| `Qwen2.5-0.5B` `mlx_native_3bit` | 53.0% ± 5.0% | 28.0% ± 4.5% | 62.0% ± 4.9% | 47.0% ± 5.0% |
| `Qwen2.5-0.5B` `mlx_lm_awq_3bit` | 56.0% ± 5.0% | 27.0% ± 4.4% | 65.0% ± 4.8% | 51.0% ± 5.0% |
| **`Qwen2.5-0.5B` `xfermat_3bit`** | **53.0% ± 5.0%** | **34.0% ± 4.7%** | **71.0% ± 4.5%** | **54.0% ± 5.0%** |
| `Qwen2.5-0.5B` `xfermat_mixed_2_3bit` | 45.0% ± 5.0% | 23.0% ± 4.2% | 55.0% ± 5.0% | 40.0% ± 4.9% |
| `Qwen2.5-0.5B` `xfermat_vptq_2bit_pv` | 47.0% ± 5.0% | 22.0% ± 4.1% | 62.0% ± 4.9% | 47.0% ± 5.0% |
| **`TinyLlama-1.1B` BF16 Baseline** | 52.0% ± 5.0% | 35.0% ± 4.8% | 80.0% ± 4.0% | 67.0% ± 4.7% |
| `TinyLlama-1.1B` `mlx_lm_awq_3bit` | 52.0% ± 5.0% | 32.0% ± 4.7% | 71.0% ± 4.5% | 69.0% ± 4.6% |
| **`TinyLlama-1.1B` `xfermat_3bit_head8`** | **50.0% ± 5.0%** | **29.0% ± 4.5%** | **75.0% ± 4.3%** | **67.0% ± 4.7%** |
| **`Qwen2.5-1.5B` BF16 Baseline** | 78.0% ± 4.1% | 46.0% ± 5.0% | 81.0% ± 3.9% | 73.0% ± 4.4% |
| `Qwen2.5-1.5B` `mlx_lm_awq_3bit` | 68.0% ± 4.7% | 42.0% ± 4.9% | 74.0% ± 4.4% | 66.0% ± 4.7% |
| **`Qwen2.5-1.5B` `xfermat_3bit`** | **64.0% ± 4.8%** | **36.0% ± 4.8%** | **78.0% ± 4.1%** | **66.0% ± 4.7%** |
| **`Qwen2.5-1.5B` `xfermat_vptq_2bit`** | **56.0% ± 5.0%** | **30.0% ± 4.6%** | **65.0% ± 4.8%** | **53.0% ± 5.0%** |
| **`Qwen2.5-3B` `xfermat_4bit`** | — | **45.0% ± 5.0%** | — | **76.0% ± 4.3%** |
| **`Qwen2.5-3B` `xfermat_3bit`** | — | **40.0% ± 4.9%** | — | **73.0% ± 4.4%** |
| `Qwen2.5-3B` `mlx_native_3bit` | — | 24.0% ± 4.3% | — | 31.0% ± 4.6% |

---

### 4.3 Long-Context KIVI KV-Cache Scaling & Passkey Retrieval

Live LLM evaluation performed using `Qwen/Qwen2.5-1.5B-Instruct` across context windows up to $16,384$ tokens ($16K$).

| Cache Configuration | Ctx Len | Full WT2 PPL | Tail WT2 PPL | KV Cache MB | Effective BPW | Passkey Retrieval | Decode tok/s (IQR) |
| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
| **FP16 KV Baseline** | $4K$ | 10.58 | 10.03 | 112.0 MB | 16.0 bpw | **5/5 (100%)** | 51.9 ± 1.6 |
| **`xfermat_kivi_mixed` (3.16 bpw)** | $4K$ | **11.14** | **10.64** | **22.2 MB** | **3.16 bpw** | **5/5 (100%)** | **42.9 ± 1.0** |
| `xfermat_kivi_4bit` | $4K$ | 14.02 | 13.84 | 31.5 MB | 4.50 bpw | 2/5 (40%) | 48.4 ± 4.0 |
| `xfermat_kivi_pure2bit` | $4K$ | 64.35 | 78.90 | 17.5 MB | 2.50 bpw | 0/5 (0%) | 53.0 ± 0.7 |
| `per_token_2bit_baseline` | $4K$ | 41622.45 | 43853.81 | 17.5 MB | 2.50 bpw | 0/5 (0%) | 46.7 ± 2.0 |
| **FP16 KV Baseline** | $8K$ | 9.93 | 9.93 | 224.0 MB | 16.0 bpw | **5/5 (100%)** | 43.6 ± 1.7 |
| **`xfermat_kivi_mixed` (3.16 bpw)** | $8K$ | **10.51** | **10.54** | **44.3 MB** | **3.16 bpw** | **5/5 (100%)** | **43.3 ± 1.0** |
| `xfermat_kivi_4bit` | $8K$ | 13.87 | 14.18 | 63.0 MB | 4.50 bpw | 4/5 (80%) | 42.1 ± 0.8 |
| `xfermat_kivi_pure2bit` | $8K$ | 53.64 | 60.01 | 35.0 MB | 2.50 bpw | 0/5 (0%) | 37.4 ± 15.3 |
| `per_token_2bit_baseline` | $8K$ | 52166.35 | 53831.66 | 35.0 MB | 2.50 bpw | 0/5 (0%) | 45.1 ± 0.5 |
| **FP16 KV Baseline** | $16K$ | — | — | 448.0 MB | 16.0 bpw | **5/5 (100%)** | — |
| **`xfermat_kivi_mixed` (3.16 bpw)** | $16K$ | — | — | **88.6 MB** | **3.16 bpw** | **5/5 (100%)** | — |
| `xfermat_kivi_4bit` | $16K$ | — | — | 126.0 MB | 4.50 bpw | 1/5 (20%) | — |
| `xfermat_kivi_pure2bit` | $16K$ | — | — | 70.0 MB | 2.50 bpw | 0/5 (0%) | — |
| `per_token_2bit_baseline` | $16K$ | — | — | 70.0 MB | 2.50 bpw | 0/5 (0%) | — |

#### Fused Metal GQA Decode Microbenchmarks
*Evaluating single-token decode latency ($L_q = 1$) against native Apple Silicon SDPA (`mx.fast.scaled_dot_product_attention`):*

| Shape Target | Apple SDPA FP16 (ms) | Fermat 4-Bit GQA (ms) | Fermat Mixed 3.16b (ms) | Max Verified Speedup |
| :--- | :---: | :---: | :---: | :---: |
| $G=7, D=64, L=2048$ | 0.0899 ms | 0.1789 ms | 0.1379 ms | 0.65× vs SDPA |
| **$G=7, D=64, L=4096$** | **0.1973 ms** | **0.0843 ms** | **0.1290 ms** | **2.34× faster vs SDPA** |
| $G=7, D=64, L=8192$ | 0.2041 ms | 0.1481 ms | 0.1747 ms | **1.38× faster vs SDPA** |
| $G=7, D=64, L=16384$ | 0.2421 ms | 0.1815 ms | 0.2543 ms | **1.33× faster vs SDPA** |
| $G=6, D=128, L=8192$ | 0.1834 ms | 0.2504 ms | 0.2728 ms | 0.73× vs SDPA (pure 2b: 1.00×) |
| $G=6, D=128, L=16384$ | 0.2942 ms | 0.3167 ms | 0.4386 ms | 0.93× vs SDPA (pure 2b: 1.14×) |

---

### 4.4 Structured Microkernel & Modular GEMM Performance

#### Pillar 1: Exact Signed 150-Bit Garner CRT Modular FP64 GEMM
*Evaluating numerical error and execution latency across dense and ill-conditioned matrix distributions:*
- **Standard $1024 \times 1024$ IID Matrix Multiplication:**
  - `cpu_fp64_blas`: $7.54\text{ ms}$ (median), relative Frobenius error $0.0$.
  - `gpu_fp32_baseline`: $3.64\text{ ms}$ (median), relative Frobenius error $5.74 \times 10^{-7}$.
  - `gpu_150bit_ozaki2`: $53.1\text{ ms}$ ($53.14\text{ ms}$), relative Frobenius error **$1.07 \times 10^{-15}$**.
  - `gpu_150bit_ozaki_crt_sliced`: $323.0\text{ ms}$ ($322.95\text{ ms}$), relative Frobenius error **$1.07 \times 10^{-15}$**.
- **Ill-Conditioned $\kappa = 10^{12}$ Matrix Multiplication ($512 \times 512$):**
  - `gpu_fp32_baseline`: relative error vs 50-digit exact reference = **$1723.2$** (complete numerical loss).
  - `cpu_fp64_blas`: relative error vs 50-digit exact reference = $2.92 \times 10^{-6}$.
  - `gpu_150bit_ozaki2`: relative error vs 50-digit exact reference = $4.45 \times 10^{-8}$.
  - `gpu_150bit_ozaki_crt_sliced`: relative error vs 50-digit exact reference = **$0.0$** (exact mathematical agreement with arbitrary-precision ground truth).

#### Zero-Barrier Register-Shuffle Fast Walsh–Hadamard Transform (FWHT)
*Comparing register-shuffle FWHT against 8-barrier threadgroup SRAM and dense unrolled matrix multiplication:*

| Matrix Dimension | Register Shuffle (ms) | 8-Barrier SRAM (ms) | Dense H256 Fallback (ms) | Speedup vs Dense | Speedup vs SRAM |
| :--- | :---: | :---: | :---: | :---: | :---: |
| $512 \times 4096$ | **0.0936 ms** (68 MB) | 0.1611 ms (68 MB) | 0.4251 ms (132 MB) | **4.54×** | **1.72×** |
| $1024 \times 4096$ | **0.1922 ms** (136 MB) | 0.3254 ms (136 MB) | 0.8836 ms (264 MB) | **4.60×** | **1.69×** |

#### Fused SwiGLU + RHT Kernel
- **Shape:** $[256, 8960]$, block size $256$.
- **Naive 2-Operator Execution (SiLU-Mul + Separate RHT):** $0.3882\text{ ms}$ ($156.95\text{ MB}$ peak memory).
- **xFermat `fused_swiglu_rht`:** **$0.1812\text{ ms}$** ($86.95\text{ MB}$ peak memory).
- **Verified Advance:** **$2.14\times$ speedup**, $-44.6\%$ reduction in intermediate memory traffic.

#### Vectorized VQ4 Metal GEMV ($4096 \times 4096$)
*SRAM codebook-resident vector-quantized matrix-vector multiplication:*

| Batch / Tokens $M$ | VQ4 GEMV Latency | Achieved Bandwidth | Dense FP16 GEMV | Speedup vs Dense |
| :---: | :---: | :---: | :---: | :---: |
| **$M = 1$ (Decode)** | **0.1044 ms** | **45.36 GB/s** | 0.3976 ms | **3.81× faster** |
| **$M = 4$** | **0.1716 ms** | **27.89 GB/s** | 0.4481 ms | **2.61× faster** |
| $M = 8$ | 0.4162 ms | 11.65 GB/s | 0.4582 ms | 1.10× faster |
| $M = 16$ | 1.1437 ms | 4.36 GB/s | 0.4661 ms | *0.41× (Autotuner routes to dense)* |
| $M = 64$ | 1.6521 ms | 3.49 GB/s | 0.8662 ms | *0.52× (Autotuner routes to dense)* |

---

### 4.5 MOHAWK Distillation & Pretrained Hybrid Scaling

#### Synthetic Equal-Compute Distillation Benchmark
*Comparing 3-stage MOHAWK against scratch training under identical compute ($180$ optimization steps):*

| Architecture Configuration | Optimization Method | Total Steps | Val Perplexity | KL vs Teacher |
| :--- | :--- | :---: | :---: | :---: |
| Teacher Attention (694k params) | Full Precision AdamW | 240 steps | 4.23 PPL | 0.000 |
| **Dense 3:1 Hybrid (700k params)** | **MOHAWK 3-Stage** | **180 steps** (30/60/90) | **3.71 PPL** | **0.320** |
| Dense 3:1 Hybrid (700k params) | From Scratch AdamW | 180 steps | 5.54 PPL | 2.757 |
| **Monarch 3:1 Hybrid (103k params)** | **MOHAWK 3-Stage** | **180 steps** (30/60/90) | **4.88 PPL** | **0.511** |
| Monarch 3:1 Hybrid (103k params) | From Scratch AdamW | 180 steps | 5.98 PPL | 2.884 |

#### Real Pretrained Model Conversion: `Qwen/Qwen2.5-0.5B-Instruct`
- **Conversion Topology:** 6 of 24 Transformer layers replaced with Mamba-2 SSD linear state space mixers (layers 3, 7, 11, 15, 19, 23).
- **Teacher FP16 Validation Perplexity:** $12.50$ (measured on $3 \times 256$ token validation subset).
- **Student Initialization Perplexity (Stage 0):** $129.96$ ($0.012 \rightarrow 0.367$ orientation cosine).
- **Student Hidden-Alignment Perplexity (Stage 1):** $24.72$.
- **Student Final Distilled Perplexity (Stage 2):** **$14.46$** (KL divergence vs teacher $0.575$, peak GPU memory $6617.6\text{ MB}$).
- **$8K$ Context Memory Savings:** Teacher KV cache $96.0\text{ MB}$; Hybrid model total cache $72.42\text{ MB}$ ($72.0\text{ MB}$ remaining attention KV $+ 0.42\text{ MB}$ recurrent SSD states), achieving **$-24.56\%$ KV cache reduction** ($72.42\text{ MB}$ vs $96.0\text{ MB}$).

---

## 5. Honest Engineering Boundaries, Null Results & Autotuner Routing

xFermat establishes clear boundaries where specific optimizations do **not** provide wall-clock gains:

1. **Sub-2-Bit Quantization Limit Without QAT:** Post-training vector quantization (`vptq_2bit_pv`) achieves $26.73$ WT2 PPL on `Qwen2.5-0.5B` (vs. $79.36$ `e2e_qp` and $56,956$ native RTN 2-bit), and $16.63$ WT2 PPL on `Qwen2.5-1.5B`. However, coherence on open-ended generation at 2 bits remains fragile without full graph Straight-Through Estimation (QAT). For production inference, **3-bit (`xfermat_3bit`) and 4-bit (`xfermat_4bit`) remain the recommended tiers**.
2. **Dense Matrix Crossover Points in Bilinear & Modular Kernels:** Sub-cubic Strassen ($O(n^{2.807})$) and AlphaEvolve rank-48 decompositions require auxiliary tensor packing and unpacking. On dense matrices smaller than $4096 \times 4096$, vendor Metal GEMM outperforms polynomial decompositions. Similarly, VQ4 GEMV delivers up to $3.81\times$ speedups at $M=1$, but crosses over at $M \ge 16$ where dense FP16 GEMM is faster. [`FermatEngine(mode="auto")`](src/fermat/engine.py) uses shape autotuning (median $+ 10\%$ hysteresis) to route dense operations to native kernels automatically.
3. **KIVI Memory vs. Wall-Clock Scope:** For short prompts ($L < 1024$ tokens), live KIVI introduces modest bit-unpacking overhead. At $L=4096$–$8192$ on live `Qwen2.5-1.5B`, Mixed KIVI (3.16 bpw) shrinks KV RAM $5.06\times$ while running at `42.9 vs 51.9 tok/s` (`4K`) and at parity (`43.3 vs 43.6 tok/s` @ `8K`); isolated 4-bit microbenchmark speedups ($2.34\times$ at `G=7, D=64, L=4096`) do not carry over to mixed `G=6, D=128` (`0.41–0.67× SDPA`) or 16K passkey retention (`4b` drops to `1/5`), making Mixed KIVI's primary win **5.06× KV capacity headroom at 5/5 Passkey**.

---

## 6. Deployment Guide & CLI Usage (`v0.7.0`)

xFermat is distributed as a clean open runtime on PyPI (`xfermat`) alongside commercial offline surgery modules:

```bash
# Install xFermat runtime with LLM streaming dependencies
pip install "xfermat[llm]"

# Verify Metal GPU kernels and report system rooflines
xfermat info
xfermat bench --json

# Run local model with fused 4-bit or 3.16-bit KIVI KV cache
xfermat run Qwen/Qwen2.5-1.5B-Instruct --kv-bits 4 --prompt "Explain Fermat's principle of least time."

# Run long-context inference with salient channel promotion
xfermat run ./my-model --kv-bits 2 --kv-outlier-ratio 0.625 --prompt "Summarize this document..."

# Offline Weight Surgery (Clip-GPTQ, Untied Head, Calibration)
xfermat compress Qwen/Qwen2.5-0.5B-Instruct --method hadamard_4bit --calib-tokens 16384 --save-dir ./qwen-4b
xfermat compress TinyLlama/TinyLlama-1.1B-Chat-v1.0 --method hadamard_3bit --head-bits 8 --save-dir ./tiny-3b-head8
```

---

## 7. Complete Bibliography (18 Foundational Publications)

### Peer-Reviewed Conference & Journal Publications

1. **Hiroyuki Ootomo, Katsuhisa Ozaki, and Rio Yokota.** 2024. DGEMM on Integer Matrix Multiplication Unit. *International Journal of High Performance Computing Applications (IJHPCA)*, 2024.
2. **Manuel Kauers and Jakob Moosbauer.** 2023. Flip Graphs for Matrix Multiplication. In *Proceedings of the 2023 International Symposium on Symbolic and Algebraic Computation (ISSAC '23)*, pp. 385–392.
3. **Tri Dao, Beidi Chen, Nimit Sohoni, Arjun Desai, Michael Poli, Jessica Grogan, Alexander Liu, Aniruddh Rao, Atri Rudra, and Christopher Ré.** 2022. Monarch: Expressive Structured Matrices for Efficient and Accurate Training. In *Proceedings of the 39th International Conference on Machine Learning (ICML 2022)*, PMLR 162:4690–4721.
4. **Albert Tseng, Jerry Chee, Qingyao Sun, Volodymyr Kuleshov, and Christopher De Sa.** 2024. QuIP#: Even Better LLM Quantization with Hadamard Incoherence and Lattice Codebooks. In *Proceedings of the 41st International Conference on Machine Learning (ICML 2024)*, PMLR 235:48651–48680.
5. **Tri Dao, Daniel Y. Fu, Stefano Ermon, Atri Rudra, and Christopher Ré.** 2022. FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. In *Advances in Neural Information Processing Systems (NeurIPS 2022)*, 35:16344–16359.
6. **Andrew Lavin and Scott Gray.** 2016. Fast Algorithms for Convolutional Neural Networks. In *IEEE Conference on Computer Vision and Pattern Recognition (CVPR 2016)*, pp. 4013–4021.
7. **Tri Dao and Albert Gu.** 2024. Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality. In *Proceedings of the 41st International Conference on Machine Learning (ICML 2024)*, PMLR 235:10065–10100.
8. **Zechun Liu, Changsheng Zhao, Igor Fedorov, Bilge Soran, Dhruv Choudhary, Raghuraman Krishnamoorthi, Vikas Chandra, Yuandong Tian, and Tijmen Blankevoort.** 2025. SpinQuant: LLM Quantization with Learned Rotations. In *International Conference on Learning Representations (ICLR 2025)*.
9. **Elias Frantar, Saleh Ashkboos, Torsten Hoefler, and Dan Alistarh.** 2023. GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers. In *International Conference on Learning Representations (ICLR 2023)*.
10. **Yifei Liu, Jicheng Wen, Yang Wang, Shengyu Ye, Li Lyna Zhang, Ting Cao, Cheng Li, and Mao Yang.** 2024. VPTQ: Extreme Low-Bit Vector Post-Training Quantization for Large Language Models. In *Proceedings of the 2024 Conference on Empirical Methods in Natural Language Processing (EMNLP 2024)*.
11. **Vage Egiazarian, Andrei Panferov, Denis Kuznedelev, Elias Frantar, Artem Babenko, and Dan Alistarh.** 2024. Extreme Compression of Large Language Models via Additive Quantization (AQLM). In *Proceedings of the 41st International Conference on Machine Learning (ICML 2024)*, PMLR 235:12301–12328.
12. **Wenqi Shao, Mengzhao Chen, Zhaoyang Zhang, Peng Xu, Lirui Zhao, Zhiqian Li, Kaipeng Zhang, Peng Gao, Yu Qiao, and Ping Luo.** 2024. OmniQuant: Omnidirectionally Calibrated Quantization for Large Language Models. In *International Conference on Learning Representations (ICLR 2024)*.
13. **Zirui Liu, Jiayi Yuan, Hongye Jin, Shaochen Zhong, Zhaozhuo Xu, Vladimir Braverman, Beidi Chen, and Xia Hu.** 2024. KIVI: A Tuning-Free Asymmetric 2-bit Quantization for KV Cache. In *Proceedings of the 41st International Conference on Machine Learning (ICML 2024)*, PMLR 235:32466–32488.
14. **Junxiong Wang, Daniele Paliotta, Avner May, Alexander M. Rush, and Tri Dao.** 2024. The Mamba in the Llama: Distilling and Accelerating Hybrid Models. In *Advances in Neural Information Processing Systems (NeurIPS 2024)*.
15. **Aviv Bick, Kevin Y. Li, Eric P. Xing, J. Zico Kolter, and Albert Gu.** 2024. Transformers to SSMs: Distilling Quadratic Knowledge to Subquadratic Models (MOHAWK). In *Advances in Neural Information Processing Systems (NeurIPS 2024)*.

### Preprints & Technical Reports (arXiv)

16. **Yuki Uchino, Katsuhisa Ozaki, and Toshiyuki Imamura.** 2025. Ozaki Scheme II: A GEMM-oriented emulation of floating-point matrix multiplication using an integer modular technique. *arXiv preprint arXiv:2504.08009*.
17. **Alexander Novikov et al. (Google DeepMind).** 2025. AlphaEvolve: A coding agent for scientific and algorithmic discovery. *arXiv preprint arXiv:2506.13131*.
18. **OpenTensor Contributors.** 2024. OpenTensor: Reproducing Faster Matrix Multiplication Discovering Algorithms. *arXiv preprint arXiv:2405.20748*.
