@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.
@@ -0,0 +1,628 @@
1
+ // Mixed-precision quantization optimizer: select per-layer bit-widths.
2
+ //
3
+ // 1:1 port of optiq/core/optimizer.py `optimize_mixed_precision` (the pure
4
+ // data-logic knapsack). Every helper is faithful to the Python:
5
+ //
6
+ // - greedy min-heap knapsack with `(-efficiency, layerName, old, new, klRed)`
7
+ // ordering (Python heapq tuple comparison, reproduced exactly)
8
+ // - block-aware floor with the attention-reserve carve-out
9
+ // - protected-layer ×100 KL bonus (output / MoE-router / boundary layers)
10
+ // - `_kl_reduction` uniform-vs-bf16 reference-mode sign detection
11
+ // - NaN-sensitivity handling (treat as maximally sensitive)
12
+ // - post-greedy block-run guard
13
+ //
14
+ // Verified bit-for-bit against the Python via
15
+ // `02d723a:tests/parity/quantize-allocator.test.ts`.
16
+ //
17
+ // The latency-aware variants (`optimize_latency_aware`,
18
+ // `optimize_for_latency_budget`) are intentionally NOT ported — they pull in
19
+ // optiq's hardware/latency model, which is out of scope for this port (the
20
+ // quality-only knapsack is the sensitivity-driven core).
21
+
22
+ import type { SensitivityResult } from "./sensitivity";
23
+
24
+ /** Per-layer chosen bit-width (port of optiq LayerQuantConfig). */
25
+ export interface LayerQuantConfig {
26
+ layerName: string;
27
+ bits: number;
28
+ groupSize: number;
29
+ paramCount: number;
30
+ }
31
+
32
+ /** Result of the knapsack (port of optiq OptimizationResult, quality fields). */
33
+ export interface OptimizationResult {
34
+ configs: LayerQuantConfig[];
35
+ targetBpw: number;
36
+ achievedBpw: number;
37
+ /** Kept for parity with the Python type; always 0 for multi-tier. */
38
+ threshold: number;
39
+ nHighBits: number;
40
+ nLowBits: number;
41
+ totalParams: number;
42
+ estimatedSizeMb: number;
43
+ }
44
+
45
+ export interface OptimizeMixedPrecisionOptions {
46
+ targetBpw?: number;
47
+ candidateBits?: number[];
48
+ groupSize?: number;
49
+ protectFirstLast?: boolean;
50
+ nProtect?: number;
51
+ nFloorPerBlock?: number;
52
+ maxLowBitRun?: number;
53
+ /** Pre-N-tier shims; ignored when candidateBits is set explicitly. */
54
+ lowBits?: number;
55
+ highBits?: number;
56
+ }
57
+
58
+ // --------------------------------------------------------------------------
59
+ // Min-heap matching Python heapq's ordering on the upgrade tuple.
60
+ // --------------------------------------------------------------------------
61
+
62
+ /** Upgrade-candidate tuple, in Python heapq comparison order:
63
+ * (-efficiency, layerName, oldBits, newBits, klReduction). */
64
+ export type UpgradeEntry = [number, string, number, number, number];
65
+
66
+ /** Lexicographic comparison of two upgrade tuples, mirroring Python's tuple
67
+ * comparison used by heapq (numeric fields numerically, the name lexically).
68
+ * Returns <0 if a < b, >0 if a > b, 0 if equal. */
69
+ function compareUpgrade(a: UpgradeEntry, b: UpgradeEntry): number {
70
+ if (a[0] !== b[0]) return a[0] < b[0] ? -1 : 1; // -efficiency
71
+ if (a[1] !== b[1]) return a[1] < b[1] ? -1 : 1; // layerName (string)
72
+ if (a[2] !== b[2]) return a[2] < b[2] ? -1 : 1; // oldBits
73
+ if (a[3] !== b[3]) return a[3] < b[3] ? -1 : 1; // newBits
74
+ if (a[4] !== b[4]) return a[4] < b[4] ? -1 : 1; // klReduction
75
+ return 0;
76
+ }
77
+
78
+ /** Binary min-heap over UpgradeEntry with Python-heapq tuple ordering.
79
+ * Dependency-free; sift-up/sift-down identical in behavior to heapq. */
80
+ export class UpgradeHeap {
81
+ private readonly data: UpgradeEntry[] = [];
82
+
83
+ get length(): number {
84
+ return this.data.length;
85
+ }
86
+
87
+ push(entry: UpgradeEntry): void {
88
+ const d = this.data;
89
+ d.push(entry);
90
+ let i = d.length - 1;
91
+ while (i > 0) {
92
+ const parent = (i - 1) >> 1;
93
+ if (compareUpgrade(d[i]!, d[parent]!) < 0) {
94
+ const tmp = d[i]!;
95
+ d[i] = d[parent]!;
96
+ d[parent] = tmp;
97
+ i = parent;
98
+ } else break;
99
+ }
100
+ }
101
+
102
+ pop(): UpgradeEntry | undefined {
103
+ const d = this.data;
104
+ if (d.length === 0) return undefined;
105
+ const top = d[0]!;
106
+ const last = d.pop()!;
107
+ if (d.length > 0) {
108
+ d[0] = last;
109
+ let i = 0;
110
+ const n = d.length;
111
+ for (;;) {
112
+ const l = 2 * i + 1;
113
+ const r = 2 * i + 2;
114
+ let smallest = i;
115
+ if (l < n && compareUpgrade(d[l]!, d[smallest]!) < 0) smallest = l;
116
+ if (r < n && compareUpgrade(d[r]!, d[smallest]!) < 0) smallest = r;
117
+ if (smallest === i) break;
118
+ const tmp = d[i]!;
119
+ d[i] = d[smallest]!;
120
+ d[smallest] = tmp;
121
+ i = smallest;
122
+ }
123
+ }
124
+ return top;
125
+ }
126
+ }
127
+
128
+ // --------------------------------------------------------------------------
129
+ // compute_bpw / _compute_allocation_bpw
130
+ // --------------------------------------------------------------------------
131
+
132
+ /** Average bits-per-weight from layer configs (port of compute_bpw). */
133
+ export function computeBpw(configs: LayerQuantConfig[]): number {
134
+ let totalBits = 0;
135
+ let totalParams = 0;
136
+ for (const c of configs) {
137
+ totalBits += c.bits * c.paramCount;
138
+ totalParams += c.paramCount;
139
+ }
140
+ if (totalParams === 0) return 0;
141
+ return totalBits / totalParams;
142
+ }
143
+
144
+ /** BPW from a layer->bits allocation map (port of _compute_allocation_bpw). */
145
+ function computeAllocationBpw(
146
+ allocation: Map<string, number>,
147
+ results: SensitivityResult[],
148
+ ): number {
149
+ let totalBits = 0;
150
+ let totalParams = 0;
151
+ for (const r of results) {
152
+ totalBits += allocation.get(r.layerName)! * r.paramCount;
153
+ totalParams += r.paramCount;
154
+ }
155
+ return totalBits / Math.max(totalParams, 1);
156
+ }
157
+
158
+ // --------------------------------------------------------------------------
159
+ // KL-reduction (reference-mode autodetect) + heap push
160
+ // --------------------------------------------------------------------------
161
+
162
+ /** Quality benefit of upgrading current→next bits (port of _kl_reduction).
163
+ *
164
+ * Two reference-mode semantics, autodetected by the sign of (kl_next - kl_cur):
165
+ * - bf16 reference: sensitivities[b] = KL(bf16 || b-bit); upgrading reduces
166
+ * KL → benefit = kl_current - kl_next.
167
+ * - uniform-N reference: sensitivities[baseline_bit] ≈ 0; sensitivities[b>base]
168
+ * measures how much upgrading moves output back toward bf16 (the benefit
169
+ * directly). Treat kl_next > kl_current as the uniform-mode signal. */
170
+ export function klReduction(
171
+ r: SensitivityResult,
172
+ currentBits: number,
173
+ nextBits: number,
174
+ ): number {
175
+ const klCurrent = r.sensitivities[currentBits] ?? 0;
176
+ const klNext = r.sensitivities[nextBits] ?? 0;
177
+ if (nextBits > currentBits && klNext > klCurrent) {
178
+ return klNext - klCurrent;
179
+ }
180
+ return klCurrent - klNext;
181
+ }
182
+
183
+ /** Push the next upgrade step for a layer (port of _push_next_upgrade). */
184
+ function pushNextUpgrade(
185
+ heap: UpgradeHeap,
186
+ r: SensitivityResult,
187
+ currentBits: number,
188
+ candidateBits: number[],
189
+ ): void {
190
+ const idx = candidateBits.indexOf(currentBits);
191
+ if (idx < 0 || idx >= candidateBits.length - 1) return; // already at max
192
+
193
+ const nextBits = candidateBits[idx + 1]!;
194
+ const klRed = klReduction(r, currentBits, nextBits);
195
+ if (klRed <= 0) return; // no benefit
196
+
197
+ const bitCost = (nextBits - currentBits) * r.paramCount;
198
+ const efficiency = klRed / Math.max(bitCost, 1);
199
+
200
+ // max-heap via negative efficiency
201
+ heap.push([-efficiency, r.layerName, currentBits, nextBits, klRed]);
202
+ }
203
+
204
+ // --------------------------------------------------------------------------
205
+ // Protected-layer identification (output / MoE / boundary)
206
+ // --------------------------------------------------------------------------
207
+
208
+ /** Output-projection layers that always get high bits (port of
209
+ * _identify_output_layers). lm_head, embeddings, output proj, plus any layer
210
+ * not inside a "layers.N" block. */
211
+ function identifyOutputLayers(layerNames: string[]): Set<string> {
212
+ const protectedSet = new Set<string>();
213
+ const outputKeywords = [
214
+ "lm_head", "embed_tokens", "wte", "wpe", "output_proj", "embed_out", "head",
215
+ ];
216
+ for (const name of layerNames) {
217
+ const nameLower = name.toLowerCase();
218
+ const parts = nameLower.split(".");
219
+ const last = parts[parts.length - 1] ?? "";
220
+ const lastTwo = parts.slice(-2);
221
+ for (const kw of outputKeywords) {
222
+ // Python: `kw in name_lower.split(".")[-1]` (substring of last segment)
223
+ // OR `kw in name_lower.split(".")[-2:]` (membership in last two)
224
+ if (last.includes(kw) || lastTwo.includes(kw)) {
225
+ protectedSet.add(name);
226
+ break;
227
+ }
228
+ }
229
+ // Also protect if the layer is NOT inside a "layers.N" block.
230
+ if (!name.split(".").includes("layers")) {
231
+ protectedSet.add(name);
232
+ }
233
+ }
234
+ return protectedSet;
235
+ }
236
+
237
+ /** MoE router projections and shared-expert MLPs to protect (port of
238
+ * _identify_moe_protected_layers). */
239
+ function identifyMoeProtectedLayers(layerNames: string[]): Set<string> {
240
+ const protectedSet = new Set<string>();
241
+ for (const name of layerNames) {
242
+ const parts = name.split(".");
243
+ if (parts.length === 0) continue;
244
+ const last = parts[parts.length - 1]!;
245
+ const prev = parts.length >= 2 ? parts[parts.length - 2]! : "";
246
+
247
+ // Router patterns: mlp.gate (Qwen3 MoE router, distinct from mlp.gate_proj),
248
+ // router, router.proj (Gemma-style).
249
+ if (
250
+ (last === "gate" && prev === "mlp") ||
251
+ last === "router" ||
252
+ (last === "proj" && prev === "router")
253
+ ) {
254
+ protectedSet.add(name);
255
+ continue;
256
+ }
257
+
258
+ // Shared-expert MLPs (any segment).
259
+ if (name.includes(".shared_experts.") || name.includes(".shared_expert.")) {
260
+ protectedSet.add(name);
261
+ continue;
262
+ }
263
+ }
264
+ return protectedSet;
265
+ }
266
+
267
+ /** First and last transformer block layers to protect (port of
268
+ * _identify_boundary_layers). */
269
+ function identifyBoundaryLayers(
270
+ layerNames: string[],
271
+ nProtect: number,
272
+ ): Set<string> {
273
+ const layerIndices = new Map<number, string[]>();
274
+ for (const name of layerNames) {
275
+ const parts = name.split(".");
276
+ for (let i = 0; i < parts.length; i++) {
277
+ if (parts[i] === "layers" && i + 1 < parts.length) {
278
+ const idx = Number.parseInt(parts[i + 1]!, 10);
279
+ if (!Number.isNaN(idx)) {
280
+ if (!layerIndices.has(idx)) layerIndices.set(idx, []);
281
+ layerIndices.get(idx)!.push(name);
282
+ }
283
+ }
284
+ }
285
+ }
286
+
287
+ if (layerIndices.size === 0) return new Set();
288
+
289
+ const sortedIndices = [...layerIndices.keys()].sort((a, b) => a - b);
290
+ const protectedSet = new Set<string>();
291
+ for (const idx of sortedIndices.slice(0, nProtect)) {
292
+ for (const n of layerIndices.get(idx)!) protectedSet.add(n);
293
+ }
294
+ for (const idx of sortedIndices.slice(-nProtect)) {
295
+ for (const n of layerIndices.get(idx)!) protectedSet.add(n);
296
+ }
297
+ return protectedSet;
298
+ }
299
+
300
+ // --------------------------------------------------------------------------
301
+ // Block helpers (floor + run-guard)
302
+ // --------------------------------------------------------------------------
303
+
304
+ /** Extract transformer block index from a layer name (port of _block_index).
305
+ * e.g. "...layers.7.mlp.up_proj" → 7. */
306
+ function blockIndex(layerName: string): number | null {
307
+ const m = /layers\.(\d+)/.exec(layerName);
308
+ return m ? Number.parseInt(m[1]!, 10) : null;
309
+ }
310
+
311
+ const ATTENTION_TOKENS: ReadonlySet<string> = new Set([
312
+ // Full-attention (Qwen, Llama, Gemma): q/k/v/o
313
+ "q_proj", "k_proj", "v_proj", "o_proj",
314
+ // Linear-attention / GatedDeltaNet (Qwen3.5/3.6 hybrid)
315
+ "in_proj_qkv", "in_proj_a", "in_proj_b", "in_proj_z", "out_proj",
316
+ // MoE attention variants and generic fall-throughs
317
+ "qkv_proj", "wqkv", "Wqkv", "attn_qkv",
318
+ ]);
319
+
320
+ /** Does this linear sit inside attention? (port of _is_attention_component) */
321
+ function isAttentionComponent(layerName: string): boolean {
322
+ const idx = layerName.lastIndexOf(".");
323
+ const last = idx >= 0 ? layerName.slice(idx + 1) : layerName;
324
+ return ATTENTION_TOKENS.has(last);
325
+ }
326
+
327
+ /** Pre-upgrade per-block components lowest_bit → second_lowest_bit (port of
328
+ * _apply_block_aware_floor). Returns the number of upgrades applied. */
329
+ function applyBlockAwareFloor(
330
+ allocation: Map<string, number>,
331
+ sensitivityResults: SensitivityResult[],
332
+ lowestBit: number,
333
+ secondLowestBit: number,
334
+ nFloor: number,
335
+ ): number {
336
+ const blockLayers = new Map<number, Array<[number, string]>>();
337
+ for (const r of sensitivityResults) {
338
+ const idx = blockIndex(r.layerName);
339
+ if (idx === null) continue;
340
+ const klLow = r.sensitivities[lowestBit] ?? 0;
341
+ if (!blockLayers.has(idx)) blockLayers.set(idx, []);
342
+ blockLayers.get(idx)!.push([klLow, r.layerName]);
343
+ }
344
+
345
+ let upgrades = 0;
346
+ for (const layers of blockLayers.values()) {
347
+ if (layers.length === 0) continue;
348
+ // most-sensitive first (stable like Python's Timsort on key=-x[0])
349
+ stableSort(layers, (a, b) => b[0] - a[0]);
350
+
351
+ const attn = layers.filter(([, n]) => isAttentionComponent(n));
352
+
353
+ // Reserve attention slots first. Full-attention blocks (q/k/v/o all
354
+ // present) get 2 reserved; single-projection blocks get 1.
355
+ let nAttnReserve = attn.length >= 4 ? 2 : attn.length > 0 ? 1 : 0;
356
+ nAttnReserve = Math.min(nAttnReserve, nFloor);
357
+
358
+ const isFullAttnBlock = attn.length >= 4;
359
+ const blockFloor = isFullAttnBlock ? nFloor : Math.min(nFloor, 1);
360
+
361
+ const picks: string[] = [];
362
+ for (const [, name] of attn.slice(0, nAttnReserve)) picks.push(name);
363
+
364
+ const pickedSet = new Set<string>(picks);
365
+ for (const [, name] of layers) {
366
+ if (picks.length >= blockFloor) break;
367
+ if (pickedSet.has(name)) continue;
368
+ picks.push(name);
369
+ pickedSet.add(name);
370
+ }
371
+
372
+ for (const name of picks) {
373
+ if ((allocation.get(name) ?? lowestBit) < secondLowestBit) {
374
+ allocation.set(name, secondLowestBit);
375
+ upgrades++;
376
+ }
377
+ }
378
+ }
379
+ return upgrades;
380
+ }
381
+
382
+ /** Scan for runs of consecutive low-bit-dominated blocks and upgrade their
383
+ * worst components (port of _enforce_block_run_limit). */
384
+ function enforceBlockRunLimit(
385
+ allocation: Map<string, number>,
386
+ sensitivityResults: SensitivityResult[],
387
+ lowestBit: number,
388
+ secondLowestBit: number,
389
+ maxRun: number,
390
+ ): number {
391
+ const byBlock = new Map<number, string[]>();
392
+ const sensMap = new Map<string, SensitivityResult>();
393
+ for (const r of sensitivityResults) sensMap.set(r.layerName, r);
394
+ for (const name of allocation.keys()) {
395
+ const idx = blockIndex(name);
396
+ if (idx === null) continue;
397
+ if (!byBlock.has(idx)) byBlock.set(idx, []);
398
+ byBlock.get(idx)!.push(name);
399
+ }
400
+
401
+ const blockIndices = [...byBlock.keys()].sort((a, b) => a - b);
402
+ const lowDom = new Map<number, boolean>();
403
+ for (const idx of blockIndices) {
404
+ const layers = byBlock.get(idx)!;
405
+ let low = 0;
406
+ for (const n of layers) if (allocation.get(n) === lowestBit) low++;
407
+ lowDom.set(idx, low / Math.max(layers.length, 1) > 0.5);
408
+ }
409
+
410
+ let upgrades = 0;
411
+ let runStart: number | null = null;
412
+ for (let i = 0; i < blockIndices.length; i++) {
413
+ const idx = blockIndices[i]!;
414
+ if (lowDom.get(idx)) {
415
+ if (runStart === null) runStart = i;
416
+ }
417
+ if (!lowDom.get(idx) || i === blockIndices.length - 1) {
418
+ const runEnd = !lowDom.get(idx) ? i : i + 1;
419
+ if (runStart !== null && runEnd - runStart > maxRun) {
420
+ const middle = blockIndices.slice(runStart, runEnd);
421
+ const stride = Math.max(1, maxRun);
422
+ for (let m = 0; m < middle.length; m += stride) {
423
+ const blk = middle[m]!;
424
+ const candidates: Array<[number, string]> = [];
425
+ for (const n of byBlock.get(blk)!) {
426
+ if (allocation.get(n) === lowestBit) {
427
+ candidates.push([sensMap.get(n)!.sensitivities[lowestBit] ?? 0, n]);
428
+ }
429
+ }
430
+ stableSort(candidates, (a, b) => b[0] - a[0]);
431
+ for (const [, name] of candidates.slice(0, 1)) {
432
+ allocation.set(name, secondLowestBit);
433
+ upgrades++;
434
+ }
435
+ }
436
+ }
437
+ runStart = null;
438
+ }
439
+ }
440
+ return upgrades;
441
+ }
442
+
443
+ /** Stable sort in place — Python's list.sort is stable; JS Array.sort is
444
+ * spec-stable since ES2019 (and in Bun's JSC), but we keep an explicit
445
+ * stable sort to be bit-exact regardless of engine. */
446
+ function stableSort<T>(arr: T[], cmp: (a: T, b: T) => number): void {
447
+ const indexed = arr.map((v, i) => [v, i] as [T, number]);
448
+ indexed.sort((a, b) => {
449
+ const c = cmp(a[0], b[0]);
450
+ return c !== 0 ? c : a[1] - b[1];
451
+ });
452
+ for (let i = 0; i < arr.length; i++) arr[i] = indexed[i]![0];
453
+ }
454
+
455
+ // --------------------------------------------------------------------------
456
+ // Public entry: optimize_mixed_precision
457
+ // --------------------------------------------------------------------------
458
+
459
+ /** Select per-layer bit-widths via greedy knapsack (1:1 port of
460
+ * optiq.core.optimizer.optimize_mixed_precision). */
461
+ export function optimizeMixedPrecision(
462
+ sensitivityResults: SensitivityResult[],
463
+ options: OptimizeMixedPrecisionOptions = {},
464
+ ): OptimizationResult {
465
+ const targetBpw = options.targetBpw ?? 4.0;
466
+ const groupSize = options.groupSize ?? 64;
467
+ const protectFirstLast = options.protectFirstLast ?? true;
468
+ const nProtect = options.nProtect ?? 1;
469
+ const nFloorPerBlock = options.nFloorPerBlock ?? 2;
470
+ const maxLowBitRun = options.maxLowBitRun ?? 3;
471
+ const lowBits = options.lowBits ?? 4;
472
+ const highBits = options.highBits ?? 8;
473
+
474
+ if (sensitivityResults.length === 0) {
475
+ return {
476
+ configs: [], targetBpw, achievedBpw: 0, threshold: 0,
477
+ nHighBits: 0, nLowBits: 0, totalParams: 0, estimatedSizeMb: 0,
478
+ };
479
+ }
480
+
481
+ // Infer candidate bits from sensitivity data if not provided.
482
+ let candidateBits = options.candidateBits;
483
+ if (candidateBits === undefined) {
484
+ const allBits = new Set<number>();
485
+ for (const r of sensitivityResults) {
486
+ for (const b of Object.keys(r.sensitivities)) allBits.add(Number(b));
487
+ }
488
+ candidateBits = [...allBits].sort((a, b) => a - b);
489
+ }
490
+ if (candidateBits.length === 0) candidateBits = [lowBits, highBits];
491
+
492
+ candidateBits = [...candidateBits].sort((a, b) => a - b);
493
+ const minBits = candidateBits[0]!;
494
+ const maxBits = candidateBits[candidateBits.length - 1]!;
495
+
496
+ const layerNames = sensitivityResults.map((r) => r.layerName);
497
+
498
+ // Identify protected layers.
499
+ const protectedLayers = new Set<string>();
500
+ for (const n of identifyOutputLayers(layerNames)) protectedLayers.add(n);
501
+ for (const n of identifyMoeProtectedLayers(layerNames)) protectedLayers.add(n);
502
+ if (protectFirstLast) {
503
+ for (const n of identifyBoundaryLayers(layerNames, nProtect)) protectedLayers.add(n);
504
+ }
505
+
506
+ let totalParams = 0;
507
+ for (const r of sensitivityResults) totalParams += r.paramCount;
508
+
509
+ // Initialize all layers at minimum bits.
510
+ const allocation = new Map<string, number>();
511
+ for (const r of sensitivityResults) allocation.set(r.layerName, minBits);
512
+
513
+ // Block-aware floor.
514
+ let floorUpgrades = 0;
515
+ if (nFloorPerBlock > 0 && candidateBits.length >= 2) {
516
+ const secondLowest = candidateBits[1]!;
517
+ floorUpgrades = applyBlockAwareFloor(
518
+ allocation, sensitivityResults, candidateBits[0]!, secondLowest, nFloorPerBlock,
519
+ );
520
+ }
521
+
522
+ // NaN-sensitivity handling — treat as maximally sensitive.
523
+ const nanLayers = new Set<string>();
524
+ let cleanedResults: SensitivityResult[] = [];
525
+ for (const r of sensitivityResults) {
526
+ const hasNan = Object.values(r.sensitivities).some((v) => Number.isNaN(v));
527
+ if (hasNan) {
528
+ nanLayers.add(r.layerName);
529
+ let maxFinite = Number.NEGATIVE_INFINITY;
530
+ for (const v of Object.values(r.sensitivities)) {
531
+ if (!Number.isNaN(v) && v > maxFinite) maxFinite = v;
532
+ }
533
+ if (maxFinite === Number.NEGATIVE_INFINITY) maxFinite = 1e6;
534
+ const fixedSens: Record<number, number> = {};
535
+ for (const [bStr, v] of Object.entries(r.sensitivities)) {
536
+ const b = Number(bStr);
537
+ fixedSens[b] = Number.isNaN(v)
538
+ ? maxFinite * 10 * (maxBits / Math.max(b, 1))
539
+ : v;
540
+ }
541
+ cleanedResults.push({
542
+ layerName: r.layerName, sensitivities: fixedSens, paramCount: r.paramCount,
543
+ });
544
+ } else {
545
+ cleanedResults.push(r);
546
+ }
547
+ }
548
+ if (nanLayers.size > 0) {
549
+ sensitivityResults = cleanedResults;
550
+ }
551
+
552
+ // Effective results — protected layers get a ×100 KL bonus so they upgrade first.
553
+ const effectiveResults = new Map<string, SensitivityResult>();
554
+ for (const r of sensitivityResults) {
555
+ if (protectedLayers.has(r.layerName)) {
556
+ const boosted: Record<number, number> = {};
557
+ for (const [bStr, v] of Object.entries(r.sensitivities)) {
558
+ boosted[Number(bStr)] = v * 100.0;
559
+ }
560
+ effectiveResults.set(r.layerName, {
561
+ layerName: r.layerName, sensitivities: boosted, paramCount: r.paramCount,
562
+ });
563
+ } else {
564
+ effectiveResults.set(r.layerName, r);
565
+ }
566
+ }
567
+
568
+ // Build upgrade candidates.
569
+ const upgradeHeap = new UpgradeHeap();
570
+ for (const r of sensitivityResults) {
571
+ const current = allocation.get(r.layerName)!;
572
+ pushNextUpgrade(upgradeHeap, effectiveResults.get(r.layerName)!, current, candidateBits);
573
+ }
574
+
575
+ // Greedy: target_bpw is a FLOOR — keep upgrading until BPW ≥ target.
576
+ while (
577
+ upgradeHeap.length > 0 &&
578
+ computeAllocationBpw(allocation, sensitivityResults) < targetBpw
579
+ ) {
580
+ const entry = upgradeHeap.pop()!;
581
+ const [, layerName, oldBits, newBits] = entry;
582
+
583
+ if (allocation.get(layerName) !== oldBits) continue; // stale
584
+
585
+ allocation.set(layerName, newBits);
586
+ pushNextUpgrade(upgradeHeap, effectiveResults.get(layerName)!, newBits, candidateBits);
587
+ }
588
+
589
+ // Post-greedy block-run guard.
590
+ let runfixUpgrades = 0;
591
+ if (maxLowBitRun > 0 && candidateBits.length >= 2) {
592
+ runfixUpgrades = enforceBlockRunLimit(
593
+ allocation, sensitivityResults, candidateBits[0]!, candidateBits[1]!, maxLowBitRun,
594
+ );
595
+ }
596
+ void floorUpgrades;
597
+ void runfixUpgrades;
598
+
599
+ // Build configs (in sensitivityResults order, matching Python).
600
+ const configs: LayerQuantConfig[] = sensitivityResults.map((r) => ({
601
+ layerName: r.layerName,
602
+ bits: allocation.get(r.layerName)!,
603
+ groupSize,
604
+ paramCount: r.paramCount,
605
+ }));
606
+
607
+ const achievedBpw = computeBpw(configs);
608
+ let nMax = 0;
609
+ let nMin = 0;
610
+ let estBits = 0;
611
+ for (const c of configs) {
612
+ if (c.bits === maxBits) nMax++;
613
+ if (c.bits === minBits) nMin++;
614
+ estBits += c.bits * c.paramCount;
615
+ }
616
+ const estSizeMb = estBits / 8 / (1024 * 1024);
617
+
618
+ return {
619
+ configs,
620
+ targetBpw,
621
+ achievedBpw,
622
+ threshold: 0,
623
+ nHighBits: nMax,
624
+ nLowBits: nMin,
625
+ totalParams,
626
+ estimatedSizeMb: estSizeMb,
627
+ };
628
+ }
@@ -0,0 +1,38 @@
1
+ import {
2
+ existsSync,
3
+ mkdirSync,
4
+ mkdtempSync,
5
+ readdirSync,
6
+ renameSync,
7
+ rmdirSync,
8
+ rmSync,
9
+ statSync,
10
+ } from "node:fs";
11
+ import { basename, dirname, join, resolve } from "node:path";
12
+
13
+ /** Build a complete directory beside its destination, then publish it with a
14
+ * single same-filesystem rename. Failed writers leave no partial destination. */
15
+ export async function writeAtomicDirectory<T>(
16
+ outDir: string,
17
+ write: (stagingDir: string) => Promise<T>,
18
+ ): Promise<T> {
19
+ const destination = resolve(outDir);
20
+ const replaceEmptyDestination = existsSync(destination);
21
+ if (
22
+ replaceEmptyDestination &&
23
+ (!statSync(destination).isDirectory() || readdirSync(destination).length !== 0)
24
+ ) throw new Error(`output directory already exists: ${outDir}`);
25
+
26
+ const parent = dirname(destination);
27
+ mkdirSync(parent, { recursive: true });
28
+ const staging = mkdtempSync(join(parent, `.${basename(destination)}.tmp-`));
29
+ try {
30
+ const result = await write(staging);
31
+ if (replaceEmptyDestination) rmdirSync(destination);
32
+ renameSync(staging, destination);
33
+ return result;
34
+ } catch (error) {
35
+ rmSync(staging, { recursive: true, force: true });
36
+ throw error;
37
+ }
38
+ }