PRODUCT DOCUMENTATION · V0.7.0

Install, Compress Qwen, and Run on Apple Silicon

Everything needed to install xfermat from PyPI (pip install "xfermat[llm]") or the standalone xfermat-0.7.0-py3-none-any.whl, run models locally on Apple Silicon with KIVI KV compression, and call the CLI or Python SDK.

01 / INSTALLATION & WHEEL CONTENTS

Install xfermat from PyPI or Offline .whl

xfermat-0.7.1-py3-none-any.whl (published on PyPI as xfermat) is the pure-source distribution of the xFermat Open Inference Runtime. You do not compile C++ or run Xcode manually: installing registers the fermat Python runtime, the xfermat CLI, JIT-compiled Metal Shading Language kernels (via MLX), and the three bundled bilinear tensor archives (alphaevolve_tensors.npz, factorizations_r.npz, factorizations_f2.npz).

Open-Core Scope & Requirements: Requires macOS on Apple Silicon (M-series GPU) and Python >= 3.12 (mlx >= 0.20.0, numpy >= 1.26.0, scipy >= 1.12.0; append [llm] for Hugging Face / mlx-lm support). The public PyPI & GitHub package ships the full Open Inference Runtime (info, bench, run, KIVI KV-cache, Metal FlashDecode, Mamba-2 SSD, CRT-Ozaki FP64); proprietary offline Weight Surgery (compress / Clip-GPTQ / 4D VPTQ) and MOHAWK distillation ship separately in xFermat Pro & Enterprise.
Terminal — Install the downloaded wheel & verify GPU setup
# Install the Open Inference Runtime from PyPI with Hugging Face / mlx-lm support:
pip install "xfermat[llm]"
# Or install directly from the offline wheel:
uv pip install "./xfermat-0.7.1-py3-none-any.whl[llm]"

# Core-only install (matrix engine, attention, SSD, KIVI, CRT FP64 without HF bridge):
pip install xfermat

# Verify Apple Silicon Metal device, bundled tensor archives, and kernels:
xfermat info
xfermat bench --json
02 / END-TO-END GUIDE

Compressing & Running Qwen2.5 Locally

The primary production workflow loads an uncompressed BF16 Hugging Face checkpoint once, folds orthogonal random block-Hadamard R1 rotations offline into embeddings, RMSNorm weights, and projections, runs layer-by-layer full-Hessian GPU sequential GPTQ calibration, and writes standard safetensors weights plus tokenizer files to disk for sub-second cold reloads (~0.7 s on Qwen2.5-1.5B).

Option A — Zero-code Terminal CLI

bash — Compress once, then reload and prompt Qwen2.5
# 1. Stream any Hugging Face / mlx-lm model directly with live 4-bit KIVI KV cache (Open Runtime):
xfermat run Qwen/Qwen2.5-1.5B-Instruct \
  --kv-bits 4 \
  --prompt "Explain Fermat's principle of least time in two sentences." \
  --max-tokens 128

# 2. Or reload a compressed safetensors directory in ~0.55 s with KIVI KV compression:
xfermat run ./qwen2.5-1.5b-3bit \
  --kv-bits 4 \
  --prompt "Explain Fermat's principle of least time in two sentences." \
  --max-tokens 128

# [xFermat Pro / Enterprise Offline Compiler] Compress a BF16 checkpoint once:
xfermat compress Qwen/Qwen2.5-1.5B-Instruct \
  --method hadamard_3bit \
  --calib-tokens 16384 \
  --save-dir ./qwen2.5-1.5b-3bit

Option B — Full Python SDK Script

qwen_quickstart.py — Calibrated 3-bit / 4-bit compression, save & reload
import mlx.core as mx
import mlx_lm
from fermat import (
    compress_pretrained_model,
    save_compressed_model,
    load_compressed_model,
    compute_effective_bpw,
)

# 1. Load BF16 Qwen2.5 checkpoint + tokenizer + config
model, tokenizer, config = mlx_lm.load("Qwen/Qwen2.5-1.5B-Instruct", return_config=True)

# 2. Build disjoint domain calibration sequences (token ID arrays of shape (1, T))
cal_texts = [
    "Optics obeys Fermat's principle of least time across inhomogeneous media.",
    "Apple Silicon unified memory lets GPU kernels operate directly without host copies.",
]
cal_batches = [mx.array([tokenizer.encode(t)], dtype=mx.int32) for t in cal_texts]

