Skip to content

Commit 059bf5f

Browse files
justinchubyCopilot
andauthored
Stream sharded safetensors export + resumable full-checkpoint preflight (#576)
## Motivation Exporting an official full-size sharded checkpoint (e.g. `zai-org/GLM-5.2` — 753.3B params BF16, **1.507 TB across 282 shards**) with the current eager loader concatenates every shard into one in-RAM `state_dict`. Measured peak host RAM for that path is ~1.5–1.9 TB, which **exceeds available RAM on a 1.7 TB box and OOMs**. There is also no way to know the disk/RAM/VRAM budget before committing to a hundreds-of-GB download. This lands the generic, model-agnostic code to (a) stream a sharded checkpoint to ONNX external data with a bounded working set, and (b) refuse a download up front when the budget is insufficient. No model-name allowlist. ## What - **`stream_safetensors_to_model()`** (`integrations/_weight_loading.py`): a pass-through lazy per-tensor loader. Each ONNX initializer is bound to an `ir.LazyTensor` that reads its tensor from the owning safetensors shard on demand (`safe_open` reads headers only), so peak RAM is bounded to one tensor, not the whole checkpoint. It **refuses** rather than mis-exporting when the source is quantized (fp8 / `*_scale_inv`) or when a graph initializer has no matching checkpoint tensor (needs fusion/split/quantization) — those must use the eager `apply_weights` path. - **`external_data_checksums()`**: deterministic sha256+size manifest for verifying byte-reproducible re-exports. - **`preflight.py` + `mobius preflight` CLI**: a resumable dry-run that validates all shard URLs/metadata from the Hub or a local dir (no success-shaped fallback), computes exact source/output disk, peak host RAM (eager vs stream) and weights VRAM (sized from the export artifact), sums download+output on a shared filesystem, checks free disk/RAM, and **refuses (exit 2)** before download when budget is insufficient, RAM can't be verified, or metadata is unavailable. Resumable JSON state refuses on commit-identity drift. The eager `apply_weights` / `_download_weights` path (incl. its pytorch + fp8 support) is unchanged. ## Proven behavior (real metadata, no download) | model | source | int4 output | peak RAM stream / eager | int4 VRAM | verdict | |---|---|---|---|---|---| | GLM-5.2 (int4-qmoe) | 1.507 TB | 0.436 TB | 10.7 GB / 1942.2 GB | 500.8 GB | READY on 8×80 GB agg; REFUSED on single 80 GB | | DeepSeek-V4 | — | — | — | — | REFUSED (404 RepositoryNotFound — data blocker) | ## Tests - `preflight_test.py` (20) + `_weight_loading_stream_test.py` (10): resolve/budget/refusal/resumability, streaming correctness + laziness, shape/missing-weight/quantized refusals, deterministic checksums. - Existing `_weight_loading_test.py` (54) unchanged. **84 pass**, `CUDA_VISIBLE_DEVICES=""`. ruff clean (line-length 95). An independent code review was run; all findings (fp8 silent mis-load, false-READY shared-fs disk double count, fp8 output under-count, download-fs mismatch, RAM-unverifiable success-shape) are fixed with tests in the second commit. > Note: this is the export/preflight plumbing. A real full GLM-5.2 run additionally requires ~1.94 TB of storage (point `HF_HOME` at a large volume), a pre-quantized int4 checkpoint (Mobius QMoE needs pre-quantized weights), and a multi-GPU/offloaded `glm_moe_dsa` runtime. Co-authored-by: Copilot <[email protected]> --------- Co-authored-by: Copilot <[email protected]>
1 parent 7003bc7 commit 059bf5f

6 files changed

Lines changed: 1670 additions & 1 deletion

File tree

‎src/mobius/__init__.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@
7272
"optimize_model",
7373
"register_ep",
7474
"registry",
75+
"stream_safetensors_to_model",
7576
"tasks",
7677
]
7778

