File size: 25,051 Bytes
c5ee76b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
#!/usr/bin/env python3
"""Streaming requantisation of DeepSeek-V4.1 routed experts to a B200-sized mixed-Q2 checkpoint.

The official V4.1 checkpoint stores routed experts as MXFP4: 16 bytes of packed E2M1
values plus one E8M0 scale byte per 32 weights (4.25 bits/weight). This tool decodes
those blocks exactly, requantises the 40 main-layer expert matrices into ggml block
formats (IQ2_XXS for gate/up ``w1``/``w3``, Q2_K for down ``w2``) and writes a complete
non-Engram checkpoint where every other tensor is preserved byte-for-byte.

Quantisation is not imatrix-based: no activation calibration is collected and no
importance matrix is consumed. IQ2_XXS is called with a constant unit importance
vector, which is the unweighted reference path; the switch is made explicit in the
manifest of every output shard.

Design constraints:
  * one pass over the source; no intermediate BF16 copy and no whole-model buffer
  * output shards mirror the source shards, so a failed shard is retried alone
  * Engram tables (203 GB) stay native and are referenced by hash, never copied
  * MTP/DSpark expert tensors stay at native precision because DSpark is disabled

Commands:
    plan     build plan.json from the source index and shard headers
    convert  write the quantised checkpoint (parallel, resumable per shard)
    verify   re-check output headers, sizes and sampled tensor hashes
"""

from __future__ import annotations

import argparse
import ctypes
import hashlib
import json
import multiprocessing as mp
import os
import sys
from collections.abc import Iterable
from concurrent.futures import ProcessPoolExecutor
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any

import numpy as np

# --------------------------------------------------------------------------------------
# Recipe
# --------------------------------------------------------------------------------------

# gate/up/down projection -> ggml quantisation type name
DEFAULT_RECIPE = {"w1": "IQ2_XXS", "w3": "IQ2_XXS", "w2": "Q2_K"}

# ggml type ids; values must match enum ggml_type in the pinned llama.cpp revision.
GGML_TYPE_IDS = {
    "Q2_K": 10,
    "IQ2_XXS": 16,
    "F32": 0,
    "F16": 1,
    "BF16": 30,
    "I8": 24,
    "F8_E4M3": 35,
    "Q8_0": 8,
}

# (block elements, bytes per block) for the quantised expert types.
GGML_BLOCK = {"Q2_K": (256, 84), "IQ2_XXS": (256, 66)}

QUANTIZE_SYMBOLS = {"Q2_K": "quantize_q2_K", "IQ2_XXS": "quantize_iq2_xxs"}

MXFP4_TABLE = np.array(
    [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0],
    dtype=np.float32,
)
MXFP4_BLOCK = 32

# Tensors that stay native in the source checkpoint and are therefore not copied.
EXTERNAL_ROLE = "engram-native"


def is_external(name: str) -> bool:
    return ".engram." in name or name.startswith("engram.")


def is_main_routed_expert(name: str) -> bool:
    """True for the 40 main-layer routed expert weights this tool requantises."""
    if not name.startswith("layers."):
        return False
    if ".ffn.experts." not in name or "shared_experts" in name:
        return False
    return name.endswith(".weight")


def expert_projection(name: str) -> str:
    return name.rsplit(".", 2)[-2]


def is_expert_scale(name: str) -> bool:
    """MXFP4 E8M0 scale blocks belonging to a requantised expert weight."""
    if not name.startswith("layers."):
        return False
    if ".ffn.experts." not in name or "shared_experts" in name:
        return False
    return name.endswith(".scale") and name[: -len(".scale")].endswith(("w1", "w2", "w3"))


# --------------------------------------------------------------------------------------
# MXFP4
# --------------------------------------------------------------------------------------