# 3. Fold offline R1 rotations & run layer-by-layer full-Hessian GPU GPTQ (or vptq_2bit 4D vector VQ)
_, report = compress_pretrained_model(
    model,
    method="hadamard_3bit",   # "hadamard_4bit", "hadamard_3bit", "mixed_2_3bit", or "vptq_2bit"
    group_size=64,
    calibration_inputs=cal_batches,
    damp=0.05,
    embed_bits=8,
    fold_r1="auto",           # active when calibration_inputs is supplied
    online_r4="auto",         # enabled at 2/3-bit on down_proj, disabled at 4-bit / vptq_2bit
    act_order=False,
)
bpw = compute_effective_bpw(model)
print(
    f"Replaced {report.layers_replaced} layers: "
    f"{report.compression_ratio:.2f}x smaller (-{report.memory_saved_pct:.1f}%) "
    f"bpw: {bpw['linear_bpw']:.2f} linear / {bpw['model_bpw']:.2f} model"
)

# 4. Save standard safetensors + xfermat_quant_config.json + tokenizer (~0.55 s cold reload)
save_compressed_model(model, "./qwen2.5-1.5b-3bit", tokenizer=tokenizer, config=config, report=report)

reloaded_model, reloaded_tok = load_compressed_model("./qwen2.5-1.5b-3bit")
print(mlx_lm.generate(reloaded_model, reloaded_tok, prompt="Explain Fermat's principle.", max_tokens=128))
03 / COMMAND-LINE TOOL

xfermat CLI Reference

Installing the wheel exposes both xfermat and fermat entrypoints (or python -m fermat). Four subcommands cover hardware verification, quick GPU self-checks, one-shot Hugging Face compression, and cached local text generation.

Command Key Flags & Defaults Purpose
xfermat info — Prints package version, active Metal GPU device, tensor archive directory (3 bundled .npz files), and capability pillars.
xfermat bench --json Runs a quick live GPU micro-check: CRT FP64 error, 4-bit Hadamard compression, FlashAttention latency, and SSD hybrid decode tok/s.
xfermat compress <model_id> --method hadamard_4bit (or hadamard_3bit, mixed_2_3bit, vptq_2bit, hadamard_2bit, ozaki_ternary_1slice, ozaki_ternary_2slice)
--group-size 64 · --embed-bits 8 · --head-bits 16|8
--calibrate (default on) / --no-calibrate
--calib-tokens 16384 · --calib-file PATH (hardcoded damp=0.05)
--act-order · --fold-r1 / --no-fold-r1 (default "auto")
--online-r4 auto|true|false · --block-ft-steps 0
--e2e-qp-steps 0 · --pv-tune-steps 0
--kv-bits 0|4|2 · --kv-outlier-ratio 0.625
--save-dir PATH · --prompt TEXT · --max-tokens 64
Loads an mlx_lm checkpoint, applies surgery (calibrated R1+GPU GPTQ, mixed_2_3bit, or MAP 4D VQ with PV tuning and optional E2E-QP fine-tuning; disabling calibration with --no-calibrate automatically skips R1 via fold_r1="auto" to match native RTN), optionally saves safetensors, and optionally runs a prompt (with GQA-packed KIVI KV cache via --kv-bits 4|2).
xfermat run <saved_dir> --kv-bits 0|4|2 · --prompt TEXT · --max-tokens 64 Reloads a compressed directory (model*.safetensors + xfermat_quant_config.json) in under a second and streams generated text (with optional 4-bit or 2-bit fused Metal KIVI KV cache).
04 / MODEL SURGERY & PERSISTENCE

Python Surgery & Safetensors API

Open-Core Note: Pretrained model compression (compress_pretrained_model, surgery, 4D VPTQ codebook) is part of the private commercial compiler in xFermat Pro & Enterprise; save_compressed_model and load_compressed_model are included in the Open Runtime so any compressed directory reloads cleanly in ~0.7 s. For supported Pre-Norm RMSNorm SwiGLU Transformers (Qwen2, Qwen2.5, Qwen3, Llama, Mistral), compress_pretrained_model replaces eligible linear and embedding modules in-place and returns (model, CompressionReport). On 4-bit models with R1 folding and calibration enabled, every q/k/v/o/gate/up/down projection becomes a standard MLX nn.QuantizedLinear with zero online Hadamard overhead.

Symbol / Argument Default / Fields Behavior
compress_pretrained_model(...) method="hadamard_4bit", group_size=64, min_features=32, skip_names=("head", "lm_head"), seed=42, calibration_inputs=None, damp=0.05, embed_bits=None, head_bits=None, fold_r1="auto", online_r4="auto", block_ft_steps=0, e2e_qp_steps=0, pv_tune_steps=0, act_order=False fold_r1="auto" enables offline R1 rotation only when calibration_inputs is provided. e2e_qp_steps > 0 runs joint end-to-end proximal quantization fine-tuning. pv_tune_steps > 0 tunes projection-vector codebook blocks. head_bits sets untied lm_head quantization (e.g. 8).
finetune_e2e_qp(...) (model, inputs, teacher_logits=None, *, steps=50, lr=1e-4) -> dict End-to-end proximal fine-tuning for low-bit weights, restoring accuracy on challenging 2-bit configurations.
pv_tune_vq_blocks(...) (blocks, inputs, targets, *, steps=40, outer_rounds=2, lr=4e-4) -> dict Projection-vector tuning for VQ codebook blocks, driving 0.5B VPTQ 2-bit perplexity down to 26.73 WT2 PPL.
compute_effective_bpw(...) (model) -> dict[str, float] Returns {'linear_bpw': ..., 'model_bpw': ...} across quantized projections, embeddings, scales, and unquantized heads.
CompressionReport method, layers_replaced, orig_weight_bytes, compressed_weight_bytes, compression_ratio, memory_saved_pct Returned alongside the mutated module; also serialized into xfermat_quant_config.json when saving.
save_compressed_model(...) (model, save_dir, tokenizer=None, config=None, report=None) -> Path Writes single or sharded 4 GB safetensors (model*.safetensors), layer reconstruction metadata (xfermat_quant_config.json), model config.json, and tokenizer files.
load_compressed_model(...) (save_dir, model=None, lazy=False, return_config=False) Reconstructs QuantizedLinear, QuantizedEmbedding, FermatFinalNorm, HadamardQuantLinear, FermatVectorQuantLinear (vptq_2bit), and ternary layers before loading safetensors; returns (model, tokenizer) (or 3-tuple with config).
05 / KERNELS & PRECISION ROUTING

FermatEngine, Attention & Double-Precision GPU Math

Use FermatEngine and flash_tiled_attention directly inside custom MLX graphs. Both default to auto routing so you keep Apple Silicon's fastest native hardware kernels where they win, while keeping exact GPU FP64 (Ozaki Scheme II CRT), GQA custom Metal FlashAttention, and sub-cubic bilinear decompositions available on demand.

engine_and_attention.py — Autotuned matmul, SDPA/Metal attention, and explicit FP64
import mlx.core as mx
import numpy as np
from fermat import CRTModularGEMM, FermatEngine, flash_tiled_attention

engine = FermatEngine()  # autotune=True by default

# 1. Autotuned real matrix multiply (selects native mx.matmul at 2048^2; Winograd-Strassen stays opt-in)
a = mx.random.normal((2048, 2048), dtype=mx.float16)
b = mx.random.normal((2048, 2048), dtype=mx.float16)
c = engine.matmul(a, b, mode="auto")

# 2. IO-aware attention: backend="auto" routes D in {64, 128} & L_q=1 to Apple Silicon SDPA;
#    pass backend="metal" for arbitrary head dims, BF16->FP32 accumulation, or custom GQA tiles
q = mx.random.normal((1, 12, 4096, 128), dtype=mx.float16)
k = mx.random.normal((1, 2, 4096, 128), dtype=mx.float16)
v = mx.random.normal((1, 2, 4096, 128), dtype=mx.float16)
attn_out = flash_tiled_attention(q, k, v, causal=True, backend="auto")