@@ -136,7 +137,7 @@
136137
compose_adapter_deltas,
137138
fingerprint_model_weights,
138139
)
139-
from mobius.integrations._weight_loading import apply_weights
140+
from mobius.integrations._weight_loading import apply_weights, stream_safetensors_to_model
140141
from mobius.integrations.diffusers import build_diffusers_pipeline
141142
from mobius.integrations.gguf import build_from_gguf
142143
from mobius.integrations.nemo import build_from_nemo

‎src/mobius/__main__.py‎

Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -711,6 +711,88 @@ def _cmd_preflight_gguf(args: argparse.Namespace) -> None:
711711
raise SystemExit(2)
712712

713713

714+
def _probe_gpu_total_bytes() -> int | None:
715+
"""Return the largest single-GPU memory in bytes via nvidia-smi, or None."""
716+
import shutil as _shutil
717+
import subprocess
718+
719+
exe = _shutil.which("nvidia-smi")
720+
if exe is None:
721+
return None
722+
try:
723+
out = subprocess.run(
724+
[exe, "--query-gpu=memory.total", "--format=csv,noheader,nounits"],
725+
capture_output=True,
726+
text=True,
727+
timeout=15,
728+
check=True,
729+
)
730+
except (subprocess.SubprocessError, OSError):
731+
return None
732+
mibs = [int(line) for line in out.stdout.split() if line.strip().isdigit()]
733+
if not mibs:
734+
return None
735+
return max(mibs) * 1024 * 1024
736+
737+
738+
def _cmd_preflight(args: argparse.Namespace) -> None:
739+
"""Execute the 'preflight' subcommand (resumable export dry-run)."""
740+
from mobius.preflight import ExportMode, LoaderMode, run_preflight
741+
742+
gpu_total = None
743+
if args.gpu_total_bytes:
744+
gpu_total = _parse_size(args.gpu_total_bytes)
745+
elif not args.no_gpu_probe:
746+
gpu_total = _probe_gpu_total_bytes()
747+
748+
result = run_preflight(
749+
args.model_id,
750+
output_dir=args.output,
751+
revision=args.revision,
752+
download_dir=args.download_dir,
753+
export_mode=ExportMode(args.export_mode),
754+
loader=LoaderMode(args.loader),
755+
group_size=args.group_size,
756+
target_dtype_bytes=args.target_dtype_bytes,
757+
gpu_total_bytes=gpu_total,
758+
margin_frac=args.margin,
759+
state_path=args.state,
760+
)
761+
762+
if args.json:
763+
print(json.dumps(result.to_dict(), indent=2))
764+
else:
765+
b = result.budget
766+
print(f"Model: {result.model_id}")
767+
print(f"Revision: {result.revision or 'default'}")
768+
print(f"Commit: {result.commit_sha or '(local)'}")
769+
print(f"Shards: {len(result.shards)}")
770+
if b is not None:
771+
print(f"Params: {b.param_count:,} dtypes={b.dtype_bytes}")
772+
print(f"Source: {b.source_bytes / 1e12:.3f} TB (download)")
773+
print(f"Output: {b.output_bytes / 1e12:.3f} TB ({b.export_mode})")
774+
print(
775+
f"Peak RAM: {b.peak_ram_bytes / 1e9:.1f} GB ({b.loader}) "
776+
f"[eager={b.peak_ram_eager_bytes / 1e9:.1f} GB, "
777+
f"stream={b.peak_ram_stream_bytes / 1e9:.1f} GB]"
778+
)
779+
print(f"Weights VRAM: {b.vram_weights_bytes / 1e9:.1f} GB")
780+
for chk in result.checks:
781+
state = "OK " if chk.ok else "FAIL"
782+
print(
783+
f" [{state}] {chk.kind}: need {chk.required_bytes / 1e9:.1f} GB, "
784+
f"free {chk.free_bytes / 1e9:.1f} GB"
785+
)
786+
if result.blockers:
787+
print("BLOCKERS:")
788+
for blk in result.blockers:
789+
print(f" - {blk}")
790+
print(f"VERDICT: {'READY' if result.ok else 'REFUSED'}")
791+
792+
if not result.ok:
793+
raise SystemExit(2)
794+
795+
714796
def _cmd_info(args: argparse.Namespace) -> None:
715797
"""Execute the 'info' subcommand."""
716798
from mobius.integrations.diffusers._builder import (
@@ -1131,6 +1213,90 @@ def build_parser() -> argparse.ArgumentParser:
11311213
)
11321214
info_parser.set_defaults(func=_cmd_info)
11331215

1216+
# --- preflight ---
1217+
preflight_parser = subparsers.add_parser(
1218+
"preflight",
1219+
help="Dry-run an export: validate shard metadata and compute the exact "
1220+
"disk/RAM/VRAM budget, refusing before any download if it will not fit.",
1221+
)
1222+
preflight_parser.add_argument(
1223+
"model_id",
1224+
help="HuggingFace model ID or local checkpoint directory to preflight.",
1225+
)
1226+
preflight_parser.add_argument(
1227+
"--output",
1228+
"-o",
1229+
required=True,
1230+
help="Intended output directory for the exported ONNX (checked for free space).",
1231+
)
1232+
preflight_parser.add_argument(
1233+
"--revision",
1234+
default=None,
1235+
help="Model revision/branch/commit to resolve (default: main).",
1236+
)
1237+
preflight_parser.add_argument(
1238+
"--download-dir",
1239+
default=None,
1240+
help="Filesystem checked for the source-download budget. Default: the "
1241+
"Hugging Face cache (HF_HUB_CACHE), where hf_hub_download actually "
1242+
"writes shards. Set this (or HF_HOME) to a large volume to relocate the "
1243+
"download.",
1244+
)
1245+
preflight_parser.add_argument(
1246+
"--export-mode",
1247+
choices=["passthrough", "fp16", "int4-qmoe"],
1248+
default="passthrough",
1249+
help="Weight representation of the exported artifact (default: passthrough).",
1250+
)
1251+
preflight_parser.add_argument(
1252+
"--loader",
1253+
choices=["eager", "stream"],
1254+
default="stream",
1255+
help="Weight application strategy that sets the host-RAM peak.",
1256+
)
1257+
preflight_parser.add_argument(
1258+
"--group-size",
1259+
type=int,
1260+
default=32,
1261+
help="Quantization block size for int4-qmoe output sizing (default: 32).",
1262+
)
1263+
preflight_parser.add_argument(
1264+
"--target-dtype-bytes",
1265+
type=float,
1266+
default=None,
1267+
help="Bytes/param of the resident runtime weights for the VRAM estimate. "
1268+
"Default: derived from the export (int4-qmoe ~0.5, fp16/passthrough 2.0). "
1269+
"Override to model a runtime dtype that differs from the export.",
1270+
)
1271+
preflight_parser.add_argument(
1272+
"--gpu-total-bytes",
1273+
default=None,
1274+
help="Largest single-GPU memory (e.g. '80GB'); default probes nvidia-smi.",
1275+
)
1276+
preflight_parser.add_argument(
1277+
"--no-gpu-probe",
1278+
action="store_true",
1279+
help="Do not probe nvidia-smi for GPU memory.",
1280+
)
1281+
preflight_parser.add_argument(
1282+
"--margin",
1283+
type=float,
1284+
default=0.05,
1285+
help="Fractional free-space headroom required above each budget (default 0.05).",
1286+
)
1287+
preflight_parser.add_argument(
1288+
"--state",
1289+
default=None,
1290+
help="Resumable state JSON file; records validated shards and refuses on "
1291+
"checkpoint identity drift.",
1292+
)
1293+
preflight_parser.add_argument(
1294+
"--json",
1295+
action="store_true",
1296+
help="Emit the full verdict as JSON.",
1297+
)
1298+
preflight_parser.set_defaults(func=_cmd_preflight)
1299+
11341300
# --- convert-comfyui ---
11351301
comfy_parser = subparsers.add_parser(
11361302
"convert-comfyui",

0 commit comments

Comments
 (0)