Skip to content

feat(models): read the qwen4_exp n-gram table from disk (ple_storage) - #2906

Merged
inureyes merged 6 commits into
mainfrom
feature/issue-2881-ple-external-storage
Nov 9, 2026
Merged

inureyes merged 6 commits into
mainfrom
feature/issue-2881-ple-external-storage

Conversation

@inureyes

@inureyes inureyes commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Checkpoints declaring text_config.ple_storage now read the roughly 30 GiB n-gram table from disk, row by row, instead of holding it in MLX parameters. Checkpoints without it keep the resident path. On the OptiQ 2-bit checkpoint, load-time resident memory is 45.39 GB (ranges view).

What changed

  • PleRowStore with Resident and External. External deduplicates ids, serves a byte-bounded LRU (default 0.5 GB, MLXCEL_PLE_CACHE_BYTES), reads misses, dequantizes once and restores caller order.
  • The mlx-vlm v2 manifest is accepted as-is (safetensors_ranges, interleaved_q4, affine 4/32, nvfp4 4/16). Every validation failure names the field.
  • MLXCEL_PLE_IO=direct|mmap|ram. The default is mmap, the simplest mode and the one upstream uses; the choice awaits measurement.
  • Gather-ahead reads the next prefill piece's rows while the GPU runs the current piece. A hint can only change what is cached.
  • mlxcel prepare-external-ple builds the view without Python.
  • mlxcel inspect and --estimate-memory count the row cache, or the table under ram, not the on-disk table. Hit, miss, bytes and time go on a stats line after generation.
  • The row cache grows in 64 MiB steps through RowCacheGrowth::can_grow, always true for now; feat(core): macOS memory guardrails for large resident models (available-memory preflight, idle compression, optional wiring) #2883 plugs in its check.
  • ple_storage with more than one PLE layer is refused, since one manifest describes one table.

Changes during review

A checkpoint directory is untrusted input. The manifest and row file must resolve inside the model directory, so an absolute ple_storage.manifest is refused. source_root cannot be confined because upstream writes it relative and outside the view, so each safetensors_ranges tensor must match its file's own safetensors header. prepare-external-ple refuses index paths leaving the source, symlinks, and reserved names, and hard-links only .safetensors files. The row cache now stays within its byte budget, including bookkeeping.

Verification

  • models::qwen4_exp lib tests: 128 passed. Clippy on lib and tests and fmt --check pass. This covers one test per manifest rule and External equal to Resident bit for bit for both layouts, both quantizations and all three I/O modes.
  • Whole-model trace on OptiQ 2-bit after 4,608 context tokens, resident against external: 0 of 128 top-1 disagreements, logit delta 0.0000. It used a safetensors_ranges view and predates the review fixes, which did not touch row decoding. interleaved_q4 is proven on tiny fixtures only, because a 30 GiB row file would disturb sibling work on this shared host.
  • After the review fixes, a fresh ranges view generated 24 tokens in both mmap and direct.
  • Interoperability on tiny checkpoints with mlx-vlm 0.7.11's ple_storage.py, at manifest and row level, in both directions.

Unverified criteria (left unchecked)

  • mlx-vlm interoperability is partial: a real-model view prepared by mlx-vlm generating in mlxcel, and the helper's output generating in mlx-vlm, were not run.
  • Per-mode paired five-run benchmarks and the peak-memory comparison: deferred to a quiet machine. No default is claimed from measurement.
  • 96 GB and 64 GB Mac runs: hardware absent.

Known limits: truncating a file while mmap mode maps it raises SIGBUS (direct avoids it), and a disk read error panics the forward, which has no error channel.

Closes #2881

The Qwen3.8-Flash-Next n-gram table is about 30 GiB of cold lookup data that each token touches 16 rows of, and keeping it resident was the largest memory cost in this family. Checkpoints that declare text_config.ple_storage now load the mlx-vlm ple-store.json manifest as-is and read rows from disk; checkpoints without it keep the resident path unchanged.

The new PleRowStore has Resident and External implementations. External deduplicates ids, serves hits from a byte-bounded LRU of raw row records, reads misses through MLXCEL_PLE_IO=direct|mmap|ram, dequantizes once and restores caller order, bit-identical to the resident table. Prefill announces the next piece's tokens through a thread-local so its rows are read ahead while the GPU runs the current piece. mlxcel prepare-external-ple builds the view without Python, and inspect and --estimate-memory count the row cache instead of the table.