# 3. Opt-in 150-bit Garner CRT GPU FP64 accuracy (0.0 rel. err. across p=25..45)
a64 = np.random.randn(512, 512)
b64 = np.random.randn(512, 512)
c64_gpu = engine.matmul(a64, b64, mode="crt_fp64")  # mode="auto" routes float64 to fast CPU BLAS
API Call Modes / Options Verified Routing Behavior
FermatEngine(autotune=True).matmul(A, B, mode=...) "auto" (default), "native", "strassen", "alphaevolve_complex", "alphatensor", "crt_fp64", "crt_sliced_fp64" "auto" benchmarks shape tuples once with median timing + 10% hysteresis margin: picks native mx.matmul on 1024²/2048² real & complex64, 3M Gauss on complex tuples, and cpu_blas on np.float64 unless GPU CRT beats CPU by ≥10%. Explicit mode="crt_fp64" runs 24 pairwise-coprime moduli (packed into 3×50-bit Garner limbs) on Metal GPU (0.0 rel. err. across p=25..45).
flash_tiled_attention(Q, K, V, causal=False, backend=...) backend="auto" (default), "sdpa", "metal" "auto" dispatches standard head dimensions (D ∈ {64, 128}) and L_q = 1 decode to native mx.fast.scaled_dot_product_attention, while "metal" provides GQA-packed Stage-1 Metal decode plus FP32-accumulated GQA/arbitrary-D prefill tiles.
QuantizedKVCache(bits=2|4, group_size=64, residual_len=64, k_group_size=64, k_outlier_ratio=0.625) & FermatKIVICache .update(k, v), .decode_attention(...), make_kivi_prompt_cache(model, bits=4|2), .effective_bpw KIVI asymmetric per-channel Key (k_group_size=64) + per-token Value quantization with zero-copy full-precision prefill at offset == 0 and GQA-packed Stage-1 Metal decode kernel (1 threadgroup per KV head unpacking once across G query heads, factorized bias). Shrinks 16K GQA KV cache 5.06× (448 MB → 88.6 MB, 3.16 bpw) with 5/5 passkey retrieval and 10.51 PPL at 8K.
06 / RESEARCH ARCHITECTURE

From-Scratch & Distillable 3:1 Hybrid Sequence Model (FermatModel)

Distinct from pretrained LLM surgery, FermatModel implements a research hybrid backbone combining three linear-time Mamba-2 State Space Duality (SSDLayer) blocks with one causal RoPE + Flash/SDPA attention block and optional MonarchLinear projections (included in the Open Runtime). Streaming decode supports fixed SSD recurrent state plus either PreallocatedKVCache or QuantizedKVCache(kv_bits=2|4); progressive attention-to-SSD teacher distillation (distill_pretrained_layers_to_ssd, Pro/Enterprise compiler) converts real pretrained transformers (e.g. 6 of 24 attention layers on Qwen2.5-0.5B cutting 8K cache −24.56% at 14.46 val PPL) and outperforms equal-compute scratch training cleanly on 3-stage MOHAWK synthetic benchmarks (3.71 vs. 5.54 val PPL).

hybrid_research.py — Initialize & decode with 3:1 SSD + SDPA
import mlx.core as mx
from fermat import (
    FermatConfig,
    FermatModel,
    QuantizedKVCache,
    distill_attention_to_ssd,
    distill_pretrained_layers_to_ssd,
    FermatPretrainedSSDMixer,
)

# 1. From-scratch / distillable 3:1 Hybrid Mamba-2 SSD + causal RoPE SDPA backbone
cfg = FermatConfig(
    d_model=256,
    n_heads=4,
    n_layers=4,
    d_ff=512,
    vocab_size=1024,
    projection_type="monarch",        # O(D sqrt(D)) block-diagonal layers (or "dense")
    mixer_type="hybrid_ssd_flash",    # 3 SSD layers + 1 causal attention layer
    ssd_state_dim=16,
    ssd_chunk_size=64,
    ssd_d_conv=4,
    attn_backend="auto",
    use_rope=True,
)
model = FermatModel(cfg)

# 2. Decode with O(1) SSD state + 4-bit / 3.16-bpw KIVI QuantizedKVCache (5.06x smaller 16K KV; 5/5 passkey)
prompt = mx.random.randint(0, 1024, shape=(1, 512), dtype=mx.int32)
tokens = model.generate(prompt, max_new_tokens=64, kv_bits=4)

