Jakevin commited on
Commit
8e6dc72
·
verified ·
1 Parent(s): a9bf912

Sync GitHub e6270bc: group 128 option, ragged-batch GEMM split, cleanup

Browse files
README.md CHANGED
@@ -24,6 +24,12 @@ A ternary value carries log2(3) ≈ 1.585 bits, plus one 16-bit scale for every
24
 
25
  Ternary currently occupies 2.25 bits per weight resident, the same as MLX 2-bit. The point is an extra supported format with no speed loss, not smaller files.
26
 
 
 
 
 
 
 
27
  The reference is the dequantized ternary matrix, `max|y − ref| / max|ref|`. The bound is 1e-3. The largest probed case was 1.44e-6 (64×6144, batch 32). Errors on the timed shapes were at most 4e-7. Those probes used scales that are exact in half precision. The batch ≥ 32 GEMM stages dequantized weights as half, so with arbitrary float32 scales its error is set by half rounding of `scale` (seen up to about 3e-4, still under 1e-3); the GEMV path stays near 1e-7.
28
 
29
  ## Load a layer
@@ -88,22 +94,22 @@ Codes are int8 `{-1, 0, +1}`, stored as `{0, 1, 2}`. Four codes fill one uint8,
88
  | 4–5 | 4t+2 |
89
  | 6–7 | 4t+3 |
90
 
91
- `weight` has shape `[output, K/4]` uint8. `scales` has shape `[output, K/64]`. `K` is a multiple of 64. The value is `(code - 1) * scale`. Code 3 is rejected.
92
 
93
  MLX affine 2-bit stores the same codes, 16 per uint32, lane `i` in bits `[2i, 2i+2)`, with a scale and a bias per group. Ternary checkpoints use bias = `-scale`. `from_mlx_2bit` checks that and returns the byte layout above. On this machine the uint32 bytes and the 4-per-byte layout are the same little-endian sequence.
94
 
95
  ## What the kernels do
96
 
97
- * Batch 1, or any batch whose size, row count, or `K` is not a multiple of 32: simdgroup GEMV. `K` multiple of 512 uses two output rows per simdgroup and 16 weights per lane. Other `K`, including 640, uses a 4-wide dot plus a scalar tail.
98
- * Batch ≥ 32 with batch, rows, and `K` all multiples of 32: 32×32×32 simdgroup-matrix GEMM. Weights are staged as half in the threadgroup; the accumulator stays float. The 32-wide K tile never crosses a scale group of 64.
99
  * Batches up to 8 use a bounded LRU of compiled graphs keyed by shape (no weight references held); larger batches dispatch directly.
100
 
101
  ## Limits
102
 
103
  * Apple Silicon, through MLX Metal.
104
- * Group size is 64. `K` is a multiple of 64. There is no per-group zero point.
105
  * The layer returns the dtype of `x`. The kernel accumulates in float32.
106
- * Inputs may be non-contiguous views; they are copied to row-major first. An empty batch returns an empty result without a kernel launch. `tern_matmul` checks that `codes` is `[N, K/4]` and `scales` is `[N, K/64]`.
107
  * Parameters are frozen. This package does not choose scales or codes.
108
  * `from_quantized_linear` accepts an affine 2-bit `QuantizedLinear` whose codes are in {0, 1, 2} and whose per-group bias equals `-scale`. Other bit widths and other biases raise `ValueError`.
109
  * The 1e-3 figure is the kernel's error against the packed ternary matrix.
 
24
 
25
  Ternary currently occupies 2.25 bits per weight resident, the same as MLX 2-bit. The point is an extra supported format with no speed loss, not smaller files.
26
 
27
+ ## Group size 128 (option)
28
+
29
+ The default is one scale per 64 weights. Pass `group_size=128` to `TernaryLinear`, `from_mlx_2bit` and `from_trits`, or `group=128` to `tern_matmul`; `from_quantized_linear` picks it up from the layer. One scale per 128 weights stores 2 + 16/128 = 2.125 bits per weight. The codes are the same; only `scales` changes to `[N, K/128]`, and `K` must be a multiple of 128.
30
+
31
+ On d3-nano (150-question eval, argmax agreement with bf16, mean KL), the shipped model, whose one ternary unit is layer 19 `mlp.down_proj`, gives KL 0.0522 at both group 64 and group 128. A stress test with every 2-bit unit made ternary (197M ternary parameters) gives KL 0.0729 at group 64 and 0.0785 at group 128, about 8% worse; agreement is 136/150 for both. Batch 1 speed is the same as group 64; batch 128 GEMM was 1-20% slower on the timed shapes.
32
+
33
  The reference is the dequantized ternary matrix, `max|y − ref| / max|ref|`. The bound is 1e-3. The largest probed case was 1.44e-6 (64×6144, batch 32). Errors on the timed shapes were at most 4e-7. Those probes used scales that are exact in half precision. The batch ≥ 32 GEMM stages dequantized weights as half, so with arbitrary float32 scales its error is set by half rounding of `scale` (seen up to about 3e-4, still under 1e-3); the GEMV path stays near 1e-7.
34
 
35
  ## Load a layer
 
94
  | 4–5 | 4t+2 |
95
  | 6–7 | 4t+3 |
96
 
97
+ `weight` has shape `[output, K/4]` uint8. `scales` has shape `[output, K/64]` (or `[output, K/128]` with the group 128 option). `K` is a multiple of the group size. The value is `(code - 1) * scale`. Code 3 is rejected.
98
 
