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.
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.
Writes single or sharded 4 GB safetensors (model*.safetensors), layer reconstruction metadata (xfermat_quant_config.json), model config.json, and tokenizer files.
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
"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).
"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.
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
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.0Latest 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.
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.0KIVI & 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.5Bvptq_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.
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.
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.
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.
xFermat Concierge
Verified v0.7.0 Specs · Offline Zero-Cost
Ready. Ask about Apple Silicon RAM sizing, Clip-GPTQ vs. mlx_lm.awq, --kv-bits 4|2, 2-bit E2E-QP / VPTQ PV-tuning, Qwen2.5-3B 8 GB Mac capacity, or Pro/Enterprise licensing.