Skip to content

model-hf::folder: an FP4-Local folder's compressed block scales are read back once, so the host reads its experts in place - #1103

Merged
juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-q38-offload-fp4l-5090
Nov 1, 2026
Merged

juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-q38-offload-fp4l-5090

Conversation

@juliankang4

@juliankang4 juliankang4 commented Nov 1, 2026 •

Copy link
Copy Markdown
Collaborator

FP4-Local 폴더가 RTX 5090에서 serve되지 않던 결함을 고쳐, 전문가 가중치를 카드와 host로 나누어 읽게 했습니다.

What and why

An FP4-Local folder could not be served on a card too small to hold all its experts. The routed expert stacks store their block scales compressed, and folder::planned_tensors turned every such stack into a card-only tensor even when the plan wanted some experts on the host or the NVMe tier. parts::load then refused the plan. Plain NVFP4 stacks were already read in place and were not affected.

This change unpacks the compressed block scales once into a cache file (BLOOMERY_SCALES, default ~/.cache/bloomery/scales, one file per folder generation). The located header points each expert's block-scale plane at that file, so the host reader, the NVMe tier and the residency machine read an FP4-Local stack the same way they read a plain NVFP4 stack. The card upload still decodes the compressed scales directly. A changed folder opens another path, so a reader that still holds the older path keeps reading the older scales. A load that keeps every expert on the card writes no scales there.

Release notes: Fixed: an FP4-Local folder now serves on a card that cannot hold all its experts, splitting them between the card, host memory and the NVMe tier.

Code shape

The review reads these first. A box left unticked needs one line of why.

  • No second copy. Logic two models (or two call sites) share has one common owner; I lifted it there instead of
    copying it (AGENTS.md "Common code first", docs/rust-quality.md R14). Where I found an existing copy, I
    named it below.
  • Model code holds only architecture facts. A model's own files carry only what its architecture forces
    (tensor shapes, the attention kind, the quant). A common owner gained no per-model branch, flag or trait method.
  • Dead code is gone. Nothing I made unused is left behind (functions, flags, gate clauses, docs).
  • No silent failure. Undefined input is a named error or panic, never a defined-looking output.
  • Comments state what is true now. No dates, issue numbers or how a bug was found (tools/check-comments.sh).
  • No relaxed gate. No band, tolerance or lint moved to make a check pass; a re-pin carries PIN(YYYY-MM-DD):
    and its reason.
  • cargo fmt and cargo clippy are clean on what I touched; the lint count did not go up.

Duplication found or removed (path:line), or "none": the compressed-format to encoding match that appeared three times in crates/hf/src/modelopt.rs is now one function, csf::Encoding::of, and Format::decoded calls it.

What I ran

Base c297d066e3e00a6e70808f039d414c2a9a226519, PR head e68f2342fd4d628ce30109ba7e6839cc39fd7172.

Card:

$ nvidia-smi
Mon Nov  2 05:03:18 2026       
+-----------------------------------------------------------------------------------------+
| NVIDIA-SMI 595.99.02              Driver Version: 595.99.02      CUDA Version: 13.2     |
+-----------------------------------------+------------------------+----------------------+
| GPU  Name                 Persistence-M | Bus-Id          Disp.A | Volatile Uncorr. ECC |
| Fan  Temp   Perf          Pwr:Usage/Cap |           Memory-Usage | GPU-Util  Compute M. |
|                                         |                        |               MIG M. |
|=========================================+========================+======================|
|   0  NVIDIA GeForce RTX 5090        Off |   00000000:01:00.0 Off |                  N/A |
|  0%   39C    P8             12W /  400W |       2MiB /  32607MiB |      0%      Default |
|                                         |                        |                  N/A |
+-----------------------------------------+------------------------+----------------------+

Model: nvidia/Qwen3.8-Flash-Next-FP4-Local at revision b9ce18a6887e18c089fdea8509a33e63429a3300 (FP4L below is the folder).

Build, for the PR and for main:

