Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

fp8: repack tool (Z.ai FP8 shards -> byte-preserved fmt=7 container)

monotophice621f6d26101
diff --git a/c/tests/test_fp8_repack.py b/c/tests/test_fp8_repack.py
new file mode 100644
index 00000000..283de225
--- /dev/null
+++ b/c/tests/test_fp8_repack.py
@@ -0,0 +1,210 @@
+"""tools/repack_fp8_passthrough.py: fmt=7 repack tool tests.
+
+fmt=7 is a PUBLIC ordinal, assigned by the maintainer on #524: see
+repack_fp8_passthrough.py's module docstring for the fmt=6 -> fmt=100 ->
+fmt=7 history (dev's own #465 merged a REAL fmt=6, E8/IQ3, so this tool's
+format moved to the PRIVATE ORDINAL BLOCK as fmt=100 during development
+before graduating to fmt=7 at merge).
+
+Synthetic fixtures ONLY (tools/glm_fp8_emit.py, the exact real-checkpoint FP8
+layout that convert_fp8_to_int4.py's dequant() reads) -- no real Z.ai shard is
+read or written by this suite, per the build's hard constraint. Covers:
+selection (resident kinds byte-preserved, routed experts / io / f32 excluded),
+byte-for-byte preservation of the fp8 weight and the .qs scale rename, the
+scale-geometry refusal path (THE DESIGN LANDMINE's write-side twin: a
+malformed source shard must be refused, not silently repacked into a
+container the engine's qt_resolve_fmt would then misread), --dry-run writing
+nothing, and the #383-class resume/params-guard behavior.
+"""
+import glob, json, os, struct, sys, tempfile, unittest
+
+try:
+ import torch
+ from safetensors import safe_open
+ from safetensors.torch import save_file
+except ImportError as e:
+ raise unittest.SkipTest(f"torch/safetensors not installed: {e}")
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "tools"))
+from glm_fp8_emit import save_fp8_safetensors
+import repack_fp8_passthrough as rp
+
+
+def _read_header(path):
+ with open(path, "rb") as f:
+ hlen = struct.unpack("<Q", f.read(8))[0]
+ return json.loads(f.read(hlen))
+
+
+def _make_fixture(path, D=256, I_=384, E=4):
+ """One synthetic shard covering every selection case: SELECTED resident
+ kinds (attn/o/sh/dmlp), the EXCLUDED resident kind kvb (kv_b_proj -- valid
+ per convert_fp8_to_int4.classify(), but the engine's CPU/CUDA MLA-absorb
+ paths have no fmt=7 case yet, so this tool must not select it -- see the
+ module docstring), routed experts (must be excluded), the router and a
+ norm (f32-kept, never fp8), and embed_tokens (io kind -- excluded by kind
+ even though glm_fp8_emit's simpler keep_f32() happens to FP8-quantize it,
+ since it doesn't know the full classify() taxonomy; that mismatch is
+ itself a useful case: is_repack_target must exclude by KIND, not by
+ guessing at source dtype conventions)."""
+ torch.manual_seed(0)
+ sd = {
+ "model.layers.0.self_attn.o_proj.weight": torch.randn(D, D) * 0.02,
+ "model.layers.0.self_attn.q_a_proj.weight": torch.randn(D, D) * 0.02,
+ "model.layers.0.self_attn.kv_b_proj.weight": torch.randn(D, D) * 0.02,
+ "model.layers.0.mlp.shared_experts.gate_proj.weight": torch.randn(D, I_) * 0.02,
+ "model.layers.0.mlp.gate_proj.weight": torch.randn(D, I_) * 0.02, # dmlp
+ "model.layers.0.mlp.experts.0.gate_proj.weight": torch.randn(I_, D) * 0.02, # routed: EXCLUDE
+ "model.layers.0.mlp.experts.1.up_proj.weight": torch.randn(I_, D) * 0.02, # routed: EXCLUDE
+ "model.layers.0.input_layernorm.weight": torch.randn(D), # f32: EXCLUDE
+ "model.layers.0.mlp.gate.weight": torch.randn(E, D), # router f32: EXCLUDE
+ "model.embed_tokens.weight": torch.randn(64, D), # io: EXCLUDE
+ }
+ n_fp8, n_tot = save_fp8_safetensors(sd, path)
+ return sd, n_fp8, n_tot
+
+
+class SelectionTest(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.indir = os.path.join(self.tmp.name, "fp8src")
+ os.makedirs(self.indir)
+ self.shard = os.path.join(self.indir, "model-00001-of-00001.safetensors")
+ self.sd, self.n_fp8, self.n_tot = _make_fixture(self.shard)
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ def test_dry_run_selection_and_no_writes(self):
+ inv = rp.shard_inventory(self.shard, n_layers=5)
+ names = {it["name"] for it in inv}
+ self.assertEqual(names, {
+ "model.layers.0.self_attn.o_proj.weight",
+ "model.layers.0.self_attn.q_a_proj.weight",
+ "model.layers.0.mlp.shared_experts.gate_proj.weight",
+ "model.layers.0.mlp.gate_proj.weight",
+ })
+ kinds = {it["name"]: it["kind"] for it in inv}
+ self.assertEqual(kinds["model.layers.0.self_attn.o_proj.weight"], "o")
+ self.assertEqual(kinds["model.layers.0.self_attn.q_a_proj.weight"], "attn")
+ self.assertEqual(kinds["model.layers.0.mlp.shared_experts.gate_proj.weight"], "sh")
+ self.assertEqual(kinds["model.layers.0.mlp.gate_proj.weight"], "dmlp")
+ # --dry-run through the CLI must not create the outdir at all
+ outdir = os.path.join(self.tmp.name, "out_dry")
+ rc = os.system(
+ f'{sys.executable} "{os.path.join(os.path.dirname(__file__), "..", "tools", "repack_fp8_passthrough.py")}" '
+ f'--indir "{self.indir}" --outdir "{outdir}" --n-layers 5 --dry-run')
+ self.assertEqual(rc, 0)
+ self.assertFalse(os.path.exists(outdir), "--dry-run must not write anything")
+
+ def test_routed_experts_excluded(self):
+ inv = rp.shard_inventory(self.shard, n_layers=5)
+ names = {it["name"] for it in inv}
+ self.assertNotIn("model.layers.0.mlp.experts.0.gate_proj.weight", names)
+ self.assertNotIn("model.layers.0.mlp.experts.1.up_proj.weight", names)
+
+ def test_kv_b_proj_excluded(self):
+ """Regression guard for a gap found in self-review: kv_b_proj is a valid
+ resident kind per classify(), but colibri.c's CPU absorb path
+ (qt_addrow/qt_matvec_rows) and the CUDA absorb kernels have no fmt=7
+ case -- selecting it here would produce a container the engine
+ silently misreads as int2. Must stay excluded until that path gains
+ fmt=7 support (separate follow-up work)."""
+ inv = rp.shard_inventory(self.shard, n_layers=5)
+ names = {it["name"] for it in inv}
+ self.assertNotIn("model.layers.0.self_attn.kv_b_proj.weight", names)
+ self.assertNotIn("kvb", rp.RESIDENT_KINDS)
+
+ def test_io_and_f32_excluded(self):
+ inv = rp.shard_inventory(self.shard, n_layers=5)
+ names = {it["name"] for it in inv}
+ self.assertNotIn("model.embed_tokens.weight", names) # io kind
+ self.assertNotIn("model.layers.0.input_layernorm.weight", names) # f32 (also not FP8 dtype)
+ self.assertNotIn("model.layers.0.mlp.gate.weight", names) # router, f32 kind
+
+ def test_byte_preservation_and_qs_rename(self):
+ out, inv = rp.repack_shard(self.shard, n_layers=5)
+ self.assertEqual(len(inv), 4)
+ with safe_open(self.shard, framework="pt") as f:
+ for it in inv:
+ name = it["name"]
+ w_src = f.get_tensor(name).view(torch.uint8)
+ sc_src = f.get_tensor(name + "_scale_inv").reshape(-1)
+ self.assertTrue(torch.equal(out[name], w_src), f"{name}: weight bytes not preserved")
+ self.assertEqual(out[name].dtype, torch.uint8)
+ self.assertTrue(torch.equal(out[name + ".qs"], sc_src), f"{name}: scale not preserved")
+ O, I_ = w_src.shape
+ nblkO, nblkI = (O + 127) // 128, (I_ + 127) // 128
+ self.assertEqual(out[name + ".qs"].numel(), nblkO * nblkI)
+
+ def test_geometry_refusal_on_malformed_scale(self):
+ """A shard whose _scale_inv shape doesn't match ceil(O/128)xceil(I/128) for
+ its weight must be REFUSED (write-side twin of qt_resolve_fmt's read-side
+ refusal for the same landmine) rather than silently repacked."""
+ bad_path = os.path.join(self.tmp.name, "bad.safetensors")
+ D = 300
+ w = torch.randn(D, D).to(torch.float8_e4m3fn)
+ bad_scale = torch.ones(1, 1, dtype=torch.float32) # wrong: should be [3,3] for D=300
+ # o_proj.weight is a resident "o"-kind name -> is_repack_target will select it
+ save_file({"model.layers.0.self_attn.o_proj.weight": w,
+ "model.layers.0.self_attn.o_proj.weight_scale_inv": bad_scale}, bad_path)
+ with self.assertRaises(ValueError):
+ rp.repack_shard(bad_path, n_layers=5)
+ with self.assertRaises(ValueError):
+ rp.shard_inventory(bad_path, n_layers=5)
+
+
+class ResumeAndParamsGuardTest(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.indir = os.path.join(self.tmp.name, "fp8src")
+ os.makedirs(self.indir)
+ self.shard = os.path.join(self.indir, "model-00001-of-00001.safetensors")
+ _make_fixture(self.shard)
+ self.outdir = os.path.join(self.tmp.name, "out")
+ self.tool = os.path.join(os.path.dirname(__file__), "..", "tools", "repack_fp8_passthrough.py")
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ def _run(self, n_layers):
+ return os.system(f'{sys.executable} "{self.tool}" --indir "{self.indir}" '
+ f'--outdir "{self.outdir}" --n-layers {n_layers} >/dev/null 2>&1')
+
+ def test_output_container_geometry(self):
+ self.assertEqual(self._run(5), 0)
+ outs = glob.glob(os.path.join(self.outdir, "out-fp8pass-*.safetensors"))
+ self.assertEqual(len(outs), 1)
+ hdr = _read_header(outs[0])
+ # o_proj is [256,256] -> nblkO=nblkI=2 -> 4 block scales
+ qs = hdr["model.layers.0.self_attn.o_proj.weight.qs"]
+ self.assertEqual(qs["dtype"], "F32")
+ self.assertEqual(qs["shape"], [4])
+ w = hdr["model.layers.0.self_attn.o_proj.weight"]
+ self.assertEqual(w["dtype"], "U8")
+ self.assertEqual(w["shape"], [256, 256])
+ # experts / io / f32 / kv_b_proj must be absent from the output container entirely
+ self.assertNotIn("model.layers.0.mlp.experts.0.gate_proj.weight", hdr)
+ self.assertNotIn("model.embed_tokens.weight", hdr)
+ self.assertNotIn("model.layers.0.input_layernorm.weight", hdr)
+ self.assertNotIn("model.layers.0.self_attn.kv_b_proj.weight", hdr)
+
+ def test_resume_skips_completed_shard(self):
+ self.assertEqual(self._run(5), 0)
+ mtime1 = os.path.getmtime(glob.glob(os.path.join(self.outdir, "out-fp8pass-*.safetensors"))[0])
+ self.assertEqual(self._run(5), 0) # rerun, same params
+ outs = glob.glob(os.path.join(self.outdir, "out-fp8pass-*.safetensors"))
+ self.assertEqual(len(outs), 1, "resume must not duplicate output shards")
+ self.assertEqual(os.path.getmtime(outs[0]), mtime1, "resume must not rewrite a completed shard")
+
+ def test_params_mismatch_refused(self):
+ self.assertEqual(self._run(5), 0)
+ rc = self._run(78) # different n_layers, same outdir
+ self.assertNotEqual(rc, 0, "a params mismatch on the same outdir must be refused")
+ # and the FIRST run's output must be untouched by the refused second run
+ outs = glob.glob(os.path.join(self.outdir, "out-fp8pass-*.safetensors"))
+ self.assertEqual(len(outs), 1)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/c/tools/README.md b/c/tools/README.md
index 20937885..b058556f 100644
--- a/c/tools/README.md
+++ b/c/tools/README.md
@@ -4,6 +4,8 @@ These scripts support model preparation and offline engineering work. They are
not runtime dependencies of the C engine.
- `convert_fp8_to_int4.py`, `download_glm52.py`: model preparation
+- `repack_fp8_passthrough.py`: fmt=7 repack (byte-preserved FP8, resident kinds only;
+ see the module docstring -- synthetic-fixture-tested only, no real-shard runs yet)
- `make_glm_oracle.py`, `make_glm_bench_model.py`: deterministic fixtures
- `benchmark_cuda_fixture.py`, `eval_glm.py`, `fetch_benchmarks.py`: benchmarks
- `gen_unicode.py`: tokenizer table generation
diff --git a/c/tools/repack_fp8_passthrough.py b/c/tools/repack_fp8_passthrough.py
new file mode 100644
index 00000000..6a1a3e0d
--- /dev/null
+++ b/c/tools/repack_fp8_passthrough.py
@@ -0,0 +1,272 @@
+"""fmt=7 repack tool: Z.ai GLM-5.2-FP8 shards -> the engine's native-FP8-passthrough
+container (byte-preserved, no dequant/requant).
+
+fmt=7 is a PUBLIC ordinal, assigned by the maintainer on #524. This tool's
+output format was minted fmt=6 during this branch's original development,
+before dev's own #465 (E8/IQ3) claimed that ordinal upstream and merged it
+into dev as a REAL fmt=6 (colibri.c's qt_resolve_fmt, quant.h's E8
+constants); re-tagged fmt=100 (PRIVATE ORDINAL BLOCK, see colibri.c's QT
+struct comment) from that point forward -- this tool has never emitted a
+container claiming ordinal 6 -- and graduated to fmt=7 at merge.
+
+Unlike convert_fp8_to_int4.py (which DEQUANTIZES fp8 -> f32 -> REQUANTIZES to a
+different, lossy format), this tool copies the fp8 weight bytes AS-IS and only
+renames/reshapes the scale sidecar to the engine's `.qs` convention. Same 8
+bits/weight streaming cost as the source, zero additional quantization loss.
+
+THE DESIGN LANDMINE (see qt_resolve_fmt in colibri.c, c/quant.h's E4M3_LUT
+comment): the engine tells fmt=7 (this tool's output) apart from fmt=1 (plain
+int8) ONLY by scale-array geometry -- per-row for fmt=1, per-128x128-block for
+fmt=7. This tool must therefore emit .qs sidecars whose byte count is EXACTLY
+ceil(O/128)*ceil(I/128)*4, never anything that could coincide with O*4 by
+accident for the shapes it targets (see _check_geometry below, which refuses
+rather than silently emitting a container the engine might misread). At I=98
+specifically, a single-block fp8 tensor's raw weight-byte count ALSO coincides
+with a genuine fmt=6 (E8/IQ3) tensor's -- see qt_resolve_fmt's "SECOND DESIGN
+LANDMINE" comment; this tool does not target I=98 shapes in practice (Z.ai's
+real projections don't land there), but the engine's read-side refusal covers
+it regardless.
+
+SCALE ENCODING: this tool always emits f32 block scales (4 bytes/block, the
+`.to(torch.float32)` below) -- the ENCODING this build implements. It never
+reads or emits a UE8M0 (1 byte/block) sidecar: Z.ai's GLM-5.2-FP8 checkpoints
+ship f32 `weight_scale_inv`, so there is no source data this tool would need
+to convert from. A DeepSeek-V4-shaped source (same weight geometry, UE8M0
+scales) is out of scope for this tool as written; the read side (qt_resolve_fmt)
+recognizes and refuses that byte signature by name rather than misread it,
+should a container carrying it ever reach the engine some other way.
+
+SELECTED kinds only: "resident" tensors (shared expert, o_proj, other
+attention projections, dense-MLP first layers, and the generic resident
+fallback) -- routed experts (kind "x" in convert_fp8_to_int4.classify) are
+EXCLUDED and stay on the existing int4-g64 streaming path; routers/norms/bias
+(kind "f32") and embed/lm_head (kind "io", BF16 in source, never FP8) are
+untouched by this tool -- carrying those into a mixed fmt=7+int4 loadout
+directory is separate, deferred "loadout index-rewrite blending" work.
+
+kv_b_proj (kind "kvb") is ALSO deliberately excluded, despite being a resident
+tensor classify() would otherwise select: colibri.c's MLA-absorption CPU path
+(qt_addrow/qt_matvec_rows, called only on l->kv_b -- the always-available
+fallback whenever the Metal fused decode kernel isn't used) has no fmt==7
+case and would silently misread fp8 bytes as int2-packed data; the CUDA
+absorb kernels (coli_cuda_attention_absorb/_kvdev in backend_cuda.cu) are
+similarly int4-specific. Repacking kv_b_proj to fmt=7 needs that CPU+CUDA
+absorb-path work first -- out of scope for this build, so this tool refuses
+to produce a container the engine cannot safely read.
+
+This tool does NOT write a container metadata stamp: __metadata__-based
+self-description (writer + qt_verify_fmt_stamp reader + docs/FORMATS.md
+registry) is a separate, follow-up PR, per the maintainer's #524 scoping.
+This PR's collision/refusal logic (qt_resolve_fmt) therefore refuses
+UNCONDITIONALLY at every ambiguous shape this tool could produce -- there is
+no stamp to break a tie.
+
+HARD CONSTRAINT for this build: unit-tested on synthetic fixtures ONLY (see
+tests/test_fp8_repack.py, built with tools/glm_fp8_emit.py's exact real-
+checkpoint layout) plus --dry-run inventory mode against those same fixtures.
+NO read of any real Z.ai shard, NO full or partial repack of a real checkpoint
+-- that is later, user-GO'd work once this build's plumbing has been reviewed.
+
+Usage (synthetic fixtures / local testing only):
+ python3 tools/repack_fp8_passthrough.py --indir <fp8_dir> --outdir <out> --dry-run
+ python3 tools/repack_fp8_passthrough.py --indir <fp8_dir> --outdir <out> --n-layers 78
+"""
+import argparse, glob, json, os, sys
+
+sys.path.insert(0, os.path.dirname(__file__))
+from convert_fp8_to_int4 import classify, check_or_record_params # reuse: same taxonomy,
+ # same #383-class params guard
+
+# Kinds classify() can return that this tool targets: resident weights, NOT routed
+# experts ("x"), NOT the always-F32 set ("f32"), NOT embed/lm_head ("io" -- BF16 in
+# source, never FP8), NOT sidecars/skips ("consumed"/"skip"). "kvb" (kv_b_proj) is
+# ALSO excluded -- see the module docstring: the CPU absorb path (qt_addrow/
+# qt_matvec_rows) and the CUDA absorb kernels have no fmt=7 case yet.
+RESIDENT_KINDS = frozenset({"sh", "o", "attn", "dmlp", "q"})
+
+BLOCK = 128
+
+
+def _nblk(n):
+ return (n + BLOCK - 1) // BLOCK
+
+
+def is_repack_target(name, dtype, keys, n_layers):
+ """True if `name` is a resident-kind FP8 tensor this tool should byte-preserve
+ into the fmt=7 container. `keys` is the full set of tensor names in the shard
+ (needed to confirm the `_scale_inv` sidecar is actually present -- classify()
+ alone can't tell FP8 tensors from any other dtype a resident-kind name might
+ carry in a non-FP8 checkpoint variant)."""
+ if name.endswith("_scale_inv"):
+ return False # sidecar, handled together with its weight
+ kind = classify(name, n_layers)
+ if kind not in RESIDENT_KINDS:
+ return False
+ if dtype not in ("F8_E4M3", "float8_e4m3fn"):
+ return False
+ return (name + "_scale_inv") in keys
+
+
+def _check_geometry(name, O, I, nblkO, nblkI):
+ """Refuse (loud, ValueError) rather than silently emit a .qs whose geometry
+ doesn't match what qt_resolve_fmt expects for [O,I] -- the same "untrusted
+ container" discipline the C side applies on read, applied here on write so a
+ malformed source checkpoint is caught at repack time, not at load time three
+ steps later with a confusing engine-side refusal."""
+ exp_nblkO, exp_nblkI = _nblk(O), _nblk(I)
+ if (nblkO, nblkI) != (exp_nblkO, exp_nblkI):
+ raise ValueError(
+ f"{name}: scale_inv block shape ({nblkO},{nblkI}) != expected "
+ f"({exp_nblkO},{exp_nblkI}) for [{O},{I}] -- refusing to repack a shape "
+ f"the engine's qt_resolve_fmt would either refuse or (worse) misread")
+
+
+def shard_inventory(path, n_layers):
+ """--dry-run: scan one shard's header only (get_slice, no tensor data pulled)
+ and return the list of tensors that WOULD be repacked, without writing
+ anything. Cheap: safe to run over an entire real checkpoint's headers."""
+ from safetensors import safe_open
+ inv = []
+ with safe_open(path, framework="pt") as f:
+ keys = set(f.keys())
+ for name in f.keys():
+ sl = f.get_slice(name)
+ dt = sl.get_dtype()
+ if not is_repack_target(name, dt, keys, n_layers):
+ continue
+ O, I = sl.get_shape()
+ sc_slice = f.get_slice(name + "_scale_inv")
+ nblkO, nblkI = sc_slice.get_shape()
+ _check_geometry(name, O, I, nblkO, nblkI)
+ inv.append({"name": name, "kind": classify(name, n_layers),
+ "O": O, "I": I, "nblkO": nblkO, "nblkI": nblkI,
+ "weight_bytes": O * I, "scale_bytes": nblkO * nblkI * 4})
+ return inv
+
+
+def repack_shard(path, n_layers):
+ """Real mode: byte-preserve every selected tensor's weight bytes (raw e4m3,
+ no dequant/requant -- `.view(torch.uint8)` is a pure bit-reinterpret, verified
+ byte-identical against torch.float8_e4m3fn's own storage) and rename/flatten
+ the `_scale_inv` sidecar to the engine's `name.qs` convention (flat F32,
+ nblkO*nblkI elements, row-major [blkO,blkI] -- matching
+ scale[(o/128)*nblkI+i/128] on the read side). Returns (out_dict, inventory)."""
+ import torch
+ from safetensors import safe_open
+ out = {}
+ inv = []
+ with safe_open(path, framework="pt") as f:
+ keys = set(f.keys())
+ for name in f.keys():
+ sl = f.get_slice(name)
+ dt = sl.get_dtype()
+ if not is_repack_target(name, dt, keys, n_layers):
+ continue
+ w = f.get_tensor(name) # torch.float8_e4m3fn [O,I]
+ sc = f.get_tensor(name + "_scale_inv") # torch.float32 [nblkO,nblkI]
+ O, I = w.shape
+ nblkO, nblkI = sc.shape
+ _check_geometry(name, O, I, nblkO, nblkI)
+ out[name] = w.view(torch.uint8).contiguous() # BYTE-PRESERVED
+ out[name + ".qs"] = sc.to(torch.float32).reshape(-1).contiguous()
+ inv.append({"name": name, "kind": classify(name, n_layers),
+ "O": O, "I": I, "nblkO": nblkO, "nblkI": nblkI,
+ "weight_bytes": O * I, "scale_bytes": nblkO * nblkI * 4})
+ return out, inv
+
+
+def _print_inventory_summary(all_inv, dry_run):
+ by_kind = {}
+ tot_w = tot_s = 0
+ for it in all_inv:
+ by_kind.setdefault(it["kind"], []).append(it)
+ tot_w += it["weight_bytes"]; tot_s += it["scale_bytes"]
+ tag = "[DRY-RUN]" if dry_run else "[REPACK]"
+ print(f"{tag} {len(all_inv)} tensor(s) selected across all shards "
+ f"({tot_w/1e9:.3f} GB weights, {tot_s/1e6:.3f} MB scales)")
+ for kind in sorted(by_kind):
+ items = by_kind[kind]
+ w = sum(it["weight_bytes"] for it in items)
+ print(f"{tag} kind={kind:5s} {len(items):5d} tensor(s) {w/1e9:.3f} GB")
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--indir", required=True, help="directory of Z.ai FP8 *.safetensors shards")
+ ap.add_argument("--outdir", required=True, help="destination for repacked fmt=7 container shards")
+ ap.add_argument("--n-layers", type=int, default=78)
+ ap.add_argument("--dry-run", action="store_true",
+ help="inventory only: scan headers, print selection counts, write nothing")
+ a = ap.parse_args()
+
+ shards = sorted(glob.glob(os.path.join(a.indir, "*.safetensors")))
+ if not shards:
+ print(f"ERROR: no *.safetensors files in {a.indir}"); sys.exit(1)
+
+ if a.dry_run:
+ all_inv = []
+ for sp in shards:
+ all_inv.extend(shard_inventory(sp, a.n_layers))
+ _print_inventory_summary(all_inv, dry_run=True)
+ return
+
+ os.makedirs(a.outdir, exist_ok=True)
+ # #383-class guard, reused (not reimplemented): refuses a resumed run whose
+ # params differ from what's already partially in this outdir (the #355 failure
+ # mode -- a second pass with different flags silently mixing containers).
+ # Owns its own sidecar (.fp8pass-params.json), separate from the shard-progress
+ # manifest below, exactly like the --repo mtp/indexer loops in
+ # convert_fp8_to_int4.py use it.
+ params = {"mode": "fp8-passthrough", "n_layers": a.n_layers}
+ if not check_or_record_params(a.outdir, "fp8pass-", params):
+ sys.exit(1)
+
+ # RESUME (same #383-class manifest idiom as convert_fp8_to_int4.py's --indir path):
+ # a sidecar records input-shard -> output-shard-name-or-"" (shards with no
+ # resident-FP8 tensors emit no file), written atomically so an interrupted run
+ # never leaves a half-written manifest for the next invocation to trust. The
+ # params guard above already owns "don't mix conversions" -- this manifest is
+ # purely which shards are done.
+ prog_path = os.path.join(a.outdir, ".fp8pass-progress.json")
+ prog = {}
+ if os.path.exists(prog_path):
+ try:
+ prog = json.loads(open(prog_path).read())
+ except (OSError, ValueError):
+ prog = {}
+ done = prog.setdefault("shards", {})
+
+ from safetensors.torch import save_file
+ all_inv = []
+ n = fresh = skipped = 0
+ for sp in shards:
+ key = os.path.basename(sp)
+ prev = done.get(key)
+ if prev is not None and (prev == "" or os.path.exists(os.path.join(a.outdir, prev))):
+ if prev:
+ n += 1
+ skipped += 1
+ continue
+ out, inv = repack_shard(sp, a.n_layers)
+ all_inv.extend(inv)
+ if not out:
+ done[key] = ""
+ else:
+ name = f"out-fp8pass-{n:05d}.safetensors"
+ save_file(out, os.path.join(a.outdir, name))
+ done[key] = name
+ n += 1
+ fresh += 1
+ tmp = prog_path + ".tmp"
+ with open(tmp, "w") as fh:
+ json.dump(prog, fh, indent=1)
+ os.replace(tmp, prog_path)
+ if skipped:
+ print(f"[RESUME] {skipped} shard(s) already done in {a.outdir}, skipped")
+ print(f"[REPACK] {fresh} new output shard(s) written")
+ _print_inventory_summary(all_inv, dry_run=False)
+
+
+if __name__ == "__main__":
+ main()