99
  MLX affine 2-bit stores the same codes, 16 per uint32, lane `i` in bits `[2i, 2i+2)`, with a scale and a bias per group. Ternary checkpoints use bias = `-scale`. `from_mlx_2bit` checks that and returns the byte layout above. On this machine the uint32 bytes and the 4-per-byte layout are the same little-endian sequence.
100
 
101
  ## What the kernels do
102
 
103
+ * Batch below 32, or a row count or `K` that is not a multiple of 32: simdgroup GEMV. `K` multiple of 512 uses two output rows per simdgroup and 16 weights per lane. Other `K`, including 640, uses a 4-wide dot plus a scalar tail.
104
+ * Batch ≥ 32 with rows and `K` multiples of 32: 32×32×32 simdgroup-matrix GEMM. Weights are staged as half in the threadgroup; the accumulator stays float. The 32-wide K tile never crosses a scale group. If the batch is not a multiple of 32, the leading multiple of 32 goes through the GEMM and the remaining rows through the GEMV (batch 100 on 6144×2048: 0.63 ms, was 2.67 ms all-GEMV).
105
  * Batches up to 8 use a bounded LRU of compiled graphs keyed by shape (no weight references held); larger batches dispatch directly.
106
 
107
  ## Limits
108
 
109
  * Apple Silicon, through MLX Metal.
110
+ * Group size is 64 (default) or 128. `K` is a multiple of the group size. There is no per-group zero point.
111
  * The layer returns the dtype of `x`. The kernel accumulates in float32.
112
+ * Inputs may be non-contiguous views; they are copied to row-major first. An empty batch returns an empty result without a kernel launch. `tern_matmul` checks that `codes` is `[N, K/4]` and `scales` is `[N, K/group]`.
113
  * Parameters are frozen. This package does not choose scales or codes.
114
  * `from_quantized_linear` accepts an affine 2-bit `QuantizedLinear` whose codes are in {0, 1, 2} and whose per-group bias equals `-scale`. Other bit widths and other biases raise `ValueError`.
115
  * The 1e-3 figure is the kernel's error against the packed ternary matrix.
src/mlx_ternary/__init__.py CHANGED
@@ -3,7 +3,8 @@
3
  """Ternary linear layers for MLX.
4
 
5
  Ternary carries about 1.85 bits of information per weight; it is stored
6
- in 2-bit slots, so the resident size is 2.25 bits, the same as MLX 2-bit.
 
7
  """
8
 
9
  from mlx_ternary.convert import from_mlx_2bit, unpack_mlx_2bit
@@ -11,6 +12,7 @@ from mlx_ternary.kernel import configure, set_cache_limit, tern_matmul
11
  from mlx_ternary.linear import TernaryLinear, replace_quantized_linears