cargo oxide build --arch sm_120a -- -p bloomery-gpu-gates \
  --features glm5next,clef,mimo2,solar2,minimaxm3,flint,gemma-embedding2,hf,vision,checkpoint,deepseek41 \
  --release --bin bloomery-serve

Serve the folder and send greedy requests to it:

BLOOMERY_SCALES=$SCALES bloomery-serve --model qwen38 -m $FP4L --host 127.0.0.1 --port 18447 --ctx-size 8192

Before, main, same card and folder:

bloomery-serve: parts::load: blk.0.ffn_down_exps.weight is placed on Card(0) and Host: a load from a part source holds every tensor whole on card 0, and reads a row-gathered table from the NVMe tier
STEP-RC serve-fp4l-main 1

After, this change, plan and first load:

plan place=a card=GeForce_RTX_5090 experts=card ctx_max=8192 host_experts=17465 card_experts=7111 ...
load phases open_s=0.12 context_s=0.01 upload_s=8.55 derive_s=0.01 host_set_s=8.61 body_s=1.49 head_s=0.00 other_s=16.33
scale store: 7549751296 B in 8220566d0db6d367.lock 8220566d0db6d367.scales
fp4l request 1: wall 3.5 s; prompt 288 ids 260.75 ids/s ttft 1104 ms; generated 128 ids 54.757 ids/s; content '\n\n<think>\nThe user wants me to read the passage about Caldmere and answer a question about how the r'
fp4l request 6: wall 1.5 s; prompt 19 ids 122.18 ids/s ttft 156 ms; generated 128 ids 97.153 ids/s; content '\n\n<think>\nThe user wants a long, detailed story about a lighthouse keeper who finds a message in a b'
STEP-RC serve-fp4l 0

A second load of the same folder reuses the scale file (other_s is the decode time):

load phases open_s=0.12 context_s=0.00 upload_s=6.56 derive_s=0.01 host_set_s=3.75 body_s=0.52 head_s=0.00 other_s=0.12
STEP-RC serve-fp4l-warm 0

With the card budget lowered to force paging (BLOOMERY_CARD_BUDGET=16G BLOOMERY_HOST_ROOM=46G, otherwise the same command), the folder also serves from the NVMe tier, and the first-token distribution stays close to the unrestricted load:

first-token fp4l-emu16: kl_top20=0.00078 top1=same (271 vs 271) greedy_shared=16/16
first-token fp4l-warm: kl_top20=0.00000 top1=same (271 vs 271) greedy_shared=16/16
STEP-RC serve-fp4l-emu16 0

The KL is over the top 20 ids of the first token, against the unrestricted FP4-Local load. This PR claims no speed change.

Unit tests:

cargo test -q -p bloomery-hf --lib            test result: ok. 170 passed; 0 failed; 2 ignored
cargo test -q -p bloomery-model-hf --lib      test result: ok. 133 passed; 0 failed; 3 ignored
bash tools/gate.sh --oxide -p bloomery-gpu --release --lib -- folder::tests
                                              test result: ok. 3 passed; 0 failed; 0 ignored

Regression test for a header reopened after the folder changed. Before the fix it fails:

cargo test --locked -p bloomery-model-hf --lib folder::tests::a_folder_reads_compressed_block_scales_back_once -- --exact --nocapture
assertion `left == right` failed: an older header reopens its mapped generation
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 135 filtered out

After the fix, same command:

test folder::tests::a_folder_reads_compressed_block_scales_back_once ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 135 filtered out

cargo fmt -p bloomery-model-hf -p bloomery-levers -- --check and cargo clippy --locked -p bloomery-model-hf -p bloomery-levers --all-targets --no-deps -- -D warnings pass with no warnings.

cargo clippy --workspace --all-targets on the PR head: lint rc 0 (^warning: 0, the ratchet 0 in tools/lint-ratchet.txt).

Hardware (if the change is for a machine)

Card Driver CUDA
NVIDIA GeForce RTX 5090 595.99.02 13.2

AI help

AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.

