binade 0.1.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.
- binade/__init__.py +3 -0
- binade/baselines.py +58 -0
- binade/bf16.py +61 -0
- binade/classify.py +75 -0
- binade/cli.py +15 -0
- binade/format.py +132 -0
- binade/info.py +39 -0
- binade/lossy.py +68 -0
- binade/mlx/__init__.py +0 -0
- binade/mlx/cublas_plan.py +192 -0
- binade/mlx/cuda_kernels.py +995 -0
- binade/mlx/kernel.py +886 -0
- binade/mlx/loader.py +247 -0
- binade/mlx/moe.py +115 -0
- binade/mlx/r4.py +379 -0
- binade/mlx/rice_kernel.py +98 -0
- binade/mlx/slow_linear.py +172 -0
- binade/pack.py +173 -0
- binade/policies.py +157 -0
- binade/rice.py +182 -0
- binade/scan.py +229 -0
- binade/st.py +226 -0
- binade/tile.py +49 -0
- binade/unpack.py +135 -0
- binade-0.1.0.dist-info/METADATA +162 -0
- binade-0.1.0.dist-info/RECORD +30 -0
- binade-0.1.0.dist-info/WHEEL +5 -0
- binade-0.1.0.dist-info/entry_points.txt +2 -0
- binade-0.1.0.dist-info/licenses/LICENSE +202 -0
- binade-0.1.0.dist-info/top_level.txt +1 -0
binade/__init__.py
ADDED
binade/baselines.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Reference exponent codes to compare against (DESIGN.md 4). All return bits per exponent."""
|
|
2
|
+
|
|
3
|
+
import heapq
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def entropy(hist: np.ndarray) -> float:
|
|
9
|
+
"""Shannon entropy (bits) of a histogram."""
|
|
10
|
+
p = hist[hist > 0] / hist.sum()
|
|
11
|
+
return float(-(p * np.log2(p)).sum())
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def huffman_lengths(hist: np.ndarray) -> np.ndarray:
|
|
15
|
+
"""Huffman code length per symbol (0 for absent symbols; 1 if only one symbol)."""
|
|
16
|
+
lengths = np.zeros(len(hist), np.int64)
|
|
17
|
+
syms = [int(s) for s in np.flatnonzero(hist)]
|
|
18
|
+
if len(syms) == 1:
|
|
19
|
+
lengths[syms[0]] = 1
|
|
20
|
+
return lengths
|
|
21
|
+
heap = [(int(hist[s]), s, [s]) for s in syms]
|
|
22
|
+
heapq.heapify(heap)
|
|
23
|
+
while len(heap) > 1:
|
|
24
|
+
c1, t1, s1 = heapq.heappop(heap)
|
|
25
|
+
c2, t2, s2 = heapq.heappop(heap)
|
|
26
|
+
for s in s1 + s2:
|
|
27
|
+
lengths[s] += 1
|
|
28
|
+
heapq.heappush(heap, (c1 + c2, min(t1, t2), s1 + s2))
|
|
29
|
+
return lengths
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def huffman_bits(hist: np.ndarray, lengths: np.ndarray | None = None) -> int:
|
|
33
|
+
"""Total bits to code `hist` with a static Huffman code (its own unless `lengths` given)."""
|
|
34
|
+
if lengths is None:
|
|
35
|
+
lengths = huffman_lengths(hist)
|
|
36
|
+
return int((hist.astype(np.int64) * lengths).sum())
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def tensor_palette_bits(hist: np.ndarray) -> int:
|
|
40
|
+
"""One palette per tensor, b = ceil(log2(distinct)); palette entries at 8 bits each."""
|
|
41
|
+
d = int((hist > 0).sum())
|
|
42
|
+
b = int(np.ceil(np.log2(d))) if d > 1 else 0
|
|
43
|
+
return int(hist.sum()) * b + 8 * d
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def palette16_segment_bits(in_weights: int, numel: int, segments: int) -> int:
|
|
47
|
+
"""Unweight-class: per-tensor palette of the 16 most frequent exponents, 4-bit index.
|
|
48
|
+
A 64-weight row segment holding any other exponent keeps its 8-bit exponents.
|
|
49
|
+
Charges the 16-byte palette and one flag bit per segment."""
|
|
50
|
+
return 4 * in_weights + 8 * (numel - in_weights) + segments + 16 * 8
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def window7_bits(hist: np.ndarray) -> int:
|
|
54
|
+
"""ZipServ-class: 7 contiguous exponents per tensor at a fixed 3-bit code (code 000 is
|
|
55
|
+
the outlier escape); an outlier is also stored as a full 16-bit BF16 value."""
|
|
56
|
+
covered = max(int(hist[b : b + 7].sum()) for b in range(0, 250))
|
|
57
|
+
n = int(hist.sum())
|
|
58
|
+
return 3 * n + 16 * (n - covered)
|
binade/bf16.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""BF16 bit helpers (DESIGN.md 1). Every function accepts numpy or mlx arrays.
|
|
2
|
+
|
|
3
|
+
BF16 layout: bit 15 sign, bits 14..7 exponent, bits 6..0 mantissa.
|
|
4
|
+
`raw` packs sign into bit 7 and mantissa into bits 6..0; it is stored verbatim.
|
|
5
|
+
Only the exponent byte is compressed.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _ns(a):
|
|
12
|
+
"""(module, uint8, uint16) matching the array type of `a`."""
|
|
13
|
+
if isinstance(a, np.ndarray):
|
|
14
|
+
return np, np.uint8, np.uint16
|
|
15
|
+
import mlx.core as mx
|
|
16
|
+
|
|
17
|
+
return mx, mx.uint8, mx.uint16
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def exponent(w):
|
|
21
|
+
"""uint16 BF16 bit patterns -> uint8 exponent field."""
|
|
22
|
+
_, u8, _ = _ns(w)
|
|
23
|
+
return ((w >> 7) & 0xFF).astype(u8)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def raw(w):
|
|
27
|
+
"""uint16 BF16 bit patterns -> uint8 sign (bit 7) | mantissa (bits 6..0)."""
|
|
28
|
+
_, u8, _ = _ns(w)
|
|
29
|
+
return (((w >> 8) & 0x80) | (w & 0x7F)).astype(u8)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def split(w):
|
|
33
|
+
return raw(w), exponent(w)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def join(r, e):
|
|
37
|
+
"""Inverse of split: (raw, exp) uint8 -> uint16 BF16 bit patterns."""
|
|
38
|
+
_, _, u16 = _ns(r)
|
|
39
|
+
r = r.astype(u16)
|
|
40
|
+
e = e.astype(u16)
|
|
41
|
+
return ((r & 0x80) << 8) | (e << 7) | (r & 0x7F)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def round_mantissa(w, m):
|
|
45
|
+
"""Keep the top m of 7 mantissa bits, round half to even, exponent field unchanged.
|
|
46
|
+
|
|
47
|
+
A round-up that would carry into the exponent saturates at the largest m-bit
|
|
48
|
+
mantissa instead, so the exponent stream stays lossless (DESIGN.md 11).
|
|
49
|
+
Inf and NaN (exponent 255) pass through untouched.
|
|
50
|
+
"""
|
|
51
|
+
if not 1 <= m <= 7:
|
|
52
|
+
raise ValueError(f"m must be in 1..7, got {m}")
|
|
53
|
+
if m == 7:
|
|
54
|
+
return w
|
|
55
|
+
ns, _, _ = _ns(w)
|
|
56
|
+
s = 7 - m
|
|
57
|
+
mant = w & 0x7F
|
|
58
|
+
q = (mant + ((1 << (s - 1)) - 1) + ((mant >> s) & 1)) >> s
|
|
59
|
+
q = ns.minimum(q, (1 << m) - 1)
|
|
60
|
+
out = (w & 0xFF80) | (q << s)
|
|
61
|
+
return ns.where(((w >> 7) & 0xFF) == 0xFF, w, out)
|
binade/classify.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Tensor classification by name and shape (DESIGN.md 5).
|
|
2
|
+
|
|
3
|
+
Classes:
|
|
4
|
+
linear decoder projections that enter a matmul: attn, linattn (linear-attention
|
|
5
|
+
blocks such as Qwen3.5 Gated DeltaNet), mlp, experts, ple_proj
|
|
6
|
+
embed token embedding and lm_head (Gemma ties lm_head to embed_tokens, so the
|
|
7
|
+
embedding also enters a matmul once per decoded token)
|
|
8
|
+
ple Gemma per-layer embedding tables (gather only)
|
|
9
|
+
mm vision/audio encoders and their projections (not on the text decode path)
|
|
10
|
+
other norms, routers, scalars, anything unrecognized
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import re
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
|
|
16
|
+
MM_MARKERS = (
|
|
17
|
+
"vision_tower",
|
|
18
|
+
"audio_tower",
|
|
19
|
+
"vision_embedder",
|
|
20
|
+
"embed_vision",
|
|
21
|
+
"embed_audio",
|
|
22
|
+
"vision_model",
|
|
23
|
+
"multi_modal_projector",
|
|
24
|
+
"mm_projector",
|
|
25
|
+
".visual.",
|
|
26
|
+
)
|
|
27
|
+
ATTN = {"q_proj", "k_proj", "v_proj", "o_proj", "qkv_proj", "out_proj"}
|
|
28
|
+
LINATTN = {"linear_attn"}
|
|
29
|
+
MLP = {"gate_proj", "up_proj", "down_proj", "gate_up_proj", "w1", "w2", "w3"}
|
|
30
|
+
PLE_PROJ = {"per_layer_input_gate", "per_layer_projection", "per_layer_model_projection"}
|
|
31
|
+
MIN_DIM = 256
|
|
32
|
+
_BLOCK = re.compile(r"^(.*?\blayers\.(\d+))\.")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class Klass:
|
|
37
|
+
cls: str
|
|
38
|
+
sub: str
|
|
39
|
+
layer: int | None # decoder layer index; None outside the main stack (e.g. mtp heads)
|
|
40
|
+
block: str | None = None # module prefix through the layer index, e.g. "mtp.layers.0"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def classify(name: str, shape: tuple[int, ...], dtype: str) -> Klass:
|
|
44
|
+
m = _BLOCK.search(name)
|
|
45
|
+
block = m.group(1) if m else None
|
|
46
|
+
layer = int(m.group(2)) if m and not name.startswith("mtp.") else None
|
|
47
|
+
parts = name.split(".")
|
|
48
|
+
if any(s in f".{name}." for s in MM_MARKERS):
|
|
49
|
+
return Klass("mm", "mm", layer, block)
|
|
50
|
+
if "embed_tokens_per_layer" in parts:
|
|
51
|
+
return Klass("ple", "ple", None)
|
|
52
|
+
if name.endswith("embed_tokens.weight"):
|
|
53
|
+
return Klass("embed", "embed_tokens", None)
|
|
54
|
+
if name.endswith("lm_head.weight"):
|
|
55
|
+
return Klass("embed", "lm_head", None)
|
|
56
|
+
matrix = dtype == "BF16" and len(shape) in (2, 3) and min(shape[-2:]) >= MIN_DIM
|
|
57
|
+
# a weight is either `<module>.weight` or a fused expert stack without the suffix
|
|
58
|
+
is_weight = parts[-1] == "weight" or (len(shape) == 3 and "experts" in parts)
|
|
59
|
+
if matrix and is_weight:
|
|
60
|
+
comps = set(parts)
|
|
61
|
+
sub = None
|
|
62
|
+
if "experts" in comps:
|
|
63
|
+
sub = "experts"
|
|
64
|
+
elif comps & LINATTN:
|
|
65
|
+
sub = "linattn"
|
|
66
|
+
elif comps & ATTN:
|
|
67
|
+
sub = "attn"
|
|
68
|
+
elif comps & MLP:
|
|
69
|
+
sub = "mlp"
|
|
70
|
+
elif comps & PLE_PROJ:
|
|
71
|
+
sub = "ple_proj"
|
|
72
|
+
if sub:
|
|
73
|
+
return Klass("linear", sub, layer, block)
|
|
74
|
+
sub = "norm" if any("norm" in p for p in parts) else "other"
|
|
75
|
+
return Klass("other", sub, layer, block)
|
binade/cli.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Command line: `binade pack ...` and `binade unpack ...`."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def main():
|
|
7
|
+
if len(sys.argv) < 2 or sys.argv[1] not in ("pack", "unpack"):
|
|
8
|
+
sys.exit("usage: binade {pack,unpack} ... (binade pack --help for options)")
|
|
9
|
+
cmd = sys.argv.pop(1)
|
|
10
|
+
sys.argv[0] = f"binade {cmd}"
|
|
11
|
+
if cmd == "pack":
|
|
12
|
+
from .pack import main as run
|
|
13
|
+
else:
|
|
14
|
+
from .unpack import main as run
|
|
15
|
+
run()
|
binade/format.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Binade format v1: exponent coding (DESIGN.md 6). numpy reference encoder and decoder.
|
|
2
|
+
|
|
3
|
+
One table per tensor lists its exponents by descending frequency (rank 0 = most common).
|
|
4
|
+
Tiles are T = 128 weights along K in one row. Per tile, a width b in 0..8 and a mode:
|
|
5
|
+
fixed every weight stores its rank in b bits, b = bit length of the tile's largest rank
|
|
6
|
+
escape b in 1..4; ranks below 2^b - 1 are stored directly, code 2^b - 1 marks an
|
|
7
|
+
escape whose exponent byte is appended to the tensor's escape stream
|
|
8
|
+
meta = b | escape << 4. Codes are packed LSB first into little-endian 32-bit words;
|
|
9
|
+
a tile of width b is exactly 4*b words. Padding weights (K up to a multiple of T) code
|
|
10
|
+
rank 0 and are dropped on decode.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
TILE = 128
|
|
18
|
+
ESCAPE = 0x10
|
|
19
|
+
_BITLEN = np.array([v.bit_length() for v in range(256)], np.uint8)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class Encoded:
|
|
24
|
+
table: np.ndarray # uint8 [256]
|
|
25
|
+
meta: np.ndarray # uint8 [ntiles]
|
|
26
|
+
idx: np.ndarray # uint32 [4 * sum(b)]
|
|
27
|
+
esc: np.ndarray # uint8 [n_escapes]
|
|
28
|
+
|
|
29
|
+
def bits(self) -> int:
|
|
30
|
+
"""Exponent-side payload in bits (excludes the raw sign+mantissa bytes)."""
|
|
31
|
+
return 8 * self.table.size + 8 * self.meta.size + 32 * self.idx.size + 8 * self.esc.size
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def rank_table(hist: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
|
35
|
+
"""(table [256] exponent by rank, rank [256] rank of each exponent) from a histogram.
|
|
36
|
+
|
|
37
|
+
Ties break toward the smaller exponent (stable sort), matching binade.scan."""
|
|
38
|
+
order = np.argsort(-hist, kind="stable").astype(np.uint8)
|
|
39
|
+
table = np.where(hist[order] > 0, order, 0).astype(np.uint8)
|
|
40
|
+
rank = np.empty(256, np.uint8)
|
|
41
|
+
rank[order] = np.arange(256, dtype=np.uint8)
|
|
42
|
+
return table, rank
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def choose(r: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
|
46
|
+
"""Per-tile (b, escape) minimizing index + escape bits (policy rank_best).
|
|
47
|
+
|
|
48
|
+
r: [nt, T] uint8 ranks. Ties go to fixed, then to the smaller escape width,
|
|
49
|
+
the same order binade.policies uses. This is the decision a search would replace."""
|
|
50
|
+
T = r.shape[1]
|
|
51
|
+
fixed_b = _BITLEN[r.max(axis=1)]
|
|
52
|
+
costs = [T * fixed_b.astype(np.int64)]
|
|
53
|
+
for b in (1, 2, 3, 4):
|
|
54
|
+
costs.append(T * b + 8 * (r >= (1 << b) - 1).sum(axis=1, dtype=np.int64))
|
|
55
|
+
pick = np.argmin(np.stack(costs), axis=0)
|
|
56
|
+
b = np.where(pick == 0, fixed_b, pick).astype(np.uint8)
|
|
57
|
+
return b, pick > 0
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def pack_codes(codes: np.ndarray, b: int) -> np.ndarray:
|
|
61
|
+
"""[n, T] codes < 2^b -> [n, T*b/32] uint32, code i at bits i*b .. i*b+b-1, LSB first."""
|
|
62
|
+
n, T = codes.shape
|
|
63
|
+
bits = ((codes[:, :, None] >> np.arange(b, dtype=np.uint8)) & 1).astype(np.uint8)
|
|
64
|
+
packed = np.packbits(bits.reshape(n, T * b), axis=1, bitorder="little")
|
|
65
|
+
return np.ascontiguousarray(packed).view("<u4").reshape(n, T * b // 32)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def unpack_codes(words: np.ndarray, b: int, T: int = TILE) -> np.ndarray:
|
|
69
|
+
"""Inverse of pack_codes: [n, T*b/32] uint32 -> [n, T] uint8."""
|
|
70
|
+
n = words.shape[0]
|
|
71
|
+
bits = np.unpackbits(np.ascontiguousarray(words, dtype="<u4").view(np.uint8), axis=1, bitorder="little")
|
|
72
|
+
bits = bits.reshape(n, T, b).astype(np.uint16)
|
|
73
|
+
return (bits << np.arange(b, dtype=np.uint16)).sum(axis=2).astype(np.uint8)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _tiles(exps: np.ndarray, fill: int, T: int) -> np.ndarray:
|
|
77
|
+
"""[R, K] -> [R * ceil(K/T), T], padding each row with `fill`."""
|
|
78
|
+
R, K = exps.shape
|
|
79
|
+
pad = -K % T
|
|
80
|
+
if pad:
|
|
81
|
+
exps = np.concatenate([exps, np.full((R, pad), fill, exps.dtype)], axis=1)
|
|
82
|
+
return exps.reshape(-1, T)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def encode(exps: np.ndarray, table: np.ndarray, rank: np.ndarray, T: int = TILE) -> Encoded:
|
|
86
|
+
"""Encode [R, K] uint8 exponents (any row range of a tensor) with the tensor's rank table."""
|
|
87
|
+
e = _tiles(exps, int(table[0]), T)
|
|
88
|
+
r = rank[e]
|
|
89
|
+
b, esc_mode = choose(r)
|
|
90
|
+
code_max = (1 << b.astype(np.int64)) - 1 # escape code per tile (for escape mode)
|
|
91
|
+
escaped = esc_mode[:, None] & (r >= code_max[:, None])
|
|
92
|
+
codes = np.where(escaped, code_max[:, None], r).astype(np.uint8)
|
|
93
|
+
words = np.zeros(4 * int(b.astype(np.int64).sum()), np.uint32)
|
|
94
|
+
start = 4 * (np.cumsum(b, dtype=np.int64) - b)
|
|
95
|
+
for w in np.unique(b):
|
|
96
|
+
if w == 0:
|
|
97
|
+
continue
|
|
98
|
+
sel = np.flatnonzero(b == w)
|
|
99
|
+
words[(start[sel][:, None] + np.arange(4 * w)).ravel()] = pack_codes(codes[sel], int(w)).ravel()
|
|
100
|
+
meta = (b | np.where(esc_mode, ESCAPE, 0)).astype(np.uint8)
|
|
101
|
+
return Encoded(table=table, meta=meta, idx=words, esc=e[escaped])
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def decode_tiles(meta: np.ndarray, idx: np.ndarray, esc: np.ndarray, table: np.ndarray, T: int = TILE) -> tuple[np.ndarray, int]:
|
|
105
|
+
"""Decode consecutive tiles -> ([nt, T] uint8 exponents, escape bytes consumed).
|
|
106
|
+
|
|
107
|
+
`idx` must start at the first tile's words; `esc` at its first escape byte and may run
|
|
108
|
+
past the last tile, so a tensor can be decoded in row chunks with running cursors."""
|
|
109
|
+
b = (meta & 0x0F).astype(np.int64)
|
|
110
|
+
esc_mode = (meta & ESCAPE) != 0
|
|
111
|
+
codes = np.zeros((b.size, T), np.uint8)
|
|
112
|
+
start = 4 * (np.cumsum(b) - b)
|
|
113
|
+
for w in np.unique(b):
|
|
114
|
+
if w == 0:
|
|
115
|
+
continue
|
|
116
|
+
sel = np.flatnonzero(b == w)
|
|
117
|
+
codes[sel] = unpack_codes(idx[start[sel][:, None] + np.arange(4 * w)], int(w), T)
|
|
118
|
+
escaped = esc_mode[:, None] & (codes == ((1 << b) - 1)[:, None])
|
|
119
|
+
n = int(escaped.sum())
|
|
120
|
+
if n > esc.size:
|
|
121
|
+
raise ValueError(f"escape stream too short: need {n}, have {esc.size}")
|
|
122
|
+
e = table[codes]
|
|
123
|
+
e[escaped] = esc[:n]
|
|
124
|
+
return e, n
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def decode(enc: Encoded, R: int, K: int, T: int = TILE) -> np.ndarray:
|
|
128
|
+
"""Inverse of encode: -> [R, K] uint8 exponents."""
|
|
129
|
+
e, n = decode_tiles(enc.meta, enc.idx, enc.esc, enc.table, T)
|
|
130
|
+
if n != enc.esc.size or 32 * enc.idx.size != T * int((enc.meta & 0x0F).astype(np.int64).sum()):
|
|
131
|
+
raise ValueError("stream length does not match meta")
|
|
132
|
+
return e.reshape(R, -1)[:, :K]
|
binade/info.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Information the row and column index carry about the exponent (see scripts/mutual_info.py)."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from . import st
|
|
8
|
+
from .bf16 import exponent
|
|
9
|
+
|
|
10
|
+
CHUNK = 1 << 24
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def entropy_mm(counts: np.ndarray) -> np.ndarray:
|
|
14
|
+
"""Miller-Madow entropy (bits) of each row of a [G, 256] count matrix."""
|
|
15
|
+
counts = np.atleast_2d(counts).astype(np.float64)
|
|
16
|
+
n = counts.sum(axis=1)
|
|
17
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
18
|
+
p = counts / n[:, None]
|
|
19
|
+
h = -np.nansum(np.where(counts > 0, p * np.log2(p), 0.0), axis=1)
|
|
20
|
+
m = (counts > 0).sum(axis=1)
|
|
21
|
+
return h + (m - 1) / (2 * np.maximum(n, 1) * math.log(2))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def tensor_info(info: st.TensorInfo) -> dict:
|
|
25
|
+
R, K = info.rows, info.shape[-1]
|
|
26
|
+
step = max(1, CHUNK // K)
|
|
27
|
+
col = np.zeros((K, 256), np.int64)
|
|
28
|
+
h_row_sum = 0.0
|
|
29
|
+
for r0 in range(0, R, step):
|
|
30
|
+
r1 = min(R, r0 + step)
|
|
31
|
+
e = exponent(st.read(info, (r0, r1))).astype(np.int64)
|
|
32
|
+
col += np.bincount((np.arange(K)[None, :] * 256 + e).ravel(), minlength=K * 256).reshape(K, 256)
|
|
33
|
+
rows = np.bincount((np.arange(r1 - r0)[:, None] * 256 + e).ravel(), minlength=(r1 - r0) * 256).reshape(-1, 256)
|
|
34
|
+
h_row_sum += float((entropy_mm(rows) * K).sum())
|
|
35
|
+
n = R * K
|
|
36
|
+
h = float(entropy_mm(col.sum(axis=0))[0])
|
|
37
|
+
h_col = float((entropy_mm(col) * R).sum() / n)
|
|
38
|
+
h_row = h_row_sum / n
|
|
39
|
+
return {"numel": n, "rows": R, "cols": K, "H": h, "H_given_row": h_row, "H_given_col": h_col}
|
binade/lossy.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Lossy dial, report only (DESIGN.md 11).
|
|
2
|
+
|
|
3
|
+
For m kept mantissa bits (round half to even, exponent exact), per tile:
|
|
4
|
+
rel_fro ||W - Q||_F / ||W||_F
|
|
5
|
+
max_rel max_i |w_i - q_i| / |w_i| over nonzero finite w_i
|
|
6
|
+
Per-tile values are streamed into log-spaced histograms so whole-model percentiles
|
|
7
|
+
need no per-tile storage.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import mlx.core as mx
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
from .bf16 import round_mantissa
|
|
14
|
+
from .tile import tiles
|
|
15
|
+
|
|
16
|
+
MANTISSA_BITS = (2, 3, 4, 5, 6, 7)
|
|
17
|
+
BINS_PER_DECADE = 200
|
|
18
|
+
LOG10_MIN = -8 # bin 0 collects everything below 1e-8, including exact zeros
|
|
19
|
+
NBINS = -LOG10_MIN * BINS_PER_DECADE + 1
|
|
20
|
+
METRICS = ("rel_fro", "max_rel")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def elementwise(w16: mx.array, m: int) -> tuple[mx.array, mx.array]:
|
|
24
|
+
"""(|w - q|, |w|) as float32 for finite weights, zeros elsewhere. w16: uint16 BF16 bits."""
|
|
25
|
+
finite = ((w16 >> 7) & 0xFF) != 0xFF
|
|
26
|
+
w = w16.view(mx.bfloat16).astype(mx.float32)
|
|
27
|
+
q = round_mantissa(w16, m).view(mx.bfloat16).astype(mx.float32)
|
|
28
|
+
d = mx.where(finite, mx.abs(w - q), 0.0)
|
|
29
|
+
a = mx.where(finite, mx.abs(w), 0.0)
|
|
30
|
+
return d, a
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def tile_errors(d: mx.array, a: mx.array, T: int) -> tuple[mx.array, mx.array]:
|
|
34
|
+
"""Per-tile (rel_fro, max_rel) from [R, K] error and magnitude arrays. NaN for all-zero tiles."""
|
|
35
|
+
out_fro, out_max = [], []
|
|
36
|
+
for (dt, at) in zip(tiles(d, T), tiles(a, T)):
|
|
37
|
+
if dt is None:
|
|
38
|
+
continue
|
|
39
|
+
num = (dt * dt).sum(axis=1)
|
|
40
|
+
den = (at * at).sum(axis=1)
|
|
41
|
+
out_fro.append(mx.where(den > 0, mx.sqrt(num / den), mx.nan))
|
|
42
|
+
rel = mx.where(at > 0, dt / mx.where(at > 0, at, 1.0), 0.0)
|
|
43
|
+
out_max.append(mx.where(at.max(axis=1) > 0, rel.max(axis=1), mx.nan))
|
|
44
|
+
return mx.concatenate(out_fro), mx.concatenate(out_max)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def histogram(x: mx.array) -> np.ndarray:
|
|
48
|
+
"""Log-spaced histogram of non-NaN values (int64 [NBINS])."""
|
|
49
|
+
x = np.asarray(x)
|
|
50
|
+
x = x[~np.isnan(x)]
|
|
51
|
+
with np.errstate(divide="ignore"):
|
|
52
|
+
b = np.floor((np.log10(x) - LOG10_MIN) * BINS_PER_DECADE)
|
|
53
|
+
b = np.clip(np.nan_to_num(b, neginf=0), 0, NBINS - 1).astype(np.int64)
|
|
54
|
+
return np.bincount(b, minlength=NBINS)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def bin_upper(i: int) -> float:
|
|
58
|
+
"""Upper edge of bin i (a conservative value for a percentile landing in it)."""
|
|
59
|
+
return 0.0 if i == 0 else 10 ** (LOG10_MIN + (i + 1) / BINS_PER_DECADE)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def percentiles(h: np.ndarray, qs=(50, 90, 99, 99.9)) -> dict:
|
|
63
|
+
"""Percentiles from a histogram, reported as bin upper edges."""
|
|
64
|
+
total = int(h.sum())
|
|
65
|
+
if total == 0:
|
|
66
|
+
return {}
|
|
67
|
+
cdf = np.cumsum(h)
|
|
68
|
+
return {f"p{q:g}": bin_upper(int(np.searchsorted(cdf, q / 100 * total))) for q in qs}
|
binade/mlx/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""Which algorithm cuBLASLt runs for MLX's BF16 x @ W.T on CUDA, read through ctypes.
|
|
2
|
+
|
|
3
|
+
MLX 0.32.2's CUDA backend sends every multi-row BF16 matmul to cuBLASLt (matmul.cpp; gemv only
|
|
4
|
+
for one row). cuBLAS is closed, but on the GPUs we measured its BF16 GEMM sums each output as
|
|
5
|
+
tensor-core m16n8k16 steps along K, in order, from zero; with split-K into S partitions, each
|
|
6
|
+
partition is summed that way, rounded to BF16 (reduction scheme OUTPUT_TYPE), and the partials
|
|
7
|
+
are added in float32 in partition order; with reduction scheme COMPUTE_TYPE the partials stay
|
|
8
|
+
float32, and with INPLACE each partition adds its float32 sum to the BF16 output so far. One
|
|
9
|
+
algorithm (31, on the A100 and L4) sums each output in two accumulators over alternating
|
|
10
|
+
32-wide K slices instead (DESIGN.md section 9; the paper, paper/binade.pdf). A kernel that does
|
|
11
|
+
the same is bit-identical, so the runtime needs the algorithm, S and the reduction scheme, which
|
|
12
|
+
depend on the shape and the GPU.
|
|
13
|
+
|
|
14
|
+
`plan(M, N, K)` builds the same descriptors MLX does (gemms/cublas_gemm.cpp, cublas_utils.cpp:
|
|
15
|
+
A and B swapped for row-major output, TRANSA = T, TRANSB = N, compute and scale type float32,
|
|
16
|
+
host pointer mode, a 32 MiB workspace on compute capability 9 and up, else 4 MiB) and asks
|
|
17
|
+
cublasLtMatmulAlgoGetHeuristic for its first result, as MLX does; it returns the algorithm's
|
|
18
|
+
split-K count and reduction scheme (`config` returns every attribute, `slices` the K slicing of
|
|
19
|
+
a verified algorithm), or None if cuBLASLt cannot be loaded or queried.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
import ctypes
|
|
23
|
+
import glob
|
|
24
|
+
import os
|
|
25
|
+
import site
|
|
26
|
+
from functools import lru_cache
|
|
27
|
+
|
|
28
|
+
import mlx.core as mx
|
|
29
|
+
|
|
30
|
+
_COMPUTE_32F = 68
|
|
31
|
+
_R_32F, _R_16BF = 0, 14
|
|
32
|
+
_OP_N, _OP_T = 0, 1
|
|
33
|
+
_DESC_POINTER_MODE, _DESC_TRANSA, _DESC_TRANSB = 2, 3, 4
|
|
34
|
+
_PREF_MAX_WORKSPACE_BYTES = 1
|
|
35
|
+
_CFG_SPLITK_NUM, _CFG_REDUCTION_SCHEME = 2, 3
|
|
36
|
+
REDUCTION_NONE, REDUCTION_OUTPUT_TYPE = 0, 4
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class _Algo(ctypes.Structure):
|
|
40
|
+
_fields_ = [("data", ctypes.c_uint64 * 8)]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class _Heuristic(ctypes.Structure):
|
|
44
|
+
_fields_ = [("algo", _Algo), ("workspaceSize", ctypes.c_size_t), ("state", ctypes.c_int), ("wavesCount", ctypes.c_float), ("reserved", ctypes.c_int * 4)]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@lru_cache(maxsize=None)
|
|
48
|
+
def _lib():
|
|
49
|
+
"""cuBLASLt from the CUDA wheels MLX links against (site-packages/nvidia/cublas/lib)."""
|
|
50
|
+
roots = site.getsitepackages() + [site.getusersitepackages()]
|
|
51
|
+
paths = sorted(p for d in roots for p in glob.glob(os.path.join(d, "nvidia", "cublas", "lib", "libcublasLt.so*")))
|
|
52
|
+
if not paths:
|
|
53
|
+
return None
|
|
54
|
+
lib = ctypes.CDLL(paths[0])
|
|
55
|
+
h = ctypes.c_void_p()
|
|
56
|
+
if lib.cublasLtCreate(ctypes.byref(h)) != 0:
|
|
57
|
+
return None
|
|
58
|
+
ws = (32 if int(mx.device_info().get("compute_capability_major", 0)) >= 9 else 4) * 1024 * 1024
|
|
59
|
+
pref = ctypes.c_void_p()
|
|
60
|
+
v = ctypes.c_uint64(ws)
|
|
61
|
+
if lib.cublasLtMatmulPreferenceCreate(ctypes.byref(pref)) or lib.cublasLtMatmulPreferenceSetAttribute(pref, _PREF_MAX_WORKSPACE_BYTES, ctypes.byref(v), ctypes.sizeof(v)):
|
|
62
|
+
return None
|
|
63
|
+
return lib, h, pref
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _layout(lib, rows: int, cols: int, ld: int):
|
|
67
|
+
d = ctypes.c_void_p()
|
|
68
|
+
if lib.cublasLtMatrixLayoutCreate(ctypes.byref(d), _R_16BF, ctypes.c_uint64(rows), ctypes.c_uint64(cols), ctypes.c_int64(ld)):
|
|
69
|
+
raise RuntimeError("cublasLtMatrixLayoutCreate")
|
|
70
|
+
return d
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
CONFIG = ("algo", "tile", "split_k", "reduction", "swizzle", "custom", "stages", "inner_shape", "cluster_shape") # cublasLtMatmulAlgoConfigAttributes_t 0..8
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@lru_cache(maxsize=4096)
|
|
77
|
+
def config(M: int, N: int, K: int) -> dict | None:
|
|
78
|
+
"""Every attribute of the algorithm cuBLASLt picks for MLX's BF16 x [M, K] @ W.T (CONFIG:
|
|
79
|
+
algorithm and tile ids, split-K count, reduction scheme, ...); None if unavailable."""
|
|
80
|
+
return _heuristic(M, N, K, tuple(range(len(CONFIG))))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@lru_cache(maxsize=4096)
|
|
84
|
+
def plan(M: int, N: int, K: int):
|
|
85
|
+
"""(split_k, reduction_scheme) cuBLASLt picks for MLX's BF16 x [M, K] @ W.T, W [N, K]; None
|
|
86
|
+
if unavailable. Cached: the choice depends only on the shape, dtypes and GPU."""
|
|
87
|
+
c = _heuristic(M, N, K, (_CFG_SPLITK_NUM, _CFG_REDUCTION_SCHEME))
|
|
88
|
+
return None if c is None else (max(1, c["split_k"]), c["reduction"])
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _heuristic(M: int, N: int, K: int, attrs: tuple):
|
|
92
|
+
ctx = _lib()
|
|
93
|
+
if ctx is None:
|
|
94
|
+
return None
|
|
95
|
+
lib, h, pref = ctx
|
|
96
|
+
desc = ctypes.c_void_p()
|
|
97
|
+
if lib.cublasLtMatmulDescCreate(ctypes.byref(desc), _COMPUTE_32F, _R_32F):
|
|
98
|
+
return None
|
|
99
|
+
try:
|
|
100
|
+
for attr, val in ((_DESC_TRANSA, _OP_T), (_DESC_TRANSB, _OP_N), (_DESC_POINTER_MODE, 0)):
|
|
101
|
+
v = ctypes.c_int(val)
|
|
102
|
+
if lib.cublasLtMatmulDescSetAttribute(desc, attr, ctypes.byref(v), ctypes.sizeof(v)):
|
|
103
|
+
return None
|
|
104
|
+
layouts = [_layout(lib, K, N, K), _layout(lib, K, M, K), _layout(lib, N, M, N)]
|
|
105
|
+
res, n = _Heuristic(), ctypes.c_int(0)
|
|
106
|
+
st = lib.cublasLtMatmulAlgoGetHeuristic(h, desc, layouts[0], layouts[1], layouts[2], layouts[2], pref, 1, ctypes.byref(res), ctypes.byref(n))
|
|
107
|
+
for d in layouts:
|
|
108
|
+
lib.cublasLtMatrixLayoutDestroy(d)
|
|
109
|
+
if st or n.value < 1:
|
|
110
|
+
return None
|
|
111
|
+
out = {}
|
|
112
|
+
for attr in attrs:
|
|
113
|
+
# attributes are 16 or 32 bits wide and the buffer size must match: ask for it first
|
|
114
|
+
v, need = ctypes.c_uint64(0), ctypes.c_size_t(0)
|
|
115
|
+
if lib.cublasLtMatmulAlgoConfigGetAttribute(ctypes.byref(res.algo), attr, None, 0, ctypes.byref(need)) or need.value > 8:
|
|
116
|
+
return None
|
|
117
|
+
if lib.cublasLtMatmulAlgoConfigGetAttribute(ctypes.byref(res.algo), attr, ctypes.byref(v), need.value, ctypes.byref(need)):
|
|
118
|
+
return None
|
|
119
|
+
out[CONFIG[attr]] = int(v.value)
|
|
120
|
+
return out
|
|
121
|
+
finally:
|
|
122
|
+
lib.cublasLtMatmulDescDestroy(desc)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
SPLIT_ALIGN = 64 # partition size = round_up(ceil(K / S), SPLIT_ALIGN), measured on the RTX PRO 6000
|
|
126
|
+
REDUCTION_COMPUTE_TYPE = 2 # float32 partials (OUTPUT_TYPE: partials rounded to the output type, BF16)
|
|
127
|
+
REDUCTION_INPLACE = 1 # serial split-K in the output: each partition adds its float sum to the BF16 output so far
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def partitions(K: int, S: int) -> list[int]:
|
|
131
|
+
"""K boundaries of cuBLAS's S split-K partitions: sizes of ceil(K / S) rounded up to a
|
|
132
|
+
multiple of SPLIT_ALIGN; trailing partitions may be short or empty (an empty partition
|
|
133
|
+
still adds a zero partial, as cuBLAS's does)."""
|
|
134
|
+
if S == 1:
|
|
135
|
+
return [0, K]
|
|
136
|
+
size = -(-(-(-K // S)) // SPLIT_ALIGN) * SPLIT_ALIGN
|
|
137
|
+
return [min(i * size, K) for i in range(S + 1)]
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# Per compute capability, the cuBLASLt algorithms whose order the fused GEMM reproduces, as the
|
|
141
|
+
# number of 32-wide K slices summed apart and added at the end (1: in order; 2: sliced-K),
|
|
142
|
+
# verified by tests/test_cuda_gemm.py on that GPU: RTX PRO 6000, L4, A100.
|
|
143
|
+
ALGO_SLICES = {(12, 0): {21: 1}, (8, 9): {21: 1, 6: 1, 5: 1, 31: 2}, (8, 0): {21: 1, 6: 1, 31: 2}}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@lru_cache(maxsize=None)
|
|
147
|
+
def _algos() -> dict | None:
|
|
148
|
+
"""This GPU's entry of ALGO_SLICES; BINADE_CUDA_ALGOS="21:1,6:1" replaces it (to check a GPU)."""
|
|
149
|
+
env = os.environ.get("BINADE_CUDA_ALGOS")
|
|
150
|
+
if env:
|
|
151
|
+
return {int(k): int(v) for k, v in (kv.split(":") for kv in env.split(","))}
|
|
152
|
+
info = mx.device_info()
|
|
153
|
+
return ALGO_SLICES.get((int(info.get("compute_capability_major", 0)), int(info.get("compute_capability_minor", 0))))
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@lru_cache(maxsize=None)
|
|
157
|
+
def mirrored() -> bool:
|
|
158
|
+
"""Whether this GPU's cuBLAS kernels are ones the fused GEMM reproduces. The split-K rule and
|
|
159
|
+
the in-order m16n8k16 steps were measured on compute capability 12.0; other GPUs can pick
|
|
160
|
+
other kernels, so elsewhere the runtime rebuilds BF16 weights for cuBLAS itself (and on a
|
|
161
|
+
listed GPU for any algorithm not listed). BINADE_CUDA_ALGOS sets the algorithms, to check a
|
|
162
|
+
new GPU with tests/test_cuda_gemm.py."""
|
|
163
|
+
return _algos() is not None
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def slices(M: int, N: int, K: int) -> int | None:
|
|
167
|
+
"""K slices of cuBLAS's kernel for this product (1: in-order m16n8k16 steps; 2: two accumulators
|
|
168
|
+
over alternating 32-wide K slices, added at the end), None for an algorithm not measured.
|
|
169
|
+
Sliced-K is only known without split-K."""
|
|
170
|
+
c, algos = config(M, N, K), _algos()
|
|
171
|
+
if c is None or algos is None or c["algo"] not in algos:
|
|
172
|
+
return None
|
|
173
|
+
n = algos[c["algo"]]
|
|
174
|
+
return n if n == 1 or c["split_k"] <= 1 else None
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def supported(p) -> str | None:
|
|
178
|
+
"""How the fused kernel reproduces plan p: "none" (no split-K), "bf16" or "f32" partials,
|
|
179
|
+
"inplace" (float partials added in order to the BF16 output so far); None for anything else
|
|
180
|
+
(the runtime then rebuilds BF16 weights for cuBLAS)."""
|
|
181
|
+
if p is None:
|
|
182
|
+
return None
|
|
183
|
+
S, scheme = p
|
|
184
|
+
if S == 1 and scheme == REDUCTION_NONE:
|
|
185
|
+
return "none"
|
|
186
|
+
if S > 1 and scheme == REDUCTION_OUTPUT_TYPE:
|
|
187
|
+
return "bf16"
|
|
188
|
+
if S > 1 and scheme == REDUCTION_COMPUTE_TYPE:
|
|
189
|
+
return "f32"
|
|
190
|
+
if S > 1 and scheme == REDUCTION_INPLACE:
|
|
191
|
+
return "inplace"
|
|
192
|
+
return None
|