# 3. Pretrained LLM distillation: converts 6 of 24 layers of Qwen2.5-0.5B to SSD (-24.6% 8K KV cache)
# report = distill_pretrained_layers_to_ssd(pretrained_model, layer_indices=[3, 7, 11, 15, 19, 23])
07 / METHOD SELECTION & CAVEATS

Which Mode to Choose (Measured Scope)

Method / Feature Measured Result (Apple Silicon GPU) Recommended Scope & Caveats
hadamard_3bit (+ calibration) With Hessian-weighted scale clipping, achieves 17.99 WikiText-2 PPL on 0.5B (vs 23.27 AWQ and 39.12 native); on 1.5B hits 11.48 PPL (vs 13.02 AWQ); on 3B hits 10.42 PPL in 1.47 GB. Recommended default for 3.28–4.00× compression, beating native RTN & AWQ quality across all tested architectures.
hadamard_4bit (+ calibration) Cuts 0.5B WikiText-2 perplexity to 15.20 PPL (vs. 16.06 AWQ / 16.80 native) at decode parity (181.8 tok/s vs. 173.4 AWQ); 1.5B hits 10.34 PPL; 3B hits 9.43 PPL. Best choice when you want near-lossless generation at fast decode speed with ~0.55–1.18 s safetensors reload.
mixed_2_3bit (2/3-bit mixed) Achieves 56.9 tok/s and 16.01 WT2 PPL on Qwen2.5-3B in only 1.19 GB (4.93× smaller than BF16), unblocking 8 GB Macs without swap thrashing. Flagship choice for large models on constrained memory systems.
vptq_2bit (+ PV-tuning) Projection-vector fine-tuning (pv_tune_vq_blocks) drives 0.5B VPTQ 2-bit down to 26.73 WT2 PPL (4.02× compression, 234.6 MB); 2-bit E2E-QP hits 79.36 WT2 PPL. Extreme-compression tier: genuine sub-30 PPL 2-bit post-training quantization on Apple Silicon GPU.
FermatModel + QuantizedKVCache + distill_pretrained_layers_to_ssd 3:1 Hybrid + 16K Mixed KIVI adds 5.06× KV savings (3.16 bpw, 5/5 passkey); converting 6 of 24 layers of Qwen2.5-0.5B cuts 8K KV −24.6% with 14.46 final PPL. For long-context inference and hybrid sequence model distillation.
Show xFermat package release history (v0.3.0 – v0.7.0)
v0.7.0 Latest Release
2026-11-26

Rigorous Benchmarks across 0.5B–3B, 16K GQA-Packed KIVI (3.16 bpw), 150-Bit Garner CRT, Fused SwiGLU+RHT & Pretrained MOHAWK Distillation

  • Rigorous Multi-Model Benchmarks (0.5B, 1.1B, 1.5B, 3B): Measured on Apple Silicon Unified GPU: Qwen2.5-0.5B 4-bit hits 15.20 WT2 PPL at decode parity (181.8 vs 173.4 AWQ); 3-bit hits 17.99 WT2 PPL (vs. 23.27 AWQ, 39.12 native); Qwen2.5-1.5B VPTQ 2-bit achieves 16.63 WT2 PPL in 589.0 MB (5.00×); Qwen2.5-3B compresses 5,886 MB (~5.75 GiB OOM > 5.33 GiB) down to 1,474 MB (3-bit, 10.42 PPL) and 1,193 MB (mixed_2_3bit, 16.01 PPL, 56.9 tok/s) on 8 GB Macs.
  • 16K Context & GQA-Packed Metal Decode: Packed Stage-1 Metal decode kernel unifies Key/Value unpacking across G query heads per KV head with 62.5% key channels promoted to 4-bit, per-token 2-bit values, and a 64-token FP16 tail (3.16 bpw), cutting 16K KV memory 5.06× (448 MB → 88.6 MB) with 5/5 Passkey retrieval accuracy and decode parity at 8K (43.3 vs 43.6 t/s FP16).
  • Micro-Kernel Accelerations: Shuffle-only zero-barrier Metal FWHT (1.72× speedup over SRAM), Fused SwiGLU+RHT (2.14× speedup over naive), VQ4 GEMV (3.81× vs FP16 @ M=1), and arbitrary-dimension zero-pad ternary.
  • Pretrained LLM MOHAWK Distillation: Converted 6 of 24 layers of Qwen2.5-0.5B to linear SSD state space, cutting 8K KV cache memory by −24.56% (96 MB → 72.4 MB) with 14.46 val PPL on 3×256 eval subset.
  • 150-Bit Garner CRT: Expanded modular ring to 24 pairwise-coprime moduli (3×50-bit Garner limbs) + 11-modulus all-GPU sliced exactness, achieving 0.0 relative error across p=25..45 and 0.0 error vs 50-digit reference on κ=1e12 sliced.
