xfermat 0.6.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fermat/__init__.py ADDED
@@ -0,0 +1,69 @@
1
+ """xFermat Open Runtime (`v0.6.0`): Apple Silicon Metal Kernels, KIVI KV Cache & Safetensors Inference.
2
+
3
+ Note: Proprietary offline compression & distillation compiler modules (`surgery`, `codebook`,
4
+ `distill`) are omitted from the public open-runtime package; see https://xfermat.com/pricing.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from fermat.bilinear import (
10
+ alphaevolve_4x4_complex_matmul,
11
+ bilinear_tensor_matmul,
12
+ gauss_complex_matmul,
13
+ load_alphaevolve_tensors,
14
+ load_alphatensor_factorizations,
15
+ winograd_strassen_matmul,
16
+ )
17
+ from fermat.engine import FermatEngine
18
+ from fermat.io_algebra import WinogradConv2d, flash_tiled_attention
19
+ from fermat.kv_quant import FermatKIVICache, QuantizedKVCache, make_kivi_prompt_cache
20
+ from fermat.model import FermatBlock, FermatConfig, FermatModel, PreallocatedKVCache
21
+ from fermat.persistence import load_compressed_model, save_compressed_model
22
+ from fermat.rns_ozaki import CRTModularGEMM, OZAKI2_MODULI_24, OZAKI_SLICE_MODULI_11
23
+ from fermat.ssd_mamba import SSDLayer, ssd_chunked_scan
24
+ from fermat.structured import (
25
+ FermatFinalNorm,
26
+ HadamardQuantLinear,
27
+ MonarchLinear,
28
+ apply_inverse_hadamard,
29
+ apply_randomized_hadamard,
30
+ fast_walsh_hadamard,
31
+ gptq_quantize_linear,
32
+ )
33
+ from fermat.ternary import OzakiHadamardTernaryLinear
34
+
35
+ __version__ = "0.6.0"
36
+
37
+ __all__ = [
38
+ "CRTModularGEMM",
39
+ "FermatBlock",
40
+ "FermatConfig",
41
+ "FermatEngine",
42
+ "FermatFinalNorm",
43
+ "FermatKIVICache",
44
+ "FermatModel",
45
+ "HadamardQuantLinear",
46
+ "MonarchLinear",
47
+ "OZAKI2_MODULI_24",
48
+ "OZAKI_SLICE_MODULI_11",
49
+ "OzakiHadamardTernaryLinear",
50
+ "PreallocatedKVCache",
51
+ "QuantizedKVCache",
52
+ "SSDLayer",
53
+ "WinogradConv2d",
54
+ "alphaevolve_4x4_complex_matmul",
55
+ "apply_inverse_hadamard",
56
+ "apply_randomized_hadamard",
57
+ "bilinear_tensor_matmul",
58
+ "fast_walsh_hadamard",
59
+ "flash_tiled_attention",
60
+ "gauss_complex_matmul",
61
+ "gptq_quantize_linear",
62
+ "load_alphaevolve_tensors",
63
+ "load_alphatensor_factorizations",
64
+ "load_compressed_model",
65
+ "make_kivi_prompt_cache",
66
+ "save_compressed_model",
67
+ "ssd_chunked_scan",
68
+ "winograd_strassen_matmul",
69
+ ]
fermat/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Module execution entry point (`python -m fermat`)."""
2
+
3
+ from fermat.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())
Binary file
Binary file
Binary file
fermat/bilinear.py ADDED
@@ -0,0 +1,292 @@
1
+ """Pillar 2: Sub-Cubic Bilinear Tensor Decompositions on Metal GPU.
2
+
3
+ Implements:
4
+ - Novikov et al. (2025), AlphaEvolve rank-48 <4,4,4> complex matrix multiplication
5
+ breaking Strassen's 56-year two-level bound of 49 (arXiv:2506.13131).
6
+ - Fawzi et al. (2022), AlphaTensor & Kauers-Moosbauer (2023) Flip Graph bilinear
7
+ decompositions loaded from verified official tensor artifacts (arXiv:2212.01175).
8
+ - Winograd's 7-multiply / 15-addition Strassen variant with fused pre/post-additions
9
+ and single-launch batched leaf GEMMs (cf. Huang et al. 2020; Jangda 2025 SubCuber).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import pathlib
15
+ from functools import lru_cache
16
+
17
+ import mlx.core as mx
18
+ import numpy as np
19
+
20
+ def _default_tensor_dir() -> pathlib.Path:
21
+ """Resolve bundled package tensors first, falling back to repo artifacts/tensors."""
22
+ pkg_dir = pathlib.Path(__file__).resolve().parent / "_tensors"
23
+ if (pkg_dir / "alphaevolve_tensors.npz").exists():
24
+ return pkg_dir
25
+ return pathlib.Path(__file__).resolve().parents[2] / "artifacts" / "tensors"
26
+
27
+
28
+ DEFAULT_TENSOR_DIR = _default_tensor_dir()
29
+
30
+
31
+ @lru_cache(maxsize=4)
32
+ def load_alphaevolve_tensors(tensor_dir: pathlib.Path = DEFAULT_TENSOR_DIR) -> dict[str, tuple[np.ndarray, np.ndarray, np.ndarray, int, int, int]]:
33
+ """Load verified AlphaEvolve bilinear tensor decompositions from disk."""
34
+ path = tensor_dir / "alphaevolve_tensors.npz"
35
+ if not path.exists():
36
+ raise FileNotFoundError(f"Missing AlphaEvolve tensors at {path}; run scripts/download_literature_and_tensors.py")
37
+ data = np.load(path)
38
+ out = {}
39
+ specs = {
40
+ "ae_245_r32": (2, 4, 5),
41
+ "ae_333_r23": (3, 3, 3),
42
+ "ae_444_r48": (4, 4, 4),
43
+ "ae_445_r61": (4, 4, 5),
44
+ "ae_555_r93": (5, 5, 5),
45
+ }
46
+ for key, (n, m, p) in specs.items():
47
+ out[key] = (data[f"{key}_u"], data[f"{key}_v"], data[f"{key}_w"], n, m, p)
48
+ return out
49
+
50
+
51
+ @lru_cache(maxsize=2)
52
+ def load_alphatensor_factorizations(tensor_dir: pathlib.Path = DEFAULT_TENSOR_DIR) -> dict[str, tuple[np.ndarray, np.ndarray, np.ndarray]]:
53
+ """Load official AlphaTensor real bilinear decompositions."""
54
+ path = tensor_dir / "factorizations_r.npz"
55
+ if not path.exists():
56
+ raise FileNotFoundError(f"Missing AlphaTensor factorizations at {path}")
57
+ data = np.load(path, allow_pickle=True)
58
+ return {k: tuple(data[k]) for k in data.files}
59
+
60
+
61
+ @mx.compile
62
+ def _winograd_pre_add(A: mx.array, B: mx.array) -> tuple[mx.array, mx.array]:
63
+ """Fused Winograd-Strassen pre-additions (8 matrix ops -> batched (7, ...) operands)."""
64
+ m2 = A.shape[0] // 2
65
+ k2 = A.shape[1] // 2
66
+ n2 = B.shape[1] // 2
67
+
68
+ A11, A12 = A[:m2, :k2], A[:m2, k2:]
69
+ A21, A22 = A[m2:, :k2], A[m2:, k2:]
70
+ B11, B12 = B[:k2, :n2], B[:k2, n2:]
71
+ B21, B22 = B[k2:, :n2], B[k2:, n2:]
72
+
73
+ S1 = A21 + A22
74
+ S2 = S1 - A11
75
+ S3 = A11 - A21
76
+ S4 = A12 - S2
77
+
78
+ T1 = B12 - B11
79
+ T2 = B22 - T1
80
+ T3 = B22 - B12
81
+ T4 = T2 - B21
82
+
83
+ left = mx.stack([A11, A12, S4, A22, S1, S2, S3], axis=0)
84
+ right = mx.stack([B11, B21, B22, T4, T1, T2, T3], axis=0)
85
+ return left, right
86
+
87
+
88
+ @mx.compile
89
+ def _winograd_post_add(P: mx.array) -> mx.array:
90
+ """Fused Winograd-Strassen post-additions (7 additions from 7 block products)."""
91
+ M1, M2, M3, M4, M5, M6, M7 = P[0], P[1], P[2], P[3], P[4], P[5], P[6]
92
+ U1 = M1 + M2
93
+ U2 = M1 + M6
94
+ U3 = U2 + M7
95
+ U4 = U2 + M5
96
+ U5 = U4 + M3
97
+ U6 = U3 - M4
98
+ U7 = U3 + M5
99
+ top = mx.concatenate([U1, U5], axis=1)
100
+ bot = mx.concatenate([U6, U7], axis=1)
101
+ return mx.concatenate([top, bot], axis=0)
102
+
103
+
104
+ def winograd_strassen_matmul(A: mx.array, B: mx.array, cutoff: int = 512) -> mx.array:
105
+ """Sub-cubic O(N^2.807) Winograd-Strassen GPU matmul with fused pre/post-additions.
106
+
107
+ Automatically pads non-even dimensions and bottoms out to a single batched 7-way
108
+ ``mx.matmul`` when child tiles fit inside ``cutoff``.
109
+ """
110
+ M, K = A.shape
111
+ K2, N = B.shape
112
+ if K != K2:
113
+ raise ValueError(f"Incompatible shapes {A.shape} and {B.shape}")
114
+
115
+ if min(M, K, N) <= cutoff:
116
+ return mx.matmul(A, B)
117
+
118
+ pad_m = M % 2
119
+ pad_k = K % 2
120
+ pad_n = N % 2
121
+ Ap = mx.pad(A, [(0, pad_m), (0, pad_k)]) if (pad_m or pad_k) else A
122
+ Bp = mx.pad(B, [(0, pad_k), (0, pad_n)]) if (pad_k or pad_n) else B
123
+
124
+ left, right = _winograd_pre_add(Ap, Bp)
125
+ child_min = min(left.shape[1], left.shape[2], right.shape[2])
126
+ if child_min <= cutoff:
127
+ products = mx.matmul(left, right)
128
+ else:
129
+ products = mx.stack(
130
+ [winograd_strassen_matmul(left[i], right[i], cutoff=cutoff) for i in range(7)],
131
+ axis=0,
132
+ )
133
+ out = _winograd_post_add(products)
134
+ if pad_m or pad_n:
135
+ out = out[:M, :N]
136
+ return out
137
+
138
+
139
+ def gauss_complex_matmul(
140
+ A_re: mx.array,
141
+ A_im: mx.array,
142
+ B_re: mx.array,
143
+ B_im: mx.array,
144
+ ) -> tuple[mx.array, mx.array]:
145
+ """Gauss 3-real-multiplication complex matmul (25% fewer GEMMs than naive 4M).
146
+
147
+ Computes (A_re + i A_im) @ (B_re + i B_im) using 3 batched real GEMMs:
148
+ P1 = A_re @ B_re
149
+ P2 = A_im @ B_im
150
+ P3 = (A_re + A_im) @ (B_re + B_im)
151
+ Re = P1 - P2, Im = P3 - P1 - P2
152
+ Supports both 2D (M, K) and batched 3D (R, M, K) inputs.
153
+ """
154
+ stack_axis = -3 if A_re.ndim >= 2 else 0
155
+ left = mx.concatenate([A_re[..., None, :, :], A_im[..., None, :, :], (A_re + A_im)[..., None, :, :]], axis=stack_axis)
156
+ right = mx.concatenate([B_re[..., None, :, :], B_im[..., None, :, :], (B_re + B_im)[..., None, :, :]], axis=stack_axis)
157
+ # Flatten leading batch dims so a single mx.matmul executes all 3M GEMMs at once.
158
+ lead_shape = left.shape[:-3]
159
+ L2 = left.reshape((-1, left.shape[-2], left.shape[-1]))
160
+ R2 = right.reshape((-1, right.shape[-2], right.shape[-1]))
161
+ P = mx.matmul(L2, R2).reshape((*lead_shape, 3, left.shape[-2], right.shape[-1]))
162
+ p1 = P[..., 0, :, :]
163
+ p2 = P[..., 1, :, :]
164
+ p3 = P[..., 2, :, :]
165
+ return p1 - p2, p3 - p1 - p2
166
+
167
+
168
+ def alphaevolve_4x4_complex_matmul(
169
+ A_re: mx.array,
170
+ A_im: mx.array,
171
+ B_re: mx.array,
172
+ B_im: mx.array,
173
+ cutoff: int = 256,
174
+ ) -> tuple[mx.array, mx.array]:
175
+ """Sub-cubic <4,4,4> rank-48 complex matmul from DeepMind AlphaEvolve (2025).
176
+
177
+ Multiplies 4x4 block-partitioned complex matrices in 48 complex block products
178
+ (instead of 64 naive or 49 two-level Strassen), and accelerates each block product
179
+ via Gauss's 3-real-multiply identity (144 real GEMMs vs 256 naive = 43.75% FLOP cut).
180
+ """
181
+ M, K = A_re.shape
182
+ K2, N = B_re.shape
183
+ if K != K2:
184
+ raise ValueError(f"Incompatible shapes {A_re.shape} and {B_re.shape}")
185
+
186
+ if min(M, K, N) <= cutoff:
187
+ return gauss_complex_matmul(A_re, A_im, B_re, B_im)
188
+
189
+ pad_m = (-M) % 4
190
+ pad_k = (-K) % 4
191
+ pad_n = (-N) % 4
192
+ if pad_m or pad_k:
193
+ A_re = mx.pad(A_re, [(0, pad_m), (0, pad_k)])
194
+ A_im = mx.pad(A_im, [(0, pad_m), (0, pad_k)])
195
+ if pad_k or pad_n:
196
+ B_re = mx.pad(B_re, [(0, pad_k), (0, pad_n)])
197
+ B_im = mx.pad(B_im, [(0, pad_k), (0, pad_n)])
198
+
199
+ Mp, Kp = A_re.shape
200
+ Np = B_re.shape[1]
201
+ bm, bk, bn = Mp // 4, Kp // 4, Np // 4
202
+
203
+ u, v, w, _, _, _ = load_alphaevolve_tensors()["ae_444_r48"]
204
+ # w maps products -> C^T (k*4 + i); transpose block indices (k, i) -> (i, k) once here.
205
+ w_t = w.reshape(4, 4, 48).transpose(1, 0, 2).reshape(16, 48)
206
+
207
+ dtype = A_re.dtype
208
+ U_re, U_im = mx.array(u.real, dtype=dtype), mx.array(u.imag, dtype=dtype)
209
+ V_re, V_im = mx.array(v.real, dtype=dtype), mx.array(v.imag, dtype=dtype)
210
+ W_re, W_im = mx.array(w_t.real, dtype=dtype), mx.array(w_t.imag, dtype=dtype)
211
+
212
+ # Reshape into 16 tiles: (4, bm, 4, bk) -> (16, bm * bk)
213
+ A_t_re = A_re.reshape(4, bm, 4, bk).transpose(0, 2, 1, 3).reshape(16, bm * bk)
214
+ A_t_im = A_im.reshape(4, bm, 4, bk).transpose(0, 2, 1, 3).reshape(16, bm * bk)
215
+ B_t_re = B_re.reshape(4, bk, 4, bn).transpose(0, 2, 1, 3).reshape(16, bk * bn)
216
+ B_t_im = B_im.reshape(4, bk, 4, bn).transpose(0, 2, 1, 3).reshape(16, bk * bn)
217
+
218
+ # Linear combinations for all 48 rank-1 factors: (48, bm, bk) and (48, bk, bn)
219
+ L_re = (mx.matmul(U_re.T, A_t_re) - mx.matmul(U_im.T, A_t_im)).reshape(48, bm, bk)
220
+ L_im = (mx.matmul(U_re.T, A_t_im) + mx.matmul(U_im.T, A_t_re)).reshape(48, bm, bk)
221
+ R_re = (mx.matmul(V_re.T, B_t_re) - mx.matmul(V_im.T, B_t_im)).reshape(48, bk, bn)
222
+ R_im = (mx.matmul(V_re.T, B_t_im) + mx.matmul(V_im.T, B_t_re)).reshape(48, bk, bn)
223
+
224
+ if min(bm, bk, bn) <= cutoff:
225
+ P_re, P_im = gauss_complex_matmul(L_re, L_im, R_re, R_im)
226
+ else:
227
+ re_list, im_list = [], []
228
+ for idx in range(48):
229
+ pr, pi = alphaevolve_4x4_complex_matmul(L_re[idx], L_im[idx], R_re[idx], R_im[idx], cutoff=cutoff)
230
+ re_list.append(pr)
231
+ im_list.append(pi)
232
+ P_re = mx.stack(re_list, axis=0)
233
+ P_im = mx.stack(im_list, axis=0)
234
+
235
+ P_re_flat = P_re.reshape(48, bm * bn)
236
+ P_im_flat = P_im.reshape(48, bm * bn)
237
+ C_t_re = mx.matmul(W_re, P_re_flat) - mx.matmul(W_im, P_im_flat)
238
+ C_t_im = mx.matmul(W_re, P_im_flat) + mx.matmul(W_im, P_re_flat)
239
+
240
+ C_re = C_t_re.reshape(4, 4, bm, bn).transpose(0, 2, 1, 3).reshape(Mp, Np)[:M, :N]
241
+ C_im = C_t_im.reshape(4, 4, bm, bn).transpose(0, 2, 1, 3).reshape(Mp, Np)[:M, :N]
242
+ return C_re, C_im
243
+
244
+
245
+ def bilinear_tensor_matmul(
246
+ A: mx.array,
247
+ B: mx.array,
248
+ tensor_key: str = "ae_333_r23",
249
+ source: str = "alphaevolve",
250
+ ) -> mx.array:
251
+ """Multiply two real matrices using any downloaded AlphaEvolve or AlphaTensor <n,m,p;R> scheme."""
252
+ if source == "alphaevolve":
253
+ u, v, w, n, m, p = load_alphaevolve_tensors()[tensor_key]
254
+ elif source == "alphatensor":
255
+ parts = [int(x) for x in tensor_key.split(",")]
256
+ n, m, p = parts[0], parts[1], parts[2]
257
+ u, v, w = load_alphatensor_factorizations()[tensor_key]
258
+ else:
259
+ raise ValueError(f"Unknown tensor source: {source}")
260
+
261
+ if np.iscomplexobj(u) or np.iscomplexobj(v) or np.iscomplexobj(w):
262
+ raise ValueError(f"Tensor {tensor_key} is complex; call alphaevolve_4x4_complex_matmul instead")
263
+
264
+ M, K = A.shape
265
+ K2, N = B.shape
266
+ if K != K2:
267
+ raise ValueError(f"Incompatible shapes {A.shape} and {B.shape}")
268
+
269
+ pad_m = (-M) % n
270
+ pad_k = (-K) % m
271
+ pad_n = (-N) % p
272
+ Ap = mx.pad(A, [(0, pad_m), (0, pad_k)]) if (pad_m or pad_k) else A
273
+ Bp = mx.pad(B, [(0, pad_k), (0, pad_n)]) if (pad_k or pad_n) else B
274
+
275
+ Mp, Kp = Ap.shape
276
+ Np = Bp.shape[1]
277
+ bm, bk, bn = Mp // n, Kp // m, Np // p
278
+ rank = u.shape[1]
279
+
280
+ w_t = w.reshape(p, n, rank).transpose(1, 0, 2).reshape(n * p, rank)
281
+ U = mx.array(u, dtype=A.dtype)
282
+ V = mx.array(v, dtype=B.dtype)
283
+ W = mx.array(w_t, dtype=A.dtype)
284
+
285
+ A_tiles = Ap.reshape(n, bm, m, bk).transpose(0, 2, 1, 3).reshape(n * m, bm * bk)
286
+ B_tiles = Bp.reshape(m, bk, p, bn).transpose(0, 2, 1, 3).reshape(m * p, bk * bn)
287
+
288
+ L = mx.matmul(U.T, A_tiles).reshape(rank, bm, bk)
289
+ R = mx.matmul(V.T, B_tiles).reshape(rank, bk, bn)
290
+ P = mx.matmul(L, R).reshape(rank, bm * bn)
291
+ C_tiles = mx.matmul(W, P).reshape(n, p, bm, bn).transpose(0, 2, 1, 3).reshape(Mp, Np)
292
+ return C_tiles[:M, :N]
fermat/cli.py ADDED
@@ -0,0 +1,244 @@
1
+ """Command-line interface for xFermat Open Runtime (`info`, `bench`, and `run`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ import time
9
+ from pathlib import Path
10
+ from typing import Any, Optional, Sequence
11
+
12
+ import mlx.core as mx
13
+ import numpy as np
14
+
15
+ from fermat import (
16
+ CRTModularGEMM,
17
+ FermatConfig,
18
+ FermatModel,
19
+ HadamardQuantLinear,
20
+ __version__,
21
+ flash_tiled_attention,
22
+ load_compressed_model,
23
+ make_kivi_prompt_cache,
24
+ )
25
+ from fermat.bilinear import DEFAULT_TENSOR_DIR
26
+
27
+ PILLARS: tuple[tuple[str, str], ...] = (
28
+ ("1. Modular Exact FP64", "CRT-Ozaki II all-GPU modular FP64 matrix multiplication"),
29
+ ("2. Bilinear Tensors", "AlphaEvolve rank-48 complex & Winograd-Strassen sub-cubic GEMM"),
30
+ ("3. Structured Runtime", "Monarch O(D sqrt(D)), fused block-FWHT, Hadamard & ternary layers"),
31
+ ("4. IO-Aware Kernels", "simdgroup_float8x8 / half8x8 FlashAttention & fused KIVI KV cache"),
32
+ ("5. State Space Duality", "Mamba-2 O(L) chunked SSD scan & O(1) autoregressive cache"),
33
+ )
34
+
35
+
36
+ def _cmd_info() -> int:
37
+ tensor_files = ("alphaevolve_tensors.npz", "factorizations_r.npz", "factorizations_f2.npz")
38
+ found = [name for name in tensor_files if (DEFAULT_TENSOR_DIR / name).exists()]
39
+ print(f"xFermat Open Runtime v{__version__}")
40
+ print(f"Device : {mx.default_device()}")
41
+ print(f"Tensor Dir : {DEFAULT_TENSOR_DIR}")
42
+ print(f"Bundled NPZ : {', '.join(found) if found else 'missing'} ({len(found)}/{len(tensor_files)})")
43
+ print("\nPillars:")
44
+ for title, desc in PILLARS:
45
+ print(f" - {title}: {desc}")
46
+ return 0
47
+
48
+
49
+ def _cmd_bench(as_json: bool = False) -> int:
50
+ rng = np.random.default_rng(7)
51
+ a64 = rng.standard_normal((64, 64), dtype=np.float64)
52
+ b64 = rng.standard_normal((64, 64), dtype=np.float64)
53
+ ref64 = a64 @ b64
54
+ crt = CRTModularGEMM(backend="gpu_120bit")
55
+ out64 = crt.matmul(a64, b64, scheme="ozaki2")
56
+ ozaki_rel_err = float(np.linalg.norm(out64 - ref64) / np.linalg.norm(ref64))
57
+
58
+ mx.random.seed(11)
59
+ w = (mx.random.normal((256, 256)) * 0.05).astype(mx.float16)
60
+ x_in = mx.random.normal((8, 256)).astype(mx.float16)
61
+ mx.eval(w, x_in)
62
+ y_ref = (x_in @ w.T).astype(mx.float32)
63
+ hq = HadamardQuantLinear.from_linear(w, bits=4, group_size=64, seed=42, two_sided=False)
64
+ y_q = hq(x_in).astype(mx.float32)
65
+ mx.eval(y_ref, y_q)
66
+ denom = mx.sqrt(mx.sum(y_ref * y_ref)) * mx.sqrt(mx.sum(y_q * y_q)) + 1e-12
67
+ hadamard_cos_sim = float((mx.sum(y_ref * y_q) / denom).item())
68
+ compression_ratio = float(w.nbytes) / max(float(hq.quantized_bytes), 1.0)
69
+
70
+ q = mx.random.normal((1, 4, 512, 64)).astype(mx.float16)
71
+ k = mx.random.normal((1, 4, 512, 64)).astype(mx.float16)
72
+ v = mx.random.normal((1, 4, 512, 64)).astype(mx.float16)
73
+ warm = flash_tiled_attention(q, k, v, causal=True)
74
+ mx.eval(warm)
75
+ t0 = time.perf_counter()
76
+ attn_out = flash_tiled_attention(q, k, v, causal=True)
77
+ mx.eval(attn_out)
78
+ flash_ms = (time.perf_counter() - t0) * 1000.0
79
+
80
+ cfg = FermatConfig(
81
+ d_model=128,
82
+ d_ff=256,
83
+ n_layers=4,
84
+ n_heads=4,
85
+ out_dim=256,
86
+ vocab_size=256,
87
+ mixer_type="hybrid_ssd_flash",
88
+ projection_type="monarch",
89
+ causal=True,
90
+ )
91
+ model = FermatModel(cfg)
92
+ prompt = mx.random.randint(0, 256, shape=(1, 16))
93
+ _, warm_cache = model.forward_with_cache(prompt)
94
+ mx.eval(warm_cache[0])
95
+ ssd_state_shape = list(warm_cache[0].shape)
96
+ t1 = time.perf_counter()
97
+ gen = model.generate(prompt, max_new_tokens=16, greedy=True)
98
+ mx.eval(gen)
99
+ hybrid_dt = max(time.perf_counter() - t1, 1e-6)
100
+ hybrid_tps = 16.0 / hybrid_dt
101
+
102
+ payload: dict[str, Any] = {
103
+ "version": __version__,
104
+ "device": str(mx.default_device()),
105
+ "crt_ozaki2_64x64_rel_err": ozaki_rel_err,
106
+ "hadamard_4bit_compression_x": round(compression_ratio, 3),
107
+ "hadamard_4bit_cos_sim": round(hadamard_cos_sim, 6),
108
+ "flash_fp16_512_ms": round(flash_ms, 3),
109
+ "hybrid_ssd_state_shape": ssd_state_shape,
110
+ "hybrid_generate_tok_s": round(hybrid_tps, 2),
111
+ }
112
+ if as_json:
113
+ print(json.dumps(payload, indent=2))
114
+ else:
115
+ print(f"xFermat Open Runtime v{__version__} ({payload['device']})")
116
+ print(f" CRT-Ozaki II 64x64 rel err : {ozaki_rel_err:.3e}")
117
+ print(f" Hadamard 4-bit 256x256 : {compression_ratio:.2f}x smaller ({hadamard_cos_sim * 100:.2f}% cos sim)")
118
+ print(f" FlashAttention FP16 L=512 : {flash_ms:.2f} ms")
119
+ print(f" Hybrid 3:1 O(1) Generate : {hybrid_tps:.1f} tok/s (SSD state shape {ssd_state_shape})")
120
+ return 0
121
+
122
+
123
+ def _generate_prompt(model: Any, tokenizer: Any, prompt: str, max_tokens: int, kv_bits: int = 0) -> None:
124
+ import mlx_lm
125
+ from mlx_lm.sample_utils import make_sampler
126
+
127
+ formatted = (
128
+ tokenizer.apply_chat_template(
129
+ [{"role": "user", "content": prompt}],
130
+ tokenize=False,
131
+ add_generation_prompt=True,
132
+ )
133
+ if getattr(tokenizer, "chat_template", None) is not None and hasattr(tokenizer, "apply_chat_template")
134
+ else prompt
135
+ )
136
+ prompt_cache = make_kivi_prompt_cache(model, bits=kv_bits) if kv_bits in (2, 4) else None
137
+ mx.reset_peak_memory()
138
+ sampler = make_sampler(temp=0.0)
139
+ parts: list[str] = []
140
+ last_resp = None
141
+ for resp in mlx_lm.stream_generate(
142
+ model,
143
+ tokenizer,
144
+ formatted,
145
+ max_tokens=max_tokens,
146
+ sampler=sampler,
147
+ prompt_cache=prompt_cache,
148
+ ):
149
+ parts.append(resp.text)
150
+ last_resp = resp
151
+ text = "".join(parts).strip()
152
+ print(f"\nOutput:\n{text}")
153
+ if last_resp is not None:
154
+ kv_str = ""
155
+ if prompt_cache is not None:
156
+ kv_mb = sum(c.nbytes for c in prompt_cache) / (1024**2)
157
+ kv_str = f" | KIVI {kv_bits}-bit KV: {kv_mb:.2f} MB"
158
+ print(
159
+ f"\nDecode: {last_resp.generation_tps:.1f} tok/s | "
160
+ f"Prefill: {last_resp.prompt_tps:.1f} tok/s | "
161
+ f"Peak GPU RAM: {last_resp.peak_memory:.3f} GB{kv_str}"
162
+ )
163
+
164
+
165
+ def _cmd_run(args: argparse.Namespace) -> int:
166
+ try:
167
+ import mlx_lm
168
+ except ImportError:
169
+ print("Install LLM support via: pip install 'xfermat[llm]'", file=sys.stderr)
170
+ return 2
171
+
172
+ target = Path(args.saved_dir)
173
+ if target.is_dir() and (target / "xfermat_quant_config.json").exists():
174
+ print(f"Loading saved xFermat model from {args.saved_dir} on {mx.default_device()}...")
175
+ model, tokenizer = load_compressed_model(args.saved_dir)
176
+ else:
177
+ print(f"Loading model '{args.saved_dir}' via mlx_lm on {mx.default_device()}...")
178
+ loaded = mlx_lm.load(args.saved_dir)
179
+ model, tokenizer = loaded[0], loaded[1]
180
+ if tokenizer is None:
181
+ print("No tokenizer found for model.", file=sys.stderr)
182
+ return 2
183
+ _generate_prompt(model, tokenizer, args.prompt, args.max_tokens, kv_bits=args.kv_bits)
184
+ return 0
185
+
186
+
187
+ def _cmd_compress(_args: argparse.Namespace) -> int:
188
+ print(
189
+ "Offline Weight Surgery (Clip-GPTQ, 4D VPTQ) and MOHAWK distillation ship in xFermat Pro / Enterprise "
190
+ "(https://xfermat.com/pricing — ask@xfermat.com).\n"
191
+ "Use `xfermat info`, `xfermat bench`, or `xfermat run <model_or_dir> --kv-bits 4|2` in this free Open Runtime.",
192
+ file=sys.stderr,
193
+ )
194
+ return 2
195
+
196
+
197
+ def build_parser() -> argparse.ArgumentParser:
198
+ parser = argparse.ArgumentParser(
199
+ prog="xfermat",
200
+ description="xFermat v0.6.0 Open Runtime: Apple Silicon Metal GPU kernels, KIVI KV-cache & compressed model runner.",
201
+ )
202
+ sub = parser.add_subparsers(dest="command", required=True)
203
+ sub.add_parser("info", help="Show version, device, bundled tensor status, and pillars.")
204
+
205
+ bench_p = sub.add_parser("bench", help="Run fast live GPU verification & micro-benchmarks.")
206
+ bench_p.add_argument("--json", action="store_true", help="Emit machine-readable JSON output.")
207
+
208
+ run_p = sub.add_parser("run", help="Load a compressed xFermat directory or Hugging Face / mlx-lm model and generate text.")
209
+ run_p.add_argument("saved_dir", help="Local xFermat compressed model directory or Hugging Face / mlx-lm repo ID.")
210
+ run_p.add_argument(
211
+ "--prompt",
212
+ default="Explain Fermat's principle of least time in 2 clear sentences.",
213
+ help="Prompt to run on the saved model.",
214
+ )
215
+ run_p.add_argument("--max-tokens", type=int, default=64, help="Maximum generated tokens.")
216
+ run_p.add_argument(
217
+ "--kv-bits",
218
+ type=int,
219
+ default=0,
220
+ choices=(0, 4, 2),
221
+ help="KIVI KV-cache bit-width during generation (0 disables, 4 or 2 enables fused Metal KIVI cache).",
222
+ )
223
+
224
+ comp_p = sub.add_parser("compress", help="Offline Weight Surgery & VPTQ compiler (xFermat Pro / Enterprise).")
225
+ comp_p.add_argument("extra", nargs=argparse.REMAINDER, help="Passed arguments (Pro/Enterprise CLI only).")
226
+ return parser
227
+
228
+
229
+ def main(argv: Optional[Sequence[str]] = None) -> int:
230
+ """Entry point for the ``xfermat`` CLI and ``python -m fermat``."""
231
+ args = build_parser().parse_args(argv)
232
+ if args.command == "info":
233
+ return _cmd_info()
234
+ if args.command == "bench":
235
+ return _cmd_bench(as_json=args.json)
236
+ if args.command == "run":
237
+ return _cmd_run(args)
238
+ if args.command == "compress":
239
+ return _cmd_compress(args)
240
+ return 1
241
+
242
+
243
+ if __name__ == "__main__":
244
+ raise SystemExit(main())