def decode_mxfp4(weight: np.ndarray, scale: np.ndarray) -> np.ndarray:
    """Decode packed E2M1 nibbles with one E8M0 scale per 32 weights along the last axis.

    Nibble order follows the official converter: the low nibble of a byte is element 2k
    and the high nibble is element 2k+1. The E8M0 byte is a power of two, value 2**(b-127).
    """
    if weight.dtype != np.uint8:
        raise ValueError(f"packed weights must be uint8, got {weight.dtype}")
    if scale.dtype != np.uint8:
        raise ValueError(f"MXFP4 scales must be uint8/E8M0 bytes, got {scale.dtype}")
    if weight.shape[:-1] != scale.shape[:-1]:
        raise ValueError(f"scale leading shape {scale.shape[:-1]} != weight {weight.shape[:-1]}")
    if weight.shape[-1] * 2 != scale.shape[-1] * MXFP4_BLOCK:
        raise ValueError(
            f"packing mismatch: {weight.shape[-1]} bytes/row vs {scale.shape[-1]} scales/row"
        )

    out = np.empty((*weight.shape[:-1], weight.shape[-1] * 2), dtype=np.float32)
    out[..., 0::2] = MXFP4_TABLE[(weight & 0x0F).astype(np.uint8)]
    out[..., 1::2] = MXFP4_TABLE[((weight >> 4) & 0x0F).astype(np.uint8)]
    # 2**(b-127) in float32; b=0..254 are finite, 255 is the reserved NaN encoding.
    scales = np.exp2(scale.astype(np.int16) - np.int16(127)).astype(np.float32, copy=False)
    return out * np.repeat(scales, MXFP4_BLOCK, axis=-1)


# --------------------------------------------------------------------------------------
# ggml bridge
# --------------------------------------------------------------------------------------