Milestone Metric v0.6.0 Baseline v0.7.0 Release Protocol-Normalized Delta
0.5B 4-Bit Ratio vs BF16 1.104× BF16 (23.61 / 21.39 @ 3k) · 150.4 t/s 1.054× BF16 (15.20 / 14.42 @ 301k) · 181.8 t/s BF16 gap +10.4% → +5.4% (decode parity vs AWQ)
0.5B 3-Bit Ratio vs BF16 1.613× BF16 (34.50 / 21.39 @ 3k) · 2.5k cal 1.248× BF16 (17.99 / 14.42 @ 301k) · 16.4k cal BF16 gap +61.3% → +24.8% (−22.7% PPL vs AWQ)
2-Bit Frontier (0.5B / 1.5B) 106.47 WT2 (0.5B MAP EM) · 1.5B untested 26.73 PPL (0.5B PV) · 16.63 PPL (1.5B VPTQ, 589 MB) NaN-guarded PV-tuning (5.00× 1.5B; 4.02× 0.5B)
3B 8 GB Mac Capacity Untested (5,886 MB / ~5.75 GiB BF16 OOM) 1,474 MB (10.42 PPL) · 1,193 MB (16.01 PPL, 56.9 t/s) 4.93× smaller, unlocks 3B within 5.33 GiB limit
KIVI Context & GQA 8K max prototype · per-qhead unpack 16K Context · GQA Stage-1 (3.16 bpw) 2× context horizon, 5.06× leaner vs 16K FP16, 5/5 Passkey
Micro-Kernel FWHT 0.161 ms (8-barrier SRAM) 0.0936 ms (shuffle-only zero-barrier) 1.72× faster vs SRAM (4.54×–4.60× vs dense)
Pretrained Hybridization Synthetic toy models only Pretrained Qwen2.5-0.5B MOHAWK (6/24 layers) −24.6% 8K KV cache with 14.46 final PPL
CRT Precision 120-bit (7.56e-16 rel err) 150-bit Garner CRT (24 moduli / 3×50-bit limbs) 0.0 relative error on Apple Silicon GPU
v0.6.0 MAP 4D VQ & Live KIVI
2026-11-25

De-Conflicted MAP 4D VQ (4.85× Faster), Differentiable Block Reconstruction (159.1 PPL @ 145.2 tok/s) & Live Pretrained KIVI

  • Contention-Free M-Step & MAP + GN Polish (codebook.py, structured.py): Replaced scattered atomic M-step sums with row-tiled SRAM Metal kernels (fermat_vq4_mstep_reduce), Bayesian MAP shrinkage, and 2-step damped full-Hessian Gauss-Newton post-GPTQ polish—cutting vptq_2bit surgery 4.85× (572.4 s → 118.0 s) and beating v0.4.0 WT2 PPL (106.47 vs. 110.31).
  • Differentiable Block Reconstruction (surgery.py, cli.py): Added opt-in finetune_vq_blocks (--block-ft-steps) jointly optimizing frozen-index centroids, scales & RMSNorms—hitting 159.12 in-dom PPL (15.3× below scalar 2-bit) at 145.16 tok/s (unthrottled; Clip-GPTQ 3b/4b reach 144.1 / 150.4 tok/s).
  • Live Pretrained KIVI & Stage-1 Tuning (kv_quant.py, cli.py): Added FermatKIVICache / make_kivi_prompt_cache + --kv-bits 4|2 on live Qwen2.5 (2.86× / 3.66× KV cut at 65.5 / 62.5 tok/s) and cut Stage-1 8K 2-bit Metal latency 0.834 ms → 0.710 ms.
v0.5.0 KIVI & User-POV
2026-11-24