12
  from mlx_ternary.pack import (
13
  GROUP,
 
14
  dequantize,
15
  info_bits_per_weight,
16
  pack_trits,
@@ -22,6 +24,7 @@ __version__ = "0.3.0"
22
 
23
  __all__ = [
24
  "GROUP",
 
25
  "TernaryLinear",
26
  "configure",
27
  "dequantize",
 
3
  """Ternary linear layers for MLX.
4
 
5
  Ternary carries about 1.85 bits of information per weight; it is stored
6
+ in 2-bit slots, so the resident size is 2.25 bits at group 64, the same as MLX 2-bit,
7
+ or 2.125 bits with the group 128 option.
8
  """
9
 
10
  from mlx_ternary.convert import from_mlx_2bit, unpack_mlx_2bit
 
12
  from mlx_ternary.linear import TernaryLinear, replace_quantized_linears
13
  from mlx_ternary.pack import (
14
  GROUP,
15
+ GROUPS,
16
  dequantize,
17
  info_bits_per_weight,
18
  pack_trits,
 
24
 
25
  __all__ = [
26
  "GROUP",
27
+ "GROUPS",
28
  "TernaryLinear",
29
  "configure",
30
  "dequantize",
src/mlx_ternary/convert.py CHANGED
@@ -12,7 +12,7 @@ from __future__ import annotations
12
  import mlx.core as mx
13
  import numpy as np
14
 
15
- from .pack import GROUP, pack_trits
16
 
17
  _LANES = 16
18
 
@@ -45,16 +45,16 @@ def from_mlx_2bit(weight, scales, biases, group_size: int = GROUP):
45
  """Repack MLX affine 2-bit ternary weights.
46
 
47
  ``weight`` is uint32 ``[N, K/16]``. ``scales`` and ``biases`` are
48
- ``[N, K/group_size]``. Codes must lie in ``{0, 1, 2}`` and ``biases``
49
  must equal ``-scales``. Returns uint8 codes ``[N, K/4]`` and float32 scales.
50
  """
51
- if group_size != GROUP:
52
- raise ValueError(f"group_size {group_size} != {GROUP}")
53
  words = _as_numpy(weight, mx.uint32, np.uint32)
54
  scale_f = np.ascontiguousarray(_as_numpy(scales, mx.float32, np.float32), dtype=np.float32)
55
  bias_f = np.ascontiguousarray(_as_numpy(biases, mx.float32, np.float32), dtype=np.float32)
56
  if words.ndim != 2 or scale_f.ndim != 2:
57
- raise ValueError("expected weight [N, K/16] and scales [N, K/64]")
58
  if bias_f.shape != scale_f.shape:
59
  raise ValueError(f"biases shape {bias_f.shape} != scales shape {scale_f.shape}")
60
  n, nwords = (int(v) for v in words.shape)
 
12
  import mlx.core as mx
13
  import numpy as np
14
 
15
+ from .pack import GROUP, GROUPS, pack_trits
16
 
17
  _LANES = 16
18
 
 
45
  """Repack MLX affine 2-bit ternary weights.
46
 
47
  ``weight`` is uint32 ``[N, K/16]``. ``scales`` and ``biases`` are
48
+ ``[N, K/group_size]`` with ``group_size`` 64 (default) or 128. Codes must lie in ``{0, 1, 2}`` and ``biases``
49
  must equal ``-scales``. Returns uint8 codes ``[N, K/4]`` and float32 scales.
50
  """
51
+ if group_size not in GROUPS:
52
+ raise ValueError(f"group_size {group_size} not in {GROUPS}")
53
  words = _as_numpy(weight, mx.uint32, np.uint32)
54
  scale_f = np.ascontiguousarray(_as_numpy(scales, mx.float32, np.float32), dtype=np.float32)
55
  bias_f = np.ascontiguousarray(_as_numpy(biases, mx.float32, np.float32), dtype=np.float32)
56
  if words.ndim != 2 or scale_f.ndim != 2:
57
+ raise ValueError("expected weight [N, K/16] and scales [N, K/group_size]")
58
  if bias_f.shape != scale_f.shape:
59
  raise ValueError(f"biases shape {bias_f.shape} != scales shape {scale_f.shape}")
60
  n, nwords = (int(v) for v in words.shape)
src/mlx_ternary/kernel.py CHANGED
@@ -3,14 +3,15 @@
3
  """Ternary GEMV and GEMM for MLX.
4
 
5
  Codes {-1,0,1} are stored as 2-bit values {0,1,2}, four per byte, low bits
6
- first. One scale per 64 weights and no zero point: value = (code - 1) * scale.
7
  The inner loop is the MLX 2-bit mask dot: pre-scale x by 1, 1/4, 1/16, 1/64
8
  and AND the byte.
9
 
10
  Small batches use a simdgroup GEMV. K multiple of 512 follows the MLX
11
  qmv_fast walk (two rows per simdgroup, 16 weights per lane). Other K,
12
- including 640, uses a 4-wide dot. Batch >= 32 with the batch, the row count,
13
- and K all divisible by 32 uses a 32x32x32 simdgroup-matrix GEMM. The weight
 
14
  tile is half, the accumulator is float, and a tile never crosses a scale group.
15
 
16
  Batches up to 8 run through a small LRU of compiled graphs keyed by shape.
@@ -21,9 +22,7 @@ from __future__ import annotations
21
 
22
  import mlx.core as mx
23
 
24
- from .pack import GROUP
25
-
26
- CACHE_LIMIT = 2 * 1024**3
27
 
28
 
29
  def set_cache_limit(gb: float = 2) -> int:
@@ -65,10 +64,10 @@ using namespace metal;
65
  """
66
 
67
 
68
- def metal(name: str, source: str, header: str = _HEADER, fast: bool = True):
69
  # MLX 0.22 metal_kernel has no compile_options. The cache key does not
70
  # include the source, so a body change must use a new name.
71
- key = (name, fast, header[:40])
72
  if key not in _KERNELS:
73
  _KERNELS[key] = mx.fast.metal_kernel(
74
  name=name,
@@ -92,10 +91,10 @@ def meta_u32(values: list[int]) -> mx.array:
92
 
93
 
94
  def _prepare(x, codes, scales, k, group):
95
- if group != GROUP:
96
- raise ValueError(f"group {group} != {GROUP}")
97
- if k % GROUP != 0:
98
- raise ValueError(f"K {k} is not a multiple of {GROUP}")
99
  if x.ndim == 1:
100
  x = x.reshape(1, -1)
101
  if not isinstance(x, mx.array):
@@ -118,6 +117,34 @@ def _prepare(x, codes, scales, k, group):
118
  return x, codes, scales, int(x.shape[0]), int(codes.shape[0])
119
 
120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  def _dot16_expr(w: str, vecdot: bool = False) -> str:
122
  if not vecdot:
123
  return (
@@ -615,8 +642,8 @@ def run_qmv_mlx(x, codes, scales, k, rows: int = 4, nsg: int = 2, group: int = G
615
  guarded = (n % rows_per_tg) != 0
616
  tg = nsg * 32
617
  n_tiles = (n + rows_per_tg - 1) // rows_per_tg
618
- name = f"mlxtern3_qmvmlx_r{rows}_s{nsg}" + ("_g" if guarded else "_a")
619
- ker = metal(name, _qmv_mlx_source(nsg, rows, guarded))
620
  (y,) = ker(
621
  inputs=[x, codes, scales, meta_u32([n, k, k // 4, k // group, b])],
622
  template=[("T", mx.float32)],
@@ -628,8 +655,7 @@ def run_qmv_mlx(x, codes, scales, k, rows: int = 4, nsg: int = 2, group: int = G
628
  return y
629
 
630
 
631
- def run_qmv(x, codes, scales, k, rows: int = QMV_ROWS, nsg: int = QMV_NSG, vpt: int = 16, use_lut: bool = False, fast: bool = True, group: int = GROUP, vecdot: bool = False, specialize: bool = True, narrow: bool = False, half_dot: bool = False, chunk128: bool = False):
632
- del vpt, use_lut
633
  x, codes, scales, b, n = _prepare(x, codes, scales, k, group)
634
  if rows not in (2, 4, 8) or nsg not in (1, 2, 4):
635
  raise ValueError(f"qmv rows={rows} nsg={nsg}")
@@ -650,9 +676,8 @@ def run_qmv(x, codes, scales, k, rows: int = QMV_ROWS, nsg: int = QMV_NSG, vpt:
650
  if half_dot:
651
  name += "_h"
652
  name += "_g" if guarded else "_a"
653
- if fast:
654
- name += "_fast"
655
- ker = metal(name, _qmv_source(nsg, rows, guarded, blocks, vecdot, narrow, half_dot, chunk128), fast=fast)
656
  (y,) = ker(
657
  inputs=[x, codes, scales, meta_u32([n, k, k // 4, k // group, b])],
658
  template=[("T", mx.float32)],
@@ -664,15 +689,14 @@ def run_qmv(x, codes, scales, k, rows: int = QMV_ROWS, nsg: int = QMV_NSG, vpt:
664
  return y
665
 
666
 
667
- def run_gemm(x, codes, scales, k, bm: int = GEMM_BM, bn: int = GEMM_BN, bk: int = GEMM_BK, safe: bool | None = None, fast: bool = True, group: int = GROUP, transpose_b: bool = True, use_lut: bool = False, wide_w: bool | None = None, half_w: bool = True, acc_half: bool = False):
668
- del safe, transpose_b, use_lut, wide_w, acc_half
669
  x, codes, scales, b, n = _prepare(x, codes, scales, k, group)
670
  if k % bk or n % bn or b % bm:
671
  raise ValueError(f"gemm tile {bm}x{bn}x{bk} does not cover N={n} K={k} B={b}")
672
  nsg = (bm // 16) * (bn // 16)
673
  tg = nsg * 32
674
- name = f"mlxtern3_u2g2_{bm}x{bn}x{bk}" + ("" if half_w else "_fw") + ("_fast" if fast else "")
675
- ker = metal(name, _gemm_source(bm, bn, bk, half_w), fast=fast)
676
  (y,) = ker(
677
  inputs=[x, codes, scales, meta_u32([n, k, k // 4, k // group, b])],
678
  template=[("T", mx.float32)],
@@ -715,6 +739,17 @@ def _dispatch(x, codes, scales, k: int, group: int):
715
  if tile is not None:
716
  bm, bn, bk = tile
717
  return run_gemm(x, codes, scales, k, bm, bn, bk, group=group)
 
 
 
 
 
 
 
 
 
 
 
718
  # K multiple of 512 uses the MLX qmv_fast walk (2 rows, 1 simdgroup).
719
  # Shorter K, including the 640-wide expert down projection, keeps the
720
  # 128-wide body, which is faster there.
@@ -723,6 +758,13 @@ def _dispatch(x, codes, scales, k: int, group: int):
723
  return run_qmv(x, codes, scales, k, group=group)
724
 
725
 
 
 
 
 
 
 
 
726
  def _gemm_launch(b: int, n: int, k: int) -> tuple[int, int, int] | None:
727
  if b < GEMM_MIN_BATCH or b % 32 or n % 32 or k % 32:
728
  return None
@@ -734,6 +776,8 @@ def _gemm_launch(b: int, n: int, k: int) -> tuple[int, int, int] | None:
734
  def tern_matmul(x, codes, scales, k: int, group: int = GROUP) -> mx.array:
735
  """x [B, K] or [K], codes uint8 [N, K/4], scales [N, K/group] -> [B, N].
736
 
 
 
737
  Batches up to ``COMPILE_MAX_BATCH`` reuse a compiled graph from a bounded
738
  LRU keyed by shape and dtype; weights are arguments, not captured, so the
739
  cache never keeps them alive. Larger batches dispatch the kernel directly.
@@ -744,10 +788,11 @@ def tern_matmul(x, codes, scales, k: int, group: int = GROUP) -> mx.array:
744
  if x.ndim == 0 or x.ndim > 2:
745
  raise ValueError(f"x must have shape [K] or [B, K], got ndim {x.ndim}")
746
  k = int(k)
747
- if group != GROUP:
748
- raise ValueError(f"group {group} != {GROUP}")
749
- if k <= 0 or k % GROUP:
750
- raise ValueError(f"K {k} is not a positive multiple of {GROUP}")
 
751
  if int(x.shape[-1]) != k:
752
  raise ValueError(f"x last dim {x.shape[-1]} != K {k}")
753
  if codes.ndim != 2 or int(codes.shape[1]) != k // 4:
 
3
  """Ternary GEMV and GEMM for MLX.
4
 
5
  Codes {-1,0,1} are stored as 2-bit values {0,1,2}, four per byte, low bits
6
+ first. One scale per 64 weights (or 128, as an option) and no zero point: value = (code - 1) * scale.
7
  The inner loop is the MLX 2-bit mask dot: pre-scale x by 1, 1/4, 1/16, 1/64
8
  and AND the byte.
9
 
10
  Small batches use a simdgroup GEMV. K multiple of 512 follows the MLX
11
  qmv_fast walk (two rows per simdgroup, 16 weights per lane). Other K,
12
+ including 640, uses a 4-wide dot. Batch >= 32 with the row count and K
13
+ divisible by 32 uses a 32x32x32 simdgroup-matrix GEMM; if the batch is not a
14
+ multiple of 32, the leftover rows go through the GEMV. The weight
15
  tile is half, the accumulator is float, and a tile never crosses a scale group.
16
 
17
  Batches up to 8 run through a small LRU of compiled graphs keyed by shape.
 
22
 
23
  import mlx.core as mx
24
 
25
+ from .pack import GROUP, GROUPS
 
 
26
 
27
 
28
  def set_cache_limit(gb: float = 2) -> int:
 
64
  """
65
 
66
 
67
+ def metal(name: str, source: str, header: str = _HEADER):
68
  # MLX 0.22 metal_kernel has no compile_options. The cache key does not
69
  # include the source, so a body change must use a new name.
70
+ key = (name, header[:40])
71
  if key not in _KERNELS:
72
  _KERNELS[key] = mx.fast.metal_kernel(
73
  name=name,
 
91
 
92
 
93
  def _prepare(x, codes, scales, k, group):
94
+ if group not in GROUPS:
95
+ raise ValueError(f"group {group} not in {GROUPS}")
96
+ if k % group != 0:
97
+ raise ValueError(f"K {k} is not a multiple of {group}")
98
  if x.ndim == 1:
99
  x = x.reshape(1, -1)
100
  if not isinstance(x, mx.array):
 
117
  return x, codes, scales, int(x.shape[0]), int(codes.shape[0])
118
 
119
 
120
+ # Kernel sources are written for group 64. Group 128 only changes how a
121
+ # weight index maps to its scale: k >> 7 instead of k >> 6, and one more
122
+ # lane bit per scale. Group 64 sources are left byte-identical.
123
+ _REGROUP_128 = (
124
+ ("k >> 6", "k >> 7"),
125
+ ("t >> 6", "t >> 7"),
126
+ ("(lane >> 2)", "(lane >> 3)"),
127
+ ("(lane >> 4)", "(lane >> 5)"),
128
+ ("((k0 + wc) >> 6)", "((k0 + wc) >> 7)"),
129
+ )
130
+
131
+
132
+ def _regroup(source: str, group: int) -> str:
133
+ if group == 64:
134
+ return source
135
+ if group != 128:
136
+ raise ValueError(f"group {group} not in {GROUPS}")
137
+ for old, new in _REGROUP_128:
138
+ source = source.replace(old, new)
139
+ if ">> 6" in source:
140
+ raise AssertionError("group 128 source still indexes scales by 64")
141
+ return source
142
+
143
+
144
+ def _gname(group: int) -> str:
145
+ return "" if group == 64 else f"_gs{group}"
146
+
147
+
148
  def _dot16_expr(w: str, vecdot: bool = False) -> str:
149
  if not vecdot:
150
  return (
 
642
  guarded = (n % rows_per_tg) != 0
643
  tg = nsg * 32
644
  n_tiles = (n + rows_per_tg - 1) // rows_per_tg
645
+ name = f"mlxtern3_qmvmlx_r{rows}_s{nsg}" + ("_g" if guarded else "_a") + _gname(group)
646
+ ker = metal(name, _regroup(_qmv_mlx_source(nsg, rows, guarded), group))
647
  (y,) = ker(
648
  inputs=[x, codes, scales, meta_u32([n, k, k // 4, k // group, b])],
649
  template=[("T", mx.float32)],
 
655
  return y
656
 
657
 
658
+ def run_qmv(x, codes, scales, k, rows: int = QMV_ROWS, nsg: int = QMV_NSG, group: int = GROUP, vecdot: bool = False, specialize: bool = True, narrow: bool = False, half_dot: bool = False, chunk128: bool = False):
 
659
  x, codes, scales, b, n = _prepare(x, codes, scales, k, group)
660
  if rows not in (2, 4, 8) or nsg not in (1, 2, 4):
661
  raise ValueError(f"qmv rows={rows} nsg={nsg}")
 
676
  if half_dot:
677
  name += "_h"
678
  name += "_g" if guarded else "_a"
679
+ name += "_fast" + _gname(group)
680
+ ker = metal(name, _regroup(_qmv_source(nsg, rows, guarded, blocks, vecdot, narrow, half_dot, chunk128), group))
 
681
  (y,) = ker(
682
  inputs=[x, codes, scales, meta_u32([n, k, k // 4, k // group, b])],
683
  template=[("T", mx.float32)],
 
689
  return y
690
 
691
 
692
+ def run_gemm(x, codes, scales, k, bm: int = GEMM_BM, bn: int = GEMM_BN, bk: int = GEMM_BK, group: int = GROUP, half_w: bool = True):
 
693
  x, codes, scales, b, n = _prepare(x, codes, scales, k, group)
694
  if k % bk or n % bn or b % bm:
695
  raise ValueError(f"gemm tile {bm}x{bn}x{bk} does not cover N={n} K={k} B={b}")
696
  nsg = (bm // 16) * (bn // 16)
697
  tg = nsg * 32
698
+ name = f"mlxtern3_u2g2_{bm}x{bn}x{bk}" + ("" if half_w else "_fw") + "_fast" + _gname(group)
699
+ ker = metal(name, _regroup(_gemm_source(bm, bn, bk, half_w), group))
700
  (y,) = ker(
701
  inputs=[x, codes, scales, meta_u32([n, k, k // 4, k // group, b])],
702
  template=[("T", mx.float32)],
 
739
  if tile is not None:
740
  bm, bn, bk = tile
741
  return run_gemm(x, codes, scales, k, bm, bn, bk, group=group)
742
+ head = _gemm_head(b, n, k)
743
+ if head:
744
+ # Batch >= 32 but not a multiple of 32: the leading multiple of 32
745
+ # rows go through the GEMM, the remainder through the GEMV.
746
+ top = run_gemm(x[:head], codes, scales, k, GEMM_BM, GEMM_BN, GEMM_BK, group=group)
747
+ rest = _gemv(x[head:], codes, scales, k, group)
748
+ return mx.concatenate([top, rest], axis=0)
749
+ return _gemv(x, codes, scales, k, group)
750
+
751
+
752
+ def _gemv(x, codes, scales, k: int, group: int):
753
  # K multiple of 512 uses the MLX qmv_fast walk (2 rows, 1 simdgroup).
754
  # Shorter K, including the 640-wide expert down projection, keeps the
755
  # 128-wide body, which is faster there.
 
758
  return run_qmv(x, codes, scales, k, group=group)
759
 
760
 
761
+ def _gemm_head(b: int, n: int, k: int) -> int:
762
+ """Rows of a ragged batch that the GEMM can take; 0 if none."""
763
+ if b < GEMM_MIN_BATCH or n % 32 or k % 32:
764
+ return 0
765
+ return (b // 32) * 32
766
+
767
+
768
  def _gemm_launch(b: int, n: int, k: int) -> tuple[int, int, int] | None:
769
  if b < GEMM_MIN_BATCH or b % 32 or n % 32 or k % 32:
770
  return None
 
776
  def tern_matmul(x, codes, scales, k: int, group: int = GROUP) -> mx.array:
777
  """x [B, K] or [K], codes uint8 [N, K/4], scales [N, K/group] -> [B, N].
778
 
779
+ ``group`` is 64 (default) or 128 weights per scale.
780
+
781
  Batches up to ``COMPILE_MAX_BATCH`` reuse a compiled graph from a bounded
782
  LRU keyed by shape and dtype; weights are arguments, not captured, so the
783
  cache never keeps them alive. Larger batches dispatch the kernel directly.
 
788
  if x.ndim == 0 or x.ndim > 2:
789
  raise ValueError(f"x must have shape [K] or [B, K], got ndim {x.ndim}")
790
  k = int(k)
791
+ group = int(group)
792
+ if group not in GROUPS:
793
+ raise ValueError(f"group {group} not in {GROUPS}")
794
+ if k <= 0 or k % group:
795
+ raise ValueError(f"K {k} is not a positive multiple of {group}")
796
  if int(x.shape[-1]) != k:
797
  raise ValueError(f"x last dim {x.shape[-1]} != K {k}")
798
  if codes.ndim != 2 or int(codes.shape[1]) != k // 4:
src/mlx_ternary/linear.py CHANGED
@@ -14,18 +14,22 @@ import numpy as np
14
 
15
  from .convert import from_mlx_2bit
16
  from .kernel import tern_matmul
17
- from .pack import GROUP, pack_trits
18
 
19
 
20
  class TernaryLinear(nn.Module):
21
  """Packed ternary affine layer.
22
 
23
  ``weight`` is uint8 ``[output_dims, input_dims / 4]``. ``scales`` is
24
- float32 ``[output_dims, input_dims / 64]``. Parameters are frozen.
 
25
  """
26
 
27
- def __init__(self, weight, scales, bias=None):
28
  super().__init__()
 
 
 
29
  if not isinstance(weight, mx.array):
30
  weight = mx.array(np.ascontiguousarray(weight))
31
  if weight.dtype != mx.uint8:
@@ -40,15 +44,16 @@ class TernaryLinear(nn.Module):
40
  raise ValueError("weight and scales must be matrices")
41
  n, row_bytes = (int(v) for v in weight.shape)
42
  k = row_bytes * 4
43
- if k % GROUP or scales.shape != (n, k // GROUP):
44
  raise ValueError(
45
  f"weight {tuple(weight.shape)} and scales {tuple(scales.shape)} "
46
- f"are not a group-{GROUP} ternary matrix"
47
  )
48
  self.weight = weight
49
  self.scales = scales
50
  self.input_dims = k
51
  self.output_dims = n
 
52
  if bias is not None:
53
  if not isinstance(bias, mx.array):
54
  bias = mx.array(bias)
@@ -60,7 +65,7 @@ class TernaryLinear(nn.Module):
60
  def _extra_repr(self) -> str:
61
  return (
62
  f"input_dims={self.input_dims}, output_dims={self.output_dims}, "
63
- f"bias={'bias' in self}, group_size={GROUP}, bits=2"
64
  )
65
 
66
  def __call__(self, x):
@@ -68,7 +73,7 @@ class TernaryLinear(nn.Module):
68
  raise ValueError(f"x last dim {x.shape[-1]} != input_dims {self.input_dims}")
69
  lead = x.shape[:-1]
70
  flat = x.reshape(-1, self.input_dims)
71
- y = tern_matmul(flat, self.weight, self.scales, self.input_dims)
72
  if y.dtype != x.dtype:
73
  y = y.astype(x.dtype)
74
  if "bias" in self:
@@ -79,31 +84,33 @@ class TernaryLinear(nn.Module):
79
  return y.reshape(*lead, self.output_dims)
80
 
81
  @classmethod
82
- def from_trits(cls, trits, scales, bias=None) -> "TernaryLinear":
83
  """Build from int8 trits ``{-1,0,1}`` of shape ``[output, input]``."""
84
  packed, _row = pack_trits(np.asarray(trits))
85
- return cls(packed, scales, bias)
86
 
87
  @classmethod
88
- def from_mlx_2bit(cls, weight, scales, biases, bias=None) -> "TernaryLinear":
89
  """Build from MLX affine 2-bit ternary tensors."""
90
- packed, scale_f = from_mlx_2bit(weight, scales, biases)
91
- return cls(packed, scale_f, bias)
92
 
93
  @classmethod
94
  def from_quantized_linear(cls, layer: nn.Module) -> "TernaryLinear":
95
  """Replace one affine 2-bit ``QuantizedLinear`` that stores ternary weights."""
96
  if not isinstance(layer, nn.QuantizedLinear):
97
  raise TypeError(f"expected QuantizedLinear, got {type(layer).__name__}")
98
- if layer.bits != 2 or layer.group_size != GROUP or layer.mode != "affine":
99
  raise ValueError(
100
- f"expected affine 2-bit group {GROUP}, got bits={layer.bits} "
101
  f"group_size={layer.group_size} mode={layer.mode}"
102
  )
103
  if layer.biases is None:
104
  raise ValueError("affine 2-bit ternary storage needs biases equal to -scales")
105
  extra = layer.bias if "bias" in layer else None
106
- return cls.from_mlx_2bit(layer.weight, layer.scales, layer.biases, bias=extra)
 
 
107
 
108
 
109
  def _replace_linear(value, path: str):
 
14
 
15
  from .convert import from_mlx_2bit
16
  from .kernel import tern_matmul
17
+ from .pack import GROUP, GROUPS, pack_trits
18
 
19
 
20
  class TernaryLinear(nn.Module):
21
  """Packed ternary affine layer.
22
 
23
  ``weight`` is uint8 ``[output_dims, input_dims / 4]``. ``scales`` is
24
+ float32 ``[output_dims, input_dims / group_size]``. ``group_size`` is 64
25
+ (default) or 128. Parameters are frozen.
26
  """
27
 
28
+ def __init__(self, weight, scales, bias=None, group_size: int = GROUP):
29
  super().__init__()
30
+ group_size = int(group_size)
31
+ if group_size not in GROUPS:
32
+ raise ValueError(f"group_size {group_size} not in {GROUPS}")
33
  if not isinstance(weight, mx.array):
34
  weight = mx.array(np.ascontiguousarray(weight))
35
  if weight.dtype != mx.uint8:
 
44
  raise ValueError("weight and scales must be matrices")
45
  n, row_bytes = (int(v) for v in weight.shape)
46
  k = row_bytes * 4
47
+ if k % group_size or scales.shape != (n, k // group_size):
48
  raise ValueError(
49
  f"weight {tuple(weight.shape)} and scales {tuple(scales.shape)} "
50
+ f"are not a group-{group_size} ternary matrix"
51
  )
52
  self.weight = weight
53
  self.scales = scales
54
  self.input_dims = k
55
  self.output_dims = n
56
+ self.group_size = group_size
57
  if bias is not None:
58
  if not isinstance(bias, mx.array):
59
  bias = mx.array(bias)
 
65
  def _extra_repr(self) -> str:
66
  return (
67
  f"input_dims={self.input_dims}, output_dims={self.output_dims}, "
68
+ f"bias={'bias' in self}, group_size={self.group_size}, bits=2"
69
  )
70
 
71
  def __call__(self, x):
 
73
  raise ValueError(f"x last dim {x.shape[-1]} != input_dims {self.input_dims}")
74
  lead = x.shape[:-1]
75
  flat = x.reshape(-1, self.input_dims)
76
+ y = tern_matmul(flat, self.weight, self.scales, self.input_dims, self.group_size)
77
  if y.dtype != x.dtype:
78
  y = y.astype(x.dtype)
79
  if "bias" in self:
 
84
  return y.reshape(*lead, self.output_dims)
85
 
86
  @classmethod
87
+ def from_trits(cls, trits, scales, bias=None, group_size: int = GROUP) -> "TernaryLinear":
88
  """Build from int8 trits ``{-1,0,1}`` of shape ``[output, input]``."""
89
  packed, _row = pack_trits(np.asarray(trits))
90
+ return cls(packed, scales, bias, group_size)
91
 
92
  @classmethod
93
+ def from_mlx_2bit(cls, weight, scales, biases, bias=None, group_size: int = GROUP) -> "TernaryLinear":
94
  """Build from MLX affine 2-bit ternary tensors."""
95
+ packed, scale_f = from_mlx_2bit(weight, scales, biases, group_size)
96
+ return cls(packed, scale_f, bias, group_size)
97
 
98
  @classmethod
99
  def from_quantized_linear(cls, layer: nn.Module) -> "TernaryLinear":
100
  """Replace one affine 2-bit ``QuantizedLinear`` that stores ternary weights."""
101
  if not isinstance(layer, nn.QuantizedLinear):
102
  raise TypeError(f"expected QuantizedLinear, got {type(layer).__name__}")
103
+ if layer.bits != 2 or layer.group_size not in GROUPS or layer.mode != "affine":
104
  raise ValueError(
105
+ f"expected affine 2-bit group {GROUPS}, got bits={layer.bits} "
106
  f"group_size={layer.group_size} mode={layer.mode}"
107
  )
108
  if layer.biases is None:
109
  raise ValueError("affine 2-bit ternary storage needs biases equal to -scales")
110
  extra = layer.bias if "bias" in layer else None
111
+ return cls.from_mlx_2bit(
112
+ layer.weight, layer.scales, layer.biases, bias=extra, group_size=layer.group_size
113
+ )
114
 
115
 
116
  def _replace_linear(value, path: str):
src/mlx_ternary/pack.py CHANGED
@@ -3,7 +3,7 @@
3
  """2-bit ternary pack format.
4
 
5
  Four codes share a byte, low bits first. The stored code is ``trit + 1``
6
- in {0, 1, 2}. One scale covers 64 weights and there is no zero point:
7
 
8
  weight = (code - 1) * scale
9
  """
@@ -14,6 +14,8 @@ import math
14
  import numpy as np
15
 
16
  GROUP = 64
 
 
17
 
18
 
19
  def info_bits_per_weight(group_size: int = GROUP) -> float:
 
3
  """2-bit ternary pack format.
4
 
5
  Four codes share a byte, low bits first. The stored code is ``trit + 1``
6
+ in {0, 1, 2}. One scale covers 64 weights (128 as an option) and there is no zero point:
7
 
8
  weight = (code - 1) * scale
9
  """
 
14
  import numpy as np
15
 
16
  GROUP = 64
17
+ # Supported group sizes. 128 halves the scale overhead (2.125 bits stored).
18
+ GROUPS = (64, 128)
19
 
20
 
21
  def info_bits_per_weight(group_size: int = GROUP) -> float:
tests/test_group128.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Jakevin
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ import mlx.core as mx
4
+ import mlx.nn as nn
5
+ import numpy as np
6
+ import pytest
7
+
8
+ from mlx_ternary import TernaryLinear, dequantize, from_mlx_2bit, pack_trits, tern_matmul
9
+
10
+
11
+ def _case(n, k, group, seed):
12
+ rng = np.random.default_rng(seed)
13
+ trits = rng.integers(-1, 2, size=(n, k), dtype=np.int8)
14
+ # Half-exact scales so the half-staged GEMM is compared without rounding noise.
15
+ scales = (rng.integers(1, 64, size=(n, k // group)) / 512.0).astype(np.float32)
16
+ packed, _ = pack_trits(trits)
17
+ return trits, scales, packed
18
+
19
+
20
+ def _check(y, ref, tol=1e-3):
21
+ y = np.array(y)
22
+ err = np.max(np.abs(y - ref)) / max(np.max(np.abs(ref)), 1e-12)
23
+ assert err < tol, err
24
+
25
+
26
+ @pytest.mark.parametrize("group", [64, 128])
27
+ @pytest.mark.parametrize(
28
+ "n,k,b",
29
+ [(64, 640, 1), (96, 2048, 3), (128, 512, 32), (64, 1024, 64), (64, 640, 100), (40, 512, 100), (32, 384, 37)],
30
+ )
31
+ def test_matmul_groups(group, n, k, b):
32
+ if k % group:
33
+ pytest.skip("K not a multiple of group")
34
+ trits, scales, packed = _case(n, k, group, n + k + b + group)
35
+ x = np.random.default_rng(b).standard_normal((b, k)).astype(np.float32)
36
+ ref = x @ dequantize(trits, scales, group).T
37
+ y = tern_matmul(mx.array(x), mx.array(packed), mx.array(scales), k, group)
38
+ _check(y, ref)
39
+
40
+
41
+ def test_group128_differs_from_64_layout():
42
+ # Same codes, scales that differ between the two halves of a 128 group.
43
+ n, k = 32, 512
44
+ trits, s128, packed = _case(n, k, 128, 7)
45
+ x = np.random.default_rng(0).standard_normal((1, k)).astype(np.float32)
46
+ ref = x @ dequantize(trits, s128, 128).T
47
+ _check(tern_matmul(mx.array(x), mx.array(packed), mx.array(s128), k, group=128), ref)
48
+ with pytest.raises(ValueError):
49
+ tern_matmul(mx.array(x), mx.array(packed), mx.array(s128), k) # g64 shape mismatch
50
+
51
+
52
+ def test_bad_group():
53
+ with pytest.raises(ValueError):
54
+ tern_matmul(mx.zeros((1, 256)), mx.zeros((4, 64), dtype=mx.uint8), mx.zeros((4, 8)), 256, group=32)
55
+ TernaryLinear(np.zeros((4, 32), np.uint8), np.zeros((4, 1), np.float32), group_size=128)
56
+ with pytest.raises(ValueError):
57
+ TernaryLinear(np.zeros((4, 16), np.uint8), np.zeros((4, 1), np.float32), group_size=128)
58
+
59
+
60
+ def test_linear_and_convert_group128():
61
+ n, k = 64, 1024
62
+ trits, scales, _ = _case(n, k, 128, 3)
63
+ w = mx.array(dequantize(trits, scales, 128))
64
+ stored = (trits.astype(np.uint32) + 1).reshape(n, k // 16, 16)
65
+ q = mx.array(np.sum(stored << (2 * np.arange(16, dtype=np.uint32)), axis=-1).astype(np.uint32))
66
+ qs, qb = mx.array(scales), mx.array(-scales)
67
+ layer = nn.QuantizedLinear(k, n, bias=False, group_size=128, bits=2, mode="affine")
68
+ layer.weight, layer.scales, layer.biases = q, qs, qb
69
+ tl = TernaryLinear.from_quantized_linear(layer)
70
+ assert tl.group_size == 128
71
+ x = mx.array(np.random.default_rng(1).standard_normal((5, k)).astype(np.float32))
72
+ _check(tl(x), np.array(layer(x)))
73
+ packed, sf = from_mlx_2bit(q, qs, qb, group_size=128)
74
+ assert sf.shape == (n, k // 128)
75
+ tl2 = TernaryLinear.from_trits(trits, scales, group_size=128)
76
+ _check(tl2(x), np.array(x) @ np.array(w).T)
77
+
78
+
79
+ @pytest.mark.parametrize("b", [1, 4, 64])
80
+ def test_new_weights_after_delete(b):
81
+ # A same-shape weight created after the old one is freed must be used,
82
+ # including through the compiled small-batch path.
83
+ n, k = 64, 512
84
+ x = np.random.default_rng(5).standard_normal((b, k)).astype(np.float32)
85
+ t1, s1, p1 = _case(n, k, 64, 11)
86
+ layer = TernaryLinear(p1, s1)
87
+ _check(layer(mx.array(x)), x @ dequantize(t1, s1).T)
88
+ del layer, p1, s1
89
+ mx.clear_cache()
90
+ t2, s2, p2 = _case(n, k, 64, 12)
91
+ assert not np.array_equal(t1, t2)
92
+ layer = TernaryLinear(p2, s2)
93
+ ref2 = x @ dequantize(t2, s2).T
94
+ _check(layer(mx.array(x)), ref2)
95
+ _check(tern_matmul(mx.array(x), mx.array(p2), mx.array(s2), k), ref2)