Validated with cargo test on the qwen4_exp modules (manifest rules, External equals Resident for both layouts and quantizations) and against views written by mlx-vlm's own prepare step.

Refs #2881
prepare-external-ple failed on the OptiQ checkpoint because its index already lists optiq/optiq_vision.safetensors among the shards, so the sidecar step tried to link a file that already existed. Skip the sidecar when the index already linked it.

Verified by building the OptiQ safetensors_ranges view and running a logit trace, resident against external, after 4,608 context tokens: 0 of 128 top-1 disagreements and a zero logit delta.

Refs #2881
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:high High priority area:models Model architectures, weights, loading, metadata platform:macos macOS (Apple Silicon) specific modelsize:xlarge 4-bit checkpoint > 100GB; exceeds a 128GB dev box, needs bigger hardware arch:hybrid Hybrid attention stack (linear/sliding/full or attention+SSM interleave) labels Nov 9, 2026
Builds without the surgery feature failed: the cfg gate meant for split_mtp sat on prepare_external_ple, so split_mtp imported the disabled mlxcel_surgery crate and main.rs named a command that was not exported. The CI no-default-features jobs build this binary. The gates now match main.rs: split_mtp is gated and prepare-external-ple is not.

The row cache could exceed MLXCEL_PLE_CACHE_BYTES because the last growth step allocated a whole slab and the charge per row undercounted the hash map and list vectors. The last step now stops at the capacity, the vectors are reserved per step, and the charge covers the worst case, so slabs plus bookkeeping stay within the budget.

Direct reads stop once a span's bytes have arrived. A span ending at the end of a file gets a short read, and retrying the unaligned remainder under O_DIRECT could fail with EINVAL and panic the lookup.

Validated with the qwen4_exp lib tests, clippy, fmt, and cargo check of the binary with no default features. The O_DIRECT path was not exercised on Linux.

Refs #2881
@inureyes

inureyes commented Nov 9, 2026

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Read the qwen4_exp PLE n-gram table from disk through ple_storage, leaving resident checkpoints on the existing path.

Findings Addressed

  • surgery gate moved onto the wrong module, breaking --no-default-features builds (HIGH)
  • Row cache could exceed MLXCEL_PLE_CACHE_BYTES: full last slab, undercharged bookkeeping (HIGH)
  • Direct read retried an unaligned remainder at end of file, risking EINVAL and a lookup panic on Linux (HIGH)

Remaining Items

  • A worker panic leaves the in-flight flag set, stalling lookups up to 60 s each until the next prefetch clears it (MEDIUM), not fixed, only reachable on thread-spawn failure
  • prepare-external-ple takes row_width from the last shard without comparing shards, so a heterogeneous checkpoint would write misaligned rows (MEDIUM), not fixed
  • A disk read error panics the forward; there is no error channel (MEDIUM), not fixed
  • read_json replaces NaN and Infinity inside strings too (LOW), not fixed
  • can_grow is polled per insert once refused at a slab boundary (LOW), for feat(core): macOS memory guardrails for large resident models (available-memory preflight, idle compression, optional wiring) #2883 to note

Verification

  • All stated requirements implemented, apart from the criteria the PR body lists as unverified
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass: qwen4_exp lib tests, clippy, fmt, no-default-features check of the binary. The O_DIRECT path was not exercised on Linux.

A checkpoint directory can come from anyone, and its manifest and index named files that the loader and `prepare-external-ple` used unchecked.