Block-Grouped 2-Bit KIVI (0.912–0.927 Cos), Adaptive M-Step + Vectorized VQ4 Metal GEMV & User-POV Pipeline

  • Block-Grouped 2-Bit KIVI (kv_quant.py): Added configurable time-chunk k_group_size=64 Key grouping inside fused Metal decode, raising RoPE-outlier 2-bit cosine vs. SDPA from 0.574–0.692 to 0.912–0.927 (5.06× smaller KV, 3.16 MB vs. 16.0 MB at 8K, 0.834 ms; 0.475 ms at 4K D=128).
  • Adaptive M-Step + Vectorized uint32/float4 VQ4 GEMV (codebook.py): Per-layer Hessian-weighted least-squares centroid updates (m_steps=2) + vectorized SRAM GEMV cut Qwen2.5-0.5B vptq_2bit in-domain PPL to 184.22 (13.2× lower than scalar 2-bit GPTQ 2,434.93; 120.69 WikiText-2; 90.91 tok/s; QAT still needed at 2-bit).
  • User-POV Prompt Screen & Pipeline: Replaced side-by-side layout with a 3-stage sequential translation pipeline, added the interactive real-time User-POV prompt latency screen, and adopted the frameless 25-dot 5×5 Fermat eigen-wave matrix mark.
v0.4.0 4D VQ & KIVI
2026-11-24

4D Vector Quantization, Scale-Clipped GPTQ, KIVI KV Cache, Split-KV FlashDecode & Teacher Distillation

  • 4D Vector Quantization (codebook.py, --method vptq_2bit): 256×4 antipodal Gaussian Lloyd-Max centroids + Block-4 Cholesky GPU GPTQ + threadgroup-SRAM Metal GEMV (FermatVectorQuantLinear).
  • Hessian-Weighted Scale Clipping (structured.py): 4-bit R1+Clip-GPTQ beats mlx_lm.awq on both 0.5B benchmarks (50.49 vs. 54.26 in-domain PPL; 23.61 vs. 23.86 WikiText-2; KL 0.09978, −25% vs. AWQ); 3-bit cuts KL 47% vs. AWQ (0.42316 vs. 0.79175; 34.50 WikiText-2 PPL).
  • Split-KV L_q=1 FlashDecode & KIVI QuantizedKVCache (io_algebra.py, kv_quant.py, model.py): Custom Metal L_q=1 GQA decode matches Apple Silicon SDPA at 8K (cos=1.0), paired with KIVI 2-bit/4-bit fused Metal decode.
  • Progressive Attention-to-SSD Distillation (distill.py): Two-stage MOHAWK/MambaInLlama distillation (init_hybrid_from_attention_teacher + distill_attention_to_ssd).
v0.3.1 Surgery & Routing
2026-11-24

Offline R1 Folding, Sharded Safetensors Persistence & Hardware Autotuning

  • Offline R1 Folding & Auto Guard (surgery.py): Folded Hadamard R1 rotations directly into embeddings, RMSNorms, and linear weights (zero runtime Hadamard ops at 4-bit) with fold_r1="auto" protecting uncalibrated calls against RTN regression.
  • Sub-Second Persistence (persistence.py): Added sharded 4 GB safetensors serialization + xfermat_quant_config.json metadata achieving ~0.70–0.87 s cold reloads on Qwen2.5-1.5B & 0.5B.
  • Autotuner & SDPA Dispatch (engine.py, io_algebra.py, model.py): Added median + 10% hysteresis autotuning across matmul backends, native SDPA auto-routing, and fair O(1) 8K PreallocatedKVCache hybrid decode (3.99× cache reduction, 1.21× decode speedup).
v0.3.0 Initial Release
2026-11-24

Initial Five-Pillar Apple Silicon Metal Engine & xfermat CLI

  • Five Mathematical Pillars: Shipped CRT-Ozaki II exact 120-bit GPU FP64 (7.56e-16 rel. err.), AlphaEvolve/AlphaTensor/Winograd-Strassen bilinear kernels, Monarch + SpinQuant/GPTQ + 1.58-bit/2-slice T-MAC Metal LUTs, custom simdgroup FlashAttention & Winograd Conv2d, and 3:1 Mamba-2 SSD forward/reverse-scan Metal kernels.
  • Wheel Package & CLI: Released fermat-0.3.0-py3-none-any.whl, bundled .npz tensor archives, the xfermat CLI, and Qwen2.5 3-bit/4-bit quantization surgery.