class GgmlQuantizer:
    """ctypes bridge to the pinned llama.cpp ggml reference quantisers."""

    def __init__(self, lib_paths: Iterable[str]):
        loaded = []
        for path in lib_paths:
            if not os.path.exists(path):
                raise FileNotFoundError(f"ggml library not found: {path}")
            ctypes.CDLL(path, mode=ctypes.RTLD_GLOBAL)
            loaded.append(path)
        self.core = ctypes.CDLL(loaded[-1])
        self.core.ggml_quantize_init.argtypes = [ctypes.c_int]
        self.core.ggml_quantize_init.restype = None
        self._fns: dict[str, Any] = {}
        self._load_paths = tuple(loaded)

    def _fn(self, type_name: str):
        if type_name not in self._fns:
            sym = QUANTIZE_SYMBOLS[type_name]
            fn = getattr(self.core, sym)
            fn.restype = ctypes.c_size_t
            fn.argtypes = [
                ctypes.POINTER(ctypes.c_float),
                ctypes.c_void_p,
                ctypes.c_int64,
                ctypes.c_int64,
                ctypes.POINTER(ctypes.c_float),
            ]
            self._fns[type_name] = fn
            self.core.ggml_quantize_init(GGML_TYPE_IDS[type_name])
        return self._fns[type_name]

    def quantize(self, weights: np.ndarray, type_name: str, importance: np.ndarray | None = None):
        """Quantise a row-major float32 matrix; returns raw ggml block bytes."""
        if weights.ndim != 2 or weights.dtype != np.float32:
            raise ValueError("expected a float32 2-D matrix")
        block, block_bytes = GGML_BLOCK[type_name]
        rows, cols = weights.shape
        if cols % block:
            raise ValueError(f"{type_name} needs a row length multiple of {block}, got {cols}")
        if not weights.flags["C_CONTIGUOUS"]:
            weights = np.ascontiguousarray(weights)

        out = np.empty(rows * (cols // block) * block_bytes, dtype=np.uint8)
        fn = self._fn(type_name)
        arg = None
        if importance is not None:
            if importance.shape != (cols,):
                raise ValueError(f"importance must have {cols} entries")
            arg = importance.ctypes.data_as(ctypes.POINTER(ctypes.c_float))
        written = fn(
            weights.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
            out.ctypes.data,
            ctypes.c_int64(rows),
            ctypes.c_int64(cols),
            arg,
        )
        if written != out.nbytes:
            raise RuntimeError(f"{type_name}: wrote {written} of {out.nbytes} bytes")
        return out


_WORKER: dict[str, Any] = {}


def _worker_init(lib_paths: tuple[str, ...]) -> None:
    _WORKER["ggml"] = GgmlQuantizer(lib_paths)


# --------------------------------------------------------------------------------------
# Source layout and plan
# --------------------------------------------------------------------------------------


@dataclass
class SourceTensor:
    name: str
    shard: str
    dtype: str
    shape: tuple[int, ...]
    begin: int
    end: int
    data_start: int
    role: str = ""
    out_shard: str = ""
    out_offset: int = 0
    out_dtype: str = ""
    out_shape: tuple[int, ...] = ()
    out_bytes: int = 0
    ggml_type: str | None = None


def read_safetensors_header(path: Path) -> tuple[dict[str, Any], int]:
    with open(path, "rb") as fh:
        raw = fh.read(8)
        if len(raw) != 8:
            raise ValueError(f"{path}: truncated safetensors header")
        length = int.from_bytes(raw, "little")
        header = json.loads(fh.read(length))
    header.pop("__metadata__", None)
    return header, 8 + length


def quantised_shape(name: str, shape: tuple[int, ...], type_name: str) -> tuple[int, ...]:
    """Byte shape of the quantised tensor as stored in the output file."""
    logical = (shape[0], shape[1] * 2)
    block, block_bytes = GGML_BLOCK[type_name]
    if logical[1] % block:
        raise ValueError(f"{name}: {logical[1]} is not a multiple of {block}")
    return (logical[0], logical[1] // block * block_bytes)


def build_plan(source: Path, recipe: dict[str, str]) -> dict[str, Any]:
    index_path = source / "model.safetensors.index.json"
    index = json.loads(index_path.read_text())
    weight_map: dict[str, str] = index["weight_map"]
    headers: dict[str, tuple[dict[str, Any], int]] = {}
    tensors: list[SourceTensor] = []

    for name, shard in weight_map.items():
        if shard not in headers:
            headers[shard] = read_safetensors_header(source / shard)
        header, data_start = headers[shard]
        entry = header[name]
        begin, end = entry["data_offsets"]
        tensor = SourceTensor(
            name=name,
            shard=shard,
            dtype=entry["dtype"],
            shape=tuple(entry["shape"]),
            begin=begin,
            end=end,
            data_start=data_start,
        )
        if is_external(name):
            tensor.role = EXTERNAL_ROLE
        elif is_expert_scale(name):
            tensor.role = "dropped-expert-scale"
        elif is_main_routed_expert(name):
            type_name = recipe[expert_projection(name)]
            tensor.role = "quantised"
            tensor.ggml_type = type_name
            tensor.out_dtype = "U8"
            tensor.out_shape = quantised_shape(name, tensor.shape, type_name)
            tensor.out_bytes = int(np.prod(tensor.out_shape))
        else:
            tensor.role = "preserved"
            tensor.out_dtype = tensor.dtype
            tensor.out_shape = tensor.shape
            tensor.out_bytes = end - begin
        tensors.append(tensor)

    # Output shards mirror the source shards; dropped tensors leave no gap.
    by_shard: dict[str, list[SourceTensor]] = {}
    for tensor in tensors:
        if tensor.role in ("preserved", "quantised"):
            by_shard.setdefault(tensor.shard, []).append(tensor)

    shard_order = sorted(by_shard)
    out_names = {
        shard: f"quant-{i + 1:05d}-of-{len(shard_order):05d}.safetensors"
        for i, shard in enumerate(shard_order)
    }
    plan_shards = []
    for shard in shard_order:
        members = sorted(by_shard[shard], key=lambda t: (t.begin, t.name))
        offset = 0
        for tensor in members:
            tensor.out_shard = out_names[shard]
            tensor.out_offset = offset
            offset += tensor.out_bytes
        plan_shards.append(
            {
                "source_shard": shard,
                "output_shard": out_names[shard],
                "data_bytes": offset,
                "tensors": [asdict(t) for t in members],
            }
        )

    external = [asdict(t) for t in tensors if t.role == EXTERNAL_ROLE]
    dropped = [asdict(t) for t in tensors if t.role == "dropped-expert-scale"]
    quant = [t for t in tensors if t.role == "quantised"]
    preserved = [t for t in tensors if t.role == "preserved"]
    return {
        "source_dir": str(source),
        "source_revision": "2bc89ac599031fa673cab993f1df02fc4a98c673",
        "recipe": recipe,
        "importance": "unit (no imatrix; no activation calibration)",
        "external": external,
        "dropped": dropped,
        "totals": {
            "source_tensors": len(weight_map),
            "preserved": len(preserved),
            "quantised": len(quant),
            "dropped_expert_scales": len(dropped),
            "external_native": len(external),
            "quantised_logical_weights": sum(t.shape[0] * t.shape[1] * 2 for t in quant),
            "preserved_bytes": sum(t.out_bytes for t in preserved),
            "quantised_bytes": sum(t.out_bytes for t in quant),
            "external_bytes": sum(t.end - t.begin for t in tensors if t.role == EXTERNAL_ROLE),
            "dropped_bytes": sum(
                t.end - t.begin for t in tensors if t.role == "dropped-expert-scale"
            ),
            "output_bytes": sum(t.out_bytes for t in preserved + quant),
        },
        "shards": plan_shards,
    }


def plan_path(out: Path) -> Path:
    return out / "plan.json"


def load_plan(out: Path) -> dict[str, Any]:
    path = plan_path(out)
    if not path.exists():
        raise SystemExit(f"missing plan: run `plan` first ({path})")
    return json.loads(path.read_text())


# --------------------------------------------------------------------------------------
# Output writing
# --------------------------------------------------------------------------------------


def safetensors_header(entries: dict[str, dict[str, Any]]) -> bytes:
    """Build a safetensors header whose data offsets are relative to the data section."""
    payload = json.dumps(entries, separators=(",", ":")).encode("utf-8")
    pad = (-(8 + len(payload))) % 8
    return len(payload + b" " * pad).to_bytes(8, "little") + payload + b" " * pad


def _source_slice(fd: int, data_start: int, begin: int, end: int) -> bytes:
    return os.pread(fd, end - begin, data_start + begin)


def _convert_tensor(task: dict[str, Any], src_path: str, out_path: str) -> dict[str, Any]:
    src_fd = os.open(src_path, os.O_RDONLY)
    out_fd = os.open(out_path, os.O_WRONLY)
    try:
        raw = _source_slice(src_fd, task["data_start"], task["begin"], task["end"])
        src_sha = hashlib.sha256(raw).hexdigest()
        if task["role"] == "preserved":
            payload = raw
        else:
            source = np.frombuffer(raw, dtype=np.uint8).reshape(task["shape"])
            scale_task = task["scale"]
            scale_raw = _source_slice(
                src_fd, scale_task["data_start"], scale_task["begin"], scale_task["end"]
            )
            scales = np.frombuffer(scale_raw, dtype=np.uint8).reshape(scale_task["shape"])
            weights = decode_mxfp4(source, scales)
            type_name = task["ggml_type"]
            # IQ2_XXS requires a non-null importance vector; unit weights are the
            # unweighted reference path and carry no calibration information.
            importance = np.ones(weights.shape[1], dtype=np.float32)
            payload = _WORKER["ggml"].quantize(weights, type_name, importance).tobytes()
        if len(payload) != task["out_bytes"]:
            raise RuntimeError(
                f"{task['name']}: produced {len(payload)} bytes, expected {task['out_bytes']}"
            )
        os.pwrite(out_fd, payload, task["file_offset"])
    finally:
        os.close(src_fd)
        os.close(out_fd)
    return {
        "name": task["name"],
        "source_bytes": len(raw),
        "source_sha256": src_sha,
        "output_bytes": len(payload),
        "output_sha256": hashlib.sha256(payload).hexdigest(),
    }


def _convert_worker_init(lib_paths: tuple[str, ...], importance_mode: str) -> None:
    _worker_init(lib_paths)
    _WORKER["importance"] = {}
    if importance_mode == "unit":
        return
    raise ValueError(f"unsupported importance mode {importance_mode}")


def _pool_context():
    """Prefer fork so workers inherit the loaded ggml library and open file handles."""
    methods = mp.get_all_start_methods()
    return mp.get_context("fork" if "fork" in methods else methods[0])


def convert_shard(
    plan: dict[str, Any],
    shard: dict[str, Any],
    source: Path,
    out_dir: Path,
    lib_paths: tuple[str, ...],
    jobs: int,
    importance_mode: str,
) -> dict[str, Any]:
    output = out_dir / shard["output_shard"]
    members = shard["tensors"]
    scale_map = {t["name"][: -len(".scale")]: t for t in plan["dropped"]}

    tasks = []
    for tensor in members:
        task = dict(tensor)
        if tensor["role"] == "quantised":
            key = tensor["name"][: -len(".weight")]
            scale = scale_map.get(key)
            if scale is None:
                raise RuntimeError(f"{tensor['name']}: no matching MXFP4 scale tensor")
            task["scale"] = scale
        tasks.append(task)

    header_entries: dict[str, dict[str, Any]] = {}
    for tensor in members:
        header_entries[tensor["name"]] = {
            "dtype": tensor["out_dtype"],
            "shape": list(tensor["out_shape"]),
            "data_offsets": [tensor["out_offset"], tensor["out_offset"] + tensor["out_bytes"]],
        }
    blob = safetensors_header(header_entries)
    data_start = len(blob)
    total = data_start + shard["data_bytes"]

    src_path = str(source / shard["source_shard"])
    out_fd = os.open(output, os.O_RDWR | os.O_CREAT | os.O_TRUNC, 0o644)
    try:
        os.pwrite(out_fd, blob, 0)
        os.ftruncate(out_fd, total)
        for task in tasks:
            task["file_offset"] = data_start + task["out_offset"]
        results = []
        if jobs <= 1:
            _convert_worker_init(lib_paths, importance_mode)
            for task in tasks:
                results.append(_convert_tensor(task, src_path, str(output)))
        else:
            with ProcessPoolExecutor(
                max_workers=jobs,
                mp_context=_pool_context(),
                initializer=_convert_worker_init,
                initargs=(lib_paths, importance_mode),
            ) as pool:
                futures = [
                    pool.submit(_convert_tensor, task, src_path, str(output)) for task in tasks
                ]
                for future in futures:
                    results.append(future.result())
        os.fsync(out_fd)
    finally:
        os.close(out_fd)

    manifest = {
        "output_shard": shard["output_shard"],
        "source_shard": shard["source_shard"],
        "source_revision": plan["source_revision"],
        "recipe": plan["recipe"],
        "importance": plan["importance"],
        "data_bytes": shard["data_bytes"],
        "file_bytes": total,
        "tensors": results,
    }
    (out_dir / (shard["output_shard"] + ".manifest.json")).write_text(
        json.dumps(manifest, indent=1) + "\n"
    )
    (out_dir / (shard["output_shard"] + ".complete")).write_text(
        f"{shard['source_shard']} {total} {len(members)}\n"
    )
    return manifest


# --------------------------------------------------------------------------------------
# Verification
# --------------------------------------------------------------------------------------


def verify(out_dir: Path, sample: int, rng: np.random.Generator) -> list[str]:
    problems: list[str] = []
    manifests = sorted(out_dir.glob("quant-*.safetensors.manifest.json"))
    if not manifests:
        return [f"no manifests in {out_dir}"]
    for path in manifests:
        manifest = json.loads(path.read_text())
        shard = out_dir / manifest["output_shard"]
        header, data_start = read_safetensors_header(shard)
        if os.path.getsize(shard) != manifest["file_bytes"]:
            problems.append(f"{shard.name}: size mismatch")
        entries = [t for t in manifest["tensors"]]
        picks = (
            range(len(entries))
            if sample <= 0
            else rng.choice(len(entries), size=min(sample, len(entries)), replace=False)
        )
        with open(shard, "rb") as fh:
            for index in picks:
                entry = entries[int(index)]
                info = header[entry["name"]]
                begin, end = info["data_offsets"]
                if end - begin != entry["output_bytes"]:
                    problems.append(f"{shard.name}:{entry['name']}: header size mismatch")
                    continue
                fh.seek(data_start + begin)
                digest = hashlib.sha256(fh.read(end - begin)).hexdigest()
                if digest != entry["output_sha256"]:
                    problems.append(f"{shard.name}:{entry['name']}: digest mismatch")
        if len(header) != len(entries):
            problems.append(
                f"{shard.name}: header has {len(header)} tensors, manifest {len(entries)}"
            )
    return problems


# --------------------------------------------------------------------------------------
# CLI
# --------------------------------------------------------------------------------------


def lib_paths_from_args(args) -> tuple[str, ...]:
    if args.ggml_lib:
        return tuple(args.ggml_lib)
    return ()


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    sub = parser.add_subparsers(dest="command", required=True)

    p_plan = sub.add_parser("plan", help="build the tensor plan")
    p_plan.add_argument("--source", type=Path, required=True)
    p_plan.add_argument("--out", type=Path, required=True)
    p_plan.add_argument("--w1", default=DEFAULT_RECIPE["w1"])
    p_plan.add_argument("--w2", default=DEFAULT_RECIPE["w2"])
    p_plan.add_argument("--w3", default=DEFAULT_RECIPE["w3"])

    p_conv = sub.add_parser("convert", help="write the quantised checkpoint")
    p_conv.add_argument("--source", type=Path, required=True)
    p_conv.add_argument("--out", type=Path, required=True)
    p_conv.add_argument("--jobs", type=int, default=max(1, (os.cpu_count() or 8) - 2))
    p_conv.add_argument(
        "--ggml-lib",
        action="append",
        default=[],
        help="ggml shared library (repeat; load order matters)",
    )
    p_conv.add_argument(
        "--only-shard",
        action="append",
        default=[],
        help="source shard name, e.g. model-00009-of-00048.safetensors",
    )
    p_conv.add_argument("--importance", default="unit", choices=["unit"])
    p_conv.add_argument("--resume", action="store_true", help="skip shards with a .complete marker")
    p_conv.add_argument("--dry-run", action="store_true")

    p_ver = sub.add_parser("verify", help="re-check output shards")
    p_ver.add_argument("--out", type=Path, required=True)
    p_ver.add_argument("--sample", type=int, default=8, help="tensors hashed per shard (0 = all)")
    p_ver.add_argument("--seed", type=int, default=20260910)

    args = parser.parse_args(argv)

    if args.command == "plan":
        plan = build_plan(args.source, {"w1": args.w1, "w2": args.w2, "w3": args.w3})
        args.out.mkdir(parents=True, exist_ok=True)
        plan_path(args.out).write_text(json.dumps(plan, indent=1) + "\n")
        print(json.dumps(plan["totals"], indent=1))
        return 0

    if args.command == "convert":
        plan = load_plan(args.out)
        if args.dry_run:
            print(json.dumps(plan["totals"], indent=1))
            return 0
        shards = plan["shards"]
        if args.only_shard:
            wanted = set(args.only_shard)
            shards = [s for s in shards if s["source_shard"] in wanted]
            if not shards:
                raise SystemExit("no matching shards")
        for shard in shards:
            marker = args.out / (shard["output_shard"] + ".complete")
            if args.resume and marker.exists():
                print(f"skip {shard['output_shard']}", flush=True)
                continue
            manifest = convert_shard(
                plan,
                shard,
                args.source,
                args.out,
                lib_paths_from_args(args),
                args.jobs,
                args.importance,
            )
            print(
                f"{manifest['output_shard']} <- {manifest['source_shard']}: "
                f"{len(manifest['tensors'])} tensors, {manifest['file_bytes'] / 1e9:.2f} GB",
                flush=True,
            )
        return 0

    if args.command == "verify":
        problems = verify(args.out, args.sample, np.random.default_rng(args.seed))
        for problem in problems:
            print("FAIL", problem)
        print("verify: OK" if not problems else f"verify: {len(problems)} problems")
        return 1 if problems else 0

    return 2


if __name__ == "__main__":
    sys.exit(main())