Loading: `ple_storage.manifest` and `data_file` must now resolve inside the model directory (a Hugging Face snapshot's blob symlinks still work). `source_root` has to stay free because a view reads its source checkpoint, so every `safetensors_ranges` tensor must instead match a tensor its file's own header declares, which keeps a manifest from reading arbitrary files as rows. A table larger than its files is refused, and safetensors header sizes are bounded by the file before allocation.

Helper: index paths, the OptiQ sidecar and copied files cannot leave the source, only `.safetensors` files are hard-linked so the view's JSON writes cannot reach the source through a link, a source file cannot replace the view's manifest or row file, and shards that disagree on `row_width` are a named error instead of a corrupt table.

A panicking gather-ahead worker now clears its in-flight flag, so lookups no longer wait 60 seconds each behind it.

Validated with the qwen4_exp unit tests and clippy on the lib and test targets.

Refs #2881
@inureyes

inureyes commented Nov 9, 2026

Copy link
Copy Markdown
Member Author

Security and performance review of the external PLE storage, with a checkpoint directory from an untrusted source as the threat model.

Fixed:

  • CRITICAL: source_root, an absolute or .. ple_storage.manifest, and a data_file symlink could read any local file as table rows. The manifest and row file must now resolve inside the model directory. Each safetensors_ranges tensor must match its file's own safetensors header, because source_root has to be able to leave a view.
  • HIGH: prepare-external-ple used index paths unchecked, so ../ could create directories and hard links outside the output. Copying also followed symlinks out of the source, and a non-safetensors "shard" could be written through its hard link into the source checkpoint.
  • HIGH: a safetensors header size was allocated without a bound, which aborts on inspect and the helper.
  • MEDIUM, as requested: shards with different row_width are a named error, and a panicking gather-ahead worker clears its in-flight flag. A table larger than its files is refused at load and in the helper.

Remaining, not fixed:

  • MEDIUM: truncating a mapped file while mmap mode runs raises SIGBUS. It needs concurrent local write access, and MLXCEL_PLE_IO=direct avoids it.
  • MEDIUM: a checkpoint's cache_rows can raise the row-cache budget up to the table size. MLXCEL_PLE_CACHE_BYTES overrides it.
  • LOW: EXTERNAL_PLE.json records the absolute source path (same as upstream), and read_json replaces NaN and Infinity inside strings too.

Performance: no regression found on the resident or per-token decode path. No benchmarks were run. Qwen4-Exp unit tests and clippy on the lib and test targets pass.

The MLXCEL_PLE_IO entry now says that an absolute ple_storage.manifest, and a manifest or row file that resolves outside the model directory, are refused at load, matching the confinement added during review.

Validation: make verify-env-var-docs passes.

Refs #2881
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 9, 2026
@inureyes
inureyes marked this pull request as ready for review November 9, 2026 15:49
@inureyes
inureyes merged commit 69a8612 into main Nov 9, 2026
13 checks passed
@inureyes
inureyes deleted the feature/issue-2881-ple-external-storage branch November 9, 2026 15:49
inureyes added a commit that referenced this pull request Nov 10, 2026
## Summary

Records the timing and memory measurements that #2908, #2906, #2912, #2909, #2911 and #2918 deferred to a quiet host, in `docs/benchmark_results/qwen4-exp-deferred-measurements-m3ultra-2026-11-10.md` (Mac Studio M3 Ultra, 512 GB, `main` @ `60a3270c`).

- Native MTP (#2880, #2917): 1.30x / 1.10x / 1.76x (code / prose / enumeration) for the OptiQ 2-bit target with the bf16 split head, 1.38x / 1.00x / 1.74x for the 4-bit target with its embedded head.
- SSD expert streaming (#2882): decode 42.8 tok/s resident, 23.0 at a 24 GB arena (89.8% hit), 18.3 at 8 GB (74.9% hit). Router sync costs 8.0 s per run at both sizes, more than the I/O wait. Output identical across arms.
- External PLE (#2881): 31 GB less resident (78.5 to 47.3 GB), same TTFT at 4K and 32K, identical output in every mode.
- Prompt-cache second turn (#2885): 0.51 to 0.60 s cached vs 15.1 s (16K) and 28.6 to 28.9 s (32K) after a reset, byte-identical in 10/10 repetitions.
- macOS memory soak (#2883): 0 compressions and 0 swap-outs in every setting. A 512 GB host cannot show the eviction the issue targets.

## Script changes

- `scripts/bench_speculative.sh`: new `flashnext` and `flashnext4` pairings.
- `scripts/macos_memory_soak.sh`: send the `model` field (every request got HTTP 400 without it), and default `--out` gets a `-wire-weights` suffix under `--wire-weights` so it no longer overwrites the plain run.

## Not covered

A Mac with less memory than the checkpoint, the `prepare-expert-stream` contiguous file, and streaming combined with the external PLE table.

Refs #2880, #2881, #2882, #2883, #2885, #2917
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

arch:hybrid Hybrid attention stack (linear/sliding/full or attention+SSM interleave) area:models Model architectures, weights, loading, metadata modelsize:xlarge 4-bit checkpoint > 100GB; exceeds a 128GB dev box, needs bigger hardware platform:macos macOS (Apple Silicon) specific priority:high High priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(models): read the qwen4_exp n-gram (PLE) table from disk instead of keeping it resident (ple_storage)

1 participant