@github-actions github-actions Bot added dgx-spark The DGX Spark (aarch64, GB10) port documentation Improvements or additions to documentation gpu The card engine: crates/gpu*, crates/app host Host crates: qdot, threads, engram, engram-lab, runtime, sampler, levers, decision, vision, refset model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja needs-gpu Changes code a card must check, and carries no gate run on a card labels Nov 1, 2026

@github-actions github-actions Bot 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.

Verdict: MUST_FIX: cache invalidation can make an NVMe load read unwritten block scales.

Must fix

1. Keep each cache generation at a stable path

crates/model-hf/src/folder/scales.rs:162 replaces the path while older headers still map its previous inode. Open A, touch a source shard's modification time, then open B without filling B. A's make_in_place fills or accepts A's old inode, but crates/gpu/src/host/nvtier.rs:467 reopens the path and reads B's zeros. Paged experts then produce incorrect results. The lock ends before these readers open.

Fix the cache identity before more readers adopt these located headers. Include the cache key in the filename and resolve the scale locations before collecting shard paths:

--- a/crates/model-hf/src/folder/scales.rs
+++ b/crates/model-hf/src/folder/scales.rs
@@ -54,5 +54,5 @@
 pub(crate) struct Wanted {
     /// The store's file of the folder; `None` without a store, refused at the first scale asked.
-    path: Option<PathBuf>,
+    pub(super) path: Option<PathBuf>,
     /// Each scale's weight, how to decode it and where in the file it lies.
     scales: Vec<(String, CompressedScale, u64)>,
@@ -127,7 +127,8 @@
         let mut pending = key.clone();
         pending[0] = b'!';
-        let path = self.path.ok_or_else(|| {
+        let base = self.path.ok_or_else(|| {
             "the scale store has no directory (BLOOMERY_SCALES or HOME)".to_string()
         })?;
+        let path = base.with_extension(format!("{:016x}.scales", digest(&key)));
         let len = HEAD as u64 + self.bytes;
         let io = |what: &str, e: std::io::Error| {
--- a/crates/model-hf/src/folder.rs
+++ b/crates/model-hf/src/folder.rs
@@ -672,4 +672,19 @@
         );
     }
+    let pending_path = wanted.path.clone();
+    // Keep the lock until the header maps this cache generation.
+    let (decoded, scale_lock) = wanted.open()?.unzip();
+    let decoded_path = decoded.as_ref().map(|d| d.path().to_path_buf());
+    if let (Some(pending), Some(decoded)) = (pending_path, decoded_path.as_ref()) {
+        for spot in &mut spots {
+            if let Spot::Stack { scales_in, .. } = spot {
+                for file in scales_in {
+                    if *file == pending {
+                        file.clone_from(decoded);
+                    }
+                }
+            }
+        }
+    }
     let used: BTreeSet<&PathBuf> = spots
         .iter()
@@ -684,8 +699,5 @@
         })
         .collect();
-    // The scale store's file follows the folder's, whose first names the split.
-    // The store's lock is held until the header maps the file.
-    let (decoded, scale_lock) = wanted.open()?.unzip();
-    let decoded_path = decoded.as_ref().map(|d| d.path().to_path_buf());
+    // The scale store follows the folder shards.
     let mut files: Vec<PathBuf> = used
         .into_iter()

Update the cache documentation to describe files per generation. In a_folder_reads_compressed_block_scales_back_once, immediately after opening c, add:

let old_bytes = std::fs::read(split.shard_path(2).unwrap()).unwrap();
let at = usize::try_from(scales_at[0]).unwrap();
assert_eq!(
    &old_bytes[at..at + 64],
    matrix(split, 0).1.as_slice(),
    "an older header reopens its mapped generation"
);

This assertion fails on the current replacement and covers the NVMe reader's reopen.

Non-blocking

⚠ Debuggability: crates/model-hf/src/folder/scales.rs:247, the fix names no promoted probe or state record for cache hits, pending files or decoding. Identify the existing diagnostic, or explain in the PR body why this fix needs no diagnostic layer.

