Skip to content

Stream sharded safetensors export + resumable full-checkpoint preflight - #576

Merged
justinchuby merged 4 commits into
mainfrom
sebastian/export-preflight-streaming
Aug 24, 2026
Merged

justinchuby merged 4 commits into
mainfrom
sebastian/export-preflight-streaming

Conversation

@justinchuby

Copy link
Copy Markdown
Member

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]

@justinchuby
justinchuby requested review from a team and a lite review from Copilot August 24, 2026 01:54
Comment thread src/mobius/preflight.py Fixed
Comment thread src/mobius/preflight_test.py Fixed
@github-actions

github-actions Bot commented Aug 24, 2026 •

Copy link
Copy Markdown

🏗️ Architecture Diff

Comparing 7003bc7 → 115823c

Model Sub-model Changes Status

No architecture changes detected. ✅


Legend: ⚪ No change · 🔵 Minor (attrs/inits) · 🟡 Moderate (nodes added/removed) · 🔴 Major (interface changed)

@github-actions

github-actions Bot commented Aug 24, 2026 •

Copy link
Copy Markdown

Performance Comparison

Comparing 7003bc7 → 115823c

Model Metric Baseline Current Delta
bert (feature-extraction) model_size_bytes 359 KB 359 KB +0.0% ⚪
bert (feature-extraction) num_nodes 68 68 +0.0% ⚪
falcon model_size_bytes 364 KB 364 KB +0.0% ⚪
falcon num_nodes 66 66 +0.0% ⚪
gemma2 model_size_bytes 428 KB 428 KB +0.0% ⚪
gemma2 num_nodes 105 105 +0.0% ⚪
gpt2 model_size_bytes 388 KB 388 KB +0.0% ⚪
gpt2 num_nodes 54 54 +0.0% ⚪
llama model_size_bytes 425 KB 425 KB +0.0% ⚪
llama num_nodes 60 60 +0.0% ⚪
llama (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
llama (static-cache) num_nodes 56 56 +0.0% ⚪
mamba (ssm-text-generation) model_size_bytes 296 KB 296 KB +0.0% ⚪
mamba (ssm-text-generation) num_nodes 94 94 +0.0% ⚪
phi3 model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 num_nodes 58 58 +0.0% ⚪
phi3 (static-cache) model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 (static-cache) num_nodes 54 54 +0.0% ⚪
qwen2 model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 num_nodes 60 60 +0.0% ⚪
qwen2 (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 (static-cache) num_nodes 56 56 +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) model_size_bytes 506 KB 506 KB +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) num_nodes 264 264 +0.0% ⚪
qwen3_5_text (hybrid-text-generation) model_size_bytes 458 KB 458 KB +0.0% ⚪
qwen3_5_text (hybrid-text-generation) num_nodes 126 126 +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) model_size_bytes 977 KB 977 KB +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) num_nodes 428 428 +0.0% ⚪
t5 (seq2seq) model_size_bytes 836 KB 836 KB +0.0% ⚪
t5 (seq2seq) num_nodes 176 176 +0.0% ⚪
whisper (speech-to-text) model_size_bytes 1008 KB 1008 KB +0.0% ⚪
whisper (speech-to-text) num_nodes 128 128 +0.0% ⚪

No performance regressions.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds lazy sharded safetensors streaming and a resumable preflight workflow for large checkpoint exports.

Changes:

  • Adds bounded-memory streaming loading and deterministic checksums.
  • Adds disk, RAM, VRAM, metadata, and resumability checks.
  • Adds the mobius preflight CLI, public API wiring, and tests.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 15 comments.

Show a summary per file
File Summary Final findings
src/mobius/preflight.py Checkpoint resolution, budgeting, and resumable state 6 critical findings and 2 moderate findings covering fallback error handling, revision pinning, FP8 detection, metadata failures, output sizing, cache accounting, and group-size validation.
src/mobius/preflight_test.py Preflight behavior and refusal tests No final comments.
src/mobius/integrations/_weight_loading.py Lazy shard loading and checksum generation 4 critical findings covering quantization guards, scale-key detection, duplicate keys, and mutable revisions.
src/mobius/integrations/_weight_loading_stream_test.py Streaming correctness and refusal tests No final comments.
src/mobius/__main__.py Preflight CLI and GPU probing 1 critical and 2 moderate findings covering download-directory handling, CLI coverage, and aggregate GPU capacity.
src/mobius/__init__.py Public streaming-loader export No final comments.
Suppressed comments (13)

src/mobius/integrations/_weight_loading.py:565

  • pathlib does not expose the standard PathLike protocol; this annotation should use os.PathLike (as the new preflight API and existing integrations do). With source type checking enabled, the new annotation is rejected even though postponed annotations hide the problem at runtime.
    output_dir: str | pathlib.PathLike,

src/mobius/integrations/_weight_loading.py:570

  • The repository supports the older onnx_ir shard naming form model.onnx-*-of-*.data as well as the newer model-*-of-*.onnx.data form (see the existing save test), but the default pattern matches only the latter. On the older supported writer this helper returns an incomplete or empty manifest, so a reproducibility check can silently omit most or all shards. Include both default naming forms or enumerate the actual external-data files.
    pattern: str = "*.onnx.data",
    chunk_size: int = 1 << 20,
) -> dict[str, dict[str, object]]:
    """Compute a deterministic sha256 + size manifest for ONNX external data.

src/mobius/integrations/_weight_loading.py:560

  • This call is not pass-through: FoldConcatInitializersPass creates a lazy callback that calls .numpy() on every input and then np.concatenates them, holding all parts plus the packed result during serialization. Large QKV/other concats spanning shards can violate the claimed one-tensor bound and still OOM; skip this fold for streaming or make it streaming-aware.
    fold_initializers_after_weights(model)

src/mobius/integrations/_weight_loading.py:446

  • The claimed one-tensor RAM bound does not hold for the normal save path: ModelPackage.save defaults to eight external-data workers, which can invoke independent lazy closures concurrently, and the post-load fold can create lazy concat/transpose values that read multiple source tensors. For large shards this can multiply RSS beyond the preflight's 2 * largest_shard estimate. Force serial materialization or expose/account the save worker count.
    The closure re-opens the shard and reads exactly one tensor at serialization
    time, so nothing is retained between assignment and ``ir.save`` and the peak
    host RAM is bounded by the largest single tensor, not the whole checkpoint.

src/mobius/preflight.py:663

  • The default GPU probe returns the maximum memory of one device, and this comparison turns that value into a hard blocker. On the documented 8x80-GB case, a 500.8-GB weight estimate is therefore refused even though the aggregate 640 GB is sufficient; there is no input for aggregate capacity. Expose separate largest-device and aggregate capacities and apply the check according to whether the runtime supports sharding, or make the single-device result advisory.
    if gpu_total_bytes is not None and budget.vram_weights_bytes > gpu_total_bytes:
        blockers.append(
            f"weights need {_h(budget.vram_weights_bytes)} VRAM but the largest "
            f"single device has {_h(gpu_total_bytes)}; multi-GPU shard or weight "
            f"offload is required (not a single-device load)"

src/mobius/preflight.py:391

  • peak_ram_stream = 2 * largest_shard assumes serialization evaluates one LazyTensor at a time, but ModelPackage.save passes the default max_workers=8 to ir.save. Multiple stream closures can materialize several tensors and cast twins concurrently, exceeding this estimate and allowing a false READY. Include save concurrency in the budget or force serial evaluation.
    # Streaming keeps at most one shard (and its cast twin) resident.
    peak_ram_stream = 2 * largest_shard if largest_shard else source_bytes

src/mobius/preflight.py:578

  • For Hub shards, sha256 is captured but never required; a sibling with a size and no LFS SHA is treated as valid and recorded in resumable state. The documented every-shard hash/no-success-fallback contract is therefore not met, and preflight can return READY without enough metadata to validate the source. Add a hard blocker for missing SHA-256 on Hub shards.
    missing_size = [s.filename for s in shards if s.size is None and not s.present_local]
    if missing_size:
        blockers.append(
            f"{len(missing_size)} shard(s) have no size metadata "
            f"(cannot budget): {missing_size[:3]}{'...' if len(missing_size) > 3 else ''}"

src/mobius/preflight.py:177

  • External metadata counts are not validated for sign. A negative count makes param_count/dtype_bytes negative, which can produce negative FP16/int4 output and VRAM requirements and let all free-space checks pass for invalid input. Convert each count once and reject values below zero.
    for dtype, count in parameters.items():
        total_params += int(count)
        per = _DTYPE_BYTES.get(dtype.upper())
        if per is None:
            raise ValueError(

src/mobius/preflight.py:214

  • A local shard is considered valid solely by is_file()/stat; a zero-length or non-safetensors file gets size metadata and no blocker. With no index dtype data this can yield a zero/underestimated budget and READY, although safe_open will fail during export. Read and validate each local safetensors header before declaring it present.
        present = path.is_file()
        size = path.stat().st_size if present else None
        shards.append(ShardMeta(filename=filename, size=size, present_local=present))

src/mobius/preflight.py:476

  • margin_frac is accepted without range validation, and a negative value increases the effective free space (free * (1 - margin_frac)), so the CLI can report READY even when the budget does not fit. Validate the API/CLI input as 0 <= margin_frac < 1 before running disk and RAM checks.
def check_disk(
    kind: str, path: pathlib.Path, required: int, margin_frac: float
) -> SpaceCheck:
    free = _free_bytes(path)
    ok = free * (1 - margin_frac) >= required

src/mobius/preflight.py:322

  • When the dtype block is absent—which is the normal path for a local checkpoint—this guesses 16-bit from the file size. A local FP8/FP32 checkpoint therefore gets the wrong parameter count and can be under-budgeted for INT4 or passthrough output/VRAM, yet still receive READY. Read the safetensors headers to derive the dtype or refuse when it cannot be determined.
    # Without a dtype block, assume 16-bit weights (bf16/fp16) — the common case
    # for an unquantized checkpoint — and record it as an assumption.
    param_count = weight_bytes // 2 if weight_bytes else 0
    dtype_bytes = {"UNKNOWN16": weight_bytes} if weight_bytes else {}
    return param_count, dtype_bytes, source_bytes

src/mobius/preflight.py:391

  • The streaming path calls fold_initializers_after_weights, whose lazy Concat closure loads every input and then allocates the concatenated result. If q/k/v inputs are in separate shards, the peak is the sum of all inputs plus the output, not 2 * largest_shard (three 1 GB inputs can reach roughly 6 GB while this reports 2 GB). This can make the RAM gate false-READY; account for folded tensors or skip these folds for streaming.
    # Streaming keeps at most one shard (and its cast twin) resident.
    peak_ram_stream = 2 * largest_shard if largest_shard else source_bytes

src/mobius/preflight.py:346

  • This applies the int4 packed rate to every source parameter, but the repository's quantization path only packs selected linear/expert tensors; embeddings, norms, biases, and any unquantized heads remain full precision. The safetensors parameter count does not identify that split, so output_bytes and VRAM can be understated and the preflight can approve an export that later runs out of disk.
    if export_mode == ExportMode.INT4_QMOE:
        # 4-bit packed weights + fp16 scales + int4 zero points, per block.
        per = 0.5 + 2.0 / group_size + 0.5 / group_size
        return int(param_count * per)

💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/mobius/__main__.py
Comment on lines +1215 to +1218
help="Filesystem checked for the source-download budget. Default: the "
"Hugging Face cache (HF_HUB_CACHE), where hf_hub_download actually "
"writes shards. Set this (or HF_HOME) to a large volume to relocate the "
"download.",
Comment thread src/mobius/__main__.py
Comment on lines +767 to +768
if not result.ok:
raise SystemExit(2)
Comment thread src/mobius/__main__.py
Comment on lines +707 to +710
mibs = [int(line) for line in out.stdout.split() if line.strip().isdigit()]
if not mibs:
return None
return max(mibs) * 1024 * 1024
Comment on lines +505 to +524
if require_passthrough:
# An fp8 checkpoint stores raw float8 weights under the same name the
# graph expects for bf16, plus separate ``*_scale_inv``/``*_scale``
# tensors. Casting fp8 -> bf16 without multiplying by the scale silently
# produces wrong weights, and the scale keys never map to an
# initializer (so the missing-tensor guard below never fires). Refuse
# such quantized sources up front; they must use the eager
# apply_weights path, which applies the scale.
quant_signals = sorted(
k
for k, (_p, _s, dt) in key_index.items()
if dt.startswith("F8") or k.endswith(("_scale_inv", "weight_scale"))
)
if quant_signals:
raise ValueError(
f"Checkpoint appears quantized (fp8 / scaled weights, e.g. "
f"{quant_signals[:5]}); the pass-through streaming loader cannot "
f"dequantize it and would drop the weight scale. Use the eager "
f"apply_weights path (which applies weight_scale_inv)."
)
quant_signals = sorted(
k
for k, (_p, _s, dt) in key_index.items()
if dt.startswith("F8") or k.endswith(("_scale_inv", "weight_scale"))
Comment thread src/mobius/preflight.py
Comment on lines +241 to +243
index_path = hf_hub_download(
repo_id=model_id, filename=_WEIGHT_INDEX_NAME, revision=revision
)
Comment thread src/mobius/preflight.py
Comment on lines +619 to +622
already_present = sum(
int(s.size) for s in shards if s.present_local and s.size is not None
)
download_required = max(budget.source_bytes - already_present, 0)
Comment thread src/mobius/preflight.py
Comment on lines +694 to +702
def _maybe_model_info(model_id: str, revision: str | None, hf_api):
try:
if hf_api is None:
from huggingface_hub import HfApi

hf_api = HfApi()
return hf_api.model_info(model_id, revision=revision, files_metadata=False)
except Exception: # dtype breakdown is best-effort
return None
Comment thread src/mobius/preflight.py
Comment on lines +336 to +340
# on the eager path, so fp8 external data is written at 2x its stored
# width. Size fp8 params at their dequantized width to avoid a false OK
# on the output-disk check.
fp8_extra = sum(v for k, v in dtype_bytes.items() if k.startswith("F8"))
return source_bytes + fp8_extra
Comment thread src/mobius/preflight.py
Comment on lines +551 to +553
blockers: list[str] = []
output_path = pathlib.Path(output_dir)
download_path = pathlib.Path(download_dir) if download_dir else _default_download_dir()
@justinchuby

Copy link
Copy Markdown
Member Author

Independent review verdict: ✅ APPROVE FOR MERGE

Reviewed at HEAD 46f292df8e30bcd7727e09a6e221260ca9dc7a22 (base main, merge-base 89ff75f). Read-only review; independently ran tests + lint.

Verified

  • Peak-RAM bound is real. stream_safetensors_to_model binds each initializer to ir.LazyTensor(...) created without cache=True. Confirmed in installed onnx_ir 1.0.0 (_core.LazyTensor._evaluate): with cache=False the thunk is re-run per access and the result is not retained, so at serialization at most one tensor is resident. _shard_key_index reads headers only (get_slice(...).get_shape()/get_dtype()), never a body. test_assignment_is_deferred_not_materialized locks the laziness in.
  • Refusals over silent mis-export. fp8/*_scale_inv sources are refused (would drop the weight scale), and a graph initializer with no checkpoint tensor is refused in pass-through mode — both covered by tests. Weight tying stays on the eager apply_weights path (data_ptr() sharing), unchanged.
  • Preflight is metadata-only and refuses before payload. Only model_info + the small *.index.json are read; no shard is downloaded. Identity-drift refusal, RAM-unverifiable refusal (no success-shaped pass), and the shared-filesystem download+output sum are all correct and tested. Access errors (401/404) surface generically as metadata unavailable blockers — no hardcoded/stale model blocker (the DeepSeek-V4 404 in the PR body is a runtime data observation, not code).
  • Disk target is honest. Download is budgeted against the real HF cache filesystem (HF_HUB_CACHE, overridable via --download-dir/HF_HOME) — no root-only /mnt assumption.
  • Determinism. external_data_checksums is sorted + sha256/size; test_checksums_are_deterministic_across_exports proves byte-reproducibility.

Independent test/lint run (venv, CUDA_VISIBLE_DEVICES="")

  • preflight_test.py + _weight_loading_stream_test.py: 29 passed
  • existing _weight_loading_test.py: 55 passed (no regression)
  • ruff check on all changed files: clean

Merge/rebase ordering

No blocking issues found. Approve after the rebase.

Reviewed independently; not the PR author. Do not auto-merge.

justinchuby and others added 3 commits August 24, 2026 09:39
Move the full-checkpoint export path off the eager whole-checkpoint
load and add a dry-run that gates large downloads before they start.

Motivation: exporting an official full-size checkpoint (e.g. GLM-5.2,
753.3B params BF16 / 1.507 TB across 282 shards) with the existing
eager `_download_weights` concatenates every shard into one in-RAM
state_dict. Measured peak host RAM for that path is ~1.507 TB, which
exceeds available RAM on a 1.7 TB box and OOMs. It also offers no way
to know the disk/RAM/VRAM budget before committing to the download.

Changes:
- preflight.py: resumable export preflight. Validates shard
  metadata/index 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 budgets, checks free disk (shutil) and
  RAM (/proc/meminfo MemAvailable), and refuses (exit 2) with
  structured blockers when budget is insufficient or metadata is
  unavailable. Resumable JSON state refuses on commit-identity drift.
- integrations/_weight_loading.py: add stream_safetensors_to_model(),
  a pass-through lazy per-tensor loader that binds each ONNX
  initializer to a safetensors slice via ir.LazyTensor and reads
  shard headers only (safe_open) so peak RAM is bounded to one tensor.
  It refuses graphs that need fusion/split/quantization instead of
  silently mis-exporting. Add external_data_checksums() for a
  deterministic sha256+size manifest. Refactor shard-path resolution
  into _resolve_shard_paths() (behavior-preserving).
- __main__.py: wire a read-only `preflight` subcommand.
- __init__.py: export stream_safetensors_to_model.

Tests: preflight_test.py (15) and _weight_loading_stream_test.py (8)
cover resolve/budget/refusal/resumability and streaming correctness,
laziness, shape/missing-weight refusals, and deterministic checksums.
Existing _weight_loading_test.py (53) still passes (76 total).

Co-authored-by: Copilot <[email protected]>
Independent code review found four correctness issues; all are fixed
with tests.

- Streaming loader silently mis-loaded fp8 checkpoints (High):
  a pass-through cast fp8 -> bf16 dropped weight_scale_inv and the
  scale keys never matched an initializer, so no refusal fired.
  stream_safetensors_to_model now detects fp8 dtypes and
  *_scale_inv/*_scale keys and refuses, directing quantized sources to
  the eager apply_weights path. (+2 tests)

- Disk budget false READY on a shared filesystem (High): the source
  download and ONNX output were checked independently against the same
  free space, hiding a combined shortfall. When download and output
  resolve to the same device the requirement is now summed and checked
  once (disk:download+output). (+1 test)

- Passthrough output under-counted fp8 by ~2x (Medium): a passthrough
  export dequantizes fp8 to bf16, so estimate_output_bytes now sizes
  fp8 params at their 2-byte dequantized width. (+1 test)

- Download budget checked the wrong filesystem (Medium): hf_hub_download
  writes to the HF cache, not the output dir. The download check now
  defaults to HF_HUB_CACHE (override with --download-dir / HF_HOME).

- check_ram no longer returns a success-shaped pass when
  /proc/meminfo:MemAvailable can't be read; an unverifiable RAM budget
  is now a blocker. (+1 test)

Targeted suite: 81 passed (was 76). ruff clean.

Co-authored-by: Copilot <[email protected]>
Real-run validation on GLM-5.2 surfaced a misleading VRAM number: an
int4-qmoe preflight reported 1.7 TB of weights VRAM because the estimate
used the default target_dtype_bytes=2.0 (the bf16 source) instead of the
int4 export footprint. The weights loaded at runtime are the weights that
were exported, so estimate_budget now defaults the VRAM footprint to the
exported artifact size (output_bytes): int4-qmoe ~0.5 B/param, fp16/
passthrough 2.0 B/param. An explicit --target-dtype-bytes still overrides
it to model a runtime dtype that differs from the export.

Effect on GLM-5.2 int4-qmoe: weights VRAM 500.8 GB (was 1732.7 GB),
which fits an 8x A100-80GB aggregate (687 GB) -> READY, while a single
80 GB device still correctly REFUSES.

Co-authored-by: Copilot <[email protected]>
@justinchuby
justinchuby force-pushed the sebastian/export-preflight-streaming branch from 46f292d to e452dab Compare August 24, 2026 09:49
The CI Lint job runs lintrunner with two linters: RUFF (ruff check) and
RUFF-FORMAT (ruff format --check). Only ruff check was run previously, so
three long dict/call literals in the preflight modules and streaming test
were left un-wrapped past the 95-column formatter width. Wrap them via
`ruff format` (ruff 0.16.2, --config=pyproject.toml). Pure formatting; no
behavior change. The rebase-touched __main__.py was already format-clean.

Co-authored-by: Copilot <[email protected]>
@justinchuby

Copy link
Copy Markdown
Member Author

Re-review after rebase + lint fix: ✅ APPROVE FOR MERGE

Re-reviewed at HEAD 115823c0762ad86988846bbd3deb8a10731aa85e (read-only). Prior approval was at 46f292df, before the #581 reconciliation. This confirms the rebase/lint changes are safe and every original invariant still holds.

Rebase is clean and onto the right base

CLI composes with #581 exactly once (the #578 collision does NOT occur here)

Original invariants intact (verified byte-for-byte)

git diff --ignore-all-space 46f292d..115823c shows:

  • _weight_loading.py and __init__.py: zero non-whitespace change. Streaming stays a pass-through ir.LazyTensor with no cache= kwarg (defaults False) → peak RAM bounded to one tensor; _shard_key_index header-only reads; fp8/*_scale_inv refusal; data_ptr() weight tying; deterministic external_data_checksums — all unchanged.
  • preflight.py, preflight_test.py, _weight_loading_stream_test.py: only ruff line-wrap reflows, no logic change. Metadata-only preflight (only model_info + *.index.json, no shard download), anonymous access (HfApi()/hf_hub_download with no forced token), identity-drift/RAM-unverifiable refusals, and shared-fs disk sum are unchanged.
  • No hardcoded /mnt and no static 401/404/RepositoryNotFound blocker — download budget still targets the configurable HF cache (HF_HUB_CACHE/--download-dir), and access errors still surface as generic metadata unavailable blockers.

Exact local lint + tests (isolated worktree, CUDA_VISIBLE_DEVICES="")

  • RUFF (ruff check --config=pyproject.toml): All checks passed!
  • RUFF-FORMAT (ruff format --check): 6 files already formatted
  • preflight_test.py + _weight_loading_stream_test.py: 29 passed
  • integrations/_weight_loading_test.py: 55 passed

No blocking issues. The rebase/lint changes are cosmetic + a clean #581 integration; the streaming and preflight semantics are identical to the previously-approved revision. Approve.

Re-reviewed independently; not the PR author. Do not auto-merge.

@justinchuby
justinchuby merged commit 059bf5f into main Aug 24, 2026
24 checks passed
@justinchuby
justinchuby deleted the sebastian/export-preflight-streaming branch August 24, 2026 10:44
justinchuby added a commit that referenced this pull request Aug 24, 2026
PR #578 was cut against #576 before #581 ("Direct multi-shard GGUF import")
merged into main as 7003bc7. #581 already ships a `preflight-gguf` CLI and the
`mobius.integrations.gguf._preflight` library, so the standalone
`mobius.preflight_gguf` module + second `preflight-gguf` subparser collided with
it (argparse `conflicting subparser` on Python 3.12, breaking the whole CLI) and
re-implemented parallel logic. Per the review, fold the genuinely-additive value
into #581's `_preflight.py` and delete the parallel implementation.

Folded in (reusing #581's GgufShardSet/GGUFModel header reader, metadata-only):
- Block-preserving, lossless-only per-tensor-type classification against the
  *real* repacker (`native_block_spec` / `repack_quant_params`) plus float
  passthrough — no model-name allowlist. Dispositions: passthrough /
  native-preserve / repack / unsupported.
- Real-artifact budget: ONNX external-data output estimate and a weights-only
  VRAM figure derived from the export artifact. Direct random-access shard
  reads, so there is NO merged second-copy budget.
- A blocker listing the *exact* unsupported native qtypes (e.g. Q5_K/Q2_K/Q3_K),
  which — with #581's sparse-MoE fusion gate — are the real remaining code gaps,
  never architecture or sharding.

Removed (net-new, now-invalid blockers): the hardcoded `split.count > 1` refusal
(GgufShardSet imports sharded sets directly), the `merged_input_bytes`
double-copy disk budget, and the `/mnt` staging recommendation. No static
DeepSeek 401/404 blocker, no bandwidth/tok-s inference, no payload download.

Tests: supported sharded set clears shard+arch gates; dispositions match the
real repacker; exact unsupported qtype is the only blocker; budget carries no
second-copy and VRAM derives from the artifact; exactly one `preflight-gguf` CLI
registration (parser builds on 3.12) and no parallel top-level module.

Co-authored-by: Copilot <[email protected]>
justinchuby added a commit that referenced this pull request Aug 24, 2026
PR #578 was cut against #576 before #581 ("Direct multi-shard GGUF import")
merged into main as 7003bc7. #581 already ships a `preflight-gguf` CLI and the
`mobius.integrations.gguf._preflight` library, so the standalone
`mobius.preflight_gguf` module + second `preflight-gguf` subparser collided with
it (argparse `conflicting subparser` on Python 3.12, breaking the whole CLI) and
re-implemented parallel logic. Per the review, fold the genuinely-additive value
into #581's `_preflight.py` and delete the parallel implementation.

Folded in (reusing #581's GgufShardSet/GGUFModel header reader, metadata-only):
- Block-preserving, lossless-only per-tensor-type classification against the
  *real* repacker (`native_block_spec` / `repack_quant_params`) plus float
  passthrough — no model-name allowlist. Dispositions: passthrough /
  native-preserve / repack / unsupported.
- Real-artifact budget: ONNX external-data output estimate and a weights-only
  VRAM figure derived from the export artifact. Direct random-access shard
  reads, so there is NO merged second-copy budget.
- A blocker listing the *exact* unsupported native qtypes (e.g. Q5_K/Q2_K/Q3_K),
  which — with #581's sparse-MoE fusion gate — are the real remaining code gaps,
  never architecture or sharding.

Removed (net-new, now-invalid blockers): the hardcoded `split.count > 1` refusal
(GgufShardSet imports sharded sets directly), the `merged_input_bytes`
double-copy disk budget, and the `/mnt` staging recommendation. No static
DeepSeek 401/404 blocker, no bandwidth/tok-s inference, no payload download.

Tests: supported sharded set clears shard+arch gates; dispositions match the
real repacker; exact unsupported qtype is the only blocker; budget carries no
second-copy and VRAM derives from the artifact; exactly one `preflight-gguf` CLI
registration (parser builds on 3.12) and no parallel top-level module.

Co-authored-by: Copilot <[email protected]>
justinchuby added a commit that referenced this pull request Aug 24, 2026
…izedMoE (+ build_from_gguf wiring) (#591)

## Native-block sparse-MoE fusion + `build_from_gguf` integration

Collapses GLM-style **routed** native-block expert storms (a per-expert
`pkg.nxrt::BlockQuantizedMatMul` for every gate/up/down of every expert,
dispatched by an `Equal` one-hot mask) into **one sparse top-k
`pkg.nxrt::BlockQuantizedMoE` per layer**, reusing the existing native
blocks
**byte-for-byte** (no dequantize, no requantize). Gated on graph/tensor
structure, never on model names.

### What's here
1. **Rewrite** (`rewrite_rules/_block_quantized_moe_fusion.py`) — the
transform:
finds the dense-fallback MoE subgraph, validates **all** layers, then
emits.
Two-pass so an unfusable layer fails **atomically** with the graph
untouched.
2. **Builder integration** (`integrations/gguf/_builder.py`) — wires the
fusion
into `build_from_gguf` at the **single** post-export authority point
(step
9b, after `pkg.apply_weights`, once every native block carries real
packed
   bytes), then a final-graph-state honesty gate.

### Applicability verdict (Phase-1 audit)
- GLM-5.2 UD-IQ1_S/M routed experts are **per-projection mixed-format**
per
layer (fused `gate==up` in iq1_s/iq1_m; `down` in a higher-bit format
such as
iq4_xs). A v1 single-`format` `BlockQuantizedMoE` therefore fuses **0**
GLM
  layers.
- Expressing a mixed-format layer needs the **`block_layout_version=2`
per-projection ABI** (`fc1_format`/`fc2_format`/`fc3_format`). That
runtime
ABI lives on an **unmerged onnx-genai branch**, so mobius's runnable
runtime
  does **not** yet have it.
- **Honest consequence:** GLM-5.2 mixed-format layers **typed-reject**
(`SparseMoEExportError`, message names `block_layout_version=2`) until
the
runtime ships v2 — we never emit an unrunnable v2 node by default.
**Uniform**
  native-block routed MoE **does** fuse today (v1).

### Honesty / fail-closed policy
- Default `allow_dense_moe=False`. Unsupported layers (mixed w/o v2,
per-expert
bias, ragged/incomplete groups) raise the shared
**`SparseMoEExportError`**
  atomically; the graph is left as the original dense storm.
- `_perproj_bqmoe_v2_runtime_available()` gates v2 emission on
`MOBIUS_ENABLE_BQMOE_PERPROJ_V2` (default off). Flip it **only** once
the
  onnx-genai v2 runtime ships.
- The **pre-export module-level gate call was removed** (it would reject
the
layers the fusion now collapses); enforcement moved to the **final graph
state** — the fusion's atomic reject + a `_assert_sparse_moe_graph`
backstop
that fails closed on any surviving routed `.experts.`
`BlockQuantizedMatMul`
storm. Single mechanism, no duplicate gate. Batty's
`_assert_sparse_moe_capability`
/ `_routed_dense_block_expert_paths` (#581) stay defined for their unit
tests.
- `allow_dense_moe=True` may warn + retain the dense fallback, but
**never**
  counts as a performance path (no throughput claim).

### Emitted ABI (unchanged runtime contract)
`BlockQuantizedMoE` 9 inputs, FLOAT32: `[input, router_logits,
fc1_experts_weights(uint8 4D), fc1_bias?, fc2_experts_weights,
fc2_bias?,
fc3_experts_weights?, fc3_bias?, router_weights?]`. Uniform layer →
`format`
attr (v1). Mixed layer → `block_layout_version=2` +
`fc1_format`/`fc2_format`/
`fc3_format`. Expert banks are the source native blocks **stacked
verbatim**
(byte-preservation asserted in tests).

### Tests (same commits)
- **Rewrite unit** (`_block_quantized_moe_fusion_test.py`, 23):
GLM-style
  Sigmoid+TopK+normalize routing, top-k {1,8}, byte-preserving stacking,
atomic fail-closed (dropped/duplicate/ragged/mixed-bias experts),
structural
proof the expert matmuls collapse, and the new **v2-runtime gate**
(uniform
fuses without v2; mixed typed-rejects without v2; mixed emits v2 when
opted in).
- **Builder integration** (`_block_quantized_moe_builder_test.py`, 20):
step-9b
helpers on synthetic exported packages (default fail-closed, v2 opt-in,
dense
retention, byte-preserving banks, deterministic external data,
final-state
backstop) **plus 5 real end-to-end `build_from_gguf` builds** on
synthetic
native-block MoE GGUFs (`qwen3_moe` / `qwen2_moe`, which lower through
the
identical routed dense-loop → `BlockQuantizedMatMul` storm and the same
step-9b
  authority point):
- uniform → **one** `BlockQuantizedMoE`, only attention matmuls remain
(no storm);
  - mixed → **`SparseMoEExportError`** (GLM-5.2's honest path);
  - mixed + `MOBIUS_ENABLE_BQMOE_PERPROJ_V2=1` → one **v2** node;
  - `allow_dense_moe=True` → dense storm retained (no fused node);
  - **shared expert stays dense** while the routed storm collapses.

Full `rewrite_rules/` + `integrations/gguf/` suites: **576 passed, 1
skipped**.
`ruff check` + `ruff format --check`: clean.

### Remaining typed blockers (not overclaimed)
1. **v2 per-projection runtime ABI is unmerged in onnx-genai** → GLM-5.2
mixed-format typed-rejects end-to-end until it ships. Uniform
native-block
   MoE fuses today.
2. **No A100 benchmark yet** — deferred until a runnable shape-faithful
importer path exists (GLM-5.2 can't build to a runnable graph until v2
lands).
   Full-model speed is not claimed.
3. **`_builder.py` merge coordination** — Sapper's #578 (unmerged) also
rewrites
`_builder.py`; a future rebase will need coordinator-mediated conflict
   resolution. No live collision on this base.

### Dependency on Batty's sharded import
Builds on the merged **#581** (`GgufShardSet`, `glm-dsa` → `glm_moe_dsa`
bridge,
shared `SparseMoEExportError`) and **#576**; rebased cleanly on
`059bf5f`. Only
uses those committed public interfaces — no edits to shard-reader /
architecture-
mapping files.

**Draft — do not merge.** Requesting independent review (excluding
author).

---------

Co-authored-by: Copilot <[email protected]>
justinchuby added a commit that referenced this pull request Aug 24, 2026
…+ budget (reconciled into #581) (#578)

## What

Metadata-only, **block-preserving / lossless-only** classification and
budget for
GGUF export, **folded into the #581 preflight library**
(`mobius.integrations.gguf._preflight`).
This is the reconciled revision of the rejected PR: the standalone
`mobius.preflight_gguf` module and its duplicate `preflight-gguf`
subcommand are
gone; the additive value lives on the single #581 code path.

Rebased/rebuilt onto current `main` (now includes #581 `7003bc7` and
#576
`059bf5f`). Base retargeted from the deleted
`sebastian/export-preflight-streaming`
to `main`. Single focused commit; no dependency on #576.

## Why the rejection is addressed

#581 shipped a `preflight-gguf` CLI + preflight library after this
branch was
cut. The old branch added a *second* subparser (breaking
`build_parser()` on
Python 3.12 with `conflicting subparser: preflight-gguf`) and duplicated
header
parsing / shard resolution. It also carried three now-invalid blockers.

**Removed (net-new, now-false):**
- Duplicate module + duplicate `preflight-gguf` CLI ownership — exactly
one
  registration remains (#581's); the parser builds on 3.12.
- Hardcoded `split.count > 1` refusal — `GgufShardSet` imports sharded
sets
directly, so GLM-5.2 `UD-IQ1_S` (6 shards) is **not** rejected for
sharding.
- `merged_input_bytes` / second-copy disk budget — direct random access
means no
  merged file; the budget reflects **real** artifacts only.
- `/mnt` staging recommendation — no environment paths in product
defaults.
- No static DeepSeek 401/404 blocker, no bandwidth/tok-s inference, no
payload
  download (headers only).

**Preserved / folded in (validated against the real repacker):**
- Dynamic architecture lookup (`glm-dsa → glm_moe_dsa`, from #581).
- Per-tensor-type lossless disposition against the **real** repacker
  (`native_block_spec` / `repack_quant_params`) + float passthrough — no
  model-name allowlist: `passthrough` / `native-preserve` / `repack` /
  `unsupported`.
- Real-artifact budget: ONNX external-data output estimate and a
weights-only
VRAM figure derived from the **export artifact** (not the source dtype).
- Honest blockers: the sparse-MoE fusion gate (#581) plus the **exact**
unsupported native qtypes (e.g. `Q5_K/Q2_K/Q3_K`) are the real remaining
code
  gaps for `UD-IQ1_S` — never architecture or sharding.

`GgufPreflightReport` gains additive fields (`type_stats`,
`output_bytes`,
`vram_weights_bytes`, `unsupported_types`) with defaults; #581 APIs
unchanged.

## Tests

Added to `_preflight_test.py` (metadata-only, shape-faithful multi-shard
fixtures): a supported **sharded** set clears the shard + arch gates;
dispositions match the real repacker; an unsupported qtype is the *only*
blocker;
the budget carries no second-copy and VRAM derives from the artifact;
exactly one
`preflight-gguf` CLI registration and no parallel top-level module. Full
`_preflight_test.py` + the GGUF suite (408) + CLI option parity pass;
`ruff`
clean (0.16.2).

Independent re-review requested. Do not merge.

---------

Co-authored-by: Copilot <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants