@mlx-bun/quantize 0.0.0-stage → 1.0.0
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.
- package/LICENSE +21 -0
- package/README.md +56 -2
- package/package.json +44 -4
- package/src/allocator.ts +628 -0
- package/src/atomic-output.ts +38 -0
- package/src/calibration.ts +182 -0
- package/src/config-writer.ts +109 -0
- package/src/convert.ts +79 -0
- package/src/drafter.ts +94 -0
- package/src/index.ts +86 -0
- package/src/quantizer.ts +691 -0
- package/src/qwen35-hf-fold.ts +103 -0
- package/src/rotate.ts +610 -0
- package/src/sensitivity.ts +216 -0
- package/src/trellis-allocation.ts +111 -0
- package/src/trellis-encoder.ts +328 -0
- package/src/trellis-quantizer.ts +405 -0
- package/src/trellis.ts +570 -0
- package/src/weight-transform.ts +299 -0
package/src/trellis.ts
ADDED
|
@@ -0,0 +1,570 @@
|
|
|
1
|
+
// Bitshift trellis codec (QTIP TCQ) — the ENGINE's copy, with the packed
|
|
2
|
+
// bit-stream the Q2b kernel reads. `02d723a:scripts/turboquant/tq-trellis.ts` is the
|
|
3
|
+
// frozen fake-quant codec that produced the Q3 artifact of record; this module
|
|
4
|
+
// is a copy of it plus `encodeStates` / `fakeQuantRowsPacked` / the host pack
|
|
5
|
+
// and unpack helpers, so nothing that reproduces the record changes.
|
|
6
|
+
//
|
|
7
|
+
// QTIP-style bitshift trellis-coded quantization (TCQ), fake-quant, on MLX.
|
|
8
|
+
//
|
|
9
|
+
// Reference (verified against source, not memory):
|
|
10
|
+
// Tseng et al., "QTIP: Quantization with Trellises and Incoherence Processing",
|
|
11
|
+
// arXiv:2406.11235v3 — Fig. 2 (bitshift trellis), §3.1.1 (computed codes),
|
|
12
|
+
// §3.2 + Algorithm 4 (tail-biting approximation), Table 2 (the (12,k,1)
|
|
13
|
+
// tail-biting distortion numbers this file's --validate reproduces).
|
|
14
|
+
// github.com/Cornell-RelaxML/qtip @ main, lib/codebook/bitshift.py.
|
|
15
|
+
//
|
|
16
|
+
// Bitshift trellis (L, k, V=1). State = L bits. Successor n of state p must
|
|
17
|
+
// satisfy `n >> k == p & (2^(L-k) - 1)` (Fig. 2: "the 2^kV nodes that share
|
|
18
|
+
// their top L-kV bits with its bottom L-kV bits"), i.e.
|
|
19
|
+
// n = ((p << k) | b) mod 2^L, b in [0, 2^k)
|
|
20
|
+
// so the predecessors of n are { (n >> k) + m·2^(L-k) : m in [0, 2^k) }.
|
|
21
|
+
// The emitted value for state s is a computed pseudo-Gaussian f(s) — no
|
|
22
|
+
// lookup table on the decode side (we materialize one anyway for the encoder).
|
|
23
|
+
//
|
|
24
|
+
// Encoder = Viterbi over 2^L states, UNWEIGHTED squared error (no Hessian /
|
|
25
|
+
// LDLQ — v2 lever), batched over thousands of 256-weight blocks at a time.
|
|
26
|
+
// Sign convention: we MAXIMIZE g = -(cost), and drop the per-step constant
|
|
27
|
+
// x², so the emission term is a single addmm: g_err = -lut² + 2·x·lut.
|
|
28
|
+
// Dropping x² shifts every path in a block by the same amount, so argmax
|
|
29
|
+
// decisions and the traceback are unchanged.
|
|
30
|
+
|
|
31
|
+
import { MlxArray as Arr, gpuStream, type MlxArray } from "@mlx-bun/mlx/array";
|
|
32
|
+
import { Dtype, clearCache, activeMemory, cacheMemory, peakMemory } from "@mlx-bun/mlx/ffi";
|
|
33
|
+
import * as ops from "@mlx-bun/mlx/ops";
|
|
34
|
+
import { lut1mad, wordsPerBlock } from "@mlx-bun/inference/kernels/trellis";
|
|
35
|
+
// The 1MAD codebook and packed-word geometry have one owner: the inference kernels.
|
|
36
|
+
export { lut1mad, wordsPerBlock };
|
|
37
|
+
|
|
38
|
+
const S = gpuStream;
|
|
39
|
+
|
|
40
|
+
// ------------------------------------------------------------- codebooks ---
|
|
41
|
+
|
|
42
|
+
/** QTIP `decode_1mad` (lib/codebook/bitshift.py) evaluated over [0, 2^L).
|
|
43
|
+
* x = (x·34038481 + 76625530) mod 2^32; y = Σ bytes(x) − 510; y / 147.800537109375.
|
|
44
|
+
* (510 = 2·255 = E[Σ of 4 uniform bytes]; 147.8005… ≈ √(4·(2^16−1)/12) is the
|
|
45
|
+
* std of that sum, so the code is unit-variance by construction.) */
|
|
46
|
+
|
|
47
|
+
/** QTIP `decode_3inst`: two bf16-shaped 16-bit lanes masked out of one
|
|
48
|
+
* multiply-add, xor'd with an exponent mask, read as fp16 and summed. */
|
|
49
|
+
export function lut3inst(L: number): Float32Array {
|
|
50
|
+
const n = 1 << L;
|
|
51
|
+
const out = new Float32Array(n);
|
|
52
|
+
const M = (1n << 32n) - 1n;
|
|
53
|
+
const a = 89226354n, b = 64248484n, fpmask = 996162400n;
|
|
54
|
+
const half = (1n << 15n) + ((1n << 12n) - 1n);
|
|
55
|
+
const mask = (half << 16n) + half;
|
|
56
|
+
const f16 = (bits: number): number => {
|
|
57
|
+
const sgn = bits & 0x8000 ? -1 : 1;
|
|
58
|
+
const exp = (bits >> 10) & 0x1f;
|
|
59
|
+
const man = bits & 0x3ff;
|
|
60
|
+
if (exp === 0) return sgn * man * 2 ** -24;
|
|
61
|
+
if (exp === 31) return sgn * (man ? NaN : Infinity);
|
|
62
|
+
return sgn * (1 + man / 1024) * 2 ** (exp - 15);
|
|
63
|
+
};
|
|
64
|
+
for (let i = 0; i < n; i++) {
|
|
65
|
+
let x = BigInt(i) & M;
|
|
66
|
+
x = (x * a + b) & M;
|
|
67
|
+
const res = (mask & x) ^ fpmask;
|
|
68
|
+
out[i] = f16(Number(res >> 16n) & 0xffff) + f16(Number(res & 0xffffn));
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Pure-lookup random Gaussian trellis code (paper's RPTC) — the L-bit LUT is
|
|
74
|
+
* 2^L iid N(0,1) draws. Used only as a codec-validation reference. */
|
|
75
|
+
export function lutRandom(L: number, seed = 0xc0ffee): Float32Array {
|
|
76
|
+
const n = 1 << L;
|
|
77
|
+
const out = new Float32Array(n);
|
|
78
|
+
let s = seed >>> 0;
|
|
79
|
+
const u = () => {
|
|
80
|
+
s = (s + 0x9e3779b9) >>> 0;
|
|
81
|
+
let z = s;
|
|
82
|
+
z = Math.imul(z ^ (z >>> 16), 0x21f0aaad) >>> 0;
|
|
83
|
+
z = Math.imul(z ^ (z >>> 15), 0x735a2d97) >>> 0;
|
|
84
|
+
return ((z ^ (z >>> 15)) >>> 0) / 4294967296 + 2 ** -33;
|
|
85
|
+
};
|
|
86
|
+
for (let i = 0; i < n; i += 2) {
|
|
87
|
+
const r = Math.sqrt(-2 * Math.log(u()));
|
|
88
|
+
const t = 2 * Math.PI * u();
|
|
89
|
+
out[i] = r * Math.cos(t);
|
|
90
|
+
if (i + 1 < n) out[i + 1] = r * Math.sin(t);
|
|
91
|
+
}
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// ----------------------------------------------------------------- codec ---
|
|
96
|
+
|
|
97
|
+
export type CodeName = "1mad" | "3inst" | "rand";
|
|
98
|
+
|
|
99
|
+
export interface TrellisCfg {
|
|
100
|
+
L: number; // state bits
|
|
101
|
+
K: number; // bits per weight (V = 1)
|
|
102
|
+
T: number; // block length (weights per tail-biting trellis)
|
|
103
|
+
code: CodeName;
|
|
104
|
+
tailBiting: boolean;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export class Trellis {
|
|
108
|
+
readonly cfg: TrellisCfg;
|
|
109
|
+
readonly nStates: number;
|
|
110
|
+
readonly G: number; // 2^K branches
|
|
111
|
+
readonly J: number; // 2^(L-K) predecessor groups
|
|
112
|
+
readonly lutRms: number;
|
|
113
|
+
/** [S] f32 code values, and the [1,S] row / -lut² row the encoder needs. */
|
|
114
|
+
private lutFlat: MlxArray;
|
|
115
|
+
private lutRow: MlxArray;
|
|
116
|
+
private negLut2: MlxArray;
|
|
117
|
+
private sHigh: MlxArray; // [1,S] int32, state >> K
|
|
118
|
+
private sLow: MlxArray; // [1,S] int32, state & (J-1)
|
|
119
|
+
private mrow: MlxArray; // [1,G,1] uint8, branch index 0..G-1
|
|
120
|
+
private sIdx: MlxArray; // [1,S] int32, arange(S)
|
|
121
|
+
private negOne: MlxArray; // int32 scalar -1
|
|
122
|
+
private kConst: MlxArray; // int32 scalar K
|
|
123
|
+
private jConst: MlxArray; // int32 scalar J
|
|
124
|
+
private negBig: MlxArray; // f32 scalar -1e30
|
|
125
|
+
|
|
126
|
+
constructor(cfg: TrellisCfg) {
|
|
127
|
+
this.cfg = cfg;
|
|
128
|
+
if (!Number.isInteger(cfg.K) || cfg.K < 1 || cfg.K >= cfg.L)
|
|
129
|
+
throw new Error(`Trellis: K=${cfg.K} must be an integer in [1, L=${cfg.L})`);
|
|
130
|
+
const n = (this.nStates = 1 << cfg.L);
|
|
131
|
+
this.G = 1 << cfg.K;
|
|
132
|
+
this.J = n >> cfg.K;
|
|
133
|
+
const host =
|
|
134
|
+
cfg.code === "1mad" ? lut1mad(cfg.L) : cfg.code === "3inst" ? lut3inst(cfg.L) : lutRandom(cfg.L);
|
|
135
|
+
let ss = 0;
|
|
136
|
+
for (const v of host) ss += v * v;
|
|
137
|
+
this.lutRms = Math.sqrt(ss / n);
|
|
138
|
+
|
|
139
|
+
this.lutFlat = Arr.fromFloat32(host, [n]);
|
|
140
|
+
this.lutRow = ops.reshape(this.lutFlat, [1, n], S);
|
|
141
|
+
const sq = ops.square(this.lutRow, S);
|
|
142
|
+
this.negLut2 = ops.neg(sq, S);
|
|
143
|
+
sq.dispose();
|
|
144
|
+
|
|
145
|
+
const idx = new Int32Array(n);
|
|
146
|
+
for (let i = 0; i < n; i++) idx[i] = i >> cfg.K;
|
|
147
|
+
this.sHigh = Arr.fromInt32(idx, [1, n]);
|
|
148
|
+
const idx2 = new Int32Array(n);
|
|
149
|
+
for (let i = 0; i < n; i++) idx2[i] = i & (this.J - 1);
|
|
150
|
+
this.sLow = Arr.fromInt32(idx2, [1, n]);
|
|
151
|
+
|
|
152
|
+
const idx3 = new Int32Array(n);
|
|
153
|
+
for (let i = 0; i < n; i++) idx3[i] = i;
|
|
154
|
+
this.sIdx = Arr.fromInt32(idx3, [1, n]);
|
|
155
|
+
this.negOne = Arr.fromInt32(new Int32Array([-1]), []);
|
|
156
|
+
|
|
157
|
+
const mh = new Int32Array(this.G);
|
|
158
|
+
for (let i = 0; i < this.G; i++) mh[i] = i;
|
|
159
|
+
const m32 = Arr.fromInt32(mh, [1, this.G, 1]);
|
|
160
|
+
this.mrow = m32.astype(Dtype.uint8, S);
|
|
161
|
+
m32.dispose();
|
|
162
|
+
|
|
163
|
+
this.kConst = Arr.fromInt32(new Int32Array([cfg.K]), []);
|
|
164
|
+
this.jConst = Arr.fromInt32(new Int32Array([this.J]), []);
|
|
165
|
+
this.negBig = Arr.fromFloat32(new Float32Array([-1e30]), []);
|
|
166
|
+
ops.evalAll([this.lutFlat, this.lutRow, this.negLut2, this.sHigh, this.sLow, this.mrow, this.sIdx]);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
dispose(): void {
|
|
170
|
+
for (const a of [this.lutFlat, this.lutRow, this.negLut2, this.sHigh, this.sLow,
|
|
171
|
+
this.mrow, this.sIdx, this.negOne, this.kConst, this.jConst, this.negBig]) a.dispose();
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** One Viterbi pass over [B,T] (time on axis 1, already scaled to the code's
|
|
175
|
+
* variance). `overlap` [B,1] int32 or null. Returns the decoded state at
|
|
176
|
+
* every t >= `from` ([B,1] int32 each; earlier slots are null). */
|
|
177
|
+
private viterbi(X2T: MlxArray, B: number, overlap: MlxArray | null, from: number): (MlxArray | null)[] {
|
|
178
|
+
const { T } = this.cfg;
|
|
179
|
+
const n = this.nStates, G = this.G, J = this.J;
|
|
180
|
+
const col = (t: number): MlxArray => {
|
|
181
|
+
const row = X2T.slice([t, 0], [t + 1, B], S); // [1,B]
|
|
182
|
+
const c = ops.reshape(row, [B, 1], S);
|
|
183
|
+
row.dispose();
|
|
184
|
+
return c;
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
// t = 0 (initial state free, or pinned to the tail-biting overlap).
|
|
188
|
+
let x = col(0);
|
|
189
|
+
let g = ops.addmm(this.negLut2, x, this.lutRow, S);
|
|
190
|
+
x.dispose();
|
|
191
|
+
if (overlap) {
|
|
192
|
+
const m = ops.equal(this.sHigh, overlap, S);
|
|
193
|
+
const masked = ops.where(m, g, this.negBig, S);
|
|
194
|
+
m.dispose(); g.dispose();
|
|
195
|
+
g = masked;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// NOTE: mlx's ArgReduce kernel is ~85x slower than Reduce on this shape
|
|
199
|
+
// (measured M1 Max: argmax over [4096,8,512] axis 1 = 42.9 ms vs max =
|
|
200
|
+
// 0.5 ms), so the branch index is recovered from the max with a
|
|
201
|
+
// compare + uint8 max instead of a real argmax.
|
|
202
|
+
const back: (MlxArray | null)[] = new Array(T).fill(null);
|
|
203
|
+
for (let t = 1; t < T; t++) {
|
|
204
|
+
const g3 = ops.reshape(g, [B, G, J], S);
|
|
205
|
+
const mx = ops.maxAxis(g3, 1, true, S); // [B,1,J]
|
|
206
|
+
const eq = ops.equal(g3, mx, S); // bool [B,G,J]
|
|
207
|
+
const e8 = eq.astype(Dtype.uint8, S);
|
|
208
|
+
const sel = ops.mul(e8, this.mrow, S);
|
|
209
|
+
back[t] = ops.maxAxis(sel, 1, false, S); // [B,J] uint8
|
|
210
|
+
const best = ops.reshape(mx, [B, J, 1], S);
|
|
211
|
+
x = col(t);
|
|
212
|
+
const err = ops.addmm(this.negLut2, x, this.lutRow, S); // [B,S]
|
|
213
|
+
const err3 = ops.reshape(err, [B, J, G], S);
|
|
214
|
+
const gn3 = ops.add(err3, best, S);
|
|
215
|
+
const gn = ops.reshape(gn3, [B, n], S);
|
|
216
|
+
ops.evalAll([gn, back[t]!]);
|
|
217
|
+
for (const a of [g3, mx, eq, e8, sel, best, x, err, err3, gn3, g]) a.dispose();
|
|
218
|
+
g = gn;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
if (overlap) {
|
|
222
|
+
const m = ops.equal(this.sLow, overlap, S);
|
|
223
|
+
const masked = ops.where(m, g, this.negBig, S);
|
|
224
|
+
m.dispose(); g.dispose();
|
|
225
|
+
g = masked;
|
|
226
|
+
}
|
|
227
|
+
// argmax over all 2^L states, again via max+compare (see note above).
|
|
228
|
+
const fmx = ops.maxAxis(g, 1, true, S); // [B,1]
|
|
229
|
+
const feq = ops.equal(g, fmx, S);
|
|
230
|
+
const fsel = ops.where(feq, this.sIdx, this.negOne, S); // [B,S] int32
|
|
231
|
+
const finI = ops.maxAxis(fsel, 1, true, S); // [B,1] int32
|
|
232
|
+
for (const a of [fmx, feq, fsel, g]) a.dispose();
|
|
233
|
+
|
|
234
|
+
const states: (MlxArray | null)[] = new Array(T).fill(null);
|
|
235
|
+
let cur = finI;
|
|
236
|
+
let curKept = T - 1 >= from;
|
|
237
|
+
if (curKept) states[T - 1] = cur;
|
|
238
|
+
for (let t = T - 1; t >= 1; t--) {
|
|
239
|
+
const j = ops.rightShift(cur, this.kConst, S); // [B,1] int32
|
|
240
|
+
const m8 = ops.takeAlongAxis(back[t]!, j, 1, S); // [B,1] uint8
|
|
241
|
+
const mi = m8.astype(Dtype.int32, S);
|
|
242
|
+
const off = ops.mul(mi, this.jConst, S);
|
|
243
|
+
const prev = ops.add(j, off, S);
|
|
244
|
+
for (const a of [m8, mi, off, j]) a.dispose();
|
|
245
|
+
back[t]!.dispose();
|
|
246
|
+
back[t] = null;
|
|
247
|
+
if (!curKept) cur.dispose();
|
|
248
|
+
cur = prev;
|
|
249
|
+
curKept = t - 1 >= from;
|
|
250
|
+
if (curKept) states[t - 1] = cur;
|
|
251
|
+
}
|
|
252
|
+
if (!curKept) cur.dispose();
|
|
253
|
+
return states;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** Trellis-encode + decode [B,T] rows (already variance-matched to the code).
|
|
257
|
+
* Returns [B,T] f32 reconstruction. */
|
|
258
|
+
encodeDecode(X: MlxArray): MlxArray {
|
|
259
|
+
const [B, T] = X.shape as [number, number];
|
|
260
|
+
if (T !== this.cfg.T) throw new Error(`block length ${T} != cfg.T ${this.cfg.T}`);
|
|
261
|
+
// NOTE: every intermediate gets its own handle and an explicit dispose —
|
|
262
|
+
// an undisposed handle for a view (transpose/concat/slice) pins its PARENT
|
|
263
|
+
// buffer, which is how the first 27-tensor run leaked ~1.4 GB per tensor.
|
|
264
|
+
const two = ops.mulScalar(X, 2, S);
|
|
265
|
+
const twoT = ops.transposeAxes(two, [1, 0], S);
|
|
266
|
+
const X2T = ops.contiguous(twoT, S); // [T,B]
|
|
267
|
+
two.dispose(); twoT.dispose();
|
|
268
|
+
ops.evalAll([X2T]);
|
|
269
|
+
|
|
270
|
+
let overlap: MlxArray | null = null;
|
|
271
|
+
if (this.cfg.tailBiting) {
|
|
272
|
+
// Algorithm 4: rotate right by ⌊T/2⌋, unconstrained Viterbi, read the
|
|
273
|
+
// state that lands on original t=0 and use its top L-k bits as overlap.
|
|
274
|
+
const H = T >> 1;
|
|
275
|
+
const a = X2T.slice([H, 0], [T, B], S);
|
|
276
|
+
const b = X2T.slice([0, 0], [H, B], S);
|
|
277
|
+
const cat = ops.concatAxis([a, b], 0, S);
|
|
278
|
+
const rot = ops.contiguous(cat, S);
|
|
279
|
+
a.dispose(); b.dispose(); cat.dispose();
|
|
280
|
+
ops.evalAll([rot]);
|
|
281
|
+
const st = this.viterbi(rot, B, null, H);
|
|
282
|
+
rot.dispose();
|
|
283
|
+
overlap = ops.rightShift(st[H]!, this.kConst, S);
|
|
284
|
+
ops.evalAll([overlap]);
|
|
285
|
+
for (const s of st) s?.dispose();
|
|
286
|
+
clearCache();
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const st = this.viterbi(X2T, B, overlap, 0);
|
|
290
|
+
X2T.dispose();
|
|
291
|
+
overlap?.dispose();
|
|
292
|
+
const idx = ops.concatAxis(st as MlxArray[], 1, S); // [B,T] int32
|
|
293
|
+
for (const s of st) s?.dispose();
|
|
294
|
+
const out = ops.takeAxis(this.lutFlat, idx, 0, S);
|
|
295
|
+
idx.dispose();
|
|
296
|
+
ops.evalAll([out]);
|
|
297
|
+
return out;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** encodeDecode over [B,T] in chunks of at most `maxB` rows. The caller has
|
|
301
|
+
* already variance-matched X to the code (BlockLDLQ path). */
|
|
302
|
+
encodeDecodeChunked(X: MlxArray, maxB: number): MlxArray {
|
|
303
|
+
const [B, T] = X.shape as [number, number];
|
|
304
|
+
if (B <= maxB) return this.encodeDecode(X);
|
|
305
|
+
const parts: MlxArray[] = [];
|
|
306
|
+
for (let b0 = 0; b0 < B; b0 += maxB) {
|
|
307
|
+
const b1 = Math.min(B, b0 + maxB);
|
|
308
|
+
const sl = X.slice([b0, 0], [b1, T], S);
|
|
309
|
+
const chunk = ops.contiguous(sl, S);
|
|
310
|
+
sl.dispose();
|
|
311
|
+
ops.evalAll([chunk]);
|
|
312
|
+
parts.push(this.encodeDecode(chunk));
|
|
313
|
+
chunk.dispose();
|
|
314
|
+
clearCache();
|
|
315
|
+
}
|
|
316
|
+
const out = ops.concatAxis(parts, 0, S);
|
|
317
|
+
for (const p of parts) p.dispose();
|
|
318
|
+
ops.evalAll([out]);
|
|
319
|
+
return out;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** Fake-quant a 2-D tensor whose trellis axis is the LAST axis. Per-row
|
|
323
|
+
* (per rotated vector) fp16 scale, QTIP's Wscale = RMS(W)/RMS(lut) applied
|
|
324
|
+
* per row instead of per tensor (deviation: our incoherence processing is
|
|
325
|
+
* one-sided, so rows do not share a norm). */
|
|
326
|
+
fakeQuantRows(W: MlxArray, batchBlocks: number, onProgress?: (done: number, total: number) => void): MlxArray {
|
|
327
|
+
const [N, C] = W.shape as [number, number];
|
|
328
|
+
const T = this.cfg.T;
|
|
329
|
+
if (C % T !== 0) throw new Error(`trellis axis ${C} not a multiple of block ${T}`);
|
|
330
|
+
const sq = ops.square(W, S);
|
|
331
|
+
const ms = ops.meanAxis(sq, 1, true, S);
|
|
332
|
+
sq.dispose();
|
|
333
|
+
const rms = ops.sqrt(ms, S);
|
|
334
|
+
ms.dispose();
|
|
335
|
+
const inv = ops.mulScalar(rms, 1 / this.lutRms, S); // scale = rms/lutRms
|
|
336
|
+
rms.dispose();
|
|
337
|
+
// guard all-zero rows
|
|
338
|
+
const zero = Arr.fromFloat32(new Float32Array([0]), []);
|
|
339
|
+
const one = Arr.fromFloat32(new Float32Array([1]), []);
|
|
340
|
+
const isz = ops.equal(inv, zero, S);
|
|
341
|
+
const scale = ops.where(isz, one, inv, S);
|
|
342
|
+
for (const a of [zero, one, isz, inv]) a.dispose();
|
|
343
|
+
// fp16 round-trip: the scale we would actually store
|
|
344
|
+
const s16 = scale.astype(Dtype.float16, S);
|
|
345
|
+
const scaleQ = s16.astype(Dtype.float32, S);
|
|
346
|
+
scale.dispose(); s16.dispose();
|
|
347
|
+
|
|
348
|
+
const Xn = ops.div(W, scaleQ, S);
|
|
349
|
+
const flat = ops.reshape(Xn, [(N * C) / T, T], S);
|
|
350
|
+
Xn.dispose();
|
|
351
|
+
ops.evalAll([flat]);
|
|
352
|
+
|
|
353
|
+
const nBlocks = (N * C) / T;
|
|
354
|
+
const parts: MlxArray[] = [];
|
|
355
|
+
for (let b0 = 0; b0 < nBlocks; b0 += batchBlocks) {
|
|
356
|
+
const b1 = Math.min(nBlocks, b0 + batchBlocks);
|
|
357
|
+
const sl = flat.slice([b0, 0], [b1, T], S);
|
|
358
|
+
const chunk = ops.contiguous(sl, S);
|
|
359
|
+
sl.dispose();
|
|
360
|
+
ops.evalAll([chunk]);
|
|
361
|
+
const rec = this.encodeDecode(chunk);
|
|
362
|
+
chunk.dispose();
|
|
363
|
+
parts.push(rec);
|
|
364
|
+
clearCache();
|
|
365
|
+
onProgress?.(b1, nBlocks);
|
|
366
|
+
}
|
|
367
|
+
flat.dispose();
|
|
368
|
+
const all = parts.length === 1 ? parts[0]! : ops.concatAxis(parts, 0, S);
|
|
369
|
+
if (parts.length > 1) for (const p of parts) p.dispose();
|
|
370
|
+
const rec2 = ops.reshape(all, [N, C], S);
|
|
371
|
+
all.dispose();
|
|
372
|
+
const out = ops.mul(rec2, scaleQ, S);
|
|
373
|
+
rec2.dispose();
|
|
374
|
+
scaleQ.dispose();
|
|
375
|
+
ops.evalAll([out]);
|
|
376
|
+
return out;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** Trellis-encode [B,T] rows (already variance-matched) and return the
|
|
380
|
+
* decoded STATE at every t as [B,T] int32 — the k low bits of state t are
|
|
381
|
+
* the emitted symbol, and (bitshift trellis) state t is exactly the last
|
|
382
|
+
* L/k symbols, which is what makes random-access decode possible. */
|
|
383
|
+
encodeStates(X: MlxArray): MlxArray {
|
|
384
|
+
const [B, T] = X.shape as [number, number];
|
|
385
|
+
if (T !== this.cfg.T) throw new Error(`block length ${T} != cfg.T ${this.cfg.T}`);
|
|
386
|
+
const two = ops.mulScalar(X, 2, S);
|
|
387
|
+
const twoT = ops.transposeAxes(two, [1, 0], S);
|
|
388
|
+
const X2T = ops.contiguous(twoT, S);
|
|
389
|
+
two.dispose(); twoT.dispose();
|
|
390
|
+
ops.evalAll([X2T]);
|
|
391
|
+
let overlap: MlxArray | null = null;
|
|
392
|
+
if (this.cfg.tailBiting) {
|
|
393
|
+
const H = T >> 1;
|
|
394
|
+
const a = X2T.slice([H, 0], [T, B], S);
|
|
395
|
+
const b = X2T.slice([0, 0], [H, B], S);
|
|
396
|
+
const cat = ops.concatAxis([a, b], 0, S);
|
|
397
|
+
const rot = ops.contiguous(cat, S);
|
|
398
|
+
a.dispose(); b.dispose(); cat.dispose();
|
|
399
|
+
ops.evalAll([rot]);
|
|
400
|
+
const st = this.viterbi(rot, B, null, H);
|
|
401
|
+
rot.dispose();
|
|
402
|
+
overlap = ops.rightShift(st[H]!, this.kConst, S);
|
|
403
|
+
ops.evalAll([overlap]);
|
|
404
|
+
for (const s of st) s?.dispose();
|
|
405
|
+
clearCache();
|
|
406
|
+
}
|
|
407
|
+
const st = this.viterbi(X2T, B, overlap, 0);
|
|
408
|
+
X2T.dispose();
|
|
409
|
+
overlap?.dispose();
|
|
410
|
+
const idx = ops.concatAxis(st as MlxArray[], 1, S);
|
|
411
|
+
for (const s of st) s?.dispose();
|
|
412
|
+
ops.evalAll([idx]);
|
|
413
|
+
return idx;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/** States → decoded values ([B,T] f32), the exact map encodeDecode uses. */
|
|
417
|
+
decodeStates(idx: MlxArray): MlxArray {
|
|
418
|
+
const out = ops.takeAxis(this.lutFlat, idx, 0, S);
|
|
419
|
+
ops.evalAll([out]);
|
|
420
|
+
return out;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/** fakeQuantRows that ALSO returns the packed bit-stream and the fp16 row
|
|
424
|
+
* scales — the on-disk trellis format (see packStates). `rec` is the same
|
|
425
|
+
* f32 reconstruction fakeQuantRows returns, so the fake-quant and packed
|
|
426
|
+
* artifacts are built from one Viterbi pass. */
|
|
427
|
+
fakeQuantRowsPacked(
|
|
428
|
+
W: MlxArray, batchBlocks: number, onProgress?: (done: number, total: number) => void,
|
|
429
|
+
): { rec: MlxArray; codes: MlxArray; scales: MlxArray } {
|
|
430
|
+
const [N, C] = W.shape as [number, number];
|
|
431
|
+
const T = this.cfg.T;
|
|
432
|
+
if (C % T !== 0) throw new Error(`trellis axis ${C} not a multiple of block ${T}`);
|
|
433
|
+
const sq = ops.square(W, S);
|
|
434
|
+
const ms = ops.meanAxis(sq, 1, true, S);
|
|
435
|
+
sq.dispose();
|
|
436
|
+
const rms = ops.sqrt(ms, S);
|
|
437
|
+
ms.dispose();
|
|
438
|
+
const inv = ops.mulScalar(rms, 1 / this.lutRms, S);
|
|
439
|
+
rms.dispose();
|
|
440
|
+
const zero = Arr.fromFloat32(new Float32Array([0]), []);
|
|
441
|
+
const one = Arr.fromFloat32(new Float32Array([1]), []);
|
|
442
|
+
const isz = ops.equal(inv, zero, S);
|
|
443
|
+
const scale = ops.where(isz, one, inv, S);
|
|
444
|
+
for (const a of [zero, one, isz, inv]) a.dispose();
|
|
445
|
+
const s16 = scale.astype(Dtype.float16, S); // [N,1] f16 — stored
|
|
446
|
+
const scaleQ = s16.astype(Dtype.float32, S);
|
|
447
|
+
scale.dispose();
|
|
448
|
+
const scales = ops.reshape(s16, [N], S);
|
|
449
|
+
s16.dispose();
|
|
450
|
+
ops.evalAll([scales]);
|
|
451
|
+
|
|
452
|
+
const Xn = ops.div(W, scaleQ, S);
|
|
453
|
+
const flat = ops.reshape(Xn, [(N * C) / T, T], S);
|
|
454
|
+
Xn.dispose();
|
|
455
|
+
ops.evalAll([flat]);
|
|
456
|
+
|
|
457
|
+
const nBlocks = (N * C) / T;
|
|
458
|
+
const wordsPerBlock = (T * this.cfg.K) / 32;
|
|
459
|
+
const packed = new Uint32Array(nBlocks * wordsPerBlock);
|
|
460
|
+
const parts: MlxArray[] = [];
|
|
461
|
+
for (let b0 = 0; b0 < nBlocks; b0 += batchBlocks) {
|
|
462
|
+
const b1 = Math.min(nBlocks, b0 + batchBlocks);
|
|
463
|
+
const sl = flat.slice([b0, 0], [b1, T], S);
|
|
464
|
+
const chunk = ops.contiguous(sl, S);
|
|
465
|
+
sl.dispose();
|
|
466
|
+
ops.evalAll([chunk]);
|
|
467
|
+
const idx = this.encodeStates(chunk);
|
|
468
|
+
chunk.dispose();
|
|
469
|
+
const rec = this.decodeStates(idx);
|
|
470
|
+
parts.push(rec);
|
|
471
|
+
const u32 = idx.astype(Dtype.uint32, S); // rawBytes has no int32 path; states are >= 0
|
|
472
|
+
const raw = u32.rawBytes(); // [B,T] row-major
|
|
473
|
+
u32.dispose();
|
|
474
|
+
const st = new Int32Array(raw.buffer, raw.byteOffset, raw.byteLength / 4);
|
|
475
|
+
packStates(st, b1 - b0, T, this.cfg.K, packed.subarray(b0 * wordsPerBlock, b1 * wordsPerBlock));
|
|
476
|
+
idx.dispose();
|
|
477
|
+
clearCache();
|
|
478
|
+
onProgress?.(b1, nBlocks);
|
|
479
|
+
}
|
|
480
|
+
flat.dispose();
|
|
481
|
+
const all = parts.length === 1 ? parts[0]! : ops.concatAxis(parts, 0, S);
|
|
482
|
+
if (parts.length > 1) for (const p of parts) p.dispose();
|
|
483
|
+
const rec2 = ops.reshape(all, [N, C], S);
|
|
484
|
+
all.dispose();
|
|
485
|
+
const out = ops.mul(rec2, scaleQ, S);
|
|
486
|
+
rec2.dispose();
|
|
487
|
+
scaleQ.dispose();
|
|
488
|
+
ops.evalAll([out]);
|
|
489
|
+
const codes = Arr.fromBytesCopy(
|
|
490
|
+
new Uint8Array(packed.buffer, packed.byteOffset, packed.byteLength),
|
|
491
|
+
[N, (C * this.cfg.K) / 32], Dtype.uint32,
|
|
492
|
+
);
|
|
493
|
+
return { rec: out, codes, scales };
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// ------------------------------------------------------------ packed format ---
|
|
498
|
+
//
|
|
499
|
+
// One coded row = C/T blocks; one block = T·k bits = T·k/32 uint32 words
|
|
500
|
+
// (little-endian words, bit i of the block = word i>>5, bit i&31). Symbol b_t
|
|
501
|
+
// (= state_t & (2^k−1)) sits at bit offset (T−1−t)·k — REVERSED time — so the
|
|
502
|
+
// L-bit window starting at that offset, read LSB-first and wrapping around the
|
|
503
|
+
// block (tail-biting), is exactly state_t = b_t | b_{t−1}<<k | … . The kernel
|
|
504
|
+
// therefore decodes any position in O(1): two word loads, a shift, a mask, and
|
|
505
|
+
// the 1MAD hash (or a 4096-entry LUT). The fp16 per-row scale is stored as a
|
|
506
|
+
// separate `.scales` [rows] tensor; the reconstructed weight is
|
|
507
|
+
// bf16(f32(lut[state]) · f32(scale)), bit-identical to the fake-quant artifact.
|
|
508
|
+
|
|
509
|
+
export const TRELLIS_L = 12;
|
|
510
|
+
export const TRELLIS_T = 256;
|
|
511
|
+
|
|
512
|
+
/** Reorder k3/T256 codes into [two-block groups, rows, 48 words].
|
|
513
|
+
* The caller selects an axis0/1MAD/L12 tensor; no code values change. */
|
|
514
|
+
export function interleaveTrellisCodes(codes: MlxArray): MlxArray {
|
|
515
|
+
if (codes.dtype !== Dtype.uint32 || codes.ndim !== 2 ||
|
|
516
|
+
codes.shape[0]! < 1 || codes.shape[1]! < 48 || codes.shape[1]! % 48 !== 0)
|
|
517
|
+
throw new Error("trellis interleave: expected uint32 rows with whole two-block groups");
|
|
518
|
+
const [rows, words] = codes.shape as [number, number];
|
|
519
|
+
const view = ops.reshape(codes, [rows, words / 48, 48]);
|
|
520
|
+
const transposed = ops.transposeAxes(view, [1, 0, 2]);
|
|
521
|
+
view.dispose();
|
|
522
|
+
try { return ops.contiguous(transposed); }
|
|
523
|
+
finally { transposed.dispose(); }
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/** Pack `nBlocks` blocks of T states ([nBlocks·T] int32, row-major) into the
|
|
527
|
+
* reversed-time bit-stream described above, writing into `out`
|
|
528
|
+
* (nBlocks · wordsPerBlock uint32). */
|
|
529
|
+
export function packStates(states: Int32Array, nBlocks: number, T: number, k: number, out: Uint32Array): void {
|
|
530
|
+
const wpb = wordsPerBlock(T, k);
|
|
531
|
+
const mask = (1 << k) - 1;
|
|
532
|
+
for (let b = 0; b < nBlocks; b++) {
|
|
533
|
+
const base = b * wpb;
|
|
534
|
+
for (let w = 0; w < wpb; w++) out[base + w] = 0;
|
|
535
|
+
for (let t = 0; t < T; t++) {
|
|
536
|
+
const sym = states[b * T + t]! & mask;
|
|
537
|
+
const p = (T - 1 - t) * k;
|
|
538
|
+
const wi = p >>> 5, off = p & 31;
|
|
539
|
+
out[base + wi] = (out[base + wi]! | (sym << off)) >>> 0;
|
|
540
|
+
if (off + k > 32) out[base + wi + 1] = (out[base + wi + 1]! | (sym >>> (32 - off))) >>> 0;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/** Read state_t back out of one packed block (host reference for the kernel). */
|
|
546
|
+
export function stateAt(words: Uint32Array, blockWordOffset: number, wpb: number, t: number, T: number, k: number, L: number): number {
|
|
547
|
+
const p = (T - 1 - t) * k;
|
|
548
|
+
const wi = p >>> 5, off = p & 31;
|
|
549
|
+
const w0 = words[blockWordOffset + wi]!;
|
|
550
|
+
const w1 = words[blockWordOffset + ((wi + 1) % wpb)]!;
|
|
551
|
+
const lo = off === 0 ? w0 : ((w0 >>> off) | (w1 << (32 - off))) >>> 0;
|
|
552
|
+
return lo & ((1 << L) - 1);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/** Host decode of a whole packed [N, C] tensor to f32 (reference only). */
|
|
556
|
+
export function unpackDecodeHost(
|
|
557
|
+
words: Uint32Array, scales: Float32Array, N: number, C: number, k: number, T: number, lut: Float32Array,
|
|
558
|
+
): Float32Array {
|
|
559
|
+
const wpb = wordsPerBlock(T, k);
|
|
560
|
+
const L = Math.log2(lut.length);
|
|
561
|
+
const out = new Float32Array(N * C);
|
|
562
|
+
const blocksPerRow = C / T;
|
|
563
|
+
for (let n = 0; n < N; n++) {
|
|
564
|
+
for (let b = 0; b < blocksPerRow; b++) {
|
|
565
|
+
const bw = (n * blocksPerRow + b) * wpb;
|
|
566
|
+
for (let t = 0; t < T; t++) out[n * C + b * T + t] = lut[stateAt(words, bw, wpb, t, T, k, L)]! * scales[n]!;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
return out;
|
|
570
|
+
}
|