Checked

Duplicates: Dryer reported zero pairs; its scan excluded GPU crates.
Complexity: Wanted::open is new at 19, covering cache validation and publication; assemble rises 33→35 through cache-integration branches.
Silent failure: pending scales reach the NVMe reader through finding 1; make_in_place fills the older file handle.
Tests: the invalidation test checks mapped readers but omits reopening the older header's path. The assertion above detects that gap by inspection.
Gates: no bands, tolerances or pins moved.
Escape catalog: no C1–C4 pattern matched.

Notes

No builds or tests were run during this static review. The PR provides serving transcripts and folder unit-test output, but no just gate-* run with output; GPU evidence is false.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/shared/serve_seats/qwen38.rs, crates/gpu-minimaxm3/src/body.rs, crates/gpu/src/arch/nemotron_h_moe/body.rs … and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

…ead back once, so the host reads its experts in place

A folder whose NVFP4 stacks store their block scales as csf kept them made for the card, so the host, the NVMe tier and the residency machine could not read an FP4-Local expert and a plan that split the experts was refused. The folder's open now places each stack's plain block scales in one file of a scale store (BLOOMERY_SCALES, ~/.cache/bloomery/scales unset) and keeps the stack in place as a plain NVFP4 one. The file is sized at open and decoded once, before the first load whose host reads an expert in place (Source::make_in_place); a later open of the unchanged folder reuses it.
@juliankang4
juliankang4 force-pushed the dgx-spark-q38-offload-fp4l-5090 branch from 1137e5f to e68f234 Compare November 1, 2026 22:27

@github-actions github-actions Bot 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.

Since the last review:

  • Must-fix 1 is fixed: crates/model-hf/src/folder/scales.rs:134 gives each generation its own path; assembly updates scale locations before indexing shards.
  • The earlier debuggability advisory remains open below.

Verdict: CLEAN: the cache-generation defect is fixed, and no new must-fix issue survives the interdiff review.

Non-blocking

⚠ Debuggability remains open: crates/model-hf/src/folder/scales.rs:250 exposes no cache-hit, pending or decode state through a probe or record.
Identify an existing diagnostic, or explain in the PR body why this fix needs no diagnostic layer.

Checked

Duplicates: 0 new definitions in the interdiff; path-remapping logic has no existing owner. Dryer reported 0 pairs; its GPU exclusions contain no interdiff changes.
Complexity: Wanted::open remains 19, covering validation and publication; assemble is 33→40 against base, with this revision adding path-remapping branches at load time.
Silent failure: 2 optional paths followed. No requested scales needs no file; an absent store errors before any compressed stack reaches a host reader.
Tests: restoring the shared filename at scales.rs:134 fails the reopen assertion at folder.rs:2044. Dropping remapping at folder.rs:683 fails assembly. Pending-generation reopen assertions cover delayed filling. Mutation results are by inspection; the PR supplies FAIL-first and passing output for the filename regression.
Gates: no gate, tolerance or pin changed. Alias reuse, concurrent same-generation fills and older pending generations retain their paths and locking.
Escape catalog: no C1–C4 pattern matched.

Notes

Static review only; no builds or tests were run here. The interdiff changes load-time code, with no added decode or prefill work.
The PR includes card serving transcripts and tools/gate.sh folder-test output, but no just gate-* command with output; GPU evidence is false.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/shared/serve_seats/qwen38.rs, crates/gpu-minimaxm3/src/body.rs, crates/gpu/src/arch/nemotron_h_moe/body.rs … and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@juliankang4

Copy link
Copy Markdown
Collaborator Author

The review is done and the contribution check passed, so I'm merging this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dgx-spark The DGX Spark (aarch64, GB10) port documentation Improvements or additions to documentation gpu The card engine: crates/gpu*, crates/app host Host crates: qdot, threads, engram, engram-lab, runtime, sampler, levers, decision, vision, refset model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja needs-gpu Changes code a card must check, and carries no gate run on a card

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant